page-agent-sdk 2.34.0 → 2.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -4
- package/README.zh-CN.md +3 -4
- package/dist/page-agent-sdk.iife.js +19 -19
- package/dist/page-agent-sdk.js +6 -1
- package/dist/page-agent-sdk.umd.cjs +1 -1
- package/package.json +1 -1
- package/types/index.d.ts +19 -0
|
@@ -105,23 +105,23 @@ Please make sure you are calling this method within a traceable function and tha
|
|
|
105
105
|
You can add a handle by creating a public prompt at:
|
|
106
106
|
|
|
107
107
|
https://smith.langchain.com/prompts`);let[r,i,a]=KE(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError(`create a prompt`,r);let o={repo_handle:i,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},s=JSON.stringify(o),{repo:c}=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await HE(e,`create prompt`),e})).json();return c}async createCommit(e,t,n){if(!await this.promptExists(e))throw Error(`Prompt does not exist, you must create it first.`);let[r,i,a]=KE(e),o=n?.parentCommitHash===`latest`||!n?.parentCommitHash?await this._getLatestCommitHash(`${r}/${i}`):n?.parentCommitHash,s={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o,...n?.description!==void 0&&{description:n.description}},c=JSON.stringify(s),l=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${r}/${i}`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await HE(e,`create commit`),e})).json(),u=l.commit??l;return n?.tags&&await this._createCommitTags(`${r}/${i}`,u.id,n.tags),this._getPromptUrl(`${r}/${i}${u.commit_hash?`:${u.commit_hash}`:``}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error(`Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.`);let n=new FormData;for(let e of t){let t=e.id,r=jD({...e.metadata&&{metadata:e.metadata},...e.split&&{split:e.split}},`Serializing body for example with id: ${t}`),i=new Blob([r],{type:`application/json`});if(n.append(t,i),e.inputs){let r=jD(e.inputs,`Serializing inputs for example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.inputs`,i)}if(e.outputs){let r=jD(e.outputs,`Serializing outputs whle updating example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.outputs`,i)}if(e.attachments)for(let[r,i]of Object.entries(e.attachments)){let e,a;Array.isArray(i)?[e,a]=i:(e=i.mimeType,a=i.data);let o=new Blob([a],{type:`${e}; length=${a.byteLength}`});n.append(`${t}.attachment.${r}`,o)}if(e.attachments_operations){let r=jD(e.attachments_operations,`Serializing attachments while updating example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.attachments_operations`,i)}}let r=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${r}/examples`)}`,{method:`PATCH`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await HE(e,`update examples`),e})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw Error(`Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.`);let n=new FormData;for(let e of t){let t=(e.id??JS()).toString(),r=jD({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}`),i=new Blob([r],{type:`application/json`});if(n.append(t,i),e.inputs){let r=jD(e.inputs,`Serializing inputs for uploaded example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.inputs`,i)}if(e.outputs){let r=jD(e.outputs,`Serializing outputs for uploaded example with id: ${t}`),i=new Blob([r],{type:`application/json`});n.append(`${t}.outputs`,i)}if(e.attachments)for(let[r,i]of Object.entries(e.attachments)){let e,a;Array.isArray(i)?[e,a]=i:(e=i.mimeType,a=i.data);let o=new Blob([a],{type:`${e}; length=${a.byteLength}`});n.append(`${t}.attachment.${r}`,o)}}return(await this.caller.call(async()=>{let t=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:`POST`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await HE(t,`upload examples`),t})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw Error(`Prompt does not exist, you must create it first.`);let[n,r]=KE(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError(`update a prompt`,n);let i={};if(t?.description!==void 0&&(i.description=t.description),t?.readme!==void 0&&(i.readme=t.readme),t?.tags!==void 0&&(i.tags=t.tags),t?.isPublic!==void 0&&(i.is_public=t.isPublic),t?.isArchived!==void 0&&(i.is_archived=t.isArchived),Object.keys(i).length===0)throw Error(`No valid update options provided`);let a=JSON.stringify(i);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await HE(e,`update prompt`),e})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw Error(`Prompt does not exist, you must create it first.`);let[t,n,r]=KE(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError(`delete a prompt`,t);return(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/${t}/${n}`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await HE(e,`delete prompt`),e})).json()}_getPromptCacheKey(e,t){return`${e}${t?`:with_model`:``}`}async _fetchPromptFromApi(e,t){let[n,r,i]=KE(e),a=await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/commits/${n}/${r}/${i}${t?.includeModel?`?include_model=true`:``}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await HE(e,`pull prompt commit`),e})).json();return{owner:n,repo:r,commit_hash:a.commit_hash,manifest:a.manifest,examples:a.examples,hub_model_config:a.model_config,hub_model_provider:a.model_provider}}async pullPromptCommit(e,t){VD(e,t?.dangerouslyPullPublicPrompt);let n=this._fetchPromptFromApi.bind(this,e,t);if(!t?.skipCache&&this._promptCache){let r=this._getPromptCacheKey(e,t?.includeModel),i=this._promptCache.get(r,n);if(i)return i;let a=await n();return this._promptCache.set(r,a,n),a}return this._fetchPromptFromApi(e,t)}async _pullPrompt(e,t){let n=await this.pullPromptCommit(e,{includeModel:t?.includeModel,skipCache:t?.skipCache,dangerouslyPullPublicPrompt:t?.dangerouslyPullPublicPrompt});return JSON.stringify(n.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&[`description`,`readme`,`tags`,`isPublic`].some(e=>t[e]!==void 0)&&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?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash,tags:t?.commitTags,description:t?.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){let[t,n]=KE(e);return this._repoExists(t,n)}async skillExists(e){let[t,n]=KE(e);return this._repoExists(t,n)}async pullAgent(e,t){return await this._pullDirectory(e,`agent`,t?.version)}async pullSkill(e,t){return await this._pullDirectory(e,`skill`,t?.version)}async pushAgent(e,t){return this._pushDirectory(e,`agent`,t)}async pushSkill(e,t){return this._pushDirectory(e,`skill`,t)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async*listAgents(e){yield*this._listReposByType(`agent`,e)}async*listSkills(e){yield*this._listReposByType(`skill`,e)}async*_listReposByType(e,t){let n=new URLSearchParams;n.append(`repo_type`,e),n.append(`is_archived`,(!!t?.isArchived).toString()),t?.isPublic!==void 0&&n.append(`is_public`,t.isPublic.toString()),t?.query&&n.append(`query`,t.query);for await(let e of this._getPaginated(`/repos`,n,e=>e.repos))yield*e}async _pullDirectory(e,t,n){let[r,i,a]=KE(e),o=n??(a===`latest`?void 0:a),s=new URL(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${r}/${i}/directories`)}`);return s.searchParams.set(`repo_type`,t),o&&s.searchParams.set(`commit`,o),await(await this.caller.call(async()=>{let e=await this._fetch(s.toString(),{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await HE(e,`pull directory`),e})).json()}async _pushDirectory(e,t,n){if(n.parentCommit!==void 0&&(n.parentCommit.length<8||n.parentCommit.length>64))throw Error(`parent_commit must be 8-64 characters`);let[r,i]=KE(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError(`push ${t}`,r);if(await this._repoExists(r,i))(n.description!==void 0||n.readme!==void 0||n.tags!==void 0||n.isPublic!==void 0)&&await this._updateRepoMetadata(r,i,n);else{let e=/^[a-z][a-z0-9-_]*$/;if(!e.test(i))throw Error(`Invalid repo_handle ${JSON.stringify(i)}: must match ${e}`);await this._createRepo(i,t,n)}let a={files:n.files};n.parentCommit&&(a.parent_commit=n.parentCommit);let o=(await(await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${r}/${i}/directories/commits`)}`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await HE(e,`push ${t}`),e})).json()).commit.commit_hash,s=await this._getSettings(),c=new URLSearchParams({organizationId:s.id});return`${this.getHostUrl()}/context/${i}/${o.slice(0,8)}?${c.toString()}`}async _deleteDirectory(e){let[t,n]=KE(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError(`delete`,t);await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${t}/${n}/directories`)}`,{method:`DELETE`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await HE(e,`delete directory`),e})}async _repoExists(e,t){try{return await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/repos/${e}/${t}`,{method:`GET`,headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await HE(n,`check repo exists`),n}),!0}catch(e){if(BE(e))return!1;throw e}}async _createRepo(e,t,n){let r={repo_handle:e,repo_type:t,is_public:!!n.isPublic};n.description!==void 0&&(r.description=n.description),n.readme!==void 0&&(r.readme=n.readme),n.tags!==void 0&&(r.tags=n.tags);try{await this.caller.call(async()=>{let e=await this._fetch(`${this.apiUrl}/repos/`,{method:`POST`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(r)});return await HE(e,`create ${t}`),e})}catch(e){if(VE(e))return;throw e}}async _updateRepoMetadata(e,t,n){let r={};n.description!==void 0&&(r.description=n.description),n.readme!==void 0&&(r.readme=n.readme),n.tags!==void 0&&(r.tags=n.tags),n.isPublic!==void 0&&(r.is_public=n.isPublic),Object.keys(r).length!==0&&await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/repos/${e}/${t}`,{method:`PATCH`,headers:{...this._mergedHeaders,"Content-Type":`application/json`},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(r)});return await HE(n,`update repo metadata`),n})}async clonePublicDataset(t,n={}){let{sourceApiUrl:r=this.apiUrl,datasetName:i}=n,[a,o]=this.parseTokenOrUrl(t,r),s=new e({apiUrl:a,apiKey:`placeholder`}),c=await s.readSharedDataset(o),l=i||c.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}let u=await s.listSharedExamples(o),d=await this.createDataset(l,{description:c.description,dataType:c.data_type||`kv`,inputsSchema:c.inputs_schema_definition??void 0,outputsSchema:c.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(e=>e.inputs),outputs:u.flatMap(e=>e.outputs?[e.outputs]:[]),datasetId:d.id})}catch(e){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),e}}parseTokenOrUrl(e,t,n=2,r=`dataset`){try{return BC(e),[t,e]}catch{}try{let i=new URL(e).pathname.split(`/`).filter(e=>e!==``);if(i.length>=n)return[t,i[i.length-n]];throw Error(`Invalid public ${r} URL: ${e}`)}catch{throw Error(`Invalid public ${r} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();for(await new Promise(e=>setTimeout(e,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await uie()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return this.webUrl!==void 0&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),this.workspaceId!==void 0&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(` `)}]`}[Symbol.for(`nodejs.util.inspect.custom`)](){return this.toString()}};Object.defineProperty(tO,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function nO(e){return`dataset_id`in e||`dataset_name`in e}var rO=Symbol.for(`lc:context_variables`),iO=Symbol.for(`langsmith:replica_trace_roots`);function aO(e,t){if(rO in e)return e[rO][t]}function oO(e,t,n){let r=rO in e?e[rO]:{};r[t]=n,e[rO]=r}var sO=`6ba7b810-9dad-11d1-80b4-00c04fd430c8`;function cO(e){return XS(Object.keys(e).sort().map(t=>`${t}:${e[t]??``}`).join(`|`),sO)}function lO(e){return e.replace(/[-:.]/g,``)}function uO(e,t=1){let n=t.toFixed(0).slice(0,3).padStart(3,`0`);return`${new Date(e).toISOString().slice(0,-1)}${n}Z`}function dO(e,t,n=1){let r=uO(e,n);return{dottedOrder:lO(r)+t,microsecondPrecisionDatestring:r}}var fO=new Set([`projectName`,`updates`,`reroot`]);function pO(e){let t={};for(let n of Object.keys(e))fO.has(n)&&(t[n]=e[n]);return t}var mO=class e{constructor(e,t,n,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}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=t,this.project_name=n,this.replicas=r}static fromHeader(t){let n=t.split(`,`),r={},i=[],a,o;for(let e of n){let[t,n]=e.split(`=`),s=decodeURIComponent(n);t===`langsmith-metadata`?r=JSON.parse(s):t===`langsmith-tags`?i=s.split(`,`):t===`langsmith-project`?a=s:t===`langsmith-replicas`&&(o=JSON.parse(s).map(e=>Array.isArray(e)?e:pO(e)))}return new e(r,i,a,o)}toHeader(){let 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(`,`)}},hO=class e{constructor(t){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),gO(t)){Object.assign(this,{...t});return}let n=e.getDefaultConfig(),{metadata:r,...i}=t,a=i.client??e.getSharedClient(),o={...r,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:o},`id`in i&&i.id==null&&delete i.id,Object.assign(this,{...n,...i,client:a}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=uO(this.start_time,this.execution_order)),this.id||=Zre(this._serialized_start_time??this.start_time),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=SO(this.replicas),!this.dotted_order){let{dottedOrder:e}=dO(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+`.`+e:this.dotted_order=e}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:`chain`,project_name:sC(),child_runs:[],api_url:Aw(`LANGCHAIN_ENDPOINT`)??`http://localhost:1984`,api_key:Aw(`LANGCHAIN_API_KEY`),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return e.sharedClient||=new tO,e.sharedClient}createChild(t){let n=this.child_execution_order+1,r=this.replicas?.map(e=>{let{reroot:t,...n}=e;return n}),i=t.replicas??r,a=new e({...t,parent_run:this,project_name:this.project_name,replicas:i,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n}),o=this.extra?.metadata??{},s=a.extra?.metadata??{};Object.keys(o).length>0&&(a.extra={...a.extra,metadata:{...o,...s}}),rO in this&&(a[rO]=this[rO]);let c=Symbol.for(`lc:child_config`),l=t.extra?.[c]??this.extra[c];if(bO(l)){let e={...l},t=yO(e.callbacks)?e.callbacks.copy?.():void 0;t&&(Object.assign(t,{_parentRunId:a.id}),t.handlers?.find(_O)?.updateFromRunTree?.(a),e.callbacks=t),a.extra[c]=e}let u=new Set,d=this;for(;d!=null&&!u.has(d.id);)u.add(d.id),d.child_execution_order=Math.max(d.child_execution_order,n),d=d.parent_run;return this.child_runs.push(a),a}async end(e,t,n=Date.now(),r){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??n,r&&Object.keys(r).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...r}}:{metadata:r})}_convertToCreate(e,t,n=!0){let r=e.extra??{};if(r?.runtime?.library===void 0&&(r.runtime||={},t))for(let[e,n]of Object.entries(t))r.runtime[e]||(r.runtime[e]=n);let i=e.parent_run?.id??e.parent_run_id,a;return a=n?[]:e.child_runs.map(e=>this._convertToCreate(e,t,n)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:r,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,t){if(t.dotted_order){let n=t.dotted_order.split(`.`),r=null;for(let t=0;t<n.length;t++)if(n[t].slice(-36)===e){r=t;break}if(r!==null){let e=n.slice(r+1);t.dotted_order=e.join(`.`),e.length>0?t.trace_id=e[0].slice(-36):t.trace_id=t.id}}t.parent_run_id===e&&(t.parent_run_id=void 0)}_setReplicaTraceRoot(e,t){let n=aO(this,iO)??{};n[e]=t,oO(this,iO,n);for(let n of this.child_runs)n._setReplicaTraceRoot(e,t)}_remapForProject(e){let{projectName:t,runtimeEnv:n,excludeChildRuns:r=!0,reroot:i=!1,distributedParentId:a,apiUrl:o,apiKey:s,workspaceId:c}=e,l=this._convertToCreate(this,n,r);if(t===this.project_name)return{...l,session_name:t};if(i){if(a)this._sliceParentId(a,l);else if(l.parent_run_id=void 0,l.dotted_order){let e=l.dotted_order.split(`.`);e.length>0&&(l.dotted_order=e[e.length-1],l.trace_id=l.id)}let e=cO({projectName:t,apiUrl:o,apiKey:s,workspaceId:c});this._setReplicaTraceRoot(e,l.id)}let u;if(!i&&(u=(aO(this,iO)??{})[cO({projectName:t,apiUrl:o,apiKey:s,workspaceId:c})],u&&(l.trace_id=u,l.dotted_order))){let e=l.dotted_order.split(`.`),t=null;for(let n=0;n<e.length;n++)if(e[n].slice(-36)===u){t=n;break}t!==null&&(l.dotted_order=e.slice(t).join(`.`))}let d=l.id,f=HC(d,t),p;p=l.trace_id?HC(l.trace_id,t):f;let m;l.parent_run_id&&(m=HC(l.parent_run_id,t));let h;return l.dotted_order&&(h=l.dotted_order.split(`.`).map(e=>{let n=HC(e.slice(-36),t);return e.slice(0,-36)+n}).join(`.`)),{...l,id:f,trace_id:p,parent_run_id:m,dotted_order:h,session_name:t}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let t=Dw();if(this.replicas&&this.replicas.length>0)for(let{projectName:e,apiKey:n,apiUrl:r,workspaceId:i,reroot:a,client:o}of this.replicas){let s=this._remapForProject({projectName:e??this.project_name,runtimeEnv:t,excludeChildRuns:!0,reroot:a,distributedParentId:this.distributedParentId,apiUrl:r,apiKey:n,workspaceId:i});await(o??this.client).createRun(s,{apiKey:n,apiUrl:r,workspaceId:i})}else{let n=this._convertToCreate(this,t,e);await this.client.createRun(n)}if(!e){lC(`Posting with excludeChildRuns=false is deprecated and will be removed in a future version.`);for(let e of this.child_runs)await e.postRun(!1)}this.child_runs=[]}catch(e){console.error(`Error in postRun for run ${this.id}:`,e)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:t,apiKey:n,apiUrl:r,workspaceId:i,updates:a,reroot:o,client:s}of this.replicas){let c=this._remapForProject({projectName:t??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:r,apiKey:n,workspaceId:i}),l={id:c.id,name:c.name,run_type:c.run_type,start_time:c.start_time,outputs:c.outputs,error:c.error,parent_run_id:c.parent_run_id,session_name:c.session_name,reference_example_id:c.reference_example_id,end_time:c.end_time,dotted_order:c.dotted_order,trace_id:c.trace_id,events:c.events,tags:c.tags,extra:c.extra,attachments:this.attachments,...a};e?.excludeInputs||(l.inputs=c.inputs),await(s??this.client).updateRun(c.id,l,{apiKey:n,apiUrl:r,workspaceId:i})}else try{let t={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.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};e?.excludeInputs||(t.inputs=this.inputs),await this.client.updateRun(this.id,t)}catch(e){console.error(`Error in patchRun for run ${this.id}`,e)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||=[],typeof e==`string`?this.events.push({name:`event`,time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(t,n){let r=t?.callbacks,i,a,o,s=UC();if(r){let e=r?.getParentRunId?.()??``,t=r?.handlers?.find(e=>e?.name==`langchain_tracer`);i=t?.getRun?.(e),a=t?.projectName,o=t?.client,s||=!!t}return i?new e({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:o,tracingEnabled:s,project_name:a,tags:[...new Set((i?.tags??[]).concat(t?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...t?.metadata}}}).createChild(n):new e({...n,client:o,tracingEnabled:s,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(t,n){let r=`get`in t&&typeof t.get==`function`?{"langsmith-trace":t.get(`langsmith-trace`),baggage:t.get(`baggage`)}:t,i=r[`langsmith-trace`];if(!i||typeof i!=`string`)return;let a=i.trim(),o=a.split(`.`).map(e=>{let[t,n]=e.split(`Z`);return{strTime:t,time:Date.parse(t+`Z`),uuid:n}}),s=o[0].uuid,c={...n,name:n?.name??`parent`,run_type:n?.run_type??`chain`,start_time:n?.start_time??Date.now(),id:o.at(-1)?.uuid,trace_id:s,dotted_order:a};if(r.baggage&&typeof r.baggage==`string`){let e=mO.fromHeader(r.baggage);c.metadata=e.metadata,c.tags=e.tags,c.project_name=e.project_name,c.replicas=e.replicas}let l=new e(c);return l.distributedParentId=l.id,l}toHeaders(e){let t={"langsmith-trace":this.dotted_order,baggage:new mO(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,r]of Object.entries(t))e.set(n,r);return t}};Object.defineProperty(hO,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function gO(e){return e!=null&&typeof e.createChild==`function`&&typeof e.postRun==`function`}function _O(e){return typeof e==`object`&&!!e&&typeof e.name==`string`&&e.name===`langchain_tracer`}function vO(e){return Array.isArray(e)&&e.some(e=>_O(e))}function yO(e){return typeof e==`object`&&!!e&&Array.isArray(e.handlers)}function bO(e){let t=e?.callbacks;return e!=null&&typeof t==`object`&&(vO(t?.handlers)||vO(t))}function xO(){let e=Aw(`LANGSMITH_RUNS_ENDPOINTS`);if(!e)return[];try{let t=JSON.parse(e);if(Array.isArray(t)){let e=[];for(let n of t){if(typeof n!=`object`||!n){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!=`string`){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!=`string`){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}e.push({apiUrl:n.api_url.replace(/\/$/,``),apiKey:n.api_key})}return e}else if(typeof t==`object`&&t){CO(t);let e=[];for(let[n,r]of Object.entries(t)){let t=n.replace(/\/$/,``);if(typeof r==`string`)e.push({apiUrl:t,apiKey:r});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof r}`);continue}}return e}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof t}`),[]}catch(e){if(GE(e))throw e;return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey`),[]}}function SO(e){return e?e.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):xO()}function CO(e){if(Object.keys(e).length>0&&jw(`ENDPOINT`))throw new WE}var wO=e=>{if(e)return e.events=e.events??[],e.child_runs=e.child_runs??[],e};function TO(e,t){if(e)return new hO({...e,start_time:e._serialized_start_time??e.start_time,parent_run:TO(t),child_runs:e.child_runs.map(e=>TO(e)).filter(e=>e!==void 0),extra:{...e.extra,runtime:Ine()},tracingEnabled:!1})}function EO(e,t){return e&&!Array.isArray(e)&&typeof e==`object`?e:{[t]:e}}function DO(e){return typeof e._addRunToRunMap==`function`}var OO=class extends US{runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(e){super(...arguments)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?wO(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`\n\n${e.stack}`:``):typeof e==`string`?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){let{dottedOrder:t,microsecondPrecisionDatestring:n}=dO(new Date(e.start_time).getTime(),e.id,e.execution_order),r={...e},i=this.getRunById(r.parent_run_id);if(r.parent_run_id===void 0?(r.trace_id=r.id,r.dotted_order=t,r._serialized_start_time=n):i?(this._addChildRun(i,r),i.child_execution_order=Math.max(i.child_execution_order,r.child_execution_order),r.trace_id=i.trace_id,i.dotted_order!==void 0&&(r.dotted_order=[i.dotted_order,t].join(`.`),r._serialized_start_time=n)):r.parent_run_id=void 0,this.usesRunTreeMap){let e=TO(r,i);e!==void 0&&this.runTreeMap.set(r.id,e)}else this.runMap.set(r.id,r);return r}async _endTrace(e){let t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,n,r,i,a,o,s){let c=this._getExecutionOrder(r),l=Date.now(),u=o?{...i,metadata:o}:i,d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,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,n,r,i,a,o,s){let c=this.getRunById(n)??this._createRunForLLMStart(e,t,n,r,i,a,o,s);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,n,r,i,a,o,s){let c=this._getExecutionOrder(r),l=Date.now(),u=o?{...i,metadata:o}:i,d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,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,n,r,i,a,o,s){let c=this.getRunById(n)??this._createRunForChatModelStart(e,t,n,r,i,a,o,s);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,n,r,i){let a=this.getRunById(t);if(!a||a?.run_type!==`llm`)throw 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,...i},await this.onLLMEnd?.(a),await this._endTrace(a),a}async handleLLMError(e,t,n,r,i){let a=this.getRunById(t);if(!a||a?.run_type!==`llm`)throw 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,...i},await this.onLLMError?.(a),await this._endTrace(a),a}_createRunForChainStart(e,t,n,r,i,a,o,s,c){let l=this._getExecutionOrder(r),u=Date.now(),d={id:n,name:s??e.id[e.id.length-1],parent_run_id:r,start_time:u,serialized:e,events:[{name:`start`,time:new Date(u).toISOString()}],inputs:t,execution_order:l,child_execution_order:l,run_type:o??`chain`,child_runs:[],extra:a?{...c,metadata:a}:{...c},tags:i||[]};return this._addRunToRunMap(d)}async handleChainStart(e,t,n,r,i,a,o,s){let c=this.getRunById(n)??this._createRunForChainStart(e,t,n,r,i,a,o,s);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,n,r,i){let a=this.getRunById(t);if(!a)throw Error(`No chain run to end.`);return a.end_time=Date.now(),a.outputs=EO(e,`output`),a.events.push({name:`end`,time:new Date(a.end_time).toISOString()}),i?.inputs!==void 0&&(a.inputs=EO(i.inputs,`input`)),await this.onChainEnd?.(a),await this._endTrace(a),a}async handleChainError(e,t,n,r,i){let a=this.getRunById(t);if(!a)throw Error(`No chain 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()}),i?.inputs!==void 0&&(a.inputs=EO(i.inputs,`input`)),await this.onChainError?.(a),await this._endTrace(a),a}_createRunForToolStart(e,t,n,r,i,a,o){let s=this._getExecutionOrder(r),c=Date.now(),l={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:`start`,time:new Date(c).toISOString()}],inputs:{input:t},execution_order:s,child_execution_order:s,run_type:`tool`,child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,n,r,i,a,o){let s=this.getRunById(n)??this._createRunForToolStart(e,t,n,r,i,a,o);return await this.onRunCreate?.(s),await this.onToolStart?.(s),s}async handleToolEnd(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`tool`)throw Error(`No tool run to end`);return n.end_time=Date.now(),n.outputs={output:e},n.events.push({name:`end`,time:new Date(n.end_time).toISOString()}),await this.onToolEnd?.(n),await this._endTrace(n),n}async handleToolError(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`tool`)throw Error(`No tool run to end`);return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:`error`,time:new Date(n.end_time).toISOString()}),await this.onToolError?.(n),await this._endTrace(n),n}async handleAgentAction(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`chain`)return;let r=n;r.actions=r.actions||[],r.actions.push(e),r.events.push({name:`agent_action`,time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(n)}async handleAgentEnd(e,t){let n=this.getRunById(t);!n||n?.run_type!==`chain`||(n.events.push({name:`agent_end`,time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(n))}_createRunForRetrieverStart(e,t,n,r,i,a,o){let s=this._getExecutionOrder(r),c=Date.now(),l={id:n,name:o??e.id[e.id.length-1],parent_run_id:r,start_time:c,serialized:e,events:[{name:`start`,time:new Date(c).toISOString()}],inputs:{query:t},execution_order:s,child_execution_order:s,run_type:`retriever`,child_runs:[],extra:a?{metadata:a}:{},tags:i||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,n,r,i,a,o){let s=this.getRunById(n)??this._createRunForRetrieverStart(e,t,n,r,i,a,o);return await this.onRunCreate?.(s),await this.onRetrieverStart?.(s),s}async handleRetrieverEnd(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`retriever`)throw Error(`No retriever run to end`);return n.end_time=Date.now(),n.outputs={documents:e},n.events.push({name:`end`,time:new Date(n.end_time).toISOString()}),await this.onRetrieverEnd?.(n),await this._endTrace(n),n}async handleRetrieverError(e,t){let n=this.getRunById(t);if(!n||n?.run_type!==`retriever`)throw Error(`No retriever run to end`);return n.end_time=Date.now(),n.error=this.stringifyError(e),n.events.push({name:`error`,time:new Date(n.end_time).toISOString()}),await this.onRetrieverError?.(n),await this._endTrace(n),n}async handleText(e,t){let n=this.getRunById(t);!n||n?.run_type!==`chain`||(n.events.push({name:`text`,time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(n))}async handleLLMNewToken(e,t,n,r,i,a){let o=this.getRunById(n);if(!o||o?.run_type!==`llm`)throw Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`);return o.events.push({name:`new_token`,time:new Date().toISOString(),kwargs:{token:e,idx:t,chunk:a?.chunk}}),await this.onLLMNewToken?.(o,e,{chunk:a?.chunk}),o}},kO={bold:{open:`\x1B[1m`,close:`\x1B[22m`},color:{grey:{open:`\x1B[90m`,close:`\x1B[39m`},green:{open:`\x1B[32m`,close:`\x1B[39m`},cyan:{open:`\x1B[36m`,close:`\x1B[39m`},red:{open:`\x1B[31m`,close:`\x1B[39m`},blue:{open:`\x1B[34m`,close:`\x1B[39m`}}};function AO(e,t){return`${e.open}${t}${e.close}`}function jO(e,t){try{return JSON.stringify(e,null,2)}catch{return t}}function MO(e){return typeof e==`string`?e.trim():e==null?e:jO(e,e.toString())}function NO(e){if(!e.end_time)return``;let t=e.end_time-e.start_time;return t<1e3?`${t}ms`:`${(t/1e3).toFixed(2)}s`}var{color:PO}=kO,FO=class extends OO{name=`console_callback_handler`;persistRun(e){return Promise.resolve()}getParents(e){let t=[],n=e;for(;n.parent_run_id;){let e=this.runMap.get(n.parent_run_id);if(e)t.push(e),n=e;else break}return t}getBreadcrumbs(e){let t=[...this.getParents(e).reverse(),e].map((e,t,n)=>{let r=`${e.execution_order}:${e.run_type}:${e.name}`;return t===n.length-1?AO(kO.bold,r):r}).join(` > `);return AO(PO.grey,t)}onChainStart(e){let t=this.getBreadcrumbs(e);console.log(`${AO(PO.green,`[chain/start]`)} [${t}] Entering Chain run with input: ${jO(e.inputs,`[inputs]`)}`)}onChainEnd(e){let t=this.getBreadcrumbs(e);console.log(`${AO(PO.cyan,`[chain/end]`)} [${t}] [${NO(e)}] Exiting Chain run with output: ${jO(e.outputs,`[outputs]`)}`)}onChainError(e){let t=this.getBreadcrumbs(e);console.log(`${AO(PO.red,`[chain/error]`)} [${t}] [${NO(e)}] Chain run errored with error: ${jO(e.error,`[error]`)}`)}onLLMStart(e){let t=this.getBreadcrumbs(e),n=`prompts`in e.inputs?{prompts:e.inputs.prompts.map(e=>e.trim())}:e.inputs;console.log(`${AO(PO.green,`[llm/start]`)} [${t}] Entering LLM run with input: ${jO(n,`[inputs]`)}`)}onLLMEnd(e){let t=this.getBreadcrumbs(e);console.log(`${AO(PO.cyan,`[llm/end]`)} [${t}] [${NO(e)}] Exiting LLM run with output: ${jO(e.outputs,`[response]`)}`)}onLLMError(e){let t=this.getBreadcrumbs(e);console.log(`${AO(PO.red,`[llm/error]`)} [${t}] [${NO(e)}] LLM run errored with error: ${jO(e.error,`[error]`)}`)}onToolStart(e){let t=this.getBreadcrumbs(e);console.log(`${AO(PO.green,`[tool/start]`)} [${t}] Entering Tool run with input: "${MO(e.inputs.input)}"`)}onToolEnd(e){let t=this.getBreadcrumbs(e);console.log(`${AO(PO.cyan,`[tool/end]`)} [${t}] [${NO(e)}] Exiting Tool run with output: "${MO(e.outputs?.output)}"`)}onToolError(e){let t=this.getBreadcrumbs(e);console.log(`${AO(PO.red,`[tool/error]`)} [${t}] [${NO(e)}] Tool run errored with error: ${jO(e.error,`[error]`)}`)}onRetrieverStart(e){let t=this.getBreadcrumbs(e);console.log(`${AO(PO.green,`[retriever/start]`)} [${t}] Entering Retriever run with input: ${jO(e.inputs,`[inputs]`)}`)}onRetrieverEnd(e){let t=this.getBreadcrumbs(e);console.log(`${AO(PO.cyan,`[retriever/end]`)} [${t}] [${NO(e)}] Exiting Retriever run with output: ${jO(e.outputs,`[outputs]`)}`)}onRetrieverError(e){let t=this.getBreadcrumbs(e);console.log(`${AO(PO.red,`[retriever/error]`)} [${t}] [${NO(e)}] Retriever run errored with error: ${jO(e.error,`[error]`)}`)}onAgentAction(e){let t=e,n=this.getBreadcrumbs(e);console.log(`${AO(PO.blue,`[agent/action]`)} [${n}] Agent selected action: ${jO(t.actions[t.actions.length-1],`[action]`)}`)}},IO,zie=()=>(IO===void 0&&(IO=new tO(HS(`LANGCHAIN_CALLBACKS_BACKGROUND`)===`false`?{blockOnRootRunFinalization:!0}:{})),IO),LO=new Set([`ls_agent_type`]);function Bie(e){let t;for(let n of e)for(let e of n)xS.isInstance(e.message)&&e.message.usage_metadata!==void 0&&(t=qx(t,e.message.usage_metadata));return t}var RO=class e extends OO{fields;name=`langchain_tracer`;projectName;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(t={}){super(t),this.fields=t;let{exampleId:n,projectName:r,client:i,replicas:a,metadata:o,tags:s}=t;this.projectName=r??sC(),this.replicas=a,this.exampleId=n,this.client=i??zie(),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=s??[];let c=e.getTraceableRunTree();c&&this.updateFromRunTree(c)}async persistRun(e){}async onRunCreate(e){zO(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){zO(this,e);let t=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await t?.postRun():await t?.patchRun()}onLLMEnd(e){let t=e.outputs;if(t?.generations){let n=Bie(t.generations);if(n!==void 0){e.extra=e.extra??{};let t=e.extra.metadata??{};t.usage_metadata=n,e.extra.metadata=t}}}copyWithTracingConfig({metadata:t,tags:n}){let r;if(t===void 0)r=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)r={...t};else{r={...this.tracingMetadata};for(let[e,n]of Object.entries(t))(!Object.prototype.hasOwnProperty.call(r,e)||LO.has(e))&&(r[e]=n)}let i=n?Array.from(new Set([...this.tracingTags,...n])):[...this.tracingTags],a=new e({...this.fields,metadata:r,tags:i});return a.runMap=this.runMap,a.runTreeMap=this.runTreeMap,a}_getRunStoreKey(){return this.runTreeMap}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let t=e,n=new Set;for(;t.parent_run&&!(n.has(t.id)||(n.add(t.id),!t.parent_run));)t=t.parent_run;n.clear();let r=[t];for(;r.length>0;){let e=r.shift();!e||n.has(e.id)||(n.add(e.id),this.runTreeMap.set(e.id,e),e.child_runs&&r.push(...e.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(e){let t=this.runTreeMap.get(e);if(t)return new hO({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return rie(!0)}catch{return}}static[Symbol.hasInstance](e){if(typeof e!=`object`||!e)return!1;let t=e;return`name`in t&&t.name===`langchain_tracer`&&`copyWithTracingConfig`in t&&typeof t.copyWithTracingConfig==`function`&&`getRunTreeWithTracingConfig`in t&&typeof t.getRunTreeWithTracingConfig==`function`}};function zO(e,t){if(e.tracingMetadata){t.extra??={};let n=t.extra.metadata??{},r=!1;for(let[t,i]of Object.entries(e.tracingMetadata))(!Object.prototype.hasOwnProperty.call(n,t)||LO.has(t))&&n[t]!==i&&(n[t]=i,r=!0);r&&(t.extra.metadata=n)}e.tracingTags.length>0&&(t.tags=Array.from(new Set([...t.tags??[],...e.tracingTags])))}var BO;function Vie(){return new(`default`in tT.default?tT.default.default:tT.default)({autoStart:!0,concurrency:1})}function Hie(){return BO===void 0&&(BO=Vie()),BO}async function VO(e,t){if(t===!0){let t=RS();t===void 0?await e():await t.run(void 0,async()=>e())}else BO=Hie(),BO.add(async()=>{let t=RS();t===void 0?await e():await t.run(void 0,async()=>e())})}var Uie=e=>e===void 0?!![`LANGSMITH_TRACING_V2`,`LANGCHAIN_TRACING_V2`,`LANGSMITH_TRACING`,`LANGCHAIN_TRACING`].find(e=>HS(e)===`true`):e;function HO(e){let t=RS();if(t!==void 0)return t.getStore()?.[LS]?.[e]}var Wie=Symbol(`lc:configure_hooks`),Gie=()=>HO(Wie)||[];function UO(e){return e._getRunStoreKey?.()??e}function Kie(e,t){return e===t?e:e.copyWithTracingConfig({metadata:t.tracingMetadata,tags:t.tracingTags})}function qie(e,t){let n=new Set(t),r=new Map,i=[],a=e=>{let t=UO(e),a=n.has(e),o=r.get(t);if(o===void 0){r.set(t,{index:i.length,tracer:e,hasInheritable:a}),i.push(e);return}a&&!o.hasInheritable?(o.tracer=e,o.hasInheritable=!0):(a||!o.hasInheritable)&&(o.tracer=Kie(o.tracer,e)),i[o.index]=o.tracer};for(let t of e)t instanceof RO?a(t):i.push(t);for(let e of t)e instanceof RO&&!r.has(UO(e))&&a(e);let o=new Set;return{handlers:i,inheritableHandlers:t.flatMap(e=>{if(!(e instanceof RO))return[e];let t=UO(e);return o.has(t)?[]:(o.add(t),[r.get(t)?.tracer??e])})}}function WO(e){return e?Array.isArray(e)||`name`in e?{callbacks:e}:e:{}}var Jie=class{setHandler(e){return this.setHandlers([e])}},GO=class{runId;handlers;inheritableHandlers;tags;inheritableTags;metadata;inheritableMetadata;_parentRunId;constructor(e,t,n,r,i,a,o,s){this.runId=e,this.handlers=t,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=i,this.metadata=a,this.inheritableMetadata=o,this._parentRunId=s}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>VO(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,n,r,i){await Promise.all(this.handlers.map(n=>VO(async()=>{try{await n.handleCustomEvent?.(e,t,this.runId,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)))}},Yie=class extends GO{getChild(e){let t=new qO(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=>VO(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=>VO(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(n){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${n}`),t.raiseError)throw e}},t.awaitHandlers)))}},KO=class extends GO{async handleLLMNewToken(e,t,n,r,i,a){await Promise.all(this.handlers.map(n=>VO(async()=>{if(!n.ignoreLLM)try{await n.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,a)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMNewToken: ${e}`),n.raiseError)throw e}},n.awaitHandlers)))}async handleChatModelStreamEvent(e){await Promise.all(this.handlers.map(t=>VO(async()=>{if(!t.ignoreLLM)try{await t.handleChatModelStreamEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleChatModelStreamEvent: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}async handleLLMError(e,t,n,r,i){await Promise.all(this.handlers.map(t=>VO(async()=>{if(!t.ignoreLLM)try{await t.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,i)}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,n,r,i){await Promise.all(this.handlers.map(t=>VO(async()=>{if(!t.ignoreLLM)try{await t.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,i)}catch(e){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleLLMEnd: ${e}`),t.raiseError)throw e}},t.awaitHandlers)))}},Xie=class extends GO{getChild(e){let t=new qO(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,n,r,i){await Promise.all(this.handlers.map(t=>VO(async()=>{if(!t.ignoreChain)try{await t.handleChainError?.(e,this.runId,this._parentRunId,this.tags,i)}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,n,r,i){await Promise.all(this.handlers.map(t=>VO(async()=>{if(!t.ignoreChain)try{await t.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,i)}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=>VO(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=>VO(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)))}},Zie=class extends GO{getChild(e){let t=new qO(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=>VO(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 handleToolEvent(e){await Promise.all(this.handlers.map(t=>VO(async()=>{if(!t.ignoreAgent)try{await t.handleToolEvent?.(e,this.runId,this._parentRunId,this.tags)}catch(e){if(t.raiseError)throw e}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>VO(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)))}},qO=class e extends Jie{handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name=`callback_manager`;_parentRunId;constructor(e,t){super(),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,n=void 0,r=void 0,i=void 0,a=void 0,o=void 0,s=void 0){return Promise.all(t.map(async(t,r)=>{let a=r===0&&n?n:PS();return await Promise.all(this.handlers.map(n=>{if(!n.ignoreLLM)return DO(n)&&n._createRunForLLMStart(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s),VO(async()=>{try{await n.handleLLMStart?.(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s)}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new KO(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,n=void 0,r=void 0,i=void 0,a=void 0,o=void 0,s=void 0){return Promise.all(t.map(async(t,r)=>{let a=r===0&&n?n:PS();return await Promise.all(this.handlers.map(n=>{if(!n.ignoreLLM)return DO(n)&&n._createRunForChatModelStart(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s),VO(async()=>{try{if(n.handleChatModelStart)await n.handleChatModelStart?.(e,[t],a,this._parentRunId,i,this.tags,this.metadata,s);else if(n.handleLLMStart){let r=yS(t);await n.handleLLMStart?.(e,[r],a,this._parentRunId,i,this.tags,this.metadata,s)}}catch(e){if((n.raiseError?console.error:console.warn)(`Error in handler ${n.constructor.name}, handleLLMStart: ${e}`),n.raiseError)throw e}},n.awaitHandlers)})),new KO(a,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,n=PS(),r=void 0,i=void 0,a=void 0,o=void 0,s=void 0,c=void 0){return await Promise.all(this.handlers.map(i=>{if(!i.ignoreChain)return DO(i)&&i._createRunForChainStart(e,t,n,this._parentRunId,this.tags,this.metadata,r,o,c),VO(async()=>{try{await i.handleChainStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,r,o,c)}catch(e){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainStart: ${e}`),i.raiseError)throw e}},i.awaitHandlers)})),new Xie(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,n=PS(),r=void 0,i=void 0,a=void 0,o=void 0,s=void 0){return await Promise.all(this.handlers.map(r=>{if(!r.ignoreAgent)return DO(r)&&r._createRunForToolStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),VO(async()=>{try{await r.handleToolStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o,s)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleToolStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new Zie(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,n=PS(),r=void 0,i=void 0,a=void 0,o=void 0){return await Promise.all(this.handlers.map(r=>{if(!r.ignoreRetriever)return DO(r)&&r._createRunForRetrieverStart(e,t,n,this._parentRunId,this.tags,this.metadata,o),VO(async()=>{try{await r.handleRetrieverStart?.(e,t,n,this._parentRunId,this.tags,this.metadata,o)}catch(e){if((r.raiseError?console.error:console.warn)(`Error in handler ${r.constructor.name}, handleRetrieverStart: ${e}`),r.raiseError)throw e}},r.awaitHandlers)})),new Yie(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,n,r,i){await Promise.all(this.handlers.map(r=>VO(async()=>{if(!r.ignoreCustomEvent)try{await r.handleCustomEvent?.(e,t,n,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)))}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(let n of e)this.addHandler(n,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(let t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(t=[],n=!0){let r=new e(this._parentRunId);for(let e of this.handlers){let t=this.inheritableHandlers.includes(e);r.addHandler(e,t)}for(let e of this.tags){let t=this.inheritableTags.includes(e);r.addTags([e],t)}for(let e of Object.keys(this.metadata)){let t=Object.keys(this.inheritableMetadata).includes(e);r.addMetadata({[e]:this.metadata[e]},t)}for(let e of t)r.handlers.filter(e=>e.name===`console_callback_handler`).some(t=>t.name===e.name)||r.addHandler(e,n);return r}static fromHandlers(e){class t extends US{name=PS();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new t),n}static configure(e,t,n,r,i,a,o){return this._configureSync(e,t,n,r,i,a,o)}static _configureSync(t,n,r,i,a,o,s){let c;(t||n)&&(Array.isArray(t)||!t?(c=new e,c.setHandlers(t?.map(JO)??[],!0)):c=t,c=c.copy(Array.isArray(n)?n.map(JO):n?.handlers,!1));let l=HS(`LANGCHAIN_VERBOSE`)===`true`||s?.verbose,u=RO.getTraceableRunTree(),d=u?.tracingEnabled??Uie();if(u?.tracingEnabled===!1&&c){let e=c.handlers.filter(e=>e.name===`langchain_tracer`);for(let t of e)c.removeHandler(t)}let f=d||(HS(`LANGCHAIN_TRACING`)??!1);if(l||f){if(c||=new e,l&&!c.handlers.some(e=>e.name===FO.prototype.name)){let e=new FO;c.addHandler(e,!0)}if(f&&!c.handlers.some(e=>e.name===`langchain_tracer`)&&d){let e=new RO;c.addHandler(e,!0)}d&&u&&c._parentRunId===void 0&&(c._parentRunId=u.id,c.handlers.find(e=>e.name===`langchain_tracer`)?.updateFromRunTree(u))}for(let{contextVar:t,inheritable:n=!0,handlerClass:r,envVar:i}of Gie()){let a=i&&HS(i)===`true`&&r,o,s=t===void 0?void 0:HO(t);s&&Bne(s)?o=s:a&&(o=new r({})),o!==void 0&&(c||=new e,c.handlers.some(e=>e.name===o.name)||c.addHandler(o,n))}(r||i)&&c&&(c.addTags(r??[]),c.addTags(i??[],!1)),(a||o)&&c&&(c.addMetadata(a??{}),c.addMetadata(o??{},!1));let p=s?.tracerInheritableMetadata,m=s?.tracerInheritableTags;if(c&&(p||m)){let e=new Map,t=t=>{if(!(t instanceof RO))return t;let n=e.get(t);if(n!==void 0)return n;let r=t.copyWithTracingConfig({metadata:p,tags:m});return e.set(t,r),r};c.handlers=c.handlers.map(t),c.inheritableHandlers=c.inheritableHandlers.map(t)}if(c){let e=qie(c.handlers,c.inheritableHandlers);c.handlers=e.handlers,c.inheritableHandlers=e.inheritableHandlers}return c}};function JO(e){return`name`in e?e:US.fromMethods(e)}var Qie=new class{getStore(){}run(e,t){return t()}enterWith(e){}},YO=Symbol.for(`lc:child_config`),XO=new class{getInstance(){return RS()??Qie}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[YO]}runWithConfig(e,t,n){let r=qO._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),i=this.getInstance(),a=i.getStore(),o=r?.getParentRunId(),s=r?.handlers?.find(e=>e?.name===`langchain_tracer`),c;return s&&o?c=s.getRunTreeWithTracingConfig(o):n||(c=new hO({name:`<runnable_lambda>`,tracingEnabled:!1})),c&&(c.extra={...c.extra,[YO]:e}),a!==void 0&&a[LS]!==void 0&&(c===void 0&&(c={}),c[LS]=a[LS]),i.run(c,t)}initializeGlobalInstance(e){RS()===void 0&&jne(e)}},$ie=new Set([`api_key`]),eae=new Set([`string`,`number`,`boolean`]);function tae(e){let t=e.configurable??{},n=e.metadata??{},r={};for(let[e,i]of Object.entries(t))!e.startsWith(`__`)&&!Object.prototype.hasOwnProperty.call(n,e)&&!$ie.has(e)&&eae.has(typeof i)&&(r[e]=i);return Object.keys(r).length>0?r:void 0}async function ZO(e){return qO._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata,void 0,{tracerInheritableMetadata:e?tae(e):void 0})}function QO(...e){let t={};for(let n of e.filter(e=>!!e))for(let e of Object.keys(n))if(e===`metadata`)t[e]={...t[e],...n[e]};else if(e===`tags`){let r=t[e]??[];t[e]=[...new Set(r.concat(n[e]??[]))]}else if(e===`configurable`)t[e]={...t[e],...n[e]};else if(e===`timeout`)t.timeout===void 0?t.timeout=n.timeout:n.timeout!==void 0&&(t.timeout=Math.min(t.timeout,n.timeout));else if(e===`signal`)t.signal===void 0?t.signal=n.signal:n.signal!==void 0&&(`any`in AbortSignal?t.signal=AbortSignal.any([t.signal,n.signal]):t.signal=n.signal);else if(e===`callbacks`){let e=t.callbacks,r=n.callbacks;if(Array.isArray(r))if(!e)t.callbacks=r;else if(Array.isArray(e))t.callbacks=e.concat(r);else{let n=e.copy();for(let e of r)n.addHandler(JO(e),!0);t.callbacks=n}else if(r)if(!e)t.callbacks=r;else if(Array.isArray(e)){let n=r.copy();for(let t of e)n.addHandler(JO(t),!0);t.callbacks=n}else t.callbacks=new qO(r._parentRunId,{handlers:e.handlers.concat(r.handlers),inheritableHandlers:e.inheritableHandlers.concat(r.inheritableHandlers),tags:Array.from(new Set(e.tags.concat(r.tags))),inheritableTags:Array.from(new Set(e.inheritableTags.concat(r.inheritableTags))),metadata:{...e.metadata,...r.metadata}})}else{let r=e;t[r]=n[r]??t[r]}return t}function $O(e){let t=XO.getRunnableConfig(),n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(t){let{runId:e,runName:r,...i}=t;n=Object.entries(i).reduce((e,[t,n])=>(n!==void 0&&(e[t]=n),e),n)}if(e&&(n=Object.entries(e).reduce((e,[t,n])=>(n!==void 0&&(e[t]=n),e),n)),n?.configurable&&typeof n.configurable.model==`string`&&n.metadata?.model===void 0&&(n.metadata||={},n.metadata.model=n.configurable.model),n.timeout!==void 0){if(n.timeout<=0)throw Error(`Timeout must be a positive number`);let e=n.timeout,t=AbortSignal.timeout(e);n.metadata||={},n.metadata.timeoutMs===void 0&&(n.metadata.timeoutMs=e),n.signal===void 0?n.signal=t:`any`in AbortSignal&&(n.signal=AbortSignal.any([n.signal,t])),delete n.timeout}return n}function ek(e={},{callbacks:t,maxConcurrency:n,recursionLimit:r,runName:i,configurable:a,runId:o}={}){let s=$O(e);return t!==void 0&&(delete s.runName,s.callbacks=t),r!==void 0&&(s.recursionLimit=r),n!==void 0&&(s.maxConcurrency=n),i!==void 0&&(s.runName=i),a!==void 0&&(s.configurable={...s.configurable,...a}),o!==void 0&&delete s.runId,s}function tk(e){if(e)return{configurable:e.configurable,recursionLimit:e.recursionLimit,callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,maxConcurrency:e.maxConcurrency,timeout:e.timeout,signal:e.signal,store:e.store}}async function nk(e,t){if(t===void 0)return e;let n;return Promise.race([e.catch(e=>{if(!t?.aborted)throw e}),new Promise((e,r)=>{n=()=>{r(rk(t))},t.addEventListener(`abort`,n,{once:!0}),t.aborted&&r(rk(t))})]).finally(()=>t.removeEventListener(`abort`,n))}function rk(e){return e?.reason instanceof Error?e.reason:typeof e?.reason==`string`?Error(e.reason):Error(`Aborted`)}var ik=class e extends ReadableStream{reader;ensureReader(){this.reader||=this.getReader()}async next(){this.ensureReader();try{let 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){let e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){let e=this.reader.cancel();this.reader.releaseLock(),await e}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(t){let n=t.getReader();return new e({start(e){return t();function t(){return n.read().then(({done:n,value:r})=>{if(n){e.close();return}return e.enqueue(r),t()})}},cancel(){n.releaseLock()}})}static fromAsyncGenerator(t){return new e({async pull(e){let{value:n,done:r}=await t.next();r&&e.close(),e.enqueue(n)},async cancel(e){await t.return(e)}})}};function ak(e,t=2){let n=Array.from({length:t},()=>[]);return n.map(async function*(t){for(;;)if(t.length===0){let t=await e.next();for(let e of n)e.push(t)}else if(t[0].done)return;else yield t.shift().value})}function ok(e,t){if(Array.isArray(e)&&Array.isArray(t))return e.concat(t);if(typeof e==`string`&&typeof t==`string`||typeof e==`number`&&typeof t==`number`)return e+t;if(`concat`in e&&typeof e.concat==`function`)return e.concat(t);if(typeof e==`object`&&typeof t==`object`){let n={...e};for(let[e,r]of Object.entries(t))e in n&&!Array.isArray(n[e])?n[e]=ok(n[e],r):n[e]=r;return n}else throw Error(`Cannot concat ${typeof e} and ${typeof t}`)}var sk=class{generator;setup;config;signal;firstResult;firstResultUsed=!1;constructor(e){this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,n)=>{XO.runWithConfig(tk(e.config),async()=>{this.firstResult=this.signal?nk(e.generator.next(),this.signal):e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,n):this.firstResult.then(e=>t(void 0),n)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?XO.runWithConfig(tk(this.config),this.signal?async()=>nk(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 nae(e,t,n,r,...i){let a=new sk({generator:t,startSetup:n,signal:r}),o=await a.setup;return{output:e(a,o,...i),setup:o}}var rae=Object.prototype.hasOwnProperty;function ck(e,t){return rae.call(e,t)}function lk(e){if(Array.isArray(e)){let t=Array(e.length);for(let e=0;e<t.length;e++)t[e]=``+e;return t}if(Object.keys)return Object.keys(e);let t=[];for(let n in e)ck(e,n)&&t.push(n);return t}function uk(e){switch(typeof e){case`object`:return JSON.parse(JSON.stringify(e));case`undefined`:return null;default:return e}}function dk(e){let t=0,n=e.length,r;for(;t<n;){if(r=e.charCodeAt(t),r>=48&&r<=57){t++;continue}return!1}return!0}function fk(e){return e.indexOf(`/`)===-1&&e.indexOf(`~`)===-1?e:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function iae(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function pk(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(pk(e[t]))return!0}else if(typeof e==`object`){let n=lk(e),r=n.length;for(var t=0;t<r;t++)if(pk(e[n[t]]))return!0}}return!1}function mk(e,t){let n=[e];for(let e in t){let r=typeof t[e]==`object`?JSON.stringify(t[e],null,2):t[e];r!==void 0&&n.push(`${e}: ${r}`)}return n.join(`
|
|
108
|
-
`)}var aae=class extends Error{name;index;operation;tree;constructor(e,t,n,r,i){super(mk(e,{name:t,index:n,operation:r,tree:i})),this.name=t,this.index=n,this.operation=r,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=mk(e,{name:t,index:n,operation:r,tree:i})}},oae=Eb({JsonPatchError:()=>hk,_areEquals:()=>Sk,applyOperation:()=>vk,applyPatch:()=>yk,applyReducer:()=>lae,deepClone:()=>sae,getValueByPointer:()=>_k,validate:()=>xk,validator:()=>bk}),hk=aae,sae=uk,gk={add:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){let r=_k(n,this.path);r&&=uk(r);let i=vk(n,{op:`remove`,path:this.from}).removed;return vk(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){let r=_k(n,this.from);return vk(n,{op:`add`,path:this.path,value:uk(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:Sk(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},cae={add:function(e,t,n){return dk(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){return{newDocument:n,removed:e.splice(t,1)[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:gk.move,copy:gk.copy,test:gk.test,_get:gk._get};function _k(e,t){if(t==``)return e;var n={op:`_get`,path:t};return vk(e,n),n.value}function vk(e,t,n=!1,r=!0,i=!0,a=0){if(n&&(typeof n==`function`?n(t,0,e,t.path):bk(t,0)),t.path===``){let r={newDocument:e};if(t.op===`add`)return r.newDocument=t.value,r;if(t.op===`replace`)return r.newDocument=t.value,r.removed=e,r;if(t.op===`move`||t.op===`copy`)return r.newDocument=_k(e,t.from),t.op===`move`&&(r.removed=e),r;if(t.op===`test`){if(r.test=Sk(e,t.value),r.test===!1)throw new hk(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return r.newDocument=e,r}else if(t.op===`remove`)return r.removed=e,r.newDocument=null,r;else if(t.op===`_get`)return t.value=e,r;else if(n)throw new hk("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,a,t,e);else return r}else{r||(e=uk(e));let o=(t.path||``).split(`/`),s=e,c=1,l=o.length,u,d,f;for(f=typeof n==`function`?n:bk;;){if(d=o[c],d&&d.indexOf(`~`)!=-1&&(d=iae(d)),i&&(d==`__proto__`||d==`prototype`&&c>0&&o[c-1]==`constructor`))throw 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(n&&u===void 0&&(s[d]===void 0?u=o.slice(0,c).join(`/`):c==l-1&&(u=t.path),u!==void 0&&f(t,0,e,u)),c++,Array.isArray(s)){if(d===`-`)d=s.length;else if(n&&!dk(d))throw new hk(`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);else dk(d)&&(d=~~d);if(c>=l){if(n&&t.op===`add`&&d>s.length)throw new hk(`The specified index MUST NOT be greater than the number of elements in the array`,`OPERATION_VALUE_OUT_OF_BOUNDS`,a,t,e);let r=cae[t.op].call(t,s,d,e);if(r.test===!1)throw new hk(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return r}}else if(c>=l){let n=gk[t.op].call(t,s,d,e);if(n.test===!1)throw new hk(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return n}if(s=s[d],n&&c<l&&(!s||typeof s!=`object`))throw new hk(`Cannot perform operation at the desired path`,`OPERATION_PATH_UNRESOLVABLE`,a,t,e)}}}function yk(e,t,n,r=!0,i=!0){if(n&&!Array.isArray(t))throw new hk(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);r||(e=uk(e));let a=Array(t.length);for(let r=0,o=t.length;r<o;r++)a[r]=vk(e,t[r],n,!0,i,r),e=a[r].newDocument;return a.newDocument=e,a}function lae(e,t,n){let r=vk(e,t);if(r.test===!1)throw new hk(`Test operation failed`,`TEST_OPERATION_FAILED`,n,t,e);return r.newDocument}function bk(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e))throw new hk(`Operation is not an object`,`OPERATION_NOT_AN_OBJECT`,t,e,n);if(!gk[e.op])throw new hk("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,t,e,n);if(typeof e.path!=`string`)throw new hk("Operation `path` property is not a string",`OPERATION_PATH_INVALID`,t,e,n);if(e.path.indexOf(`/`)!==0&&e.path.length>0)throw new hk('Operation `path` property must start with "/"',`OPERATION_PATH_INVALID`,t,e,n);if((e.op===`move`||e.op===`copy`)&&typeof e.from!=`string`)throw new hk("Operation `from` property is not present (applicable in `move` and `copy` operations)",`OPERATION_FROM_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&e.value===void 0)throw new hk("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&pk(e.value))throw new hk("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED`,t,e,n);if(n){if(e.op==`add`){var i=e.path.split(`/`).length,a=r.split(`/`).length;if(i!==a+1&&i!==a)throw new hk("Cannot perform an `add` operation at the desired path",`OPERATION_PATH_CANNOT_ADD`,t,e,n)}else if(e.op===`replace`||e.op===`remove`||e.op===`_get`){if(e.path!==r)throw new hk(`Cannot perform the operation at a path that does not exist`,`OPERATION_PATH_UNRESOLVABLE`,t,e,n)}else if(e.op===`move`||e.op===`copy`){var o=xk([{op:`_get`,path:e.from,value:void 0}],n);if(o&&o.name===`OPERATION_PATH_UNRESOLVABLE`)throw new hk(`Cannot perform the operation from a path that does not exist`,`OPERATION_FROM_UNRESOLVABLE`,t,e,n)}}}function xk(e,t,n){try{if(!Array.isArray(e))throw new hk(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)yk(uk(t),uk(e),n||!0);else{n||=bk;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(e){if(e instanceof hk)return e;throw e}}function Sk(e,t){if(e===t)return!0;if(e&&t&&typeof e==`object`&&typeof t==`object`){var n=Array.isArray(e),r=Array.isArray(t),i,a,o;if(n&&r){if(a=e.length,a!=t.length)return!1;for(i=a;i--!==0;)if(!Sk(e[i],t[i]))return!1;return!0}if(n!=r)return!1;var s=Object.keys(e);if(a=s.length,a!==Object.keys(t).length)return!1;for(i=a;i--!==0;)if(!t.hasOwnProperty(s[i]))return!1;for(i=a;i--!==0;)if(o=s[i],!Sk(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}function Ck(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=lk(t),o=lk(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(ck(t,l)&&!(t[l]===void 0&&u!==void 0&&Array.isArray(t)===!1)){var d=t[l];typeof u==`object`&&u&&typeof d==`object`&&d&&Array.isArray(u)===Array.isArray(d)?Ck(u,d,n,r+`/`+fk(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+fk(l),value:uk(u)}),n.push({op:`replace`,path:r+`/`+fk(l),value:uk(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+fk(l),value:uk(u)}),n.push({op:`remove`,path:r+`/`+fk(l)}),s=!0):(i&&n.push({op:`test`,path:r,value:e}),n.push({op:`replace`,path:r,value:t}))}if(!(!s&&a.length==o.length))for(var c=0;c<a.length;c++){var l=a[c];!ck(e,l)&&t[l]!==void 0&&n.push({op:`add`,path:r+`/`+fk(l),value:uk(t[l])})}}}function uae(e,t,n=!1){var r=[];return Ck(e,t,r,``,n),r}({...oae});var wk=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),n=yk({},t);return new Tk({ops:t,state:n[n.length-1].newDocument})}},Tk=class e extends wk{state;constructor(e){super(e),this.state=e.state}concat(t){let n=this.ops.concat(t.ops),r=yk(this.state,t.ops);return new e({ops:n,state:r[r.length-1].newDocument})}static fromRunLogPatch(t){let n=yk({},t.ops);return new e({ops:t.ops,state:n[n.length-1].newDocument})}},dae=e=>e.name===`log_stream_tracer`;async function Ek(e,t){if(t===`original`)throw 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.`);let{inputs:n}=e;if([`retriever`,`llm`,`prompt`].includes(e.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===``))return n.input}async function Dk(e,t){let{outputs:n}=e;return t===`original`||[`retriever`,`llm`,`prompt`].includes(e.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function fae(e){return e!==void 0&&e.message!==void 0}var Ok=class extends OO{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat=`original`;rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name=`log_stream_tracer`;lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),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=ik.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(n||=t.find(e=>this.includeTags?.includes(e))!==void 0),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(n&&=t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){for await(let n of t){if(e!==this.rootId){let t=this.keyMapByRunId[e];t&&await this.writer.write(new wk({ops:[{op:`add`,path:`/logs/${t}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new wk({ops:[{op:`replace`,path:``,value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;let n={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};this._schemaFormat===`streaming_events`&&(n.inputs=await Ek(e,this._schemaFormat)),await this.writer.write(new wk({ops:[{op:`add`,path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let n=[];this._schemaFormat===`streaming_events`&&n.push({op:`replace`,path:`/logs/${t}/inputs`,value:await Ek(e,this._schemaFormat)}),n.push({op:`add`,path:`/logs/${t}/final_output`,value:await Dk(e,this._schemaFormat)}),e.end_time!==void 0&&n.push({op:`add`,path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let r=new wk({ops:n});await this.writer.write(r)}finally{if(e.id===this.rootId){let t=new wk({ops:[{op:`replace`,path:`/final_output`,value:await Dk(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){let r=this.keyMapByRunId[e.id];if(r===void 0)return;let i=e.inputs.messages!==void 0,a;a=i?fae(n?.chunk)?n?.chunk:new wS({id:`run-${e.id}`,content:t}):t;let o=new wk({ops:[{op:`add`,path:`/logs/${r}/streamed_output_str/-`,value:t},{op:`add`,path:`/logs/${r}/streamed_output/-`,value:a}]});await this.writer.write(o)}},kk=`__run`,Ak=class e{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},jk=class e extends Ak{message;constructor(e){super(e),this.message=e.message}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function Mk({name:e,serialized:t}){return e===void 0?t?.name===void 0?t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:`Unnamed`:t.name:e}var pae=e=>e.name===`event_stream_tracer`,mae=class extends OO{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;name=`event_stream_tracer`;lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),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({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=ik.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(n||=t.find(e=>this.includeTags?.includes(e))!==void 0),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(n&&=t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){let n=await t.next();if(n.done)return;let r=this.runInfoMap.get(e);if(r===void 0){yield n.value;return}function i(e,t){return e===`llm`&&typeof t==`string`?new Ak({text:t}):t}let a=this.tappedPromises.get(e);if(a===void 0){let o;a=new Promise(e=>{o=e}),this.tappedPromises.set(e,a);try{let a={event:`on_${r.runType}_stream`,run_id:e,name:r.name,tags:r.tags,metadata:r.metadata,data:{}};await this.send({...a,data:{chunk:i(r.runType,n.value)}},r),yield n.value;for await(let e of t)r.runType!==`tool`&&r.runType!==`retriever`&&await this.send({...a,data:{chunk:i(r.runType,e)}},r),yield e}finally{o?.()}}else{yield n.value;for await(let e of t)yield e}}async send(e,t){this.readableStreamClosed||this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let n=this.tappedPromises.get(e.run_id);n===void 0?await this.send(e,t):n.then(()=>{this.send(e,t)})}async onLLMStart(e){let t=Mk(e),n=e.inputs.messages===void 0?`llm`:`chat_model`,r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,r);let i=`on_${n}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onLLMNewToken(e,t,n){let r=this.runInfoMap.get(e.id),i,a;if(r===void 0)throw Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(r.runType===`chat_model`)a=`on_chat_model_stream`,i=n?.chunk===void 0?new wS({content:t,id:`run-${e.id}`}):n.chunk.message;else if(r.runType===`llm`)a=`on_llm_stream`,i=n?.chunk===void 0?new Ak({text:t}):n.chunk;else throw Error(`Unexpected run type ${r.runType}`);await this.send({event:a,data:{chunk:i},run_id:e.id,name:r.name,tags:r.tags,metadata:r.metadata},r)}}async onLLMEnd(e){let t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let n;if(t===void 0)throw Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let r=e.outputs?.generations,i;if(t.runType===`chat_model`){for(let e of r??[]){if(i!==void 0)break;i=e[0]?.message}n=`on_chat_model_end`}else if(t.runType===`llm`)i={generations:r?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n=`on_llm_end`;else throw Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){let t=Mk(e),n=e.run_type??`chain`,r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};e.inputs.input===``&&Object.keys(e.inputs).length===1?(i={},r.inputs={}):e.inputs.input===void 0?(i.input=e.inputs,r.inputs=e.inputs):(i.input=e.inputs.input,r.inputs=e.inputs.input),this.runInfoMap.set(e.id,r),await this.send({event:`on_${n}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let n=`on_${e.run_type}_end`,r=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:r};r.input&&Object.keys(r).length===1&&(i.input=r.input,t.inputs=r.input),await this.sendEndEvent({event:n,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=Mk(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:`tool`,inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:`on_tool_start`,data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},n)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let n=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:`on_tool_end`,data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:`on_tool_error`,data:{input:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=Mk(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:`retriever`,inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,n),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??{}},n)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw 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,n){let r=this.runInfoMap.get(n);if(r===void 0)throw Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:`on_custom_event`,run_id:n,name:e,tags:r.tags,metadata:r.metadata,data:t},r)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}},hae=Object.prototype.toString,gae=e=>hae.call(e)===`[object Error]`,_ae=new Set([`network error`,`Failed to fetch`,`NetworkError when attempting to fetch resource.`,`The Internet connection appears to be offline.`,`Network request failed`,`fetch failed`,`terminated`,` A network error occurred.`,`Network connection lost`]);function vae(e){if(!(e&&gae(e)&&e.name===`TypeError`&&typeof e.message==`string`))return!1;let{message:t,stack:n}=e;return t===`Load failed`?n===void 0||`__sentry_captured__`in e:t.startsWith(`error sending request for url`)?!0:_ae.has(t)}function yae(e){if(typeof e==`number`){if(e<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function Nk(e,t,{min:n=0,allowInfinity:r=!1}={}){if(t!==void 0){if(typeof t!=`number`||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${r?` or Infinity`:``}.`);if(!r&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw TypeError(`Expected \`${e}\` to be \u2265 ${n}.`)}}var bae=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name=`AbortError`,this.message=e}};function xae(e,t){let n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1,i=Math.round(r*t.minTimeout*t.factor**(n-1));return i=Math.min(i,t.maxTimeout),i}function Pk(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function Sae({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){let a=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(a instanceof bae)throw a.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,s=i.maxRetryTime??1/0,c=Object.freeze({error:a,attemptNumber:t,retriesLeft:o,retriesConsumed:n});if(await i.onFailedAttempt(c),Pk(r,s)<=0)throw a;let l=await i.shouldConsumeRetry(c),u=Pk(r,s);if(u<=0||o<=0)throw a;if(a instanceof TypeError&&!vae(a)){if(l)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!l)return i.signal?.throwIfAborted(),!1;let d=xae(n,i),f=typeof a.retryAfterMs==`number`&&a.retryAfterMs>=0?a.retryAfterMs:void 0;f!==void 0&&(d=Math.max(d,f));let p=Math.min(d,u);return p>0&&await new Promise((e,t)=>{let n=()=>{clearTimeout(r),i.signal?.removeEventListener(`abort`,n),t(i.signal.reason)},r=setTimeout(()=>{i.signal?.removeEventListener(`abort`,n),e()},p);i.unref&&r.unref?.(),i.signal?.addEventListener(`abort`,n,{once:!0})}),i.signal?.throwIfAborted(),!0}async function Fk(e,t={}){if(t={...t},yae(t.retries),Object.hasOwn(t,`forever`))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,Nk(`factor`,t.factor,{min:0,allowInfinity:!1}),Nk(`minTimeout`,t.minTimeout,{min:0,allowInfinity:!1}),Nk(`maxTimeout`,t.maxTimeout,{min:0,allowInfinity:!0}),Nk(`maxRetryTime`,t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0,i=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();let r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await Sae({error:e,attemptNumber:n,retriesConsumed:r,startTime:i,options:t})&&r++}}throw Error(`Retry attempts exhausted without throwing an error.`)}var Ik=[400,401,402,403,404,405,406,407,409],Lk=6e4,Rk=[/insufficient[_ -]?quota/i,/exceeded (?:your|the current|the available).+quota/i,/usage quota/i,/quota (?:has been )?exhausted/i,/billing/i,/credit balance/i,/out of credits/i,/will reset at/i],zk=/(?:try again in|retry after)\s+(\d+(?:\.\d+)?)\s*(milliseconds?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b/i;function Bk(e){return typeof e==`object`&&e&&`response`in e&&typeof e.response==`object`&&e.response!==null&&`status`in e.response&&typeof e.response.status==`number`?e.response.status:void 0}function Vk(e){if(!(typeof e!=`object`||!e)){if(`status`in e&&typeof e.status==`number`)return e.status;if(`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}}function Hk(e){return typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`?e.message:void 0}function Uk(e){if(!(typeof e!=`object`||!e))return`code`in e&&typeof e.code==`string`?e.code:`error`in e&&typeof e.error==`object`&&e.error!==null&&`code`in e.error&&typeof e.error.code==`string`?e.error.code:void 0}function Wk(e){if(e?.headers)return typeof e.headers.get==`function`?e.headers.get(`retry-after`):e.headers[`retry-after`]??e.headers[`Retry-After`];if(e?.response?.headers)return typeof e.response.headers.get==`function`?e.response.headers.get(`retry-after`):e.response.headers[`retry-after`]??e.response.headers[`Retry-After`]}function Gk(e){if(e==null)return;let t=zk.exec(e);if(!t)return;let n=Number(t[1]),r=t[2]?.toLowerCase();if(!(Number.isNaN(n)||!r))return r===`ms`||r.startsWith(`millisecond`)?n:r===`m`||r.startsWith(`min`)?n*6e4:r===`h`||r.startsWith(`hr`)||r.startsWith(`hour`)?n*36e5:n*1e3}function Kk(e,t){if(e instanceof Error)return e;let n=Error(t);return typeof e==`object`&&e&&Object.assign(n,e),n}function qk(e,t){if(typeof e!=`object`||!e)return;let n=e;n.rateLimitType=t.action,n.rateLimitReason=t.reason,t.retryAfterMs!==void 0&&(n.retryAfterMs=t.retryAfterMs)}function Jk(e){if(e==null)return;let t=e.trim();if(!t)return;let n=Number(t);if(!Number.isNaN(n)&&n>=0)return n*1e3;let r=Date.parse(t);if(!Number.isNaN(r)){let e=r-Date.now();return e>0?e:0}}function Yk(e){if((Bk(e)??Vk(e))!==429)return;if(Uk(e)===`insufficient_quota`)return{action:`stop`,reason:`insufficient_quota`};let t=Hk(e);if(t&&Rk.some(e=>e.test(t)))return{action:`stop`,reason:`quota_message`};let n=Jk(Wk(e))??Gk(t);return n===void 0?{action:`capacity`,reason:`headerless_429`}:n<=Lk?{action:`wait`,retryAfterMs:n,reason:`retry_after_hint`}:{action:`capacity`,retryAfterMs:n,reason:`retry_after_too_large`}}var Xk=e=>{if(typeof e!=`object`||!e)return;if(`message`in e&&typeof e.message==`string`&&(e.message.startsWith(`Cancel`)||e.message.startsWith(`AbortError`))||`name`in e&&typeof e.name==`string`&&e.name===`AbortError`||`code`in e&&typeof e.code==`string`&&e.code===`ECONNABORTED`)throw e;let t=Bk(e)??Vk(e);if(t&&Ik.includes(+t))throw e;if(Uk(e)===`insufficient_quota`){let t=Kk(e,Hk(e)??`Insufficient quota`);throw t.name=`InsufficientQuotaError`,qk(t,{action:`stop`,reason:`insufficient_quota`}),t}let n=Yk(e);if(n){if(n.action===`wait`){qk(e,n);return}let t=Kk(e,Hk(e)??`Rate limit exceeded`);throw t.name===`Error`&&(t.name=n.action===`stop`?`RateLimitQuotaExhaustedError`:`RateLimitCapacityError`),qk(t,n),t}},Zk=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??Xk;let t=`default`in tT.default?tT.default.default:tT.default;this.queue=new t({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>Fk(()=>e(...t).catch(e=>{throw e instanceof Error?e:Error(e)}),{onFailedAttempt:({error:e})=>this.onFailedAttempt?.(e),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){if(e.signal){let r;return Promise.race([this.call(t,...n),new Promise((t,n)=>{r=()=>{n(rk(e.signal))},e.signal?.addEventListener(`abort`,r,{once:!0})})]).finally(()=>{e.signal&&r&&e.signal.removeEventListener(`abort`,r)})}return this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}},Qk=class extends OO{name=`RootListenersTracer`;rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:n,onError:r}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=r}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function $k(e){return e?e.lc_runnable:!1}var eA=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){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 n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,r=e.tags??[];return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(t)),this.includeTags!==void 0&&(n||=r.some(e=>this.includeTags?.includes(e))),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n&&=r.every(e=>!this.excludeTags?.includes(e))),n}},tA=e=>btoa(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``);Du();function nA(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(`_zod`in t))return!1;let n=t._zod;return typeof n==`object`&&!!n&&`def`in n}function rA(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(`_def`in t)||`_zod`in t)return!1;let n=t._def;return typeof n==`object`&&!!n&&`typeName`in n}function iA(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:!!(nA(e)||rA(e))}async function aA(e,t){if(nA(e))try{return{success:!0,data:await mt(e,t)}}catch(e){return{success:!1,error:e}}if(rA(e))return await e.safeParseAsync(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}async function oA(e,t){if(nA(e))return await mt(e,t);if(rA(e))return await e.parseAsync(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function sA(e){if(nA(e))return zs.get(e)?.description;if(rA(e)||`description`in e&&typeof e.description==`string`)return e.description}function cA(e){return iA(e)?rA(e)?e._def.typeName===`ZodString`:nA(e)?e._zod.def.type===`string`:!1:!1}function lA(e){return!!(typeof e==`object`&&e&&`_def`in e&&typeof e._def==`object`&&e._def!==null&&`typeName`in e._def&&e._def.typeName===`ZodObject`)}function uA(e){return nA(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`object`):!1}function dA(e){return nA(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`array`):!1}function fA(e){return nA(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`optional`):!1}function pA(e){return nA(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`nullable`):!1}function mA(e,t=!1){if(lA(e))return e.strict();if(uA(e)){let n=e._zod.def.shape;if(t)for(let[r,i]of Object.entries(e._zod.def.shape)){if(uA(i))n[r]=mA(i,t);else if(dA(i)){let e=i._zod.def.element;uA(e)&&(e=mA(e,t)),n[r]=Se(i,{...i._zod.def,element:e})}else n[r]=i;let e=zs.get(i);e&&zs.add(n[r],e)}let r=Se(e,{...e._zod.def,shape:n,catchall:Pc(Mi)}),i=zs.get(e);return i&&zs.add(r,i),r}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function hA(e){return rA(e)&&`typeName`in e._def&&e._def.typeName===`ZodEffects`}function gA(e){return nA(e)&&e._zod.def.type===`pipe`}function _A(e,t,n){let r=n.get(e);if(r!==void 0)return r;if(rA(e))return hA(e)?_A(e._def.schema,t,n):e;if(nA(e)){let r=e;if(gA(e)&&(r=_A(e._zod.def.in,t,n)),t){if(uA(r)){let e={};for(let[i,a]of Object.entries(r._zod.def.shape))e[i]=_A(a,t,n);r=Se(r,{...r._zod.def,shape:e})}else if(dA(r)){let e=_A(r._zod.def.element,t,n);r=Se(r,{...r._zod.def,element:e})}else if(fA(r)){let e=_A(r._zod.def.innerType,t,n);r=Se(r,{...r._zod.def,innerType:e})}else if(pA(r)){let e=_A(r._zod.def.innerType,t,n);r=Se(r,{...r._zod.def,innerType:e})}}let i=zs.get(e);return i&&zs.add(r,i),n.set(e,r),r}throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function vA(e,t=!1){return _A(e,t,new WeakMap)}function yA(e){return e instanceof Error&&(e.constructor.name===`ZodError`||e.constructor.name===`$ZodError`)}function bA(e){return e.replace(/[^a-zA-Z-_0-9]/g,`_`)}var xA=[`*`,`_`,"`"];function SA(e){let t=``;for(let[n,r]of Object.entries(e))t+=`\tclassDef ${n} ${r};\n`;return t}function CA(e,t,n){let{firstNode:r,lastNode:i,nodeColors:a,withStyles:o=!0,curveStyle:s=`linear`,wrapLabelNWords:c=9}=n??{},l=o?`%%{init: {'flowchart': {'curve': '${s}'}}}%%\ngraph TD;\n`:`graph TD;
|
|
109
|
-
`;if(o){let t=`default`,n={[t]:`{0}({1})`};r!==void 0&&(n[r]=`{0}([{1}]):::first`),i!==void 0&&(n[i]=`{0}([{1}]):::last`);for(let[r,i]of Object.entries(e)){let e=i.name.split(`:`).pop()??``,a=
|
|
110
|
-
`)}</em></small>`);let o=(n[r]??n[t]).replace(`{0}`,
|
|
111
|
-
`)}p(u[``]??[],``);for(let e in u)!e.includes(`:`)&&e!==``&&p(u[e],e);return o&&(l+=
|
|
112
|
-
`));return await o.blob()}var TA=Symbol(`Let zodToJsonSchema decide on which parser to use`),EA={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},DA=e=>typeof e==`string`?{...EA,name:e}:{...EA,...e},OA=e=>{let t=DA(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},kA=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function AA(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?kA(t,e.currentPath):t.join(`/`)}}function jA(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function MA(e,t,n,r,i){e[t]=n,jA(e,t,r,i)}var NA,PA,FA,IA,LA=c((()=>{(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(NA||={}),(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(PA||={}),FA=NA.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),IA=e=>{switch(typeof e){case`undefined`:return FA.undefined;case`string`:return FA.string;case`number`:return Number.isNaN(e)?FA.nan:FA.number;case`boolean`:return FA.boolean;case`function`:return FA.function;case`bigint`:return FA.bigint;case`symbol`:return FA.symbol;case`object`:return Array.isArray(e)?FA.array:e===null?FA.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?FA.promise:typeof Map<`u`&&e instanceof Map?FA.map:typeof Set<`u`&&e instanceof Set?FA.set:typeof Date<`u`&&e instanceof Date?FA.date:FA.object;default:return FA.unknown}}})),W,RA,zA=c((()=>{LA(),W=NA.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`]),RA=class e 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]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,NA.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}},RA.create=e=>new RA(e)})),BA,VA=c((()=>{zA(),LA(),BA=(e,t)=>{let n;switch(e.code){case W.invalid_type:n=e.received===FA.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case W.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,NA.jsonStringifyReplacer)}`;break;case W.unrecognized_keys:n=`Unrecognized key(s) in object: ${NA.joinValues(e.keys,`, `)}`;break;case W.invalid_union:n=`Invalid input`;break;case W.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${NA.joinValues(e.options)}`;break;case W.invalid_enum_value:n=`Invalid enum value. Expected ${NA.joinValues(e.options)}, received '${e.received}'`;break;case W.invalid_arguments:n=`Invalid function arguments`;break;case W.invalid_return_type:n=`Invalid function return type`;break;case W.invalid_date:n=`Invalid date`;break;case W.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:NA.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case W.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`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 W.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case W.custom:n=`Invalid input`;break;case W.invalid_intersection_types:n=`Intersection results could not be merged`;break;case W.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case W.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,NA.assertNever(e)}return{message:n}}}));function HA(){return UA}var UA,WA=c((()=>{VA(),UA=BA}));function G(e,t){let n=HA(),r=GA({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===BA?void 0:BA].filter(e=>!!e)});e.common.issues.push(r)}var GA,KA,qA,JA,YA,XA,ZA,QA,$A,ej=c((()=>{WA(),VA(),GA=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}},KA=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return qA;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return qA;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},qA=Object.freeze({status:`aborted`}),JA=e=>({status:`dirty`,value:e}),YA=e=>({status:`valid`,value:e}),XA=e=>e.status===`aborted`,ZA=e=>e.status===`dirty`,QA=e=>e.status===`valid`,$A=e=>typeof Promise<`u`&&e instanceof Promise})),tj=c((()=>{})),nj,rj=c((()=>{(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(nj||={})}));function ij(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}function aj(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function oj(e){return RegExp(`^${aj(e)}$`)}function sj(e){let t=`${Pj}T${aj(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function cj(e,t){return!!((t===`v4`||!t)&&Oj.test(e)||(t===`v6`||!t)&&Aj.test(e))}function lj(e,t){if(!Cj.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function uj(e,t){return!!((t===`v4`||!t)&&kj.test(e)||(t===`v6`||!t)&&jj.test(e))}function dj(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}function fj(e){if(e instanceof Yj){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=dM.create(fj(r))}return new Yj({...e._def,shape:()=>t})}else if(e instanceof Jj)return new Jj({...e._def,type:fj(e.element)});else if(e instanceof dM)return dM.create(fj(e.unwrap()));else if(e instanceof fM)return fM.create(fj(e.unwrap()));else if(e instanceof eM)return eM.create(e.items.map(e=>fj(e)));else return e}function pj(e,t){let n=IA(e),r=IA(t);if(e===t)return{valid:!0,data:e};if(n===FA.object&&r===FA.object){let n=NA.objectKeys(t),r=NA.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=pj(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===FA.array&&r===FA.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=pj(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===FA.date&&r===FA.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}function mj(e,t){return new sM({values:e,typeName:K.ZodEnum,...ij(t)})}var hj,gj,_j,vj,yj,bj,xj,Sj,Cj,wj,Tj,Ej,Dj,Oj,kj,Aj,jj,Mj,Nj,Pj,Fj,Ij,Lj,Rj,zj,Bj,Vj,Hj,Uj,Wj,Gj,Kj,qj,Jj,Yj,Xj,Zj,Qj,$j,eM,tM,nM,rM,iM,aM,oM,sM,cM,lM,uM,dM,fM,pM,mM,hM,gM,_M,vM,K,yM,bM,xM,SM=c((()=>{zA(),WA(),rj(),ej(),LA(),hj=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},gj=(e,t)=>{if(QA(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new RA(e.common.issues);return this._error=t,this._error}}},_j=class{get description(){return this._def.description}_getType(e){return IA(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:IA(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new KA,ctx:{common:e.parent.common,data:e.data,parsedType:IA(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if($A(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:IA(e)},r=this._parseSync({data:e,path:n.path,parent:n});return gj(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:IA(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return QA(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>QA(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:IA(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await($A(r)?r:Promise.resolve(r));return gj(n,i)}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:W.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new uM({schema:this,typeName:K.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 dM.create(this,this._def)}nullable(){return fM.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Jj.create(this)}promise(){return lM.create(this,this._def)}or(e){return Xj.create([this,e],this._def)}and(e){return $j.create(this,e,this._def)}transform(e){return new uM({...ij(this._def),schema:this,typeName:K.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new pM({...ij(this._def),innerType:this,defaultValue:t,typeName:K.ZodDefault})}brand(){return new gM({typeName:K.ZodBranded,type:this,...ij(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new mM({...ij(this._def),innerType:this,catchValue:t,typeName:K.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return _M.create(this,e)}readonly(){return vM.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},vj=/^c[^\s-]{8,}$/i,yj=/^[0-9a-z]+$/,bj=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xj=/^[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,Sj=/^[a-z0-9_-]{21}$/i,Cj=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,wj=/^[-+]?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)?)??$/,Tj=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ej=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,Oj=/^(?:(?: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])$/,kj=/^(?:(?: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])$/,Aj=/^(([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]))$/,jj=/^(([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])$/,Mj=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Nj=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Pj=`((\\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])))`,Fj=RegExp(`^${Pj}$`),Ij=class e extends _j{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==FA.string){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:FA.string,received:t.parsedType}),qA}let t=new KA,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?G(n,{code:W.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&G(n,{code:W.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Tj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`email`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Dj||=new RegExp(Ej,`u`),Dj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`emoji`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)xj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`uuid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Sj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`nanoid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)vj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`cuid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)yj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`cuid2`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)bj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`ulid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),G(n,{validation:`url`,code:W.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`regex`,code:W.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?sj(r).test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Fj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?oj(r).test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?wj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`duration`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?cj(e.data,r.version)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`ip`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?lj(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`jwt`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?uj(e.data,r.version)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`cidr`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Mj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`base64`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Nj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`base64url`,code:W.invalid_string,message:r.message}),t.dirty()):NA.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:W.invalid_string,...nj.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...nj.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...nj.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...nj.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...nj.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...nj.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...nj.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...nj.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...nj.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...nj.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...nj.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...nj.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...nj.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...nj.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...nj.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...nj.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...nj.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...nj.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...nj.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...nj.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...nj.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...nj.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...nj.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...nj.errToObj(t)})}nonempty(e){return this.min(1,nj.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}},Ij.create=e=>new Ij({checks:[],typeName:K.ZodString,coerce:e?.coerce??!1,...ij(e)}),Lj=class e extends _j{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==FA.number){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:FA.number,received:t.parsedType}),qA}let t,n=new KA;for(let r of this._def.checks)r.kind===`int`?NA.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),G(t,{code:W.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?dj(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),G(t,{code:W.not_finite,message:r.message}),n.dirty()):NA.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,nj.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,nj.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,nj.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,nj.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:nj.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:nj.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:nj.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:nj.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:nj.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:nj.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:nj.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:nj.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:nj.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:nj.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&NA.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}},Lj.create=e=>new Lj({checks:[],typeName:K.ZodNumber,coerce:e?.coerce||!1,...ij(e)}),Rj=class e extends _j{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==FA.bigint)return this._getInvalidInput(e);let t,n=new KA;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):NA.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:FA.bigint,received:t.parsedType}),qA}gte(e,t){return this.setLimit(`min`,e,!0,nj.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,nj.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,nj.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,nj.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:nj.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:nj.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:nj.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:nj.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:nj.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:nj.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}},Rj.create=e=>new Rj({checks:[],typeName:K.ZodBigInt,coerce:e?.coerce??!1,...ij(e)}),zj=class extends _j{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==FA.boolean){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:FA.boolean,received:t.parsedType}),qA}return YA(e.data)}},zj.create=e=>new zj({typeName:K.ZodBoolean,coerce:e?.coerce||!1,...ij(e)}),Bj=class e extends _j{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==FA.date){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:FA.date,received:t.parsedType}),qA}if(Number.isNaN(e.data.getTime()))return G(this._getOrReturnCtx(e),{code:W.invalid_date}),qA;let t=new KA,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):NA.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:nj.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:nj.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}},Bj.create=e=>new Bj({checks:[],coerce:e?.coerce||!1,typeName:K.ZodDate,...ij(e)}),Vj=class extends _j{_parse(e){if(this._getType(e)!==FA.symbol){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:FA.symbol,received:t.parsedType}),qA}return YA(e.data)}},Vj.create=e=>new Vj({typeName:K.ZodSymbol,...ij(e)}),Hj=class extends _j{_parse(e){if(this._getType(e)!==FA.undefined){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:FA.undefined,received:t.parsedType}),qA}return YA(e.data)}},Hj.create=e=>new Hj({typeName:K.ZodUndefined,...ij(e)}),Uj=class extends _j{_parse(e){if(this._getType(e)!==FA.null){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:FA.null,received:t.parsedType}),qA}return YA(e.data)}},Uj.create=e=>new Uj({typeName:K.ZodNull,...ij(e)}),Wj=class extends _j{constructor(){super(...arguments),this._any=!0}_parse(e){return YA(e.data)}},Wj.create=e=>new Wj({typeName:K.ZodAny,...ij(e)}),Gj=class extends _j{constructor(){super(...arguments),this._unknown=!0}_parse(e){return YA(e.data)}},Gj.create=e=>new Gj({typeName:K.ZodUnknown,...ij(e)}),Kj=class extends _j{_parse(e){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:FA.never,received:t.parsedType}),qA}},Kj.create=e=>new Kj({typeName:K.ZodNever,...ij(e)}),qj=class extends _j{_parse(e){if(this._getType(e)!==FA.undefined){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:FA.void,received:t.parsedType}),qA}return YA(e.data)}},qj.create=e=>new qj({typeName:K.ZodVoid,...ij(e)}),Jj=class e extends _j{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==FA.array)return G(t,{code:W.invalid_type,expected:FA.array,received:t.parsedType}),qA;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(G(t,{code:e?W.too_big:W.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(G(t,{code:W.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(G(t,{code:W.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new hj(t,e,t.path,n)))).then(e=>KA.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new hj(t,e,t.path,n)));return KA.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:nj.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:nj.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:nj.toString(n)}})}nonempty(e){return this.min(1,e)}},Jj.create=(e,t)=>new Jj({type:e,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...ij(t)}),Yj=class e extends _j{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=NA.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==FA.object){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:FA.object,received:t.parsedType}),qA}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Kj&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new hj(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Kj){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(G(n,{code:W.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new hj(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>KA.mergeObjectSync(t,e)):KA.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return nj.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:nj.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:K.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of NA.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of NA.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return fj(this)}partial(t){let n={};for(let e of NA.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of NA.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof dM;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return mj(NA.objectKeys(this.shape))}},Yj.create=(e,t)=>new Yj({shape:()=>e,unknownKeys:`strip`,catchall:Kj.create(),typeName:K.ZodObject,...ij(t)}),Yj.strictCreate=(e,t)=>new Yj({shape:()=>e,unknownKeys:`strict`,catchall:Kj.create(),typeName:K.ZodObject,...ij(t)}),Yj.lazycreate=(e,t)=>new Yj({shape:e,unknownKeys:`strip`,catchall:Kj.create(),typeName:K.ZodObject,...ij(t)}),Xj=class extends _j{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new RA(e.ctx.common.issues));return G(t,{code:W.invalid_union,unionErrors:n}),qA}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new RA(e));return G(t,{code:W.invalid_union,unionErrors:i}),qA}}get options(){return this._def.options}},Xj.create=(e,t)=>new Xj({options:e,typeName:K.ZodUnion,...ij(t)}),Zj=e=>e instanceof aM?Zj(e.schema):e instanceof uM?Zj(e.innerType()):e instanceof oM?[e.value]:e instanceof sM?e.options:e instanceof cM?NA.objectValues(e.enum):e instanceof pM?Zj(e._def.innerType):e instanceof Hj?[void 0]:e instanceof Uj?[null]:e instanceof dM?[void 0,...Zj(e.unwrap())]:e instanceof fM?[null,...Zj(e.unwrap())]:e instanceof gM||e instanceof vM?Zj(e.unwrap()):e instanceof mM?Zj(e._def.innerType):[],Qj=class e extends _j{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==FA.object)return G(t,{code:W.invalid_type,expected:FA.object,received:t.parsedType}),qA;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(G(t,{code:W.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),qA)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=Zj(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:K.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...ij(r)})}},$j=class extends _j{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(XA(e)||XA(r))return qA;let i=pj(e.value,r.value);return i.valid?((ZA(e)||ZA(r))&&t.dirty(),{status:t.value,value:i.data}):(G(n,{code:W.invalid_intersection_types}),qA)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}},$j.create=(e,t,n)=>new $j({left:e,right:t,typeName:K.ZodIntersection,...ij(n)}),eM=class e extends _j{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==FA.array)return G(n,{code:W.invalid_type,expected:FA.array,received:n.parsedType}),qA;if(n.data.length<this._def.items.length)return G(n,{code:W.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),qA;!this._def.rest&&n.data.length>this._def.items.length&&(G(n,{code:W.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new hj(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>KA.mergeArray(t,e)):KA.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}},eM.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new eM({items:e,typeName:K.ZodTuple,rest:null,...ij(t)})},tM=class e extends _j{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==FA.object)return G(n,{code:W.invalid_type,expected:FA.object,received:n.parsedType}),qA;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new hj(n,e,n.path,e)),value:a._parse(new hj(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?KA.mergeObjectAsync(t,r):KA.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof _j?new e({keyType:t,valueType:n,typeName:K.ZodRecord,...ij(r)}):new e({keyType:Ij.create(),valueType:t,typeName:K.ZodRecord,...ij(n)})}},nM=class extends _j{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==FA.map)return G(n,{code:W.invalid_type,expected:FA.map,received:n.parsedType}),qA;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new hj(n,e,n.path,[a,`key`])),value:i._parse(new hj(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return qA;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return qA;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}},nM.create=(e,t,n)=>new nM({valueType:t,keyType:e,typeName:K.ZodMap,...ij(n)}),rM=class e extends _j{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==FA.set)return G(n,{code:W.invalid_type,expected:FA.set,received:n.parsedType}),qA;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(G(n,{code:W.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(G(n,{code:W.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return qA;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new hj(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:nj.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:nj.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}},rM.create=(e,t)=>new rM({valueType:e,minSize:null,maxSize:null,typeName:K.ZodSet,...ij(t)}),iM=class e extends _j{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==FA.function)return G(t,{code:W.invalid_type,expected:FA.function,received:t.parsedType}),qA;function n(e,n){return GA({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,HA(),BA].filter(e=>!!e),issueData:{code:W.invalid_arguments,argumentsError:n}})}function r(e,n){return GA({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,HA(),BA].filter(e=>!!e),issueData:{code:W.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof lM){let e=this;return YA(async function(...t){let o=new RA([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return YA(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new RA([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new RA([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:eM.create(t).rest(Gj.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||eM.create([]).rest(Gj.create()),returns:n||Gj.create(),typeName:K.ZodFunction,...ij(r)})}},aM=class extends _j{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}},aM.create=(e,t)=>new aM({getter:e,typeName:K.ZodLazy,...ij(t)}),oM=class extends _j{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return G(t,{received:t.data,code:W.invalid_literal,expected:this._def.value}),qA}return{status:`valid`,value:e.data}}get value(){return this._def.value}},oM.create=(e,t)=>new oM({value:e,typeName:K.ZodLiteral,...ij(t)}),sM=class e extends _j{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return G(t,{expected:NA.joinValues(n),received:t.parsedType,code:W.invalid_type}),qA}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return G(t,{received:t.data,code:W.invalid_enum_value,options:n}),qA}return YA(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}},sM.create=mj,cM=class extends _j{_parse(e){let t=NA.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==FA.string&&n.parsedType!==FA.number){let e=NA.objectValues(t);return G(n,{expected:NA.joinValues(e),received:n.parsedType,code:W.invalid_type}),qA}if(this._cache||=new Set(NA.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=NA.objectValues(t);return G(n,{received:n.data,code:W.invalid_enum_value,options:e}),qA}return YA(e.data)}get enum(){return this._def.values}},cM.create=(e,t)=>new cM({values:e,typeName:K.ZodNativeEnum,...ij(t)}),lM=class extends _j{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==FA.promise&&t.common.async===!1?(G(t,{code:W.invalid_type,expected:FA.promise,received:t.parsedType}),qA):YA((t.parsedType===FA.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}},lM.create=(e,t)=>new lM({type:e,typeName:K.ZodPromise,...ij(t)}),uM=class extends _j{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{G(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return qA;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?qA:r.status===`dirty`||t.value===`dirty`?JA(r.value):r});{if(t.value===`aborted`)return qA;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?qA:r.status===`dirty`||t.value===`dirty`?JA(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?qA:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?qA:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!QA(e))return qA;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>QA(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):qA);NA.assertNever(r)}},uM.create=(e,t,n)=>new uM({schema:e,typeName:K.ZodEffects,effect:t,...ij(n)}),uM.createWithPreprocess=(e,t,n)=>new uM({schema:t,effect:{type:`preprocess`,transform:e},typeName:K.ZodEffects,...ij(n)}),dM=class extends _j{_parse(e){return this._getType(e)===FA.undefined?YA(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}},dM.create=(e,t)=>new dM({innerType:e,typeName:K.ZodOptional,...ij(t)}),fM=class extends _j{_parse(e){return this._getType(e)===FA.null?YA(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}},fM.create=(e,t)=>new fM({innerType:e,typeName:K.ZodNullable,...ij(t)}),pM=class extends _j{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===FA.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}},pM.create=(e,t)=>new pM({innerType:e,typeName:K.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...ij(t)}),mM=class extends _j{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return $A(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new RA(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new RA(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}},mM.create=(e,t)=>new mM({innerType:e,typeName:K.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...ij(t)}),hM=class extends _j{_parse(e){if(this._getType(e)!==FA.nan){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:FA.nan,received:t.parsedType}),qA}return{status:`valid`,value:e.data}}},hM.create=e=>new hM({typeName:K.ZodNaN,...ij(e)}),gM=class extends _j{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},_M=class e extends _j{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?qA:e.status===`dirty`?(t.dirty(),JA(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?qA:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:K.ZodPipeline})}},vM=class extends _j{_parse(e){let t=this._def.innerType._parse(e),n=e=>(QA(e)&&(e.value=Object.freeze(e.value)),e);return $A(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}},vM.create=(e,t)=>new vM({innerType:e,typeName:K.ZodReadonly,...ij(t)}),Yj.lazycreate,(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`})(K||={}),yM=Ij.create,Lj.create,hM.create,Rj.create,zj.create,Bj.create,Vj.create,Hj.create,Uj.create,bM=Wj.create,Gj.create,Kj.create,qj.create,Jj.create,xM=Yj.create,Yj.strictCreate,Xj.create,Qj.create,$j.create,eM.create,tM.create,nM.create,rM.create,iM.create,aM.create,oM.create,sM.create,cM.create,lM.create,uM.create,dM.create,fM.create,uM.createWithPreprocess,_M.create})),CM=c((()=>{WA(),ej(),tj(),LA(),SM(),zA()})),wM=c((()=>{CM(),CM()}));wM();function TM(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==K.ZodAny&&(n.items=hN(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&MA(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&MA(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(MA(n,`minItems`,e.exactLength.value,e.exactLength.message,t),MA(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function EM(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?MA(n,`minimum`,r.value,r.message,t):MA(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),MA(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?MA(n,`maximum`,r.value,r.message,t):MA(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),MA(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:MA(n,`multipleOf`,r.value,r.message,t);break}return n}function DM(){return{type:`boolean`}}function OM(e,t){return hN(e.type._def,t)}var kM=(e,t)=>hN(e.innerType._def,t);function AM(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(n=>AM(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return jM(e,t)}}var jM=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:MA(n,`minimum`,r.value,r.message,t);break;case`max`:MA(n,`maximum`,r.value,r.message,t);break}return n};function MM(e,t){return{...hN(e.innerType._def,t),default:e.defaultValue()}}function NM(e,t){return t.effectStrategy===`input`?hN(e.schema._def,t):AA(t)}function PM(e){return{type:`string`,enum:Array.from(e.values)}}var FM=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function IM(e,t){let n=[hN(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),hN(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(FM(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function LM(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var RM=void 0,zM={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(RM===void 0&&(RM=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),RM),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function BM(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:MA(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:MA(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:WM(n,`email`,r.message,t);break;case`format:idn-email`:WM(n,`idn-email`,r.message,t);break;case`pattern:zod`:GM(n,zM.email,r.message,t);break}break;case`url`:WM(n,`uri`,r.message,t);break;case`uuid`:WM(n,`uuid`,r.message,t);break;case`regex`:GM(n,r.regex,r.message,t);break;case`cuid`:GM(n,zM.cuid,r.message,t);break;case`cuid2`:GM(n,zM.cuid2,r.message,t);break;case`startsWith`:GM(n,RegExp(`^${VM(r.value,t)}`),r.message,t);break;case`endsWith`:GM(n,RegExp(`${VM(r.value,t)}$`),r.message,t);break;case`datetime`:WM(n,`date-time`,r.message,t);break;case`date`:WM(n,`date`,r.message,t);break;case`time`:WM(n,`time`,r.message,t);break;case`duration`:WM(n,`duration`,r.message,t);break;case`length`:MA(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),MA(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:GM(n,RegExp(VM(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&WM(n,`ipv4`,r.message,t),r.version!==`v4`&&WM(n,`ipv6`,r.message,t);break;case`base64url`:GM(n,zM.base64url,r.message,t);break;case`jwt`:GM(n,zM.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&GM(n,zM.ipv4Cidr,r.message,t),r.version!==`v4`&&GM(n,zM.ipv6Cidr,r.message,t);break;case`emoji`:GM(n,zM.emoji(),r.message,t);break;case`ulid`:GM(n,zM.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:WM(n,`binary`,r.message,t);break;case`contentEncoding:base64`:MA(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:GM(n,zM.base64,r.message,t);break}break;case`nanoid`:GM(n,zM.nanoid,r.message,t);break;case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return n}function VM(e,t){return t.patternStrategy===`escape`?UM(e):e}var HM=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function UM(e){let t=``;for(let n=0;n<e.length;n++)HM.has(e[n])||(t+=`\\`),t+=e[n];return t}function WM(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):MA(e,`format`,t,n,r)}function GM(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:KM(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):MA(e,`pattern`,KM(t,r),n,r)}function KM(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
108
|
+
`)}var aae=class extends Error{name;index;operation;tree;constructor(e,t,n,r,i){super(mk(e,{name:t,index:n,operation:r,tree:i})),this.name=t,this.index=n,this.operation=r,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=mk(e,{name:t,index:n,operation:r,tree:i})}},oae=Eb({JsonPatchError:()=>hk,_areEquals:()=>Sk,applyOperation:()=>vk,applyPatch:()=>yk,applyReducer:()=>lae,deepClone:()=>sae,getValueByPointer:()=>_k,validate:()=>xk,validator:()=>bk}),hk=aae,sae=uk,gk={add:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){if(t===`__proto__`||t===`constructor`)throw TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){let r=_k(n,this.path);r&&=uk(r);let i=vk(n,{op:`remove`,path:this.from}).removed;return vk(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){let r=_k(n,this.from);return vk(n,{op:`add`,path:this.path,value:uk(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:Sk(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},cae={add:function(e,t,n){return dk(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){return{newDocument:n,removed:e.splice(t,1)[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:gk.move,copy:gk.copy,test:gk.test,_get:gk._get};function _k(e,t){if(t==``)return e;var n={op:`_get`,path:t};return vk(e,n),n.value}function vk(e,t,n=!1,r=!0,i=!0,a=0){if(n&&(typeof n==`function`?n(t,0,e,t.path):bk(t,0)),t.path===``){let r={newDocument:e};if(t.op===`add`)return r.newDocument=t.value,r;if(t.op===`replace`)return r.newDocument=t.value,r.removed=e,r;if(t.op===`move`||t.op===`copy`)return r.newDocument=_k(e,t.from),t.op===`move`&&(r.removed=e),r;if(t.op===`test`){if(r.test=Sk(e,t.value),r.test===!1)throw new hk(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return r.newDocument=e,r}else if(t.op===`remove`)return r.removed=e,r.newDocument=null,r;else if(t.op===`_get`)return t.value=e,r;else if(n)throw new hk("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,a,t,e);else return r}else{r||(e=uk(e));let o=(t.path||``).split(`/`),s=e,c=1,l=o.length,u,d,f;for(f=typeof n==`function`?n:bk;;){if(d=o[c],d&&d.indexOf(`~`)!=-1&&(d=iae(d)),i&&(d==`__proto__`||d==`prototype`&&c>0&&o[c-1]==`constructor`))throw 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(n&&u===void 0&&(s[d]===void 0?u=o.slice(0,c).join(`/`):c==l-1&&(u=t.path),u!==void 0&&f(t,0,e,u)),c++,Array.isArray(s)){if(d===`-`)d=s.length;else if(n&&!dk(d))throw new hk(`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);else dk(d)&&(d=~~d);if(c>=l){if(n&&t.op===`add`&&d>s.length)throw new hk(`The specified index MUST NOT be greater than the number of elements in the array`,`OPERATION_VALUE_OUT_OF_BOUNDS`,a,t,e);let r=cae[t.op].call(t,s,d,e);if(r.test===!1)throw new hk(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return r}}else if(c>=l){let n=gk[t.op].call(t,s,d,e);if(n.test===!1)throw new hk(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return n}if(s=s[d],n&&c<l&&(!s||typeof s!=`object`))throw new hk(`Cannot perform operation at the desired path`,`OPERATION_PATH_UNRESOLVABLE`,a,t,e)}}}function yk(e,t,n,r=!0,i=!0){if(n&&!Array.isArray(t))throw new hk(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);r||(e=uk(e));let a=Array(t.length);for(let r=0,o=t.length;r<o;r++)a[r]=vk(e,t[r],n,!0,i,r),e=a[r].newDocument;return a.newDocument=e,a}function lae(e,t,n){let r=vk(e,t);if(r.test===!1)throw new hk(`Test operation failed`,`TEST_OPERATION_FAILED`,n,t,e);return r.newDocument}function bk(e,t,n,r){if(typeof e!=`object`||!e||Array.isArray(e))throw new hk(`Operation is not an object`,`OPERATION_NOT_AN_OBJECT`,t,e,n);if(!gk[e.op])throw new hk("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,t,e,n);if(typeof e.path!=`string`)throw new hk("Operation `path` property is not a string",`OPERATION_PATH_INVALID`,t,e,n);if(e.path.indexOf(`/`)!==0&&e.path.length>0)throw new hk('Operation `path` property must start with "/"',`OPERATION_PATH_INVALID`,t,e,n);if((e.op===`move`||e.op===`copy`)&&typeof e.from!=`string`)throw new hk("Operation `from` property is not present (applicable in `move` and `copy` operations)",`OPERATION_FROM_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&e.value===void 0)throw new hk("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&pk(e.value))throw new hk("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED`,t,e,n);if(n){if(e.op==`add`){var i=e.path.split(`/`).length,a=r.split(`/`).length;if(i!==a+1&&i!==a)throw new hk("Cannot perform an `add` operation at the desired path",`OPERATION_PATH_CANNOT_ADD`,t,e,n)}else if(e.op===`replace`||e.op===`remove`||e.op===`_get`){if(e.path!==r)throw new hk(`Cannot perform the operation at a path that does not exist`,`OPERATION_PATH_UNRESOLVABLE`,t,e,n)}else if(e.op===`move`||e.op===`copy`){var o=xk([{op:`_get`,path:e.from,value:void 0}],n);if(o&&o.name===`OPERATION_PATH_UNRESOLVABLE`)throw new hk(`Cannot perform the operation from a path that does not exist`,`OPERATION_FROM_UNRESOLVABLE`,t,e,n)}}}function xk(e,t,n){try{if(!Array.isArray(e))throw new hk(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)yk(uk(t),uk(e),n||!0);else{n||=bk;for(var r=0;r<e.length;r++)n(e[r],r,t,void 0)}}catch(e){if(e instanceof hk)return e;throw e}}function Sk(e,t){if(e===t)return!0;if(e&&t&&typeof e==`object`&&typeof t==`object`){var n=Array.isArray(e),r=Array.isArray(t),i,a,o;if(n&&r){if(a=e.length,a!=t.length)return!1;for(i=a;i--!==0;)if(!Sk(e[i],t[i]))return!1;return!0}if(n!=r)return!1;var s=Object.keys(e);if(a=s.length,a!==Object.keys(t).length)return!1;for(i=a;i--!==0;)if(!t.hasOwnProperty(s[i]))return!1;for(i=a;i--!==0;)if(o=s[i],!Sk(e[o],t[o]))return!1;return!0}return e!==e&&t!==t}function Ck(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=lk(t),o=lk(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(ck(t,l)&&!(t[l]===void 0&&u!==void 0&&Array.isArray(t)===!1)){var d=t[l];typeof u==`object`&&u&&typeof d==`object`&&d&&Array.isArray(u)===Array.isArray(d)?Ck(u,d,n,r+`/`+fk(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+fk(l),value:uk(u)}),n.push({op:`replace`,path:r+`/`+fk(l),value:uk(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+fk(l),value:uk(u)}),n.push({op:`remove`,path:r+`/`+fk(l)}),s=!0):(i&&n.push({op:`test`,path:r,value:e}),n.push({op:`replace`,path:r,value:t}))}if(!(!s&&a.length==o.length))for(var c=0;c<a.length;c++){var l=a[c];!ck(e,l)&&t[l]!==void 0&&n.push({op:`add`,path:r+`/`+fk(l),value:uk(t[l])})}}}function uae(e,t,n=!1){var r=[];return Ck(e,t,r,``,n),r}({...oae});var wk=class{ops;constructor(e){this.ops=e.ops??[]}concat(e){let t=this.ops.concat(e.ops),n=yk({},t);return new Tk({ops:t,state:n[n.length-1].newDocument})}},Tk=class e extends wk{state;constructor(e){super(e),this.state=e.state}concat(t){let n=this.ops.concat(t.ops),r=yk(this.state,t.ops);return new e({ops:n,state:r[r.length-1].newDocument})}static fromRunLogPatch(t){let n=yk({},t.ops);return new e({ops:t.ops,state:n[n.length-1].newDocument})}},dae=e=>e.name===`log_stream_tracer`;async function Ek(e,t){if(t===`original`)throw 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.`);let{inputs:n}=e;if([`retriever`,`llm`,`prompt`].includes(e.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===``))return n.input}async function Dk(e,t){let{outputs:n}=e;return t===`original`||[`retriever`,`llm`,`prompt`].includes(e.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function fae(e){return e!==void 0&&e.message!==void 0}var Ok=class extends OO{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;_schemaFormat=`original`;rootId;keyMapByRunId={};counterMapByRunName={};transformStream;writer;receiveStream;name=`log_stream_tracer`;lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),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=ik.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(n||=t.find(e=>this.includeTags?.includes(e))!==void 0),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(n&&=t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){for await(let n of t){if(e!==this.rootId){let t=this.keyMapByRunId[e];t&&await this.writer.write(new wk({ops:[{op:`add`,path:`/logs/${t}/streamed_output/-`,value:n}]}))}yield n}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new wk({ops:[{op:`replace`,path:``,value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;let n={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};this._schemaFormat===`streaming_events`&&(n.inputs=await Ek(e,this._schemaFormat)),await this.writer.write(new wk({ops:[{op:`add`,path:`/logs/${this.keyMapByRunId[e.id]}`,value:n}]}))}async onRunUpdate(e){try{let t=this.keyMapByRunId[e.id];if(t===void 0)return;let n=[];this._schemaFormat===`streaming_events`&&n.push({op:`replace`,path:`/logs/${t}/inputs`,value:await Ek(e,this._schemaFormat)}),n.push({op:`add`,path:`/logs/${t}/final_output`,value:await Dk(e,this._schemaFormat)}),e.end_time!==void 0&&n.push({op:`add`,path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});let r=new wk({ops:n});await this.writer.write(r)}finally{if(e.id===this.rootId){let t=new wk({ops:[{op:`replace`,path:`/final_output`,value:await Dk(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,n){let r=this.keyMapByRunId[e.id];if(r===void 0)return;let i=e.inputs.messages!==void 0,a;a=i?fae(n?.chunk)?n?.chunk:new wS({id:`run-${e.id}`,content:t}):t;let o=new wk({ops:[{op:`add`,path:`/logs/${r}/streamed_output_str/-`,value:t},{op:`add`,path:`/logs/${r}/streamed_output/-`,value:a}]});await this.writer.write(o)}},kk=`__run`,Ak=class e{text;generationInfo;constructor(e){this.text=e.text,this.generationInfo=e.generationInfo}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo}})}},jk=class e extends Ak{message;constructor(e){super(e),this.message=e.message}concat(t){return new e({text:this.text+t.text,generationInfo:{...this.generationInfo,...t.generationInfo},message:this.message.concat(t.message)})}};function Mk({name:e,serialized:t}){return e===void 0?t?.name===void 0?t?.id!==void 0&&Array.isArray(t?.id)?t.id[t.id.length-1]:`Unnamed`:t.name:e}var pae=e=>e.name===`event_stream_tracer`,mae=class extends OO{autoClose=!0;includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;runInfoMap=new Map;tappedPromises=new Map;transformStream;writer;receiveStream;readableStreamClosed=!1;name=`event_stream_tracer`;lc_prefer_streaming=!0;constructor(e){super({_awaitHandler:!0,...e}),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({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=ik.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let t=e.tags??[],n=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(n||=t.find(e=>this.includeTags?.includes(e))!==void 0),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(n&&=t.every(e=>!this.excludeTags?.includes(e))),n}async*tapOutputIterable(e,t){let n=await t.next();if(n.done)return;let r=this.runInfoMap.get(e);if(r===void 0){yield n.value;return}function i(e,t){return e===`llm`&&typeof t==`string`?new Ak({text:t}):t}let a=this.tappedPromises.get(e);if(a===void 0){let o;a=new Promise(e=>{o=e}),this.tappedPromises.set(e,a);try{let a={event:`on_${r.runType}_stream`,run_id:e,name:r.name,tags:r.tags,metadata:r.metadata,data:{}};await this.send({...a,data:{chunk:i(r.runType,n.value)}},r),yield n.value;for await(let e of t)r.runType!==`tool`&&r.runType!==`retriever`&&await this.send({...a,data:{chunk:i(r.runType,e)}},r),yield e}finally{o?.()}}else{yield n.value;for await(let e of t)yield e}}async send(e,t){this.readableStreamClosed||this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){let n=this.tappedPromises.get(e.run_id);n===void 0?await this.send(e,t):n.then(()=>{this.send(e,t)})}async onLLMStart(e){let t=Mk(e),n=e.inputs.messages===void 0?`llm`:`chat_model`,r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:n,inputs:e.inputs};this.runInfoMap.set(e.id,r);let i=`on_${n}_start`;await this.send({event:i,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onLLMNewToken(e,t,n){let r=this.runInfoMap.get(e.id),i,a;if(r===void 0)throw Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(r.runType===`chat_model`)a=`on_chat_model_stream`,i=n?.chunk===void 0?new wS({content:t,id:`run-${e.id}`}):n.chunk.message;else if(r.runType===`llm`)a=`on_llm_stream`,i=n?.chunk===void 0?new Ak({text:t}):n.chunk;else throw Error(`Unexpected run type ${r.runType}`);await this.send({event:a,data:{chunk:i},run_id:e.id,name:r.name,tags:r.tags,metadata:r.metadata},r)}}async onLLMEnd(e){let t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let n;if(t===void 0)throw Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let r=e.outputs?.generations,i;if(t.runType===`chat_model`){for(let e of r??[]){if(i!==void 0)break;i=e[0]?.message}n=`on_chat_model_end`}else if(t.runType===`llm`)i={generations:r?.map(e=>e.map(e=>({text:e.text,generationInfo:e.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},n=`on_llm_end`;else throw Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:n,data:{output:i,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){let t=Mk(e),n=e.run_type??`chain`,r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type},i={};e.inputs.input===``&&Object.keys(e.inputs).length===1?(i={},r.inputs={}):e.inputs.input===void 0?(i.input=e.inputs,r.inputs=e.inputs):(i.input=e.inputs.input,r.inputs=e.inputs.input),this.runInfoMap.set(e.id,r),await this.send({event:`on_${n}_start`,data:i,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onChainEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let n=`on_${e.run_type}_end`,r=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:r};r.input&&Object.keys(r).length===1&&(i.input=r.input,t.inputs=r.input),await this.sendEndEvent({event:n,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){let t=Mk(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:`tool`,inputs:e.inputs??{}};this.runInfoMap.set(e.id,n),await this.send({event:`on_tool_start`,data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},n)}async onToolEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let n=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:`on_tool_end`,data:{output:n,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onToolError(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:`on_tool_error`,data:{input:t.inputs,error:e.error},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){let t=Mk(e),n={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:`retriever`,inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,n),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??{}},n)}async onRetrieverEnd(e){let t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw 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,n){let r=this.runInfoMap.get(n);if(r===void 0)throw Error(`handleCustomEvent: Run ID ${n} not found in run map.`);await this.send({event:`on_custom_event`,run_id:n,name:e,tags:r.tags,metadata:r.metadata,data:t},r)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}},hae=Object.prototype.toString,gae=e=>hae.call(e)===`[object Error]`,_ae=new Set([`network error`,`Failed to fetch`,`NetworkError when attempting to fetch resource.`,`The Internet connection appears to be offline.`,`Network request failed`,`fetch failed`,`terminated`,` A network error occurred.`,`Network connection lost`]);function vae(e){if(!(e&&gae(e)&&e.name===`TypeError`&&typeof e.message==`string`))return!1;let{message:t,stack:n}=e;return t===`Load failed`?n===void 0||`__sentry_captured__`in e:t.startsWith(`error sending request for url`)?!0:_ae.has(t)}function yae(e){if(typeof e==`number`){if(e<0)throw TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw TypeError("Expected `retries` to be a number or Infinity.")}function Nk(e,t,{min:n=0,allowInfinity:r=!1}={}){if(t!==void 0){if(typeof t!=`number`||Number.isNaN(t))throw TypeError(`Expected \`${e}\` to be a number${r?` or Infinity`:``}.`);if(!r&&!Number.isFinite(t))throw TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw TypeError(`Expected \`${e}\` to be \u2265 ${n}.`)}}var bae=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=Error(e),this.originalError.stack=this.stack),this.name=`AbortError`,this.message=e}};function xae(e,t){let n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1,i=Math.round(r*t.minTimeout*t.factor**(n-1));return i=Math.min(i,t.maxTimeout),i}function Pk(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function Sae({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:i}){let a=e instanceof Error?e:TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(a instanceof bae)throw a.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,s=i.maxRetryTime??1/0,c=Object.freeze({error:a,attemptNumber:t,retriesLeft:o,retriesConsumed:n});if(await i.onFailedAttempt(c),Pk(r,s)<=0)throw a;let l=await i.shouldConsumeRetry(c),u=Pk(r,s);if(u<=0||o<=0)throw a;if(a instanceof TypeError&&!vae(a)){if(l)throw a;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(c))throw a;if(!l)return i.signal?.throwIfAborted(),!1;let d=xae(n,i),f=typeof a.retryAfterMs==`number`&&a.retryAfterMs>=0?a.retryAfterMs:void 0;f!==void 0&&(d=Math.max(d,f));let p=Math.min(d,u);return p>0&&await new Promise((e,t)=>{let n=()=>{clearTimeout(r),i.signal?.removeEventListener(`abort`,n),t(i.signal.reason)},r=setTimeout(()=>{i.signal?.removeEventListener(`abort`,n),e()},p);i.unref&&r.unref?.(),i.signal?.addEventListener(`abort`,n,{once:!0})}),i.signal?.throwIfAborted(),!0}async function Fk(e,t={}){if(t={...t},yae(t.retries),Object.hasOwn(t,`forever`))throw Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=1/0,t.maxRetryTime??=1/0,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,Nk(`factor`,t.factor,{min:0,allowInfinity:!1}),Nk(`minTimeout`,t.minTimeout,{min:0,allowInfinity:!1}),Nk(`maxTimeout`,t.maxTimeout,{min:0,allowInfinity:!0}),Nk(`maxRetryTime`,t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0,i=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();let r=await e(n);return t.signal?.throwIfAborted(),r}catch(e){await Sae({error:e,attemptNumber:n,retriesConsumed:r,startTime:i,options:t})&&r++}}throw Error(`Retry attempts exhausted without throwing an error.`)}var Cae=[400,401,402,403,404,405,406,407,409],Ik=6e4,Lk=[/insufficient[_ -]?quota/i,/exceeded (?:your|the current|the available).+quota/i,/usage quota/i,/quota (?:has been )?exhausted/i,/billing/i,/credit balance/i,/out of credits/i,/will reset at/i],Rk=/(?:try again in|retry after)\s+(\d+(?:\.\d+)?)\s*(milliseconds?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b/i;function zk(e){return typeof e==`object`&&e&&`response`in e&&typeof e.response==`object`&&e.response!==null&&`status`in e.response&&typeof e.response.status==`number`?e.response.status:void 0}function Bk(e){if(!(typeof e!=`object`||!e)){if(`status`in e&&typeof e.status==`number`)return e.status;if(`statusCode`in e&&typeof e.statusCode==`number`)return e.statusCode}}function Vk(e){return typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`?e.message:void 0}function Hk(e){if(!(typeof e!=`object`||!e))return`code`in e&&typeof e.code==`string`?e.code:`error`in e&&typeof e.error==`object`&&e.error!==null&&`code`in e.error&&typeof e.error.code==`string`?e.error.code:void 0}function Uk(e){if(e?.headers)return typeof e.headers.get==`function`?e.headers.get(`retry-after`):e.headers[`retry-after`]??e.headers[`Retry-After`];if(e?.response?.headers)return typeof e.response.headers.get==`function`?e.response.headers.get(`retry-after`):e.response.headers[`retry-after`]??e.response.headers[`Retry-After`]}function Wk(e){if(e==null)return;let t=Rk.exec(e);if(!t)return;let n=Number(t[1]),r=t[2]?.toLowerCase();if(!(Number.isNaN(n)||!r))return r===`ms`||r.startsWith(`millisecond`)?n:r===`m`||r.startsWith(`min`)?n*6e4:r===`h`||r.startsWith(`hr`)||r.startsWith(`hour`)?n*36e5:n*1e3}function Gk(e,t){if(e instanceof Error)return e;let n=Error(t);return typeof e==`object`&&e&&Object.assign(n,e),n}function Kk(e,t){if(typeof e!=`object`||!e)return;let n=e;n.rateLimitType=t.action,n.rateLimitReason=t.reason,t.retryAfterMs!==void 0&&(n.retryAfterMs=t.retryAfterMs)}function qk(e){if(e==null)return;let t=e.trim();if(!t)return;let n=Number(t);if(!Number.isNaN(n)&&n>=0)return n*1e3;let r=Date.parse(t);if(!Number.isNaN(r)){let e=r-Date.now();return e>0?e:0}}function Jk(e){if((zk(e)??Bk(e))!==429)return;if(Hk(e)===`insufficient_quota`)return{action:`stop`,reason:`insufficient_quota`};let t=Vk(e);if(t&&Lk.some(e=>e.test(t)))return{action:`stop`,reason:`quota_message`};let n=qk(Uk(e))??Wk(t);return n===void 0?{action:`capacity`,reason:`headerless_429`}:n<=Ik?{action:`wait`,retryAfterMs:n,reason:`retry_after_hint`}:{action:`capacity`,retryAfterMs:n,reason:`retry_after_too_large`}}var Yk=e=>{if(typeof e!=`object`||!e)return;if(`message`in e&&typeof e.message==`string`&&(e.message.startsWith(`Cancel`)||e.message.startsWith(`AbortError`))||`name`in e&&typeof e.name==`string`&&e.name===`AbortError`||`code`in e&&typeof e.code==`string`&&e.code===`ECONNABORTED`)throw e;let t=zk(e)??Bk(e);if(t&&Cae.includes(+t))throw e;if(Hk(e)===`insufficient_quota`){let t=Gk(e,Vk(e)??`Insufficient quota`);throw t.name=`InsufficientQuotaError`,Kk(t,{action:`stop`,reason:`insufficient_quota`}),t}let n=Jk(e);if(n){if(n.action===`wait`){Kk(e,n);return}let t=Gk(e,Vk(e)??`Rate limit exceeded`);throw t.name===`Error`&&(t.name=n.action===`stop`?`RateLimitQuotaExhaustedError`:`RateLimitCapacityError`),Kk(t,n),t}},Xk=class{maxConcurrency;maxRetries;onFailedAttempt;queue;constructor(e){this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??Yk;let t=`default`in tT.default?tT.default.default:tT.default;this.queue=new t({concurrency:this.maxConcurrency})}async call(e,...t){return this.queue.add(()=>Fk(()=>e(...t).catch(e=>{throw e instanceof Error?e:Error(e)}),{onFailedAttempt:({error:e})=>this.onFailedAttempt?.(e),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...n){if(e.signal){let r;return Promise.race([this.call(t,...n),new Promise((t,n)=>{r=()=>{n(rk(e.signal))},e.signal?.addEventListener(`abort`,r,{once:!0})})]).finally(()=>{e.signal&&r&&e.signal.removeEventListener(`abort`,r)})}return this.call(t,...n)}fetch(...e){return this.call(()=>fetch(...e).then(e=>e.ok?e:Promise.reject(e)))}},Zk=class extends OO{name=`RootListenersTracer`;rootId;config;argOnStart;argOnEnd;argOnError;constructor({config:e,onStart:t,onEnd:n,onError:r}){super({_awaitHandler:!0}),this.config=e,this.argOnStart=t,this.argOnEnd=n,this.argOnError=r}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function Qk(e){return e?e.lc_runnable:!1}var $k=class{includeNames;includeTypes;includeTags;excludeNames;excludeTypes;excludeTags;constructor(e){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 n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,r=e.tags??[];return this.includeNames!==void 0&&(n||=this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(n||=this.includeTypes.includes(t)),this.includeTags!==void 0&&(n||=r.some(e=>this.includeTags?.includes(e))),this.excludeNames!==void 0&&(n&&=!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(n&&=!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(n&&=r.every(e=>!this.excludeTags?.includes(e))),n}},eA=e=>btoa(e).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``);Du();function tA(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(`_zod`in t))return!1;let n=t._zod;return typeof n==`object`&&!!n&&`def`in n}function nA(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(`_def`in t)||`_zod`in t)return!1;let n=t._def;return typeof n==`object`&&!!n&&`typeName`in n}function rA(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:!!(tA(e)||nA(e))}async function iA(e,t){if(tA(e))try{return{success:!0,data:await mt(e,t)}}catch(e){return{success:!1,error:e}}if(nA(e))return await e.safeParseAsync(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}async function aA(e,t){if(tA(e))return await mt(e,t);if(nA(e))return await e.parseAsync(t);throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function oA(e){if(tA(e))return zs.get(e)?.description;if(nA(e)||`description`in e&&typeof e.description==`string`)return e.description}function sA(e){return rA(e)?nA(e)?e._def.typeName===`ZodString`:tA(e)?e._zod.def.type===`string`:!1:!1}function cA(e){return!!(typeof e==`object`&&e&&`_def`in e&&typeof e._def==`object`&&e._def!==null&&`typeName`in e._def&&e._def.typeName===`ZodObject`)}function lA(e){return tA(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`object`):!1}function uA(e){return tA(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`array`):!1}function dA(e){return tA(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`optional`):!1}function fA(e){return tA(e)?!!(typeof e==`object`&&e&&`_zod`in e&&typeof e._zod==`object`&&e._zod!==null&&`def`in e._zod&&typeof e._zod.def==`object`&&e._zod.def!==null&&`type`in e._zod.def&&e._zod.def.type===`nullable`):!1}function pA(e,t=!1){if(cA(e))return e.strict();if(lA(e)){let n=e._zod.def.shape;if(t)for(let[r,i]of Object.entries(e._zod.def.shape)){if(lA(i))n[r]=pA(i,t);else if(uA(i)){let e=i._zod.def.element;lA(e)&&(e=pA(e,t)),n[r]=Se(i,{...i._zod.def,element:e})}else n[r]=i;let e=zs.get(i);e&&zs.add(n[r],e)}let r=Se(e,{...e._zod.def,shape:n,catchall:Pc(Mi)}),i=zs.get(e);return i&&zs.add(r,i),r}throw Error(`Schema must be an instance of z3.ZodObject or z4.$ZodObject`)}function mA(e){return nA(e)&&`typeName`in e._def&&e._def.typeName===`ZodEffects`}function hA(e){return tA(e)&&e._zod.def.type===`pipe`}function gA(e,t,n){let r=n.get(e);if(r!==void 0)return r;if(nA(e))return mA(e)?gA(e._def.schema,t,n):e;if(tA(e)){let r=e;if(hA(e)&&(r=gA(e._zod.def.in,t,n)),t){if(lA(r)){let e={};for(let[i,a]of Object.entries(r._zod.def.shape))e[i]=gA(a,t,n);r=Se(r,{...r._zod.def,shape:e})}else if(uA(r)){let e=gA(r._zod.def.element,t,n);r=Se(r,{...r._zod.def,element:e})}else if(dA(r)){let e=gA(r._zod.def.innerType,t,n);r=Se(r,{...r._zod.def,innerType:e})}else if(fA(r)){let e=gA(r._zod.def.innerType,t,n);r=Se(r,{...r._zod.def,innerType:e})}}let i=zs.get(e);return i&&zs.add(r,i),n.set(e,r),r}throw Error(`Schema must be an instance of z3.ZodType or z4.$ZodType`)}function _A(e,t=!1){return gA(e,t,new WeakMap)}function vA(e){return e instanceof Error&&(e.constructor.name===`ZodError`||e.constructor.name===`$ZodError`)}function yA(e){return e.replace(/[^a-zA-Z-_0-9]/g,`_`)}var bA=[`*`,`_`,"`"];function xA(e){let t=``;for(let[n,r]of Object.entries(e))t+=`\tclassDef ${n} ${r};\n`;return t}function SA(e,t,n){let{firstNode:r,lastNode:i,nodeColors:a,withStyles:o=!0,curveStyle:s=`linear`,wrapLabelNWords:c=9}=n??{},l=o?`%%{init: {'flowchart': {'curve': '${s}'}}}%%\ngraph TD;\n`:`graph TD;
|
|
109
|
+
`;if(o){let t=`default`,n={[t]:`{0}({1})`};r!==void 0&&(n[r]=`{0}([{1}]):::first`),i!==void 0&&(n[i]=`{0}([{1}]):::last`);for(let[r,i]of Object.entries(e)){let e=i.name.split(`:`).pop()??``,a=bA.some(t=>e.startsWith(t)&&e.endsWith(t))?`<p>${e}</p>`:e;Object.keys(i.metadata??{}).length&&(a+=`<hr/><small><em>${Object.entries(i.metadata??{}).map(([e,t])=>`${e} = ${t}`).join(`
|
|
110
|
+
`)}</em></small>`);let o=(n[r]??n[t]).replace(`{0}`,yA(r)).replace(`{1}`,a);l+=`\t${o}\n`}}let u={};for(let e of t){let t=e.source.split(`:`),n=e.target.split(`:`),r=t.filter((e,t)=>e===n[t]).join(`:`);u[r]||(u[r]=[]),u[r].push(e)}let d=new Set;function f(e){return[...e].sort((e,t)=>e.split(`:`).length-t.split(`:`).length)}function p(e,t){let n=e.length===1&&e[0].source===e[0].target;if(t&&!n){let e=t.split(`:`).pop();if(d.has(t))throw Error(`Found duplicate subgraph '${e}' at '${t} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(t),l+=`\tsubgraph ${e}\n`}let r=f(Object.keys(u).filter(e=>e.startsWith(`${t}:`)&&e!==t&&e.split(`:`).length===t.split(`:`).length+1));for(let e of r)p(u[e],e);for(let t of e){let{source:e,target:n,data:r,conditional:i}=t,a=``;if(r!==void 0){let e=r,t=e.split(` `);t.length>c&&(e=Array.from({length:Math.ceil(t.length/c)},(e,n)=>t.slice(n*c,(n+1)*c).join(` `)).join(` <br> `)),a=i?` -. ${e} .-> `:` -- ${e} --> `}else a=i?` -.-> `:` --> `;l+=`\t${yA(e)}${a}${yA(n)};\n`}t&&!n&&(l+=` end
|
|
111
|
+
`)}p(u[``]??[],``);for(let e in u)!e.includes(`:`)&&e!==``&&p(u[e],e);return o&&(l+=xA(a??{})),l}async function CA(e,t){let n=t?.backgroundColor??`white`,r=t?.imageType??`png`,i=eA(e);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));let a=`https://mermaid.ink/img/${i}?bgColor=${n}&type=${r}`,o=await fetch(a);if(!o.ok)throw Error([`Failed to render the graph using the Mermaid.INK API.`,`Status code: ${o.status}`,`Status text: ${o.statusText}`].join(`
|
|
112
|
+
`));return await o.blob()}var wA=Symbol(`Let zodToJsonSchema decide on which parser to use`),TA={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},EA=e=>typeof e==`string`?{...TA,name:e}:{...TA,...e},DA=e=>{let t=EA(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},OA=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function kA(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?OA(t,e.currentPath):t.join(`/`)}}function AA(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function jA(e,t,n,r,i){e[t]=n,AA(e,t,r,i)}var MA,NA,PA,FA,IA=c((()=>{(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(MA||={}),(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(NA||={}),PA=MA.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),FA=e=>{switch(typeof e){case`undefined`:return PA.undefined;case`string`:return PA.string;case`number`:return Number.isNaN(e)?PA.nan:PA.number;case`boolean`:return PA.boolean;case`function`:return PA.function;case`bigint`:return PA.bigint;case`symbol`:return PA.symbol;case`object`:return Array.isArray(e)?PA.array:e===null?PA.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?PA.promise:typeof Map<`u`&&e instanceof Map?PA.map:typeof Set<`u`&&e instanceof Set?PA.set:typeof Date<`u`&&e instanceof Date?PA.date:PA.object;default:return PA.unknown}}})),W,LA,RA=c((()=>{IA(),W=MA.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`]),LA=class e 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]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,MA.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}},LA.create=e=>new LA(e)})),zA,BA=c((()=>{RA(),IA(),zA=(e,t)=>{let n;switch(e.code){case W.invalid_type:n=e.received===PA.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case W.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,MA.jsonStringifyReplacer)}`;break;case W.unrecognized_keys:n=`Unrecognized key(s) in object: ${MA.joinValues(e.keys,`, `)}`;break;case W.invalid_union:n=`Invalid input`;break;case W.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${MA.joinValues(e.options)}`;break;case W.invalid_enum_value:n=`Invalid enum value. Expected ${MA.joinValues(e.options)}, received '${e.received}'`;break;case W.invalid_arguments:n=`Invalid function arguments`;break;case W.invalid_return_type:n=`Invalid function return type`;break;case W.invalid_date:n=`Invalid date`;break;case W.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:MA.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case W.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`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 W.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case W.custom:n=`Invalid input`;break;case W.invalid_intersection_types:n=`Intersection results could not be merged`;break;case W.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case W.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,MA.assertNever(e)}return{message:n}}}));function VA(){return HA}var HA,UA=c((()=>{BA(),HA=zA}));function G(e,t){let n=VA(),r=WA({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===zA?void 0:zA].filter(e=>!!e)});e.common.issues.push(r)}var WA,GA,KA,qA,JA,YA,XA,ZA,QA,$A=c((()=>{UA(),BA(),WA=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}},GA=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return KA;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return KA;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}},KA=Object.freeze({status:`aborted`}),qA=e=>({status:`dirty`,value:e}),JA=e=>({status:`valid`,value:e}),YA=e=>e.status===`aborted`,XA=e=>e.status===`dirty`,ZA=e=>e.status===`valid`,QA=e=>typeof Promise<`u`&&e instanceof Promise})),ej=c((()=>{})),tj,nj=c((()=>{(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(tj||={})}));function rj(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}function ij(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function aj(e){return RegExp(`^${ij(e)}$`)}function oj(e){let t=`${Nj}T${ij(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function sj(e,t){return!!((t===`v4`||!t)&&Dj.test(e)||(t===`v6`||!t)&&kj.test(e))}function cj(e,t){if(!Sj.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function lj(e,t){return!!((t===`v4`||!t)&&Oj.test(e)||(t===`v6`||!t)&&Aj.test(e))}function uj(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}function dj(e){if(e instanceof Jj){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=uM.create(dj(r))}return new Jj({...e._def,shape:()=>t})}else if(e instanceof qj)return new qj({...e._def,type:dj(e.element)});else if(e instanceof uM)return uM.create(dj(e.unwrap()));else if(e instanceof dM)return dM.create(dj(e.unwrap()));else if(e instanceof $j)return $j.create(e.items.map(e=>dj(e)));else return e}function fj(e,t){let n=FA(e),r=FA(t);if(e===t)return{valid:!0,data:e};if(n===PA.object&&r===PA.object){let n=MA.objectKeys(t),r=MA.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=fj(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===PA.array&&r===PA.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=fj(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===PA.date&&r===PA.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}function pj(e,t){return new oM({values:e,typeName:K.ZodEnum,...rj(t)})}var mj,hj,gj,_j,vj,yj,bj,xj,Sj,Cj,wj,Tj,Ej,Dj,Oj,kj,Aj,jj,Mj,Nj,Pj,Fj,Ij,Lj,Rj,zj,Bj,Vj,Hj,Uj,Wj,Gj,Kj,qj,Jj,Yj,Xj,Zj,Qj,$j,eM,tM,nM,rM,iM,aM,oM,sM,cM,lM,uM,dM,fM,pM,mM,hM,gM,_M,K,vM,yM,bM,xM=c((()=>{RA(),UA(),nj(),$A(),IA(),mj=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},hj=(e,t)=>{if(ZA(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new LA(e.common.issues);return this._error=t,this._error}}},gj=class{get description(){return this._def.description}_getType(e){return FA(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:FA(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new GA,ctx:{common:e.parent.common,data:e.data,parsedType:FA(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(QA(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:FA(e)},r=this._parseSync({data:e,path:n.path,parent:n});return hj(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:FA(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ZA(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>ZA(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:FA(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(QA(r)?r:Promise.resolve(r));return hj(n,i)}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:W.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new lM({schema:this,typeName:K.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 uM.create(this,this._def)}nullable(){return dM.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return qj.create(this)}promise(){return cM.create(this,this._def)}or(e){return Yj.create([this,e],this._def)}and(e){return Qj.create(this,e,this._def)}transform(e){return new lM({...rj(this._def),schema:this,typeName:K.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new fM({...rj(this._def),innerType:this,defaultValue:t,typeName:K.ZodDefault})}brand(){return new hM({typeName:K.ZodBranded,type:this,...rj(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new pM({...rj(this._def),innerType:this,catchValue:t,typeName:K.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return gM.create(this,e)}readonly(){return _M.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},_j=/^c[^\s-]{8,}$/i,vj=/^[0-9a-z]+$/,yj=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bj=/^[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,xj=/^[a-z0-9_-]{21}$/i,Sj=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Cj=/^[-+]?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)?)??$/,wj=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Tj=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,Dj=/^(?:(?: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])$/,Oj=/^(?:(?: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])$/,kj=/^(([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]))$/,Aj=/^(([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])$/,jj=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Mj=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Nj=`((\\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])))`,Pj=RegExp(`^${Nj}$`),Fj=class e extends gj{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==PA.string){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:PA.string,received:t.parsedType}),KA}let t=new GA,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?G(n,{code:W.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&G(n,{code:W.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)wj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`email`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)Ej||=new RegExp(Tj,`u`),Ej.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`emoji`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)bj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`uuid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)xj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`nanoid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)_j.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`cuid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)vj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`cuid2`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)yj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`ulid`,code:W.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),G(n,{validation:`url`,code:W.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`regex`,code:W.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?oj(r).test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Pj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?aj(r).test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{code:W.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Cj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`duration`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?sj(e.data,r.version)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`ip`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?cj(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`jwt`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?lj(e.data,r.version)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`cidr`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?jj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`base64`,code:W.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Mj.test(e.data)||(n=this._getOrReturnCtx(e,n),G(n,{validation:`base64url`,code:W.invalid_string,message:r.message}),t.dirty()):MA.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:W.invalid_string,...tj.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...tj.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...tj.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...tj.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...tj.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...tj.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...tj.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...tj.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...tj.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...tj.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...tj.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...tj.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...tj.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...tj.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...tj.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...tj.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...tj.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...tj.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...tj.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...tj.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...tj.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...tj.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...tj.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...tj.errToObj(t)})}nonempty(e){return this.min(1,tj.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}},Fj.create=e=>new Fj({checks:[],typeName:K.ZodString,coerce:e?.coerce??!1,...rj(e)}),Ij=class e extends gj{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==PA.number){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:PA.number,received:t.parsedType}),KA}let t,n=new GA;for(let r of this._def.checks)r.kind===`int`?MA.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),G(t,{code:W.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?uj(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),G(t,{code:W.not_finite,message:r.message}),n.dirty()):MA.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,tj.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,tj.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,tj.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,tj.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:tj.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:tj.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:tj.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:tj.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:tj.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:tj.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:tj.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:tj.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:tj.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:tj.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&MA.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}},Ij.create=e=>new Ij({checks:[],typeName:K.ZodNumber,coerce:e?.coerce||!1,...rj(e)}),Lj=class e extends gj{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==PA.bigint)return this._getInvalidInput(e);let t,n=new GA;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),G(t,{code:W.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):MA.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:PA.bigint,received:t.parsedType}),KA}gte(e,t){return this.setLimit(`min`,e,!0,tj.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,tj.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,tj.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,tj.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:tj.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:tj.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:tj.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:tj.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:tj.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:tj.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}},Lj.create=e=>new Lj({checks:[],typeName:K.ZodBigInt,coerce:e?.coerce??!1,...rj(e)}),Rj=class extends gj{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==PA.boolean){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:PA.boolean,received:t.parsedType}),KA}return JA(e.data)}},Rj.create=e=>new Rj({typeName:K.ZodBoolean,coerce:e?.coerce||!1,...rj(e)}),zj=class e extends gj{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==PA.date){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:PA.date,received:t.parsedType}),KA}if(Number.isNaN(e.data.getTime()))return G(this._getOrReturnCtx(e),{code:W.invalid_date}),KA;let t=new GA,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),G(n,{code:W.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):MA.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:tj.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:tj.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}},zj.create=e=>new zj({checks:[],coerce:e?.coerce||!1,typeName:K.ZodDate,...rj(e)}),Bj=class extends gj{_parse(e){if(this._getType(e)!==PA.symbol){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:PA.symbol,received:t.parsedType}),KA}return JA(e.data)}},Bj.create=e=>new Bj({typeName:K.ZodSymbol,...rj(e)}),Vj=class extends gj{_parse(e){if(this._getType(e)!==PA.undefined){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:PA.undefined,received:t.parsedType}),KA}return JA(e.data)}},Vj.create=e=>new Vj({typeName:K.ZodUndefined,...rj(e)}),Hj=class extends gj{_parse(e){if(this._getType(e)!==PA.null){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:PA.null,received:t.parsedType}),KA}return JA(e.data)}},Hj.create=e=>new Hj({typeName:K.ZodNull,...rj(e)}),Uj=class extends gj{constructor(){super(...arguments),this._any=!0}_parse(e){return JA(e.data)}},Uj.create=e=>new Uj({typeName:K.ZodAny,...rj(e)}),Wj=class extends gj{constructor(){super(...arguments),this._unknown=!0}_parse(e){return JA(e.data)}},Wj.create=e=>new Wj({typeName:K.ZodUnknown,...rj(e)}),Gj=class extends gj{_parse(e){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:PA.never,received:t.parsedType}),KA}},Gj.create=e=>new Gj({typeName:K.ZodNever,...rj(e)}),Kj=class extends gj{_parse(e){if(this._getType(e)!==PA.undefined){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:PA.void,received:t.parsedType}),KA}return JA(e.data)}},Kj.create=e=>new Kj({typeName:K.ZodVoid,...rj(e)}),qj=class e extends gj{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==PA.array)return G(t,{code:W.invalid_type,expected:PA.array,received:t.parsedType}),KA;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(G(t,{code:e?W.too_big:W.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(G(t,{code:W.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(G(t,{code:W.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new mj(t,e,t.path,n)))).then(e=>GA.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new mj(t,e,t.path,n)));return GA.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:tj.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:tj.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:tj.toString(n)}})}nonempty(e){return this.min(1,e)}},qj.create=(e,t)=>new qj({type:e,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...rj(t)}),Jj=class e extends gj{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=MA.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==PA.object){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:PA.object,received:t.parsedType}),KA}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Gj&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new mj(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Gj){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(G(n,{code:W.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new mj(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>GA.mergeObjectSync(t,e)):GA.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return tj.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:tj.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:K.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of MA.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of MA.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return dj(this)}partial(t){let n={};for(let e of MA.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of MA.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof uM;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return pj(MA.objectKeys(this.shape))}},Jj.create=(e,t)=>new Jj({shape:()=>e,unknownKeys:`strip`,catchall:Gj.create(),typeName:K.ZodObject,...rj(t)}),Jj.strictCreate=(e,t)=>new Jj({shape:()=>e,unknownKeys:`strict`,catchall:Gj.create(),typeName:K.ZodObject,...rj(t)}),Jj.lazycreate=(e,t)=>new Jj({shape:e,unknownKeys:`strip`,catchall:Gj.create(),typeName:K.ZodObject,...rj(t)}),Yj=class extends gj{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new LA(e.ctx.common.issues));return G(t,{code:W.invalid_union,unionErrors:n}),KA}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new LA(e));return G(t,{code:W.invalid_union,unionErrors:i}),KA}}get options(){return this._def.options}},Yj.create=(e,t)=>new Yj({options:e,typeName:K.ZodUnion,...rj(t)}),Xj=e=>e instanceof iM?Xj(e.schema):e instanceof lM?Xj(e.innerType()):e instanceof aM?[e.value]:e instanceof oM?e.options:e instanceof sM?MA.objectValues(e.enum):e instanceof fM?Xj(e._def.innerType):e instanceof Vj?[void 0]:e instanceof Hj?[null]:e instanceof uM?[void 0,...Xj(e.unwrap())]:e instanceof dM?[null,...Xj(e.unwrap())]:e instanceof hM||e instanceof _M?Xj(e.unwrap()):e instanceof pM?Xj(e._def.innerType):[],Zj=class e extends gj{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==PA.object)return G(t,{code:W.invalid_type,expected:PA.object,received:t.parsedType}),KA;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(G(t,{code:W.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),KA)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=Xj(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:K.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...rj(r)})}},Qj=class extends gj{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(YA(e)||YA(r))return KA;let i=fj(e.value,r.value);return i.valid?((XA(e)||XA(r))&&t.dirty(),{status:t.value,value:i.data}):(G(n,{code:W.invalid_intersection_types}),KA)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}},Qj.create=(e,t,n)=>new Qj({left:e,right:t,typeName:K.ZodIntersection,...rj(n)}),$j=class e extends gj{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==PA.array)return G(n,{code:W.invalid_type,expected:PA.array,received:n.parsedType}),KA;if(n.data.length<this._def.items.length)return G(n,{code:W.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),KA;!this._def.rest&&n.data.length>this._def.items.length&&(G(n,{code:W.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new mj(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>GA.mergeArray(t,e)):GA.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}},$j.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new $j({items:e,typeName:K.ZodTuple,rest:null,...rj(t)})},eM=class e extends gj{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==PA.object)return G(n,{code:W.invalid_type,expected:PA.object,received:n.parsedType}),KA;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new mj(n,e,n.path,e)),value:a._parse(new mj(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?GA.mergeObjectAsync(t,r):GA.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof gj?new e({keyType:t,valueType:n,typeName:K.ZodRecord,...rj(r)}):new e({keyType:Fj.create(),valueType:t,typeName:K.ZodRecord,...rj(n)})}},tM=class extends gj{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==PA.map)return G(n,{code:W.invalid_type,expected:PA.map,received:n.parsedType}),KA;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new mj(n,e,n.path,[a,`key`])),value:i._parse(new mj(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return KA;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return KA;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}},tM.create=(e,t,n)=>new tM({valueType:t,keyType:e,typeName:K.ZodMap,...rj(n)}),nM=class e extends gj{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==PA.set)return G(n,{code:W.invalid_type,expected:PA.set,received:n.parsedType}),KA;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(G(n,{code:W.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(G(n,{code:W.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return KA;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new mj(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:tj.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:tj.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}},nM.create=(e,t)=>new nM({valueType:e,minSize:null,maxSize:null,typeName:K.ZodSet,...rj(t)}),rM=class e extends gj{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==PA.function)return G(t,{code:W.invalid_type,expected:PA.function,received:t.parsedType}),KA;function n(e,n){return WA({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,VA(),zA].filter(e=>!!e),issueData:{code:W.invalid_arguments,argumentsError:n}})}function r(e,n){return WA({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,VA(),zA].filter(e=>!!e),issueData:{code:W.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof cM){let e=this;return JA(async function(...t){let o=new LA([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return JA(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new LA([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new LA([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:$j.create(t).rest(Wj.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||$j.create([]).rest(Wj.create()),returns:n||Wj.create(),typeName:K.ZodFunction,...rj(r)})}},iM=class extends gj{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}},iM.create=(e,t)=>new iM({getter:e,typeName:K.ZodLazy,...rj(t)}),aM=class extends gj{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return G(t,{received:t.data,code:W.invalid_literal,expected:this._def.value}),KA}return{status:`valid`,value:e.data}}get value(){return this._def.value}},aM.create=(e,t)=>new aM({value:e,typeName:K.ZodLiteral,...rj(t)}),oM=class e extends gj{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return G(t,{expected:MA.joinValues(n),received:t.parsedType,code:W.invalid_type}),KA}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return G(t,{received:t.data,code:W.invalid_enum_value,options:n}),KA}return JA(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}},oM.create=pj,sM=class extends gj{_parse(e){let t=MA.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==PA.string&&n.parsedType!==PA.number){let e=MA.objectValues(t);return G(n,{expected:MA.joinValues(e),received:n.parsedType,code:W.invalid_type}),KA}if(this._cache||=new Set(MA.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=MA.objectValues(t);return G(n,{received:n.data,code:W.invalid_enum_value,options:e}),KA}return JA(e.data)}get enum(){return this._def.values}},sM.create=(e,t)=>new sM({values:e,typeName:K.ZodNativeEnum,...rj(t)}),cM=class extends gj{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==PA.promise&&t.common.async===!1?(G(t,{code:W.invalid_type,expected:PA.promise,received:t.parsedType}),KA):JA((t.parsedType===PA.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}},cM.create=(e,t)=>new cM({type:e,typeName:K.ZodPromise,...rj(t)}),lM=class extends gj{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{G(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return KA;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?KA:r.status===`dirty`||t.value===`dirty`?qA(r.value):r});{if(t.value===`aborted`)return KA;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?KA:r.status===`dirty`||t.value===`dirty`?qA(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?KA:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?KA:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ZA(e))return KA;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>ZA(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):KA);MA.assertNever(r)}},lM.create=(e,t,n)=>new lM({schema:e,typeName:K.ZodEffects,effect:t,...rj(n)}),lM.createWithPreprocess=(e,t,n)=>new lM({schema:t,effect:{type:`preprocess`,transform:e},typeName:K.ZodEffects,...rj(n)}),uM=class extends gj{_parse(e){return this._getType(e)===PA.undefined?JA(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}},uM.create=(e,t)=>new uM({innerType:e,typeName:K.ZodOptional,...rj(t)}),dM=class extends gj{_parse(e){return this._getType(e)===PA.null?JA(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}},dM.create=(e,t)=>new dM({innerType:e,typeName:K.ZodNullable,...rj(t)}),fM=class extends gj{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===PA.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}},fM.create=(e,t)=>new fM({innerType:e,typeName:K.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...rj(t)}),pM=class extends gj{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return QA(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new LA(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new LA(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}},pM.create=(e,t)=>new pM({innerType:e,typeName:K.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...rj(t)}),mM=class extends gj{_parse(e){if(this._getType(e)!==PA.nan){let t=this._getOrReturnCtx(e);return G(t,{code:W.invalid_type,expected:PA.nan,received:t.parsedType}),KA}return{status:`valid`,value:e.data}}},mM.create=e=>new mM({typeName:K.ZodNaN,...rj(e)}),hM=class extends gj{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},gM=class e extends gj{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?KA:e.status===`dirty`?(t.dirty(),qA(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?KA:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:K.ZodPipeline})}},_M=class extends gj{_parse(e){let t=this._def.innerType._parse(e),n=e=>(ZA(e)&&(e.value=Object.freeze(e.value)),e);return QA(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}},_M.create=(e,t)=>new _M({innerType:e,typeName:K.ZodReadonly,...rj(t)}),Jj.lazycreate,(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`})(K||={}),vM=Fj.create,Ij.create,mM.create,Lj.create,Rj.create,zj.create,Bj.create,Vj.create,Hj.create,yM=Uj.create,Wj.create,Gj.create,Kj.create,qj.create,bM=Jj.create,Jj.strictCreate,Yj.create,Zj.create,Qj.create,$j.create,eM.create,tM.create,nM.create,rM.create,iM.create,aM.create,oM.create,sM.create,cM.create,lM.create,uM.create,dM.create,lM.createWithPreprocess,gM.create})),SM=c((()=>{UA(),$A(),ej(),IA(),xM(),RA()})),CM=c((()=>{SM(),SM()}));CM();function wM(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==K.ZodAny&&(n.items=mN(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&jA(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&jA(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(jA(n,`minItems`,e.exactLength.value,e.exactLength.message,t),jA(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function TM(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?jA(n,`minimum`,r.value,r.message,t):jA(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),jA(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?jA(n,`maximum`,r.value,r.message,t):jA(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),jA(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:jA(n,`multipleOf`,r.value,r.message,t);break}return n}function EM(){return{type:`boolean`}}function DM(e,t){return mN(e.type._def,t)}var OM=(e,t)=>mN(e.innerType._def,t);function kM(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(n=>kM(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return AM(e,t)}}var AM=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:jA(n,`minimum`,r.value,r.message,t);break;case`max`:jA(n,`maximum`,r.value,r.message,t);break}return n};function jM(e,t){return{...mN(e.innerType._def,t),default:e.defaultValue()}}function MM(e,t){return t.effectStrategy===`input`?mN(e.schema._def,t):kA(t)}function NM(e){return{type:`string`,enum:Array.from(e.values)}}var PM=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function FM(e,t){let n=[mN(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),mN(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(PM(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function IM(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var LM=void 0,RM={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(LM===void 0&&(LM=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),LM),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function zM(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:jA(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:jA(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:UM(n,`email`,r.message,t);break;case`format:idn-email`:UM(n,`idn-email`,r.message,t);break;case`pattern:zod`:WM(n,RM.email,r.message,t);break}break;case`url`:UM(n,`uri`,r.message,t);break;case`uuid`:UM(n,`uuid`,r.message,t);break;case`regex`:WM(n,r.regex,r.message,t);break;case`cuid`:WM(n,RM.cuid,r.message,t);break;case`cuid2`:WM(n,RM.cuid2,r.message,t);break;case`startsWith`:WM(n,RegExp(`^${BM(r.value,t)}`),r.message,t);break;case`endsWith`:WM(n,RegExp(`${BM(r.value,t)}$`),r.message,t);break;case`datetime`:UM(n,`date-time`,r.message,t);break;case`date`:UM(n,`date`,r.message,t);break;case`time`:UM(n,`time`,r.message,t);break;case`duration`:UM(n,`duration`,r.message,t);break;case`length`:jA(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),jA(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:WM(n,RegExp(BM(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&UM(n,`ipv4`,r.message,t),r.version!==`v4`&&UM(n,`ipv6`,r.message,t);break;case`base64url`:WM(n,RM.base64url,r.message,t);break;case`jwt`:WM(n,RM.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&WM(n,RM.ipv4Cidr,r.message,t),r.version!==`v4`&&WM(n,RM.ipv6Cidr,r.message,t);break;case`emoji`:WM(n,RM.emoji(),r.message,t);break;case`ulid`:WM(n,RM.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:UM(n,`binary`,r.message,t);break;case`contentEncoding:base64`:jA(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:WM(n,RM.base64,r.message,t);break}break;case`nanoid`:WM(n,RM.nanoid,r.message,t);break;case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return n}function BM(e,t){return t.patternStrategy===`escape`?HM(e):e}var VM=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function HM(e){let t=``;for(let n=0;n<e.length;n++)VM.has(e[n])||(t+=`\\`),t+=e[n];return t}function UM(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):jA(e,`format`,t,n,r)}function WM(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:GM(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):jA(e,`pattern`,GM(t,r),n,r)}function GM(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
|
|
113
113
|
]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
|
|
114
|
-
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}wM();function qM(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===K.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:hN(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??AA(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:hN(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===K.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=BM(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===K.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===K.ZodBranded&&e.keyType._def.type._def.typeName===K.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=OM(e.keyType._def,t);return{...n,propertyNames:i}}return n}function JM(e,t){return t.mapStrategy===`record`?qM(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[hN(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||AA(t),hN(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||AA(t)],minItems:2,maxItems:2}}}function YM(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function XM(e){return e.target===`openAi`?void 0:{not:AA({...e,currentPath:[...e.currentPath,`not`]})}}function ZM(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var QM={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function $M(e,t){if(t.target===`openApi3`)return eN(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in QM&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=QM[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:return t._def.value===null?[...e,`null`]:e;default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return eN(e,t)}var eN=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>hN(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function tN(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:QM[e.innerType._def.typeName],nullable:!0}:{type:[QM[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=hN(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=hN(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function nN(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,jA(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?MA(n,`minimum`,r.value,r.message,t):MA(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),MA(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?MA(n,`maximum`,r.value,r.message,t):MA(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),MA(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:MA(n,`multipleOf`,r.value,r.message,t);break}return n}function rN(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=aN(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=hN(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=iN(e,t);return o!==void 0&&(r.additionalProperties=o),r}function iN(e,t){if(e.catchall._def.typeName!==`ZodNever`)return hN(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function aN(e){try{return e.isOptional()}catch{return!0}}var oN=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return hN(e.innerType._def,t);let n=hN(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:AA(t)},n]}:AA(t)},sN=(e,t)=>{if(t.pipeStrategy===`input`)return hN(e.in._def,t);if(t.pipeStrategy===`output`)return hN(e.out._def,t);let n=hN(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,hN(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function cN(e,t){return hN(e.type._def,t)}function lN(e,t){let n={type:`array`,uniqueItems:!0,items:hN(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&MA(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&MA(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function uN(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>hN(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:hN(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>hN(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function dN(e){return{not:AA(e)}}function fN(e){return AA(e)}var pN=(e,t)=>hN(e.innerType._def,t);wM();var mN=(e,t,n)=>{switch(t){case K.ZodString:return BM(e,n);case K.ZodNumber:return nN(e,n);case K.ZodObject:return rN(e,n);case K.ZodBigInt:return EM(e,n);case K.ZodBoolean:return DM();case K.ZodDate:return AM(e,n);case K.ZodUndefined:return dN(n);case K.ZodNull:return ZM(n);case K.ZodArray:return TM(e,n);case K.ZodUnion:case K.ZodDiscriminatedUnion:return $M(e,n);case K.ZodIntersection:return IM(e,n);case K.ZodTuple:return uN(e,n);case K.ZodRecord:return qM(e,n);case K.ZodLiteral:return LM(e,n);case K.ZodEnum:return PM(e);case K.ZodNativeEnum:return YM(e);case K.ZodNullable:return tN(e,n);case K.ZodOptional:return oN(e,n);case K.ZodMap:return JM(e,n);case K.ZodSet:return lN(e,n);case K.ZodLazy:return()=>e.getter()._def;case K.ZodPromise:return cN(e,n);case K.ZodNaN:case K.ZodNever:return XM(n);case K.ZodEffects:return NM(e,n);case K.ZodAny:return AA(n);case K.ZodUnknown:return fN(n);case K.ZodDefault:return MM(e,n);case K.ZodBranded:return OM(e,n);case K.ZodReadonly:return pN(e,n);case K.ZodCatch:return kM(e,n);case K.ZodPipeline:return sN(e,n);case K.ZodFunction:case K.ZodVoid:case K.ZodSymbol:return;default:return(e=>void 0)(t)}};function hN(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==TA)return i}if(r&&!n){let e=gN(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=mN(e,e.typeName,t),o=typeof a==`function`?hN(a(),t):a;if(o&&_N(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var gN=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:kA(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),AA(t)):t.$refStrategy===`seen`?AA(t):void 0}},_N=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),vN=(e,t)=>{let n=OA(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:hN(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??AA(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=hN(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??AA(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function yN(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`validate`in e[`~standard`]}function bN(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`jsonSchema`in e[`~standard`]}function xN(e){return yN(e)&&bN(e)}function SN(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!SN(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!SN(e[r],t[r]))return!1;return!0}return e===t}function CN(e){return encodeURI(wN(e))}function wN(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var TN={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},EN={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},DN={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},ON=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`);function kN(e,t=Object.create(null),n=ON,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:kN(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(DN[i])continue;let a=`${r}/${CN(i)}`,o=e[i];if(Array.isArray(o)){if(TN[i]){let e=o.length;for(let r=0;r<e;r++)kN(o[r],t,n,`${a}/${r}`)}}else if(EN[i])for(let e in o)kN(o[e],t,n,`${a}/${CN(e)}`);else kN(o,t,n,a)}return t}var AN=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,jN=[0,31,28,31,30,31,30,31,31,30,31,30,31],MN=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,NN=/^(?=.{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,PN=/^(?:[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,FN=/^(?:(?:[^\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,IN=/^(?:(?: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,LN=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,RN=/^(?:\/(?:[^~/]|~0|~1)*)*$/,zN=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,BN=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,VN=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},HN=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,UN=/^((([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,WN=e=>e.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));function GN(e){return e.test.bind(e)}var KN={date:JN,time:YN.bind(void 0,!1),"date-time":ZN,duration:WN,uri:eP,"uri-reference":GN(PN),"uri-template":GN(FN),url:GN(IN),email:VN,hostname:GN(NN),ipv4:GN(HN),ipv6:GN(UN),regex:nP,uuid:GN(LN),"json-pointer":GN(RN),"json-pointer-uri-fragment":GN(zN),"relative-json-pointer":GN(BN)};function qN(e){return e%4==0&&(e%100!=0||e%400==0)}function JN(e){let t=e.match(AN);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&qN(n)?29:jN[r])}function YN(e,t){let n=t.match(MN);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}var XN=/t|\s/i;function ZN(e){let t=e.split(XN);return t.length==2&&JN(t[0])&&YN(!0,t[1])}var QN=/\/|:/,$N=/^(?:[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;function eP(e){return QN.test(e)&&$N.test(e)}var tP=/[^\\]\\Z/;function nP(e){if(tP.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function rP(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function iP(e,t,n=`2019-09`,r=kN(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:ee,else:C,format:te,properties:ne,patternProperties:w,additionalProperties:re,unevaluatedProperties:ie,minProperties:T,maxProperties:ae,propertyNames:E,dependentRequired:oe,dependentSchemas:se,dependencies:ce,prefixItems:D,items:le,additionalItems:ue,unevaluatedItems:O,contains:de,minContains:fe,maxContains:pe,minItems:me,maxItems:he,uniqueItems:ge,minimum:_e,maximum:ve,exclusiveMinimum:ye,exclusiveMaximum:be,multipleOf:xe,minLength:Se,maxLength:k,pattern:Ce,__absolute_ref__:A,__absolute_recursive_ref__:we}=t,j=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[we]:a,u=`${s}/$recursiveRef`,d=iP(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||j.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[A||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw A&&A!==d&&(e+=` Absolute URI "${A}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
|
|
115
|
-
- `)}`,Error(e)}let l=`${s}/$ref`,u=iP(e,t,n,r,i,a,o,l,c);if(u.valid||j.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:j.length===0,errors:j}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||j.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&j.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&j.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?SN(e,h)||j.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&j.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>SN(e,t))||j.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||j.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){let t=`${s}/not`;iP(e,v,n,r,i,a,o,t).valid&&j.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Te=[];if(y!==void 0){let t=`${s}/anyOf`,l=j.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=iP(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);j.push(...f.errors),u||=f.valid,f.valid&&Te.push(d)}u?j.length=l:j.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${s}/allOf`,l=j.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=iP(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);j.push(...f.errors),u&&=f.valid,f.valid&&Te.push(d)}u?j.length=l:j.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(x!==void 0){let t=`${s}/oneOf`,l=j.length,u=x.filter((s,l)=>{let u=Object.create(c),d=iP(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return j.push(...d.errors),d.valid&&Te.push(u),d.valid}).length;u===1?j.length=l:j.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Te),S!==void 0){let t=`${s}/if`;if(iP(e,S,n,r,i,a,o,t,c).valid){if(ee!==void 0){let l=iP(e,ee,n,r,i,a,o,`${s}/then`,c);l.valid||j.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(C!==void 0){let l=iP(e,C,n,r,i,a,o,`${s}/else`,c);l.valid||j.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||j.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(T!==void 0&&t.length<T&&j.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${T} properties.`}),ae!==void 0&&t.length>ae&&j.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${ae} properties.`}),E!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${CN(s)}`,c=iP(s,E,n,r,i,a,e,t);c.valid||j.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(oe!==void 0){let t=`${s}/dependantRequired`;for(let n in oe)if(n in e){let r=oe[n];for(let i of r)i in e||j.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(se!==void 0)for(let t in se){let l=`${s}/dependentSchemas`;if(t in e){let s=iP(e,se[t],n,r,i,a,o,`${l}/${CN(t)}`,c);s.valid||j.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(ce!==void 0){let t=`${s}/dependencies`;for(let s in ce)if(s in e){let c=ce[s];if(Array.isArray(c))for(let n of c)n in e||j.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=iP(e,c,n,r,i,a,o,`${t}/${CN(s)}`);l.valid||j.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(ne!==void 0){let t=`${s}/properties`;for(let s in ne){if(!(s in e))continue;let d=`${o}/${CN(s)}`,f=iP(e[s],ne[s],n,r,i,a,d,`${t}/${CN(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,j.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&w!==void 0){let t=`${s}/patternProperties`;for(let s in w){let d=new RegExp(s,`u`),f=w[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${CN(p)}`,h=iP(e[p],f,n,r,i,a,m,`${t}/${CN(s)}`);h.valid?c[p]=l[p]=!0:(u=i,j.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&re!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${CN(s)}`,f=iP(e[s],re,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,j.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&ie!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${CN(s)}`,u=iP(e[s],ie,n,r,i,a,l,t);u.valid?c[s]=!0:j.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){he!==void 0&&e.length>he&&j.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${he}).`}),me!==void 0&&e.length<me&&j.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${me}).`});let t=e.length,l=0,u=!1;if(D!==void 0){let d=`${s}/prefixItems`,f=Math.min(D.length,t);for(;l<f;l++){let t=iP(e[l],D[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,j.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(le!==void 0){let d=`${s}/items`;if(Array.isArray(le)){let s=Math.min(le.length,t);for(;l<s;l++){let t=iP(e[l],le[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,j.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=iP(e[l],le,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,j.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ue!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=iP(e[l],ue,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,j.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(de!==void 0)if(t===0&&fe===void 0)j.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(fe!==void 0&&t<fe)j.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${fe}).`});else{let l=`${s}/contains`,u=j.length,d=0;for(let s=0;s<t;s++){let t=iP(e[s],de,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):j.push(...t.errors)}d>=(fe||0)&&(j.length=u),fe===void 0&&pe===void 0&&d===0?j.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):fe!==void 0&&d<fe?j.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${fe} items matching schema. Only ${d} items were found.`}):pe!==void 0&&d>pe&&j.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${pe} items matching schema. ${d} items were found.`})}if(!u&&O!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=iP(e[l],O,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||j.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(ge)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&SN(r,t))&&(j.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(_e!==void 0&&(ye===!0&&e<=_e||e<_e)&&j.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${ye?`or equal to `:``} ${_e}.`}),ve!==void 0&&(be===!0&&e>=ve||e>ve)&&j.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${be?`or equal to `:``} ${ve}.`})):(_e!==void 0&&e<_e&&j.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${_e}.`}),ve!==void 0&&e>ve&&j.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${ve}.`}),ye!==void 0&&e<=ye&&j.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${ye}.`}),be!==void 0&&e>=be&&j.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${be}.`})),xe!==void 0){let t=e%xe;Math.abs(0-t)>=1.1920929e-7&&Math.abs(xe-t)>=1.1920929e-7&&j.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${xe}.`})}}else if(u===`string`){let t=Se===void 0&&k===void 0?0:rP(e);Se!==void 0&&t<Se&&j.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${Se}).`}),k!==void 0&&t>k&&j.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${k}).`}),Ce!==void 0&&!new RegExp(Ce,`u`).test(e)&&j.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),te!==void 0&&KN[te]&&!KN[te](e)&&j.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${te}".`})}return{valid:j.length===0,errors:j}}Du();var aP=new WeakMap;function oP(e,t){let n=!t&&typeof e==`object`&&!!e;if(n){let t=aP.get(e);if(t)return t}let r;if(bN(e)&&!nA(e))r=e[`~standard`].jsonSchema.input({target:`draft-07`});else if(nA(e)){let n=vA(e,!0);r=uA(n)?Nl(mA(n,!0),t):Nl(e,t)}else r=rA(e)?vN(e):e;return n&&typeof r==`object`&&r&&aP.set(e,r),r}function sP(e){if(!e||typeof e!=`object`||Object.keys(e).length===0||Array.isArray(e))return!1;if(`type`in e)return typeof e.type==`string`?e.type===`string`:Array.isArray(e.type)?e.type.every(e=>e===`string`):!1;if(`enum`in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(e=>typeof e==`string`);if(`const`in e)return typeof e.const==`string`;if(`allOf`in e&&Array.isArray(e.allOf))return e.allOf.some(e=>sP(e));if(`anyOf`in e&&Array.isArray(e.anyOf)||`oneOf`in e&&Array.isArray(e.oneOf)){let t=`anyOf`in e?e.anyOf:e.oneOf;return t.length>0&&t.every(e=>sP(e))}if(`not`in e)return!1;if(`$ref`in e&&typeof e.$ref==`string`){let t=e.$ref,n=kN(e);return n[t]?sP(n[t]):!1}return!1}function cP(e,t){if(e!==void 0&&!FS(e))return e;if($k(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}function lP(e){return $k(e.data)?{type:`runnable`,data:{id:e.data.lc_id,name:e.data.getName()}}:{type:`schema`,data:{...oP(e.data.schema),title:e.data.name}}}var uP=class e{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((t,n)=>{e[t.id]=FS(t.id)?n:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...lP(t)})),edges:this.edges.map(t=>{let n={source:e[t.source],target:e[t.target]};return t.data!==void 0&&(n.data=t.data),t.conditional!==void 0&&(n.conditional=t.conditional),n})}}addNode(e,t,n){if(t!==void 0&&this.nodes[t]!==void 0)throw Error(`Node with id ${t} already exists`);let r=t??Ane(),i={id:r,data:e,name:cP(t,e),metadata:n};return this.nodes[r]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,n,r){if(this.nodes[e.id]===void 0)throw Error(`Source node ${e.id} not in graph`);if(this.nodes[t.id]===void 0)throw Error(`Target node ${t.id} not in graph`);let i={source:e.id,target:t.id,data:n,conditional:r};return this.edges.push(i),i}firstNode(){return dP(this)}lastNode(){return fP(this)}extend(e,t=``){let n=t;Object.values(e.nodes).map(e=>e.id).every(FS)&&(n=``);let r=e=>n?`${n}:${e}`:e;Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[r(e)]={...t,id:r(e)}});let i=e.edges.map(e=>({...e,source:r(e.source),target:r(e.target)}));this.edges=[...this.edges,...i];let a=e.firstNode(),o=e.lastNode();return[a?{id:r(a.id),data:a.data}:void 0,o?{id:r(o.id),data:o.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&dP(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&fP(this,[e.id])&&this.removeNode(e)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(e=>[e.id,e.name])),n=new Map;Object.values(t).forEach(e=>{n.set(e,(n.get(e)||0)+1)});let r=e=>{let r=t[e];return FS(e)&&n.get(r)===1?r:e};return new e({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){let{withStyles:t,curveStyle:n,nodeColors:r={default:`fill:#f2f0ff,line-height:1.2`,first:`fill-opacity:0`,last:`fill:#bfb6fc`},wrapLabelNWords:i}=e??{},a=this.reid(),o=a.firstNode(),s=a.lastNode();return CA(a.nodes,a.edges,{firstNode:o?.id,lastNode:s?.id,withStyles:t,curveStyle:n,nodeColors:r,wrapLabelNWords:i})}async drawMermaidPng(e){return wA(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}};function dP(e,t=[]){let n=new Set(e.edges.filter(e=>!t.includes(e.source)).map(e=>e.target)),r=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!n.has(i.id)&&r.push(i);return r.length===1?r[0]:void 0}function fP(e,t=[]){let n=new Set(e.edges.filter(e=>!t.includes(e.target)).map(e=>e.source)),r=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!n.has(i.id)&&r.push(i);return r.length===1?r[0]:void 0}function pP(e){let t=new TextEncoder,n=new ReadableStream({async start(n){for await(let r of e)n.enqueue(t.encode(`event: data\ndata: ${JSON.stringify(r)}\n\n`));n.enqueue(t.encode(`event: end
|
|
114
|
+
]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}CM();function KM(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===K.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:mN(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??kA(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:mN(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===K.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=zM(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===K.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===K.ZodBranded&&e.keyType._def.type._def.typeName===K.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=DM(e.keyType._def,t);return{...n,propertyNames:i}}return n}function qM(e,t){return t.mapStrategy===`record`?KM(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[mN(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||kA(t),mN(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||kA(t)],minItems:2,maxItems:2}}}function JM(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function YM(e){return e.target===`openAi`?void 0:{not:kA({...e,currentPath:[...e.currentPath,`not`]})}}function XM(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var ZM={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function QM(e,t){if(t.target===`openApi3`)return $M(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in ZM&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=ZM[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:return t._def.value===null?[...e,`null`]:e;default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return $M(e,t)}var $M=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>mN(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function eN(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:ZM[e.innerType._def.typeName],nullable:!0}:{type:[ZM[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=mN(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=mN(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function tN(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,AA(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?jA(n,`minimum`,r.value,r.message,t):jA(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),jA(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?jA(n,`maximum`,r.value,r.message,t):jA(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),jA(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:jA(n,`multipleOf`,r.value,r.message,t);break}return n}function nN(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=iN(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=mN(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=rN(e,t);return o!==void 0&&(r.additionalProperties=o),r}function rN(e,t){if(e.catchall._def.typeName!==`ZodNever`)return mN(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function iN(e){try{return e.isOptional()}catch{return!0}}var aN=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return mN(e.innerType._def,t);let n=mN(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:kA(t)},n]}:kA(t)},oN=(e,t)=>{if(t.pipeStrategy===`input`)return mN(e.in._def,t);if(t.pipeStrategy===`output`)return mN(e.out._def,t);let n=mN(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,mN(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function sN(e,t){return mN(e.type._def,t)}function cN(e,t){let n={type:`array`,uniqueItems:!0,items:mN(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&jA(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&jA(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function lN(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>mN(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:mN(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>mN(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function uN(e){return{not:kA(e)}}function dN(e){return kA(e)}var fN=(e,t)=>mN(e.innerType._def,t);CM();var pN=(e,t,n)=>{switch(t){case K.ZodString:return zM(e,n);case K.ZodNumber:return tN(e,n);case K.ZodObject:return nN(e,n);case K.ZodBigInt:return TM(e,n);case K.ZodBoolean:return EM();case K.ZodDate:return kM(e,n);case K.ZodUndefined:return uN(n);case K.ZodNull:return XM(n);case K.ZodArray:return wM(e,n);case K.ZodUnion:case K.ZodDiscriminatedUnion:return QM(e,n);case K.ZodIntersection:return FM(e,n);case K.ZodTuple:return lN(e,n);case K.ZodRecord:return KM(e,n);case K.ZodLiteral:return IM(e,n);case K.ZodEnum:return NM(e);case K.ZodNativeEnum:return JM(e);case K.ZodNullable:return eN(e,n);case K.ZodOptional:return aN(e,n);case K.ZodMap:return qM(e,n);case K.ZodSet:return cN(e,n);case K.ZodLazy:return()=>e.getter()._def;case K.ZodPromise:return sN(e,n);case K.ZodNaN:case K.ZodNever:return YM(n);case K.ZodEffects:return MM(e,n);case K.ZodAny:return kA(n);case K.ZodUnknown:return dN(n);case K.ZodDefault:return jM(e,n);case K.ZodBranded:return DM(e,n);case K.ZodReadonly:return fN(e,n);case K.ZodCatch:return OM(e,n);case K.ZodPipeline:return oN(e,n);case K.ZodFunction:case K.ZodVoid:case K.ZodSymbol:return;default:return(e=>void 0)(t)}};function mN(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==wA)return i}if(r&&!n){let e=hN(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=pN(e,e.typeName,t),o=typeof a==`function`?mN(a(),t):a;if(o&&gN(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var hN=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:OA(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),kA(t)):t.$refStrategy===`seen`?kA(t):void 0}},gN=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),_N=(e,t)=>{let n=DA(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:mN(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??kA(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=mN(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??kA(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function vN(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`validate`in e[`~standard`]}function yN(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`jsonSchema`in e[`~standard`]}function bN(e){return vN(e)&&yN(e)}function xN(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!xN(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!xN(e[r],t[r]))return!1;return!0}return e===t}function SN(e){return encodeURI(CN(e))}function CN(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var wN={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},TN={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},EN={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},DN=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`);function ON(e,t=Object.create(null),n=DN,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:ON(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(EN[i])continue;let a=`${r}/${SN(i)}`,o=e[i];if(Array.isArray(o)){if(wN[i]){let e=o.length;for(let r=0;r<e;r++)ON(o[r],t,n,`${a}/${r}`)}}else if(TN[i])for(let e in o)ON(o[e],t,n,`${a}/${SN(e)}`);else ON(o,t,n,a)}return t}var kN=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,AN=[0,31,28,31,30,31,30,31,31,30,31,30,31],jN=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,MN=/^(?=.{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,NN=/^(?:[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,PN=/^(?:(?:[^\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,FN=/^(?:(?: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,IN=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,LN=/^(?:\/(?:[^~/]|~0|~1)*)*$/,RN=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,zN=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,BN=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},VN=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,HN=/^((([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,UN=e=>e.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));function WN(e){return e.test.bind(e)}var GN={date:qN,time:JN.bind(void 0,!1),"date-time":XN,duration:UN,uri:$N,"uri-reference":WN(NN),"uri-template":WN(PN),url:WN(FN),email:BN,hostname:WN(MN),ipv4:WN(VN),ipv6:WN(HN),regex:tP,uuid:WN(IN),"json-pointer":WN(LN),"json-pointer-uri-fragment":WN(RN),"relative-json-pointer":WN(zN)};function KN(e){return e%4==0&&(e%100!=0||e%400==0)}function qN(e){let t=e.match(kN);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&KN(n)?29:AN[r])}function JN(e,t){let n=t.match(jN);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}var YN=/t|\s/i;function XN(e){let t=e.split(YN);return t.length==2&&qN(t[0])&&JN(!0,t[1])}var ZN=/\/|:/,QN=/^(?:[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;function $N(e){return ZN.test(e)&&QN.test(e)}var eP=/[^\\]\\Z/;function tP(e){if(eP.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function nP(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}function rP(e,t,n=`2019-09`,r=ON(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:ee,else:C,format:te,properties:ne,patternProperties:w,additionalProperties:re,unevaluatedProperties:ie,minProperties:T,maxProperties:ae,propertyNames:E,dependentRequired:oe,dependentSchemas:se,dependencies:ce,prefixItems:D,items:le,additionalItems:ue,unevaluatedItems:O,contains:de,minContains:fe,maxContains:pe,minItems:me,maxItems:he,uniqueItems:ge,minimum:_e,maximum:ve,exclusiveMinimum:ye,exclusiveMaximum:be,multipleOf:xe,minLength:Se,maxLength:k,pattern:Ce,__absolute_ref__:A,__absolute_recursive_ref__:we}=t,j=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[we]:a,u=`${s}/$recursiveRef`,d=rP(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||j.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[A||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw A&&A!==d&&(e+=` Absolute URI "${A}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
|
|
115
|
+
- `)}`,Error(e)}let l=`${s}/$ref`,u=rP(e,t,n,r,i,a,o,l,c);if(u.valid||j.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:j.length===0,errors:j}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||j.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&j.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&j.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?xN(e,h)||j.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&j.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>xN(e,t))||j.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||j.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){let t=`${s}/not`;rP(e,v,n,r,i,a,o,t).valid&&j.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Te=[];if(y!==void 0){let t=`${s}/anyOf`,l=j.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=rP(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);j.push(...f.errors),u||=f.valid,f.valid&&Te.push(d)}u?j.length=l:j.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${s}/allOf`,l=j.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=rP(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);j.push(...f.errors),u&&=f.valid,f.valid&&Te.push(d)}u?j.length=l:j.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(x!==void 0){let t=`${s}/oneOf`,l=j.length,u=x.filter((s,l)=>{let u=Object.create(c),d=rP(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return j.push(...d.errors),d.valid&&Te.push(u),d.valid}).length;u===1?j.length=l:j.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Te),S!==void 0){let t=`${s}/if`;if(rP(e,S,n,r,i,a,o,t,c).valid){if(ee!==void 0){let l=rP(e,ee,n,r,i,a,o,`${s}/then`,c);l.valid||j.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(C!==void 0){let l=rP(e,C,n,r,i,a,o,`${s}/else`,c);l.valid||j.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||j.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(T!==void 0&&t.length<T&&j.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${T} properties.`}),ae!==void 0&&t.length>ae&&j.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${ae} properties.`}),E!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${SN(s)}`,c=rP(s,E,n,r,i,a,e,t);c.valid||j.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(oe!==void 0){let t=`${s}/dependantRequired`;for(let n in oe)if(n in e){let r=oe[n];for(let i of r)i in e||j.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(se!==void 0)for(let t in se){let l=`${s}/dependentSchemas`;if(t in e){let s=rP(e,se[t],n,r,i,a,o,`${l}/${SN(t)}`,c);s.valid||j.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(ce!==void 0){let t=`${s}/dependencies`;for(let s in ce)if(s in e){let c=ce[s];if(Array.isArray(c))for(let n of c)n in e||j.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=rP(e,c,n,r,i,a,o,`${t}/${SN(s)}`);l.valid||j.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(ne!==void 0){let t=`${s}/properties`;for(let s in ne){if(!(s in e))continue;let d=`${o}/${SN(s)}`,f=rP(e[s],ne[s],n,r,i,a,d,`${t}/${SN(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,j.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&w!==void 0){let t=`${s}/patternProperties`;for(let s in w){let d=new RegExp(s,`u`),f=w[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${SN(p)}`,h=rP(e[p],f,n,r,i,a,m,`${t}/${SN(s)}`);h.valid?c[p]=l[p]=!0:(u=i,j.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&re!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${SN(s)}`,f=rP(e[s],re,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,j.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&ie!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${SN(s)}`,u=rP(e[s],ie,n,r,i,a,l,t);u.valid?c[s]=!0:j.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){he!==void 0&&e.length>he&&j.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${he}).`}),me!==void 0&&e.length<me&&j.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${me}).`});let t=e.length,l=0,u=!1;if(D!==void 0){let d=`${s}/prefixItems`,f=Math.min(D.length,t);for(;l<f;l++){let t=rP(e[l],D[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,j.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(le!==void 0){let d=`${s}/items`;if(Array.isArray(le)){let s=Math.min(le.length,t);for(;l<s;l++){let t=rP(e[l],le[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,j.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=rP(e[l],le,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,j.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ue!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=rP(e[l],ue,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,j.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(de!==void 0)if(t===0&&fe===void 0)j.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(fe!==void 0&&t<fe)j.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${fe}).`});else{let l=`${s}/contains`,u=j.length,d=0;for(let s=0;s<t;s++){let t=rP(e[s],de,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):j.push(...t.errors)}d>=(fe||0)&&(j.length=u),fe===void 0&&pe===void 0&&d===0?j.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):fe!==void 0&&d<fe?j.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${fe} items matching schema. Only ${d} items were found.`}):pe!==void 0&&d>pe&&j.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${pe} items matching schema. ${d} items were found.`})}if(!u&&O!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=rP(e[l],O,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||j.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(ge)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&xN(r,t))&&(j.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(_e!==void 0&&(ye===!0&&e<=_e||e<_e)&&j.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${ye?`or equal to `:``} ${_e}.`}),ve!==void 0&&(be===!0&&e>=ve||e>ve)&&j.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${be?`or equal to `:``} ${ve}.`})):(_e!==void 0&&e<_e&&j.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${_e}.`}),ve!==void 0&&e>ve&&j.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${ve}.`}),ye!==void 0&&e<=ye&&j.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${ye}.`}),be!==void 0&&e>=be&&j.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${be}.`})),xe!==void 0){let t=e%xe;Math.abs(0-t)>=1.1920929e-7&&Math.abs(xe-t)>=1.1920929e-7&&j.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${xe}.`})}}else if(u===`string`){let t=Se===void 0&&k===void 0?0:nP(e);Se!==void 0&&t<Se&&j.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${Se}).`}),k!==void 0&&t>k&&j.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${k}).`}),Ce!==void 0&&!new RegExp(Ce,`u`).test(e)&&j.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),te!==void 0&&GN[te]&&!GN[te](e)&&j.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${te}".`})}return{valid:j.length===0,errors:j}}Du();var iP=new WeakMap;function aP(e,t){let n=!t&&typeof e==`object`&&!!e;if(n){let t=iP.get(e);if(t)return t}let r;if(yN(e)&&!tA(e))r=e[`~standard`].jsonSchema.input({target:`draft-07`});else if(tA(e)){let n=_A(e,!0);r=lA(n)?Nl(pA(n,!0),t):Nl(e,t)}else r=nA(e)?_N(e):e;return n&&typeof r==`object`&&r&&iP.set(e,r),r}function oP(e){if(!e||typeof e!=`object`||Object.keys(e).length===0||Array.isArray(e))return!1;if(`type`in e)return typeof e.type==`string`?e.type===`string`:Array.isArray(e.type)?e.type.every(e=>e===`string`):!1;if(`enum`in e)return Array.isArray(e.enum)&&e.enum.length>0&&e.enum.every(e=>typeof e==`string`);if(`const`in e)return typeof e.const==`string`;if(`allOf`in e&&Array.isArray(e.allOf))return e.allOf.some(e=>oP(e));if(`anyOf`in e&&Array.isArray(e.anyOf)||`oneOf`in e&&Array.isArray(e.oneOf)){let t=`anyOf`in e?e.anyOf:e.oneOf;return t.length>0&&t.every(e=>oP(e))}if(`not`in e)return!1;if(`$ref`in e&&typeof e.$ref==`string`){let t=e.$ref,n=ON(e);return n[t]?oP(n[t]):!1}return!1}function sP(e,t){if(e!==void 0&&!FS(e))return e;if(Qk(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}function cP(e){return Qk(e.data)?{type:`runnable`,data:{id:e.data.lc_id,name:e.data.getName()}}:{type:`schema`,data:{...aP(e.data.schema),title:e.data.name}}}var lP=class e{nodes={};edges=[];constructor(e){this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((t,n)=>{e[t.id]=FS(t.id)?n:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...cP(t)})),edges:this.edges.map(t=>{let n={source:e[t.source],target:e[t.target]};return t.data!==void 0&&(n.data=t.data),t.conditional!==void 0&&(n.conditional=t.conditional),n})}}addNode(e,t,n){if(t!==void 0&&this.nodes[t]!==void 0)throw Error(`Node with id ${t} already exists`);let r=t??Ane(),i={id:r,data:e,name:sP(t,e),metadata:n};return this.nodes[r]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,n,r){if(this.nodes[e.id]===void 0)throw Error(`Source node ${e.id} not in graph`);if(this.nodes[t.id]===void 0)throw Error(`Target node ${t.id} not in graph`);let i={source:e.id,target:t.id,data:n,conditional:r};return this.edges.push(i),i}firstNode(){return uP(this)}lastNode(){return dP(this)}extend(e,t=``){let n=t;Object.values(e.nodes).map(e=>e.id).every(FS)&&(n=``);let r=e=>n?`${n}:${e}`:e;Object.entries(e.nodes).forEach(([e,t])=>{this.nodes[r(e)]={...t,id:r(e)}});let i=e.edges.map(e=>({...e,source:r(e.source),target:r(e.target)}));this.edges=[...this.edges,...i];let a=e.firstNode(),o=e.lastNode();return[a?{id:r(a.id),data:a.data}:void 0,o?{id:r(o.id),data:o.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&uP(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&dP(this,[e.id])&&this.removeNode(e)}reid(){let t=Object.fromEntries(Object.values(this.nodes).map(e=>[e.id,e.name])),n=new Map;Object.values(t).forEach(e=>{n.set(e,(n.get(e)||0)+1)});let r=e=>{let r=t[e];return FS(e)&&n.get(r)===1?r:e};return new e({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){let{withStyles:t,curveStyle:n,nodeColors:r={default:`fill:#f2f0ff,line-height:1.2`,first:`fill-opacity:0`,last:`fill:#bfb6fc`},wrapLabelNWords:i}=e??{},a=this.reid(),o=a.firstNode(),s=a.lastNode();return SA(a.nodes,a.edges,{firstNode:o?.id,lastNode:s?.id,withStyles:t,curveStyle:n,nodeColors:r,wrapLabelNWords:i})}async drawMermaidPng(e){return CA(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}};function uP(e,t=[]){let n=new Set(e.edges.filter(e=>!t.includes(e.source)).map(e=>e.target)),r=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!n.has(i.id)&&r.push(i);return r.length===1?r[0]:void 0}function dP(e,t=[]){let n=new Set(e.edges.filter(e=>!t.includes(e.target)).map(e=>e.source)),r=[];for(let i of Object.values(e.nodes))!t.includes(i.id)&&!n.has(i.id)&&r.push(i);return r.length===1?r[0]:void 0}function fP(e){let t=new TextEncoder,n=new ReadableStream({async start(n){for await(let r of e)n.enqueue(t.encode(`event: data\ndata: ${JSON.stringify(r)}\n\n`));n.enqueue(t.encode(`event: end
|
|
116
116
|
|
|
117
|
-
`)),n.close()}});return ik.fromReadableStream(n)}function mP(e){return typeof e==`object`&&!!e&&typeof e[Symbol.iterator]==`function`&&typeof e.next==`function`}var hP=e=>typeof e==`object`&&!!e&&`next`in e&&typeof e.next==`function`;function gP(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}function _P(e){return typeof e==`object`&&!!e&&typeof e.next==`function`}async function vP(e,t){try{let n=await e.next();for(;!n.done;)await t?.(n.value),n=await e.next();return n.value}finally{await e.return?.(void 0)}}function*yP(e,t){for(;;){let{value:n,done:r}=XO.runWithConfig(tk(e),t.next.bind(t),!0);if(r)break;yield n}}async function*bP(e,t){let n=t[Symbol.asyncIterator]();for(;;){let{value:r,done:i}=await XO.runWithConfig(tk(e),n.next.bind(t),!0);if(i)break;yield r}}wM();function xP(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}var SP=class extends ox{lc_runnable=!0;name;getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new wP({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new CP({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new AP({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw 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($O);if(t>1&&!Array.isArray(e)&&e.runId){console.warn(`Provided runId will be used only for the first element of the batch.`);let n=Object.fromEntries(Object.entries(e).filter(([e])=>e!==`runId`));return Array.from({length:t},(t,r)=>$O(r===0?e:n))}return Array.from({length:t},()=>$O(e))}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=new Zk({maxConcurrency:r[0]?.maxConcurrency??n?.maxConcurrency,onFailedAttempt:e=>{throw e}}),a=e.map((e,t)=>i.call(async()=>{try{return await this.invoke(e,r[t])}catch(e){if(n?.returnExceptions)return e;throw e}}));return Promise.all(a)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let n=$O(t),r=new sk({generator:this._streamIterator(e,n),config:n});return await r.setup,ik.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(e){let t;t=$O(e===void 0?e:{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});let n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){let r=$O(n),i=await(await ZO(r))?.handleChainStart(this.toJSON(),xP(t,`input`),r.runId,r?.runType,void 0,void 0,r?.runName??this.getName());delete r.runId;let a;try{a=await nk(e.call(this,t,r,i),r.signal)}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd(xP(a,`output`)),a}async _batchWithConfig(e,t,n,r){let i=this._getOptionsList(n??{},t.length),a=await Promise.all(i.map(ZO)),o=await Promise.all(a.map(async(e,n)=>{let r=await e?.handleChainStart(this.toJSON(),xP(t[n],`input`),i[n].runId,i[n].runType,void 0,void 0,i[n].runName??this.getName());return delete i[n].runId,r})),s;try{s=await nk(e.call(this,t,i,o,r),i?.[0]?.signal)}catch(e){throw await Promise.all(o.map(t=>t?.handleChainError(e))),e}return await Promise.all(o.map(e=>e?.handleChainEnd(xP(s,`output`)))),s}_concatOutputChunks(e,t){return ok(e,t)}async*_transformStreamWithConfig(e,t,n){let r,i=!0,a,o=!0,s=$O(n),c=await ZO(s),l=this;async function*u(){for await(let t of e){if(i)if(r===void 0)r=t;else try{r=l._concatOutputChunks(r,t)}catch{r=void 0,i=!1}yield t}}let d;try{let e=await nae(t.bind(this),u(),async()=>c?.handleChainStart(this.toJSON(),{input:``},s.runId,s.runType,void 0,void 0,s.runName??this.getName(),void 0,{lc_defers_inputs:!0}),s.signal,s);delete s.runId,d=e.setup;let n=d?.handlers.find(pae),r=e.output;n!==void 0&&d!==void 0&&(r=n.tapOutputIterable(d.runId,r));let i=d?.handlers.find(dae);i!==void 0&&d!==void 0&&(r=i.tapOutputIterable(d.runId,r));for await(let e of r)if(yield e,o)if(a===void 0)a=e;else try{a=this._concatOutputChunks(a,e)}catch{a=void 0,o=!1}}catch(e){throw await d?.handleChainError(e,void 0,void 0,void 0,{inputs:xP(r,`input`)}),e}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:xP(r,`input`)})}getGraph(e){let t=new uP,n=t.addNode({name:`${this.getName()}Input`,schema:bM()}),r=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:bM()});return t.addEdge(n,r),t.addEdge(r,i),t}pipe(e){return new TP({first:this,last:jP(e)})}pick(e){return this.pipe(new NP(e))}assign(e){return this.pipe(new MP(new EP({steps:e})))}async*transform(e,t){let n;for await(let t of e)n=n===void 0?t:this._concatOutputChunks(n,t);yield*this._streamIterator(n,$O(t))}async*streamLog(e,t,n){let r=new Ok({...n,autoClose:!1,_schemaFormat:`original`}),i=$O(t);yield*this._streamLog(e,r,i)}async*_streamLog(e,t,n){let{callbacks:r}=n;if(r===void 0)n.callbacks=[t];else if(Array.isArray(r))n.callbacks=r.concat([t]);else{let e=r.copy();e.addHandler(t,!0),n.callbacks=e}let i=this.stream(e,n);async function a(){try{let e=await i;for await(let n of e){let e=new wk({ops:[{op:`add`,path:`/streamed_output/-`,value:n}]});await t.writer.write(e)}}finally{await t.writer.close()}}let o=a();try{for await(let e of t)yield e}finally{await o}}streamEvents(e,t,n){let r;if(t.version===`v1`)r=this._streamEventsV1(e,t,n);else if(t.version===`v2`)r=this._streamEventsV2(e,t,n);else throw Error(`Only versions "v1" and "v2" of the schema are currently supported.`);return t.encoding===`text/event-stream`?pP(r):ik.fromAsyncGenerator(r)}async*_streamEventsV2(e,t,n){let r=new mae({...n,autoClose:!1}),i=$O(t),a=i.runId??PS();i.runId=a;let o=i.callbacks;if(o===void 0)i.callbacks=[r];else if(Array.isArray(o))i.callbacks=o.concat(r);else{let e=o.copy();e.addHandler(r,!0),i.callbacks=e}let s=new AbortController,c=this;async function l(){let t;try{if(i.signal)if(`any`in AbortSignal)t=AbortSignal.any([s.signal,i.signal]);else{let e=new AbortController;i.signal.addEventListener(`abort`,()=>e.abort(),{once:!0}),s.signal.addEventListener(`abort`,()=>e.abort(),{once:!0}),t=e.signal}else t=s.signal;let n=await c.stream(e,{...i,signal:t}),o=r.tapOutputIterable(a,n);for await(let e of o)if(s.signal.aborted)break}finally{await r.finish()}}let u=l(),d=!1,f;try{for await(let t of r){if(!d){t.data.input=e,d=!0,f=t.run_id,yield t;continue}t.run_id===f&&t.event.endsWith(`_end`)&&t.data?.input&&delete t.data.input,yield t}}finally{s.abort(),await u}}async*_streamEventsV1(e,t,n){let r,i=!1,a=$O(t),o=a.tags??[],s=a.metadata??{},c=a.runName??this.getName(),l=new Ok({...n,autoClose:!1,_schemaFormat:`streaming_events`}),u=new eA({...n}),d=this._streamLog(e,l,a);for await(let t of d){if(r=r?r.concat(t):Tk.fromRunLogPatch(t),r.state===void 0)throw Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`);if(!i){i=!0;let t={...r.state},n={run_id:t.id,event:`on_${t.type}_start`,name:c,tags:o,metadata:s,data:{input:e}};u.includeEvent(n,t.type)&&(yield n)}let n=t.ops.filter(e=>e.path.startsWith(`/logs/`)).map(e=>e.path.split(`/`)[2]),a=[...new Set(n)];for(let e of a){let t,n={},i=r.state.logs[e];if(t=i.end_time===void 0?i.streamed_output.length>0?`stream`:`start`:`end`,t===`start`)i.inputs!==void 0&&(n.input=i.inputs);else if(t===`end`)i.inputs!==void 0&&(n.input=i.inputs),n.output=i.final_output;else if(t===`stream`){let e=i.streamed_output.length;if(e!==1)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${i.name}"`);n={chunk:i.streamed_output[0]},i.streamed_output=[]}yield{event:`on_${i.type}_${t}`,name:i.name,run_id:i.id,tags:i.tags,metadata:i.metadata,data:n}}let{state:l}=r;if(l.streamed_output.length>0){let e=l.streamed_output.length;if(e!==1)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${l.name}"`);let t={chunk:l.streamed_output[0]};l.streamed_output=[];let n={event:`on_${l.type}_stream`,run_id:l.id,tags:o,metadata:s,name:c,data:t};u.includeEvent(n,l.type)&&(yield n)}}let f=r?.state;if(f!==void 0){let e={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:o,metadata:s,data:{output:f.final_output}};u.includeEvent(e,f.type)&&(yield e)}}static isRunnable(e){return $k(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new CP({bound:this,config:{},configFactories:[r=>({callbacks:[new Qk({config:r,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return FP(this,e)}},CP=class e extends SP{static lc_name(){return`RunnableBinding`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),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){let t=QO(this.config,...e);return QO(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(t))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new wP({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(t,this.kwargs))}async batch(e,t,n){let r=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig($O(e),this.kwargs))):await this._mergeConfig($O(t),this.kwargs);return this.bound.batch(e,r,n)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig($O(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig($O(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig($O(t),this.kwargs))}streamEvents(e,t,n){let r=this;return ik.fromAsyncGenerator(async function*(){yield*r.bound.streamEvents(e,{...await r._mergeConfig($O(t),r.kwargs),version:t.version},n)}())}static isRunnableBinding(e){return e.bound&&SP.isRunnable(e.bound)}withListeners({onStart:t,onEnd:n,onError:r}){return new e({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[e=>({callbacks:[new Qk({config:e,onStart:t,onEnd:n,onError:r})]})]})}},wP=class extends CP{static lc_name(){return`RunnableRetry`}lc_namespace=[`langchain_core`,`runnables`];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){let r=e>1?`retry:attempt:${e}`:void 0;return ek(t,{callbacks:n?.getChild(r)})}async _invoke(e,t,n){return Fk(r=>super.invoke(e,this._patchConfigForRetry(r,t,n)),{onFailedAttempt:({error: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,n,r){let i={};try{await Fk(async a=>{let o=e.map((e,t)=>t).filter(e=>i[e.toString()]===void 0||i[e.toString()]instanceof Error),s=o.map(t=>e[t]),c=o.map(e=>this._patchConfigForRetry(a,t?.[e],n?.[e])),l=await super.batch(s,c,{...r,returnExceptions:!0}),u;for(let e=0;e<l.length;e+=1){let t=l[e],n=o[e];t instanceof Error&&u===void 0&&(u=t,u.input=s[e]),i[n.toString()]=t}if(u)throw u;return l},{onFailedAttempt:({error:e})=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(r?.returnExceptions!==!0)throw e}return Object.keys(i).sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>i[parseInt(e,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},TP=class e extends SP{static lc_name(){return`RunnableSequence`}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=[`langchain_core`,`runnables`];constructor(e){super(e),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){let n=$O(t),r=await(await ZO(n))?.handleChainStart(this.toJSON(),xP(e,`input`),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i=e,a;try{let e=[this.first,...this.middle];for(let t=0;t<e.length;t+=1)i=await nk(e[t].invoke(i,ek(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)})),n.signal);if(n.signal?.aborted)throw rk(n.signal);a=await this.last.invoke(i,ek(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(e){throw await r?.handleChainError(e),e}return await r?.handleChainEnd(xP(a,`output`)),a}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=await Promise.all(r.map(ZO)),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),xP(e[n],`input`),r[n].runId,void 0,void 0,void 0,r[n].runName);return delete r[n].runId,i})),o=e;try{for(let e=0;e<this.steps.length;e+=1)o=await nk(this.steps[e].batch(o,a.map((t,n)=>{let i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return ek(r[n],{callbacks:i})}),n),r[0]?.signal)}catch(e){throw await Promise.all(a.map(t=>t?.handleChainError(e))),e}return await Promise.all(a.map(e=>e?.handleChainEnd(xP(o,`output`)))),o}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){let n=await ZO(t),{runId:r,...i}=t??{},a=await n?.handleChainStart(this.toJSON(),xP(e,`input`),r,void 0,void 0,void 0,i?.runName),o=[this.first,...this.middle,this.last],s=!0,c;async function*l(){yield e}try{let e=o[0].transform(l(),ek(i,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:1`)}));for(let t=1;t<o.length;t+=1)e=await o[t].transform(e,ek(i,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)}));for await(let n of e)if(t?.signal?.throwIfAborted(),yield n,s)if(c===void 0)c=n;else try{c=this._concatOutputChunks(c,n)}catch{c=void 0,s=!1}}catch(e){throw await a?.handleChainError(e),e}await a?.handleChainEnd(xP(c,`output`))}getGraph(e){let t=new uP,n=null;return this.steps.forEach((r,i)=>{let a=r.getGraph(e);i!==0&&a.trimFirstNode(),i!==this.steps.length-1&&a.trimLastNode(),t.extend(a);let o=a.firstNode();if(!o)throw Error(`Runnable ${r} has no first node`);n&&t.addEdge(n,o),n=a.lastNode()}),t}pipe(t){return e.isRunnableSequence(t)?new e({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new e({first:this.first,middle:[...this.middle,this.last],last:jP(t),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&SP.isRunnable(e)}static from([t,...n],r){let i={};return typeof r==`string`?i.name=r:r!==void 0&&(i=r),new e({...i,first:jP(t),middle:n.slice(0,-1).map(jP),last:jP(n[n.length-1])})}},EP=class e extends SP{static lc_name(){return`RunnableMap`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),this.steps={};for(let[t,n]of Object.entries(e.steps))this.steps[t]=jP(n)}static from(t){return new e({steps:t})}async invoke(e,t){let n=$O(t),r=await(await ZO(n))?.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i={};try{let t=Object.entries(this.steps).map(async([t,a])=>{i[t]=await a.invoke(e,ek(n,{callbacks:r?.getChild(`map:key:${t}`)}))});await nk(Promise.all(t),n.signal)}catch(e){throw await r?.handleChainError(e),e}return await r?.handleChainEnd(i),i}async*_transform(e,t,n){let r={...this.steps},i=ak(e,Object.keys(r).length),a=new Map(Object.entries(r).map(([e,r],a)=>{let o=r.transform(i[a],ek(n,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,o.next().then(t=>({key:e,gen:o,result:t}))]}));for(;a.size;){let{key:e,result:t,gen:r}=await nk(Promise.race(a.values()),n?.signal);a.delete(e),t.done||(yield{[e]:t.value},a.set(e,r.next().then(t=>({key:e,gen:r,result:t}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=$O(t),i=new sk({generator:this.transform(n(),r),config:r});return await i.setup,ik.fromAsyncGenerator(i)}},DP=class e extends SP{lc_serializable=!1;lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(super(e),!qC(e.func))throw Error(`RunnableTraceable requires a function that is wrapped in traceable higher-order function`);this.func=e.func}async invoke(e,t){let[n]=this._getOptionsList(t??{},1),r=await ZO(n);return nk(this.func(ek(n,{callbacks:r}),e),n?.signal)}async*_streamIterator(e,t){let[n]=this._getOptionsList(t??{},1),r=await this.invoke(e,t);if(gP(r)){for await(let e of r)n?.signal?.throwIfAborted(),yield e;return}if(hP(r)){for(;;){n?.signal?.throwIfAborted();let e=r.next();if(e.done)break;yield e.value}return}yield r}static from(t){return new e({func:t})}};function OP(e){if(qC(e))throw Error(`RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.`)}var kP=class e extends SP{static lc_name(){return`RunnableLambda`}lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(qC(e.func))return DP.from(e.func);super(e),OP(e.func),this.func=e.func}static from(t){return new e({func:t})}async _invoke(e,t,n){return new Promise((r,i)=>{let a=ek(t,{callbacks:n?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});XO.runWithConfig(tk(a),async()=>{try{let n=await this.func(e,{...a});if(n&&SP.isRunnable(n)){if(t?.recursionLimit===0)throw Error(`Recursion limit reached.`);n=await n.invoke(e,{...a,recursionLimit:(a.recursionLimit??25)-1})}else if(gP(n)){let e;for await(let r of bP(a,n))if(t?.signal?.throwIfAborted(),e===void 0)e=r;else try{e=this._concatOutputChunks(e,r)}catch{e=r}n=e}else if(mP(n)){let e;for(let r of yP(a,n))if(t?.signal?.throwIfAborted(),e===void 0)e=r;else try{e=this._concatOutputChunks(e,r)}catch{e=r}n=e}r(n)}catch(e){i(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,n){let r;for await(let t of e)if(r===void 0)r=t;else try{r=this._concatOutputChunks(r,t)}catch{r=t}let i=ek(n,{callbacks:t?.getChild(),recursionLimit:(n?.recursionLimit??25)-1}),a=await new Promise((e,t)=>{XO.runWithConfig(tk(i),async()=>{try{e(await this.func(r,{...i,config:i}))}catch(e){t(e)}})});if(a&&SP.isRunnable(a)){if(n?.recursionLimit===0)throw Error(`Recursion limit reached.`);let e=await a.stream(r,i);for await(let t of e)yield t}else if(gP(a))for await(let e of bP(i,a))n?.signal?.throwIfAborted(),yield e;else if(mP(a))for(let e of yP(i,a))n?.signal?.throwIfAborted(),yield e;else yield a}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=$O(t),i=new sk({generator:this.transform(n(),r),config:r});return await i.setup,ik.fromAsyncGenerator(i)}},AP=class extends SP{static lc_name(){return`RunnableWithFallbacks`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(let e of this.fallbacks)yield e}async invoke(e,t){let n=$O(t),r=await ZO(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),xP(e,`input`),i,void 0,void 0,void 0,a?.runName),s=ek(a,{callbacks:o?.getChild()});return await XO.runWithConfig(s,async()=>{let t;for(let r of this.runnables()){n?.signal?.throwIfAborted();try{let t=await r.invoke(e,s);return await o?.handleChainEnd(xP(t,`output`)),t}catch(e){t===void 0&&(t=e)}}throw t===void 0?Error(`No error stored at end of fallback.`):(await o?.handleChainError(t),t)})}async*_streamIterator(e,t){let n=$O(t),r=await ZO(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),xP(e,`input`),i,void 0,void 0,void 0,a?.runName),s,c;for(let t of this.runnables()){n?.signal?.throwIfAborted();let r=ek(a,{callbacks:o?.getChild()});try{c=bP(r,await t.stream(e,r));break}catch(e){s===void 0&&(s=e)}}if(c===void 0){let e=s??Error(`No error stored at end of fallback.`);throw await o?.handleChainError(e),e}let l;try{for await(let e of c){yield e;try{l=l===void 0?l:this._concatOutputChunks(l,e)}catch{l=void 0}}}catch(e){throw await o?.handleChainError(e),e}await o?.handleChainEnd(xP(l,`output`))}async batch(e,t,n){if(n?.returnExceptions)throw Error(`Not implemented.`);let r=this._getOptionsList(t??{},e.length),i=await Promise.all(r.map(e=>ZO(e))),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),xP(e[n],`input`),r[n].runId,void 0,void 0,void 0,r[n].runName);return delete r[n].runId,i})),o;for(let t of this.runnables()){r[0].signal?.throwIfAborted();try{let i=await t.batch(e,a.map((e,t)=>ek(r[t],{callbacks:e?.getChild()})),n);return await Promise.all(a.map((e,t)=>e?.handleChainEnd(xP(i[t],`output`)))),i}catch(e){o===void 0&&(o=e)}}throw o?(await Promise.all(a.map(e=>e?.handleChainError(o))),o):Error(`No error stored at end of fallbacks.`)}};function jP(e){if(typeof e==`function`)return new kP({func:e});if(SP.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=jP(r);return new EP({steps:t})}else throw Error(`Expected a Runnable, function or object.
|
|
118
|
-
Instead got an unsupported type.`)}var
|
|
117
|
+
`)),n.close()}});return ik.fromReadableStream(n)}function pP(e){return typeof e==`object`&&!!e&&typeof e[Symbol.iterator]==`function`&&typeof e.next==`function`}var mP=e=>typeof e==`object`&&!!e&&`next`in e&&typeof e.next==`function`;function hP(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}function gP(e){return typeof e==`object`&&!!e&&typeof e.next==`function`}async function _P(e,t){try{let n=await e.next();for(;!n.done;)await t?.(n.value),n=await e.next();return n.value}finally{await e.return?.(void 0)}}function*vP(e,t){for(;;){let{value:n,done:r}=XO.runWithConfig(tk(e),t.next.bind(t),!0);if(r)break;yield n}}async function*yP(e,t){let n=t[Symbol.asyncIterator]();for(;;){let{value:r,done:i}=await XO.runWithConfig(tk(e),n.next.bind(t),!0);if(i)break;yield r}}CM();function bP(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}var xP=class extends ox{lc_runnable=!0;name;getName(e){let t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}withRetry(e){return new CP({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new SP({bound:this,config:e,kwargs:{}})}withFallbacks(e){let t=Array.isArray(e)?e:e.fallbacks;return new kP({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw 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($O);if(t>1&&!Array.isArray(e)&&e.runId){console.warn(`Provided runId will be used only for the first element of the batch.`);let n=Object.fromEntries(Object.entries(e).filter(([e])=>e!==`runId`));return Array.from({length:t},(t,r)=>$O(r===0?e:n))}return Array.from({length:t},()=>$O(e))}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=new Xk({maxConcurrency:r[0]?.maxConcurrency??n?.maxConcurrency,onFailedAttempt:e=>{throw e}}),a=e.map((e,t)=>i.call(async()=>{try{return await this.invoke(e,r[t])}catch(e){if(n?.returnExceptions)return e;throw e}}));return Promise.all(a)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){let n=$O(t),r=new sk({generator:this._streamIterator(e,n),config:n});return await r.setup,ik.fromAsyncGenerator(r)}_separateRunnableConfigFromCallOptions(e){let t;t=$O(e===void 0?e:{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});let n={...e};return delete n.callbacks,delete n.tags,delete n.metadata,delete n.runName,delete n.configurable,delete n.recursionLimit,delete n.maxConcurrency,delete n.runId,delete n.timeout,delete n.signal,[t,n]}async _callWithConfig(e,t,n){let r=$O(n),i=await(await ZO(r))?.handleChainStart(this.toJSON(),bP(t,`input`),r.runId,r?.runType,void 0,void 0,r?.runName??this.getName());delete r.runId;let a;try{a=await nk(e.call(this,t,r,i),r.signal)}catch(e){throw await i?.handleChainError(e),e}return await i?.handleChainEnd(bP(a,`output`)),a}async _batchWithConfig(e,t,n,r){let i=this._getOptionsList(n??{},t.length),a=await Promise.all(i.map(ZO)),o=await Promise.all(a.map(async(e,n)=>{let r=await e?.handleChainStart(this.toJSON(),bP(t[n],`input`),i[n].runId,i[n].runType,void 0,void 0,i[n].runName??this.getName());return delete i[n].runId,r})),s;try{s=await nk(e.call(this,t,i,o,r),i?.[0]?.signal)}catch(e){throw await Promise.all(o.map(t=>t?.handleChainError(e))),e}return await Promise.all(o.map(e=>e?.handleChainEnd(bP(s,`output`)))),s}_concatOutputChunks(e,t){return ok(e,t)}async*_transformStreamWithConfig(e,t,n){let r,i=!0,a,o=!0,s=$O(n),c=await ZO(s),l=this;async function*u(){for await(let t of e){if(i)if(r===void 0)r=t;else try{r=l._concatOutputChunks(r,t)}catch{r=void 0,i=!1}yield t}}let d;try{let e=await nae(t.bind(this),u(),async()=>c?.handleChainStart(this.toJSON(),{input:``},s.runId,s.runType,void 0,void 0,s.runName??this.getName(),void 0,{lc_defers_inputs:!0}),s.signal,s);delete s.runId,d=e.setup;let n=d?.handlers.find(pae),r=e.output;n!==void 0&&d!==void 0&&(r=n.tapOutputIterable(d.runId,r));let i=d?.handlers.find(dae);i!==void 0&&d!==void 0&&(r=i.tapOutputIterable(d.runId,r));for await(let e of r)if(yield e,o)if(a===void 0)a=e;else try{a=this._concatOutputChunks(a,e)}catch{a=void 0,o=!1}}catch(e){throw await d?.handleChainError(e,void 0,void 0,void 0,{inputs:bP(r,`input`)}),e}await d?.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:bP(r,`input`)})}getGraph(e){let t=new lP,n=t.addNode({name:`${this.getName()}Input`,schema:yM()}),r=t.addNode(this),i=t.addNode({name:`${this.getName()}Output`,schema:yM()});return t.addEdge(n,r),t.addEdge(r,i),t}pipe(e){return new wP({first:this,last:AP(e)})}pick(e){return this.pipe(new MP(e))}assign(e){return this.pipe(new jP(new TP({steps:e})))}async*transform(e,t){let n;for await(let t of e)n=n===void 0?t:this._concatOutputChunks(n,t);yield*this._streamIterator(n,$O(t))}async*streamLog(e,t,n){let r=new Ok({...n,autoClose:!1,_schemaFormat:`original`}),i=$O(t);yield*this._streamLog(e,r,i)}async*_streamLog(e,t,n){let{callbacks:r}=n;if(r===void 0)n.callbacks=[t];else if(Array.isArray(r))n.callbacks=r.concat([t]);else{let e=r.copy();e.addHandler(t,!0),n.callbacks=e}let i=this.stream(e,n);async function a(){try{let e=await i;for await(let n of e){let e=new wk({ops:[{op:`add`,path:`/streamed_output/-`,value:n}]});await t.writer.write(e)}}finally{await t.writer.close()}}let o=a();try{for await(let e of t)yield e}finally{await o}}streamEvents(e,t,n){let r;if(t.version===`v1`)r=this._streamEventsV1(e,t,n);else if(t.version===`v2`)r=this._streamEventsV2(e,t,n);else throw Error(`Only versions "v1" and "v2" of the schema are currently supported.`);return t.encoding===`text/event-stream`?fP(r):ik.fromAsyncGenerator(r)}async*_streamEventsV2(e,t,n){let r=new mae({...n,autoClose:!1}),i=$O(t),a=i.runId??PS();i.runId=a;let o=i.callbacks;if(o===void 0)i.callbacks=[r];else if(Array.isArray(o))i.callbacks=o.concat(r);else{let e=o.copy();e.addHandler(r,!0),i.callbacks=e}let s=new AbortController,c=this;async function l(){let t;try{if(i.signal)if(`any`in AbortSignal)t=AbortSignal.any([s.signal,i.signal]);else{let e=new AbortController;i.signal.addEventListener(`abort`,()=>e.abort(),{once:!0}),s.signal.addEventListener(`abort`,()=>e.abort(),{once:!0}),t=e.signal}else t=s.signal;let n=await c.stream(e,{...i,signal:t}),o=r.tapOutputIterable(a,n);for await(let e of o)if(s.signal.aborted)break}finally{await r.finish()}}let u=l(),d=!1,f;try{for await(let t of r){if(!d){t.data.input=e,d=!0,f=t.run_id,yield t;continue}t.run_id===f&&t.event.endsWith(`_end`)&&t.data?.input&&delete t.data.input,yield t}}finally{s.abort(),await u}}async*_streamEventsV1(e,t,n){let r,i=!1,a=$O(t),o=a.tags??[],s=a.metadata??{},c=a.runName??this.getName(),l=new Ok({...n,autoClose:!1,_schemaFormat:`streaming_events`}),u=new $k({...n}),d=this._streamLog(e,l,a);for await(let t of d){if(r=r?r.concat(t):Tk.fromRunLogPatch(t),r.state===void 0)throw Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`);if(!i){i=!0;let t={...r.state},n={run_id:t.id,event:`on_${t.type}_start`,name:c,tags:o,metadata:s,data:{input:e}};u.includeEvent(n,t.type)&&(yield n)}let n=t.ops.filter(e=>e.path.startsWith(`/logs/`)).map(e=>e.path.split(`/`)[2]),a=[...new Set(n)];for(let e of a){let t,n={},i=r.state.logs[e];if(t=i.end_time===void 0?i.streamed_output.length>0?`stream`:`start`:`end`,t===`start`)i.inputs!==void 0&&(n.input=i.inputs);else if(t===`end`)i.inputs!==void 0&&(n.input=i.inputs),n.output=i.final_output;else if(t===`stream`){let e=i.streamed_output.length;if(e!==1)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${i.name}"`);n={chunk:i.streamed_output[0]},i.streamed_output=[]}yield{event:`on_${i.type}_${t}`,name:i.name,run_id:i.id,tags:i.tags,metadata:i.metadata,data:n}}let{state:l}=r;if(l.streamed_output.length>0){let e=l.streamed_output.length;if(e!==1)throw Error(`Expected exactly one chunk of streamed output, got ${e} instead. Encountered in: "${l.name}"`);let t={chunk:l.streamed_output[0]};l.streamed_output=[];let n={event:`on_${l.type}_stream`,run_id:l.id,tags:o,metadata:s,name:c,data:t};u.includeEvent(n,l.type)&&(yield n)}}let f=r?.state;if(f!==void 0){let e={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:o,metadata:s,data:{output:f.final_output}};u.includeEvent(e,f.type)&&(yield e)}}static isRunnable(e){return Qk(e)}withListeners({onStart:e,onEnd:t,onError:n}){return new SP({bound:this,config:{},configFactories:[r=>({callbacks:[new Zk({config:r,onStart:e,onEnd:t,onError:n})]})]})}asTool(e){return PP(this,e)}},SP=class e extends xP{static lc_name(){return`RunnableBinding`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;bound;config;kwargs;configFactories;constructor(e){super(e),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){let t=QO(this.config,...e);return QO(t,...this.configFactories?await Promise.all(this.configFactories.map(async e=>await e(t))):[])}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new CP({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(t,this.kwargs))}async batch(e,t,n){let r=Array.isArray(t)?await Promise.all(t.map(async e=>this._mergeConfig($O(e),this.kwargs))):await this._mergeConfig($O(t),this.kwargs);return this.bound.batch(e,r,n)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig($O(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig($O(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig($O(t),this.kwargs))}streamEvents(e,t,n){let r=this;return ik.fromAsyncGenerator(async function*(){yield*r.bound.streamEvents(e,{...await r._mergeConfig($O(t),r.kwargs),version:t.version},n)}())}static isRunnableBinding(e){return e.bound&&xP.isRunnable(e.bound)}withListeners({onStart:t,onEnd:n,onError:r}){return new e({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[e=>({callbacks:[new Zk({config:e,onStart:t,onEnd:n,onError:r})]})]})}},CP=class extends SP{static lc_name(){return`RunnableRetry`}lc_namespace=[`langchain_core`,`runnables`];maxAttemptNumber=3;onFailedAttempt=()=>{};constructor(e){super(e),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,n){let r=e>1?`retry:attempt:${e}`:void 0;return ek(t,{callbacks:n?.getChild(r)})}async _invoke(e,t,n){return Fk(r=>super.invoke(e,this._patchConfigForRetry(r,t,n)),{onFailedAttempt:({error: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,n,r){let i={};try{await Fk(async a=>{let o=e.map((e,t)=>t).filter(e=>i[e.toString()]===void 0||i[e.toString()]instanceof Error),s=o.map(t=>e[t]),c=o.map(e=>this._patchConfigForRetry(a,t?.[e],n?.[e])),l=await super.batch(s,c,{...r,returnExceptions:!0}),u;for(let e=0;e<l.length;e+=1){let t=l[e],n=o[e];t instanceof Error&&u===void 0&&(u=t,u.input=s[e]),i[n.toString()]=t}if(u)throw u;return l},{onFailedAttempt:({error:e})=>this.onFailedAttempt(e,e.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(e){if(r?.returnExceptions!==!0)throw e}return Object.keys(i).sort((e,t)=>parseInt(e,10)-parseInt(t,10)).map(e=>i[parseInt(e,10)])}async batch(e,t,n){return this._batchWithConfig(this._batch.bind(this),e,t,n)}},wP=class e extends xP{static lc_name(){return`RunnableSequence`}first;middle=[];last;omitSequenceTags=!1;lc_serializable=!0;lc_namespace=[`langchain_core`,`runnables`];constructor(e){super(e),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){let n=$O(t),r=await(await ZO(n))?.handleChainStart(this.toJSON(),bP(e,`input`),n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i=e,a;try{let e=[this.first,...this.middle];for(let t=0;t<e.length;t+=1)i=await nk(e[t].invoke(i,ek(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)})),n.signal);if(n.signal?.aborted)throw rk(n.signal);a=await this.last.invoke(i,ek(n,{callbacks:r?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(e){throw await r?.handleChainError(e),e}return await r?.handleChainEnd(bP(a,`output`)),a}async batch(e,t,n){let r=this._getOptionsList(t??{},e.length),i=await Promise.all(r.map(ZO)),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),bP(e[n],`input`),r[n].runId,void 0,void 0,void 0,r[n].runName);return delete r[n].runId,i})),o=e;try{for(let e=0;e<this.steps.length;e+=1)o=await nk(this.steps[e].batch(o,a.map((t,n)=>{let i=t?.getChild(this.omitSequenceTags?void 0:`seq:step:${e+1}`);return ek(r[n],{callbacks:i})}),n),r[0]?.signal)}catch(e){throw await Promise.all(a.map(t=>t?.handleChainError(e))),e}return await Promise.all(a.map(e=>e?.handleChainEnd(bP(o,`output`)))),o}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){let n=await ZO(t),{runId:r,...i}=t??{},a=await n?.handleChainStart(this.toJSON(),bP(e,`input`),r,void 0,void 0,void 0,i?.runName),o=[this.first,...this.middle,this.last],s=!0,c;async function*l(){yield e}try{let e=o[0].transform(l(),ek(i,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:1`)}));for(let t=1;t<o.length;t+=1)e=await o[t].transform(e,ek(i,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${t+1}`)}));for await(let n of e)if(t?.signal?.throwIfAborted(),yield n,s)if(c===void 0)c=n;else try{c=this._concatOutputChunks(c,n)}catch{c=void 0,s=!1}}catch(e){throw await a?.handleChainError(e),e}await a?.handleChainEnd(bP(c,`output`))}getGraph(e){let t=new lP,n=null;return this.steps.forEach((r,i)=>{let a=r.getGraph(e);i!==0&&a.trimFirstNode(),i!==this.steps.length-1&&a.trimLastNode(),t.extend(a);let o=a.firstNode();if(!o)throw Error(`Runnable ${r} has no first node`);n&&t.addEdge(n,o),n=a.lastNode()}),t}pipe(t){return e.isRunnableSequence(t)?new e({first:this.first,middle:this.middle.concat([this.last,t.first,...t.middle]),last:t.last,name:this.name??t.name}):new e({first:this.first,middle:[...this.middle,this.last],last:AP(t),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&xP.isRunnable(e)}static from([t,...n],r){let i={};return typeof r==`string`?i.name=r:r!==void 0&&(i=r),new e({...i,first:AP(t),middle:n.slice(0,-1).map(AP),last:AP(n[n.length-1])})}},TP=class e extends xP{static lc_name(){return`RunnableMap`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;steps;getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),this.steps={};for(let[t,n]of Object.entries(e.steps))this.steps[t]=AP(n)}static from(t){return new e({steps:t})}async invoke(e,t){let n=$O(t),r=await(await ZO(n))?.handleChainStart(this.toJSON(),{input:e},n.runId,void 0,void 0,void 0,n?.runName);delete n.runId;let i={};try{let t=Object.entries(this.steps).map(async([t,a])=>{i[t]=await a.invoke(e,ek(n,{callbacks:r?.getChild(`map:key:${t}`)}))});await nk(Promise.all(t),n.signal)}catch(e){throw await r?.handleChainError(e),e}return await r?.handleChainEnd(i),i}async*_transform(e,t,n){let r={...this.steps},i=ak(e,Object.keys(r).length),a=new Map(Object.entries(r).map(([e,r],a)=>{let o=r.transform(i[a],ek(n,{callbacks:t?.getChild(`map:key:${e}`)}));return[e,o.next().then(t=>({key:e,gen:o,result:t}))]}));for(;a.size;){let{key:e,result:t,gen:r}=await nk(Promise.race(a.values()),n?.signal);a.delete(e),t.done||(yield{[e]:t.value},a.set(e,r.next().then(t=>({key:e,gen:r,result:t}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=$O(t),i=new sk({generator:this.transform(n(),r),config:r});return await i.setup,ik.fromAsyncGenerator(i)}},EP=class e extends xP{lc_serializable=!1;lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(super(e),!qC(e.func))throw Error(`RunnableTraceable requires a function that is wrapped in traceable higher-order function`);this.func=e.func}async invoke(e,t){let[n]=this._getOptionsList(t??{},1),r=await ZO(n);return nk(this.func(ek(n,{callbacks:r}),e),n?.signal)}async*_streamIterator(e,t){let[n]=this._getOptionsList(t??{},1),r=await this.invoke(e,t);if(hP(r)){for await(let e of r)n?.signal?.throwIfAborted(),yield e;return}if(mP(r)){for(;;){n?.signal?.throwIfAborted();let e=r.next();if(e.done)break;yield e.value}return}yield r}static from(t){return new e({func:t})}};function DP(e){if(qC(e))throw Error(`RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.`)}var OP=class e extends xP{static lc_name(){return`RunnableLambda`}lc_namespace=[`langchain_core`,`runnables`];func;constructor(e){if(qC(e.func))return EP.from(e.func);super(e),DP(e.func),this.func=e.func}static from(t){return new e({func:t})}async _invoke(e,t,n){return new Promise((r,i)=>{let a=ek(t,{callbacks:n?.getChild(),recursionLimit:(t?.recursionLimit??25)-1});XO.runWithConfig(tk(a),async()=>{try{let n=await this.func(e,{...a});if(n&&xP.isRunnable(n)){if(t?.recursionLimit===0)throw Error(`Recursion limit reached.`);n=await n.invoke(e,{...a,recursionLimit:(a.recursionLimit??25)-1})}else if(hP(n)){let e;for await(let r of yP(a,n))if(t?.signal?.throwIfAborted(),e===void 0)e=r;else try{e=this._concatOutputChunks(e,r)}catch{e=r}n=e}else if(pP(n)){let e;for(let r of vP(a,n))if(t?.signal?.throwIfAborted(),e===void 0)e=r;else try{e=this._concatOutputChunks(e,r)}catch{e=r}n=e}r(n)}catch(e){i(e)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,n){let r;for await(let t of e)if(r===void 0)r=t;else try{r=this._concatOutputChunks(r,t)}catch{r=t}let i=ek(n,{callbacks:t?.getChild(),recursionLimit:(n?.recursionLimit??25)-1}),a=await new Promise((e,t)=>{XO.runWithConfig(tk(i),async()=>{try{e(await this.func(r,{...i,config:i}))}catch(e){t(e)}})});if(a&&xP.isRunnable(a)){if(n?.recursionLimit===0)throw Error(`Recursion limit reached.`);let e=await a.stream(r,i);for await(let t of e)yield t}else if(hP(a))for await(let e of yP(i,a))n?.signal?.throwIfAborted(),yield e;else if(pP(a))for(let e of vP(i,a))n?.signal?.throwIfAborted(),yield e;else yield a}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=$O(t),i=new sk({generator:this.transform(n(),r),config:r});return await i.setup,ik.fromAsyncGenerator(i)}},kP=class extends xP{static lc_name(){return`RunnableWithFallbacks`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;runnable;fallbacks;constructor(e){super(e),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(let e of this.fallbacks)yield e}async invoke(e,t){let n=$O(t),r=await ZO(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),bP(e,`input`),i,void 0,void 0,void 0,a?.runName),s=ek(a,{callbacks:o?.getChild()});return await XO.runWithConfig(s,async()=>{let t;for(let r of this.runnables()){n?.signal?.throwIfAborted();try{let t=await r.invoke(e,s);return await o?.handleChainEnd(bP(t,`output`)),t}catch(e){t===void 0&&(t=e)}}throw t===void 0?Error(`No error stored at end of fallback.`):(await o?.handleChainError(t),t)})}async*_streamIterator(e,t){let n=$O(t),r=await ZO(n),{runId:i,...a}=n,o=await r?.handleChainStart(this.toJSON(),bP(e,`input`),i,void 0,void 0,void 0,a?.runName),s,c;for(let t of this.runnables()){n?.signal?.throwIfAborted();let r=ek(a,{callbacks:o?.getChild()});try{c=yP(r,await t.stream(e,r));break}catch(e){s===void 0&&(s=e)}}if(c===void 0){let e=s??Error(`No error stored at end of fallback.`);throw await o?.handleChainError(e),e}let l;try{for await(let e of c){yield e;try{l=l===void 0?l:this._concatOutputChunks(l,e)}catch{l=void 0}}}catch(e){throw await o?.handleChainError(e),e}await o?.handleChainEnd(bP(l,`output`))}async batch(e,t,n){if(n?.returnExceptions)throw Error(`Not implemented.`);let r=this._getOptionsList(t??{},e.length),i=await Promise.all(r.map(e=>ZO(e))),a=await Promise.all(i.map(async(t,n)=>{let i=await t?.handleChainStart(this.toJSON(),bP(e[n],`input`),r[n].runId,void 0,void 0,void 0,r[n].runName);return delete r[n].runId,i})),o;for(let t of this.runnables()){r[0].signal?.throwIfAborted();try{let i=await t.batch(e,a.map((e,t)=>ek(r[t],{callbacks:e?.getChild()})),n);return await Promise.all(a.map((e,t)=>e?.handleChainEnd(bP(i[t],`output`)))),i}catch(e){o===void 0&&(o=e)}}throw o?(await Promise.all(a.map(e=>e?.handleChainError(o))),o):Error(`No error stored at end of fallbacks.`)}};function AP(e){if(typeof e==`function`)return new OP({func:e});if(xP.isRunnable(e))return e;if(!Array.isArray(e)&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=AP(r);return new TP({steps:t})}else throw Error(`Expected a Runnable, function or object.
|
|
118
|
+
Instead got an unsupported type.`)}var jP=class extends xP{static lc_name(){return`RunnableAssign`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;mapper;constructor(e){e instanceof TP&&(e={mapper:e}),super(e),this.mapper=e.mapper}async invoke(e,t){let n=await this.mapper.invoke(e,t);return{...e,...n}}async*_transform(e,t,n){let r=this.mapper.getStepsKeys(),[i,a]=ak(e),o=this.mapper.transform(a,ek(n,{callbacks:t?.getChild()})),s=o.next();for await(let e of i){if(typeof e!=`object`||Array.isArray(e))throw Error(`RunnableAssign can only be used with objects as input, got ${typeof e}`);let t=Object.fromEntries(Object.entries(e).filter(([e])=>!r.includes(e)));Object.keys(t).length>0&&(yield t)}yield(await s).value;for await(let e of o)yield e}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=$O(t),i=new sk({generator:this.transform(n(),r),config:r});return await i.setup,ik.fromAsyncGenerator(i)}},MP=class extends xP{static lc_name(){return`RunnablePick`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;keys;constructor(e){(typeof e==`string`||Array.isArray(e))&&(e={keys:e}),super(e),this.keys=e.keys}async _pick(e){if(typeof this.keys==`string`)return e[this.keys];{let t=this.keys.map(t=>[t,e[t]]).filter(e=>e[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(let t of e){let e=await this._pick(t);e!==void 0&&(yield e)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*n(){yield e}let r=$O(t),i=new sk({generator:this.transform(n(),r),config:r});return await i.setup,ik.fromAsyncGenerator(i)}},NP=class extends SP{name;description;schema;constructor(e){let t=wP.from([OP.from(async e=>{let t;if(oS(e))try{t=await aA(this.schema,e.args)}catch{throw new sS(`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});super({bound:t,config:e.config??{}}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return`RunnableToolLike`}};function PP(e,t){let n=t.name??e.getName(),r=t.description??oA(t.schema);return sA(t.schema)?new NP({name:n,description:r,schema:bM({input:vM()}).transform(e=>e.input),bound:e}):new NP({name:n,description:r,schema:t.schema,bound:e})}var FP=[`tool_call`,`tool_call_chunk`,`invalid_tool_call`,`server_tool_call`,`server_tool_call_chunk`,`server_tool_call_result`],IP=[`image`,`video`,`audio`,`text-plain`,`file`];[...FP,...IP];var LP=e=>e();function RP(e){return e?!!(/^o\d/.test(e??``)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)):!1}function zP(e){return e.role!==`system`&&e.role!==`developer`&&e.role!==`assistant`&&e.role!==`user`&&e.role!==`function`&&e.role!==`tool`&&console.warn(`Unknown message role: ${e.role}`),e.role}function BP(e){return e.metadata?.filename??e.metadata?.name??e.metadata?.title}var VP=`LC_AUTOGENERATED`;function HP(e){return(e.metadata?.filename??e.metadata?.name??e.metadata?.title)||(console.warn(`OpenAI may require a filename for file uploads. Specify a filename in the content block metadata, e.g.: { type: 'file', mimeType: '...', data: '...', metadata: { filename: 'my-file.pdf' } }. Using placeholder filename 'LC_AUTOGENERATED'.`),VP)}function UP(e){let t=e._getType();switch(t){case`system`:return`system`;case`ai`:return`assistant`;case`human`:return`user`;case`function`:return`function`;case`tool`:return`tool`;case`generic`:if(!uS.isInstance(e))throw Error(`Invalid generic chat message`);return zP(e);default:throw Error(`Unknown message type: ${t}`)}}function WP(e){return!!(e.includes(`gpt-5.2-pro`)||e.includes(`gpt-5.4-pro`)||e.includes(`gpt-5.5-pro`)||e.includes(`codex`))}function GP(e){let{azureOpenAIApiDeploymentName:t,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:r,azureOpenAIBasePath:i,baseURL:a,azureADTokenProvider:o,azureOpenAIEndpoint:s}=e;if((r||o)&&i&&t)return`${i}/${t}`;if((r||o)&&s&&t)return`${s}/openai/deployments/${t}`;if(r||o){if(!n)throw Error(`azureOpenAIApiInstanceName is required when using azureOpenAIApiKey`);if(!t)throw Error(`azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey`);return`https://${n}.openai.azure.com/openai/deployments/${t}`}return a}function KP(e){return typeof Headers<`u`&&typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Headers]`}function qP(e){let t=LP(()=>{if(KP(e))return e;if(Array.isArray(e))return new Headers(e);if(typeof e==`object`&&e&&`values`in e&&KP(e.values))return e.values;if(typeof e==`object`&&e){let t=Object.entries(e).filter(([,e])=>typeof e==`string`).map(([e,t])=>[e,t]);return new Headers(t)}return new Headers});return Object.fromEntries(t.entries())}function JP(){let e=BS();return(e===`node`||e===`deno`)&&(e=`(${e}/${t.version}; ${t.platform}; ${t.arch})`),e}function YP(e,t=!1,n=`1.0.0`){let r=qP(e),i=JP(),a=`langchainjs${t?`-azure`:``}-openai`;return{...r,"User-Agent":r[`User-Agent`]?`${a}/${n} (${i})${r[`User-Agent`]}`:`${a}/${n} (${i})`}}function XP(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function ZP(e){return e!==void 0&&xP.isRunnable(e)&&`lc_name`in e.constructor&&typeof e.constructor.lc_name==`function`&&e.constructor.lc_name()===`RunnableToolLike`}function QP(e){return!!e&&typeof e==`object`&&`name`in e&&`schema`in e&&(rA(e.schema)||e.schema!=null&&typeof e.schema==`object`&&`type`in e.schema&&typeof e.schema.type==`string`&&[`null`,`boolean`,`object`,`array`,`number`,`string`].includes(e.schema.type))}function $P(e){return QP(e)||ZP(e)||XP(e)}function wae(e,t){let n=typeof t==`number`?void 0:t;return{name:e.name,description:e.description,parameters:aP(e.schema),...n?.strict===void 0?{}:{strict:n.strict}}}function Tae(e,t){let n=typeof t==`number`?void 0:t,r;return r=$P(e)?{type:`function`,function:wae(e)}:e,n?.strict!==void 0&&(r.function.strict=n.strict),r}function Eae(e,t){let n;return n=$P(e)?Tae(e):e,t?.strict!==void 0&&(n.function.strict=t.strict),n}function Dae(e){return e.anyOf!==void 0&&Array.isArray(e.anyOf)}function Oae(e){let t=[`namespace functions {`,``];for(let n of e)n.description&&t.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(t.push(`type ${n.name} = (_: {`),t.push(eF(n.parameters,0)),t.push(`}) => any;`)):t.push(`type ${n.name} = () => any;`),t.push(``);return t.push(`} // namespace functions`),t.join(`
|
|
119
119
|
`)}function eF(e,t){let n=[];for(let[r,i]of Object.entries(e.properties??{}))i.description&&t<2&&n.push(`// ${i.description}`),e.required?.includes(r)?n.push(`${r}: ${tF(i,t)},`):n.push(`${r}?: ${tF(i,t)},`);return n.map(e=>` `.repeat(t)+e).join(`
|
|
120
120
|
`)}function tF(e,t){if(Dae(e))return e.anyOf.map(e=>tF(e,t)).join(` | `);switch(e.type){case`string`:return e.enum?e.enum.map(e=>`"${e}"`).join(` | `):`string`;case`number`:return e.enum?e.enum.map(e=>`${e}`).join(` | `):`number`;case`integer`:return e.enum?e.enum.map(e=>`${e}`).join(` | `):`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`object`:return[`{`,eF(e,t+2),`}`].join(`
|
|
121
|
-
`);case`array`:return e.items?`${tF(e.items,t)}[]`:`any[]`;default:return``}}function nF(e){if(e)return e===`any`||e===`required`?`required`:e===`auto`?`auto`:e===`none`?`none`:typeof e==`string`?{type:`function`,function:{name:e}}:e}function rF(e){return`type`in e&&e.type!==`function`}function kae(e){return typeof e==`object`&&!!e&&`extras`in e&&typeof e.extras==`object`&&e.extras!==null&&`providerToolDefinition`in e.extras&&typeof e.extras.providerToolDefinition==`object`&&e.extras.providerToolDefinition!==null}function Aae(e){return typeof e==`object`&&!!e&&`type`in e&&e.type!==`function`}function iF(e){return typeof e==`object`&&!!e&&`metadata`in e&&typeof e.metadata==`object`&&e.metadata!==null&&`customTool`in e.metadata&&typeof e.metadata.customTool==`object`&&e.metadata.customTool!==null}function aF(e){return`type`in e&&e.type===`custom`&&`custom`in e&&typeof e.custom==`object`&&e.custom!==null}function jae(e){if(e.type===`custom_tool_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:e.name,isCustomTool:!0,args:{input:e.input}}}function Mae(e){if(e.type===`computer_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:`computer_use`,isComputerTool:!0,args:{action:e.action}}}function Nae(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_call`&&`isComputerTool`in e&&e.isComputerTool===!0}function Pae(e,t){return typeof e!=`object`||!e||!(`type`in e)||e.type!==`tool_call`?!1:!!(`isCustomTool`in e&&e.isCustomTool===!0||t&&`id`in e&&typeof e.id==`string`&&e.id in t)}function Fae(e){return{type:`custom`,name:e.custom.name,description:e.custom.description,format:(()=>{if(e.custom.format){if(e.custom.format.type===`grammar`)return{type:`grammar`,definition:e.custom.format.grammar.definition,syntax:e.custom.format.grammar.syntax};if(e.custom.format.type===`text`)return{type:`text`}}})()}}function Iae(e){return{type:`custom`,custom:{name:e.name,description:e.description,format:(()=>{if(e.format){if(e.format.type===`grammar`)return{type:`grammar`,grammar:{definition:e.format.definition,syntax:e.format.syntax}};if(e.format.type===`text`)return{type:`text`}}})()}}}var Lae=c((()=>{bm(),bm()})),oF=c((()=>{Lae()})),Rae=Symbol(`Let zodToJsonSchema decide on which parser to use`),sF={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`},zae=e=>typeof e==`string`?{...sF,basePath:[`#`],definitions:{},name:e}:{...sF,basePath:[`#`],definitions:{},...e},cF=e=>`_def`in e?e._def:e;function Bae(e){if(!e)return!0;for(let t in e)return!1;return!0}var Vae=e=>{let t=zae(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[cF(n),{def:cF(n),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function lF(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function uF(e,t,n,r,i){e[t]=n,lF(e,t,r,i)}function Hae(){return{}}wM();function Uae(e,t){let n={type:`array`};return e.type?._def?.typeName!==K.ZodAny&&(n.items=xF(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&uF(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&uF(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(uF(n,`minItems`,e.exactLength.value,e.exactLength.message,t),uF(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Wae(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?uF(n,`minimum`,r.value,r.message,t):uF(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),uF(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?uF(n,`maximum`,r.value,r.message,t):uF(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),uF(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:uF(n,`multipleOf`,r.value,r.message,t);break}return n}function Gae(){return{type:`boolean`}}function Kae(e,t,n){return xF(e.type._def,t,n)}var qae=(e,t,n)=>xF(e.innerType._def,t,n);function dF(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>dF(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Jae(e,t)}}var Jae=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:uF(n,`minimum`,r.value,r.message,t);break;case`max`:uF(n,`maximum`,r.value,r.message,t);break}return n};function Yae(e,t,n){return{...xF(e.innerType._def,t,n),default:e.defaultValue()}}function Xae(e,t,n){return t.effectStrategy===`input`?xF(e.schema._def,t,n):{}}function Zae(e){return{type:`string`,enum:[...e.values]}}var Qae=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function $ae(e,t){let n=[xF(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),xF(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Qae(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function eoe(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var fF,pF={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(fF===void 0&&(fF=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),fF),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function mF(e,t){let n={type:`string`};function r(e){return t.patternStrategy===`escape`?toe(e):e}if(e.checks)for(let i of e.checks)switch(i.kind){case`min`:uF(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t);break;case`max`:uF(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:hF(n,`email`,i.message,t);break;case`format:idn-email`:hF(n,`idn-email`,i.message,t);break;case`pattern:zod`:gF(n,pF.email,i.message,t);break}break;case`url`:hF(n,`uri`,i.message,t);break;case`uuid`:hF(n,`uuid`,i.message,t);break;case`regex`:gF(n,i.regex,i.message,t);break;case`cuid`:gF(n,pF.cuid,i.message,t);break;case`cuid2`:gF(n,pF.cuid2,i.message,t);break;case`startsWith`:gF(n,RegExp(`^${r(i.value)}`),i.message,t);break;case`endsWith`:gF(n,RegExp(`${r(i.value)}$`),i.message,t);break;case`datetime`:hF(n,`date-time`,i.message,t);break;case`date`:hF(n,`date`,i.message,t);break;case`time`:hF(n,`time`,i.message,t);break;case`duration`:hF(n,`duration`,i.message,t);break;case`length`:uF(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t),uF(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`includes`:gF(n,RegExp(r(i.value)),i.message,t);break;case`ip`:i.version!==`v6`&&hF(n,`ipv4`,i.message,t),i.version!==`v4`&&hF(n,`ipv6`,i.message,t);break;case`emoji`:gF(n,pF.emoji,i.message,t);break;case`ulid`:gF(n,pF.ulid,i.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:hF(n,`binary`,i.message,t);break;case`contentEncoding:base64`:uF(n,`contentEncoding`,`base64`,i.message,t);break;case`pattern:zod`:gF(n,pF.base64,i.message,t);break}break;case`nanoid`:gF(n,pF.nanoid,i.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return n}var toe=e=>Array.from(e).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(``),hF=(e,t,n,r)=>{e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):uF(e,`format`,t,n,r)},gF=(e,t,n,r)=>{e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:_F(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):uF(e,`pattern`,_F(t,r),n,r)},_F=(e,t)=>{let n=typeof e==`function`?e():e;if(!t.applyRegexFlags||!n.flags)return n.source;let r={i:n.flags.includes(`i`),m:n.flags.includes(`m`),s:n.flags.includes(`s`)},i=r.i?n.source.toLowerCase():n.source,a=``,o=!1,s=!1,c=!1;for(let e=0;e<i.length;e++){if(o){a+=i[e],o=!1;continue}if(r.i){if(s){if(i[e].match(/[a-z]/)){c?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),c=!1):i[e+1]===`-`&&i[e+2]?.match(/[a-z]/)?(a+=i[e],c=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}}if(r.m){if(i[e]===`^`){a+=`(^|(?<=[\r
|
|
121
|
+
`);case`array`:return e.items?`${tF(e.items,t)}[]`:`any[]`;default:return``}}function nF(e){if(e)return e===`any`||e===`required`?`required`:e===`auto`?`auto`:e===`none`?`none`:typeof e==`string`?{type:`function`,function:{name:e}}:e}function rF(e){return`type`in e&&e.type!==`function`}function kae(e){return typeof e==`object`&&!!e&&`extras`in e&&typeof e.extras==`object`&&e.extras!==null&&`providerToolDefinition`in e.extras&&typeof e.extras.providerToolDefinition==`object`&&e.extras.providerToolDefinition!==null}function Aae(e){return typeof e==`object`&&!!e&&`type`in e&&e.type!==`function`}function iF(e){return typeof e==`object`&&!!e&&`metadata`in e&&typeof e.metadata==`object`&&e.metadata!==null&&`customTool`in e.metadata&&typeof e.metadata.customTool==`object`&&e.metadata.customTool!==null}function aF(e){return`type`in e&&e.type===`custom`&&`custom`in e&&typeof e.custom==`object`&&e.custom!==null}function jae(e){if(e.type===`custom_tool_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:e.name,isCustomTool:!0,args:{input:e.input}}}function Mae(e){if(e.type===`computer_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:`computer_use`,isComputerTool:!0,args:{action:e.action}}}function Nae(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_call`&&`isComputerTool`in e&&e.isComputerTool===!0}function Pae(e,t){return typeof e!=`object`||!e||!(`type`in e)||e.type!==`tool_call`?!1:!!(`isCustomTool`in e&&e.isCustomTool===!0||t&&`id`in e&&typeof e.id==`string`&&e.id in t)}function Fae(e){return{type:`custom`,name:e.custom.name,description:e.custom.description,format:(()=>{if(e.custom.format){if(e.custom.format.type===`grammar`)return{type:`grammar`,definition:e.custom.format.grammar.definition,syntax:e.custom.format.grammar.syntax};if(e.custom.format.type===`text`)return{type:`text`}}})()}}function Iae(e){return{type:`custom`,custom:{name:e.name,description:e.description,format:(()=>{if(e.format){if(e.format.type===`grammar`)return{type:`grammar`,grammar:{definition:e.format.definition,syntax:e.format.syntax}};if(e.format.type===`text`)return{type:`text`}}})()}}}var Lae=c((()=>{bm(),bm()})),oF=c((()=>{Lae()})),Rae=Symbol(`Let zodToJsonSchema decide on which parser to use`),sF={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`},zae=e=>typeof e==`string`?{...sF,basePath:[`#`],definitions:{},name:e}:{...sF,basePath:[`#`],definitions:{},...e},cF=e=>`_def`in e?e._def:e;function Bae(e){if(!e)return!0;for(let t in e)return!1;return!0}var Vae=e=>{let t=zae(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[cF(n),{def:cF(n),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function lF(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function uF(e,t,n,r,i){e[t]=n,lF(e,t,r,i)}function Hae(){return{}}CM();function Uae(e,t){let n={type:`array`};return e.type?._def?.typeName!==K.ZodAny&&(n.items=xF(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&uF(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&uF(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(uF(n,`minItems`,e.exactLength.value,e.exactLength.message,t),uF(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Wae(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?uF(n,`minimum`,r.value,r.message,t):uF(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),uF(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?uF(n,`maximum`,r.value,r.message,t):uF(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),uF(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:uF(n,`multipleOf`,r.value,r.message,t);break}return n}function Gae(){return{type:`boolean`}}function Kae(e,t,n){return xF(e.type._def,t,n)}var qae=(e,t,n)=>xF(e.innerType._def,t,n);function dF(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>dF(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Jae(e,t)}}var Jae=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:uF(n,`minimum`,r.value,r.message,t);break;case`max`:uF(n,`maximum`,r.value,r.message,t);break}return n};function Yae(e,t,n){return{...xF(e.innerType._def,t,n),default:e.defaultValue()}}function Xae(e,t,n){return t.effectStrategy===`input`?xF(e.schema._def,t,n):{}}function Zae(e){return{type:`string`,enum:[...e.values]}}var Qae=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function $ae(e,t){let n=[xF(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),xF(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Qae(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function eoe(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var fF,pF={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(fF===void 0&&(fF=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),fF),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function mF(e,t){let n={type:`string`};function r(e){return t.patternStrategy===`escape`?toe(e):e}if(e.checks)for(let i of e.checks)switch(i.kind){case`min`:uF(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t);break;case`max`:uF(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:hF(n,`email`,i.message,t);break;case`format:idn-email`:hF(n,`idn-email`,i.message,t);break;case`pattern:zod`:gF(n,pF.email,i.message,t);break}break;case`url`:hF(n,`uri`,i.message,t);break;case`uuid`:hF(n,`uuid`,i.message,t);break;case`regex`:gF(n,i.regex,i.message,t);break;case`cuid`:gF(n,pF.cuid,i.message,t);break;case`cuid2`:gF(n,pF.cuid2,i.message,t);break;case`startsWith`:gF(n,RegExp(`^${r(i.value)}`),i.message,t);break;case`endsWith`:gF(n,RegExp(`${r(i.value)}$`),i.message,t);break;case`datetime`:hF(n,`date-time`,i.message,t);break;case`date`:hF(n,`date`,i.message,t);break;case`time`:hF(n,`time`,i.message,t);break;case`duration`:hF(n,`duration`,i.message,t);break;case`length`:uF(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t),uF(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`includes`:gF(n,RegExp(r(i.value)),i.message,t);break;case`ip`:i.version!==`v6`&&hF(n,`ipv4`,i.message,t),i.version!==`v4`&&hF(n,`ipv6`,i.message,t);break;case`emoji`:gF(n,pF.emoji,i.message,t);break;case`ulid`:gF(n,pF.ulid,i.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:hF(n,`binary`,i.message,t);break;case`contentEncoding:base64`:uF(n,`contentEncoding`,`base64`,i.message,t);break;case`pattern:zod`:gF(n,pF.base64,i.message,t);break}break;case`nanoid`:gF(n,pF.nanoid,i.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return n}var toe=e=>Array.from(e).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(``),hF=(e,t,n,r)=>{e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):uF(e,`format`,t,n,r)},gF=(e,t,n,r)=>{e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:_F(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):uF(e,`pattern`,_F(t,r),n,r)},_F=(e,t)=>{let n=typeof e==`function`?e():e;if(!t.applyRegexFlags||!n.flags)return n.source;let r={i:n.flags.includes(`i`),m:n.flags.includes(`m`),s:n.flags.includes(`s`)},i=r.i?n.source.toLowerCase():n.source,a=``,o=!1,s=!1,c=!1;for(let e=0;e<i.length;e++){if(o){a+=i[e],o=!1;continue}if(r.i){if(s){if(i[e].match(/[a-z]/)){c?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),c=!1):i[e+1]===`-`&&i[e+2]?.match(/[a-z]/)?(a+=i[e],c=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}}if(r.m){if(i[e]===`^`){a+=`(^|(?<=[\r
|
|
122
122
|
]))`;continue}else if(i[e]===`$`){a+=`($|(?=[\r
|
|
123
|
-
]))`;continue}}if(r.s&&i[e]===`.`){a+=s?`${i[e]}\r\n`:`[${i[e]}\r\n]`;continue}a+=i[e],i[e]===`\\`?o=!0:s&&i[e]===`]`?s=!1:!s&&i[e]===`[`&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a};wM();function vF(e,t){if(t.target===`openApi3`&&e.keyType?._def.typeName===K.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:xF(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??{}}),{}),additionalProperties:!1};let n={type:`object`,additionalProperties:xF(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??{}};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===K.ZodString&&e.keyType._def.checks?.length){let r=Object.entries(mF(e.keyType._def,t)).reduce((e,[t,n])=>t===`type`?e:{...e,[t]:n},{});return{...n,propertyNames:r}}else if(e.keyType?._def.typeName===K.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};return n}function noe(e,t){return t.mapStrategy===`record`?vF(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[xF(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||{},xF(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||{}],minItems:2,maxItems:2}}}function roe(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function ioe(){return{not:{}}}function aoe(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var yF={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function ooe(e,t){if(t.target===`openApi3`)return bF(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in yF&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=yF[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return bF(e,t)}var bF=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>xF(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function soe(e,t,n){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`||t.nullableStrategy===`property`?{type:yF[e.innerType._def.typeName],nullable:!0}:{type:[yF[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let r=xF(e.innerType._def,{...t,currentPath:[...t.currentPath]},n);return r&&`$ref`in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let r=xF(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return r&&{anyOf:[r,{type:`null`}]}}function coe(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,lF(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?uF(n,`minimum`,r.value,r.message,t):uF(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),uF(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?uF(n,`maximum`,r.value,r.message,t):uF(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),uF(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:uF(n,`multipleOf`,r.value,r.message,t);break}return n}function loe(e,t){return t.removeAdditionalStrategy===`strict`?e.catchall._def.typeName===`ZodNever`?e.unknownKeys!==`strict`:xF(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0:e.catchall._def.typeName===`ZodNever`?e.unknownKeys===`passthrough`:xF(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0}function uoe(e,t){let n={type:`object`,...Object.entries(e.shape()).reduce((e,[n,r])=>{if(r===void 0||r._def===void 0)return e;let i=[...t.currentPath,`properties`,n],a=xF(r._def,{...t,currentPath:i,propertyPath:i});if(a===void 0)return e;if(t.openaiStrictMode&&r.isOptional()&&!r.isNullable()&&r._def?.defaultValue===void 0)throw Error(`Zod field at \`${i.join(`/`)}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...e.properties,[n]:a},required:r.isOptional()&&!t.openaiStrictMode?e.required:[...e.required,n]}},{properties:{},required:[]}),additionalProperties:loe(e,t)};return n.required.length||delete n.required,n}var doe=(e,t,n)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return xF(e.innerType._def,{...t,currentPath:t.currentPath},n);let r=xF(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]},n);return r?{anyOf:[{not:{}},r]}:{}},foe=(e,t,n)=>{if(t.pipeStrategy===`input`)return xF(e.in._def,t,n);if(t.pipeStrategy===`output`)return xF(e.out._def,t,n);let r=xF(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[r,xF(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,r?`1`:`0`]})].filter(e=>e!==void 0)}};function poe(e,t,n){return xF(e.type._def,t,n)}function moe(e,t){let n={type:`array`,uniqueItems:!0,items:xF(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&uF(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&uF(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function hoe(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>xF(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:xF(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>xF(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function goe(){return{not:{}}}function _oe(){return{}}var voe=(e,t,n)=>xF(e.innerType._def,t,n);wM();function xF(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==Rae)return i}if(r&&!n){let e=yoe(r,t);if(e!==void 0)return`$ref`in e&&t.seenRefs.add(e.$ref),e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);try{let r=Soe(e,e.typeName,t,n);return r&&Coe(e,t,r),i.jsonSchema=r,r}finally{n&&r&&t.seen.set(e,r)}}var yoe=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`extract-to-root`:let n=e.path.slice(t.basePath.length+1).map((e,t)=>t===0?e:boe(e)).join(`_`);return n!==t.name&&t.nameStrategy===`duplicate-ref`&&(t.definitions[n]=e.def),{$ref:[...t.basePath,t.definitionPath,n].join(`/`)};case`relative`:return{$ref:xoe(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),{}):t.$refStrategy===`seen`?{}:void 0}},SF=`_x_`,boe=e=>{if(/^[A-Za-z0-9_-]*$/.test(e)&&!e.startsWith(SF))return e;let t=SF;for(let n=0;n<e.length;n++)t+=e.charCodeAt(n).toString(16).padStart(4,`0`);return t},xoe=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)},Soe=(e,t,n,r)=>{switch(t){case K.ZodString:return mF(e,n);case K.ZodNumber:return coe(e,n);case K.ZodObject:return uoe(e,n);case K.ZodBigInt:return Wae(e,n);case K.ZodBoolean:return Gae();case K.ZodDate:return dF(e,n);case K.ZodUndefined:return goe();case K.ZodNull:return aoe(n);case K.ZodArray:return Uae(e,n);case K.ZodUnion:case K.ZodDiscriminatedUnion:return ooe(e,n);case K.ZodIntersection:return $ae(e,n);case K.ZodTuple:return hoe(e,n);case K.ZodRecord:return vF(e,n);case K.ZodLiteral:return eoe(e,n);case K.ZodEnum:return Zae(e);case K.ZodNativeEnum:return roe(e);case K.ZodNullable:return soe(e,n,r);case K.ZodOptional:return doe(e,n,r);case K.ZodMap:return noe(e,n);case K.ZodSet:return moe(e,n);case K.ZodLazy:return xF(e.getter()._def,n,r);case K.ZodPromise:return poe(e,n,r);case K.ZodNaN:case K.ZodNever:return ioe();case K.ZodEffects:return Xae(e,n,r);case K.ZodAny:return Hae();case K.ZodUnknown:return _oe();case K.ZodDefault:return Yae(e,n,r);case K.ZodBranded:return Kae(e,n,r);case K.ZodReadonly:return voe(e,n,r);case K.ZodCatch:return qae(e,n,r);case K.ZodPipeline:return foe(e,n,r);case K.ZodFunction:case K.ZodVoid:case K.ZodSymbol:return;default:return(e=>void 0)(t)}},Coe=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),woe=(e,t)=>{let n=Vae(t),r=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,i=xF(e._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},a=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;a!==void 0&&(i.title=a);let o=(()=>{if(Bae(n.definitions))return;let e={},t=new Set;for(let r=0;r<500;r++){let r=Object.entries(n.definitions).filter(([e])=>!t.has(e));if(r.length===0)break;for(let[i,a]of r)e[i]=xF(cF(a),{...n,currentPath:[...n.basePath,n.definitionPath,i]},!0)??{},t.add(i)}return e})(),s=r===void 0?o?{...i,[n.definitionPath]:o}:i:n.nameStrategy===`duplicate-ref`?{...i,...o||n.seenRefs.size?{[n.definitionPath]:{...o,...n.seenRefs.size?{[r]:i}:void 0}}:void 0}:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,r].join(`/`),[n.definitionPath]:{...o,[r]:i}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:n.target===`jsonSchema2019-09`&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),s};oF();function Toe(e){if(e.type!==`object`)throw Error(`Root schema must have type: 'object' but got type: ${e.type?`'${e.type}'`:`undefined`}`);let t=structuredClone(e);return wF(t,[],t)}function CF(e){if(typeof e==`boolean`)return!1;if(e.type===`null`)return!0;for(let t of e.oneOf??[])if(CF(t))return!0;for(let t of e.anyOf??[])if(CF(t))return!0;return!1}function wF(e,t,n){if(typeof e==`boolean`)throw TypeError(`Expected object schema but got boolean; path=${t.join(`/`)}`);if(!TF(e))throw TypeError(`Expected ${JSON.stringify(e)} to be an object; path=${t.join(`/`)}`);let r=e.$defs;if(TF(r))for(let[e,i]of Object.entries(r))wF(i,[...t,`$defs`,e],n);let i=e.definitions;if(TF(i))for(let[e,r]of Object.entries(i))wF(r,[...t,`definitions`,e],n);e.type===`object`&&!(`additionalProperties`in e)&&(e.additionalProperties=!1);let a=e.required??[],o=e.properties;if(TF(o)){for(let[e,n]of Object.entries(o))if(!CF(n)&&!a.includes(e))throw Error(`Zod field at \`${[...t,`properties`,e].join(`/`)}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);e.required=Object.keys(o),e.properties=Object.fromEntries(Object.entries(o).map(([e,r])=>[e,wF(r,[...t,`properties`,e],n)]))}let s=e.items;TF(s)&&(e.items=wF(s,[...t,`items`],n));let c=e.anyOf;Array.isArray(c)&&(e.anyOf=c.map((e,r)=>wF(e,[...t,`anyOf`,String(r)],n)));let l=e.allOf;if(Array.isArray(l))if(l.length===1){let r=wF(l[0],[...t,`allOf`,`0`],n);Object.assign(e,r),delete e.allOf}else e.allOf=l.map((e,r)=>wF(e,[...t,`allOf`,String(r)],n));e.default===null&&delete e.default;let u=e.$ref;if(u&&Doe(e,1)){if(typeof u!=`string`)throw TypeError(`Received non-string $ref - ${u}; path=${t.join(`/`)}`);let r=Eoe(n,u);if(typeof r==`boolean`)throw Error(`Expected \`$ref: ${u}\` to resolve to an object schema but got boolean`);if(!TF(r))throw Error(`Expected \`$ref: ${u}\` to resolve to an object but got ${JSON.stringify(r)}`);return Object.assign(e,{...r,...e}),delete e.$ref,wF(e,t,n)}return e}function Eoe(e,t){if(!t.startsWith(`#/`))throw Error(`Unexpected $ref format ${JSON.stringify(t)}; Does not start with #/`);let n=t.slice(2).split(`/`),r=e;for(let e of n){if(!TF(r))throw Error(`encountered non-object entry while resolving ${t} - ${JSON.stringify(r)}`);let n=r[e];if(n===void 0)throw Error(`Key ${e} not found while resolving ${t}`);r=n}return r}function TF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Doe(e,t){let n=0;for(let r in e)if(n++,n>t)return!0;return!1}function Ooe(e,t){return woe(e,{openaiStrictMode:!0,name:t.name,nameStrategy:`duplicate-ref`,$refStrategy:`extract-to-root`,nullableStrategy:`property`})}function koe(e){return Toe(Nl(e,{target:`draft-7`,override:({zodSchema:e,jsonSchema:t})=>{let n=e._zod.def;if(n.type===`union`&&`discriminator`in n&&Array.isArray(t.oneOf)){if(t.anyOf!==void 0)throw Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");t.anyOf=t.oneOf,delete t.oneOf}}}))}function Aoe(e){return`_zod`in e}function joe(e,t,n){return Ste({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:Aoe(e)?koe(e):Ooe(e,{name:t})}},t=>e.parse(JSON.parse(t)))}Du();var EF=[`jsonSchema`,`functionCalling`,`jsonMode`];function Moe(e,t){if(t!==void 0&&!EF.includes(t))throw Error(`Invalid method: ${t}. Supported methods are: ${EF.join(`, `)}`);let n=!e.startsWith(`gpt-3`)&&!e.startsWith(`gpt-4-`)&&e!==`gpt-4`;if(n&&!t)return`jsonSchema`;if(!n&&t===`jsonSchema`)throw Error(`JSON Schema is not supported for model "${e}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return t??`functionCalling`}function Noe(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function Poe(e,t,n){if(rA(e))return joe(e,t,n);if(nA(e))return Noe({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:oP(e,{cycles:`ref`,reused:`ref`,override(e){e.jsonSchema.title=t}})}},t=>ft(e,JSON.parse(t)));throw Error(`Unsupported schema response format`)}function Foe(e,t){if(t&&typeof t==`object`&&`images`in t&&Array.isArray(t.images)){let n=t.images.filter(e=>typeof e?.image_url?.url==`string`).map(e=>({type:`image`,url:e.image_url.url}));return[{type:`text`,text:e},...n]}return e}var Ioe={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}},DF=`0123456789abcdef`.split(``),Loe=[-2147483648,8388608,32768,128],OF=[24,16,8,0],kF=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],AF=[];function jF(e,t){t?(AF[0]=AF[16]=AF[1]=AF[2]=AF[3]=AF[4]=AF[5]=AF[6]=AF[7]=AF[8]=AF[9]=AF[10]=AF[11]=AF[12]=AF[13]=AF[14]=AF[15]=0,this.blocks=AF):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}jF.prototype.update=function(e){if(!this.finalized){var t,n=typeof e;if(n!==`string`){if(n===`object`){if(e===null)throw Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw Error(ERROR)}else throw Error(ERROR);t=!0}for(var r,i=0,a,o=e.length,s=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,s[0]=this.block,this.block=s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),t)for(a=this.start;i<o&&a<64;++i)s[a>>>2]|=e[i]<<OF[a++&3];else for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<OF[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<OF[a++&3],s[a>>>2]|=(128|r&63)<<OF[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<OF[a++&3],s[a>>>2]|=(128|r>>>6&63)<<OF[a++&3],s[a>>>2]|=(128|r&63)<<OF[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<OF[a++&3],s[a>>>2]|=(128|r>>>12&63)<<OF[a++&3],s[a>>>2]|=(128|r>>>6&63)<<OF[a++&3],s[a>>>2]|=(128|r&63)<<OF[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=s[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes%=4294967296),this}},jF.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=Loe[t&3],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()}},jF.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=this.blocks,l,u,d,f,p,m,h,g,_,v,y;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(y=t&n,l=0;l<64;l+=4)this.first?(this.is224?(g=300032,p=c[0]-1413257819,s=p-150054599<<0,r=p+24177077<<0):(g=704751109,p=c[0]-210244248,s=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),g=e&t,f=g^e&n^y,h=i&a^~i&o,p=s+d+h+kF[l]+c[l],m=u+f,s=r+p<<0,r=p+m<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),_=r&e,f=_^r&t^g,h=o&s^~o&i,p=a+d+h+kF[l+1]+c[l+1],m=u+f,o=n+p<<0,n=p+m<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=n&r,f=v^n&e^_,h=a&o^~a&s,p=i+d+h+kF[l+2]+c[l+2],m=u+f,a=t+p<<0,t=p+m<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),y=t&n,f=y^t&r^v,h=a&o^~a&s,p=i+d+h+kF[l+3]+c[l+3],m=u+f,i=e+p<<0,e=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+o<<0,this.h7=this.h7+s<<0},jF.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=DF[e>>>28&15]+DF[e>>>24&15]+DF[e>>>20&15]+DF[e>>>16&15]+DF[e>>>12&15]+DF[e>>>8&15]+DF[e>>>4&15]+DF[e&15]+DF[t>>>28&15]+DF[t>>>24&15]+DF[t>>>20&15]+DF[t>>>16&15]+DF[t>>>12&15]+DF[t>>>8&15]+DF[t>>>4&15]+DF[t&15]+DF[n>>>28&15]+DF[n>>>24&15]+DF[n>>>20&15]+DF[n>>>16&15]+DF[n>>>12&15]+DF[n>>>8&15]+DF[n>>>4&15]+DF[n&15]+DF[r>>>28&15]+DF[r>>>24&15]+DF[r>>>20&15]+DF[r>>>16&15]+DF[r>>>12&15]+DF[r>>>8&15]+DF[r>>>4&15]+DF[r&15]+DF[i>>>28&15]+DF[i>>>24&15]+DF[i>>>20&15]+DF[i>>>16&15]+DF[i>>>12&15]+DF[i>>>8&15]+DF[i>>>4&15]+DF[i&15]+DF[a>>>28&15]+DF[a>>>24&15]+DF[a>>>20&15]+DF[a>>>16&15]+DF[a>>>12&15]+DF[a>>>8&15]+DF[a>>>4&15]+DF[a&15]+DF[o>>>28&15]+DF[o>>>24&15]+DF[o>>>20&15]+DF[o>>>16&15]+DF[o>>>12&15]+DF[o>>>8&15]+DF[o>>>4&15]+DF[o&15];return this.is224||(c+=DF[s>>>28&15]+DF[s>>>24&15]+DF[s>>>20&15]+DF[s>>>16&15]+DF[s>>>12&15]+DF[s>>>8&15]+DF[s>>>4&15]+DF[s&15]),c},jF.prototype.toString=jF.prototype.hex,jF.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(s>>>24&255,s>>>16&255,s>>>8&255,s&255),c},jF.prototype.array=jF.prototype.digest,jF.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),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),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};var Roe=(...e)=>new jF(!1,!0).update(e.join(``)).hex(),zoe=(...e)=>Roe(e.join(`_`)),Boe=class{keyEncoder=zoe;makeDefaultKeyEncoder(e){this.keyEncoder=e}},Voe=new Map,Hoe=class e extends Boe{cache;constructor(e){super(),this.cache=e??new Map}lookup(e,t){return Promise.resolve(this.cache.get(this.keyEncoder(e,t))??null)}async update(e,t,n){this.cache.set(this.keyEncoder(e,t),n)}static global(){return new e(Voe)}},MF=class extends ox{},Uoe=class extends MF{static lc_name(){return`StringPromptValue`}lc_namespace=[`langchain_core`,`prompt_values`];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new pS(this.value)]}},Woe=class extends MF{lc_namespace=[`langchain_core`,`prompt_values`];lc_serializable=!0;static lc_name(){return`ChatPromptValue`}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return yS(this.messages)}toChatMessages(){return this.messages}},Goe=f(l((e=>{e.toByteArray=l;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e,t,n){return(t+n)*3/4-n}function l(e){var t,i=s(e),a=i[0],o=i[1],l=new r(c(e,a,o)),u=0,d=o>0?a-4:a,f;for(f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],l[u++]=t>>16&255,l[u++]=t>>8&255,l[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,l[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,l[u++]=t>>8&255,l[u++]=t&255),l}}))(),1),Koe=Object.defineProperty,qoe=(e,t,n)=>t in e?Koe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Joe=(e,t,n)=>(qoe(e,typeof t==`symbol`?t:t+``,n),n);function Yoe(e,t){let n=Array.from({length:e.length},(e,t)=>({start:t,end:t+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){let a=e.slice(n[i].start,n[i+1].end),o=t.get(a.join(`,`));o!=null&&(r==null||o<r[0])&&(r=[o,i])}if(r!=null){let e=r[1];n[e]={start:n[e].start,end:n[e+1].end},n.splice(e+1,1)}else break}return n}function Xoe(e,t){return e.length===1?[t.get(e.join(`,`))]:Yoe(e,t).map(n=>t.get(e.slice(n.start,n.end).join(`,`))).filter(e=>e!=null)}function Zoe(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,`\\$&`)}var NF=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;let n=e.bpe_ranks.split(`
|
|
124
|
-
`).filter(Boolean).reduce((e,t)=>{let[n,r,...i]=t.split(` `),a=Number.parseInt(r,10);return i.forEach((t,n)=>e[t]=a+n),e},{});for(let[e,t]of Object.entries(n)){let n=Goe.toByteArray(e);this.rankMap.set(n.join(`,`),t),this.textMap.set(t,n)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((e,[t,n])=>(e[n]=this.textEncoder.encode(t),e),{})}encode(e,t=[],n=`all`){let r=new RegExp(this.patStr,`ug`),i=NF.specialTokenRegex(Object.keys(this.specialTokens)),a=[],o=new Set(t===`all`?Object.keys(this.specialTokens):t),s=new Set(n===`all`?Object.keys(this.specialTokens).filter(e=>!o.has(e)):n);if(s.size>0){let t=NF.specialTokenRegex([...s]),n=e.match(t);if(n!=null)throw Error(`The text contains a special token that is not allowed: ${n[0]}`)}let c=0;for(;;){let t=null,n=c;for(;i.lastIndex=n,t=i.exec(e),!(t==null||o.has(t[0]));)n=t.index+1;let s=t?.index??e.length;for(let t of e.substring(c,s).matchAll(r)){let e=this.textEncoder.encode(t[0]),n=this.rankMap.get(e.join(`,`));if(n!=null){a.push(n);continue}a.push(...Xoe(e,this.rankMap))}if(t==null)break;let l=this.specialTokens[t[0]];a.push(l),c=t.index+t[0].length}return a}decode(e){let t=[],n=0;for(let r=0;r<e.length;++r){let i=e[r],a=this.textMap.get(i)??this.inverseSpecialTokens[i];a!=null&&(t.push(a),n+=a.length)}let r=new Uint8Array(n),i=0;for(let e of t)r.set(e,i),i+=e.length;return this.textDecoder.decode(r)}},PF=NF;Joe(PF,`specialTokenRegex`,e=>new RegExp(e.map(e=>Zoe(e)).join(`|`),`g`));function Qoe(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`:case`gpt-5`:case`gpt-5-2025-08-07`:case`gpt-5-nano`:case`gpt-5-nano-2025-08-07`:case`gpt-5-mini`:case`gpt-5-mini-2025-08-07`:case`gpt-5-chat-latest`:return`o200k_base`;default:throw Error(`Unknown model`)}}var FF={},$oe=new Zk({});async function ese(e){return e in FF||(FF[e]=$oe.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(e=>e.json()).then(e=>new PF(e)).catch(t=>{throw delete FF[e],t})),await FF[e]}async function tse(e){return ese(Qoe(e))}var nse=e=>e.startsWith(`gpt-5`)?`gpt-5`: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;function IF(e){return typeof e!=`object`||!e?!1:!!(`type`in e&&e.type===`function`&&`function`in e&&typeof e.function==`object`&&e.function&&`name`in e.function&&`parameters`in e.function)}var rse=()=>!1,LF=class extends SP{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??rse(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion(`@langchain/core`,`1.2.5`)}_addVersion(e,t){let n=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof n==`object`&&n?n:{},[e]:t}}}},ise=class extends LF{get callKeys(){return[`stop`,`timeout`,`signal`,`tags`,`metadata`,`callbacks`]}caller;cache;constructor({callbacks:e,callbackManager:t,...n}){let{cache:r,...i}=n;super({callbacks:e??t,...i}),typeof r==`object`?this.cache=r:r?this.cache=Hoe.global():this.cache=void 0,this.caller=new Zk(n??{})}_encoding;async getNumTokens(e){let t;t=typeof e==`string`?e:e.map(e=>typeof e==`string`?e:e.type===`text`&&`text`in e?e.text:``).join(``);let n=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await tse(`modelName`in this?nse(this.modelName):`gpt2`)}catch(e){console.warn(`Failed to calculate number of tokens, falling back to approximate count`,e)}if(this._encoding)try{n=this._encoding.encode(t).length}catch(e){console.warn(`Failed to calculate number of tokens, falling back to approximate count`,e)}return n}static _convertInputToPromptValue(e){return typeof e==`string`?new Uoe(e):Array.isArray(e)?new Woe(e.map(vS)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){let n={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>`${e}:${JSON.stringify(t)}`).sort().join(`,`)}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw Error(`Use .toJSON() instead`)}get profile(){return{}}_filterInvocationParamsForTracing(e){let{tools:t,functions:n,messages:r,response_format:i,...a}=e;return a}},ase=e=>e();function RF(e){let t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:`v1`}})}var zF=class extends SP{static lc_name(){return`RunnablePassthrough`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){let n=$O(t);return this.func&&await this.func(e,n),this._callWithConfig(e=>Promise.resolve(e),e,n)}async*transform(e,t){let n=$O(t),r,i=!0;for await(let t of this._transformStreamWithConfig(e,e=>e,n))if(yield t,i)if(r===void 0)r=t;else try{r=ok(r,t)}catch{r=void 0,i=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new MP(new EP({steps:e}))}},ose=class extends SP{parseResultWithPrompt(e,t,n){return this.parseResult(e,n)}_baseMessageToString(e){return typeof e.content==`string`?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e==`string`?this._callWithConfig(async(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`})}},BF=class extends ose{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,n){return this.parse(e,n)}_type(){throw Error(`_type not implemented`)}},VF=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,n,r=!1){if(super(e),this.llmOutput=t,this.observation=n,this.sendToLLM=r,r&&(n===void 0||t===void 0))throw Error(`Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true`);kb(this,`OUTPUT_PARSING_FAILURE`)}},sse=class extends BF{async*_transform(e){for await(let t of e)typeof t==`string`?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:`parser`})}},HF=class extends sse{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,n;for await(let r of e){if(typeof r!=`string`&&typeof r.content!=`string`)throw Error(`Cannot handle non-string output.`);let e;if(Wte(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new jk({message:r,text:r.content})}else if(Gx(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new jk({message:gne(r),text:r.content})}else e=new Ak({text:r});n=n===void 0?e:n.concat(e);let i=await this.parsePartialResult([n]);i!=null&&!SN(i,t)&&(this.diff?yield this._diff(t,i):yield i,t=i)}}getFormatInstructions(){return``}},UF=class extends HF{static lc_name(){return`JsonOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`];lc_serializable=!0;_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?uae(e,t):[{op:`replace`,path:``,value:t}]}async parsePartialResult(e){return cS(e[0].text)}async parse(e){return cS(e,JSON.parse)}getFormatInstructions(){return``}_baseMessageToString(e){return e.text}},cse=class extends BF{static lc_name(){return`StandardSchemaOutputParser`}lc_namespace=[`langchain`,`output_parsers`,`standard_schema`];schema;constructor(e){super(),this.schema=e}static fromSerializableSchema(e){return new this(e)}async parse(e){try{let t=cS(e,JSON.parse),n=await this.schema[`~standard`].validate(t);if(n.issues)throw Error(`Validation failed: ${JSON.stringify(n.issues)}`);return n.value}catch(t){throw new VF(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}getFormatInstructions(){return``}};wM();var lse=class extends BF{schema;static lc_name(){return`StructuredOutputParser`}lc_namespace=[`langchain`,`output_parsers`,`structured`];toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),this.schema=e}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let t=xM(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,yM().describe(t)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
|
|
123
|
+
]))`;continue}}if(r.s&&i[e]===`.`){a+=s?`${i[e]}\r\n`:`[${i[e]}\r\n]`;continue}a+=i[e],i[e]===`\\`?o=!0:s&&i[e]===`]`?s=!1:!s&&i[e]===`[`&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a};CM();function vF(e,t){if(t.target===`openApi3`&&e.keyType?._def.typeName===K.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:xF(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??{}}),{}),additionalProperties:!1};let n={type:`object`,additionalProperties:xF(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??{}};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===K.ZodString&&e.keyType._def.checks?.length){let r=Object.entries(mF(e.keyType._def,t)).reduce((e,[t,n])=>t===`type`?e:{...e,[t]:n},{});return{...n,propertyNames:r}}else if(e.keyType?._def.typeName===K.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};return n}function noe(e,t){return t.mapStrategy===`record`?vF(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[xF(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||{},xF(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||{}],minItems:2,maxItems:2}}}function roe(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function ioe(){return{not:{}}}function aoe(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var yF={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function ooe(e,t){if(t.target===`openApi3`)return bF(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in yF&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=yF[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return bF(e,t)}var bF=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>xF(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function soe(e,t,n){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`||t.nullableStrategy===`property`?{type:yF[e.innerType._def.typeName],nullable:!0}:{type:[yF[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let r=xF(e.innerType._def,{...t,currentPath:[...t.currentPath]},n);return r&&`$ref`in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let r=xF(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return r&&{anyOf:[r,{type:`null`}]}}function coe(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,lF(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?uF(n,`minimum`,r.value,r.message,t):uF(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),uF(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?uF(n,`maximum`,r.value,r.message,t):uF(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),uF(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:uF(n,`multipleOf`,r.value,r.message,t);break}return n}function loe(e,t){return t.removeAdditionalStrategy===`strict`?e.catchall._def.typeName===`ZodNever`?e.unknownKeys!==`strict`:xF(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0:e.catchall._def.typeName===`ZodNever`?e.unknownKeys===`passthrough`:xF(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0}function uoe(e,t){let n={type:`object`,...Object.entries(e.shape()).reduce((e,[n,r])=>{if(r===void 0||r._def===void 0)return e;let i=[...t.currentPath,`properties`,n],a=xF(r._def,{...t,currentPath:i,propertyPath:i});if(a===void 0)return e;if(t.openaiStrictMode&&r.isOptional()&&!r.isNullable()&&r._def?.defaultValue===void 0)throw Error(`Zod field at \`${i.join(`/`)}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...e.properties,[n]:a},required:r.isOptional()&&!t.openaiStrictMode?e.required:[...e.required,n]}},{properties:{},required:[]}),additionalProperties:loe(e,t)};return n.required.length||delete n.required,n}var doe=(e,t,n)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return xF(e.innerType._def,{...t,currentPath:t.currentPath},n);let r=xF(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]},n);return r?{anyOf:[{not:{}},r]}:{}},foe=(e,t,n)=>{if(t.pipeStrategy===`input`)return xF(e.in._def,t,n);if(t.pipeStrategy===`output`)return xF(e.out._def,t,n);let r=xF(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[r,xF(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,r?`1`:`0`]})].filter(e=>e!==void 0)}};function poe(e,t,n){return xF(e.type._def,t,n)}function moe(e,t){let n={type:`array`,uniqueItems:!0,items:xF(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&uF(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&uF(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function hoe(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>xF(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:xF(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>xF(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function goe(){return{not:{}}}function _oe(){return{}}var voe=(e,t,n)=>xF(e.innerType._def,t,n);CM();function xF(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==Rae)return i}if(r&&!n){let e=yoe(r,t);if(e!==void 0)return`$ref`in e&&t.seenRefs.add(e.$ref),e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);try{let r=Soe(e,e.typeName,t,n);return r&&Coe(e,t,r),i.jsonSchema=r,r}finally{n&&r&&t.seen.set(e,r)}}var yoe=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`extract-to-root`:let n=e.path.slice(t.basePath.length+1).map((e,t)=>t===0?e:boe(e)).join(`_`);return n!==t.name&&t.nameStrategy===`duplicate-ref`&&(t.definitions[n]=e.def),{$ref:[...t.basePath,t.definitionPath,n].join(`/`)};case`relative`:return{$ref:xoe(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),{}):t.$refStrategy===`seen`?{}:void 0}},SF=`_x_`,boe=e=>{if(/^[A-Za-z0-9_-]*$/.test(e)&&!e.startsWith(SF))return e;let t=SF;for(let n=0;n<e.length;n++)t+=e.charCodeAt(n).toString(16).padStart(4,`0`);return t},xoe=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)},Soe=(e,t,n,r)=>{switch(t){case K.ZodString:return mF(e,n);case K.ZodNumber:return coe(e,n);case K.ZodObject:return uoe(e,n);case K.ZodBigInt:return Wae(e,n);case K.ZodBoolean:return Gae();case K.ZodDate:return dF(e,n);case K.ZodUndefined:return goe();case K.ZodNull:return aoe(n);case K.ZodArray:return Uae(e,n);case K.ZodUnion:case K.ZodDiscriminatedUnion:return ooe(e,n);case K.ZodIntersection:return $ae(e,n);case K.ZodTuple:return hoe(e,n);case K.ZodRecord:return vF(e,n);case K.ZodLiteral:return eoe(e,n);case K.ZodEnum:return Zae(e);case K.ZodNativeEnum:return roe(e);case K.ZodNullable:return soe(e,n,r);case K.ZodOptional:return doe(e,n,r);case K.ZodMap:return noe(e,n);case K.ZodSet:return moe(e,n);case K.ZodLazy:return xF(e.getter()._def,n,r);case K.ZodPromise:return poe(e,n,r);case K.ZodNaN:case K.ZodNever:return ioe();case K.ZodEffects:return Xae(e,n,r);case K.ZodAny:return Hae();case K.ZodUnknown:return _oe();case K.ZodDefault:return Yae(e,n,r);case K.ZodBranded:return Kae(e,n,r);case K.ZodReadonly:return voe(e,n,r);case K.ZodCatch:return qae(e,n,r);case K.ZodPipeline:return foe(e,n,r);case K.ZodFunction:case K.ZodVoid:case K.ZodSymbol:return;default:return(e=>void 0)(t)}},Coe=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),woe=(e,t)=>{let n=Vae(t),r=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,i=xF(e._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},a=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;a!==void 0&&(i.title=a);let o=(()=>{if(Bae(n.definitions))return;let e={},t=new Set;for(let r=0;r<500;r++){let r=Object.entries(n.definitions).filter(([e])=>!t.has(e));if(r.length===0)break;for(let[i,a]of r)e[i]=xF(cF(a),{...n,currentPath:[...n.basePath,n.definitionPath,i]},!0)??{},t.add(i)}return e})(),s=r===void 0?o?{...i,[n.definitionPath]:o}:i:n.nameStrategy===`duplicate-ref`?{...i,...o||n.seenRefs.size?{[n.definitionPath]:{...o,...n.seenRefs.size?{[r]:i}:void 0}}:void 0}:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,r].join(`/`),[n.definitionPath]:{...o,[r]:i}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:n.target===`jsonSchema2019-09`&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),s};oF();function Toe(e){if(e.type!==`object`)throw Error(`Root schema must have type: 'object' but got type: ${e.type?`'${e.type}'`:`undefined`}`);let t=structuredClone(e);return wF(t,[],t)}function CF(e){if(typeof e==`boolean`)return!1;if(e.type===`null`)return!0;for(let t of e.oneOf??[])if(CF(t))return!0;for(let t of e.anyOf??[])if(CF(t))return!0;return!1}function wF(e,t,n){if(typeof e==`boolean`)throw TypeError(`Expected object schema but got boolean; path=${t.join(`/`)}`);if(!TF(e))throw TypeError(`Expected ${JSON.stringify(e)} to be an object; path=${t.join(`/`)}`);let r=e.$defs;if(TF(r))for(let[e,i]of Object.entries(r))wF(i,[...t,`$defs`,e],n);let i=e.definitions;if(TF(i))for(let[e,r]of Object.entries(i))wF(r,[...t,`definitions`,e],n);e.type===`object`&&!(`additionalProperties`in e)&&(e.additionalProperties=!1);let a=e.required??[],o=e.properties;if(TF(o)){for(let[e,n]of Object.entries(o))if(!CF(n)&&!a.includes(e))throw Error(`Zod field at \`${[...t,`properties`,e].join(`/`)}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);e.required=Object.keys(o),e.properties=Object.fromEntries(Object.entries(o).map(([e,r])=>[e,wF(r,[...t,`properties`,e],n)]))}let s=e.items;TF(s)&&(e.items=wF(s,[...t,`items`],n));let c=e.anyOf;Array.isArray(c)&&(e.anyOf=c.map((e,r)=>wF(e,[...t,`anyOf`,String(r)],n)));let l=e.allOf;if(Array.isArray(l))if(l.length===1){let r=wF(l[0],[...t,`allOf`,`0`],n);Object.assign(e,r),delete e.allOf}else e.allOf=l.map((e,r)=>wF(e,[...t,`allOf`,String(r)],n));e.default===null&&delete e.default;let u=e.$ref;if(u&&Doe(e,1)){if(typeof u!=`string`)throw TypeError(`Received non-string $ref - ${u}; path=${t.join(`/`)}`);let r=Eoe(n,u);if(typeof r==`boolean`)throw Error(`Expected \`$ref: ${u}\` to resolve to an object schema but got boolean`);if(!TF(r))throw Error(`Expected \`$ref: ${u}\` to resolve to an object but got ${JSON.stringify(r)}`);return Object.assign(e,{...r,...e}),delete e.$ref,wF(e,t,n)}return e}function Eoe(e,t){if(!t.startsWith(`#/`))throw Error(`Unexpected $ref format ${JSON.stringify(t)}; Does not start with #/`);let n=t.slice(2).split(`/`),r=e;for(let e of n){if(!TF(r))throw Error(`encountered non-object entry while resolving ${t} - ${JSON.stringify(r)}`);let n=r[e];if(n===void 0)throw Error(`Key ${e} not found while resolving ${t}`);r=n}return r}function TF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Doe(e,t){let n=0;for(let r in e)if(n++,n>t)return!0;return!1}function Ooe(e,t){return woe(e,{openaiStrictMode:!0,name:t.name,nameStrategy:`duplicate-ref`,$refStrategy:`extract-to-root`,nullableStrategy:`property`})}function koe(e){return Toe(Nl(e,{target:`draft-7`,override:({zodSchema:e,jsonSchema:t})=>{let n=e._zod.def;if(n.type===`union`&&`discriminator`in n&&Array.isArray(t.oneOf)){if(t.anyOf!==void 0)throw Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");t.anyOf=t.oneOf,delete t.oneOf}}}))}function Aoe(e){return`_zod`in e}function joe(e,t,n){return Ste({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:Aoe(e)?koe(e):Ooe(e,{name:t})}},t=>e.parse(JSON.parse(t)))}Du();var EF=[`jsonSchema`,`functionCalling`,`jsonMode`];function Moe(e,t){if(t!==void 0&&!EF.includes(t))throw Error(`Invalid method: ${t}. Supported methods are: ${EF.join(`, `)}`);let n=!e.startsWith(`gpt-3`)&&!e.startsWith(`gpt-4-`)&&e!==`gpt-4`;if(n&&!t)return`jsonSchema`;if(!n&&t===`jsonSchema`)throw Error(`JSON Schema is not supported for model "${e}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return t??`functionCalling`}function Noe(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function Poe(e,t,n){if(nA(e))return joe(e,t,n);if(tA(e))return Noe({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:aP(e,{cycles:`ref`,reused:`ref`,override(e){e.jsonSchema.title=t}})}},t=>ft(e,JSON.parse(t)));throw Error(`Unsupported schema response format`)}function Foe(e,t){if(t&&typeof t==`object`&&`images`in t&&Array.isArray(t.images)){let n=t.images.filter(e=>typeof e?.image_url?.url==`string`).map(e=>({type:`image`,url:e.image_url.url}));return[{type:`text`,text:e},...n]}return e}var Ioe={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}},DF=`0123456789abcdef`.split(``),Loe=[-2147483648,8388608,32768,128],OF=[24,16,8,0],kF=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],AF=[];function jF(e,t){t?(AF[0]=AF[16]=AF[1]=AF[2]=AF[3]=AF[4]=AF[5]=AF[6]=AF[7]=AF[8]=AF[9]=AF[10]=AF[11]=AF[12]=AF[13]=AF[14]=AF[15]=0,this.blocks=AF):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}jF.prototype.update=function(e){if(!this.finalized){var t,n=typeof e;if(n!==`string`){if(n===`object`){if(e===null)throw Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw Error(ERROR)}else throw Error(ERROR);t=!0}for(var r,i=0,a,o=e.length,s=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,s[0]=this.block,this.block=s[16]=s[1]=s[2]=s[3]=s[4]=s[5]=s[6]=s[7]=s[8]=s[9]=s[10]=s[11]=s[12]=s[13]=s[14]=s[15]=0),t)for(a=this.start;i<o&&a<64;++i)s[a>>>2]|=e[i]<<OF[a++&3];else for(a=this.start;i<o&&a<64;++i)r=e.charCodeAt(i),r<128?s[a>>>2]|=r<<OF[a++&3]:r<2048?(s[a>>>2]|=(192|r>>>6)<<OF[a++&3],s[a>>>2]|=(128|r&63)<<OF[a++&3]):r<55296||r>=57344?(s[a>>>2]|=(224|r>>>12)<<OF[a++&3],s[a>>>2]|=(128|r>>>6&63)<<OF[a++&3],s[a>>>2]|=(128|r&63)<<OF[a++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),s[a>>>2]|=(240|r>>>18)<<OF[a++&3],s[a>>>2]|=(128|r>>>12&63)<<OF[a++&3],s[a>>>2]|=(128|r>>>6&63)<<OF[a++&3],s[a>>>2]|=(128|r&63)<<OF[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=s[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes%=4294967296),this}},jF.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=Loe[t&3],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()}},jF.prototype.hash=function(){var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=this.blocks,l,u,d,f,p,m,h,g,_,v,y;for(l=16;l<64;++l)p=c[l-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=c[l-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,c[l]=c[l-16]+u+c[l-7]+d<<0;for(y=t&n,l=0;l<64;l+=4)this.first?(this.is224?(g=300032,p=c[0]-1413257819,s=p-150054599<<0,r=p+24177077<<0):(g=704751109,p=c[0]-210244248,s=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),g=e&t,f=g^e&n^y,h=i&a^~i&o,p=s+d+h+kF[l]+c[l],m=u+f,s=r+p<<0,r=p+m<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),_=r&e,f=_^r&t^g,h=o&s^~o&i,p=a+d+h+kF[l+1]+c[l+1],m=u+f,o=n+p<<0,n=p+m<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),v=n&r,f=v^n&e^_,h=a&o^~a&s,p=i+d+h+kF[l+2]+c[l+2],m=u+f,a=t+p<<0,t=p+m<<0,u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),y=t&n,f=y^t&r^v,h=a&o^~a&s,p=i+d+h+kF[l+3]+c[l+3],m=u+f,i=e+p<<0,e=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+o<<0,this.h7=this.h7+s<<0},jF.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=DF[e>>>28&15]+DF[e>>>24&15]+DF[e>>>20&15]+DF[e>>>16&15]+DF[e>>>12&15]+DF[e>>>8&15]+DF[e>>>4&15]+DF[e&15]+DF[t>>>28&15]+DF[t>>>24&15]+DF[t>>>20&15]+DF[t>>>16&15]+DF[t>>>12&15]+DF[t>>>8&15]+DF[t>>>4&15]+DF[t&15]+DF[n>>>28&15]+DF[n>>>24&15]+DF[n>>>20&15]+DF[n>>>16&15]+DF[n>>>12&15]+DF[n>>>8&15]+DF[n>>>4&15]+DF[n&15]+DF[r>>>28&15]+DF[r>>>24&15]+DF[r>>>20&15]+DF[r>>>16&15]+DF[r>>>12&15]+DF[r>>>8&15]+DF[r>>>4&15]+DF[r&15]+DF[i>>>28&15]+DF[i>>>24&15]+DF[i>>>20&15]+DF[i>>>16&15]+DF[i>>>12&15]+DF[i>>>8&15]+DF[i>>>4&15]+DF[i&15]+DF[a>>>28&15]+DF[a>>>24&15]+DF[a>>>20&15]+DF[a>>>16&15]+DF[a>>>12&15]+DF[a>>>8&15]+DF[a>>>4&15]+DF[a&15]+DF[o>>>28&15]+DF[o>>>24&15]+DF[o>>>20&15]+DF[o>>>16&15]+DF[o>>>12&15]+DF[o>>>8&15]+DF[o>>>4&15]+DF[o&15];return this.is224||(c+=DF[s>>>28&15]+DF[s>>>24&15]+DF[s>>>20&15]+DF[s>>>16&15]+DF[s>>>12&15]+DF[s>>>8&15]+DF[s>>>4&15]+DF[s&15]),c},jF.prototype.toString=jF.prototype.hex,jF.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3,i=this.h4,a=this.h5,o=this.h6,s=this.h7,c=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||c.push(s>>>24&255,s>>>16&255,s>>>8&255,s&255),c},jF.prototype.array=jF.prototype.digest,jF.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),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),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};var Roe=(...e)=>new jF(!1,!0).update(e.join(``)).hex(),zoe=(...e)=>Roe(e.join(`_`)),Boe=class{keyEncoder=zoe;makeDefaultKeyEncoder(e){this.keyEncoder=e}},Voe=new Map,Hoe=class e extends Boe{cache;constructor(e){super(),this.cache=e??new Map}lookup(e,t){return Promise.resolve(this.cache.get(this.keyEncoder(e,t))??null)}async update(e,t,n){this.cache.set(this.keyEncoder(e,t),n)}static global(){return new e(Voe)}},MF=class extends ox{},Uoe=class extends MF{static lc_name(){return`StringPromptValue`}lc_namespace=[`langchain_core`,`prompt_values`];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new pS(this.value)]}},Woe=class extends MF{lc_namespace=[`langchain_core`,`prompt_values`];lc_serializable=!0;static lc_name(){return`ChatPromptValue`}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return yS(this.messages)}toChatMessages(){return this.messages}},Goe=f(l((e=>{e.toByteArray=l;for(var t=[],n=[],r=typeof Uint8Array<`u`?Uint8Array:Array,i=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,a=0,o=i.length;a<o;++a)t[a]=i[a],n[i.charCodeAt(a)]=a;n[45]=62,n[95]=63;function s(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function c(e,t,n){return(t+n)*3/4-n}function l(e){var t,i=s(e),a=i[0],o=i[1],l=new r(c(e,a,o)),u=0,d=o>0?a-4:a,f;for(f=0;f<d;f+=4)t=n[e.charCodeAt(f)]<<18|n[e.charCodeAt(f+1)]<<12|n[e.charCodeAt(f+2)]<<6|n[e.charCodeAt(f+3)],l[u++]=t>>16&255,l[u++]=t>>8&255,l[u++]=t&255;return o===2&&(t=n[e.charCodeAt(f)]<<2|n[e.charCodeAt(f+1)]>>4,l[u++]=t&255),o===1&&(t=n[e.charCodeAt(f)]<<10|n[e.charCodeAt(f+1)]<<4|n[e.charCodeAt(f+2)]>>2,l[u++]=t>>8&255,l[u++]=t&255),l}}))(),1),Koe=Object.defineProperty,qoe=(e,t,n)=>t in e?Koe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Joe=(e,t,n)=>(qoe(e,typeof t==`symbol`?t:t+``,n),n);function Yoe(e,t){let n=Array.from({length:e.length},(e,t)=>({start:t,end:t+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){let a=e.slice(n[i].start,n[i+1].end),o=t.get(a.join(`,`));o!=null&&(r==null||o<r[0])&&(r=[o,i])}if(r!=null){let e=r[1];n[e]={start:n[e].start,end:n[e+1].end},n.splice(e+1,1)}else break}return n}function Xoe(e,t){return e.length===1?[t.get(e.join(`,`))]:Yoe(e,t).map(n=>t.get(e.slice(n.start,n.end).join(`,`))).filter(e=>e!=null)}function Zoe(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,`\\$&`)}var NF=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;let n=e.bpe_ranks.split(`
|
|
124
|
+
`).filter(Boolean).reduce((e,t)=>{let[n,r,...i]=t.split(` `),a=Number.parseInt(r,10);return i.forEach((t,n)=>e[t]=a+n),e},{});for(let[e,t]of Object.entries(n)){let n=Goe.toByteArray(e);this.rankMap.set(n.join(`,`),t),this.textMap.set(t,n)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((e,[t,n])=>(e[n]=this.textEncoder.encode(t),e),{})}encode(e,t=[],n=`all`){let r=new RegExp(this.patStr,`ug`),i=NF.specialTokenRegex(Object.keys(this.specialTokens)),a=[],o=new Set(t===`all`?Object.keys(this.specialTokens):t),s=new Set(n===`all`?Object.keys(this.specialTokens).filter(e=>!o.has(e)):n);if(s.size>0){let t=NF.specialTokenRegex([...s]),n=e.match(t);if(n!=null)throw Error(`The text contains a special token that is not allowed: ${n[0]}`)}let c=0;for(;;){let t=null,n=c;for(;i.lastIndex=n,t=i.exec(e),!(t==null||o.has(t[0]));)n=t.index+1;let s=t?.index??e.length;for(let t of e.substring(c,s).matchAll(r)){let e=this.textEncoder.encode(t[0]),n=this.rankMap.get(e.join(`,`));if(n!=null){a.push(n);continue}a.push(...Xoe(e,this.rankMap))}if(t==null)break;let l=this.specialTokens[t[0]];a.push(l),c=t.index+t[0].length}return a}decode(e){let t=[],n=0;for(let r=0;r<e.length;++r){let i=e[r],a=this.textMap.get(i)??this.inverseSpecialTokens[i];a!=null&&(t.push(a),n+=a.length)}let r=new Uint8Array(n),i=0;for(let e of t)r.set(e,i),i+=e.length;return this.textDecoder.decode(r)}},PF=NF;Joe(PF,`specialTokenRegex`,e=>new RegExp(e.map(e=>Zoe(e)).join(`|`),`g`));function Qoe(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`:case`gpt-5`:case`gpt-5-2025-08-07`:case`gpt-5-nano`:case`gpt-5-nano-2025-08-07`:case`gpt-5-mini`:case`gpt-5-mini-2025-08-07`:case`gpt-5-chat-latest`:return`o200k_base`;default:throw Error(`Unknown model`)}}var FF={},$oe=new Xk({});async function ese(e){return e in FF||(FF[e]=$oe.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(e=>e.json()).then(e=>new PF(e)).catch(t=>{throw delete FF[e],t})),await FF[e]}async function tse(e){return ese(Qoe(e))}var nse=e=>e.startsWith(`gpt-5`)?`gpt-5`: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;function IF(e){return typeof e!=`object`||!e?!1:!!(`type`in e&&e.type===`function`&&`function`in e&&typeof e.function==`object`&&e.function&&`name`in e.function&&`parameters`in e.function)}var rse=()=>!1,LF=class extends xP{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??rse(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion(`@langchain/core`,`1.2.5`)}_addVersion(e,t){let n=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof n==`object`&&n?n:{},[e]:t}}}},ise=class extends LF{get callKeys(){return[`stop`,`timeout`,`signal`,`tags`,`metadata`,`callbacks`]}caller;cache;constructor({callbacks:e,callbackManager:t,...n}){let{cache:r,...i}=n;super({callbacks:e??t,...i}),typeof r==`object`?this.cache=r:r?this.cache=Hoe.global():this.cache=void 0,this.caller=new Xk(n??{})}_encoding;async getNumTokens(e){let t;t=typeof e==`string`?e:e.map(e=>typeof e==`string`?e:e.type===`text`&&`text`in e?e.text:``).join(``);let n=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await tse(`modelName`in this?nse(this.modelName):`gpt2`)}catch(e){console.warn(`Failed to calculate number of tokens, falling back to approximate count`,e)}if(this._encoding)try{n=this._encoding.encode(t).length}catch(e){console.warn(`Failed to calculate number of tokens, falling back to approximate count`,e)}return n}static _convertInputToPromptValue(e){return typeof e==`string`?new Uoe(e):Array.isArray(e)?new Woe(e.map(vS)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){let n={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>`${e}:${JSON.stringify(t)}`).sort().join(`,`)}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw Error(`Use .toJSON() instead`)}get profile(){return{}}_filterInvocationParamsForTracing(e){let{tools:t,functions:n,messages:r,response_format:i,...a}=e;return a}},ase=e=>e();function RF(e){let t=e.constructor;return new t({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:`v1`}})}var zF=class extends xP{static lc_name(){return`RunnablePassthrough`}lc_namespace=[`langchain_core`,`runnables`];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,t){let n=$O(t);return this.func&&await this.func(e,n),this._callWithConfig(e=>Promise.resolve(e),e,n)}async*transform(e,t){let n=$O(t),r,i=!0;for await(let t of this._transformStreamWithConfig(e,e=>e,n))if(yield t,i)if(r===void 0)r=t;else try{r=ok(r,t)}catch{r=void 0,i=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new jP(new TP({steps:e}))}},ose=class extends xP{parseResultWithPrompt(e,t,n){return this.parseResult(e,n)}_baseMessageToString(e){return typeof e.content==`string`?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e==`string`?this._callWithConfig(async(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`})}},BF=class extends ose{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,n){return this.parse(e,n)}_type(){throw Error(`_type not implemented`)}},VF=class extends Error{llmOutput;observation;sendToLLM;constructor(e,t,n,r=!1){if(super(e),this.llmOutput=t,this.observation=n,this.sendToLLM=r,r&&(n===void 0||t===void 0))throw Error(`Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true`);kb(this,`OUTPUT_PARSING_FAILURE`)}},sse=class extends BF{async*_transform(e){for await(let t of e)typeof t==`string`?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:`parser`})}},HF=class extends sse{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let t,n;for await(let r of e){if(typeof r!=`string`&&typeof r.content!=`string`)throw Error(`Cannot handle non-string output.`);let e;if(Wte(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new jk({message:r,text:r.content})}else if(Gx(r)){if(typeof r.content!=`string`)throw Error(`Cannot handle non-string message output.`);e=new jk({message:gne(r),text:r.content})}else e=new Ak({text:r});n=n===void 0?e:n.concat(e);let i=await this.parsePartialResult([n]);i!=null&&!xN(i,t)&&(this.diff?yield this._diff(t,i):yield i,t=i)}}getFormatInstructions(){return``}},UF=class extends HF{static lc_name(){return`JsonOutputParser`}lc_namespace=[`langchain_core`,`output_parsers`];lc_serializable=!0;_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?uae(e,t):[{op:`replace`,path:``,value:t}]}async parsePartialResult(e){return cS(e[0].text)}async parse(e){return cS(e,JSON.parse)}getFormatInstructions(){return``}_baseMessageToString(e){return e.text}},cse=class extends BF{static lc_name(){return`StandardSchemaOutputParser`}lc_namespace=[`langchain`,`output_parsers`,`standard_schema`];schema;constructor(e){super(),this.schema=e}static fromSerializableSchema(e){return new this(e)}async parse(e){try{let t=cS(e,JSON.parse),n=await this.schema[`~standard`].validate(t);if(n.issues)throw Error(`Validation failed: ${JSON.stringify(n.issues)}`);return n.value}catch(t){throw new VF(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}getFormatInstructions(){return``}};CM();var lse=class extends BF{schema;static lc_name(){return`StructuredOutputParser`}lc_namespace=[`langchain`,`output_parsers`,`structured`];toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),this.schema=e}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let t=bM(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,vM().describe(t)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
|
|
125
125
|
|
|
126
126
|
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
|
|
127
127
|
|
|
@@ -133,9 +133,9 @@ Your output will be parsed and type-checked according to the provided schema ins
|
|
|
133
133
|
|
|
134
134
|
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
|
|
135
135
|
\`\`\`json
|
|
136
|
-
${JSON.stringify(
|
|
136
|
+
${JSON.stringify(aP(this.schema))}
|
|
137
137
|
\`\`\`
|
|
138
|
-
`}async parse(e){try{let t=e.trim(),n=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(e,t)=>`"${t.replace(/\n/g,`\\n`)}"`).replace(/\n/g,``);return await
|
|
138
|
+
`}async parse(e){try{let t=e.trim(),n=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(e,t)=>`"${t.replace(/\n/g,`\\n`)}"`).replace(/\n/g,``);return await aA(this.schema,JSON.parse(n))}catch(t){throw new VF(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}_baseMessageToString(e){return e.text}};(function(){let e={};e.parser=function(e,t){return new n(e,t)},e.SAXParser=n,e.SAXStream=l,e.createStream=c,e.MAX_BUFFER_LENGTH=64*1024;let t=[`comment`,`sgmlDecl`,`textNode`,`tagName`,`doctype`,`procInstName`,`procInstBody`,`entity`,`attribName`,`attribValue`,`cdata`,`script`];e.EVENTS=[`text`,`processinginstruction`,`sgmldeclaration`,`doctype`,`comment`,`opentagstart`,`attribute`,`opentag`,`closetag`,`opencdata`,`cdata`,`closecdata`,`error`,`end`,`ready`,`script`,`opennamespace`,`closenamespace`];function n(t,r){if(!(this instanceof n))return new n(t,r);var a=this;i(a),a.q=a.c=``,a.bufferCheckPosition=e.MAX_BUFFER_LENGTH,a.opt=r||{},a.opt.lowercase=a.opt.lowercase||a.opt.lowercasetags,a.looseCase=a.opt.lowercase?`toLowerCase`:`toUpperCase`,a.tags=[],a.closed=a.closedRoot=a.sawRoot=!1,a.tag=a.error=null,a.strict=!!t,a.noscript=!!(t||a.opt.noscript),a.state=C.BEGIN,a.strictEntities=a.opt.strictEntities,a.ENTITIES=a.strictEntities?Object.create(e.XML_ENTITIES):Object.create(e.ENTITIES),a.attribList=[],a.opt.xmlns&&(a.ns=Object.create(m)),a.trackPosition=a.opt.position!==!1,a.trackPosition&&(a.position=a.line=a.column=0),ne(a,`onready`)}Object.create||(Object.create=function(e){function t(){}return t.prototype=e,new t}),Object.keys||(Object.keys=function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t});function r(n){for(var r=Math.max(e.MAX_BUFFER_LENGTH,10),i=0,a=0,o=t.length;a<o;a++){var s=n[t[a]].length;if(s>r)switch(t[a]){case`textNode`:re(n);break;case`cdata`:w(n,`oncdata`,n.cdata),n.cdata=``;break;case`script`:w(n,`onscript`,n.script),n.script=``;break;default:T(n,`Max buffer length exceeded: `+t[a])}i=Math.max(i,s)}n.bufferCheckPosition=e.MAX_BUFFER_LENGTH-i+n.position}function i(e){for(var n=0,r=t.length;n<r;n++)e[t[n]]=``}function a(e){re(e),e.cdata!==``&&(w(e,`oncdata`,e.cdata),e.cdata=``),e.script!==``&&(w(e,`onscript`,e.script),e.script=``)}n.prototype={end:function(){ae(this)},write:fe,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){a(this)}};var o=ReadableStream;o||=function(){};var s=e.EVENTS.filter(function(e){return e!==`error`&&e!==`end`});function c(e,t){return new l(e,t)}function l(e,t){if(!(this instanceof l))return new l(e,t);o.apply(this),this._parser=new n(e,t),this.writable=!0,this.readable=!0;var r=this;this._parser.onend=function(){r.emit(`end`)},this._parser.onerror=function(e){r.emit(`error`,e),r._parser.error=null},this._decoder=null,s.forEach(function(e){Object.defineProperty(r,`on`+e,{get:function(){return r._parser[`on`+e]},set:function(t){if(!t)return r.removeAllListeners(e),r._parser[`on`+e]=t,t;r.on(e,t)},enumerable:!0,configurable:!1})})}l.prototype=Object.create(o.prototype,{constructor:{value:l}}),l.prototype.write=function(e){return this._parser.write(e.toString()),this.emit(`data`,e),!0},l.prototype.end=function(e){return e&&e.length&&this.write(e),this._parser.end(),!0},l.prototype.on=function(e,t){var n=this;return!n._parser[`on`+e]&&s.indexOf(e)!==-1&&(n._parser[`on`+e]=function(){var t=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);t.splice(0,0,e),n.emit.apply(n,t)}),o.prototype.on.call(n,e,t)};var u=`[CDATA[`,d=`DOCTYPE`,f=`http://www.w3.org/XML/1998/namespace`,p=`http://www.w3.org/2000/xmlns/`,m={xml:f,xmlns:p},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]/,g=/[:_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-]/,_=/[#:_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]/,v=/[#:_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 y(e){return e===` `||e===`
|
|
139
139
|
`||e===`\r`||e===` `}function b(e){return e===`"`||e===`'`}function x(e){return e===`>`||y(e)}function S(e,t){return e.test(t)}function ee(e,t){return!S(e,t)}var C=0;for(var te in e.STATE={BEGIN:C++,BEGIN_WHITESPACE:C++,TEXT:C++,TEXT_ENTITY:C++,OPEN_WAKA:C++,SGML_DECL:C++,SGML_DECL_QUOTED:C++,DOCTYPE:C++,DOCTYPE_QUOTED:C++,DOCTYPE_DTD:C++,DOCTYPE_DTD_QUOTED:C++,COMMENT_STARTING:C++,COMMENT:C++,COMMENT_ENDING:C++,COMMENT_ENDED:C++,CDATA:C++,CDATA_ENDING:C++,CDATA_ENDING_2:C++,PROC_INST:C++,PROC_INST_BODY:C++,PROC_INST_ENDING:C++,OPEN_TAG:C++,OPEN_TAG_SLASH:C++,ATTRIB:C++,ATTRIB_NAME:C++,ATTRIB_NAME_SAW_WHITE:C++,ATTRIB_VALUE:C++,ATTRIB_VALUE_QUOTED:C++,ATTRIB_VALUE_CLOSED:C++,ATTRIB_VALUE_UNQUOTED:C++,ATTRIB_VALUE_ENTITY_Q:C++,ATTRIB_VALUE_ENTITY_U:C++,CLOSE_TAG:C++,CLOSE_TAG_SAW_WHITE:C++,SCRIPT:C++,SCRIPT_ENDING:C++},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 n=e.ENTITIES[t],r=typeof n==`number`?String.fromCharCode(n):n;e.ENTITIES[t]=r}),e.STATE)e.STATE[e.STATE[te]]=te;C=e.STATE;function ne(e,t,n){e[t]&&e[t](n)}function w(e,t,n){e.textNode&&re(e),ne(e,t,n)}function re(e){e.textNode=ie(e.opt,e.textNode),e.textNode&&ne(e,`ontext`,e.textNode),e.textNode=``}function ie(e,t){return e.trim&&(t=t.trim()),e.normalize&&(t=t.replace(/\s+/g,` `)),t}function T(e,t){return re(e),e.trackPosition&&(t+=`
|
|
140
140
|
Line: `+e.line+`
|
|
141
141
|
Column: `+e.column+`
|
|
@@ -144,8 +144,8 @@ Actual: `+e.attribValue);else if(r===`xmlns`&&e.attribValue!==p)E(e,`xmlns: pref
|
|
|
144
144
|
Actual: `+e.attribValue);else{var i=e.tag,a=e.tags[e.tags.length-1]||e;i.ns===a.ns&&(i.ns=Object.create(a.ns)),i.ns[r]=e.attribValue}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,w(e,`onattribute`,{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=``}function D(e,t){if(e.opt.xmlns){var n=e.tag,r=se(e.tagName);n.prefix=r.prefix,n.local=r.local,n.uri=n.ns[r.prefix]||``,n.prefix&&!n.uri&&(E(e,`Unbound namespace prefix: `+JSON.stringify(e.tagName)),n.uri=r.prefix);var i=e.tags[e.tags.length-1]||e;n.ns&&i.ns!==n.ns&&Object.keys(n.ns).forEach(function(t){w(e,`onopennamespace`,{prefix:t,uri:n.ns[t]})});for(var a=0,o=e.attribList.length;a<o;a++){var s=e.attribList[a],c=s[0],l=s[1],u=se(c,!0),d=u.prefix,f=u.local,p=d===``?``:n.ns[d]||``,m={name:c,value:l,prefix:d,local:f,uri:p};d&&d!==`xmlns`&&!p&&(E(e,`Unbound namespace prefix: `+JSON.stringify(d)),m.uri=d),e.tag.attributes[c]=m,w(e,`onattribute`,m)}e.attribList.length=0}e.tag.isSelfClosing=!!t,e.sawRoot=!0,e.tags.push(e.tag),w(e,`onopentag`,e.tag),t||(!e.noscript&&e.tagName.toLowerCase()===`script`?e.state=C.SCRIPT:e.state=C.TEXT,e.tag=null,e.tagName=``),e.attribName=e.attribValue=``,e.attribList.length=0}function le(e){if(!e.tagName){E(e,`Weird empty close tag.`),e.textNode+=`</>`,e.state=C.TEXT;return}if(e.script){if(e.tagName!==`script`){e.script+=`</`+e.tagName+`>`,e.tagName=``,e.state=C.SCRIPT;return}w(e,`onscript`,e.script),e.script=``}var t=e.tags.length,n=e.tagName;e.strict||(n=n[e.looseCase]());for(var r=n;t--&&e.tags[t].name!==r;)E(e,`Unexpected close tag`);if(t<0){E(e,`Unmatched closing tag: `+e.tagName),e.textNode+=`</`+e.tagName+`>`,e.state=C.TEXT;return}e.tagName=n;for(var i=e.tags.length;i-->t;){var a=e.tag=e.tags.pop();e.tagName=e.tag.name,w(e,`onclosetag`,e.tagName);var o={};for(var s in a.ns)o[s]=a.ns[s];var c=e.tags[e.tags.length-1]||e;e.opt.xmlns&&a.ns!==c.ns&&Object.keys(a.ns).forEach(function(t){var n=a.ns[t];w(e,`onclosenamespace`,{prefix:t,uri:n})})}t===0&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName=``,e.attribList.length=0,e.state=C.TEXT}function ue(e){var t=e.entity,n=t.toLowerCase(),r,i=``;return e.ENTITIES[t]?e.ENTITIES[t]:e.ENTITIES[n]?e.ENTITIES[n]:(t=n,t.charAt(0)===`#`&&(t.charAt(1)===`x`?(t=t.slice(2),r=parseInt(t,16),i=r.toString(16)):(t=t.slice(1),r=parseInt(t,10),i=r.toString(10))),t=t.replace(/^0+/,``),isNaN(r)||i.toLowerCase()!==t?(E(e,`Invalid character entity`),`&`+e.entity+`;`):String.fromCodePoint(r))}function O(e,t){t===`<`?(e.state=C.OPEN_WAKA,e.startTagPosition=e.position):y(t)||(E(e,`Non-whitespace before first tag.`),e.textNode=t,e.state=C.TEXT)}function de(e,t){var n=``;return t<e.length&&(n=e.charAt(t)),n}function fe(e){var t=this;if(this.error)throw this.error;if(t.closed)return T(t,`Cannot write after close. Assign an onready handler.`);if(e===null)return ae(t);typeof e==`object`&&(e=e.toString());for(var n=0,i=``;i=de(e,n++),t.c=i,i;)switch(t.trackPosition&&(t.position++,i===`
|
|
145
145
|
`?(t.line++,t.column=0):t.column++),t.state){case C.BEGIN:if(t.state=C.BEGIN_WHITESPACE,i===``)continue;O(t,i);continue;case C.BEGIN_WHITESPACE:O(t,i);continue;case C.TEXT:if(t.sawRoot&&!t.closedRoot){for(var a=n-1;i&&i!==`<`&&i!==`&`;)i=de(e,n++),i&&t.trackPosition&&(t.position++,i===`
|
|
146
146
|
`?(t.line++,t.column=0):t.column++);t.textNode+=e.substring(a,n-1)}i===`<`&&!(t.sawRoot&&t.closedRoot&&!t.strict)?(t.state=C.OPEN_WAKA,t.startTagPosition=t.position):(!y(i)&&(!t.sawRoot||t.closedRoot)&&E(t,`Text data outside of root node.`),i===`&`?t.state=C.TEXT_ENTITY:t.textNode+=i);continue;case C.SCRIPT:i===`<`?t.state=C.SCRIPT_ENDING:t.script+=i;continue;case C.SCRIPT_ENDING:i===`/`?t.state=C.CLOSE_TAG:(t.script+=`<`+i,t.state=C.SCRIPT);continue;case C.OPEN_WAKA:if(i===`!`)t.state=C.SGML_DECL,t.sgmlDecl=``;else if(!y(i))if(S(h,i))t.state=C.OPEN_TAG,t.tagName=i;else if(i===`/`)t.state=C.CLOSE_TAG,t.tagName=``;else if(i===`?`)t.state=C.PROC_INST,t.procInstName=t.procInstBody=``;else{if(E(t,`Unencoded <`),t.startTagPosition+1<t.position){var o=t.position-t.startTagPosition;i=Array(o).join(` `)+i}t.textNode+=`<`+i,t.state=C.TEXT}continue;case C.SGML_DECL:(t.sgmlDecl+i).toUpperCase()===u?(w(t,`onopencdata`),t.state=C.CDATA,t.sgmlDecl=``,t.cdata=``):t.sgmlDecl+i===`--`?(t.state=C.COMMENT,t.comment=``,t.sgmlDecl=``):(t.sgmlDecl+i).toUpperCase()===d?(t.state=C.DOCTYPE,(t.doctype||t.sawRoot)&&E(t,`Inappropriately located doctype declaration`),t.doctype=``,t.sgmlDecl=``):i===`>`?(w(t,`onsgmldeclaration`,t.sgmlDecl),t.sgmlDecl=``,t.state=C.TEXT):(b(i)&&(t.state=C.SGML_DECL_QUOTED),t.sgmlDecl+=i);continue;case C.SGML_DECL_QUOTED:i===t.q&&(t.state=C.SGML_DECL,t.q=``),t.sgmlDecl+=i;continue;case C.DOCTYPE:i===`>`?(t.state=C.TEXT,w(t,`ondoctype`,t.doctype),t.doctype=!0):(t.doctype+=i,i===`[`?t.state=C.DOCTYPE_DTD:b(i)&&(t.state=C.DOCTYPE_QUOTED,t.q=i));continue;case C.DOCTYPE_QUOTED:t.doctype+=i,i===t.q&&(t.q=``,t.state=C.DOCTYPE);continue;case C.DOCTYPE_DTD:t.doctype+=i,i===`]`?t.state=C.DOCTYPE:b(i)&&(t.state=C.DOCTYPE_DTD_QUOTED,t.q=i);continue;case C.DOCTYPE_DTD_QUOTED:t.doctype+=i,i===t.q&&(t.state=C.DOCTYPE_DTD,t.q=``);continue;case C.COMMENT:i===`-`?t.state=C.COMMENT_ENDING:t.comment+=i;continue;case C.COMMENT_ENDING:i===`-`?(t.state=C.COMMENT_ENDED,t.comment=ie(t.opt,t.comment),t.comment&&w(t,`oncomment`,t.comment),t.comment=``):(t.comment+=`-`+i,t.state=C.COMMENT);continue;case C.COMMENT_ENDED:i===`>`?t.state=C.TEXT:(E(t,`Malformed comment`),t.comment+=`--`+i,t.state=C.COMMENT);continue;case C.CDATA:i===`]`?t.state=C.CDATA_ENDING:t.cdata+=i;continue;case C.CDATA_ENDING:i===`]`?t.state=C.CDATA_ENDING_2:(t.cdata+=`]`+i,t.state=C.CDATA);continue;case C.CDATA_ENDING_2:i===`>`?(t.cdata&&w(t,`oncdata`,t.cdata),w(t,`onclosecdata`),t.cdata=``,t.state=C.TEXT):i===`]`?t.cdata+=`]`:(t.cdata+=`]]`+i,t.state=C.CDATA);continue;case C.PROC_INST:i===`?`?t.state=C.PROC_INST_ENDING:y(i)?t.state=C.PROC_INST_BODY:t.procInstName+=i;continue;case C.PROC_INST_BODY:if(!t.procInstBody&&y(i))continue;i===`?`?t.state=C.PROC_INST_ENDING:t.procInstBody+=i;continue;case C.PROC_INST_ENDING:i===`>`?(w(t,`onprocessinginstruction`,{name:t.procInstName,body:t.procInstBody}),t.procInstName=t.procInstBody=``,t.state=C.TEXT):(t.procInstBody+=`?`+i,t.state=C.PROC_INST_BODY);continue;case C.OPEN_TAG:S(g,i)?t.tagName+=i:(oe(t),i===`>`?D(t):i===`/`?t.state=C.OPEN_TAG_SLASH:(y(i)||E(t,`Invalid character in tag name`),t.state=C.ATTRIB));continue;case C.OPEN_TAG_SLASH:i===`>`?(D(t,!0),le(t)):(E(t,`Forward-slash in opening tag not followed by >`),t.state=C.ATTRIB);continue;case C.ATTRIB:if(y(i))continue;i===`>`?D(t):i===`/`?t.state=C.OPEN_TAG_SLASH:S(h,i)?(t.attribName=i,t.attribValue=``,t.state=C.ATTRIB_NAME):E(t,`Invalid attribute name`);continue;case C.ATTRIB_NAME:i===`=`?t.state=C.ATTRIB_VALUE:i===`>`?(E(t,`Attribute without value`),t.attribValue=t.attribName,ce(t),D(t)):y(i)?t.state=C.ATTRIB_NAME_SAW_WHITE:S(g,i)?t.attribName+=i:E(t,`Invalid attribute name`);continue;case C.ATTRIB_NAME_SAW_WHITE:if(i===`=`)t.state=C.ATTRIB_VALUE;else if(y(i))continue;else E(t,`Attribute without value`),t.tag.attributes[t.attribName]=``,t.attribValue=``,w(t,`onattribute`,{name:t.attribName,value:``}),t.attribName=``,i===`>`?D(t):S(h,i)?(t.attribName=i,t.state=C.ATTRIB_NAME):(E(t,`Invalid attribute name`),t.state=C.ATTRIB);continue;case C.ATTRIB_VALUE:if(y(i))continue;b(i)?(t.q=i,t.state=C.ATTRIB_VALUE_QUOTED):(E(t,`Unquoted attribute value`),t.state=C.ATTRIB_VALUE_UNQUOTED,t.attribValue=i);continue;case C.ATTRIB_VALUE_QUOTED:if(i!==t.q){i===`&`?t.state=C.ATTRIB_VALUE_ENTITY_Q:t.attribValue+=i;continue}ce(t),t.q=``,t.state=C.ATTRIB_VALUE_CLOSED;continue;case C.ATTRIB_VALUE_CLOSED:y(i)?t.state=C.ATTRIB:i===`>`?D(t):i===`/`?t.state=C.OPEN_TAG_SLASH:S(h,i)?(E(t,`No whitespace between attributes`),t.attribName=i,t.attribValue=``,t.state=C.ATTRIB_NAME):E(t,`Invalid attribute name`);continue;case C.ATTRIB_VALUE_UNQUOTED:if(!x(i)){i===`&`?t.state=C.ATTRIB_VALUE_ENTITY_U:t.attribValue+=i;continue}ce(t),i===`>`?D(t):t.state=C.ATTRIB;continue;case C.CLOSE_TAG:if(t.tagName)i===`>`?le(t):S(g,i)?t.tagName+=i:t.script?(t.script+=`</`+t.tagName,t.tagName=``,t.state=C.SCRIPT):(y(i)||E(t,`Invalid tagname in closing tag`),t.state=C.CLOSE_TAG_SAW_WHITE);else{if(y(i))continue;ee(h,i)?t.script?(t.script+=`</`+i,t.state=C.SCRIPT):E(t,`Invalid tagname in closing tag.`):t.tagName=i}continue;case C.CLOSE_TAG_SAW_WHITE:if(y(i))continue;i===`>`?le(t):E(t,`Invalid characters in closing tag`);continue;case C.TEXT_ENTITY:case C.ATTRIB_VALUE_ENTITY_Q:case C.ATTRIB_VALUE_ENTITY_U:var s,c;switch(t.state){case C.TEXT_ENTITY:s=C.TEXT,c=`textNode`;break;case C.ATTRIB_VALUE_ENTITY_Q:s=C.ATTRIB_VALUE_QUOTED,c=`attribValue`;break;case C.ATTRIB_VALUE_ENTITY_U:s=C.ATTRIB_VALUE_UNQUOTED,c=`attribValue`;break}if(i===`;`)if(t.opt.unparsedEntities){var l=ue(t);t.entity=``,t.state=s,t.write(l)}else t[c]+=ue(t),t.entity=``,t.state=s;else S(t.entity.length?v:_,i)?t.entity+=i:(E(t,`Invalid character in entity name`),t[c]+=`&`+t.entity+i,t.entity=``,t.state=s);continue;default:throw Error(t,`Unknown state: `+t.state)}return t.position>=t.bufferCheckPosition&&r(t),t}return String.fromCodePoint||(function(){var e=String.fromCharCode,t=Math.floor,n=function(){var n=16384,r=[],i,a,o=-1,s=arguments.length;if(!s)return``;for(var c=``;++o<s;){var l=Number(arguments[o]);if(!isFinite(l)||l<0||l>1114111||t(l)!==l)throw RangeError(`Invalid code point: `+l);l<=65535?r.push(l):(l-=65536,i=(l>>10)+55296,a=l%1024+56320,r.push(i,a)),(o+1===s||r.length>n)&&(c+=e.apply(null,r),r.length=0)}return c};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:n,configurable:!0,writable:!0}):String.fromCodePoint=n})(),e})();function WF(e,t){if(e.function===void 0)return;let n;if(t?.partial)try{n=lS(e.function.arguments??`{}`)}catch{return}else try{n=JSON.parse(e.function.arguments)}catch(t){throw new VF([`Function "${e.function.name}" arguments:`,``,e.function.arguments,``,`are not valid JSON.`,`Error: ${t.message}`].join(`
|
|
147
|
-
`))}let r={name:e.function.name,args:n,type:`tool_call`};return t?.returnId&&(r.id=e.id),r}function GF(e){if(e.id===void 0)throw 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 KF(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:`invalid_tool_call`}}var use=class extends HF{static lc_name(){return`JsonOutputToolsParser`}returnId=!1;lc_namespace=[`langchain`,`output_parsers`,`openai_tools`];lc_serializable=!0;constructor(e){super(e),this.returnId=e?.returnId??this.returnId}_diff(){throw Error(`Not supported.`)}async parse(){throw Error(`Not implemented.`)}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){let n=e[0].message,r;if(SS(n)&&n.tool_calls?.length?r=n.tool_calls.map(e=>{let{id:t,...n}=e;return this.returnId?{id:t,...n}:n}):n.additional_kwargs.tool_calls!==void 0&&(r=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(e=>WF(e,{returnId:this.returnId,partial:t}))),!r)return[];let i=[];for(let e of r)if(e!==void 0){let t={type:e.name,args:e.args,id:e.id};i.push(t)}return i}},dse=class extends use{static lc_name(){return`JsonOutputKeyToolsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_tools`];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,`zodSchema`in e&&(this.zodSchema=e.zodSchema),`serializableSchema`in e&&(this.serializableSchema=e.serializableSchema)}async _validateResult(e){if(this.serializableSchema!==void 0){let t=await this.serializableSchema[`~standard`].validate(e);if(t.issues)throw new VF(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.issues)}`,JSON.stringify(e,null,2));return t.value}if(this.zodSchema===void 0)return e;let t=await aA(this.zodSchema,e);if(t.success)return t.data;throw new VF(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let t=(await super.parsePartialResult(e)).filter(e=>e.type===this.keyName),n=t;if(t.length)return this.returnId||(n=t.map(e=>e.args)),this.returnSingle?n[0]:n}async parseResult(e){let t=(await super.parsePartialResult(e,!1)).filter(e=>e.type===this.keyName),n=t;if(t.length)return this.returnId||(n=t.map(e=>e.args)),this.returnSingle?this._validateResult(n[0]):await Promise.all(n.map(e=>this._validateResult(e)))}};function qF(e){return iA(e)?lse.fromZodSchema(e):xN(e)?cse.fromSerializableSchema(e):new UF}function fse(e,t,n){let r=n??dse;return iA(e)?new r({returnSingle:!0,keyName:t,zodSchema:e}):xN(e)?new r({returnSingle:!0,keyName:t,serializableSchema:e}):new r({returnSingle:!0,keyName:t})}function JF(e,t,n,r){if(!n){let n=e.pipe(t);return r?n.withConfig({runName:r}):n}let i=zF.assign({parsed:(e,n)=>t.invoke(e.raw,n)}),a=zF.assign({parsed:()=>null}),o=i.withFallbacks({fallbacks:[a]}),s=TP.from([{raw:e},o]);return r?s.withConfig({runName:r}):s}var pse=class{events=[];finished=!1;waiters=[];error=null;push(e){this.events.push(e);let t=this.waiters.splice(0);for(let e of t)e()}finish(){this.finished=!0;let e=this.waiters.splice(0);for(let t of e)t()}setError(e){this.error=e,this.finished=!0;let t=this.waiters.splice(0);for(let e of t)e()}async*iterate(){if(this.finished){if(this.error)throw this.error;yield*this.events;return}let e=0;for(;;){for(;e<this.events.length;)yield this.events[e],e++;if(this.finished){if(this.error)throw this.error;return}await new Promise(t=>{if(e<this.events.length||this.finished){t();return}this.waiters.push(t)})}}};function mse(e,t){switch(t.type){case`text-delta`:return e.type===`text`?{...e,text:(e.text??``)+t.text}:e;case`reasoning-delta`:return e.type===`thinking`?{...e,thinking:(e.thinking??``)+t.reasoning}:e.type===`reasoning`?{...e,reasoning:(e.reasoning??``)+t.reasoning}:e;case`data-delta`:return{...e,data:(e.data??``)+t.data};case`block-delta`:return{...e,...t.fields};default:throw Error(`Unknown delta type: ${JSON.stringify(t)}`)}}function YF(e){if(e.event!==`content-block-delta`)return;if(`delta`in e&&e.delta)return e.delta;let t=e.content;if(typeof t!=`object`||!t)return;let n=t;if(n.type===`text`&&typeof n.text==`string`)return{type:`text-delta`,text:n.text};if(n.type===`reasoning`&&typeof n.reasoning==`string`)return{type:`reasoning-delta`,reasoning:n.reasoning};if(n.type===`thinking`&&typeof n.thinking==`string`)return{type:`reasoning-delta`,reasoning:n.thinking};if(typeof n.data==`string`)return{type:`data-delta`,data:n.data,encoding:`base64`};if(typeof n.type==`string`)return{type:`block-delta`,fields:{...n,type:n.type}}}function XF(e){if(typeof e!=`object`||!e)return;let t=e;if(t.type===`reasoning`&&typeof t.reasoning==`string`)return t.reasoning;if(t.type===`thinking`&&typeof t.thinking==`string`)return t.thinking}function ZF(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`reasoning`||t===`thinking`}function QF(e){if(e)return{...e,input_tokens:e.input_tokens??0,output_tokens:e.output_tokens??0,total_tokens:e.total_tokens??0}}function hse(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e;if(typeof e!=`string`||e.length===0)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch{return{}}}function gse(e){let t=e;if(e.type===`tool_call`||e.type!==`tool_call_chunk`&&e.type!==`tool_use`&&e.type!==`input_json_delta`)return e;let n=typeof t.name==`string`?t.name:void 0;if(n==null)return e;let r=t.args??t.input;return{...t,type:`tool_call`,name:n,args:hse(r)}}var _se=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t=``;for await(let n of e.iterate()){let e=YF(n);e?.type===`text-delta`&&(t+=e.text,yield t)}}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let t of e.iterate()){let e=YF(t);e?.type===`text-delta`&&(yield e.text)}}return t()}then(e,t){return(async()=>{let e=``;for await(let t of this)e+=t;return e})().then(e,t)}},vse=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t=[];for await(let n of e.iterate())n.event===`content-block-finish`&&n.content.type===`tool_call`&&(t.push(n.content),yield[...t])}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let t of e.iterate())t.event===`content-block-finish`&&t.content.type===`tool_call`&&(yield t.content)}return t()}then(e,t){return(async()=>{let e=[];for await(let t of this)e.push(t);return e})().then(e,t)}},yse=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t=``,n=!1;for await(let r of e.iterate())if(r.event===`content-block-start`){if(!ZF(r.content)){if(n)return;continue}n=!0;let e=XF(r.content);if(e==null||e.length===0)continue;t+=e,yield t}else if(r.event===`content-block-delta`){let e=YF(r);if(e?.type!==`reasoning-delta`)continue;n=!0;let i=e.reasoning;if(i==null||i.length===0)continue;t+=i,yield t}else if(r.event===`content-block-finish`&&ZF(r.content))return;else if(r.event===`message-finish`)return}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){let t=!1;for await(let n of e.iterate())if(n.event===`content-block-start`){if(!ZF(n.content)){if(t)return;continue}t=!0;let e=XF(n.content);e!=null&&e.length>0&&(yield e)}else if(n.event===`content-block-delta`){let e=YF(n);if(e?.type!==`reasoning-delta`)continue;t=!0;let r=e.reasoning;r!=null&&r.length>0&&(yield r)}else if(n.event===`content-block-finish`&&ZF(n.content))return;else if(n.event===`message-finish`)return}return t()}then(e,t){return(async()=>{let e=``;for await(let t of this)e+=t;return e})().then(e,t)}},bse=class{_buffer;constructor(e){this._buffer=e}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let t of e.iterate())if(t.event===`usage`){let e=QF(t.usage);e&&(yield e)}else if(t.event===`message-start`&&t.usage){let e=QF(t.usage);e&&(yield e)}else if(t.event===`message-finish`&&t.usage){let e=QF(t.usage);e&&(yield e)}}return t()}then(e,t){return(async()=>{let e;for await(let t of this)e=t;return e})().then(e,t)}},$F=class{_buffer;constructor(e){this._buffer=new pse,this._consume(e)}async _consume(e){try{for await(let t of e)this._buffer.push(t);this._buffer.finish()}catch(e){this._buffer.setError(e instanceof Error?e:Error(String(e)))}}[Symbol.asyncIterator](){return this._buffer.iterate()}get text(){return new _se(this._buffer)}get toolCalls(){return new vse(this._buffer)}get reasoning(){return new yse(this._buffer)}get usage(){return new bse(this._buffer)}get output(){return this._assembleMessage()}then(e,t){return this._assembleMessage().then(e,t)}async _assembleMessage(){let e=[],t,n,r={},i;for await(let a of this._buffer.iterate())switch(a.event){case`message-start`:t=a.id??t,a.usage&&(n=QF(a.usage));break;case`content-block-start`:e[a.index]=a.content;break;case`content-block-delta`:{let t=e[a.index],n=YF(a);t&&n&&(e[a.index]=mse(t,n));break}case`content-block-finish`:e[a.index]=a.content;break;case`usage`:n=QF(a.usage);break;case`message-finish`:i=a.reason,a.usage&&(n=QF(a.usage)),a.responseMetadata&&(r={...r,...a.responseMetadata});break;default:break}let a=e.filter(e=>e!=null).map(gse);return new xS({id:t,content:a,usage_metadata:n,response_metadata:{...r,...i?{finish_reason:i}:{},output_version:`v1`}})}},xse={wav:`audio/wav`,mp3:`audio/mpeg`,flac:`audio/flac`,opus:`audio/opus`,aac:`audio/aac`,pcm16:`audio/pcm`},Sse={png:`image/png`,jpeg:`image/jpeg`,jpg:`image/jpeg`,webp:`image/webp`,gif:`image/gif`};function eI(e){let t=0;for(let n of e.keys())n>=t&&(t=n+1);return t}function tI(e){let t=e.additional_kwargs;return typeof t==`object`&&t?t:{}}function Cse(e){let t=tI(e).tool_outputs;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e;if(t.type!==`image_generation_call`)continue;let r=typeof t.result==`string`?t.result:void 0,i=typeof t.url==`string`?t.url:void 0;if(r==null&&i==null)continue;let a=typeof t.output_format==`string`?t.output_format.toLowerCase():void 0,o=(a==null?void 0:Sse[a])??`image/png`;n.push({type:`image`,...typeof t.id==`string`?{id:t.id}:{},...i==null?{}:{url:i},...r==null?{}:{data:r},mimeType:o})}return n}function wse(e){let t=tI(e).audio;if(typeof t!=`object`||!t)return;let n=t,r=typeof n.data==`string`?n.data:void 0,i=typeof n.url==`string`?n.url:void 0,a=typeof n.transcript==`string`?n.transcript:void 0;if(r==null&&i==null&&a==null)return;let o=typeof n.mime_type==`string`?n.mime_type:typeof n.mimeType==`string`?n.mimeType:void 0,s=typeof n.format==`string`?n.format.toLowerCase():void 0,c=o??(s==null?void 0:xse[s])??(r==null?`audio/pcm`:`audio/wav`);return{...typeof n.id==`string`?{id:n.id}:{},...r==null?{}:{data:r},...i==null?{}:{url:i},...a==null?{}:{transcript:a},mimeType:c}}async function*Tse(e,t){let n=new Map,r=!1,i,a,o=new Set;for await(let s of e){t?.signal?.throwIfAborted();let e=s.message,c=!1;if(!r){r=!0;let t={event:`message-start`,id:e.id??void 0};wS.isInstance(e)&&e.usage_metadata&&(t.usage=e.usage_metadata,i={...e.usage_metadata},c=!0),yield t}let l=e.content;if(typeof l==`string`){if(l!==``){if(!n.has(0)){let e={type:`text`,text:``};n.set(0,{type:`text`,accumulated:e}),yield{event:`content-block-start`,index:0,content:e}}let e=n.get(0);e.accumulated={...e.accumulated,text:(e.accumulated.text??``)+l},yield{event:`content-block-delta`,index:0,delta:{type:`text-delta`,text:l}}}}else if(Array.isArray(l))for(let e of l){let t=typeof e.index==`number`?e.index:n.size;if(!n.has(t))n.set(t,{type:e.type,accumulated:{...e}}),yield{event:`content-block-start`,index:t,content:{...e}};else{let r=n.get(t),i=Dse(e);r.accumulated=Ese(r.accumulated,i),yield{event:`content-block-delta`,index:t,delta:i}}}if(wS.isInstance(e)&&e.tool_call_chunks&&e.tool_call_chunks.length>0)for(let t of e.tool_call_chunks){let e=typeof t.index==`number`?t.index:n.size;if(!n.has(e)){let r={type:`tool_call_chunk`,id:t.id,name:t.name,args:``,index:e};n.set(e,{type:`tool_call_chunk`,accumulated:r}),yield{event:`content-block-start`,index:e,content:r}}let r=n.get(e).accumulated;t.id!=null&&(r.id=t.id),t.name!=null&&(r.name=t.name),r.args=(r.args??``)+(t.args??``),yield{event:`content-block-delta`,index:e,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...`id`in r&&r.id!=null?{id:r.id}:{},...`name`in r&&r.name!=null?{name:r.name}:{},args:r.args}}}}let u=wse(e);if(u!=null){if(a==null){let e=eI(n);a={index:e,id:u.id,mimeType:u.mimeType,transcript:``};let t={type:`audio`,...u.id==null?{}:{id:u.id},...u.url==null?{}:{url:u.url},data:``,mimeType:u.mimeType};n.set(e,{type:`audio`,accumulated:t}),yield{event:`content-block-start`,index:e,content:t}}let e=n.get(a.index);if(e!=null){let t=e.accumulated;u.id!=null&&a.id==null&&(a.id=u.id,t.id=u.id),u.transcript!=null&&(a.transcript+=u.transcript,t.transcript=a.transcript,yield{event:`content-block-delta`,index:a.index,delta:{type:`block-delta`,fields:{type:`audio`,transcript:a.transcript}}}),u.data!=null&&u.data.length>0&&(t.data=(t.data??``)+u.data,yield{event:`content-block-delta`,index:a.index,delta:{type:`data-delta`,data:u.data,encoding:`base64`}})}}for(let t of Cse(e)){let e=t,r=e.id??e.url??(e.data==null?void 0:`${e.data.length}:${e.data.slice(0,32)}`);if(r!=null&&o.has(r))continue;r!=null&&o.add(r);let i=eI(n);n.set(i,{type:`image`,accumulated:t}),yield{event:`content-block-start`,index:i,content:t}}if(!c&&wS.isInstance(e)&&e.usage_metadata){let t=e.usage_metadata;i=i?{input_tokens:i.input_tokens+t.input_tokens,output_tokens:i.output_tokens+t.output_tokens,total_tokens:i.total_tokens+t.total_tokens}:{...t},yield{event:`usage`,usage:{...i}}}}for(let[e,t]of n)yield{event:`content-block-finish`,index:e,content:nI(t.accumulated)};yield{event:`message-finish`,reason:`stop`,...i?{usage:i}:{}}}function Ese(e,t){switch(t.type){case`text-delta`:return e.type===`text`?{...e,text:(e.text??``)+t.text}:e;case`reasoning-delta`:return e.type===`thinking`?{...e,thinking:(e.thinking??``)+t.reasoning}:e.type===`reasoning`?{...e,reasoning:(e.reasoning??``)+t.reasoning}:e;case`data-delta`:return{...e,data:(e.data??``)+t.data};case`block-delta`:return{...e,...t.fields};default:throw Error(`Unknown delta type: ${JSON.stringify(t)}`)}}function Dse(e){if(e.type===`text`)return{type:`text-delta`,text:e.text};if(e.type===`reasoning`)return{type:`reasoning-delta`,reasoning:e.reasoning};if(e.type===`thinking`&&typeof e.thinking==`string`)return{type:`reasoning-delta`,reasoning:e.thinking};if(typeof e.data==`string`)return{type:`data-delta`,data:e.data,encoding:`base64`};if(typeof e.type==`string`)return{type:`block-delta`,fields:{...e}};throw Error(`Unsupported content block delta: ${JSON.stringify(e)}`)}function nI(e){if(e.type===`tool_call_chunk`){let t=e,n;try{n=JSON.parse(t.args??`{}`)}catch{return{type:`invalid_tool_call`,id:t.id,name:t.name,args:t.args,error:`Failed to parse tool call arguments as JSON`}}return{type:`tool_call`,id:t.id,name:t.name,args:n}}return e}function rI(e){let t=[];for(let n of e){let e=n;if(Array.isArray(n.content))for(let t=0;t<n.content.length;t++){let r=n.content[t];(Lb(r)||Rb(r))&&e===n&&(e=new n.constructor({...e,content:[...n.content.slice(0,t),Bb(r),...n.content.slice(t+1)]}))}t.push(e)}return t}var Ose=class e extends ise{lc_namespace=[`langchain`,`chat_models`,this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,`outputVersion`]}constructor(e){super(e),this.outputVersion=ase(()=>{let t=e.outputVersion??HS(`LC_OUTPUT_VERSION`);return t&&[`v0`,`v1`].includes(t)?t:`v0`})}_separateRunnableConfigFromCallOptionsCompat(e){let[t,n]=super._separateRunnableConfigFromCallOptions(e);return n.signal=t.signal,[t,n]}async invoke(t,n){let r=e._convertInputToPromptValue(t);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(e,t,n){throw Error(`Not implemented.`)}async*_streamChatModelEvents(e,t,n){yield*Tse(this._streamResponseChunks(e,t,n),{signal:t.signal})}streamEvents(t,n,r){if(n?.version===`v1`||n?.version===`v2`)return super.streamEvents(t,n,r);let i=e._convertInputToPromptValue(t).toChatMessages(),[,a]=this._separateRunnableConfigFromCallOptionsCompat(n);return new $F(this._streamChatModelEvents(i,a))}streamV2(e,t){return this.streamEvents(e,t)}async*_streamIterator(t,n){if(this._streamResponseChunks===e.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,n);else{let r=e._convertInputToPromptValue(t).toChatMessages(),[i,a]=this._separateRunnableConfigFromCallOptionsCompat(n),o={...i.metadata,...this.getLsParamsWithDefaults(a)},s=this._getInvocationParamsForTracing(a),c=await qO.configure(i.callbacks,this.callbacks,i.tags,this.tags,o,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(s)}),l={options:this._getCallOptionsForTracing(a,s),invocation_params:s,batch_size:1},u=a.outputVersion??this.outputVersion,d=await c?.handleChatModelStart(this.toJSON(),[rI(r)],i.runId,void 0,l,void 0,void 0,i.runName),f,p;try{for await(let e of this._streamResponseChunks(r,a,d?.[0])){if(a.signal?.throwIfAborted(),e.message.id==null){let t=d?.at(0)?.runId;t!=null&&e.message._updateId(`run-${t}`)}e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},u===`v1`?yield RF(e.message):yield e.message,f=f?f.concat(e):e,CS(e.message)&&e.message.usage_metadata!==void 0&&(p={tokenUsage:{promptTokens:e.message.usage_metadata.input_tokens,completionTokens:e.message.usage_metadata.output_tokens,totalTokens:e.message.usage_metadata.total_tokens}})}a.signal?.throwIfAborted()}catch(e){throw await Promise.all((d??[]).map(t=>t?.handleLLMError(e))),e}await Promise.all((d??[]).map(e=>e?.handleLLMEnd({generations:[[f]],llmOutput:p})))}}getLsParams(e){let t=this.getName().startsWith(`Chat`)?this.getName().replace(`Chat`,``):this.getName();return{ls_model_type:`chat`,ls_stop:e.stop,ls_provider:t}}getLsParamsWithDefaults(e){return{...this.getLsParams(e),ls_integration:`langchain_chat_model`}}async _generateUncached(t,n,r,i){let a=t.map(e=>e.map(vS)),o;if(i!==void 0&&i.length===a.length)o=i;else{let e={...r.metadata,...this.getLsParamsWithDefaults(n)},t=this._getInvocationParamsForTracing(n),i=await qO.configure(r.callbacks,this.callbacks,r.tags,this.tags,e,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(t)}),s={options:this._getCallOptionsForTracing(n,t),invocation_params:t,batch_size:1};o=await i?.handleChatModelStart(this.toJSON(),a.map(rI),r.runId,void 0,s,void 0,void 0,r.runName)}let s=n.outputVersion??this.outputVersion,c=[],l=[],u=!!o?.[0].handlers.find(zne),d=!!o?.[0].handlers.find(Rne);if(u&&!this.disableStreaming&&a.length===1&&(this._streamChatModelEvents!==e.prototype._streamChatModelEvents||this._streamResponseChunks!==e.prototype._streamResponseChunks))try{let e=!1,t=o?.[0],r=this._streamChatModelEvents(a[0],n),i=await new $F({async*[Symbol.asyncIterator](){for await(let i of r){n.signal?.throwIfAborted(),e=!0;let r=i.event===`message-start`&&i.id==null&&t?.runId!=null?{...i,id:`run-${t.runId}`}:i;await t?.handleChatModelStreamEvent(r),yield r}}});if(n.signal?.throwIfAborted(),!e)throw Error(`Received empty response from chat model call.`);if(i.id==null){let e=o?.at(0)?.runId;e!=null&&i._updateId(`run-${e}`)}let s={text:i.text,message:i};c.push([s]);let l=i.usage_metadata===void 0?void 0:{tokenUsage:{promptTokens:i.usage_metadata.input_tokens,completionTokens:i.usage_metadata.output_tokens,totalTokens:i.usage_metadata.total_tokens}};await o?.[0].handleLLMEnd({generations:c,llmOutput:l})}catch(e){throw await o?.[0].handleLLMError(e),e}else if(d&&!this.disableStreaming&&a.length===1&&this._streamResponseChunks!==e.prototype._streamResponseChunks)try{let e=await this._streamResponseChunks(a[0],n,o?.[0]),t,r;for await(let i of e){if(n.signal?.aborted){let e=t?.message;throw new Mb(`Model invocation was aborted.`,e)}if(i.message.id==null){let e=o?.at(0)?.runId;e!=null&&i.message._updateId(`run-${e}`)}t=t===void 0?i:ok(t,i),CS(i.message)&&i.message.usage_metadata!==void 0&&(r={tokenUsage:{promptTokens:i.message.usage_metadata.input_tokens,completionTokens:i.message.usage_metadata.output_tokens,totalTokens:i.message.usage_metadata.total_tokens}})}if(n.signal?.aborted){let e=t?.message;throw new Mb(`Model invocation was aborted.`,e)}if(t===void 0)throw Error(`Received empty response from chat model call.`);s===`v1`&&(t.message=RF(t.message)),c.push([t]),await o?.[0].handleLLMEnd({generations:c,llmOutput:r})}catch(e){throw await o?.[0].handleLLMError(e),e}else{let e=await Promise.allSettled(a.map(async(e,t)=>{let r=await this._generate(e,{...n,promptIndex:t},o?.[t]);if(s===`v1`)for(let e of r.generations)e.message=RF(e.message);return r}));await Promise.all(e.map(async(e,t)=>{if(e.status===`fulfilled`){let n=e.value;for(let e of n.generations){if(e.message.id==null){let t=o?.at(0)?.runId;t!=null&&e.message._updateId(`run-${t}`)}e.message.response_metadata={...e.generationInfo,...e.message.response_metadata}}return n.generations.length===1&&(n.generations[0].message.response_metadata={...n.llmOutput,...n.generations[0].message.response_metadata}),c[t]=n.generations,l[t]=n.llmOutput,o?.[t]?.handleLLMEnd({generations:[n.generations],llmOutput:n.llmOutput})}else return await o?.[t]?.handleLLMError(e.reason),Promise.reject(e.reason)}))}let f={generations:c,llmOutput:l.length?this._combineLLMOutput?.(...l):void 0};return Object.defineProperty(f,kk,{value:o?{runIds:o?.map(e=>e.runId)}:void 0,configurable:!0}),f}async _generateCached({messages:t,cache:n,llmStringKey:r,parsedOptions:i,handledOptions:a}){let o=t.map(e=>e.map(vS)),s={...a.metadata,...this.getLsParamsWithDefaults(i)},c=this._getInvocationParamsForTracing(i),l=await qO.configure(a.callbacks,this.callbacks,a.tags,this.tags,s,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(c)}),u={options:this._getCallOptionsForTracing(i,c),invocation_params:c,batch_size:1},d=await l?.handleChatModelStart(this.toJSON(),o.map(rI),a.runId,void 0,u,void 0,void 0,a.runName),f=[],p=(await Promise.allSettled(o.map(async(t,i)=>{let a=e._convertInputToPromptValue(t).toString(),o=await n.lookup(a,r);return o??f.push(i),o}))).map((e,t)=>({result:e,runManager:d?.[t]})).filter(({result:e})=>e.status===`fulfilled`&&e.value!=null||e.status===`rejected`),m=i.outputVersion??this.outputVersion,h=[];await Promise.all(p.map(async({result:e,runManager:t},n)=>{if(e.status===`fulfilled`){let r=e.value;return h[n]=r.map(e=>(`message`in e&&Gx(e.message)&&SS(e.message)&&(e.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},m===`v1`&&(e.message=RF(e.message))),e.generationInfo={...e.generationInfo,tokenUsage:{}},e)),r.length&&await t?.handleLLMNewToken(r[0].text),t?.handleLLMEnd({generations:[r]},void 0,void 0,void 0,{cached:!0})}else return await t?.handleLLMError(e.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(e.reason)}));let g={generations:h,missingPromptIndices:f,startedRunManagers:d};return Object.defineProperty(g,kk,{value:d?{runIds:d?.map(e=>e.runId)}:void 0,configurable:!0}),g}async generate(t,n,r){let i;i=Array.isArray(n)?{stop:n}:n;let a=t.map(e=>e.map(vS)),[o,s]=this._separateRunnableConfigFromCallOptionsCompat(i);if(o.callbacks=o.callbacks??r,!this.cache)return this._generateUncached(a,s,o);let{cache:c}=this,l=this._getSerializedCacheKeyParametersForCall(s),{generations:u,missingPromptIndices:d,startedRunManagers:f}=await this._generateCached({messages:a,cache:c,llmStringKey:l,parsedOptions:s,handledOptions:o}),p={};if(d.length>0){let t=await this._generateUncached(d.map(e=>a[e]),s,o,f===void 0?void 0:d.map(e=>f?.[e]));await Promise.all(t.generations.map(async(t,n)=>{let r=d[n];u[r]=t;let i=e._convertInputToPromptValue(a[r]).toString();return c.update(i,l,t)})),p=t.llmOutput??{}}return{generations:u,llmOutput:p}}_getInvocationParamsForTracing(e){return this.invocationParams(e)}_getCallOptionsForTracing(e,t){return e}invocationParams(e){return{}}_modelType(){return`base_chat_model`}async generatePrompt(e,t,n){let r=e.map(e=>e.toChatMessages());return this.generate(r,t,n)}withStructuredOutput(e,t){if(typeof this.bindTools!=`function`)throw Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`);if(t?.strict)throw Error(`"strict" mode is not supported for this model by default.`);let n=e,r=t?.name,i=sA(n)??`A function available to call.`,a=t?.method,o=t?.includeRaw;if(a===`jsonMode`)throw Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`);let s=r??`extract`;!iA(n)&&!xN(n)&&`name`in n&&(s=n.name);let c=iA(n)||xN(n)?oP(n):n,l=[{type:`function`,function:{name:s,description:i,parameters:c}}];return JF(this.bindTools(l),kP.from(e=>{if(!wS.isInstance(e))throw Error(`Input is not an AIMessageChunk.`);if(!e.tool_calls||e.tool_calls.length===0)throw Error(`No tool calls found in the response.`);let t=e.tool_calls.find(e=>e.name===s);if(!t)throw Error(`No tool call found with name ${s}.`);return t.args}),o,o?`StructuredOutputRunnable`:`StructuredOutput`)}};function iI(e,t){return typeof e==`string`?{model:e,...t??{}}:e??t}var aI=class extends Ose{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model=`gpt-3.5-turbo`;modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return`openai`}static lc_name(){return`ChatOpenAI`}get callKeys(){return[...super.callKeys,`options`,`function_call`,`functions`,`tools`,`tool_choice`,`promptIndex`,`response_format`,`seed`,`reasoning`,`reasoning_effort`,`service_tier`]}lc_serializable=!0;get lc_secrets(){return{apiKey:`OPENAI_API_KEY`,organization:`OPENAI_ORGANIZATION`}}get lc_aliases(){return{apiKey:`openai_api_key`,modelName:`model`}}get lc_serializable_keys(){return`configuration.logprobs.topLogprobs.prefixMessages.supportsStrictToolCalling.modalities.audio.temperature.maxTokens.topP.frequencyPenalty.presencePenalty.n.logitBias.user.streaming.streamUsage.model.modelName.modelKwargs.stop.stopSequences.timeout.apiKey.cache.maxConcurrency.maxRetries.verbose.callbacks.tags.metadata.disableStreaming.zdrEnabled.reasoning.promptCacheKey.promptCacheRetention.verbosity`.split(`.`)}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`openai`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{});let t=typeof e?.configuration?.apiKey==`string`||typeof e?.configuration?.apiKey==`function`?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??t??HS(`OPENAI_API_KEY`),this.organization=e?.configuration?.organization??HS(`OPENAI_ORGANIZATION`),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=e?.promptCacheRetention??this.promptCacheRetention,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.disableStreaming&&(this.streaming=!1),e?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1,this._addVersion(`@langchain/openai`,`1.5.5`)}_getReasoningParams(e){if(!zP(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),e?.reasoningEffort!==void 0&&t?.effort===void 0&&(t={...t,effort:e.reasoningEffort}),t}_getResponseFormat(e){return e&&e.type===`json_schema`&&e.json_schema.schema&&iA(e.json_schema.schema)?Poe(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){let e=KP({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,t.defaultHeaders=XP(t.defaultHeaders),this.client=new Sb(t)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return iF(e)?Iae(e.metadata.customTool):IF(e)?t?.strict===void 0?e:{...e,function:{...e.function,strict:t.strict}}:Eae(e,t)}bindTools(e,t){let n;return t?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=t.strict,this.withConfig({tools:e.map(e=>{if(rF(e)||iF(e))return e;if(kae(e))return e.extras.providerToolDefinition;let t=this._convertChatOpenAIToolToCompletionsTool(e,{strict:n});return $P(e)&&e.extras?.defer_loading===!0?{...t,defer_loading:!0}:t}),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((e,t)=>(t&&t.tokenUsage&&(e.tokenUsage.completionTokens+=t.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=t.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=t.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,n=0,r=0;this.model===`gpt-3.5-turbo-0301`?(n=4,r=-1):(n=3,r=1);let i=await Promise.all(e.map(async e=>{let[i,a]=await Promise.all([this.getNumTokens(e.content),this.getNumTokens(WP(e))]),o=e.name===void 0?0:r+await this.getNumTokens(e.name),s=i+n+a+o,c=e;if(c._getType()===`function`&&(s-=2),c.additional_kwargs?.function_call&&(s+=3),c?.additional_kwargs.function_call?.name&&(s+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{s+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(e){console.error(`Error parsing function arguments`,e,JSON.stringify(c.additional_kwargs.function_call)),s+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return t+=s,s}));return t+=3,{totalCount:t,countPerMessage:i}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,t)=>e+t,0)}async _getEstimatedTokenCountFromPrompt(e,t,n){let r=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&n!==`auto`){let e=Oae(t);r+=await this.getNumTokens(e),r+=9}return t&&e.find(e=>e._getType()===`system`)&&(r-=4),n===`none`?r+=1:typeof n==`object`&&(r+=await this.getNumTokens(n.name)+4),r}async moderateContent(e,t){let n=this._getClientOptions(t?.options),r={input:e,model:t?.model??`omni-moderation-latest`};return this.caller.call(async()=>{try{return await this.client.moderations.create(r,n)}catch(e){throw Fb(e)}})}get profile(){return Ioe[this.model]??{}}_getStructuredOutputMethod(e){let t={...e};if(!this.model.startsWith(`gpt-3`)&&!this.model.startsWith(`gpt-4-`)&&this.model!==`gpt-4`){if(t?.method===void 0)return`jsonSchema`}else t.method===`jsonSchema`&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e};if(t?.strict!==void 0&&t.method===`jsonMode`)throw Error("Argument `strict` is only supported for `method` = 'function_calling'");let s=Moe(this.model,t?.method);if(s===`jsonMode`){r=qF(i);let e=oP(i);n=this.withConfig({outputVersion:`v0`,response_format:{type:`json_object`},ls_structured_output_format:{kwargs:{method:`json_mode`},schema:{title:a??`extract`,...e}}})}else if(s===`jsonSchema`){let e=oP(i),o={name:a??`extract`,description:sA(e),schema:iA(i)?i:e,strict:t?.strict};if(n=this.withConfig({outputVersion:`v0`,response_format:{type:`json_schema`,json_schema:o},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:{title:o.name,description:o.description,...e}}}),iA(i)||xN(i)){let e=qF(i);r=kP.from(async t=>`parsed`in t.additional_kwargs?t.additional_kwargs.parsed:e.invoke(t.content))}else r=new UF}else{let e=a??`extract`,o=oP(i),s;iA(i)||xN(i)?s={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(s=i,e=i.name):(e=i.title??e,s={name:e,description:i.description??``,parameters:i}),n=this.withConfig({outputVersion:`v0`,tools:[{type:`function`,function:s}],tool_choice:{type:`function`,function:{name:e}},ls_structured_output_format:{kwargs:{method:`function_calling`},schema:{title:e,...o}},...t?.strict===void 0?{}:{strict:t.strict}}),r=fse(i,e)}return JF(n,r,o)}},oI={providerName:`ChatOpenAI`,fromStandardTextBlock(e){return{type:`text`,text:e.text}},fromStandardImageBlock(e){if(e.source_type===`url`)return{type:`image_url`,image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if(e.source_type===`base64`)return{type:`image_url`,image_url:{url:`data:${e.mime_type??``};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};throw Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if(e.source_type===`url`){let t=Hb({dataUrl:e.url});if(!t)throw Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);let n=t.mime_type||e.mime_type||``,r;try{r=Vb(n)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!==`audio`||r.subtype!==`wav`&&r.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:r.subtype,data:t.data}}}if(e.source_type===`base64`){let t;try{t=Vb(e.mime_type??``)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(t.type!==`audio`||t.subtype!==`wav`&&t.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:t.subtype,data:e.data}}}throw Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if(e.source_type===`url`){let t=Hb({dataUrl:e.url}),n=UP(e);if(!t)throw Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:`file`,file:{file_data:e.url,filename:n}}}if(e.source_type===`base64`){let t=UP(e);return{type:`file`,file:{file_data:`data:${e.mime_type??``};base64,${e.data}`,filename:t}}}if(e.source_type===`id`)return{type:`file`,file:{file_id:e.id}};throw Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}},kse=({message:e,rawResponse:t,includeRawResponse:n})=>{let r=e.tool_calls,i=e.reasoning_content;switch(e.role){case`assistant`:{let a=[],o=[];for(let e of r??[])try{a.push(WF(e,{returnId:!0}))}catch(t){o.push(KF(e,t.message))}let s={function_call:e.function_call,tool_calls:r};n!==void 0&&(s.__raw_response=t),i!==void 0&&(s.reasoning_content=i);let c={model_provider:`openai`,model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return e.audio&&(s.audio=e.audio),new xS({content:Foe(e.content||``,t.choices?.[0]?.message),tool_calls:a,invalid_tool_calls:o,additional_kwargs:s,response_metadata:c,id:t.id})}default:return new uS(e.content||``,e.role??`unknown`)}},Ase=({delta:e,rawResponse:t,includeRawResponse:n,defaultRole:r})=>{let i=e.role??r,a=e.content??``,o;o=e.function_call?{function_call:e.function_call}:e.tool_calls?{tool_calls:e.tool_calls}:{},n&&(o.__raw_response=t),e.reasoning_content!==void 0&&(o.reasoning_content=e.reasoning_content),e.audio&&(o.audio={...e.audio,index:t.choices[0].index});let s={model_provider:`openai`,usage:{...t.usage}};if(i===`user`)return new mS({content:a,response_metadata:s});if(i===`assistant`){let n=[];if(Array.isArray(e.tool_calls))for(let t of e.tool_calls)n.push({name:t.function?.name,args:t.function?.arguments,id:t.id,index:t.index,type:`tool_call_chunk`});return new wS({content:a,tool_call_chunks:n,additional_kwargs:o,id:t.id,response_metadata:s})}else if(i===`system`)return new gS({content:a,response_metadata:s});else if(i===`developer`)return new gS({content:a,response_metadata:s,additional_kwargs:{__openai_role__:`developer`}});else if(i===`function`)return new fS({content:a,additional_kwargs:o,name:e.name,response_metadata:s});else if(i===`tool`)return new Yte({content:a,additional_kwargs:o,tool_call_id:e.tool_call_id,response_metadata:s});else return new dS({content:a,role:i,response_metadata:s})},jse=e=>{if(e.type===`image`){if(e.url)return{type:`image_url`,image_url:{url:e.url}};if(e.data)return{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}}if(e.type===`audio`&&e.data){let t=fne(()=>{let[,t]=e.mimeType.split(`/`);return t===`wav`||t===`mp3`?t:`wav`});return{type:`input_audio`,input_audio:{data:e.data.toString(),format:t}}}if(e.type===`file`){if(e.data){let t=UP(e);return{type:`file`,file:{file_data:`data:${e.mimeType};base64,${e.data}`,filename:t}}}if(e.fileId)return{type:`file`,file:{file_id:e.fileId}}}},Mse=({message:e,model:t})=>{let n=WP(e);if(n===`system`&&zP(t)&&(n=`developer`),n===`developer`)return{role:`developer`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`system`)return{role:`system`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`assistant`){let t={role:`assistant`,content:e.contentBlocks.filter(e=>e.type===`text`)};return xS.isInstance(e)&&e.tool_calls?.length?t.tool_calls=e.tool_calls.map(GF):e.additional_kwargs.tool_calls!=null&&(t.tool_calls=e.additional_kwargs.tool_calls),t}else if(n===`tool`&&Jx.isInstance(e))return{role:`tool`,tool_call_id:e.tool_call_id,content:e.contentBlocks.filter(e=>e.type===`text`)};else if(n===`function`)return{role:`function`,name:e.name??``,content:e.contentBlocks.filter(e=>e.type===`text`).join(``)};function*r(e){for(let t of e){t.type===`text`&&(yield{type:`text`,text:t.text});let e=jse(t);e&&(yield e)}}return{role:`user`,content:Array.from(r(e.contentBlocks))}},sI=({messages:e,model:t})=>e.flatMap(e=>{if(`output_version`in e.response_metadata&&e.response_metadata?.output_version===`v1`)return Mse({message:e});let n=WP(e);n===`system`&&zP(t)&&(n=`developer`);let r=typeof e.content==`string`?e.content:e.content.flatMap(e=>Ib(e)?Ub(e,oI):typeof e==`object`&&e&&`type`in e&&(e.type===`tool_use`||e.type===`tool_call`||e.type===`reasoning`||e.type===`reasoning_content`||e.type===`thinking`)?[]:e),i={role:n,content:r};return e.name!=null&&(i.name=e.name),e.additional_kwargs.function_call!=null&&(i.function_call=e.additional_kwargs.function_call),xS.isInstance(e)&&e.tool_calls?.length?i.tool_calls=e.tool_calls.map(GF):(e.additional_kwargs.tool_calls!=null&&(i.tool_calls=e.additional_kwargs.tool_calls),Jx.isInstance(e)&&e.tool_call_id!=null&&(i.tool_call_id=e.tool_call_id)),e.additional_kwargs.audio&&typeof e.additional_kwargs.audio==`object`&&`id`in e.additional_kwargs.audio?[i,{role:`assistant`,audio:{id:e.additional_kwargs.audio.id}}]:i});async function*Nse(e,t={}){let n=t.streamUsage??!0,r=t.provider??`openai`,i=t.mapChunk,a=new Map,o=new Map,s=0,c=!1,l,u,d,f=!1,p=(e,t)=>{let n=o.get(e);if(n!==void 0)return{index:n,isNew:!1};let r=s++;return o.set(e,r),a.set(r,{...t}),{index:r,isNew:!0}};for await(let t of e){i&&(t=i(t)),c||(c=!0,yield{event:`message-start`,id:t.id}),!f&&(t.model||t.service_tier)&&(f=!0,yield{event:`provider`,provider:r,name:`stream_metadata`,payload:{model:t.model,service_tier:t.service_tier}}),t.usage&&n&&(l=Lse(t.usage),yield{event:`usage`,usage:l});let e=t.x_groq?.usage;e&&n&&(l=Fse(e),yield{event:`usage`,usage:l});let o=t.choices?.[0];if(!o)continue;o.finish_reason!=null&&(u=Ise(o.finish_reason),d=Rse(t,o));let{delta:s}=o;if(!s)continue;let m=Pse(s);if(m){let{index:e,isNew:t}=p(`reasoning`,{type:`reasoning`,reasoning:``});t&&(yield{event:`content-block-start`,index:e,content:{type:`reasoning`,reasoning:``}});let n=a.get(e);n.reasoning=(n.reasoning??``)+m,yield{event:`content-block-delta`,index:e,delta:{type:`reasoning-delta`,reasoning:m}}}if(s.content){let{index:e,isNew:t}=p(`text`,{type:`text`,text:``});t&&(yield{event:`content-block-start`,index:e,content:{type:`text`,text:``}});let n=a.get(e);n.text=(n.text??``)+s.content,yield{event:`content-block-delta`,index:e,delta:{type:`text-delta`,text:s.content}}}if(Array.isArray(s.tool_calls))for(let e of s.tool_calls){let t=e.index??0,{index:n,isNew:r}=p(`tool:${t}`,{type:`tool_call_chunk`,id:e.id,name:e.function?.name,args:``,index:t});r&&(yield{event:`content-block-start`,index:n,content:{type:`tool_call_chunk`,id:e.id,name:e.function?.name,args:``,index:t}});let i=a.get(n);e.id!=null&&(i.id=e.id),e.function?.name!=null&&(i.name=e.function.name);let o=e.function?.arguments??``;i.args=(i.args??``)+o,yield{event:`content-block-delta`,index:n,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...i.id==null?{}:{id:i.id},...i.name==null?{}:{name:i.name},args:i.args}}}}if(s.audio){let{index:e,isNew:t}=p(`audio`,{type:`audio`,id:s.audio.id,data:``,mimeType:`audio/pcm`,transcript:s.audio.transcript??``});t&&(yield{event:`content-block-start`,index:e,content:{type:`audio`,id:s.audio.id,data:``,mimeType:`audio/pcm`,transcript:s.audio.transcript??``}});let n=a.get(e);s.audio.transcript&&(n.transcript=(n.transcript??``)+s.audio.transcript,yield{event:`content-block-delta`,index:e,delta:{type:`block-delta`,fields:{type:`audio`,transcript:n.transcript}}}),s.audio.data&&(n.data=(n.data??``)+s.audio.data,yield{event:`content-block-delta`,index:e,delta:{type:`data-delta`,data:s.audio.data,encoding:`base64`}})}s.function_call&&(yield{event:`provider`,provider:r,name:`function_call`,payload:s.function_call}),o.logprobs&&(yield{event:`provider`,provider:r,name:`logprobs`,payload:o.logprobs})}for(let[e,t]of a)yield{event:`content-block-finish`,index:e,content:nI(t)};yield{event:`message-finish`,reason:u,...l?{usage:l}:{},...d?{responseMetadata:d}:{}}}function Pse(e){let t=e.reasoning_content??e.reasoning;return typeof t==`string`&&t.length>0?t:void 0}function Fse(e){return{input_tokens:e.prompt_tokens??0,output_tokens:e.completion_tokens??0,total_tokens:e.total_tokens??0}}function Ise(e){switch(e){case`stop`:return`stop`;case`length`:case`max_tokens`:return`length`;case`tool_calls`:case`function_call`:return`tool_use`;case`content_filter`:return`content_filter`;default:return`stop`}}function Lse(e){let t={...e.prompt_tokens_details?.audio_tokens!=null&&{audio:e.prompt_tokens_details.audio_tokens},...e.prompt_tokens_details?.cached_tokens!=null&&{cache_read:e.prompt_tokens_details.cached_tokens}},n={...e.completion_tokens_details?.audio_tokens!=null&&{audio:e.completion_tokens_details.audio_tokens},...e.completion_tokens_details?.reasoning_tokens!=null&&{reasoning:e.completion_tokens_details.reasoning_tokens}};return{input_tokens:e.prompt_tokens??0,output_tokens:e.completion_tokens??0,total_tokens:e.total_tokens??0,...Object.keys(t).length>0&&{input_token_details:t},...Object.keys(n).length>0&&{output_token_details:n}}}function Rse(e,t){return{model_provider:`openai`,model_name:e.model,system_fingerprint:e.system_fingerprint,service_tier:e.service_tier,finish_reason:t.finish_reason,...e.usage?{usage:e.usage}:{}}}var zse=class extends aI{constructor(e,t){super(iI(e,t))}invocationParams(e,t){let n;e?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=e.strict,!(this.streaming||t?.streaming)&&e?.response_format?.type===`json_schema`&&n!==!1&&(n=!0);let r={};e?.stream_options===void 0?this.streamUsage&&(this.streaming||t?.streaming)&&(r={stream_options:{include_usage:!0}}):r={stream_options:e.stream_options};let i={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(e=>this._convertChatOpenAIToolToCompletionsTool(e,{strict:n})):void 0,tool_choice:nF(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...r,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,verbosity:e?.verbosity??this.verbosity};e?.prediction!==void 0&&(i.prediction=e.prediction),this.service_tier!==void 0&&(i.service_tier=this.service_tier),e?.service_tier!==void 0&&(i.service_tier=e.service_tier);let a=this._getReasoningParams(e);return a!==void 0&&a.effort!==void 0&&(i.reasoning_effort=a.effort),zP(i.model)?i.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:i.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,i}async _generate(e,t,n){t.signal?.throwIfAborted();let r={},i=this.invocationParams(t),a=sI({messages:e,model:this.model});if(i.stream){let i=this._streamResponseChunks(e,t,n),a={};for await(let e of i){e.message.response_metadata={...e.generationInfo,...e.message.response_metadata};let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}let o=Object.entries(a).sort(([e],[t])=>parseInt(e,10)-parseInt(t,10)).map(([e,t])=>t),{functions:s,function_call:c}=this.invocationParams(t),l=await this._getEstimatedTokenCountFromPrompt(e,s,c),u=await this._getNumTokensFromGenerations(o);return r.input_tokens=l,r.output_tokens=u,r.total_tokens=l+u,{generations:o,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{let e=await this.completionWithRetry({...i,stream:!1,messages:a},{signal:t?.signal,...t?.options}),{completion_tokens:n,prompt_tokens:o,total_tokens:s,prompt_tokens_details:c,completion_tokens_details:l}=e?.usage??{};n&&(r.output_tokens=(r.output_tokens??0)+n),o&&(r.input_tokens=(r.input_tokens??0)+o),s&&(r.total_tokens=(r.total_tokens??0)+s),(c?.audio_tokens!==null||c?.cached_tokens!==null)&&(r.input_token_details={...c?.audio_tokens!==null&&{audio:c?.audio_tokens},...c?.cached_tokens!==null&&{cache_read:c?.cached_tokens}}),(l?.audio_tokens!==null||l?.reasoning_tokens!==null)&&(r.output_token_details={...l?.audio_tokens!==null&&{audio:l?.audio_tokens},...l?.reasoning_tokens!==null&&{reasoning:l?.reasoning_tokens}});let u=[];for(let t of e?.choices??[]){let n={text:t.message?.content??``,message:this._convertCompletionsMessageToBaseMessage(t.message??{role:`assistant`},e)};n.generationInfo={...t.finish_reason?{finish_reason:t.finish_reason}:{},...t.logprobs?{logprobs:t.logprobs}:{}},SS(n.message)&&(n.message.usage_metadata=r),n.message=new xS(Object.fromEntries(Object.entries(n.message).filter(([e])=>!e.startsWith(`lc_`)))),u.push(n)}return{generations:u,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamChatModelEvents(e,t,n){let r=sI({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a=await this.completionWithRetry(i,t),o=this.streamUsage??t.streamUsage;yield*Nse(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(a,t.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return`openai`}async*_streamResponseChunks(e,t,n){let r=sI({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a,o=await this.completionWithRetry(i,t),s;for await(let e of o){if(t.signal?.aborted)return;let r=e?.choices?.[0];if(e.usage&&(s=e.usage),!r)continue;let{delta:i}=r;if(!i)continue;let o=this._convertCompletionsDeltaToBaseMessageChunk(i,e,a);a=i.role??a;let c={prompt:t.promptIndex??0,completion:r.index??0};if(typeof o.content!=`string`){console.log(`[WARNING]: Received non-string content from OpenAI. This is currently not supported.`);continue}let l={...c};r.finish_reason!=null&&(l.finish_reason=r.finish_reason,l.system_fingerprint=e.system_fingerprint,l.model_name=e.model,l.service_tier=e.service_tier),this.logprobs&&(l.logprobs=r.logprobs);let u=new jk({message:o,text:o.content,generationInfo:l});yield u,await n?.handleLLMNewToken(u.text??``,c,void 0,void 0,void 0,{chunk:u})}if(s){let e={...s.prompt_tokens_details?.audio_tokens!==null&&{audio:s.prompt_tokens_details?.audio_tokens},...s.prompt_tokens_details?.cached_tokens!==null&&{cache_read:s.prompt_tokens_details?.cached_tokens}},t={...s.completion_tokens_details?.audio_tokens!==null&&{audio:s.completion_tokens_details?.audio_tokens},...s.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:s.completion_tokens_details?.reasoning_tokens}},r=new jk({message:new wS({content:``,response_metadata:{usage:{...s}},usage_metadata:{input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,total_tokens:s.total_tokens,...Object.keys(e).length>0&&{input_token_details:e},...Object.keys(t).length>0&&{output_token_details:t}}}),text:``});yield r,await n?.handleLLMNewToken(r.text??``,{prompt:0,completion:0},void 0,void 0,void 0,{chunk:r})}if(t.signal?.aborted)throw Error(`AbortError`)}async completionWithRetry(e,t){let n=this._getClientOptions(t),r=e.response_format&&e.response_format.type===`json_schema`;return this.caller.call(async()=>{try{return r&&!e.stream?await this.client.chat.completions.parse(e,n):await this.client.chat.completions.create(e,n)}catch(e){throw Fb(e)}})}_convertCompletionsDeltaToBaseMessageChunk(e,t,n){return Ase({delta:e,rawResponse:t,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(e,t){return kse({message:e,rawResponse:t,includeRawResponse:this.__includeRawResponse})}},cI=`__openai_function_call_ids__`,lI=`__openai_custom_tool_call_ids__`;function uI(e){return e.type===`url_citation`?{type:`citation`,source:`url_citation`,url:e.url,title:e.title,startIndex:e.start_index,endIndex:e.end_index}:e.type===`file_citation`?{type:`citation`,source:`file_citation`,title:e.filename,startIndex:e.index,file_id:e.file_id}:e.type===`container_file_citation`?{type:`citation`,source:`container_file_citation`,title:e.filename,startIndex:e.start_index,endIndex:e.end_index,file_id:e.file_id,container_id:e.container_id}:e.type===`file_path`?{type:`citation`,source:`file_path`,startIndex:e.index,file_id:e.file_id}:{type:`non_standard`,value:e}}function Bse(e){if(e.type===`url_citation`||e.type===`file_citation`||e.type===`container_file_citation`||e.type===`file_path`)return e;if(e.type===`citation`){let t=e;if(t.source===`url_citation`)return{type:`url_citation`,url:t.url??``,title:t.title??``,start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source===`file_citation`)return{type:`file_citation`,file_id:t.file_id??``,filename:t.title??``,index:t.startIndex??0};if(t.source===`container_file_citation`)return{type:`container_file_citation`,file_id:t.file_id??``,filename:t.title??``,container_id:t.container_id??``,start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source===`file_path`)return{type:`file_path`,file_id:t.file_id??``,index:t.startIndex??0}}return e.type===`non_standard`?e.value:e}var dI=e=>{let t={...e?.input_tokens_details?.cached_tokens!=null&&{cache_read:e?.input_tokens_details?.cached_tokens}},n={...e?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:e?.output_tokens_details?.reasoning_tokens}};return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,input_token_details:t,output_token_details:n}},fI=e=>{if(e.error){let t=Error(e.error.message);throw t.name=e.error.code,t}let t=[],n=[],r=[],i=e.output.map(e=>{if(e.type===`function_call`&&`parsed_arguments`in e){let t={...e};return delete t.parsed_arguments,t}return e}),a={model_provider:`openai`,model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,output:i,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(let i of e.output)if(i.type===`message`)t.push(...i.content.flatMap(e=>e.type===`output_text`?(`parsed`in e&&e.parsed!=null&&(o.parsed=e.parsed),{type:`text`,text:e.text,annotations:e.annotations.map(uI),...i.phase===null?{}:{phase:i.phase}}):e.type===`refusal`?(o.refusal=e.refusal,[]):e));else if(i.type===`function_call`){let e={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{n.push(WF(e,{returnId:!0}))}catch(t){let n;typeof t==`object`&&t&&`message`in t&&typeof t.message==`string`&&(n=t.message),r.push(KF(e,n))}o[cI]??={},i.id&&(o[cI][i.call_id]=i.id)}else if(i.type===`reasoning`){o.reasoning=i;let e=i.summary?.map(e=>e.text).filter(Boolean).join(``);e&&t.push({type:`reasoning`,reasoning:e})}else if(i.type===`custom_tool_call`){let e=jae(i);e?(n.push(e),o[lI]??={},i.id&&i.call_id&&(o[lI][i.call_id]=i.id)):r.push(KF(i,`Malformed custom tool call`))}else if(i.type===`computer_call`){let e=Mae(i);e?n.push(e):r.push(KF(i,`Malformed computer call`))}else i.type===`image_generation_call`?(i.result&&t.push({type:`image`,mimeType:`image/png`,data:i.result,id:i.id,metadata:{status:i.status}}),o.tool_outputs??=[],o.tool_outputs.push(i)):(o.tool_outputs??=[],o.tool_outputs.push(i));return new xS({id:e.id,content:t,tool_calls:n,invalid_tool_calls:r,usage_metadata:dI(e.usage),additional_kwargs:o,response_metadata:a})},Vse=e=>{let t=(e.summary.length>1?e.summary.reduce((e,t)=>{let n=e[e.length-1];return n.index===t.index?n.text+=t.text:e.push(t),e},[{...e.summary[0]}]):e.summary).map(e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==`index`)));return{...e,summary:t}},Hse=e=>{let t=[],n={},r,i=[],a={model_provider:`openai`},o={},s;if(e.type===`response.output_text.delta`)t.push({type:`text`,text:e.delta,index:e.content_index});else if(e.type===`response.output_text.annotation.added`)t.push({type:`text`,text:``,annotations:[uI(e.annotation)],index:e.content_index});else if(e.type===`response.output_item.added`&&e.item.type===`message`){let n=`phase`in e.item?e.item.phase:void 0;n&&t.push({type:`text`,text:``,phase:n,index:0})}else if(e.type===`response.output_item.added`&&e.item.type===`function_call`)i.push({type:`tool_call_chunk`,name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),o[cI]={[e.item.call_id]:e.item.id};else if(e.type===`response.output_item.added`&&e.item.type===`custom_tool_call`)i.push({type:`tool_call_chunk`,isCustomTool:!0,name:e.item.name,args:e.item.input,id:e.item.call_id,index:e.output_index}),o[lI]={[e.item.call_id]:e.item.id};else if(e.type===`response.output_item.done`&&e.item.type===`computer_call`)i.push({type:`tool_call_chunk`,name:`computer_use`,args:JSON.stringify({action:e.item.action}),id:e.item.call_id,index:e.output_index}),o.tool_outputs=[e.item];else if(e.type===`response.output_item.done`&&e.item.type===`image_generation_call`)e.item.result&&t.push({type:`image`,mimeType:`image/png`,data:e.item.result,id:e.item.id,metadata:{status:e.item.status}}),o.tool_outputs=[e.item];else if(e.type===`response.output_item.done`&&[`web_search_call`,`file_search_call`,`code_interpreter_call`,`shell_call`,`local_shell_call`,`mcp_call`,`mcp_list_tools`,`mcp_approval_request`,`custom_tool_call`,`tool_search_call`,`tool_search_output`].includes(e.item.type))o.tool_outputs=[e.item];else if(e.type===`response.created`)s=e.response.id,a.id=e.response.id,a.model_name=e.response.model,a.model=e.response.model;else if(e.type===`response.completed`||e.type===`response.incomplete`){s=e.response.id;let t=fI(e.response);if(r=dI(e.response.usage),e.response.text?.format?.type===`json_schema`&&t.text)try{o.parsed??=JSON.parse(t.text)}catch{}for(let[n,r]of Object.entries(e.response))n!==`id`&&(n===`output`?a[n]=t.response_metadata.output:a[n]=r)}else if(e.type===`response.function_call_arguments.delta`||e.type===`response.custom_tool_call_input.delta`)i.push({type:`tool_call_chunk`,args:e.delta,index:e.output_index,...e.type===`response.custom_tool_call_input.delta`?{isCustomTool:!0}:{}});else if(e.type===`response.web_search_call.in_progress`||e.type===`response.web_search_call.searching`||e.type===`response.web_search_call.completed`||e.type===`response.file_search_call.in_progress`||e.type===`response.file_search_call.searching`||e.type===`response.file_search_call.completed`||e.type===`response.image_generation_call.in_progress`||e.type===`response.image_generation_call.generating`||e.type===`response.image_generation_call.completed`){let[,t,r]=e.type.match(/^response\.(.*)\.([^.]+)$/)??[``,``,``];n={tool_outputs:{id:e.item_id,type:t,status:r}}}else if(e.type===`response.refusal.done`)o.refusal=e.refusal;else if(e.type===`response.output_item.added`&&`item`in e&&e.item.type===`reasoning`){let n=e.item.summary?e.item.summary.map((e,t)=>({...e,index:t})):void 0;o.reasoning={id:e.item.id,type:e.item.type,...n?{summary:n}:{}};let r=e.item.summary?.map(e=>e.text).filter(Boolean).join(``);r&&t.push({type:`reasoning`,reasoning:r})}else if(e.type===`response.reasoning_summary_part.added`)o.reasoning={type:`reasoning`,summary:[{...e.part,index:e.summary_index}]},e.part.text&&t.push({type:`reasoning`,reasoning:e.part.text,index:e.summary_index});else if(e.type===`response.reasoning_summary_text.delta`)o.reasoning={type:`reasoning`,summary:[{text:e.delta,type:`summary_text`,index:e.summary_index}]},e.delta&&t.push({type:`reasoning`,reasoning:e.delta,index:e.summary_index});else if(e.type===`response.image_generation_call.partial_image`)return null;else return null;return new jk({text:t.map(e=>e.text).join(``),message:new wS({id:s,content:t,tool_call_chunks:i,usage_metadata:r,additional_kwargs:o,response_metadata:a}),generationInfo:n})},Use=e=>{let t=xS.isInstance(e)&&e.response_metadata?.model_provider===`openai`;function*n(){let n=RP(()=>{try{let t=WP(e);return t===`system`||t===`developer`||t===`assistant`||t===`user`?t:`assistant`}catch{return`assistant`}}),r=e=>n===`assistant`?{type:`output_text`,text:e,annotations:[]}:{type:`input_text`,text:e},i,a=new Set,o=new Set,s=new Map,c=new Map;function*l(){if(!i)return;let e=i.content;(typeof e==`string`&&e.length>0||Array.isArray(e)&&e.length>0)&&(yield i),i=void 0}let u=(e,t)=>{i||={type:`message`,role:n,content:[],...t?{phase:t}:{}},typeof i.content==`string`?i.content=i.content.length>0?[r(i.content),...e]:[...e]:i.content.push(...e)},d=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e??{})}catch{return`{}`}},f=e=>{let t=RP(()=>{let t=e.metadata?.detail;return t===`low`||t===`high`||t===`auto`?t:`auto`});if(e.fileId)return{type:`input_image`,detail:t,file_id:e.fileId};if(e.url)return{type:`input_image`,detail:t,image_url:e.url};if(e.data){let n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_image`,detail:t,image_url:`data:${e.mimeType??`image/png`};base64,${n}`}}},p=e=>{if(e.fileId){let t=VP(e);return{type:`input_file`,file_id:e.fileId,...t?{filename:t}:{}}}if(e.url){let t=VP(e);return{...t?{filename:t}:{},type:`input_file`,file_url:e.url}}if(e.data){let t=UP(e),n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_file`,file_data:`data:${e.mimeType??`application/octet-stream`};base64,${n}`,filename:t}}},m=e=>{let t=RP(()=>{if(Array.isArray(e.summary)){let t=e.summary?.map(e=>e?.text).filter(e=>typeof e==`string`)??[];if(t.length>0)return t}return e.reasoning?[e.reasoning]:[]}),n=t.length>0?t.map(e=>({type:`summary_text`,text:e})):[{type:`summary_text`,text:``}];return{type:`reasoning`,...e.id?{id:e.id}:{},summary:n}},h=e=>({type:`function_call`,name:e.name??``,call_id:e.id??``,arguments:d(e.args)}),g=e=>{let t=d(e.output),n=e.status===`success`?`completed`:e.status===`error`?`incomplete`:void 0;return{type:`function_call_output`,call_id:e.toolCallId??``,output:t,...n?{status:n}:{}}};for(let n of e.contentBlocks)if(n.type===`text`){let e=RP(()=>{if(`extras`in n&&typeof n.extras==`object`&&n.extras!==null&&`phase`in n.extras)return n.extras.phase});u([r(n.text)],e)}else if(n.type!==`invalid_tool_call`){if(n.type===`reasoning`)yield*l(),yield m(n);else if(n.type===`tool_call`){yield*l();let e=n.id??``;e&&(a.add(e),s.delete(e)),yield h(n)}else if(n.type===`tool_call_chunk`){if(n.id){let e=s.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),s.set(n.id,e)}}else if(n.type===`server_tool_call`){yield*l();let e=n.id??``;e&&(o.add(e),c.delete(e)),yield h(n)}else if(n.type===`server_tool_call_chunk`){if(n.id){let e=c.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),c.set(n.id,e)}}else if(n.type===`server_tool_call_result`)yield*l(),yield g(n);else if(n.type!==`audio`)if(n.type===`file`){let e=p(n);e&&u([e])}else if(n.type===`image`){let e=f(n);e&&u([e])}else if(n.type===`video`){let e=p(n);e&&u([e])}else n.type===`text-plain`?n.text&&u([r(n.text)]):n.type===`non_standard`&&t&&(yield*l(),yield n.value)}yield*l();for(let[e,t]of s){if(!e||a.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}for(let[e,t]of c){if(!e||o.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}}return Array.from(n())},pI=({messages:e,zdrEnabled:t,model:n})=>e.flatMap(e=>{let r=e.response_metadata;if(r?.output_version===`v1`)return Use(e);let i=e.additional_kwargs,a=WP(e);if(a===`system`&&zP(n)&&(a=`developer`),a===`function`)throw Error(`Function messages are not supported in Responses API`);if(a===`tool`){let t=e;if(i?.type===`computer_call_output`)return{type:`computer_call_output`,output:(()=>{if(typeof t.content==`string`)return{type:`input_image`,image_url:t.content};if(Array.isArray(t.content)){let e=t.content.find(e=>e.type===`input_image`);if(e)return e;let n=t.content.find(e=>e.type===`computer_screenshot`);if(n)return n;let r=t.content.find(e=>e.type===`image_url`);if(r)return{type:`input_image`,image_url:typeof r.image_url==`string`?r.image_url:r.image_url.url}}throw Error(`Invalid computer call output`)})(),call_id:t.tool_call_id};if(t.additional_kwargs?.customTool)return{type:`custom_tool_call_output`,call_id:t.tool_call_id,output:t.content};let n=Array.isArray(t.content)&&t.content.every(e=>typeof e==`object`&&!!e&&`type`in e&&(e.type===`input_file`||e.type===`input_image`||e.type===`input_text`));return{type:`function_call_output`,call_id:t.tool_call_id,id:t.id?.startsWith(`fc_`)?t.id:void 0,output:n||typeof t.content==`string`?t.content:JSON.stringify(t.content)}}if(a===`assistant`){if(!t&&r?.output!=null&&Array.isArray(r?.output)&&r?.output.length>0&&r?.output.every(e=>`type`in e))return r?.output;let n=[],a=i?.reasoning,o=!!a?.encrypted_content;if(a&&(!t||o)){let e=Vse(a);n.push(e)}let{content:s}=e;if(i?.refusal&&(typeof s==`string`&&(s=[{type:`output_text`,text:s,annotations:[]}]),s=[...s,{type:`refusal`,refusal:i.refusal}]),typeof s==`string`||s.length>0){let r={type:`message`,role:`assistant`,...e.id&&!t&&e.id.startsWith(`msg_`)?{id:e.id}:{},content:RP(()=>typeof s==`string`?s:s.flatMap(e=>{if(e.type===`text`){let t=e;return{type:`output_text`,text:t.text,annotations:(t.annotations??[]).map(Bse)}}return e.type===`output_text`||e.type===`refusal`?e:[]})),phase:RP(()=>{if(Array.isArray(s))return s.find(e=>`phase`in e&&typeof e.phase==`string`)?.phase})};n.push(r)}let c=i?.[cI],l=i?.[lI];xS.isInstance(e)&&e.tool_calls?.length?n.push(...e.tool_calls.map(e=>Pae(e,l)?{type:`custom_tool_call`,id:`call_id`in e&&typeof e.call_id==`string`?e.call_id:l?.[e.id??``]??``,call_id:e.id??``,input:e.args.input,name:e.name}:Nae(e)?{type:`computer_call`,id:e.call_id,call_id:e.id??``,action:e.args.action}:{type:`function_call`,name:e.name,arguments:JSON.stringify(e.args),call_id:e.id,...t?{}:{id:c?.[e.id]}})):i?.tool_calls&&n.push(...i.tool_calls.map(e=>({type:`function_call`,name:e.function.name,call_id:e.id,arguments:e.function.arguments,...t?{}:{id:c?.[e.id]}})));let u=r?.output?.length?r?.output:i.tool_outputs,d=[`computer_call`,`mcp_call`,`code_interpreter_call`,`image_generation_call`,`shell_call`,`local_shell_call`];if(u!=null){let e=u?.filter(e=>d.includes(e.type));e.length>0&&n.push(...e)}return n}if(a===`user`||a===`system`||a===`developer`){if(typeof e.content==`string`)return{type:`message`,role:a,content:e.content};let t=[],n=e.content.flatMap(e=>{if(e.type===`mcp_approval_response`&&t.push({type:`mcp_approval_response`,approval_request_id:e.approval_request_id,approve:e.approve}),Ib(e)){if(e.type===`file`){let t=VP(e);if(e.source_type===`url`)return{type:`input_file`,file_url:e.url,...t?{filename:t}:{}};if(e.source_type===`id`)return{type:`input_file`,file_id:e.id,...t?{filename:t}:{}};if(e.source_type===`base64`)return{type:`input_file`,file_data:`data:${e.mime_type??``};base64,${e.data}`,filename:UP(e)}}return Ub(e,oI)}return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`image_url`?{type:`input_image`,image_url:RP(()=>{if(typeof e.image_url==`string`)return e.image_url;if(typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url)return e.image_url.url}),detail:RP(()=>{if(typeof e.image_url==`string`)return`auto`;if(typeof e.image_url==`object`&&e.image_url!==null&&`detail`in e.image_url)return e.image_url.detail})}:e.type===`input_text`||e.type===`input_image`||e.type===`input_file`?e:[]});return n.length>0&&t.push({type:`message`,role:a,content:n}),t}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});async function*Wse(e,t={}){let n=t.streamUsage??!0,r=t.provider??`openai`,i=new Map,a=new Map,o=0,s=!1,c,l,u,d,f=new Set,p=(e,t)=>{let n=a.get(e);if(n!==void 0)return{index:n,isNew:!1};let r=o++;return a.set(e,r),i.set(r,{...t}),{index:r,isNew:!0}},m=function*(){s||(s=!0,yield{event:`message-start`,id:c})},h=function*(e){if(f.has(e))return;let t=i.get(e);t&&(f.add(e),yield{event:`content-block-finish`,index:e,content:nI(t)})};for await(let t of e){if(t.type===`response.created`){c=t.response.id,yield*m(),yield{event:`provider`,provider:r,name:`response.created`,payload:{model:t.response.model,id:t.response.id}};continue}if(t.type===`response.output_text.delta`){yield*m();let{index:e,isNew:n}=p(`text:${t.output_index}:${t.content_index}`,{type:`text`,text:``});n&&(yield{event:`content-block-start`,index:e,content:{type:`text`,text:``}});let r=i.get(e);r.text=(r.text??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`text-delta`,text:t.delta}};continue}if(t.type===`response.reasoning_summary_text.delta`){yield*m();let{index:e,isNew:n}=p(`reasoning:${t.output_index}:${t.summary_index}`,{type:`reasoning`,reasoning:``});n&&(yield{event:`content-block-start`,index:e,content:{type:`reasoning`,reasoning:``}});let r=i.get(e);r.reasoning=(r.reasoning??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`reasoning-delta`,reasoning:t.delta}};continue}if(t.type===`response.output_item.added`&&(t.item.type===`function_call`||t.item.type===`custom_tool_call`)){yield*m();let e=`tool:${t.output_index}`,n=t.item.type===`custom_tool_call`,r=t.item.type===`function_call`?t.item.arguments??``:t.item.input??``,{index:a,isNew:o}=p(e,{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:r,index:t.output_index,...n?{isCustomTool:!0}:{}});if(o&&(yield{event:`content-block-start`,index:a,content:{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:r,index:t.output_index}}),r){let e=i.get(a);yield{event:`content-block-delta`,index:a,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...e.id==null?{}:{id:e.id},...e.name==null?{}:{name:e.name},args:e.args}}}}continue}if(t.type===`response.function_call_arguments.delta`||t.type===`response.custom_tool_call_input.delta`){yield*m();let{index:e,isNew:n}=p(`tool:${t.output_index}`,{type:`tool_call_chunk`,args:``,index:t.output_index,...t.type===`response.custom_tool_call_input.delta`?{isCustomTool:!0}:{}});n&&(yield{event:`content-block-start`,index:e,content:{type:`tool_call_chunk`,args:``,index:t.output_index}});let r=i.get(e);r.args=(r.args??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...r.id==null?{}:{id:r.id},...r.name==null?{}:{name:r.name},args:r.args}}};continue}if(t.type===`response.output_item.done`&&(t.item.type===`function_call`||t.item.type===`custom_tool_call`)){yield*m();let e=`tool:${t.output_index}`,n=t.item.type===`function_call`?t.item.arguments??``:t.item.input??``,{index:r,isNew:a}=p(e,{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:n,index:t.output_index});if(a)yield{event:`content-block-start`,index:r,content:{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:n,index:t.output_index}};else{let e=i.get(r);e.args=n,e.id=t.item.call_id,e.name=t.item.name}yield*h(r);continue}if(t.type===`response.completed`||t.type===`response.incomplete`){yield*m(),c=t.response.id,u=Gse(t.response.status,t.type),d={model_provider:r,id:t.response.id,model:t.response.model,status:t.response.status},n&&t.response.usage&&(l=dI(t.response.usage),yield{event:`usage`,usage:l});continue}t.type!==`response.image_generation_call.partial_image`&&(yield*m(),yield{event:`provider`,provider:r,name:t.type,payload:t})}s||(yield{event:`message-start`});for(let[e]of i)f.has(e)||(yield*h(e));yield{event:`message-finish`,reason:u,...l?{usage:l}:{},...d?{responseMetadata:d}:{}}}function Gse(e,t){return t===`response.incomplete`?`length`:e===`completed`?`stop`:e===`incomplete`?`length`:`stop`}var Kse=class extends aI{constructor(e,t){super(iI(e,t))}invocationParams(e){let t;e?.strict!==void 0&&(t=e.strict),t===void 0&&this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:Aae(e?.tool_choice)?e?.tool_choice:(()=>{let t=nF(e?.tool_choice);if(typeof t==`object`&&`type`in t){if(t.type===`function`)return{type:`function`,name:t.function.name};if(t.type===`allowed_tools`)return{type:`allowed_tools`,mode:t.allowed_tools.mode,tools:t.allowed_tools.tools};if(t.type===`custom`)return{type:`custom`,name:t.custom.name}}})(),text:(()=>{if(e?.text)return e.text;let t=this._getResponseFormat(e?.response_format);return t?.type===`json_schema`?t.json_schema.schema==null?void 0:{format:{type:`json_schema`,schema:t.json_schema.schema,description:t.json_schema.description,name:t.json_schema.name,strict:t.json_schema.strict},verbosity:e?.verbosity}:{format:t,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(e);return r!==void 0&&(n.reasoning=r),n}async _generate(e,t,n){t.signal?.throwIfAborted();let r=this.invocationParams(t);if(r.stream){let r=this._streamResponseChunks(e,t,n),i;for await(let e of r)e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},i=i?.concat(e)??e;return{generations:i?[i]:[],llmOutput:{estimatedTokenUsage:i?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:pI({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:n.output_text,message:fI(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:pI({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t),i=this.streamUsage??t.streamUsage;yield*Wse(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(r,t.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return`openai`}async*_streamResponseChunks(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:pI({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t);try{for await(let e of r){if(t.signal?.aborted)return;let r=Hse(e);r!=null&&(yield r,await n?.handleLLMNewToken(r.text||``,{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:r}))}}catch(e){throw Fb(e)}}async completionWithRetry(e,t){return this.caller.call(async()=>{let n=this._getClientOptions(t);try{return e.text?.format?.type===`json_schema`&&!e.stream?await this.client.responses.parse(e,n):await this.client.responses.create(e,n)}catch(e){throw Fb(e)}})}_reduceChatOpenAITools(e,t){let n=[];for(let r of e)if(rF(r))r.type===`image_generation`&&t?.stream&&(r.partial_images=1),n.push(r);else if(iF(r)){let e=r.metadata.customTool;n.push({type:`custom`,name:e.name,description:e.description,format:e.format})}else if(IF(r)){let e={};for(let[t,n]of Object.entries(r))t!==`type`&&t!==`function`&&(e[t]=n);n.push({type:`function`,name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:t?.strict??null,...e})}else aF(r)&&n.push(Fae(r));return n}},mI=class e extends aI{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,`useResponsesApi`]}get callKeys(){return[...super.callKeys,`useResponsesApi`]}fields;constructor(e,t){let n=iI(e,t);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Kse(n),this.completions=n?.completions??new zse(n)}_useResponsesApi(e){let t=e?.tools?.some(rF),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,r=e?.tools?.some(aF)||e?.tools?.some(iF);return this.useResponsesApi||t||n||r||GP(this.model)}getLsParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(t):this.completions.getLsParams(t)}invocationParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(t):this.completions.invocationParams(t)}async _generate(e,t,n){return this._useResponsesApi(t)?this.responses._generate(e,t,n):this.completions._generate(e,t,n)}async*_streamChatModelEvents(e,t,n){if(this._useResponsesApi(t)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(t),n);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(t),n)}async*_streamResponseChunks(e,t,n){if(this._useResponsesApi(t)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(t),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(t),n)}withConfig(t){let n=new e(this.fields);return n.defaultOptions={...this.defaultOptions,...t},n}};wM(),oF();var hI=class extends LF{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return[`langchain`,`tools`]}responseFormat=`content`;defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}async invoke(e,t){let n,r=$O(QO(this.defaultConfig,t));return oS(e)?(n=e.args,r={...r,toolCall:e}):n=e,this.call(n,r)}async call(e,t,n){let r=oS(e)?e.args:e,i;if(iA(this.schema))try{i=await oA(this.schema,r)}catch(t){let n=`Received tool input did not match expected schema`;throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.message}`),yA(t)&&(n=`${n}\n\n${st(t)}`),new sS(n,JSON.stringify(e))}else{let t=iP(r,this.schema);if(!t.valid){let n=`Received tool input did not match expected schema`;throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.errors.map(e=>`${e.keywordLocation}: ${e.error}`).join(`
|
|
148
|
-
`)}`),new sS(n,JSON.stringify(e))}i=r}let a=WO(t),o=qO.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),s;oS(e)&&(s=e.id),!s&&cne(a)&&(s=a.toolCall.id);let c=await o?.handleToolStart(this.toJSON(),typeof e==`string`?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName,s);delete a.runId;let l;try{let e=await this._call(i,c,a);l=_P(e)?await vP(e,async e=>{try{await c?.handleToolEvent(e)}catch(e){await c?.handleToolError(e)}}):e}catch(e){throw await c?.handleToolError(e),e}let u,d;if(this.responseFormat===`content_and_artifact`)if(Array.isArray(l)&&l.length===2)[u,d]=l;else throw Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(l)}`);else u=l;let f=Zse({content:u,artifact:d,toolCallId:s,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(f),f}},qse=class extends hI{schema=xM({input:yM().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){let n=typeof e==`string`||e==null?{input:e}:e;return super.call(n,t)}},Jse=class extends qse{static lc_name(){return`DynamicTool`}name;description;func;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){let n=WO(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}_call(e,t,n){return this.func(e,t,n)}},Yse=class extends hI{static lc_name(){return`DynamicStructuredTool`}description;func;schema;constructor(e){super(e),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,n){let r=WO(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r,n)}_call(e,t,n){return this.func(e,t,n)}};function gI(e,t){let n=cA(t.schema),r=sP(t.schema);if(!t.schema||n||r)return new Jse({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(t,n,r)=>new Promise((i,a)=>{let o=ek(r,{callbacks:n?.getChild()});XO.runWithConfig(tk(o),async()=>{try{i(e(t,o))}catch(e){a(e)}})})});let i=t.schema,a=t.description??t.schema.description??`${t.name} tool`;return new Yse({...t,description:a,schema:i,func:async(t,n,r)=>new Promise((i,a)=>{let o,s=()=>{r?.signal&&o&&r.signal.removeEventListener(`abort`,o)};r?.signal&&(o=()=>{s(),a(rk(r.signal))},r.signal.addEventListener(`abort`,o,{once:!0}));let c=ek(r,{callbacks:n?.getChild()});XO.runWithConfig(tk(c),async()=>{try{let n=await e(t,c);if(_P(n)){i(n);return}if(r?.signal?.aborted){s();return}s(),i(n)}catch(e){s(),a(e)}})})})}function Xse(e){return typeof e==`object`&&!!e&&`type`in e}function Zse(e){let{content:t,artifact:n,toolCallId:r,metadata:i}=e;return r&&!Jte(t)?typeof t==`string`||Array.isArray(t)&&t.every(Xse)?new Jx({status:`success`,content:t,artifact:n,tool_call_id:r,name:e.name,metadata:i}):new Jx({status:`success`,content:Qse(t),artifact:n,tool_call_id:r,name:e.name,metadata:i}):t}function Qse(e){try{return JSON.stringify(e)??``}catch{return`${e}`}}oF(),F({action:ef([F({type:I(`screenshot`)}),F({type:I(`click`),x:Nd(),y:Nd(),button:df([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),F({type:I(`double_click`),x:Nd(),y:Nd(),button:df([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),F({type:I(`drag`),path:P(F({x:Nd(),y:Nd()}))}),F({type:I(`keypress`),keys:P(N())}),F({type:I(`move`),x:Nd(),y:Nd()}),F({type:I(`scroll`),x:Nd(),y:Nd(),scroll_x:Nd(),scroll_y:Nd()}),F({type:I(`type`),text:N()}),F({type:I(`wait`),duration:Nd().optional()})])}),oF(),ef([F({type:I(`exec`),command:P(N()),env:of(N(),N()).optional(),working_directory:N().optional(),timeout_ms:Nd().optional(),user:N().optional()})]),oF(),F({commands:P(N()).describe(`Array of shell commands to execute`),timeout_ms:Nd().optional().describe(`Optional timeout in milliseconds for the commands`),max_output_length:Nd().optional().describe(`Optional maximum number of characters to return from each command`)}),oF(),ef([F({type:I(`create_file`),path:N(),diff:N()}),F({type:I(`update_file`),path:N(),diff:N()}),F({type:I(`delete_file`),path:N()})]);function $se(e){return!!(e==null||typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob||e instanceof URLSearchParams||e instanceof FormData)}function ece(e){let t=e.model||`gpt-3.5-turbo`,n=e.temperature,r=e.maxTokens,i=e.baseUrl;if(e.mode===`direct`){let a=!1;try{a=typeof location<`u`&&location.protocol===`https:`&&![`localhost`,`127.0.0.1`,`0.0.0.0`].includes(location.hostname)}catch{}if(a){if(e.throwOnDirectInProduction)throw Error(`[page-agent-sdk][proxyLlm] direct 模式在生产环境(https + 非本地)会泄露 apiKey(进 bundle),建议改用 proxy 模式(throwOnDirectInProduction 已启用强安全闸;若确需生产直连,设为 false 显式承认风险)`);console.warn(`[page-agent-sdk][proxyLlm] direct 模式在生产环境(https + 非本地)会泄露 apiKey(进 bundle),建议改用 proxy 模式`)}if(!e.apiKey)throw Error(`[page-agent-sdk][proxyLlm] direct 模式需提供 apiKey(开发环境用真实 key)`);return new mI({apiKey:e.apiKey,model:t,temperature:n,maxTokens:r,configuration:i?{baseURL:i}:void 0})}i||console.warn(`[page-agent-sdk][proxyLlm] proxy 模式未配 baseUrl,将打到页面 origin(通常不是预期);请传代理地址如 '/api/llm'`);let a=e.userToken||`proxy`,o=null;function s(){return e.refreshToken?(o||=e.refreshToken().finally(()=>{o=null}),o):Promise.resolve(a)}return new mI({apiKey:a,model:t,temperature:n,maxTokens:r,configuration:{baseURL:i||`/`,fetch:async(t,n)=>{let r,i;typeof t==`string`?(r=t,i=n?.headers):t instanceof URL?(r=t.toString(),i=n?.headers):(r=t.url,i=n?.headers??t.headers);let o=new Headers(i);if(o.set(`Authorization`,`Bearer ${a}`),e.headers)for(let[t,n]of Object.entries(e.headers))o.set(t,n);let c=()=>fetch(r,{...n,headers:o}),l=await c();if(l.status===401&&e.refreshToken&&$se(n?.body))try{a=await s(),o.set(`Authorization`,`Bearer ${a}`),l=await c()}catch{}return l}}})}function _I(e,t={}){return new mI({apiKey:e.apiKey,model:e.model,temperature:t.temperature??e.temperature,maxTokens:t.maxTokens??e.maxTokens,configuration:{...e.baseUrl?{baseURL:e.baseUrl}:{},...e.extraConfig},...e.extraBody?{modelKwargs:e.extraBody}:{}})}async function vI(e,t={}){if((e.provider??`openai`)===`openai`)return _I(e,t);let{ChatAnthropic:n}=await import(`@langchain/anthropic`);return new n({apiKey:e.apiKey,model:e.model,temperature:t.temperature??e.temperature,maxTokens:t.maxTokens??e.maxTokens,...e.baseUrl?{anthropicApiUrl:e.baseUrl}:{},...e.extraConfig?{clientOptions:e.extraConfig}:{}})}function yI(e){let t=e.content;return typeof t==`string`?t:Array.isArray(t)?t.map(e=>typeof e==`string`?e:e?.type===`text`&&typeof e.text==`string`?e.text:``).join(``):``}function bI(e){let t=e.additional_kwargs||{},n=t.reasoning_content||t.reasoning||``;return!n&&Array.isArray(e.content)&&(n=e.content.map(e=>e?.type===`thinking`?e.thinking??``:e?.type===`thinking_delta`?e.delta??e.thinking??``:``).join(``)),n}function xI(e){let t=e;return t?.additional_kwargs?.usage??t?.response_metadata?.usage??t?.response_metadata?.token_usage??void 0}function SI(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var CI={},wI=[],TI=()=>{},EI=()=>!1,DI=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),OI=e=>e.startsWith(`onUpdate:`),kI=Object.assign,AI=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},tce=Object.prototype.hasOwnProperty,jI=(e,t)=>tce.call(e,t),MI=Array.isArray,NI=e=>HI(e)===`[object Map]`,PI=e=>HI(e)===`[object Set]`,FI=e=>HI(e)===`[object Date]`,II=e=>typeof e==`function`,LI=e=>typeof e==`string`,RI=e=>typeof e==`symbol`,zI=e=>typeof e==`object`&&!!e,BI=e=>(zI(e)||II(e))&&II(e.then)&&II(e.catch),VI=Object.prototype.toString,HI=e=>VI.call(e),nce=e=>HI(e).slice(8,-1),UI=e=>HI(e)===`[object Object]`,WI=e=>LI(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,GI=SI(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),KI=e=>{let t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},rce=/-\w/g,qI=KI(e=>e.replace(rce,e=>e.slice(1).toUpperCase())),ice=/\B([A-Z])/g,JI=KI(e=>e.replace(ice,`-$1`).toLowerCase()),YI=KI(e=>e.charAt(0).toUpperCase()+e.slice(1)),XI=KI(e=>e?`on${YI(e)}`:``),ZI=(e,t)=>!Object.is(e,t),QI=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},$I=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},eL=e=>{let t=parseFloat(e);return isNaN(t)?e:t},ace=e=>{let t=LI(e)?Number(e):NaN;return isNaN(t)?e:t},oce,tL=()=>oce||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{};function nL(e){if(MI(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=LI(r)?uce(r):nL(r);if(i)for(let e in i)t[e]=i[e]}return t}else if(LI(e)||zI(e))return e}var sce=/;(?![^(]*\))/g,cce=/:([^]+)/,lce=/\/\*[^]*?\*\//g;function uce(e){let t={};return e.replace(lce,``).split(sce).forEach(e=>{if(e){let n=e.split(cce);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function rL(e){let t=``;if(LI(e))t=e;else if(MI(e))for(let n=0;n<e.length;n++){let r=rL(e[n]);r&&(t+=r+` `)}else if(zI(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}var iL=`itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`,dce=SI(iL);iL+``;function aL(e){return!!e||e===``}function fce(e,t){if(e.length!==t.length)return!1;let n=!0;for(let r=0;n&&r<e.length;r++)n=oL(e[r],t[r]);return n}function oL(e,t){if(e===t)return!0;let n=FI(e),r=FI(t);if(n||r)return n&&r?e.getTime()===t.getTime():!1;if(n=RI(e),r=RI(t),n||r)return e===t;if(n=MI(e),r=MI(t),n||r)return n&&r?fce(e,t):!1;if(n=zI(e),r=zI(t),n||r){if(!n||!r||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e){let r=e.hasOwnProperty(n),i=t.hasOwnProperty(n);if(r&&!i||!r&&i||!oL(e[n],t[n]))return!1}}return String(e)===String(t)}var sL=e=>!!(e&&e.__v_isRef===!0),q=e=>LI(e)?e:e==null?``:MI(e)||zI(e)&&(e.toString===VI||!II(e.toString))?sL(e)?q(e.value):JSON.stringify(e,cL,2):String(e),cL=(e,t)=>sL(t)?cL(e,t.value):NI(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[lL(t,r)+` =>`]=n,e),{})}:PI(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>lL(e))}:RI(t)?lL(t):zI(t)&&!MI(t)&&!UI(t)?String(t):t,lL=(e,t=``)=>RI(e)?`Symbol(${e.description??t})`:e,uL,pce=class{constructor(e=!1){this.detached=e,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!e&&uL&&(uL.active?(this.parent=uL,this.index=(uL.scopes||=[]).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let e,t;if(this.scopes)for(e=0,t=this.scopes.length;e<t;e++)this.scopes[e].pause();for(e=0,t=this.effects.length;e<t;e++)this.effects[e].pause()}}resume(){if(this._active&&this._isPaused){this._isPaused=!1;let e,t;if(this.scopes)for(e=0,t=this.scopes.length;e<t;e++)this.scopes[e].resume();for(e=0,t=this.effects.length;e<t;e++)this.effects[e].resume()}}run(e){if(this._active){let t=uL;try{return uL=this,e()}finally{uL=t}}}on(){++this._on===1&&(this.prevScope=uL,uL=this)}off(){if(this._on>0&&--this._on===0){if(uL===this)uL=this.prevScope;else{let e=uL;for(;e;){if(e.prevScope===this){e.prevScope=this.prevScope;break}e=e.prevScope}}this.prevScope=void 0}}stop(e){if(this._active){this._active=!1;let t,n;for(t=0,n=this.effects.length;t<n;t++)this.effects[t].stop();for(this.effects.length=0,t=0,n=this.cleanups.length;t<n;t++)this.cleanups[t]();if(this.cleanups.length=0,this.scopes){for(t=0,n=this.scopes.length;t<n;t++)this.scopes[t].stop(!0);this.scopes.length=0}if(!this.detached&&this.parent&&!e){let e=this.parent.scopes.pop();e&&e!==this&&(this.parent.scopes[this.index]=e,e.index=this.index)}this.parent=void 0}}};function mce(){return uL}var dL,fL=new WeakSet,pL=class{constructor(e){this.fn=e,this.deps=void 0,this.depsTail=void 0,this.flags=5,this.next=void 0,this.cleanup=void 0,this.scheduler=void 0,uL&&(uL.active?uL.effects.push(this):this.flags&=-2)}pause(){this.flags|=64}resume(){this.flags&64&&(this.flags&=-65,fL.has(this)&&(fL.delete(this),this.trigger()))}notify(){this.flags&2&&!(this.flags&32)||this.flags&8||_L(this)}run(){if(!(this.flags&1))return this.fn();this.flags|=2,kL(this),bL(this);let e=dL,t=TL;dL=this,TL=!0;try{return this.fn()}finally{xL(this),dL=e,TL=t,this.flags&=-3}}stop(){if(this.flags&1){for(let e=this.deps;e;e=e.nextDep)wL(e);this.deps=this.depsTail=void 0,kL(this),this.onStop&&this.onStop(),this.flags&=-2}}trigger(){this.flags&64?fL.add(this):this.scheduler?this.scheduler():this.runIfDirty()}runIfDirty(){SL(this)&&this.run()}get dirty(){return SL(this)}},mL=0,hL,gL;function _L(e,t=!1){if(e.flags|=8,t){e.next=gL,gL=e;return}e.next=hL,hL=e}function vL(){mL++}function yL(){if(--mL>0)return;if(gL){let e=gL;for(gL=void 0;e;){let t=e.next;e.next=void 0,e.flags&=-9,e=t}}let e;for(;hL;){let t=hL;for(hL=void 0;t;){let n=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(t){e||=t}t=n}}if(e)throw e}function bL(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function xL(e){let t,n=e.depsTail,r=n;for(;r;){let e=r.prevDep;r.version===-1?(r===n&&(n=e),wL(r),hce(r)):t=r,r.dep.activeLink=r.prevActiveLink,r.prevActiveLink=void 0,r=e}e.deps=t,e.depsTail=n}function SL(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(CL(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function CL(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===AL)||(e.globalVersion=AL,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!SL(e))))return;e.flags|=2;let t=e.dep,n=dL,r=TL;dL=e,TL=!0;try{bL(e);let n=e.fn(e._value);(t.version===0||ZI(n,e._value))&&(e.flags|=128,e._value=n,t.version++)}catch(e){throw t.version++,e}finally{dL=n,TL=r,xL(e),e.flags&=-3}}function wL(e,t=!1){let{dep:n,prevSub:r,nextSub:i}=e;if(r&&(r.nextSub=i,e.prevSub=void 0),i&&(i.prevSub=r,e.nextSub=void 0),n.subs===e&&(n.subs=r,!r&&n.computed)){n.computed.flags&=-5;for(let e=n.computed.deps;e;e=e.nextDep)wL(e,!0)}!t&&!--n.sc&&n.map&&n.map.delete(n.key)}function hce(e){let{prevDep:t,nextDep:n}=e;t&&(t.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=t,e.nextDep=void 0)}var TL=!0,EL=[];function DL(){EL.push(TL),TL=!1}function OL(){let e=EL.pop();TL=e===void 0||e}function kL(e){let{cleanup:t}=e;if(e.cleanup=void 0,t){let e=dL;dL=void 0;try{t()}finally{dL=e}}}var AL=0,gce=class{constructor(e,t){this.sub=e,this.dep=t,this.version=t.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}},jL=class{constructor(e){this.computed=e,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(e){if(!dL||!TL||dL===this.computed)return;let t=this.activeLink;if(t===void 0||t.sub!==dL)t=this.activeLink=new gce(dL,this),dL.deps?(t.prevDep=dL.depsTail,dL.depsTail.nextDep=t,dL.depsTail=t):dL.deps=dL.depsTail=t,ML(t);else if(t.version===-1&&(t.version=this.version,t.nextDep)){let e=t.nextDep;e.prevDep=t.prevDep,t.prevDep&&(t.prevDep.nextDep=e),t.prevDep=dL.depsTail,t.nextDep=void 0,dL.depsTail.nextDep=t,dL.depsTail=t,dL.deps===t&&(dL.deps=e)}return t}trigger(e){this.version++,AL++,this.notify(e)}notify(e){vL();try{for(let e=this.subs;e;e=e.prevSub)e.sub.notify()&&e.sub.dep.notify()}finally{yL()}}};function ML(e){if(e.dep.sc++,e.sub.flags&4){let t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let e=t.deps;e;e=e.nextDep)ML(e)}let n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}var NL=new WeakMap,PL=Symbol(``),FL=Symbol(``),IL=Symbol(``);function LL(e,t,n){if(TL&&dL){let t=NL.get(e);t||NL.set(e,t=new Map);let r=t.get(n);r||(t.set(n,r=new jL),r.map=t,r.key=n),r.track()}}function RL(e,t,n,r,i,a){let o=NL.get(e);if(!o){AL++;return}let s=e=>{e&&e.trigger()};if(vL(),t===`clear`)o.forEach(s);else{let i=MI(e),a=i&&WI(n);if(i&&n===`length`){let e=Number(r);o.forEach((t,n)=>{(n===`length`||n===IL||!RI(n)&&n>=e)&&s(t)})}else switch((n!==void 0||o.has(void 0))&&s(o.get(n)),a&&s(o.get(IL)),t){case`add`:i?a&&s(o.get(`length`)):(s(o.get(PL)),NI(e)&&s(o.get(FL)));break;case`delete`:i||(s(o.get(PL)),NI(e)&&s(o.get(FL)));break;case`set`:NI(e)&&s(o.get(PL));break}}yL()}function zL(e){let t=wR(e);return t===e?t:(LL(t,`iterate`,IL),SR(e)?t:t.map(ER))}function BL(e){return LL(e=wR(e),`iterate`,IL),e}function VL(e,t){return xR(e)?DR(bR(e)?ER(t):t):ER(t)}var _ce={__proto__:null,[Symbol.iterator](){return HL(this,Symbol.iterator,e=>VL(this,e))},concat(...e){return zL(this).concat(...e.map(e=>MI(e)?zL(e):e))},entries(){return HL(this,`entries`,e=>(e[1]=VL(this,e[1]),e))},every(e,t){return UL(this,`every`,e,t,void 0,arguments)},filter(e,t){return UL(this,`filter`,e,t,e=>e.map(e=>VL(this,e)),arguments)},find(e,t){return UL(this,`find`,e,t,e=>VL(this,e),arguments)},findIndex(e,t){return UL(this,`findIndex`,e,t,void 0,arguments)},findLast(e,t){return UL(this,`findLast`,e,t,e=>VL(this,e),arguments)},findLastIndex(e,t){return UL(this,`findLastIndex`,e,t,void 0,arguments)},forEach(e,t){return UL(this,`forEach`,e,t,void 0,arguments)},includes(...e){return GL(this,`includes`,e)},indexOf(...e){return GL(this,`indexOf`,e)},join(e){return zL(this).join(e)},lastIndexOf(...e){return GL(this,`lastIndexOf`,e)},map(e,t){return UL(this,`map`,e,t,void 0,arguments)},pop(){return KL(this,`pop`)},push(...e){return KL(this,`push`,e)},reduce(e,...t){return WL(this,`reduce`,e,t)},reduceRight(e,...t){return WL(this,`reduceRight`,e,t)},shift(){return KL(this,`shift`)},some(e,t){return UL(this,`some`,e,t,void 0,arguments)},splice(...e){return KL(this,`splice`,e)},toReversed(){return zL(this).toReversed()},toSorted(e){return zL(this).toSorted(e)},toSpliced(...e){return zL(this).toSpliced(...e)},unshift(...e){return KL(this,`unshift`,e)},values(){return HL(this,`values`,e=>VL(this,e))}};function HL(e,t,n){let r=BL(e),i=r[t]();return r!==e&&!SR(e)&&(i._next=i.next,i.next=()=>{let e=i._next();return e.done||(e.value=n(e.value)),e}),i}var vce=Array.prototype;function UL(e,t,n,r,i,a){let o=BL(e),s=o!==e&&!SR(e),c=o[t];if(c!==vce[t]){let t=c.apply(e,a);return s?ER(t):t}let l=n;o!==e&&(s?l=function(t,r){return n.call(this,VL(e,t),r,e)}:n.length>2&&(l=function(t,r){return n.call(this,t,r,e)}));let u=c.call(o,l,r);return s&&i?i(u):u}function WL(e,t,n,r){let i=BL(e),a=i!==e&&!SR(e),o=n,s=!1;i!==e&&(a?(s=r.length===0,o=function(t,r,i){return s&&(s=!1,t=VL(e,t)),n.call(this,t,VL(e,r),i,e)}):n.length>3&&(o=function(t,r,i){return n.call(this,t,r,i,e)}));let c=i[t](o,...r);return s?VL(e,c):c}function GL(e,t,n){let r=wR(e);LL(r,`iterate`,IL);let i=r[t](...n);return(i===-1||i===!1)&&CR(n[0])?(n[0]=wR(n[0]),r[t](...n)):i}function KL(e,t,n=[]){DL(),vL();let r=wR(e)[t].apply(e,n);return yL(),OL(),r}var qL=SI(`__proto__,__v_isRef,__isVue`),JL=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!==`arguments`&&e!==`caller`).map(e=>Symbol[e]).filter(RI));function YL(e){RI(e)||(e=String(e));let t=wR(this);return LL(t,`has`,e),t.hasOwnProperty(e)}var XL=class{constructor(e=!1,t=!1){this._isReadonly=e,this._isShallow=t}get(e,t,n){if(t===`__v_skip`)return e.__v_skip;let r=this._isReadonly,i=this._isShallow;if(t===`__v_isReactive`)return!r;if(t===`__v_isReadonly`)return r;if(t===`__v_isShallow`)return i;if(t===`__v_raw`)return n===(r?i?mR:pR:i?fR:dR).get(e)||Object.getPrototypeOf(e)===Object.getPrototypeOf(n)?e:void 0;let a=MI(e);if(!r){let e;if(a&&(e=_ce[t]))return e;if(t===`hasOwnProperty`)return YL}let o=Reflect.get(e,t,OR(e)?e:n);if((RI(t)?JL.has(t):qL(t))||(r||LL(e,`get`,t),i))return o;if(OR(o)){let e=a&&WI(t)?o:o.value;return r&&zI(e)?vR(e):e}return zI(o)?r?vR(o):gR(o):o}},ZL=class extends XL{constructor(e=!1){super(!1,e)}set(e,t,n,r){let i=e[t],a=MI(e)&&WI(t);if(!this._isShallow){let e=xR(i);if(!SR(n)&&!xR(n)&&(i=wR(i),n=wR(n)),!a&&OR(i)&&!OR(n))return e||(i.value=n),!0}let o=a?Number(t)<e.length:jI(e,t),s=Reflect.set(e,t,n,OR(e)?e:r);return e===wR(r)&&s&&(o?ZI(n,i)&&RL(e,`set`,t,n,i):RL(e,`add`,t,n)),s}deleteProperty(e,t){let n=jI(e,t),r=e[t],i=Reflect.deleteProperty(e,t);return i&&n&&RL(e,`delete`,t,void 0,r),i}has(e,t){let n=Reflect.has(e,t);return(!RI(t)||!JL.has(t))&&LL(e,`has`,t),n}ownKeys(e){return LL(e,`iterate`,MI(e)?`length`:PL),Reflect.ownKeys(e)}},QL=class extends XL{constructor(e=!1){super(!0,e)}set(e,t){return!0}deleteProperty(e,t){return!0}},$L=new ZL,eR=new QL,tR=new ZL(!0),nR=e=>e,rR=e=>Reflect.getPrototypeOf(e);function iR(e,t,n){return function(...r){let i=this.__v_raw,a=wR(i),o=NI(a),s=e===`entries`||e===Symbol.iterator&&o,c=e===`keys`&&o,l=i[e](...r),u=n?nR:t?DR:ER;return!t&&LL(a,`iterate`,c?FL:PL),kI(Object.create(l),{next(){let{value:e,done:t}=l.next();return t?{value:e,done:t}:{value:s?[u(e[0]),u(e[1])]:u(e),done:t}}})}}function aR(e){return function(...t){return e===`delete`?!1:e===`clear`?void 0:this}}function oR(e,t){let n={get(n){let r=this.__v_raw,i=wR(r),a=wR(n);e||(ZI(n,a)&&LL(i,`get`,n),LL(i,`get`,a));let{has:o}=rR(i),s=t?nR:e?DR:ER;if(o.call(i,n))return s(r.get(n));if(o.call(i,a))return s(r.get(a));r!==i&&r.get(n)},get size(){let t=this.__v_raw;return!e&&LL(wR(t),`iterate`,PL),t.size},has(t){let n=this.__v_raw,r=wR(n),i=wR(t);return e||(ZI(t,i)&&LL(r,`has`,t),LL(r,`has`,i)),t===i?n.has(t):n.has(t)||n.has(i)},forEach(n,r){let i=this,a=i.__v_raw,o=wR(a),s=t?nR:e?DR:ER;return!e&&LL(o,`iterate`,PL),a.forEach((e,t)=>n.call(r,s(e),s(t),i))}};return kI(n,e?{add:aR(`add`),set:aR(`set`),delete:aR(`delete`),clear:aR(`clear`)}:{add(e){let n=wR(this),r=rR(n),i=wR(e),a=!t&&!SR(e)&&!xR(e)?i:e;return r.has.call(n,a)||ZI(e,a)&&r.has.call(n,e)||ZI(i,a)&&r.has.call(n,i)||(n.add(a),RL(n,`add`,a,a)),this},set(e,n){!t&&!SR(n)&&!xR(n)&&(n=wR(n));let r=wR(this),{has:i,get:a}=rR(r),o=i.call(r,e);o||=(e=wR(e),i.call(r,e));let s=a.call(r,e);return r.set(e,n),o?ZI(n,s)&&RL(r,`set`,e,n,s):RL(r,`add`,e,n),this},delete(e){let t=wR(this),{has:n,get:r}=rR(t),i=n.call(t,e);i||=(e=wR(e),n.call(t,e));let a=r?r.call(t,e):void 0,o=t.delete(e);return i&&RL(t,`delete`,e,void 0,a),o},clear(){let e=wR(this),t=e.size!==0,n=e.clear();return t&&RL(e,`clear`,void 0,void 0,void 0),n}}),[`keys`,`values`,`entries`,Symbol.iterator].forEach(r=>{n[r]=iR(r,e,t)}),n}function sR(e,t){let n=oR(e,t);return(t,r,i)=>r===`__v_isReactive`?!e:r===`__v_isReadonly`?e:r===`__v_raw`?t:Reflect.get(jI(n,r)&&r in t?n:t,r,i)}var cR={get:sR(!1,!1)},lR={get:sR(!1,!0)},uR={get:sR(!0,!1)},dR=new WeakMap,fR=new WeakMap,pR=new WeakMap,mR=new WeakMap;function hR(e){switch(e){case`Object`:case`Array`:return 1;case`Map`:case`Set`:case`WeakMap`:case`WeakSet`:return 2;default:return 0}}function gR(e){return xR(e)?e:yR(e,!1,$L,cR,dR)}function _R(e){return yR(e,!1,tR,lR,fR)}function vR(e){return yR(e,!0,eR,uR,pR)}function yR(e,t,n,r,i){if(!zI(e)||e.__v_raw&&!(t&&e.__v_isReactive)||e.__v_skip||!Object.isExtensible(e))return e;let a=i.get(e);if(a)return a;let o=hR(nce(e));if(o===0)return e;let s=new Proxy(e,o===2?r:n);return i.set(e,s),s}function bR(e){return xR(e)?bR(e.__v_raw):!!(e&&e.__v_isReactive)}function xR(e){return!!(e&&e.__v_isReadonly)}function SR(e){return!!(e&&e.__v_isShallow)}function CR(e){return e?!!e.__v_raw:!1}function wR(e){let t=e&&e.__v_raw;return t?wR(t):e}function TR(e){return!jI(e,`__v_skip`)&&Object.isExtensible(e)&&$I(e,`__v_skip`,!0),e}var ER=e=>zI(e)?gR(e):e,DR=e=>zI(e)?vR(e):e;function OR(e){return e?e.__v_isRef===!0:!1}function kR(e){return jR(e,!1)}function AR(e){return jR(e,!0)}function jR(e,t){return OR(e)?e:new MR(e,t)}var MR=class{constructor(e,t){this.dep=new jL,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=t?e:wR(e),this._value=t?e:ER(e),this.__v_isShallow=t}get value(){return this.dep.track(),this._value}set value(e){let t=this._rawValue,n=this.__v_isShallow||SR(e)||xR(e);e=n?e:wR(e),ZI(e,t)&&(this._rawValue=e,this._value=n?e:ER(e),this.dep.trigger())}};function NR(e){e.dep&&e.dep.trigger()}function J(e){return OR(e)?e.value:e}var PR={get:(e,t,n)=>t===`__v_raw`?e:J(Reflect.get(e,t,n)),set:(e,t,n,r)=>{let i=e[t];return OR(i)&&!OR(n)?(i.value=n,!0):Reflect.set(e,t,n,r)}};function FR(e){return bR(e)?e:new Proxy(e,PR)}var IR=class{constructor(e,t,n){this.fn=e,this.setter=t,this._value=void 0,this.dep=new jL(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=AL-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!t,this.isSSR=n}notify(){if(this.flags|=16,!(this.flags&8)&&dL!==this)return _L(this,!0),!0}get value(){let e=this.dep.track();return CL(this),e&&(e.version=this.dep.version),this._value}set value(e){this.setter&&this.setter(e)}};function LR(e,t,n=!1){let r,i;return II(e)?r=e:(r=e.get,i=e.set),new IR(r,i,n)}var RR={},zR=new WeakMap,BR=void 0;function VR(e,t=!1,n=BR){if(n){let t=zR.get(n);t||zR.set(n,t=[]),t.push(e)}}function HR(e,t,n=CI){let{immediate:r,deep:i,once:a,scheduler:o,augmentJob:s,call:c}=n,l=e=>i?e:SR(e)||i===!1||i===0?UR(e,1):UR(e),u,d,f,p,m=!1,h=!1;if(OR(e)?(d=()=>e.value,m=SR(e)):bR(e)?(d=()=>l(e),m=!0):MI(e)?(h=!0,m=e.some(e=>bR(e)||SR(e)),d=()=>e.map(e=>{if(OR(e))return e.value;if(bR(e))return l(e);if(II(e))return c?c(e,2):e()})):d=II(e)?t?c?()=>c(e,2):e:()=>{if(f){DL();try{f()}finally{OL()}}let t=BR;BR=u;try{return c?c(e,3,[p]):e(p)}finally{BR=t}}:TI,t&&i){let e=d,t=i===!0?1/0:i;d=()=>UR(e(),t)}let g=mce(),_=()=>{u.stop(),g&&g.active&&AI(g.effects,u)};if(a&&t){let e=t;t=(...t)=>{let n=e(...t);return _(),n}}let v=h?Array(e.length).fill(RR):RR,y=e=>{if(!(!(u.flags&1)||!u.dirty&&!e))if(t){let n=u.run();if(e||i||m||(h?n.some((e,t)=>ZI(e,v[t])):ZI(n,v))){f&&f();let e=BR;BR=u;try{let e=[n,v===RR?void 0:h&&v[0]===RR?[]:v,p];v=n,c?c(t,3,e):t(...e)}finally{BR=e}}}else u.run()};return s&&s(y),u=new pL(d),u.scheduler=o?()=>o(y,!1):y,p=e=>VR(e,!1,u),f=u.onStop=()=>{let e=zR.get(u);if(e){if(c)c(e,4);else for(let t of e)t();zR.delete(u)}},t?r?y(!0):v=u.run():o?o(y.bind(null,!0),!0):u.run(),_.pause=u.pause.bind(u),_.resume=u.resume.bind(u),_.stop=_,_}function UR(e,t=1/0,n){if(t<=0||!zI(e)||e.__v_skip||(n||=new Map,(n.get(e)||0)>=t))return e;if(n.set(e,t),t--,OR(e))UR(e.value,t,n);else if(MI(e))for(let r=0;r<e.length;r++)UR(e[r],t,n);else if(PI(e)||NI(e))e.forEach(e=>{UR(e,t,n)});else if(UI(e)){for(let r in e)UR(e[r],t,n);for(let r of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,r)&&UR(e[r],t,n)}return e}function WR(e,t,n,r){try{return r?e(...r):e()}catch(e){KR(e,t,n)}}function GR(e,t,n,r){if(II(e)){let i=WR(e,t,n,r);return i&&BI(i)&&i.catch(e=>{KR(e,t,n)}),i}if(MI(e)){let i=[];for(let a=0;a<e.length;a++)i.push(GR(e[a],t,n,r));return i}}function KR(e,t,n,r=!0){let i=t?t.vnode:null,{errorHandler:a,throwUnhandledErrorInProduction:o}=t&&t.appContext.config||CI;if(t){let r=t.parent,i=t.proxy,o=`https://vuejs.org/error-reference/#runtime-${n}`;for(;r;){let t=r.ec;if(t){for(let n=0;n<t.length;n++)if(t[n](e,i,o)===!1)return}r=r.parent}if(a){DL(),WR(a,null,10,[e,i,o]),OL();return}}qR(e,n,i,r,o)}function qR(e,t,n,r=!0,i=!1){if(i)throw e;console.error(e)}var JR=[],YR=-1,XR=[],ZR=null,QR=0,$R=Promise.resolve(),ez=null;function tz(e){let t=ez||$R;return e?t.then(this?e.bind(this):e):t}function nz(e){let t=YR+1,n=JR.length;for(;t<n;){let r=t+n>>>1,i=JR[r],a=cz(i);a<e||a===e&&i.flags&2?t=r+1:n=r}return t}function rz(e){if(!(e.flags&1)){let t=cz(e),n=JR[JR.length-1];!n||!(e.flags&2)&&t>=cz(n)?JR.push(e):JR.splice(nz(t),0,e),e.flags|=1,iz()}}function iz(){ez||=$R.then(lz)}function az(e){MI(e)?XR.push(...e):ZR&&e.id===-1?ZR.splice(QR+1,0,e):e.flags&1||(XR.push(e),e.flags|=1),iz()}function oz(e,t,n=YR+1){for(;n<JR.length;n++){let t=JR[n];if(t&&t.flags&2){if(e&&t.id!==e.uid)continue;JR.splice(n,1),n--,t.flags&4&&(t.flags&=-2),t(),t.flags&4||(t.flags&=-2)}}}function sz(e){if(XR.length){let e=[...new Set(XR)].sort((e,t)=>cz(e)-cz(t));if(XR.length=0,ZR){ZR.push(...e);return}for(ZR=e,QR=0;QR<ZR.length;QR++){let e=ZR[QR];e.flags&4&&(e.flags&=-2),e.flags&8||e(),e.flags&=-2}ZR=null,QR=0}}var cz=e=>e.id==null?e.flags&2?-1:1/0:e.id;function lz(e){try{for(YR=0;YR<JR.length;YR++){let e=JR[YR];e&&!(e.flags&8)&&(e.flags&4&&(e.flags&=-2),WR(e,e.i,e.i?15:14),e.flags&4||(e.flags&=-2))}}finally{for(;YR<JR.length;YR++){let e=JR[YR];e&&(e.flags&=-2)}YR=-1,JR.length=0,sz(e),ez=null,(JR.length||XR.length)&&lz(e)}}var uz=null,dz=null;function fz(e){let t=uz;return uz=e,dz=e&&e.type.__scopeId||null,t}function pz(e,t=uz,n){if(!t||e._n)return e;let r=(...n)=>{r._d&&JV(-1);let i=fz(t),a;try{a=e(...n)}finally{fz(i),r._d&&JV(1)}return a};return r._n=!0,r._c=!0,r._d=!0,r}function mz(e,t){if(uz===null)return e;let n=AH(uz),r=e.dirs||=[];for(let e=0;e<t.length;e++){let[i,a,o,s=CI]=t[e];i&&(II(i)&&(i={mounted:i,updated:i}),i.deep&&UR(a),r.push({dir:i,instance:n,value:a,oldValue:void 0,arg:o,modifiers:s}))}return e}function hz(e,t,n,r){let i=e.dirs,a=t&&t.dirs;for(let o=0;o<i.length;o++){let s=i[o];a&&(s.oldValue=a[o].value);let c=s.dir[r];c&&(DL(),GR(c,n,8,[e.el,s,e,t]),OL())}}function gz(e,t){if(mH){let n=mH.provides,r=mH.parent&&mH.parent.provides;r===n&&(n=mH.provides=Object.create(r)),n[e]=t}}function _z(e,t,n=!1){let r=hH();if(r||XB){let i=XB?XB._context.provides:r?r.parent==null||r.ce?r.vnode.appContext&&r.vnode.appContext.provides:r.parent.provides:void 0;if(i&&e in i)return i[e];if(arguments.length>1)return n&&II(t)?t.call(r&&r.proxy):t}}var vz=Symbol.for(`v-scx`),yz=()=>_z(vz);function bz(e,t,n){return xz(e,t,n)}function xz(e,t,n=CI){let{immediate:r,deep:i,flush:a,once:o}=n,s=kI({},n),c=t&&r||!t&&a!==`post`,l;if(xH){if(a===`sync`){let e=yz();l=e.__watcherHandles||=[]}else if(!c){let e=()=>{};return e.stop=TI,e.resume=TI,e.pause=TI,e}}let u=mH;s.call=(e,t,n)=>GR(e,u,t,n);let d=!1;a===`post`?s.scheduler=e=>{DV(e,u&&u.suspense)}:a!==`sync`&&(d=!0,s.scheduler=(e,t)=>{t?e():rz(e)}),s.augmentJob=e=>{t&&(e.flags|=4),d&&(e.flags|=2,u&&(e.id=u.uid,e.i=u))};let f=HR(e,t,s);return xH&&(l?l.push(f):c&&f()),f}function Sz(e,t,n){let r=this.proxy,i=LI(e)?e.includes(`.`)?Cz(r,e):()=>r[e]:e.bind(r,r),a;II(t)?a=t:(a=t.handler,n=t);let o=vH(this),s=xz(i,a.bind(r),n);return o(),s}function Cz(e,t){let n=t.split(`.`);return()=>{let t=e;for(let e=0;e<n.length&&t;e++)t=t[n[e]];return t}}var wz=new WeakMap,Tz=Symbol(`_vte`),Ez=e=>e.__isTeleport,Dz=e=>e&&(e.disabled||e.disabled===``),Oz=e=>e&&(e.defer||e.defer===``),kz=e=>typeof SVGElement<`u`&&e instanceof SVGElement,Az=e=>typeof MathMLElement==`function`&&e instanceof MathMLElement,jz=(e,t)=>{let n=e&&e.to;return LI(n)?t?t(n):null:n},Mz={name:`Teleport`,__isTeleport:!0,process(e,t,n,r,i,a,o,s,c,l){let{mc:u,pc:d,pbc:f,o:{insert:p,querySelector:m,createText:h,createComment:g,parentNode:_}}=l,v=Dz(t.props),{dynamicChildren:y}=t,b=(e,t,n)=>{e.shapeFlag&16&&u(e.children,t,n,i,a,o,s,c)},x=(e=t)=>{let n=Dz(e.props),r=e.target=jz(e.props,m),a=Lz(r,e,h,p);r&&(o!==`svg`&&kz(r)?o=`svg`:o!==`mathml`&&Az(r)&&(o=`mathml`),i&&i.isCE&&(i.ce._teleportTargets||(i.ce._teleportTargets=new Set)).add(r),n||(b(e,r,a),Iz(e,!1)))},S=e=>{let t=()=>{if(wz.get(e)===t){if(wz.delete(e),Dz(e.props)){let t=_(e.el)||n;b(e,t,e.anchor),Iz(e,!0)}x(e)}};wz.set(e,t),DV(t,a)};if(e==null){let e=t.el=h(``),i=t.anchor=h(``);if(p(e,n,r),p(i,n,r),Oz(t.props)||a&&a.pendingBranch){S(t);return}v&&(b(t,n,i),Iz(t,!0)),x()}else{t.el=e.el;let r=t.anchor=e.anchor,u=wz.get(e);if(u){u.flags|=8,wz.delete(e),S(t);return}t.targetStart=e.targetStart;let p=t.target=e.target,h=t.targetAnchor=e.targetAnchor,g=Dz(e.props),_=g?n:p,b=g?r:h;if(o===`svg`||kz(p)?o=`svg`:(o===`mathml`||Az(p))&&(o=`mathml`),y?(f(e.dynamicChildren,y,_,i,a,o,s),NV(e,t,!0)):c||d(e,t,_,b,i,a,o,s,!1),v)g?t.props&&e.props&&t.props.to!==e.props.to&&(t.props.to=e.props.to):Nz(t,n,r,l,1);else if((t.props&&t.props.to)!==(e.props&&e.props.to)){let e=jz(t.props,m);e&&(t.target=e,Nz(t,e,null,l,0))}else g&&Nz(t,p,h,l,1);Iz(t,v)}},remove(e,t,n,{um:r,o:{remove:i}},a){let{shapeFlag:o,children:s,anchor:c,targetStart:l,targetAnchor:u,target:d,props:f}=e,p=Dz(f),m=a||!p,h=wz.get(e);if(h&&(h.flags|=8,wz.delete(e)),d&&(i(l),i(u)),a&&i(c),!h&&(p||d)&&o&16)for(let e=0;e<s.length;e++){let i=s[e];r(i,t,n,m,!!i.dynamicChildren)}},move:Nz,hydrate:Pz};function Nz(e,t,n,{o:{insert:r},m:i},a=2){a===0&&r(e.targetAnchor,t,n);let{el:o,anchor:s,shapeFlag:c,children:l,props:u}=e,d=a===2;if(d&&r(o,t,n),!wz.has(e)&&(!d||Dz(u))&&c&16)for(let e=0;e<l.length;e++)i(l[e],t,n,2);d&&r(s,t,n)}function Pz(e,t,n,r,i,a,{o:{nextSibling:o,parentNode:s,querySelector:c,insert:l,createText:u}},d){function f(e,n){let r=n;for(;r;){if(r&&r.nodeType===8){if(r.data===`teleport start anchor`)t.targetStart=r;else if(r.data===`teleport anchor`){t.targetAnchor=r,e._lpa=t.targetAnchor&&o(t.targetAnchor);break}}r=o(r)}}function p(e,t){t.anchor=d(o(e),t,s(e),n,r,i,a)}let m=t.target=jz(t.props,c),h=Dz(t.props);if(m){let c=m._lpa||m.firstChild;t.shapeFlag&16&&(h?(p(e,t),f(m,c),t.targetAnchor||Lz(m,t,u,l,s(e)===m?e:null)):(t.anchor=o(e),f(m,c),t.targetAnchor||Lz(m,t,u,l),d(c&&o(c),t,m,n,r,i,a))),Iz(t,h)}else h&&t.shapeFlag&16&&(p(e,t),t.targetStart=e,t.targetAnchor=o(e));return t.anchor&&o(t.anchor)}var Fz=Mz;function Iz(e,t){let n=e.ctx;if(n&&n.ut){let r,i;for(t?(r=e.el,i=e.anchor):(r=e.targetStart,i=e.targetAnchor);r&&r!==i;)r.nodeType===1&&r.setAttribute(`data-v-owner`,n.uid),r=r.nextSibling;n.ut()}}function Lz(e,t,n,r,i=null){let a=t.targetStart=n(``),o=t.targetAnchor=n(``);return a[Tz]=o,e&&(r(a,e,i),r(o,e,i)),o}var Rz=Symbol(`_leaveCb`),zz=Symbol(`_enterCb`);function Bz(){let e={isMounted:!1,isLeaving:!1,isUnmounting:!1,leavingVNodes:new Map};return mB(()=>{e.isMounted=!0}),_B(()=>{e.isUnmounting=!0}),e}var Vz=[Function,Array],Hz={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:Vz,onEnter:Vz,onAfterEnter:Vz,onEnterCancelled:Vz,onBeforeLeave:Vz,onLeave:Vz,onAfterLeave:Vz,onLeaveCancelled:Vz,onBeforeAppear:Vz,onAppear:Vz,onAfterAppear:Vz,onAppearCancelled:Vz},Uz=e=>{let t=e.subTree;return t.component?Uz(t.component):t},Wz={name:`BaseTransition`,props:Hz,setup(e,{slots:t}){let n=hH(),r=Bz();return()=>{let i=t.default&&Qz(t.default(),!0),a=i&&i.length?Gz(i):n.subTree?Q():void 0;if(!a)return;let o=wR(e),{mode:s}=o;if(r.isLeaving)return Yz(a);let c=Xz(a);if(!c)return Yz(a);let l=Jz(c,o,r,n,e=>l=e);c.type!==HV&&Zz(c,l);let u=n.subTree&&Xz(n.subTree);if(u&&u.type!==HV&&!QV(u,c)&&Uz(n).type!==HV){let e=Jz(u,o,r,n);if(Zz(u,e),s===`out-in`&&c.type!==HV)return r.isLeaving=!0,e.afterLeave=()=>{r.isLeaving=!1,n.job.flags&8||n.update(),delete e.afterLeave,u=void 0},Yz(a);s===`in-out`&&c.type!==HV?e.delayLeave=(e,t,n)=>{let i=qz(r,u);i[String(u.key)]=u,e[Rz]=()=>{t(),e[Rz]=void 0,delete l.delayedLeave,u=void 0},l.delayedLeave=()=>{n(),delete l.delayedLeave,u=void 0}}:u=void 0}else u&&=void 0;return a}}};function Gz(e){let t=e[0];if(e.length>1){for(let n of e)if(n.type!==HV){t=n;break}}return t}var Kz=Wz;function qz(e,t){let{leavingVNodes:n}=e,r=n.get(t.type);return r||(r=Object.create(null),n.set(t.type,r)),r}function Jz(e,t,n,r,i){let{appear:a,mode:o,persisted:s=!1,onBeforeEnter:c,onEnter:l,onAfterEnter:u,onEnterCancelled:d,onBeforeLeave:f,onLeave:p,onAfterLeave:m,onLeaveCancelled:h,onBeforeAppear:g,onAppear:_,onAfterAppear:v,onAppearCancelled:y}=t,b=String(e.key),x=qz(n,e),S=(e,t)=>{e&&GR(e,r,9,t)},ee=(e,t)=>{let n=t[1];S(e,t),MI(e)?e.every(e=>e.length<=1)&&n():e.length<=1&&n()},C={mode:o,persisted:s,beforeEnter(t){let r=c;if(!n.isMounted)if(a)r=g||c;else return;t[Rz]&&t[Rz](!0);let i=x[b];i&&QV(e,i)&&i.el[Rz]&&i.el[Rz](),S(r,[t])},enter(t){if(x[b]===e)return;let r=l,i=u,o=d;if(!n.isMounted)if(a)r=_||l,i=v||u,o=y||d;else return;let s=!1;t[zz]=e=>{s||(s=!0,S(e?o:i,[t]),C.delayedLeave&&C.delayedLeave(),t[zz]=void 0)};let c=t[zz].bind(null,!1);r?ee(r,[t,c]):c()},leave(t,r){let i=String(e.key);if(t[zz]&&t[zz](!0),n.isUnmounting)return r();S(f,[t]);let a=!1;t[Rz]=n=>{a||(a=!0,r(),S(n?h:m,[t]),t[Rz]=void 0,x[i]===e&&delete x[i])};let o=t[Rz].bind(null,!1);x[i]=e,p?ee(p,[t,o]):o()},clone(e){let a=Jz(e,t,n,r,i);return i&&i(a),a}};return C}function Yz(e){if(oB(e))return e=iH(e),e.children=null,e}function Xz(e){if(!oB(e))return Ez(e.type)&&e.children?Gz(e.children):e;if(e.component)return e.component.subTree;let{shapeFlag:t,children:n}=e;if(n){if(t&16)return n[0];if(t&32&&II(n.default))return n.default()}}function Zz(e,t){e.shapeFlag&6&&e.component?(e.transition=t,Zz(e.component.subTree,t)):e.shapeFlag&128?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function Qz(e,t=!1,n){let r=[],i=0;for(let a=0;a<e.length;a++){let o=e[a],s=n==null?o.key:String(n)+String(o.key==null?a:o.key);o.type===BV?(o.patchFlag&128&&i++,r=r.concat(Qz(o.children,t,s))):(t||o.type!==HV)&&r.push(s==null?o:iH(o,{key:s}))}if(i>1)for(let e=0;e<r.length;e++)r[e].patchFlag=-2;return r}function $z(e,t){return II(e)?kI({name:e.name},t,{setup:e}):e}function eB(e){e.ids=[e.ids[0]+e.ids[2]+++`-`,0,0]}function tB(e,t){let n;return!!((n=Object.getOwnPropertyDescriptor(e,t))&&!n.configurable)}var nB=new WeakMap;function rB(e,t,n,r,i=!1){if(MI(e)){e.forEach((e,a)=>rB(e,t&&(MI(t)?t[a]:t),n,r,i));return}if(aB(r)&&!i){r.shapeFlag&512&&r.type.__asyncResolved&&r.component.subTree.component&&rB(e,t,n,r.component.subTree);return}let a=r.shapeFlag&4?AH(r.component):r.el,o=i?null:a,{i:s,r:c}=e,l=t&&t.r,u=s.refs===CI?s.refs={}:s.refs,d=s.setupState,f=wR(d),p=d===CI?EI:e=>!tB(u,e)&&jI(f,e),m=(e,t)=>!(t&&tB(u,t));if(l!=null&&l!==c){if(iB(t),LI(l))u[l]=null,p(l)&&(d[l]=null);else if(OR(l)){let e=t;m(l,e.k)&&(l.value=null),e.k&&(u[e.k]=null)}}if(II(c)){DL();try{WR(c,s,12,[o,u])}finally{OL()}}else{let t=LI(c),r=OR(c);if(t||r){let s=()=>{if(e.f){let n=t?p(c)?d[c]:u[c]:m(c)||!e.k?c.value:u[e.k];if(i)MI(n)&&AI(n,a);else if(MI(n))n.includes(a)||n.push(a);else if(t)u[c]=[a],p(c)&&(d[c]=u[c]);else{let t=[a];m(c,e.k)&&(c.value=t),e.k&&(u[e.k]=t)}}else t?(u[c]=o,p(c)&&(d[c]=o)):r&&(m(c,e.k)&&(c.value=o),e.k&&(u[e.k]=o))};if(o){let t=()=>{s(),nB.delete(e)};t.id=-1,nB.set(e,t),DV(t,n)}else iB(e),s()}}}function iB(e){let t=nB.get(e);t&&(t.flags|=8,nB.delete(e))}tL().requestIdleCallback,tL().cancelIdleCallback;var aB=e=>!!e.type.__asyncLoader,oB=e=>e.type.__isKeepAlive;function sB(e,t){lB(e,`a`,t)}function cB(e,t){lB(e,`da`,t)}function lB(e,t,n=mH){let r=e.__wdc||=()=>{let t=n;for(;t;){if(t.isDeactivated)return;t=t.parent}return e()};if(dB(t,r,n),n){let e=n.parent;for(;e&&e.parent;)oB(e.parent.vnode)&&uB(r,t,n,e),e=e.parent}}function uB(e,t,n,r){let i=dB(t,e,r,!0);vB(()=>{AI(r[t],i)},n)}function dB(e,t,n=mH,r=!1){if(n){let i=n[e]||(n[e]=[]),a=t.__weh||=(...r)=>{DL();let i=vH(n),a=GR(t,n,e,r);return i(),OL(),a};return r?i.unshift(a):i.push(a),a}}var fB=e=>(t,n=mH)=>{(!xH||e===`sp`)&&dB(e,(...e)=>t(...e),n)},pB=fB(`bm`),mB=fB(`m`),hB=fB(`bu`),gB=fB(`u`),_B=fB(`bum`),vB=fB(`um`),yB=fB(`sp`),bB=fB(`rtg`),xB=fB(`rtc`);function SB(e,t=mH){dB(`ec`,e,t)}var CB=Symbol.for(`v-ndc`);function wB(e,t,n,r){let i,a=n&&n[r],o=MI(e);if(o||LI(e)){let n=o&&bR(e),r=!1,s=!1;n&&(r=!SR(e),s=xR(e),e=BL(e)),i=Array(e.length);for(let n=0,o=e.length;n<o;n++)i[n]=t(r?s?DR(ER(e[n])):ER(e[n]):e[n],n,void 0,a&&a[n])}else if(typeof e==`number`){i=Array(e);for(let n=0;n<e;n++)i[n]=t(n+1,n,void 0,a&&a[n])}else if(zI(e))if(e[Symbol.iterator])i=Array.from(e,(e,n)=>t(e,n,void 0,a&&a[n]));else{let n=Object.keys(e);i=Array(n.length);for(let r=0,o=n.length;r<o;r++){let o=n[r];i[r]=t(e[o],o,r,a&&a[r])}}else i=[];return n&&(n[r]=i),i}function TB(e,t,n={},r,i){if(uz.ce||uz.parent&&aB(uz.parent)&&uz.parent.ce){let e=Object.keys(n).length>0;return t!=="default"&&(n.name=t),Y(),XV(BV,null,[tH(`slot`,n,r&&r())],e?-2:64)}let a=e[t];a&&a._c&&(a._d=!1),Y();let o=a&&EB(a(n)),s=n.key||o&&o.key,c=XV(BV,{key:(s&&!RI(s)?s:`_${t}`)+(!o&&r?`_fb`:``)},o||(r?r():[]),o&&e._===1?64:-2);return!i&&c.scopeId&&(c.slotScopeIds=[c.scopeId+`-s`]),a&&a._c&&(a._d=!0),c}function EB(e){return e.some(e=>!ZV(e)||!(e.type===HV||e.type===BV&&!EB(e.children)))?e:null}var DB=e=>e?bH(e)?AH(e):DB(e.parent):null,OB=kI(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>DB(e.parent),$root:e=>DB(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>LB(e),$forceUpdate:e=>e.f||=()=>{rz(e.update)},$nextTick:e=>e.n||=tz.bind(e.proxy),$watch:e=>Sz.bind(e)}),kB=(e,t)=>e!==CI&&!e.__isScriptSetup&&jI(e,t),AB={get({_:e},t){if(t===`__v_skip`)return!0;let{ctx:n,setupState:r,data:i,props:a,accessCache:o,type:s,appContext:c}=e;if(t[0]!==`$`){let e=o[t];if(e!==void 0)switch(e){case 1:return r[t];case 2:return i[t];case 4:return n[t];case 3:return a[t]}else if(kB(r,t))return o[t]=1,r[t];else if(i!==CI&&jI(i,t))return o[t]=2,i[t];else if(jI(a,t))return o[t]=3,a[t];else if(n!==CI&&jI(n,t))return o[t]=4,n[t];else MB&&(o[t]=0)}let l=OB[t],u,d;if(l)return t===`$attrs`&&LL(e.attrs,`get`,``),l(e);if((u=s.__cssModules)&&(u=u[t]))return u;if(n!==CI&&jI(n,t))return o[t]=4,n[t];if(d=c.config.globalProperties,jI(d,t))return d[t]},set({_:e},t,n){let{data:r,setupState:i,ctx:a}=e;return kB(i,t)?(i[t]=n,!0):r!==CI&&jI(r,t)?(r[t]=n,!0):jI(e.props,t)||t[0]===`$`&&t.slice(1)in e?!1:(a[t]=n,!0)},has({_:{data:e,setupState:t,accessCache:n,ctx:r,appContext:i,props:a,type:o}},s){let c;return!!(n[s]||e!==CI&&s[0]!==`$`&&jI(e,s)||kB(t,s)||jI(a,s)||jI(r,s)||jI(OB,s)||jI(i.config.globalProperties,s)||(c=o.__cssModules)&&c[s])},defineProperty(e,t,n){return n.get==null?jI(n,`value`)&&this.set(e,t,n.value,null):e._.accessCache[t]=0,Reflect.defineProperty(e,t,n)}};function jB(e){return MI(e)?e.reduce((e,t)=>(e[t]=null,e),{}):e}var MB=!0;function NB(e){let t=LB(e),n=e.proxy,r=e.ctx;MB=!1,t.beforeCreate&&FB(t.beforeCreate,e,`bc`);let{data:i,computed:a,methods:o,watch:s,provide:c,inject:l,created:u,beforeMount:d,mounted:f,beforeUpdate:p,updated:m,activated:h,deactivated:g,beforeDestroy:_,beforeUnmount:v,destroyed:y,unmounted:b,render:x,renderTracked:S,renderTriggered:ee,errorCaptured:C,serverPrefetch:te,expose:ne,inheritAttrs:w,components:re,directives:ie,filters:T}=t;if(l&&PB(l,r,null),o)for(let e in o){let t=o[e];II(t)&&(r[e]=t.bind(n))}if(i){let t=i.call(n,n);zI(t)&&(e.data=gR(t))}if(MB=!0,a)for(let e in a){let t=a[e],i=MH({get:II(t)?t.bind(n,n):II(t.get)?t.get.bind(n,n):TI,set:!II(t)&&II(t.set)?t.set.bind(n):TI});Object.defineProperty(r,e,{enumerable:!0,configurable:!0,get:()=>i.value,set:e=>i.value=e})}if(s)for(let e in s)IB(s[e],r,n,e);if(c){let e=II(c)?c.call(n):c;Reflect.ownKeys(e).forEach(t=>{gz(t,e[t])})}u&&FB(u,e,`c`);function ae(e,t){MI(t)?t.forEach(t=>e(t.bind(n))):t&&e(t.bind(n))}if(ae(pB,d),ae(mB,f),ae(hB,p),ae(gB,m),ae(sB,h),ae(cB,g),ae(SB,C),ae(xB,S),ae(bB,ee),ae(_B,v),ae(vB,b),ae(yB,te),MI(ne))if(ne.length){let t=e.exposed||={};ne.forEach(e=>{Object.defineProperty(t,e,{get:()=>n[e],set:t=>n[e]=t,enumerable:!0})})}else e.exposed||={};x&&e.render===TI&&(e.render=x),w!=null&&(e.inheritAttrs=w),re&&(e.components=re),ie&&(e.directives=ie),te&&eB(e)}function PB(e,t,n=TI){MI(e)&&(e=HB(e));for(let n in e){let r=e[n],i;i=zI(r)?`default`in r?_z(r.from||n,r.default,!0):_z(r.from||n):_z(r),OR(i)?Object.defineProperty(t,n,{enumerable:!0,configurable:!0,get:()=>i.value,set:e=>i.value=e}):t[n]=i}}function FB(e,t,n){GR(MI(e)?e.map(e=>e.bind(t.proxy)):e.bind(t.proxy),t,n)}function IB(e,t,n,r){let i=r.includes(`.`)?Cz(n,r):()=>n[r];if(LI(e)){let n=t[e];II(n)&&bz(i,n)}else if(II(e))bz(i,e.bind(n));else if(zI(e))if(MI(e))e.forEach(e=>IB(e,t,n,r));else{let r=II(e.handler)?e.handler.bind(n):t[e.handler];II(r)&&bz(i,r,e)}}function LB(e){let t=e.type,{mixins:n,extends:r}=t,{mixins:i,optionsCache:a,config:{optionMergeStrategies:o}}=e.appContext,s=a.get(t),c;return s?c=s:!i.length&&!n&&!r?c=t:(c={},i.length&&i.forEach(e=>RB(c,e,o,!0)),RB(c,t,o)),zI(t)&&a.set(t,c),c}function RB(e,t,n,r=!1){let{mixins:i,extends:a}=t;a&&RB(e,a,n,!0),i&&i.forEach(t=>RB(e,t,n,!0));for(let i in t)if(!(r&&i===`expose`)){let r=zB[i]||n&&n[i];e[i]=r?r(e[i],t[i]):t[i]}return e}var zB={data:BB,props:GB,emits:GB,methods:WB,computed:WB,beforeCreate:UB,created:UB,beforeMount:UB,mounted:UB,beforeUpdate:UB,updated:UB,beforeDestroy:UB,beforeUnmount:UB,destroyed:UB,unmounted:UB,activated:UB,deactivated:UB,errorCaptured:UB,serverPrefetch:UB,components:WB,directives:WB,watch:KB,provide:BB,inject:VB};function BB(e,t){return t?e?function(){return kI(II(e)?e.call(this,this):e,II(t)?t.call(this,this):t)}:t:e}function VB(e,t){return WB(HB(e),HB(t))}function HB(e){if(MI(e)){let t={};for(let n=0;n<e.length;n++)t[e[n]]=e[n];return t}return e}function UB(e,t){return e?[...new Set([].concat(e,t))]:t}function WB(e,t){return e?kI(Object.create(null),e,t):t}function GB(e,t){return e?MI(e)&&MI(t)?[...new Set([...e,...t])]:kI(Object.create(null),jB(e),jB(t??{})):t}function KB(e,t){if(!e)return t;if(!t)return e;let n=kI(Object.create(null),e);for(let r in t)n[r]=UB(e[r],t[r]);return n}function qB(){return{app:null,config:{isNativeTag:EI,performance:!1,globalProperties:{},optionMergeStrategies:{},errorHandler:void 0,warnHandler:void 0,compilerOptions:{}},mixins:[],components:{},directives:{},provides:Object.create(null),optionsCache:new WeakMap,propsCache:new WeakMap,emitsCache:new WeakMap}}var JB=0;function YB(e,t){return function(n,r=null){II(n)||(n=kI({},n)),r!=null&&!zI(r)&&(r=null);let i=qB(),a=new WeakSet,o=[],s=!1,c=i.app={_uid:JB++,_component:n,_props:r,_container:null,_context:i,_instance:null,version:PH,get config(){return i.config},set config(e){},use(e,...t){return a.has(e)||(e&&II(e.install)?(a.add(e),e.install(c,...t)):II(e)&&(a.add(e),e(c,...t))),c},mixin(e){return i.mixins.includes(e)||i.mixins.push(e),c},component(e,t){return t?(i.components[e]=t,c):i.components[e]},directive(e,t){return t?(i.directives[e]=t,c):i.directives[e]},mount(a,o,l){if(!s){let u=c._ceVNode||tH(n,r);return u.appContext=i,l===!0?l=`svg`:l===!1&&(l=void 0),o&&t?t(u,a):e(u,a,l),s=!0,c._container=a,a.__vue_app__=c,AH(u.component)}},onUnmount(e){o.push(e)},unmount(){s&&(GR(o,c._instance,16),e(null,c._container),delete c._container.__vue_app__)},provide(e,t){return i.provides[e]=t,c},runWithContext(e){let t=XB;XB=c;try{return e()}finally{XB=t}}};return c}}var XB=null,ZB=(e,t)=>t===`modelValue`||t===`model-value`?e.modelModifiers:e[`${t}Modifiers`]||e[`${qI(t)}Modifiers`]||e[`${JI(t)}Modifiers`];function QB(e,t,...n){if(e.isUnmounted)return;let r=e.vnode.props||CI,i=n,a=t.startsWith(`update:`),o=a&&ZB(r,t.slice(7));o&&(o.trim&&(i=n.map(e=>LI(e)?e.trim():e)),o.number&&(i=n.map(eL)));let s,c=r[s=XI(t)]||r[s=XI(qI(t))];!c&&a&&(c=r[s=XI(JI(t))]),c&&GR(c,e,6,i);let l=r[s+`Once`];if(l){if(!e.emitted)e.emitted={};else if(e.emitted[s])return;e.emitted[s]=!0,GR(l,e,6,i)}}var $B=new WeakMap;function eV(e,t,n=!1){let r=n?$B:t.emitsCache,i=r.get(e);if(i!==void 0)return i;let a=e.emits,o={},s=!1;if(!II(e)){let r=e=>{let n=eV(e,t,!0);n&&(s=!0,kI(o,n))};!n&&t.mixins.length&&t.mixins.forEach(r),e.extends&&r(e.extends),e.mixins&&e.mixins.forEach(r)}return!a&&!s?(zI(e)&&r.set(e,null),null):(MI(a)?a.forEach(e=>o[e]=null):kI(o,a),zI(e)&&r.set(e,o),o)}function tV(e,t){return!e||!DI(t)?!1:(t=t.slice(2),t=t===`Once`?t:t.replace(/Once$/,``),jI(e,t[0].toLowerCase()+t.slice(1))||jI(e,JI(t))||jI(e,t))}function nV(e){let{type:t,vnode:n,proxy:r,withProxy:i,propsOptions:[a],slots:o,attrs:s,emit:c,render:l,renderCache:u,props:d,data:f,setupState:p,ctx:m,inheritAttrs:h}=e,g=fz(e),_,v;try{if(n.shapeFlag&4){let e=i||r,t=e;_=oH(l.call(t,e,u,d,p,f,m)),v=s}else{let e=t;_=oH(e.length>1?e(d,{attrs:s,slots:o,emit:c}):e(d,null)),v=t.props?s:rV(s)}}catch(t){WV.length=0,KR(t,e,1),_=tH(HV)}let y=_;if(v&&h!==!1){let e=Object.keys(v),{shapeFlag:t}=y;e.length&&t&7&&(a&&e.some(OI)&&(v=iV(v,a)),y=iH(y,v,!1,!0))}return n.dirs&&(y=iH(y,null,!1,!0),y.dirs=y.dirs?y.dirs.concat(n.dirs):n.dirs),n.transition&&Zz(y,n.transition),_=y,fz(g),_}var rV=e=>{let t;for(let n in e)(n===`class`||n===`style`||DI(n))&&((t||={})[n]=e[n]);return t},iV=(e,t)=>{let n={};for(let r in e)(!OI(r)||!(r.slice(9)in t))&&(n[r]=e[r]);return n};function aV(e,t,n){let{props:r,children:i,component:a}=e,{props:o,children:s,patchFlag:c}=t,l=a.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&c>=0){if(c&1024)return!0;if(c&16)return r?oV(r,o,l):!!o;if(c&8){let e=t.dynamicProps;for(let t=0;t<e.length;t++){let n=e[t];if(sV(o,r,n)&&!tV(l,n))return!0}}}else return(i||s)&&(!s||!s.$stable)?!0:r===o?!1:r?!o||oV(r,o,l):!!o;return!1}function oV(e,t,n){let r=Object.keys(t);if(r.length!==Object.keys(e).length)return!0;for(let i=0;i<r.length;i++){let a=r[i];if(sV(t,e,a)&&!tV(n,a))return!0}return!1}function sV(e,t,n){let r=e[n],i=t[n];return n===`style`&&zI(r)&&zI(i)?!oL(r,i):r!==i}function cV({vnode:e,parent:t,suspense:n},r){for(;t;){let n=t.subTree;if(n.suspense&&n.suspense.activeBranch===e&&(n.suspense.vnode.el=n.el=r,e=n),n===e)(e=t.vnode).el=r,t=t.parent;else break}n&&n.activeBranch===e&&(n.vnode.el=r)}var lV={},uV=()=>Object.create(lV),dV=e=>Object.getPrototypeOf(e)===lV;function fV(e,t,n,r=!1){let i={},a=uV();e.propsDefaults=Object.create(null),mV(e,t,i,a);for(let t in e.propsOptions[0])t in i||(i[t]=void 0);n?e.props=r?i:_R(i):e.type.props?e.props=i:e.props=a,e.attrs=a}function pV(e,t,n,r){let{props:i,attrs:a,vnode:{patchFlag:o}}=e,s=wR(i),[c]=e.propsOptions,l=!1;if((r||o>0)&&!(o&16)){if(o&8){let n=e.vnode.dynamicProps;for(let r=0;r<n.length;r++){let o=n[r];if(tV(e.emitsOptions,o))continue;let u=t[o];if(c)if(jI(a,o))u!==a[o]&&(a[o]=u,l=!0);else{let t=qI(o);i[t]=hV(c,s,t,u,e,!1)}else u!==a[o]&&(a[o]=u,l=!0)}}}else{mV(e,t,i,a)&&(l=!0);let r;for(let a in s)(!t||!jI(t,a)&&((r=JI(a))===a||!jI(t,r)))&&(c?n&&(n[a]!==void 0||n[r]!==void 0)&&(i[a]=hV(c,s,a,void 0,e,!0)):delete i[a]);if(a!==s)for(let e in a)(!t||!jI(t,e))&&(delete a[e],l=!0)}l&&RL(e.attrs,`set`,``)}function mV(e,t,n,r){let[i,a]=e.propsOptions,o=!1,s;if(t)for(let c in t){if(GI(c))continue;let l=t[c],u;i&&jI(i,u=qI(c))?!a||!a.includes(u)?n[u]=l:(s||={})[u]=l:tV(e.emitsOptions,c)||(!(c in r)||l!==r[c])&&(r[c]=l,o=!0)}if(a){let t=wR(n),r=s||CI;for(let o=0;o<a.length;o++){let s=a[o];n[s]=hV(i,t,s,r[s],e,!jI(r,s))}}return o}function hV(e,t,n,r,i,a){let o=e[n];if(o!=null){let e=jI(o,`default`);if(e&&r===void 0){let e=o.default;if(o.type!==Function&&!o.skipFactory&&II(e)){let{propsDefaults:a}=i;if(n in a)r=a[n];else{let o=vH(i);r=a[n]=e.call(null,t),o()}}else r=e;i.ce&&i.ce._setProp(n,r)}o[0]&&(a&&!e?r=!1:o[1]&&(r===``||r===JI(n))&&(r=!0))}return r}var gV=new WeakMap;function _V(e,t,n=!1){let r=n?gV:t.propsCache,i=r.get(e);if(i)return i;let a=e.props,o={},s=[],c=!1;if(!II(e)){let r=e=>{c=!0;let[n,r]=_V(e,t,!0);kI(o,n),r&&s.push(...r)};!n&&t.mixins.length&&t.mixins.forEach(r),e.extends&&r(e.extends),e.mixins&&e.mixins.forEach(r)}if(!a&&!c)return zI(e)&&r.set(e,wI),wI;if(MI(a))for(let e=0;e<a.length;e++){let t=qI(a[e]);vV(t)&&(o[t]=CI)}else if(a)for(let e in a){let t=qI(e);if(vV(t)){let n=a[e],r=o[t]=MI(n)||II(n)?{type:n}:kI({},n),i=r.type,c=!1,l=!0;if(MI(i))for(let e=0;e<i.length;++e){let t=i[e],n=II(t)&&t.name;if(n===`Boolean`){c=!0;break}else n===`String`&&(l=!1)}else c=II(i)&&i.name===`Boolean`;r[0]=c,r[1]=l,(c||jI(r,`default`))&&s.push(t)}}let l=[o,s];return zI(e)&&r.set(e,l),l}function vV(e){return e[0]!==`$`&&!GI(e)}var yV=e=>e===`_`||e===`_ctx`||e===`$stable`,bV=e=>MI(e)?e.map(oH):[oH(e)],xV=(e,t,n)=>{if(t._n)return t;let r=pz((...e)=>bV(t(...e)),n);return r._c=!1,r},SV=(e,t,n)=>{let r=e._ctx;for(let n in e){if(yV(n))continue;let i=e[n];if(II(i))t[n]=xV(n,i,r);else if(i!=null){let e=bV(i);t[n]=()=>e}}},CV=(e,t)=>{let n=bV(t);e.slots.default=()=>n},wV=(e,t,n)=>{for(let r in t)(n||!yV(r))&&(e[r]=t[r])},TV=(e,t,n)=>{let r=e.slots=uV();if(e.vnode.shapeFlag&32){let e=t._;e?(wV(r,t,n),n&&$I(r,`_`,e,!0)):SV(t,r)}else t&&CV(e,t)},EV=(e,t,n)=>{let{vnode:r,slots:i}=e,a=!0,o=CI;if(r.shapeFlag&32){let e=t._;e?n&&e===1?a=!1:wV(i,t,n):(a=!t.$stable,SV(t,i)),o=t}else t&&(CV(e,t),o={default:1});if(a)for(let e in i)!yV(e)&&o[e]==null&&delete i[e]},DV=zV;function OV(e){return kV(e)}function kV(e,t){let n=tL();n.__VUE__=!0;let{insert:r,remove:i,patchProp:a,createElement:o,createText:s,createComment:c,setText:l,setElementText:u,parentNode:d,nextSibling:f,setScopeId:p=TI,insertStaticContent:m}=e,h=(e,t,n,r=null,i=null,a=null,o=void 0,s=null,c=!!t.dynamicChildren)=>{if(e===t)return;e&&!QV(e,t)&&(r=me(e),ue(e,i,a,!0),e=null),t.patchFlag===-2&&(c=!1,t.dynamicChildren=null);let{type:l,ref:u,shapeFlag:d}=t;switch(l){case VV:g(e,t,n,r);break;case HV:_(e,t,n,r);break;case UV:e??v(t,n,r,o);break;case BV:re(e,t,n,r,i,a,o,s,c);break;default:d&1?x(e,t,n,r,i,a,o,s,c):d&6?ie(e,t,n,r,i,a,o,s,c):(d&64||d&128)&&l.process(e,t,n,r,i,a,o,s,c,_e)}u!=null&&i?rB(u,e&&e.ref,a,t||e,!t):u==null&&e&&e.ref!=null&&rB(e.ref,null,a,e,!0)},g=(e,t,n,i)=>{if(e==null)r(t.el=s(t.children),n,i);else{let n=t.el=e.el;t.children!==e.children&&l(n,t.children)}},_=(e,t,n,i)=>{e==null?r(t.el=c(t.children||``),n,i):t.el=e.el},v=(e,t,n,r)=>{[e.el,e.anchor]=m(e.children,t,n,r,e.el,e.anchor)},y=({el:e,anchor:t},n,i)=>{let a;for(;e&&e!==t;)a=f(e),r(e,n,i),e=a;r(t,n,i)},b=({el:e,anchor:t})=>{let n;for(;e&&e!==t;)n=f(e),i(e),e=n;i(t)},x=(e,t,n,r,i,a,o,s,c)=>{if(t.type===`svg`?o=`svg`:t.type===`math`&&(o=`mathml`),e==null)S(t,n,r,i,a,o,s,c);else{let n=e.el&&e.el._isVueCE?e.el:null;try{n&&n._beginPatch(),te(e,t,i,a,o,s,c)}finally{n&&n._endPatch()}}},S=(e,t,n,i,s,c,l,d)=>{let f,p,{props:m,shapeFlag:h,transition:g,dirs:_}=e;if(f=e.el=o(e.type,c,m&&m.is,m),h&8?u(f,e.children):h&16&&C(e.children,f,null,i,s,AV(e,c),l,d),_&&hz(e,null,i,`created`),ee(f,e,e.scopeId,l,i),m){for(let e in m)e!==`value`&&!GI(e)&&a(f,e,null,m[e],c,i);`value`in m&&a(f,`value`,null,m.value,c),(p=m.onVnodeBeforeMount)&&uH(p,i,e)}_&&hz(e,null,i,`beforeMount`);let v=MV(s,g);v&&g.beforeEnter(f),r(f,t,n),((p=m&&m.onVnodeMounted)||v||_)&&DV(()=>{try{p&&uH(p,i,e),v&&g.enter(f),_&&hz(e,null,i,`mounted`)}finally{}},s)},ee=(e,t,n,r,i)=>{if(n&&p(e,n),r)for(let t=0;t<r.length;t++)p(e,r[t]);if(i){let n=i.subTree;if(t===n||RV(n.type)&&(n.ssContent===t||n.ssFallback===t)){let t=i.vnode;ee(e,t,t.scopeId,t.slotScopeIds,i.parent)}}},C=(e,t,n,r,i,a,o,s,c=0)=>{for(let l=c;l<e.length;l++){let c=e[l]=s?sH(e[l]):oH(e[l]);h(null,c,t,n,r,i,a,o,s)}},te=(e,t,n,r,i,o,s)=>{let c=t.el=e.el,{patchFlag:l,dynamicChildren:d,dirs:f}=t;l|=e.patchFlag&16;let p=e.props||CI,m=t.props||CI,h;if(n&&jV(n,!1),(h=m.onVnodeBeforeUpdate)&&uH(h,n,t,e),f&&hz(t,e,n,`beforeUpdate`),n&&jV(n,!0),d&&(!e.dynamicChildren||e.dynamicChildren.length!==d.length)&&(l=0,s=!1,d=null),(p.innerHTML&&m.innerHTML==null||p.textContent&&m.textContent==null)&&u(c,``),d?ne(e.dynamicChildren,d,c,n,r,AV(t,i),o):s||se(e,t,c,null,n,r,AV(t,i),o,!1),l>0){if(l&16)w(c,p,m,n,i);else if(l&2&&p.class!==m.class&&a(c,`class`,null,m.class,i),l&4&&a(c,`style`,p.style,m.style,i),l&8){let e=t.dynamicProps;for(let t=0;t<e.length;t++){let r=e[t],o=p[r],s=m[r];(s!==o||r===`value`)&&a(c,r,o,s,i,n)}}l&1&&e.children!==t.children&&u(c,t.children)}else!s&&d==null&&w(c,p,m,n,i);((h=m.onVnodeUpdated)||f)&&DV(()=>{h&&uH(h,n,t,e),f&&hz(t,e,n,`updated`)},r)},ne=(e,t,n,r,i,a,o)=>{for(let s=0;s<t.length;s++){let c=e[s],l=t[s],u=c.el&&(c.type===BV||!QV(c,l)||c.shapeFlag&198)?d(c.el):n;h(c,l,u,null,r,i,a,o,!0)}},w=(e,t,n,r,i)=>{if(t!==n){if(t!==CI)for(let o in t)!GI(o)&&!(o in n)&&a(e,o,t[o],null,i,r);for(let o in n){if(GI(o))continue;let s=n[o],c=t[o];s!==c&&o!==`value`&&a(e,o,c,s,i,r)}`value`in n&&a(e,`value`,t.value,n.value,i)}},re=(e,t,n,i,a,o,c,l,u)=>{let d=t.el=e?e.el:s(``),f=t.anchor=e?e.anchor:s(``),{patchFlag:p,dynamicChildren:m,slotScopeIds:h}=t;h&&(l=l?l.concat(h):h),e==null?(r(d,n,i),r(f,n,i),C(t.children||[],n,f,a,o,c,l,u)):p>0&&p&64&&m&&e.dynamicChildren&&e.dynamicChildren.length===m.length?(ne(e.dynamicChildren,m,n,a,o,c,l),(t.key!=null||a&&t===a.subTree)&&NV(e,t,!0)):se(e,t,n,f,a,o,c,l,u)},ie=(e,t,n,r,i,a,o,s,c)=>{t.slotScopeIds=s,e==null?t.shapeFlag&512?i.ctx.activate(t,n,r,o,c):T(t,n,r,i,a,o,c):ae(e,t,c)},T=(e,t,n,r,i,a,o)=>{let s=e.component=pH(e,r,i);if(oB(e)&&(s.ctx.renderer=_e),SH(s,!1,o),s.asyncDep){if(i&&i.registerDep(s,E,o),!e.el){let r=s.subTree=tH(HV);_(null,r,t,n),e.placeholder=r.el}}else E(s,e,t,n,i,a,o)},ae=(e,t,n)=>{let r=t.component=e.component;if(aV(e,t,n))if(r.asyncDep&&!r.asyncResolved){oe(r,t,n);return}else r.next=t,r.update();else t.el=e.el,r.vnode=t},E=(e,t,n,r,i,a,o)=>{let s=()=>{if(e.isMounted){let{next:t,bu:n,u:r,parent:s,vnode:c}=e;{let n=FV(e);if(n){t&&(t.el=c.el,oe(e,t,o)),n.asyncDep.then(()=>{DV(()=>{e.isUnmounted||l()},i)});return}}let u=t,f;jV(e,!1),t?(t.el=c.el,oe(e,t,o)):t=c,n&&QI(n),(f=t.props&&t.props.onVnodeBeforeUpdate)&&uH(f,s,t,c),jV(e,!0);let p=nV(e),m=e.subTree;e.subTree=p,h(m,p,d(m.el),me(m),e,i,a),t.el=p.el,u===null&&cV(e,p.el),r&&DV(r,i),(f=t.props&&t.props.onVnodeUpdated)&&DV(()=>uH(f,s,t,c),i)}else{let o,{el:s,props:c}=t,{bm:l,m:u,parent:d,root:f,type:p}=e,m=aB(t);if(jV(e,!1),l&&QI(l),!m&&(o=c&&c.onVnodeBeforeMount)&&uH(o,d,t),jV(e,!0),s&&ye){let t=()=>{e.subTree=nV(e),ye(s,e.subTree,e,i,null)};m&&p.__asyncHydrate?p.__asyncHydrate(s,e,t):t()}else{f.ce&&f.ce._hasShadowRoot()&&f.ce._injectChildStyle(p,e.parent?e.parent.type:void 0);let o=e.subTree=nV(e);h(null,o,n,r,e,i,a),t.el=o.el}if(u&&DV(u,i),!m&&(o=c&&c.onVnodeMounted)){let e=t;DV(()=>uH(o,d,e),i)}(t.shapeFlag&256||d&&aB(d.vnode)&&d.vnode.shapeFlag&256)&&e.a&&DV(e.a,i),e.isMounted=!0,t=n=r=null}};e.scope.on();let c=e.effect=new pL(s);e.scope.off();let l=e.update=c.run.bind(c),u=e.job=c.runIfDirty.bind(c);u.i=e,u.id=e.uid,c.scheduler=()=>rz(u),jV(e,!0),l()},oe=(e,t,n)=>{t.component=e;let r=e.vnode.props;e.vnode=t,e.next=null,pV(e,t.props,r,n),EV(e,t.children,n),DL(),oz(e),OL()},se=(e,t,n,r,i,a,o,s,c=!1)=>{let l=e&&e.children,d=e?e.shapeFlag:0,f=t.children,{patchFlag:p,shapeFlag:m}=t;if(p>0){if(p&128){D(l,f,n,r,i,a,o,s,c);return}else if(p&256){ce(l,f,n,r,i,a,o,s,c);return}}m&8?(d&16&&pe(l,i,a),f!==l&&u(n,f)):d&16?m&16?D(l,f,n,r,i,a,o,s,c):pe(l,i,a,!0):(d&8&&u(n,``),m&16&&C(f,n,r,i,a,o,s,c))},ce=(e,t,n,r,i,a,o,s,c)=>{e||=wI,t||=wI;let l=e.length,u=t.length,d=Math.min(l,u),f;for(f=0;f<d;f++){let r=t[f]=c?sH(t[f]):oH(t[f]);h(e[f],r,n,null,i,a,o,s,c)}l>u?pe(e,i,a,!0,!1,d):C(t,n,r,i,a,o,s,c,d)},D=(e,t,n,r,i,a,o,s,c)=>{let l=0,u=t.length,d=e.length-1,f=u-1;for(;l<=d&&l<=f;){let r=e[l],u=t[l]=c?sH(t[l]):oH(t[l]);if(QV(r,u))h(r,u,n,null,i,a,o,s,c);else break;l++}for(;l<=d&&l<=f;){let r=e[d],l=t[f]=c?sH(t[f]):oH(t[f]);if(QV(r,l))h(r,l,n,null,i,a,o,s,c);else break;d--,f--}if(l>d){if(l<=f){let e=f+1,d=e<u?t[e].el:r;for(;l<=f;)h(null,t[l]=c?sH(t[l]):oH(t[l]),n,d,i,a,o,s,c),l++}}else if(l>f)for(;l<=d;)ue(e[l],i,a,!0),l++;else{let p=l,m=l,g=new Map;for(l=m;l<=f;l++){let e=t[l]=c?sH(t[l]):oH(t[l]);e.key!=null&&g.set(e.key,l)}let _,v=0,y=f-m+1,b=!1,x=0,S=Array(y);for(l=0;l<y;l++)S[l]=0;for(l=p;l<=d;l++){let r=e[l];if(v>=y){ue(r,i,a,!0);continue}let u;if(r.key!=null)u=g.get(r.key);else for(_=m;_<=f;_++)if(S[_-m]===0&&QV(r,t[_])){u=_;break}u===void 0?ue(r,i,a,!0):(S[u-m]=l+1,u>=x?x=u:b=!0,h(r,t[u],n,null,i,a,o,s,c),v++)}let ee=b?PV(S):wI;for(_=ee.length-1,l=y-1;l>=0;l--){let e=m+l,d=t[e],f=t[e+1],p=e+1<u?f.el||LV(f):r;S[l]===0?h(null,d,n,p,i,a,o,s,c):b&&(_<0||l!==ee[_]?le(d,n,p,2):_--)}}},le=(e,t,n,a,o=null)=>{let{el:s,type:c,transition:l,children:u,shapeFlag:d}=e;if(d&6){le(e.component.subTree,t,n,a);return}if(d&128){e.suspense.move(t,n,a);return}if(d&64){c.move(e,t,n,_e);return}if(c===BV){r(s,t,n);for(let e=0;e<u.length;e++)le(u[e],t,n,a);r(e.anchor,t,n);return}if(c===UV){y(e,t,n);return}if(a!==2&&d&1&&l)if(a===0)l.persisted&&!s[Rz]?r(s,t,n):(l.beforeEnter(s),r(s,t,n),DV(()=>l.enter(s),o));else{let{leave:a,delayLeave:o,afterLeave:c}=l,u=()=>{e.ctx.isUnmounted?i(s):r(s,t,n)},d=()=>{let e=s._isLeaving||!!s[Rz];s._isLeaving&&s[Rz](!0),l.persisted&&!e?u():a(s,()=>{u(),c&&c()})};o?o(s,u,d):d()}else r(s,t,n)},ue=(e,t,n,r=!1,i=!1)=>{let{type:a,props:o,ref:s,children:c,dynamicChildren:l,shapeFlag:u,patchFlag:d,dirs:f,cacheIndex:p,memo:m}=e;if(d===-2&&(i=!1),s!=null&&(DL(),rB(s,null,n,e,!0),OL()),p!=null&&(t.renderCache[p]=void 0),u&256){t.ctx.deactivate(e);return}let h=u&1&&f,g=!aB(e),_;if(g&&(_=o&&o.onVnodeBeforeUnmount)&&uH(_,t,e),u&6)fe(e.component,n,r);else{if(u&128){e.suspense.unmount(n,r);return}h&&hz(e,null,t,`beforeUnmount`),u&64?e.type.remove(e,t,n,_e,r):l&&!l.hasOnce&&(a!==BV||d>0&&d&64)?pe(l,t,n,!1,!0):(a===BV&&d&384||!i&&u&16)&&pe(c,t,n),r&&O(e)}let v=m!=null&&p==null;(g&&(_=o&&o.onVnodeUnmounted)||h||v)&&DV(()=>{_&&uH(_,t,e),h&&hz(e,null,t,`unmounted`),v&&(e.el=null)},n)},O=e=>{let{type:t,el:n,anchor:r,transition:a}=e;if(t===BV){de(n,r);return}if(t===UV){b(e);return}let o=()=>{i(n),a&&!a.persisted&&a.afterLeave&&a.afterLeave()};if(e.shapeFlag&1&&a&&!a.persisted){let{leave:t,delayLeave:r}=a,i=()=>t(n,o);r?r(e.el,o,i):i()}else o()},de=(e,t)=>{let n;for(;e!==t;)n=f(e),i(e),e=n;i(t)},fe=(e,t,n)=>{let{bum:r,scope:i,job:a,subTree:o,um:s,m:c,a:l}=e;IV(c),IV(l),r&&QI(r),i.stop(),a&&(a.flags|=8,ue(o,e,t,n)),s&&DV(s,t),DV(()=>{e.isUnmounted=!0},t)},pe=(e,t,n,r=!1,i=!1,a=0)=>{for(let o=a;o<e.length;o++)ue(e[o],t,n,r,i)},me=e=>{if(e.shapeFlag&6)return me(e.component.subTree);if(e.shapeFlag&128)return e.suspense.next();let t=f(e.anchor||e.el),n=t&&t[Tz];return n?f(n):t},he=!1,ge=(e,t,n)=>{let r;e==null?t._vnode&&(ue(t._vnode,null,null,!0),r=t._vnode.component):h(t._vnode||null,e,t,null,null,null,n),t._vnode=e,he||=(he=!0,oz(r),sz(),!1)},_e={p:h,um:ue,m:le,r:O,mt:T,mc:C,pc:se,pbc:ne,n:me,o:e},ve,ye;return t&&([ve,ye]=t(_e)),{render:ge,hydrate:ve,createApp:YB(ge,ve)}}function AV({type:e,props:t},n){return n===`svg`&&e===`foreignObject`||n===`mathml`&&e===`annotation-xml`&&t&&t.encoding&&t.encoding.includes(`html`)?void 0:n}function jV({effect:e,job:t},n){n?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function MV(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function NV(e,t,n=!1){let r=e.children,i=t.children;if(MI(r)&&MI(i))for(let e=0;e<r.length;e++){let t=r[e],a=i[e];a.shapeFlag&1&&!a.dynamicChildren&&((a.patchFlag<=0||a.patchFlag===32)&&(a=i[e]=sH(i[e]),a.el=t.el),!n&&a.patchFlag!==-2&&NV(t,a)),a.type===VV&&(a.patchFlag===-1&&(a=i[e]=sH(a)),a.el=t.el),a.type===HV&&!a.el&&(a.el=t.el)}}function PV(e){let t=e.slice(),n=[0],r,i,a,o,s,c=e.length;for(r=0;r<c;r++){let c=e[r];if(c!==0){if(i=n[n.length-1],e[i]<c){t[r]=i,n.push(r);continue}for(a=0,o=n.length-1;a<o;)s=a+o>>1,e[n[s]]<c?a=s+1:o=s;c<e[n[a]]&&(a>0&&(t[r]=n[a-1]),n[a]=r)}}for(a=n.length,o=n[a-1];a-->0;)n[a]=o,o=t[o];return n}function FV(e){let t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:FV(t)}function IV(e){if(e)for(let t=0;t<e.length;t++)e[t].flags|=8}function LV(e){if(e.placeholder)return e.placeholder;let t=e.component;return t?LV(t.subTree):null}var RV=e=>e.__isSuspense;function zV(e,t){t&&t.pendingBranch?MI(e)?t.effects.push(...e):t.effects.push(e):az(e)}var BV=Symbol.for(`v-fgt`),VV=Symbol.for(`v-txt`),HV=Symbol.for(`v-cmt`),UV=Symbol.for(`v-stc`),WV=[],GV=null;function Y(e=!1){WV.push(GV=e?null:[])}function KV(){WV.pop(),GV=WV[WV.length-1]||null}var qV=1;function JV(e,t=!1){qV+=e,e<0&&GV&&t&&(GV.hasOnce=!0)}function YV(e){return e.dynamicChildren=qV>0?GV||wI:null,KV(),qV>0&&GV&&GV.push(e),e}function X(e,t,n,r,i,a){return YV(Z(e,t,n,r,i,a,!0))}function XV(e,t,n,r,i){return YV(tH(e,t,n,r,i,!0))}function ZV(e){return e?e.__v_isVNode===!0:!1}function QV(e,t){return e.type===t.type&&e.key===t.key}var $V=({key:e})=>e??null,eH=({ref:e,ref_key:t,ref_for:n})=>(typeof e==`number`&&(e=``+e),e==null?null:LI(e)||OR(e)||II(e)?{i:uz,r:e,k:t,f:!!n}:e);function Z(e,t=null,n=null,r=0,i=null,a=e===BV?0:1,o=!1,s=!1){let c={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&$V(t),ref:t&&eH(t),scopeId:dz,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:a,patchFlag:r,dynamicProps:i,dynamicChildren:null,appContext:null,ctx:uz};return s?(cH(c,n),a&128&&e.normalize(c)):n&&(c.shapeFlag|=LI(n)?8:16),qV>0&&!o&&GV&&(c.patchFlag>0||a&6)&&c.patchFlag!==32&&GV.push(c),c}var tH=nH;function nH(e,t=null,n=null,r=0,i=null,a=!1){if((!e||e===CB)&&(e=HV),ZV(e)){let r=iH(e,t,!0);return n&&cH(r,n),qV>0&&!a&&GV&&(r.shapeFlag&6?GV[GV.indexOf(e)]=r:GV.push(r)),r.patchFlag=-2,r}if(jH(e)&&(e=e.__vccOpts),t){t=rH(t);let{class:e,style:n}=t;e&&!LI(e)&&(t.class=rL(e)),zI(n)&&(CR(n)&&!MI(n)&&(n=kI({},n)),t.style=nL(n))}let o=LI(e)?1:RV(e)?128:Ez(e)?64:zI(e)?4:II(e)?2:0;return Z(e,t,n,r,i,o,a,!0)}function rH(e){return e?CR(e)||dV(e)?kI({},e):e:null}function iH(e,t,n=!1,r=!1){let{props:i,ref:a,patchFlag:o,children:s,transition:c}=e,l=t?lH(i||{},t):i,u={__v_isVNode:!0,__v_skip:!0,type:e.type,props:l,key:l&&$V(l),ref:t&&t.ref?n&&a?MI(a)?a.concat(eH(t)):[a,eH(t)]:eH(t):a,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:s,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==BV?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:c,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&iH(e.ssContent),ssFallback:e.ssFallback&&iH(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce};return c&&r&&Zz(u,c.clone(u)),u}function aH(e=` `,t=0){return tH(VV,null,e,t)}function Q(e=``,t=!1){return t?(Y(),XV(HV,null,e)):tH(HV,null,e)}function oH(e){return e==null||typeof e==`boolean`?tH(HV):MI(e)?tH(BV,null,e.slice()):ZV(e)?sH(e):tH(VV,null,String(e))}function sH(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:iH(e)}function cH(e,t){let n=0,{shapeFlag:r}=e;if(t==null)t=null;else if(MI(t))n=16;else if(typeof t==`object`)if(r&65){let n=t.default;n&&(n._c&&(n._d=!1),cH(e,n()),n._c&&(n._d=!0));return}else{n=32;let r=t._;!r&&!dV(t)?t._ctx=uz:r===3&&uz&&(uz.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else if(II(t)){if(r&65){cH(e,{default:t});return}t={default:t,_ctx:uz},n=32}else t=String(t),r&64?(n=16,t=[aH(t)]):n=8;e.children=t,e.shapeFlag|=n}function lH(...e){let t={};for(let n=0;n<e.length;n++){let r=e[n];for(let e in r)if(e===`class`)t.class!==r.class&&(t.class=rL([t.class,r.class]));else if(e===`style`)t.style=nL([t.style,r.style]);else if(DI(e)){let n=t[e],i=r[e];i&&n!==i&&!(MI(n)&&n.includes(i))?t[e]=n?[].concat(n,i):i:i==null&&n==null&&!OI(e)&&(t[e]=i)}else e!==``&&(t[e]=r[e])}return t}function uH(e,t,n,r=null){GR(e,t,7,[n,r])}var dH=qB(),fH=0;function pH(e,t,n){let r=e.type,i=(t?t.appContext:e.appContext)||dH,a={uid:fH++,vnode:e,type:r,parent:t,appContext:i,root:null,next:null,subTree:null,effect:null,update:null,job:null,scope:new pce(!0),render:null,proxy:null,exposed:null,exposeProxy:null,withProxy:null,provides:t?t.provides:Object.create(i.provides),ids:t?t.ids:[``,0,0],accessCache:null,renderCache:[],components:null,directives:null,propsOptions:_V(r,i),emitsOptions:eV(r,i),emit:null,emitted:null,propsDefaults:CI,inheritAttrs:r.inheritAttrs,ctx:CI,data:CI,props:CI,attrs:CI,slots:CI,refs:CI,setupState:CI,setupContext:null,suspense:n,suspenseId:n?n.pendingId:0,asyncDep:null,asyncResolved:!1,isMounted:!1,isUnmounted:!1,isDeactivated:!1,bc:null,c:null,bm:null,m:null,bu:null,u:null,um:null,bum:null,da:null,a:null,rtg:null,rtc:null,ec:null,sp:null};return a.ctx={_:a},a.root=t?t.root:a,a.emit=QB.bind(null,a),e.ce&&e.ce(a),a}var mH=null,hH=()=>mH||uz,gH,_H;{let e=tL(),t=(t,n)=>{let r;return(r=e[t])||(r=e[t]=[]),r.push(n),e=>{r.length>1?r.forEach(t=>t(e)):r[0](e)}};gH=t(`__VUE_INSTANCE_SETTERS__`,e=>mH=e),_H=t(`__VUE_SSR_SETTERS__`,e=>xH=e)}var vH=e=>{let t=mH;return gH(e),e.scope.on(),()=>{e.scope.off(),gH(t)}},yH=()=>{mH&&mH.scope.off(),gH(null)};function bH(e){return e.vnode.shapeFlag&4}var xH=!1;function SH(e,t=!1,n=!1){t&&_H(t);let{props:r,children:i}=e.vnode,a=bH(e);fV(e,r,a,t),TV(e,i,n||t);let o=a?CH(e,t):void 0;return t&&_H(!1),o}function CH(e,t){let n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,AB);let{setup:r}=n;if(r){DL();let n=e.setupContext=r.length>1?kH(e):null,i=vH(e),a=WR(r,e,0,[e.props,n]),o=BI(a);if(OL(),i(),(o||e.sp)&&!aB(e)&&eB(e),o){if(a.then(yH,yH),t)return a.then(n=>{wH(e,n,t)}).catch(t=>{KR(t,e,0)});e.asyncDep=a}else wH(e,a,t)}else DH(e,t)}function wH(e,t,n){II(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:zI(t)&&(e.setupState=FR(t)),DH(e,n)}var TH,EH;function DH(e,t,n){let r=e.type;if(!e.render){if(!t&&TH&&!r.render){let t=r.template||LB(e).template;if(t){let{isCustomElement:n,compilerOptions:i}=e.appContext.config,{delimiters:a,compilerOptions:o}=r;r.render=TH(t,kI(kI({isCustomElement:n,delimiters:a},i),o))}}e.render=r.render||TI,EH&&EH(e)}{let t=vH(e);DL();try{NB(e)}finally{OL(),t()}}}var OH={get(e,t){return LL(e,`get`,``),e[t]}};function kH(e){return{attrs:new Proxy(e.attrs,OH),slots:e.slots,emit:e.emit,expose:t=>{e.exposed=t||{}}}}function AH(e){return e.exposed?e.exposeProxy||=new Proxy(FR(TR(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in OB)return OB[n](e)},has(e,t){return t in e||t in OB}}):e.proxy}function jH(e){return II(e)&&`__vccOpts`in e}var MH=(e,t)=>LR(e,t,xH);function NH(e,t,n){try{JV(-1);let r=arguments.length;return r===2?zI(t)&&!MI(t)?ZV(t)?tH(e,null,[t]):tH(e,t):tH(e,null,t):(r>3?n=Array.prototype.slice.call(arguments,2):r===3&&ZV(n)&&(n=[n]),tH(e,t,n))}finally{JV(1)}}var PH=`3.5.39`,FH=void 0,IH=typeof window<`u`&&window.trustedTypes;if(IH)try{FH=IH.createPolicy(`vue`,{createHTML:e=>e})}catch{}var LH=FH?e=>FH.createHTML(e):e=>e,RH=`http://www.w3.org/2000/svg`,zH=`http://www.w3.org/1998/Math/MathML`,BH=typeof document<`u`?document:null,VH=BH&&BH.createElement(`template`),HH={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{let t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,r)=>{let i=t===`svg`?BH.createElementNS(RH,e):t===`mathml`?BH.createElementNS(zH,e):n?BH.createElement(e,{is:n}):BH.createElement(e);return e===`select`&&r&&r.multiple!=null&&i.setAttribute(`multiple`,r.multiple),i},createText:e=>BH.createTextNode(e),createComment:e=>BH.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>BH.querySelector(e),setScopeId(e,t){e.setAttribute(t,``)},insertStaticContent(e,t,n,r,i,a){let o=n?n.previousSibling:t.lastChild;if(i&&(i===a||i.nextSibling))for(;t.insertBefore(i.cloneNode(!0),n),!(i===a||!(i=i.nextSibling)););else{VH.innerHTML=LH(r===`svg`?`<svg>${e}</svg>`:r===`mathml`?`<math>${e}</math>`:e);let i=VH.content;if(r===`svg`||r===`mathml`){let e=i.firstChild;for(;e.firstChild;)i.appendChild(e.firstChild);i.removeChild(e)}t.insertBefore(i,n)}return[o?o.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},UH=`transition`,WH=`animation`,GH=Symbol(`_vtc`),KH={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},qH=kI({},Hz,KH),JH=(e=>(e.displayName=`Transition`,e.props=qH,e))((e,{slots:t})=>NH(Kz,ZH(e),t)),YH=(e,t=[])=>{MI(e)?e.forEach(e=>e(...t)):e&&e(...t)},XH=e=>e?MI(e)?e.some(e=>e.length>1):e.length>1:!1;function ZH(e){let t={};for(let n in e)n in KH||(t[n]=e[n]);if(e.css===!1)return t;let{name:n=`v`,type:r,duration:i,enterFromClass:a=`${n}-enter-from`,enterActiveClass:o=`${n}-enter-active`,enterToClass:s=`${n}-enter-to`,appearFromClass:c=a,appearActiveClass:l=o,appearToClass:u=s,leaveFromClass:d=`${n}-leave-from`,leaveActiveClass:f=`${n}-leave-active`,leaveToClass:p=`${n}-leave-to`}=e,m=QH(i),h=m&&m[0],g=m&&m[1],{onBeforeEnter:_,onEnter:v,onEnterCancelled:y,onLeave:b,onLeaveCancelled:x,onBeforeAppear:S=_,onAppear:ee=v,onAppearCancelled:C=y}=t,te=(e,t,n,r)=>{e._enterCancelled=r,tU(e,t?u:s),tU(e,t?l:o),n&&n()},ne=(e,t)=>{e._isLeaving=!1,tU(e,d),tU(e,p),tU(e,f),t&&t()},w=e=>(t,n)=>{let i=e?ee:v,o=()=>te(t,e,n);YH(i,[t,o]),nU(()=>{tU(t,e?c:a),eU(t,e?u:s),XH(i)||iU(t,r,h,o)})};return kI(t,{onBeforeEnter(e){YH(_,[e]),eU(e,a),eU(e,o)},onBeforeAppear(e){YH(S,[e]),eU(e,c),eU(e,l)},onEnter:w(!1),onAppear:w(!0),onLeave(e,t){e._isLeaving=!0;let n=()=>ne(e,t);eU(e,d),e._enterCancelled?(eU(e,f),cU(e)):(cU(e),eU(e,f)),nU(()=>{e._isLeaving&&(tU(e,d),eU(e,p),XH(b)||iU(e,r,g,n))}),YH(b,[e,n])},onEnterCancelled(e){te(e,!1,void 0,!0),YH(y,[e])},onAppearCancelled(e){te(e,!0,void 0,!0),YH(C,[e])},onLeaveCancelled(e){ne(e),YH(x,[e])}})}function QH(e){if(e==null)return null;if(zI(e))return[$H(e.enter),$H(e.leave)];{let t=$H(e);return[t,t]}}function $H(e){return ace(e)}function eU(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.add(t)),(e[GH]||(e[GH]=new Set)).add(t)}function tU(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.remove(t));let n=e[GH];n&&(n.delete(t),n.size||(e[GH]=void 0))}function nU(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}var rU=0;function iU(e,t,n,r){let i=e._endId=++rU,a=()=>{i===e._endId&&r()};if(n!=null)return setTimeout(a,n);let{type:o,timeout:s,propCount:c}=aU(e,t);if(!o)return r();let l=o+`end`,u=0,d=()=>{e.removeEventListener(l,f),a()},f=t=>{t.target===e&&++u>=c&&d()};setTimeout(()=>{u<c&&d()},s+1),e.addEventListener(l,f)}function aU(e,t){let n=window.getComputedStyle(e),r=e=>(n[e]||``).split(`, `),i=r(`${UH}Delay`),a=r(`${UH}Duration`),o=oU(i,a),s=r(`${WH}Delay`),c=r(`${WH}Duration`),l=oU(s,c),u=null,d=0,f=0;t===UH?o>0&&(u=UH,d=o,f=a.length):t===WH?l>0&&(u=WH,d=l,f=c.length):(d=Math.max(o,l),u=d>0?o>l?UH:WH:null,f=u?u===UH?a.length:c.length:0);let p=u===UH&&/\b(?:transform|all)(?:,|$)/.test(r(`${UH}Property`).toString());return{type:u,timeout:d,propCount:f,hasTransform:p}}function oU(e,t){for(;e.length<t.length;)e=e.concat(e);return Math.max(...t.map((t,n)=>sU(t)+sU(e[n])))}function sU(e){return e===`auto`?0:Number(e.slice(0,-1).replace(`,`,`.`))*1e3}function cU(e){return(e?e.ownerDocument:document).body.offsetHeight}function lU(e,t,n){let r=e[GH];r&&(t=(t?[t,...r]:[...r]).join(` `)),t==null?e.removeAttribute(`class`):n?e.setAttribute(`class`,t):e.className=t}var uU=Symbol(`_vod`),dU=Symbol(`_vsh`),fU={name:`show`,beforeMount(e,{value:t},{transition:n}){e[uU]=e.style.display===`none`?``:e.style.display,n&&t?n.beforeEnter(e):pU(e,t)},mounted(e,{value:t},{transition:n}){n&&t&&n.enter(e)},updated(e,{value:t,oldValue:n},{transition:r}){!t!=!n&&(r?t?(r.beforeEnter(e),pU(e,!0),r.enter(e)):r.leave(e,()=>{pU(e,!1)}):pU(e,t))},beforeUnmount(e,{value:t}){pU(e,t)}};function pU(e,t){e.style.display=t?e[uU]:`none`,e[dU]=!t}var mU=Symbol(``),hU=/(?:^|;)\s*display\s*:/;function gU(e,t,n){let r=e.style,i=LI(n),a=!1;if(n&&!i){if(t)if(LI(t))for(let e of t.split(`;`)){let t=e.slice(0,e.indexOf(`:`)).trim();n[t]??vU(r,t,``)}else for(let e in t)n[e]??vU(r,e,``);for(let i in n){i===`display`&&(a=!0);let o=n[i];o==null?vU(r,i,``):SU(e,i,!LI(t)&&t?t[i]:void 0,o)||vU(r,i,o)}}else if(i){if(t!==n){let e=r[mU];e&&(n+=`;`+e),r.cssText=n,a=hU.test(n)}}else t&&e.removeAttribute(`style`);uU in e&&(e[uU]=a?r.display:``,e[dU]&&(r.display=`none`))}var _U=/\s*!important$/;function vU(e,t,n){if(MI(n))n.forEach(n=>vU(e,t,n));else if(n??=``,t.startsWith(`--`))e.setProperty(t,n);else{let r=xU(e,t);_U.test(n)?e.setProperty(JI(r),n.replace(_U,``),`important`):e[r]=n}}var yU=[`Webkit`,`Moz`,`ms`],bU={};function xU(e,t){let n=bU[t];if(n)return n;let r=qI(t);if(r!==`filter`&&r in e)return bU[t]=r;r=YI(r);for(let n=0;n<yU.length;n++){let i=yU[n]+r;if(i in e)return bU[t]=i}return t}function SU(e,t,n,r){return e.tagName===`TEXTAREA`&&(t===`width`||t===`height`)&&LI(r)&&n===r}var CU=`http://www.w3.org/1999/xlink`;function wU(e,t,n,r,i,a=dce(t)){r&&t.startsWith(`xlink:`)?n==null?e.removeAttributeNS(CU,t.slice(6,t.length)):e.setAttributeNS(CU,t,n):n==null||a&&!aL(n)?e.removeAttribute(t):e.setAttribute(t,a?``:RI(n)?String(n):n)}function TU(e,t,n,r,i){if(t===`innerHTML`||t===`textContent`){n!=null&&(e[t]=t===`innerHTML`?LH(n):n);return}let a=e.tagName;if(t===`value`&&a!==`PROGRESS`&&!a.includes(`-`)){let r=a===`OPTION`?e.getAttribute(`value`)||``:e.value,i=n==null?e.type===`checkbox`?`on`:``:String(n);(r!==i||!(`_value`in e))&&(e.value=i),n??e.removeAttribute(t),e._value=n;return}let o=!1;if(n===``||n==null){let r=typeof e[t];r===`boolean`?n=aL(n):n==null&&r===`string`?(n=``,o=!0):r===`number`&&(n=0,o=!0)}try{e[t]=n}catch{}o&&e.removeAttribute(i||t)}function EU(e,t,n,r){e.addEventListener(t,n,r)}function DU(e,t,n,r){e.removeEventListener(t,n,r)}var OU=Symbol(`_vei`);function kU(e,t,n,r,i=null){let a=e[OU]||(e[OU]={}),o=a[t];if(r&&o)o.value=r;else{let[n,s]=MU(t);r?EU(e,n,a[t]=IU(r,i),s):o&&(DU(e,n,o,s),a[t]=void 0)}}var AU=/(Once|Passive|Capture)$/,jU=/^on:?(?:Once|Passive|Capture)$/;function MU(e){let t,n;for(;(n=e.match(AU))&&!jU.test(e);)t||={},e=e.slice(0,e.length-n[1].length),t[n[1].toLowerCase()]=!0;return[e[2]===`:`?e.slice(3):JI(e.slice(2)),t]}var NU=0,PU=Promise.resolve(),FU=()=>NU||=(PU.then(()=>NU=0),Date.now());function IU(e,t){let n=e=>{if(!e._vts)e._vts=Date.now();else if(e._vts<=n.attached)return;let r=n.value;if(MI(r)){let n=e.stopImmediatePropagation;e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0};let i=r.slice(),a=[e];for(let n=0;n<i.length&&!e._stopped;n++){let e=i[n];e&&GR(e,t,5,a)}}else GR(r,t,5,[e])};return n.value=e,n.attached=FU(),n}var LU=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,RU=(e,t,n,r,i,a)=>{let o=i===`svg`;t===`class`?lU(e,r,o):t===`style`?gU(e,n,r):DI(t)?OI(t)||kU(e,t,n,r,a):(t[0]===`.`?(t=t.slice(1),!0):t[0]===`^`?(t=t.slice(1),!1):zU(e,t,r,o))?(TU(e,t,r),!e.tagName.includes(`-`)&&(t===`value`||t===`checked`||t===`selected`)&&wU(e,t,r,o,a,t!==`value`)):e._isVueCE&&(BU(e,t)||e._def.__asyncLoader&&(/[A-Z]/.test(t)||!LI(r)))?TU(e,qI(t),r,a,t):(t===`true-value`?e._trueValue=r:t===`false-value`&&(e._falseValue=r),wU(e,t,r,o))};function zU(e,t,n,r){if(r)return!!(t===`innerHTML`||t===`textContent`||t in e&&LU(t)&&II(n));if(t===`spellcheck`||t===`draggable`||t===`translate`||t===`autocorrect`||t===`sandbox`&&e.tagName===`IFRAME`||t===`form`||t===`list`&&e.tagName===`INPUT`||t===`type`&&e.tagName===`TEXTAREA`)return!1;if(t===`width`||t===`height`){let t=e.tagName;if(t===`IMG`||t===`VIDEO`||t===`CANVAS`||t===`SOURCE`)return!1}return LU(t)&&LI(n)?!1:t in e}function BU(e,t){let n=e._def.props;if(!n)return!1;let r=qI(t);return Array.isArray(n)?n.some(e=>qI(e)===r):Object.keys(n).some(e=>qI(e)===r)}var VU=e=>{let t=e.props[`onUpdate:modelValue`]||!1;return MI(t)?e=>QI(t,e):t};function HU(e){e.target.composing=!0}function UU(e){let t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event(`input`)))}var WU=Symbol(`_assign`);function GU(e,t,n){return t&&(e=e.trim()),n&&(e=eL(e)),e}var KU={created(e,{modifiers:{lazy:t,trim:n,number:r}},i){e[WU]=VU(i);let a=r||i.props&&i.props.type===`number`;EU(e,t?`change`:`input`,t=>{t.target.composing||e[WU](GU(e.value,n,a))}),(n||a)&&EU(e,`change`,()=>{e.value=GU(e.value,n,a)}),t||(EU(e,`compositionstart`,HU),EU(e,`compositionend`,UU),EU(e,`change`,UU))},mounted(e,{value:t}){e.value=t??``},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[WU]=VU(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?eL(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},qU=[`ctrl`,`shift`,`alt`,`meta`],JU={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>qU.some(n=>e[`${n}Key`]&&!t.includes(n))},YU=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=JU[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},XU={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},ZU=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=JI(n.key);if(t.some(e=>e===r||XU[e]===r))return e(n)}))},QU=kI({patchProp:RU},HH),$U;function eW(){return $U||=OV(QU)}var tW=((...e)=>{let t=eW().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=rW(e);if(!r)return;let i=t._component;!II(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,nW(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t});function nW(e){if(e instanceof SVGElement)return`svg`;if(typeof MathMLElement==`function`&&e instanceof MathMLElement)return`mathml`}function rW(e){return LI(e)?document.querySelector(e):e}function iW(e,t){return t?.aborted?!0:e?.name===`AbortError`}function aW(e,t){if(iW(e,t))return!1;let n=e;return n?n.name===`TimeoutError`||n.status===void 0||n.status===429||n.lc_error_code===`MODEL_RATE_LIMIT`||n.status>=500:!1}function oW(){let e=Error(`Aborted`);return e.name=`AbortError`,e}function sW(e,t){return new Promise((n,r)=>{if(t?.aborted){r(oW());return}let i=()=>{clearTimeout(a),r(oW())},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}async function cW(e,t={}){let n=t.maxRetries??2,r=t.baseDelayMs??500,i=0;for(;;)try{return await e()}catch(e){if(iW(e,t.signal)||i>=n||!aW(e,t.signal))throw e;let a=r*2**i+Math.floor(Math.random()*r*.5);t.onRetry?.({attempt:i+1,error:e,waitMs:a}),await sW(a,t.signal),i++}}function lW(e={}){let{fetchResponse:t,fetchStream:n,onPersist:r,onClear:i}=e,a=gR({messages:e.messages??[],loading:!1,error:null}),o=kR(null),s=kR(!0),c=null,l=kR([]),u=kR(null);function d(){}function f(e){let t=o.value;e.deltaY<0?s.value=!1:t&&(s.value=t.scrollHeight-t.scrollTop-t.clientHeight<64)}function p(){o.value&&requestAnimationFrame(()=>{let e=o.value;!e||!s.value||(e.scrollTop=e.scrollHeight)})}function m(e,t,n){a.messages.push({role:e,content:t,timestamp:Date.now(),...n&&n.length?{focuses:n}:{}}),s.value=!0,p()}async function h(e){if(s.value=!0,n){let t=gR({role:`assistant`,content:``,timestamp:Date.now(),reasoning:``,steps:[]}),r=!1;a.messages.push(t);try{await n(a.messages.slice(0,-1),e=>{switch(e.type){case`round_start`:e.round>1&&(t.content||t.reasoning)&&(r=!0);break;case`reasoning`:r&&=(t.reasoning+=`
|
|
147
|
+
`))}let r={name:e.function.name,args:n,type:`tool_call`};return t?.returnId&&(r.id=e.id),r}function GF(e){if(e.id===void 0)throw 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 KF(e,t){return{name:e.function?.name,args:e.function?.arguments,id:e.id,error:t,type:`invalid_tool_call`}}var use=class extends HF{static lc_name(){return`JsonOutputToolsParser`}returnId=!1;lc_namespace=[`langchain`,`output_parsers`,`openai_tools`];lc_serializable=!0;constructor(e){super(e),this.returnId=e?.returnId??this.returnId}_diff(){throw Error(`Not supported.`)}async parse(){throw Error(`Not implemented.`)}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,t=!0){let n=e[0].message,r;if(SS(n)&&n.tool_calls?.length?r=n.tool_calls.map(e=>{let{id:t,...n}=e;return this.returnId?{id:t,...n}:n}):n.additional_kwargs.tool_calls!==void 0&&(r=JSON.parse(JSON.stringify(n.additional_kwargs.tool_calls)).map(e=>WF(e,{returnId:this.returnId,partial:t}))),!r)return[];let i=[];for(let e of r)if(e!==void 0){let t={type:e.name,args:e.args,id:e.id};i.push(t)}return i}},dse=class extends use{static lc_name(){return`JsonOutputKeyToolsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_tools`];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;serializableSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,`zodSchema`in e&&(this.zodSchema=e.zodSchema),`serializableSchema`in e&&(this.serializableSchema=e.serializableSchema)}async _validateResult(e){if(this.serializableSchema!==void 0){let t=await this.serializableSchema[`~standard`].validate(e);if(t.issues)throw new VF(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.issues)}`,JSON.stringify(e,null,2));return t.value}if(this.zodSchema===void 0)return e;let t=await iA(this.zodSchema,e);if(t.success)return t.data;throw new VF(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let t=(await super.parsePartialResult(e)).filter(e=>e.type===this.keyName),n=t;if(t.length)return this.returnId||(n=t.map(e=>e.args)),this.returnSingle?n[0]:n}async parseResult(e){let t=(await super.parsePartialResult(e,!1)).filter(e=>e.type===this.keyName),n=t;if(t.length)return this.returnId||(n=t.map(e=>e.args)),this.returnSingle?this._validateResult(n[0]):await Promise.all(n.map(e=>this._validateResult(e)))}};function qF(e){return rA(e)?lse.fromZodSchema(e):bN(e)?cse.fromSerializableSchema(e):new UF}function fse(e,t,n){let r=n??dse;return rA(e)?new r({returnSingle:!0,keyName:t,zodSchema:e}):bN(e)?new r({returnSingle:!0,keyName:t,serializableSchema:e}):new r({returnSingle:!0,keyName:t})}function JF(e,t,n,r){if(!n){let n=e.pipe(t);return r?n.withConfig({runName:r}):n}let i=zF.assign({parsed:(e,n)=>t.invoke(e.raw,n)}),a=zF.assign({parsed:()=>null}),o=i.withFallbacks({fallbacks:[a]}),s=wP.from([{raw:e},o]);return r?s.withConfig({runName:r}):s}var pse=class{events=[];finished=!1;waiters=[];error=null;push(e){this.events.push(e);let t=this.waiters.splice(0);for(let e of t)e()}finish(){this.finished=!0;let e=this.waiters.splice(0);for(let t of e)t()}setError(e){this.error=e,this.finished=!0;let t=this.waiters.splice(0);for(let e of t)e()}async*iterate(){if(this.finished){if(this.error)throw this.error;yield*this.events;return}let e=0;for(;;){for(;e<this.events.length;)yield this.events[e],e++;if(this.finished){if(this.error)throw this.error;return}await new Promise(t=>{if(e<this.events.length||this.finished){t();return}this.waiters.push(t)})}}};function mse(e,t){switch(t.type){case`text-delta`:return e.type===`text`?{...e,text:(e.text??``)+t.text}:e;case`reasoning-delta`:return e.type===`thinking`?{...e,thinking:(e.thinking??``)+t.reasoning}:e.type===`reasoning`?{...e,reasoning:(e.reasoning??``)+t.reasoning}:e;case`data-delta`:return{...e,data:(e.data??``)+t.data};case`block-delta`:return{...e,...t.fields};default:throw Error(`Unknown delta type: ${JSON.stringify(t)}`)}}function YF(e){if(e.event!==`content-block-delta`)return;if(`delta`in e&&e.delta)return e.delta;let t=e.content;if(typeof t!=`object`||!t)return;let n=t;if(n.type===`text`&&typeof n.text==`string`)return{type:`text-delta`,text:n.text};if(n.type===`reasoning`&&typeof n.reasoning==`string`)return{type:`reasoning-delta`,reasoning:n.reasoning};if(n.type===`thinking`&&typeof n.thinking==`string`)return{type:`reasoning-delta`,reasoning:n.thinking};if(typeof n.data==`string`)return{type:`data-delta`,data:n.data,encoding:`base64`};if(typeof n.type==`string`)return{type:`block-delta`,fields:{...n,type:n.type}}}function XF(e){if(typeof e!=`object`||!e)return;let t=e;if(t.type===`reasoning`&&typeof t.reasoning==`string`)return t.reasoning;if(t.type===`thinking`&&typeof t.thinking==`string`)return t.thinking}function ZF(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`reasoning`||t===`thinking`}function QF(e){if(e)return{...e,input_tokens:e.input_tokens??0,output_tokens:e.output_tokens??0,total_tokens:e.total_tokens??0}}function hse(e){if(typeof e==`object`&&e&&!Array.isArray(e))return e;if(typeof e!=`string`||e.length===0)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch{return{}}}function gse(e){let t=e;if(e.type===`tool_call`||e.type!==`tool_call_chunk`&&e.type!==`tool_use`&&e.type!==`input_json_delta`)return e;let n=typeof t.name==`string`?t.name:void 0;if(n==null)return e;let r=t.args??t.input;return{...t,type:`tool_call`,name:n,args:hse(r)}}var _se=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t=``;for await(let n of e.iterate()){let e=YF(n);e?.type===`text-delta`&&(t+=e.text,yield t)}}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let t of e.iterate()){let e=YF(t);e?.type===`text-delta`&&(yield e.text)}}return t()}then(e,t){return(async()=>{let e=``;for await(let t of this)e+=t;return e})().then(e,t)}},vse=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t=[];for await(let n of e.iterate())n.event===`content-block-finish`&&n.content.type===`tool_call`&&(t.push(n.content),yield[...t])}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let t of e.iterate())t.event===`content-block-finish`&&t.content.type===`tool_call`&&(yield t.content)}return t()}then(e,t){return(async()=>{let e=[];for await(let t of this)e.push(t);return e})().then(e,t)}},yse=class{_buffer;constructor(e){this._buffer=e}get full(){let e=this._buffer;return{async*[Symbol.asyncIterator](){let t=``,n=!1;for await(let r of e.iterate())if(r.event===`content-block-start`){if(!ZF(r.content)){if(n)return;continue}n=!0;let e=XF(r.content);if(e==null||e.length===0)continue;t+=e,yield t}else if(r.event===`content-block-delta`){let e=YF(r);if(e?.type!==`reasoning-delta`)continue;n=!0;let i=e.reasoning;if(i==null||i.length===0)continue;t+=i,yield t}else if(r.event===`content-block-finish`&&ZF(r.content))return;else if(r.event===`message-finish`)return}}}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){let t=!1;for await(let n of e.iterate())if(n.event===`content-block-start`){if(!ZF(n.content)){if(t)return;continue}t=!0;let e=XF(n.content);e!=null&&e.length>0&&(yield e)}else if(n.event===`content-block-delta`){let e=YF(n);if(e?.type!==`reasoning-delta`)continue;t=!0;let r=e.reasoning;r!=null&&r.length>0&&(yield r)}else if(n.event===`content-block-finish`&&ZF(n.content))return;else if(n.event===`message-finish`)return}return t()}then(e,t){return(async()=>{let e=``;for await(let t of this)e+=t;return e})().then(e,t)}},bse=class{_buffer;constructor(e){this._buffer=e}[Symbol.asyncIterator](){let e=this._buffer;async function*t(){for await(let t of e.iterate())if(t.event===`usage`){let e=QF(t.usage);e&&(yield e)}else if(t.event===`message-start`&&t.usage){let e=QF(t.usage);e&&(yield e)}else if(t.event===`message-finish`&&t.usage){let e=QF(t.usage);e&&(yield e)}}return t()}then(e,t){return(async()=>{let e;for await(let t of this)e=t;return e})().then(e,t)}},$F=class{_buffer;constructor(e){this._buffer=new pse,this._consume(e)}async _consume(e){try{for await(let t of e)this._buffer.push(t);this._buffer.finish()}catch(e){this._buffer.setError(e instanceof Error?e:Error(String(e)))}}[Symbol.asyncIterator](){return this._buffer.iterate()}get text(){return new _se(this._buffer)}get toolCalls(){return new vse(this._buffer)}get reasoning(){return new yse(this._buffer)}get usage(){return new bse(this._buffer)}get output(){return this._assembleMessage()}then(e,t){return this._assembleMessage().then(e,t)}async _assembleMessage(){let e=[],t,n,r={},i;for await(let a of this._buffer.iterate())switch(a.event){case`message-start`:t=a.id??t,a.usage&&(n=QF(a.usage));break;case`content-block-start`:e[a.index]=a.content;break;case`content-block-delta`:{let t=e[a.index],n=YF(a);t&&n&&(e[a.index]=mse(t,n));break}case`content-block-finish`:e[a.index]=a.content;break;case`usage`:n=QF(a.usage);break;case`message-finish`:i=a.reason,a.usage&&(n=QF(a.usage)),a.responseMetadata&&(r={...r,...a.responseMetadata});break;default:break}let a=e.filter(e=>e!=null).map(gse);return new xS({id:t,content:a,usage_metadata:n,response_metadata:{...r,...i?{finish_reason:i}:{},output_version:`v1`}})}},xse={wav:`audio/wav`,mp3:`audio/mpeg`,flac:`audio/flac`,opus:`audio/opus`,aac:`audio/aac`,pcm16:`audio/pcm`},Sse={png:`image/png`,jpeg:`image/jpeg`,jpg:`image/jpeg`,webp:`image/webp`,gif:`image/gif`};function eI(e){let t=0;for(let n of e.keys())n>=t&&(t=n+1);return t}function tI(e){let t=e.additional_kwargs;return typeof t==`object`&&t?t:{}}function Cse(e){let t=tI(e).tool_outputs;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e;if(t.type!==`image_generation_call`)continue;let r=typeof t.result==`string`?t.result:void 0,i=typeof t.url==`string`?t.url:void 0;if(r==null&&i==null)continue;let a=typeof t.output_format==`string`?t.output_format.toLowerCase():void 0,o=(a==null?void 0:Sse[a])??`image/png`;n.push({type:`image`,...typeof t.id==`string`?{id:t.id}:{},...i==null?{}:{url:i},...r==null?{}:{data:r},mimeType:o})}return n}function wse(e){let t=tI(e).audio;if(typeof t!=`object`||!t)return;let n=t,r=typeof n.data==`string`?n.data:void 0,i=typeof n.url==`string`?n.url:void 0,a=typeof n.transcript==`string`?n.transcript:void 0;if(r==null&&i==null&&a==null)return;let o=typeof n.mime_type==`string`?n.mime_type:typeof n.mimeType==`string`?n.mimeType:void 0,s=typeof n.format==`string`?n.format.toLowerCase():void 0,c=o??(s==null?void 0:xse[s])??(r==null?`audio/pcm`:`audio/wav`);return{...typeof n.id==`string`?{id:n.id}:{},...r==null?{}:{data:r},...i==null?{}:{url:i},...a==null?{}:{transcript:a},mimeType:c}}async function*Tse(e,t){let n=new Map,r=!1,i,a,o=new Set;for await(let s of e){t?.signal?.throwIfAborted();let e=s.message,c=!1;if(!r){r=!0;let t={event:`message-start`,id:e.id??void 0};wS.isInstance(e)&&e.usage_metadata&&(t.usage=e.usage_metadata,i={...e.usage_metadata},c=!0),yield t}let l=e.content;if(typeof l==`string`){if(l!==``){if(!n.has(0)){let e={type:`text`,text:``};n.set(0,{type:`text`,accumulated:e}),yield{event:`content-block-start`,index:0,content:e}}let e=n.get(0);e.accumulated={...e.accumulated,text:(e.accumulated.text??``)+l},yield{event:`content-block-delta`,index:0,delta:{type:`text-delta`,text:l}}}}else if(Array.isArray(l))for(let e of l){let t=typeof e.index==`number`?e.index:n.size;if(!n.has(t))n.set(t,{type:e.type,accumulated:{...e}}),yield{event:`content-block-start`,index:t,content:{...e}};else{let r=n.get(t),i=Dse(e);r.accumulated=Ese(r.accumulated,i),yield{event:`content-block-delta`,index:t,delta:i}}}if(wS.isInstance(e)&&e.tool_call_chunks&&e.tool_call_chunks.length>0)for(let t of e.tool_call_chunks){let e=typeof t.index==`number`?t.index:n.size;if(!n.has(e)){let r={type:`tool_call_chunk`,id:t.id,name:t.name,args:``,index:e};n.set(e,{type:`tool_call_chunk`,accumulated:r}),yield{event:`content-block-start`,index:e,content:r}}let r=n.get(e).accumulated;t.id!=null&&(r.id=t.id),t.name!=null&&(r.name=t.name),r.args=(r.args??``)+(t.args??``),yield{event:`content-block-delta`,index:e,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...`id`in r&&r.id!=null?{id:r.id}:{},...`name`in r&&r.name!=null?{name:r.name}:{},args:r.args}}}}let u=wse(e);if(u!=null){if(a==null){let e=eI(n);a={index:e,id:u.id,mimeType:u.mimeType,transcript:``};let t={type:`audio`,...u.id==null?{}:{id:u.id},...u.url==null?{}:{url:u.url},data:``,mimeType:u.mimeType};n.set(e,{type:`audio`,accumulated:t}),yield{event:`content-block-start`,index:e,content:t}}let e=n.get(a.index);if(e!=null){let t=e.accumulated;u.id!=null&&a.id==null&&(a.id=u.id,t.id=u.id),u.transcript!=null&&(a.transcript+=u.transcript,t.transcript=a.transcript,yield{event:`content-block-delta`,index:a.index,delta:{type:`block-delta`,fields:{type:`audio`,transcript:a.transcript}}}),u.data!=null&&u.data.length>0&&(t.data=(t.data??``)+u.data,yield{event:`content-block-delta`,index:a.index,delta:{type:`data-delta`,data:u.data,encoding:`base64`}})}}for(let t of Cse(e)){let e=t,r=e.id??e.url??(e.data==null?void 0:`${e.data.length}:${e.data.slice(0,32)}`);if(r!=null&&o.has(r))continue;r!=null&&o.add(r);let i=eI(n);n.set(i,{type:`image`,accumulated:t}),yield{event:`content-block-start`,index:i,content:t}}if(!c&&wS.isInstance(e)&&e.usage_metadata){let t=e.usage_metadata;i=i?{input_tokens:i.input_tokens+t.input_tokens,output_tokens:i.output_tokens+t.output_tokens,total_tokens:i.total_tokens+t.total_tokens}:{...t},yield{event:`usage`,usage:{...i}}}}for(let[e,t]of n)yield{event:`content-block-finish`,index:e,content:nI(t.accumulated)};yield{event:`message-finish`,reason:`stop`,...i?{usage:i}:{}}}function Ese(e,t){switch(t.type){case`text-delta`:return e.type===`text`?{...e,text:(e.text??``)+t.text}:e;case`reasoning-delta`:return e.type===`thinking`?{...e,thinking:(e.thinking??``)+t.reasoning}:e.type===`reasoning`?{...e,reasoning:(e.reasoning??``)+t.reasoning}:e;case`data-delta`:return{...e,data:(e.data??``)+t.data};case`block-delta`:return{...e,...t.fields};default:throw Error(`Unknown delta type: ${JSON.stringify(t)}`)}}function Dse(e){if(e.type===`text`)return{type:`text-delta`,text:e.text};if(e.type===`reasoning`)return{type:`reasoning-delta`,reasoning:e.reasoning};if(e.type===`thinking`&&typeof e.thinking==`string`)return{type:`reasoning-delta`,reasoning:e.thinking};if(typeof e.data==`string`)return{type:`data-delta`,data:e.data,encoding:`base64`};if(typeof e.type==`string`)return{type:`block-delta`,fields:{...e}};throw Error(`Unsupported content block delta: ${JSON.stringify(e)}`)}function nI(e){if(e.type===`tool_call_chunk`){let t=e,n;try{n=JSON.parse(t.args??`{}`)}catch{return{type:`invalid_tool_call`,id:t.id,name:t.name,args:t.args,error:`Failed to parse tool call arguments as JSON`}}return{type:`tool_call`,id:t.id,name:t.name,args:n}}return e}function rI(e){let t=[];for(let n of e){let e=n;if(Array.isArray(n.content))for(let t=0;t<n.content.length;t++){let r=n.content[t];(Lb(r)||Rb(r))&&e===n&&(e=new n.constructor({...e,content:[...n.content.slice(0,t),Bb(r),...n.content.slice(t+1)]}))}t.push(e)}return t}var Ose=class e extends ise{lc_namespace=[`langchain`,`chat_models`,this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,`outputVersion`]}constructor(e){super(e),this.outputVersion=ase(()=>{let t=e.outputVersion??HS(`LC_OUTPUT_VERSION`);return t&&[`v0`,`v1`].includes(t)?t:`v0`})}_separateRunnableConfigFromCallOptionsCompat(e){let[t,n]=super._separateRunnableConfigFromCallOptions(e);return n.signal=t.signal,[t,n]}async invoke(t,n){let r=e._convertInputToPromptValue(t);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(e,t,n){throw Error(`Not implemented.`)}async*_streamChatModelEvents(e,t,n){yield*Tse(this._streamResponseChunks(e,t,n),{signal:t.signal})}streamEvents(t,n,r){if(n?.version===`v1`||n?.version===`v2`)return super.streamEvents(t,n,r);let i=e._convertInputToPromptValue(t).toChatMessages(),[,a]=this._separateRunnableConfigFromCallOptionsCompat(n);return new $F(this._streamChatModelEvents(i,a))}streamV2(e,t){return this.streamEvents(e,t)}async*_streamIterator(t,n){if(this._streamResponseChunks===e.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(t,n);else{let r=e._convertInputToPromptValue(t).toChatMessages(),[i,a]=this._separateRunnableConfigFromCallOptionsCompat(n),o={...i.metadata,...this.getLsParamsWithDefaults(a)},s=this._getInvocationParamsForTracing(a),c=await qO.configure(i.callbacks,this.callbacks,i.tags,this.tags,o,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(s)}),l={options:this._getCallOptionsForTracing(a,s),invocation_params:s,batch_size:1},u=a.outputVersion??this.outputVersion,d=await c?.handleChatModelStart(this.toJSON(),[rI(r)],i.runId,void 0,l,void 0,void 0,i.runName),f,p;try{for await(let e of this._streamResponseChunks(r,a,d?.[0])){if(a.signal?.throwIfAborted(),e.message.id==null){let t=d?.at(0)?.runId;t!=null&&e.message._updateId(`run-${t}`)}e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},u===`v1`?yield RF(e.message):yield e.message,f=f?f.concat(e):e,CS(e.message)&&e.message.usage_metadata!==void 0&&(p={tokenUsage:{promptTokens:e.message.usage_metadata.input_tokens,completionTokens:e.message.usage_metadata.output_tokens,totalTokens:e.message.usage_metadata.total_tokens}})}a.signal?.throwIfAborted()}catch(e){throw await Promise.all((d??[]).map(t=>t?.handleLLMError(e))),e}await Promise.all((d??[]).map(e=>e?.handleLLMEnd({generations:[[f]],llmOutput:p})))}}getLsParams(e){let t=this.getName().startsWith(`Chat`)?this.getName().replace(`Chat`,``):this.getName();return{ls_model_type:`chat`,ls_stop:e.stop,ls_provider:t}}getLsParamsWithDefaults(e){return{...this.getLsParams(e),ls_integration:`langchain_chat_model`}}async _generateUncached(t,n,r,i){let a=t.map(e=>e.map(vS)),o;if(i!==void 0&&i.length===a.length)o=i;else{let e={...r.metadata,...this.getLsParamsWithDefaults(n)},t=this._getInvocationParamsForTracing(n),i=await qO.configure(r.callbacks,this.callbacks,r.tags,this.tags,e,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(t)}),s={options:this._getCallOptionsForTracing(n,t),invocation_params:t,batch_size:1};o=await i?.handleChatModelStart(this.toJSON(),a.map(rI),r.runId,void 0,s,void 0,void 0,r.runName)}let s=n.outputVersion??this.outputVersion,c=[],l=[],u=!!o?.[0].handlers.find(zne),d=!!o?.[0].handlers.find(Rne);if(u&&!this.disableStreaming&&a.length===1&&(this._streamChatModelEvents!==e.prototype._streamChatModelEvents||this._streamResponseChunks!==e.prototype._streamResponseChunks))try{let e=!1,t=o?.[0],r=this._streamChatModelEvents(a[0],n),i=await new $F({async*[Symbol.asyncIterator](){for await(let i of r){n.signal?.throwIfAborted(),e=!0;let r=i.event===`message-start`&&i.id==null&&t?.runId!=null?{...i,id:`run-${t.runId}`}:i;await t?.handleChatModelStreamEvent(r),yield r}}});if(n.signal?.throwIfAborted(),!e)throw Error(`Received empty response from chat model call.`);if(i.id==null){let e=o?.at(0)?.runId;e!=null&&i._updateId(`run-${e}`)}let s={text:i.text,message:i};c.push([s]);let l=i.usage_metadata===void 0?void 0:{tokenUsage:{promptTokens:i.usage_metadata.input_tokens,completionTokens:i.usage_metadata.output_tokens,totalTokens:i.usage_metadata.total_tokens}};await o?.[0].handleLLMEnd({generations:c,llmOutput:l})}catch(e){throw await o?.[0].handleLLMError(e),e}else if(d&&!this.disableStreaming&&a.length===1&&this._streamResponseChunks!==e.prototype._streamResponseChunks)try{let e=await this._streamResponseChunks(a[0],n,o?.[0]),t,r;for await(let i of e){if(n.signal?.aborted){let e=t?.message;throw new Mb(`Model invocation was aborted.`,e)}if(i.message.id==null){let e=o?.at(0)?.runId;e!=null&&i.message._updateId(`run-${e}`)}t=t===void 0?i:ok(t,i),CS(i.message)&&i.message.usage_metadata!==void 0&&(r={tokenUsage:{promptTokens:i.message.usage_metadata.input_tokens,completionTokens:i.message.usage_metadata.output_tokens,totalTokens:i.message.usage_metadata.total_tokens}})}if(n.signal?.aborted){let e=t?.message;throw new Mb(`Model invocation was aborted.`,e)}if(t===void 0)throw Error(`Received empty response from chat model call.`);s===`v1`&&(t.message=RF(t.message)),c.push([t]),await o?.[0].handleLLMEnd({generations:c,llmOutput:r})}catch(e){throw await o?.[0].handleLLMError(e),e}else{let e=await Promise.allSettled(a.map(async(e,t)=>{let r=await this._generate(e,{...n,promptIndex:t},o?.[t]);if(s===`v1`)for(let e of r.generations)e.message=RF(e.message);return r}));await Promise.all(e.map(async(e,t)=>{if(e.status===`fulfilled`){let n=e.value;for(let e of n.generations){if(e.message.id==null){let t=o?.at(0)?.runId;t!=null&&e.message._updateId(`run-${t}`)}e.message.response_metadata={...e.generationInfo,...e.message.response_metadata}}return n.generations.length===1&&(n.generations[0].message.response_metadata={...n.llmOutput,...n.generations[0].message.response_metadata}),c[t]=n.generations,l[t]=n.llmOutput,o?.[t]?.handleLLMEnd({generations:[n.generations],llmOutput:n.llmOutput})}else return await o?.[t]?.handleLLMError(e.reason),Promise.reject(e.reason)}))}let f={generations:c,llmOutput:l.length?this._combineLLMOutput?.(...l):void 0};return Object.defineProperty(f,kk,{value:o?{runIds:o?.map(e=>e.runId)}:void 0,configurable:!0}),f}async _generateCached({messages:t,cache:n,llmStringKey:r,parsedOptions:i,handledOptions:a}){let o=t.map(e=>e.map(vS)),s={...a.metadata,...this.getLsParamsWithDefaults(i)},c=this._getInvocationParamsForTracing(i),l=await qO.configure(a.callbacks,this.callbacks,a.tags,this.tags,s,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(c)}),u={options:this._getCallOptionsForTracing(i,c),invocation_params:c,batch_size:1},d=await l?.handleChatModelStart(this.toJSON(),o.map(rI),a.runId,void 0,u,void 0,void 0,a.runName),f=[],p=(await Promise.allSettled(o.map(async(t,i)=>{let a=e._convertInputToPromptValue(t).toString(),o=await n.lookup(a,r);return o??f.push(i),o}))).map((e,t)=>({result:e,runManager:d?.[t]})).filter(({result:e})=>e.status===`fulfilled`&&e.value!=null||e.status===`rejected`),m=i.outputVersion??this.outputVersion,h=[];await Promise.all(p.map(async({result:e,runManager:t},n)=>{if(e.status===`fulfilled`){let r=e.value;return h[n]=r.map(e=>(`message`in e&&Gx(e.message)&&SS(e.message)&&(e.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},m===`v1`&&(e.message=RF(e.message))),e.generationInfo={...e.generationInfo,tokenUsage:{}},e)),r.length&&await t?.handleLLMNewToken(r[0].text),t?.handleLLMEnd({generations:[r]},void 0,void 0,void 0,{cached:!0})}else return await t?.handleLLMError(e.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(e.reason)}));let g={generations:h,missingPromptIndices:f,startedRunManagers:d};return Object.defineProperty(g,kk,{value:d?{runIds:d?.map(e=>e.runId)}:void 0,configurable:!0}),g}async generate(t,n,r){let i;i=Array.isArray(n)?{stop:n}:n;let a=t.map(e=>e.map(vS)),[o,s]=this._separateRunnableConfigFromCallOptionsCompat(i);if(o.callbacks=o.callbacks??r,!this.cache)return this._generateUncached(a,s,o);let{cache:c}=this,l=this._getSerializedCacheKeyParametersForCall(s),{generations:u,missingPromptIndices:d,startedRunManagers:f}=await this._generateCached({messages:a,cache:c,llmStringKey:l,parsedOptions:s,handledOptions:o}),p={};if(d.length>0){let t=await this._generateUncached(d.map(e=>a[e]),s,o,f===void 0?void 0:d.map(e=>f?.[e]));await Promise.all(t.generations.map(async(t,n)=>{let r=d[n];u[r]=t;let i=e._convertInputToPromptValue(a[r]).toString();return c.update(i,l,t)})),p=t.llmOutput??{}}return{generations:u,llmOutput:p}}_getInvocationParamsForTracing(e){return this.invocationParams(e)}_getCallOptionsForTracing(e,t){return e}invocationParams(e){return{}}_modelType(){return`base_chat_model`}async generatePrompt(e,t,n){let r=e.map(e=>e.toChatMessages());return this.generate(r,t,n)}withStructuredOutput(e,t){if(typeof this.bindTools!=`function`)throw Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`);if(t?.strict)throw Error(`"strict" mode is not supported for this model by default.`);let n=e,r=t?.name,i=oA(n)??`A function available to call.`,a=t?.method,o=t?.includeRaw;if(a===`jsonMode`)throw Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`);let s=r??`extract`;!rA(n)&&!bN(n)&&`name`in n&&(s=n.name);let c=rA(n)||bN(n)?aP(n):n,l=[{type:`function`,function:{name:s,description:i,parameters:c}}];return JF(this.bindTools(l),OP.from(e=>{if(!wS.isInstance(e))throw Error(`Input is not an AIMessageChunk.`);if(!e.tool_calls||e.tool_calls.length===0)throw Error(`No tool calls found in the response.`);let t=e.tool_calls.find(e=>e.name===s);if(!t)throw Error(`No tool call found with name ${s}.`);return t.args}),o,o?`StructuredOutputRunnable`:`StructuredOutput`)}};function iI(e,t){return typeof e==`string`?{model:e,...t??{}}:e??t}var aI=class extends Ose{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model=`gpt-3.5-turbo`;modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return`openai`}static lc_name(){return`ChatOpenAI`}get callKeys(){return[...super.callKeys,`options`,`function_call`,`functions`,`tools`,`tool_choice`,`promptIndex`,`response_format`,`seed`,`reasoning`,`reasoning_effort`,`service_tier`]}lc_serializable=!0;get lc_secrets(){return{apiKey:`OPENAI_API_KEY`,organization:`OPENAI_ORGANIZATION`}}get lc_aliases(){return{apiKey:`openai_api_key`,modelName:`model`}}get lc_serializable_keys(){return`configuration.logprobs.topLogprobs.prefixMessages.supportsStrictToolCalling.modalities.audio.temperature.maxTokens.topP.frequencyPenalty.presencePenalty.n.logitBias.user.streaming.streamUsage.model.modelName.modelKwargs.stop.stopSequences.timeout.apiKey.cache.maxConcurrency.maxRetries.verbose.callbacks.tags.metadata.disableStreaming.zdrEnabled.reasoning.promptCacheKey.promptCacheRetention.verbosity`.split(`.`)}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`openai`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{});let t=typeof e?.configuration?.apiKey==`string`||typeof e?.configuration?.apiKey==`function`?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??t??HS(`OPENAI_API_KEY`),this.organization=e?.configuration?.organization??HS(`OPENAI_ORGANIZATION`),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=e?.promptCacheRetention??this.promptCacheRetention,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.disableStreaming&&(this.streaming=!1),e?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1,this._addVersion(`@langchain/openai`,`1.5.5`)}_getReasoningParams(e){if(!RP(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),e?.reasoningEffort!==void 0&&t?.effort===void 0&&(t={...t,effort:e.reasoningEffort}),t}_getResponseFormat(e){return e&&e.type===`json_schema`&&e.json_schema.schema&&rA(e.json_schema.schema)?Poe(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){let e=GP({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,t.defaultHeaders=YP(t.defaultHeaders),this.client=new Sb(t)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return iF(e)?Iae(e.metadata.customTool):IF(e)?t?.strict===void 0?e:{...e,function:{...e.function,strict:t.strict}}:Eae(e,t)}bindTools(e,t){let n;return t?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=t.strict,this.withConfig({tools:e.map(e=>{if(rF(e)||iF(e))return e;if(kae(e))return e.extras.providerToolDefinition;let t=this._convertChatOpenAIToolToCompletionsTool(e,{strict:n});return $P(e)&&e.extras?.defer_loading===!0?{...t,defer_loading:!0}:t}),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((e,t)=>(t&&t.tokenUsage&&(e.tokenUsage.completionTokens+=t.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=t.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=t.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,n=0,r=0;this.model===`gpt-3.5-turbo-0301`?(n=4,r=-1):(n=3,r=1);let i=await Promise.all(e.map(async e=>{let[i,a]=await Promise.all([this.getNumTokens(e.content),this.getNumTokens(UP(e))]),o=e.name===void 0?0:r+await this.getNumTokens(e.name),s=i+n+a+o,c=e;if(c._getType()===`function`&&(s-=2),c.additional_kwargs?.function_call&&(s+=3),c?.additional_kwargs.function_call?.name&&(s+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{s+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(e){console.error(`Error parsing function arguments`,e,JSON.stringify(c.additional_kwargs.function_call)),s+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return t+=s,s}));return t+=3,{totalCount:t,countPerMessage:i}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,t)=>e+t,0)}async _getEstimatedTokenCountFromPrompt(e,t,n){let r=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&n!==`auto`){let e=Oae(t);r+=await this.getNumTokens(e),r+=9}return t&&e.find(e=>e._getType()===`system`)&&(r-=4),n===`none`?r+=1:typeof n==`object`&&(r+=await this.getNumTokens(n.name)+4),r}async moderateContent(e,t){let n=this._getClientOptions(t?.options),r={input:e,model:t?.model??`omni-moderation-latest`};return this.caller.call(async()=>{try{return await this.client.moderations.create(r,n)}catch(e){throw Fb(e)}})}get profile(){return Ioe[this.model]??{}}_getStructuredOutputMethod(e){let t={...e};if(!this.model.startsWith(`gpt-3`)&&!this.model.startsWith(`gpt-4-`)&&this.model!==`gpt-4`){if(t?.method===void 0)return`jsonSchema`}else t.method===`jsonSchema`&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let n,r,{schema:i,name:a,includeRaw:o}={...t,schema:e};if(t?.strict!==void 0&&t.method===`jsonMode`)throw Error("Argument `strict` is only supported for `method` = 'function_calling'");let s=Moe(this.model,t?.method);if(s===`jsonMode`){r=qF(i);let e=aP(i);n=this.withConfig({outputVersion:`v0`,response_format:{type:`json_object`},ls_structured_output_format:{kwargs:{method:`json_mode`},schema:{title:a??`extract`,...e}}})}else if(s===`jsonSchema`){let e=aP(i),o={name:a??`extract`,description:oA(e),schema:rA(i)?i:e,strict:t?.strict};if(n=this.withConfig({outputVersion:`v0`,response_format:{type:`json_schema`,json_schema:o},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:{title:o.name,description:o.description,...e}}}),rA(i)||bN(i)){let e=qF(i);r=OP.from(async t=>`parsed`in t.additional_kwargs?t.additional_kwargs.parsed:e.invoke(t.content))}else r=new UF}else{let e=a??`extract`,o=aP(i),s;rA(i)||bN(i)?s={name:e,description:o.description,parameters:o}:typeof i.name==`string`&&typeof i.parameters==`object`&&i.parameters!=null?(s=i,e=i.name):(e=i.title??e,s={name:e,description:i.description??``,parameters:i}),n=this.withConfig({outputVersion:`v0`,tools:[{type:`function`,function:s}],tool_choice:{type:`function`,function:{name:e}},ls_structured_output_format:{kwargs:{method:`function_calling`},schema:{title:e,...o}},...t?.strict===void 0?{}:{strict:t.strict}}),r=fse(i,e)}return JF(n,r,o)}},oI={providerName:`ChatOpenAI`,fromStandardTextBlock(e){return{type:`text`,text:e.text}},fromStandardImageBlock(e){if(e.source_type===`url`)return{type:`image_url`,image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if(e.source_type===`base64`)return{type:`image_url`,image_url:{url:`data:${e.mime_type??``};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};throw Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if(e.source_type===`url`){let t=Hb({dataUrl:e.url});if(!t)throw Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);let n=t.mime_type||e.mime_type||``,r;try{r=Vb(n)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!==`audio`||r.subtype!==`wav`&&r.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:r.subtype,data:t.data}}}if(e.source_type===`base64`){let t;try{t=Vb(e.mime_type??``)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(t.type!==`audio`||t.subtype!==`wav`&&t.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:t.subtype,data:e.data}}}throw Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if(e.source_type===`url`){let t=Hb({dataUrl:e.url}),n=HP(e);if(!t)throw Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:`file`,file:{file_data:e.url,filename:n}}}if(e.source_type===`base64`){let t=HP(e);return{type:`file`,file:{file_data:`data:${e.mime_type??``};base64,${e.data}`,filename:t}}}if(e.source_type===`id`)return{type:`file`,file:{file_id:e.id}};throw Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}},kse=({message:e,rawResponse:t,includeRawResponse:n})=>{let r=e.tool_calls,i=e.reasoning_content;switch(e.role){case`assistant`:{let a=[],o=[];for(let e of r??[])try{a.push(WF(e,{returnId:!0}))}catch(t){o.push(KF(e,t.message))}let s={function_call:e.function_call,tool_calls:r};n!==void 0&&(s.__raw_response=t),i!==void 0&&(s.reasoning_content=i);let c={model_provider:`openai`,model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return e.audio&&(s.audio=e.audio),new xS({content:Foe(e.content||``,t.choices?.[0]?.message),tool_calls:a,invalid_tool_calls:o,additional_kwargs:s,response_metadata:c,id:t.id})}default:return new uS(e.content||``,e.role??`unknown`)}},Ase=({delta:e,rawResponse:t,includeRawResponse:n,defaultRole:r})=>{let i=e.role??r,a=e.content??``,o;o=e.function_call?{function_call:e.function_call}:e.tool_calls?{tool_calls:e.tool_calls}:{},n&&(o.__raw_response=t),e.reasoning_content!==void 0&&(o.reasoning_content=e.reasoning_content),e.audio&&(o.audio={...e.audio,index:t.choices[0].index});let s={model_provider:`openai`,usage:{...t.usage}};if(i===`user`)return new mS({content:a,response_metadata:s});if(i===`assistant`){let n=[];if(Array.isArray(e.tool_calls))for(let t of e.tool_calls)n.push({name:t.function?.name,args:t.function?.arguments,id:t.id,index:t.index,type:`tool_call_chunk`});return new wS({content:a,tool_call_chunks:n,additional_kwargs:o,id:t.id,response_metadata:s})}else if(i===`system`)return new gS({content:a,response_metadata:s});else if(i===`developer`)return new gS({content:a,response_metadata:s,additional_kwargs:{__openai_role__:`developer`}});else if(i===`function`)return new fS({content:a,additional_kwargs:o,name:e.name,response_metadata:s});else if(i===`tool`)return new Yte({content:a,additional_kwargs:o,tool_call_id:e.tool_call_id,response_metadata:s});else return new dS({content:a,role:i,response_metadata:s})},jse=e=>{if(e.type===`image`){if(e.url)return{type:`image_url`,image_url:{url:e.url}};if(e.data)return{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}}if(e.type===`audio`&&e.data){let t=fne(()=>{let[,t]=e.mimeType.split(`/`);return t===`wav`||t===`mp3`?t:`wav`});return{type:`input_audio`,input_audio:{data:e.data.toString(),format:t}}}if(e.type===`file`){if(e.data){let t=HP(e);return{type:`file`,file:{file_data:`data:${e.mimeType};base64,${e.data}`,filename:t}}}if(e.fileId)return{type:`file`,file:{file_id:e.fileId}}}},Mse=({message:e,model:t})=>{let n=UP(e);if(n===`system`&&RP(t)&&(n=`developer`),n===`developer`)return{role:`developer`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`system`)return{role:`system`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`assistant`){let t={role:`assistant`,content:e.contentBlocks.filter(e=>e.type===`text`)};return xS.isInstance(e)&&e.tool_calls?.length?t.tool_calls=e.tool_calls.map(GF):e.additional_kwargs.tool_calls!=null&&(t.tool_calls=e.additional_kwargs.tool_calls),t}else if(n===`tool`&&Jx.isInstance(e))return{role:`tool`,tool_call_id:e.tool_call_id,content:e.contentBlocks.filter(e=>e.type===`text`)};else if(n===`function`)return{role:`function`,name:e.name??``,content:e.contentBlocks.filter(e=>e.type===`text`).join(``)};function*r(e){for(let t of e){t.type===`text`&&(yield{type:`text`,text:t.text});let e=jse(t);e&&(yield e)}}return{role:`user`,content:Array.from(r(e.contentBlocks))}},sI=({messages:e,model:t})=>e.flatMap(e=>{if(`output_version`in e.response_metadata&&e.response_metadata?.output_version===`v1`)return Mse({message:e});let n=UP(e);n===`system`&&RP(t)&&(n=`developer`);let r=typeof e.content==`string`?e.content:e.content.flatMap(e=>Ib(e)?Ub(e,oI):typeof e==`object`&&e&&`type`in e&&(e.type===`tool_use`||e.type===`tool_call`||e.type===`reasoning`||e.type===`reasoning_content`||e.type===`thinking`)?[]:e),i={role:n,content:r};return e.name!=null&&(i.name=e.name),e.additional_kwargs.function_call!=null&&(i.function_call=e.additional_kwargs.function_call),xS.isInstance(e)&&e.tool_calls?.length?i.tool_calls=e.tool_calls.map(GF):(e.additional_kwargs.tool_calls!=null&&(i.tool_calls=e.additional_kwargs.tool_calls),Jx.isInstance(e)&&e.tool_call_id!=null&&(i.tool_call_id=e.tool_call_id)),e.additional_kwargs.audio&&typeof e.additional_kwargs.audio==`object`&&`id`in e.additional_kwargs.audio?[i,{role:`assistant`,audio:{id:e.additional_kwargs.audio.id}}]:i});async function*Nse(e,t={}){let n=t.streamUsage??!0,r=t.provider??`openai`,i=t.mapChunk,a=new Map,o=new Map,s=0,c=!1,l,u,d,f=!1,p=(e,t)=>{let n=o.get(e);if(n!==void 0)return{index:n,isNew:!1};let r=s++;return o.set(e,r),a.set(r,{...t}),{index:r,isNew:!0}};for await(let t of e){i&&(t=i(t)),c||(c=!0,yield{event:`message-start`,id:t.id}),!f&&(t.model||t.service_tier)&&(f=!0,yield{event:`provider`,provider:r,name:`stream_metadata`,payload:{model:t.model,service_tier:t.service_tier}}),t.usage&&n&&(l=Lse(t.usage),yield{event:`usage`,usage:l});let e=t.x_groq?.usage;e&&n&&(l=Fse(e),yield{event:`usage`,usage:l});let o=t.choices?.[0];if(!o)continue;o.finish_reason!=null&&(u=Ise(o.finish_reason),d=Rse(t,o));let{delta:s}=o;if(!s)continue;let m=Pse(s);if(m){let{index:e,isNew:t}=p(`reasoning`,{type:`reasoning`,reasoning:``});t&&(yield{event:`content-block-start`,index:e,content:{type:`reasoning`,reasoning:``}});let n=a.get(e);n.reasoning=(n.reasoning??``)+m,yield{event:`content-block-delta`,index:e,delta:{type:`reasoning-delta`,reasoning:m}}}if(s.content){let{index:e,isNew:t}=p(`text`,{type:`text`,text:``});t&&(yield{event:`content-block-start`,index:e,content:{type:`text`,text:``}});let n=a.get(e);n.text=(n.text??``)+s.content,yield{event:`content-block-delta`,index:e,delta:{type:`text-delta`,text:s.content}}}if(Array.isArray(s.tool_calls))for(let e of s.tool_calls){let t=e.index??0,{index:n,isNew:r}=p(`tool:${t}`,{type:`tool_call_chunk`,id:e.id,name:e.function?.name,args:``,index:t});r&&(yield{event:`content-block-start`,index:n,content:{type:`tool_call_chunk`,id:e.id,name:e.function?.name,args:``,index:t}});let i=a.get(n);e.id!=null&&(i.id=e.id),e.function?.name!=null&&(i.name=e.function.name);let o=e.function?.arguments??``;i.args=(i.args??``)+o,yield{event:`content-block-delta`,index:n,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...i.id==null?{}:{id:i.id},...i.name==null?{}:{name:i.name},args:i.args}}}}if(s.audio){let{index:e,isNew:t}=p(`audio`,{type:`audio`,id:s.audio.id,data:``,mimeType:`audio/pcm`,transcript:s.audio.transcript??``});t&&(yield{event:`content-block-start`,index:e,content:{type:`audio`,id:s.audio.id,data:``,mimeType:`audio/pcm`,transcript:s.audio.transcript??``}});let n=a.get(e);s.audio.transcript&&(n.transcript=(n.transcript??``)+s.audio.transcript,yield{event:`content-block-delta`,index:e,delta:{type:`block-delta`,fields:{type:`audio`,transcript:n.transcript}}}),s.audio.data&&(n.data=(n.data??``)+s.audio.data,yield{event:`content-block-delta`,index:e,delta:{type:`data-delta`,data:s.audio.data,encoding:`base64`}})}s.function_call&&(yield{event:`provider`,provider:r,name:`function_call`,payload:s.function_call}),o.logprobs&&(yield{event:`provider`,provider:r,name:`logprobs`,payload:o.logprobs})}for(let[e,t]of a)yield{event:`content-block-finish`,index:e,content:nI(t)};yield{event:`message-finish`,reason:u,...l?{usage:l}:{},...d?{responseMetadata:d}:{}}}function Pse(e){let t=e.reasoning_content??e.reasoning;return typeof t==`string`&&t.length>0?t:void 0}function Fse(e){return{input_tokens:e.prompt_tokens??0,output_tokens:e.completion_tokens??0,total_tokens:e.total_tokens??0}}function Ise(e){switch(e){case`stop`:return`stop`;case`length`:case`max_tokens`:return`length`;case`tool_calls`:case`function_call`:return`tool_use`;case`content_filter`:return`content_filter`;default:return`stop`}}function Lse(e){let t={...e.prompt_tokens_details?.audio_tokens!=null&&{audio:e.prompt_tokens_details.audio_tokens},...e.prompt_tokens_details?.cached_tokens!=null&&{cache_read:e.prompt_tokens_details.cached_tokens}},n={...e.completion_tokens_details?.audio_tokens!=null&&{audio:e.completion_tokens_details.audio_tokens},...e.completion_tokens_details?.reasoning_tokens!=null&&{reasoning:e.completion_tokens_details.reasoning_tokens}};return{input_tokens:e.prompt_tokens??0,output_tokens:e.completion_tokens??0,total_tokens:e.total_tokens??0,...Object.keys(t).length>0&&{input_token_details:t},...Object.keys(n).length>0&&{output_token_details:n}}}function Rse(e,t){return{model_provider:`openai`,model_name:e.model,system_fingerprint:e.system_fingerprint,service_tier:e.service_tier,finish_reason:t.finish_reason,...e.usage?{usage:e.usage}:{}}}var zse=class extends aI{constructor(e,t){super(iI(e,t))}invocationParams(e,t){let n;e?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=e.strict,!(this.streaming||t?.streaming)&&e?.response_format?.type===`json_schema`&&n!==!1&&(n=!0);let r={};e?.stream_options===void 0?this.streamUsage&&(this.streaming||t?.streaming)&&(r={stream_options:{include_usage:!0}}):r={stream_options:e.stream_options};let i={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(e=>this._convertChatOpenAIToolToCompletionsTool(e,{strict:n})):void 0,tool_choice:nF(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...r,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,verbosity:e?.verbosity??this.verbosity};e?.prediction!==void 0&&(i.prediction=e.prediction),this.service_tier!==void 0&&(i.service_tier=this.service_tier),e?.service_tier!==void 0&&(i.service_tier=e.service_tier);let a=this._getReasoningParams(e);return a!==void 0&&a.effort!==void 0&&(i.reasoning_effort=a.effort),RP(i.model)?i.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:i.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,i}async _generate(e,t,n){t.signal?.throwIfAborted();let r={},i=this.invocationParams(t),a=sI({messages:e,model:this.model});if(i.stream){let i=this._streamResponseChunks(e,t,n),a={};for await(let e of i){e.message.response_metadata={...e.generationInfo,...e.message.response_metadata};let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}let o=Object.entries(a).sort(([e],[t])=>parseInt(e,10)-parseInt(t,10)).map(([e,t])=>t),{functions:s,function_call:c}=this.invocationParams(t),l=await this._getEstimatedTokenCountFromPrompt(e,s,c),u=await this._getNumTokensFromGenerations(o);return r.input_tokens=l,r.output_tokens=u,r.total_tokens=l+u,{generations:o,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{let e=await this.completionWithRetry({...i,stream:!1,messages:a},{signal:t?.signal,...t?.options}),{completion_tokens:n,prompt_tokens:o,total_tokens:s,prompt_tokens_details:c,completion_tokens_details:l}=e?.usage??{};n&&(r.output_tokens=(r.output_tokens??0)+n),o&&(r.input_tokens=(r.input_tokens??0)+o),s&&(r.total_tokens=(r.total_tokens??0)+s),(c?.audio_tokens!==null||c?.cached_tokens!==null)&&(r.input_token_details={...c?.audio_tokens!==null&&{audio:c?.audio_tokens},...c?.cached_tokens!==null&&{cache_read:c?.cached_tokens}}),(l?.audio_tokens!==null||l?.reasoning_tokens!==null)&&(r.output_token_details={...l?.audio_tokens!==null&&{audio:l?.audio_tokens},...l?.reasoning_tokens!==null&&{reasoning:l?.reasoning_tokens}});let u=[];for(let t of e?.choices??[]){let n={text:t.message?.content??``,message:this._convertCompletionsMessageToBaseMessage(t.message??{role:`assistant`},e)};n.generationInfo={...t.finish_reason?{finish_reason:t.finish_reason}:{},...t.logprobs?{logprobs:t.logprobs}:{}},SS(n.message)&&(n.message.usage_metadata=r),n.message=new xS(Object.fromEntries(Object.entries(n.message).filter(([e])=>!e.startsWith(`lc_`)))),u.push(n)}return{generations:u,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamChatModelEvents(e,t,n){let r=sI({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a=await this.completionWithRetry(i,t),o=this.streamUsage??t.streamUsage;yield*Nse(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(a,t.signal),{streamUsage:o??!0,provider:this.streamEventProvider})}get streamEventProvider(){return`openai`}async*_streamResponseChunks(e,t,n){let r=sI({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a,o=await this.completionWithRetry(i,t),s;for await(let e of o){if(t.signal?.aborted)return;let r=e?.choices?.[0];if(e.usage&&(s=e.usage),!r)continue;let{delta:i}=r;if(!i)continue;let o=this._convertCompletionsDeltaToBaseMessageChunk(i,e,a);a=i.role??a;let c={prompt:t.promptIndex??0,completion:r.index??0};if(typeof o.content!=`string`){console.log(`[WARNING]: Received non-string content from OpenAI. This is currently not supported.`);continue}let l={...c};r.finish_reason!=null&&(l.finish_reason=r.finish_reason,l.system_fingerprint=e.system_fingerprint,l.model_name=e.model,l.service_tier=e.service_tier),this.logprobs&&(l.logprobs=r.logprobs);let u=new jk({message:o,text:o.content,generationInfo:l});yield u,await n?.handleLLMNewToken(u.text??``,c,void 0,void 0,void 0,{chunk:u})}if(s){let e={...s.prompt_tokens_details?.audio_tokens!==null&&{audio:s.prompt_tokens_details?.audio_tokens},...s.prompt_tokens_details?.cached_tokens!==null&&{cache_read:s.prompt_tokens_details?.cached_tokens}},t={...s.completion_tokens_details?.audio_tokens!==null&&{audio:s.completion_tokens_details?.audio_tokens},...s.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:s.completion_tokens_details?.reasoning_tokens}},r=new jk({message:new wS({content:``,response_metadata:{usage:{...s}},usage_metadata:{input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,total_tokens:s.total_tokens,...Object.keys(e).length>0&&{input_token_details:e},...Object.keys(t).length>0&&{output_token_details:t}}}),text:``});yield r,await n?.handleLLMNewToken(r.text??``,{prompt:0,completion:0},void 0,void 0,void 0,{chunk:r})}if(t.signal?.aborted)throw Error(`AbortError`)}async completionWithRetry(e,t){let n=this._getClientOptions(t),r=e.response_format&&e.response_format.type===`json_schema`;return this.caller.call(async()=>{try{return r&&!e.stream?await this.client.chat.completions.parse(e,n):await this.client.chat.completions.create(e,n)}catch(e){throw Fb(e)}})}_convertCompletionsDeltaToBaseMessageChunk(e,t,n){return Ase({delta:e,rawResponse:t,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(e,t){return kse({message:e,rawResponse:t,includeRawResponse:this.__includeRawResponse})}},cI=`__openai_function_call_ids__`,lI=`__openai_custom_tool_call_ids__`;function uI(e){return e.type===`url_citation`?{type:`citation`,source:`url_citation`,url:e.url,title:e.title,startIndex:e.start_index,endIndex:e.end_index}:e.type===`file_citation`?{type:`citation`,source:`file_citation`,title:e.filename,startIndex:e.index,file_id:e.file_id}:e.type===`container_file_citation`?{type:`citation`,source:`container_file_citation`,title:e.filename,startIndex:e.start_index,endIndex:e.end_index,file_id:e.file_id,container_id:e.container_id}:e.type===`file_path`?{type:`citation`,source:`file_path`,startIndex:e.index,file_id:e.file_id}:{type:`non_standard`,value:e}}function Bse(e){if(e.type===`url_citation`||e.type===`file_citation`||e.type===`container_file_citation`||e.type===`file_path`)return e;if(e.type===`citation`){let t=e;if(t.source===`url_citation`)return{type:`url_citation`,url:t.url??``,title:t.title??``,start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source===`file_citation`)return{type:`file_citation`,file_id:t.file_id??``,filename:t.title??``,index:t.startIndex??0};if(t.source===`container_file_citation`)return{type:`container_file_citation`,file_id:t.file_id??``,filename:t.title??``,container_id:t.container_id??``,start_index:t.startIndex??0,end_index:t.endIndex??0};if(t.source===`file_path`)return{type:`file_path`,file_id:t.file_id??``,index:t.startIndex??0}}return e.type===`non_standard`?e.value:e}var dI=e=>{let t={...e?.input_tokens_details?.cached_tokens!=null&&{cache_read:e?.input_tokens_details?.cached_tokens}},n={...e?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:e?.output_tokens_details?.reasoning_tokens}};return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,input_token_details:t,output_token_details:n}},fI=e=>{if(e.error){let t=Error(e.error.message);throw t.name=e.error.code,t}let t=[],n=[],r=[],i=e.output.map(e=>{if(e.type===`function_call`&&`parsed_arguments`in e){let t={...e};return delete t.parsed_arguments,t}return e}),a={model_provider:`openai`,model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,output:i,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(let i of e.output)if(i.type===`message`)t.push(...i.content.flatMap(e=>e.type===`output_text`?(`parsed`in e&&e.parsed!=null&&(o.parsed=e.parsed),{type:`text`,text:e.text,annotations:e.annotations.map(uI),...i.phase===null?{}:{phase:i.phase}}):e.type===`refusal`?(o.refusal=e.refusal,[]):e));else if(i.type===`function_call`){let e={function:{name:i.name,arguments:i.arguments},id:i.call_id};try{n.push(WF(e,{returnId:!0}))}catch(t){let n;typeof t==`object`&&t&&`message`in t&&typeof t.message==`string`&&(n=t.message),r.push(KF(e,n))}o[cI]??={},i.id&&(o[cI][i.call_id]=i.id)}else if(i.type===`reasoning`){o.reasoning=i;let e=i.summary?.map(e=>e.text).filter(Boolean).join(``);e&&t.push({type:`reasoning`,reasoning:e})}else if(i.type===`custom_tool_call`){let e=jae(i);e?(n.push(e),o[lI]??={},i.id&&i.call_id&&(o[lI][i.call_id]=i.id)):r.push(KF(i,`Malformed custom tool call`))}else if(i.type===`computer_call`){let e=Mae(i);e?n.push(e):r.push(KF(i,`Malformed computer call`))}else i.type===`image_generation_call`?(i.result&&t.push({type:`image`,mimeType:`image/png`,data:i.result,id:i.id,metadata:{status:i.status}}),o.tool_outputs??=[],o.tool_outputs.push(i)):(o.tool_outputs??=[],o.tool_outputs.push(i));return new xS({id:e.id,content:t,tool_calls:n,invalid_tool_calls:r,usage_metadata:dI(e.usage),additional_kwargs:o,response_metadata:a})},Vse=e=>{let t=(e.summary.length>1?e.summary.reduce((e,t)=>{let n=e[e.length-1];return n.index===t.index?n.text+=t.text:e.push(t),e},[{...e.summary[0]}]):e.summary).map(e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==`index`)));return{...e,summary:t}},Hse=e=>{let t=[],n={},r,i=[],a={model_provider:`openai`},o={},s;if(e.type===`response.output_text.delta`)t.push({type:`text`,text:e.delta,index:e.content_index});else if(e.type===`response.output_text.annotation.added`)t.push({type:`text`,text:``,annotations:[uI(e.annotation)],index:e.content_index});else if(e.type===`response.output_item.added`&&e.item.type===`message`){let n=`phase`in e.item?e.item.phase:void 0;n&&t.push({type:`text`,text:``,phase:n,index:0})}else if(e.type===`response.output_item.added`&&e.item.type===`function_call`)i.push({type:`tool_call_chunk`,name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),o[cI]={[e.item.call_id]:e.item.id};else if(e.type===`response.output_item.added`&&e.item.type===`custom_tool_call`)i.push({type:`tool_call_chunk`,isCustomTool:!0,name:e.item.name,args:e.item.input,id:e.item.call_id,index:e.output_index}),o[lI]={[e.item.call_id]:e.item.id};else if(e.type===`response.output_item.done`&&e.item.type===`computer_call`)i.push({type:`tool_call_chunk`,name:`computer_use`,args:JSON.stringify({action:e.item.action}),id:e.item.call_id,index:e.output_index}),o.tool_outputs=[e.item];else if(e.type===`response.output_item.done`&&e.item.type===`image_generation_call`)e.item.result&&t.push({type:`image`,mimeType:`image/png`,data:e.item.result,id:e.item.id,metadata:{status:e.item.status}}),o.tool_outputs=[e.item];else if(e.type===`response.output_item.done`&&[`web_search_call`,`file_search_call`,`code_interpreter_call`,`shell_call`,`local_shell_call`,`mcp_call`,`mcp_list_tools`,`mcp_approval_request`,`custom_tool_call`,`tool_search_call`,`tool_search_output`].includes(e.item.type))o.tool_outputs=[e.item];else if(e.type===`response.created`)s=e.response.id,a.id=e.response.id,a.model_name=e.response.model,a.model=e.response.model;else if(e.type===`response.completed`||e.type===`response.incomplete`){s=e.response.id;let t=fI(e.response);if(r=dI(e.response.usage),e.response.text?.format?.type===`json_schema`&&t.text)try{o.parsed??=JSON.parse(t.text)}catch{}for(let[n,r]of Object.entries(e.response))n!==`id`&&(n===`output`?a[n]=t.response_metadata.output:a[n]=r)}else if(e.type===`response.function_call_arguments.delta`||e.type===`response.custom_tool_call_input.delta`)i.push({type:`tool_call_chunk`,args:e.delta,index:e.output_index,...e.type===`response.custom_tool_call_input.delta`?{isCustomTool:!0}:{}});else if(e.type===`response.web_search_call.in_progress`||e.type===`response.web_search_call.searching`||e.type===`response.web_search_call.completed`||e.type===`response.file_search_call.in_progress`||e.type===`response.file_search_call.searching`||e.type===`response.file_search_call.completed`||e.type===`response.image_generation_call.in_progress`||e.type===`response.image_generation_call.generating`||e.type===`response.image_generation_call.completed`){let[,t,r]=e.type.match(/^response\.(.*)\.([^.]+)$/)??[``,``,``];n={tool_outputs:{id:e.item_id,type:t,status:r}}}else if(e.type===`response.refusal.done`)o.refusal=e.refusal;else if(e.type===`response.output_item.added`&&`item`in e&&e.item.type===`reasoning`){let n=e.item.summary?e.item.summary.map((e,t)=>({...e,index:t})):void 0;o.reasoning={id:e.item.id,type:e.item.type,...n?{summary:n}:{}};let r=e.item.summary?.map(e=>e.text).filter(Boolean).join(``);r&&t.push({type:`reasoning`,reasoning:r})}else if(e.type===`response.reasoning_summary_part.added`)o.reasoning={type:`reasoning`,summary:[{...e.part,index:e.summary_index}]},e.part.text&&t.push({type:`reasoning`,reasoning:e.part.text,index:e.summary_index});else if(e.type===`response.reasoning_summary_text.delta`)o.reasoning={type:`reasoning`,summary:[{text:e.delta,type:`summary_text`,index:e.summary_index}]},e.delta&&t.push({type:`reasoning`,reasoning:e.delta,index:e.summary_index});else if(e.type===`response.image_generation_call.partial_image`)return null;else return null;return new jk({text:t.map(e=>e.text).join(``),message:new wS({id:s,content:t,tool_call_chunks:i,usage_metadata:r,additional_kwargs:o,response_metadata:a}),generationInfo:n})},Use=e=>{let t=xS.isInstance(e)&&e.response_metadata?.model_provider===`openai`;function*n(){let n=LP(()=>{try{let t=UP(e);return t===`system`||t===`developer`||t===`assistant`||t===`user`?t:`assistant`}catch{return`assistant`}}),r=e=>n===`assistant`?{type:`output_text`,text:e,annotations:[]}:{type:`input_text`,text:e},i,a=new Set,o=new Set,s=new Map,c=new Map;function*l(){if(!i)return;let e=i.content;(typeof e==`string`&&e.length>0||Array.isArray(e)&&e.length>0)&&(yield i),i=void 0}let u=(e,t)=>{i||={type:`message`,role:n,content:[],...t?{phase:t}:{}},typeof i.content==`string`?i.content=i.content.length>0?[r(i.content),...e]:[...e]:i.content.push(...e)},d=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e??{})}catch{return`{}`}},f=e=>{let t=LP(()=>{let t=e.metadata?.detail;return t===`low`||t===`high`||t===`auto`?t:`auto`});if(e.fileId)return{type:`input_image`,detail:t,file_id:e.fileId};if(e.url)return{type:`input_image`,detail:t,image_url:e.url};if(e.data){let n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_image`,detail:t,image_url:`data:${e.mimeType??`image/png`};base64,${n}`}}},p=e=>{if(e.fileId){let t=BP(e);return{type:`input_file`,file_id:e.fileId,...t?{filename:t}:{}}}if(e.url){let t=BP(e);return{...t?{filename:t}:{},type:`input_file`,file_url:e.url}}if(e.data){let t=HP(e),n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_file`,file_data:`data:${e.mimeType??`application/octet-stream`};base64,${n}`,filename:t}}},m=e=>{let t=LP(()=>{if(Array.isArray(e.summary)){let t=e.summary?.map(e=>e?.text).filter(e=>typeof e==`string`)??[];if(t.length>0)return t}return e.reasoning?[e.reasoning]:[]}),n=t.length>0?t.map(e=>({type:`summary_text`,text:e})):[{type:`summary_text`,text:``}];return{type:`reasoning`,...e.id?{id:e.id}:{},summary:n}},h=e=>({type:`function_call`,name:e.name??``,call_id:e.id??``,arguments:d(e.args)}),g=e=>{let t=d(e.output),n=e.status===`success`?`completed`:e.status===`error`?`incomplete`:void 0;return{type:`function_call_output`,call_id:e.toolCallId??``,output:t,...n?{status:n}:{}}};for(let n of e.contentBlocks)if(n.type===`text`){let e=LP(()=>{if(`extras`in n&&typeof n.extras==`object`&&n.extras!==null&&`phase`in n.extras)return n.extras.phase});u([r(n.text)],e)}else if(n.type!==`invalid_tool_call`){if(n.type===`reasoning`)yield*l(),yield m(n);else if(n.type===`tool_call`){yield*l();let e=n.id??``;e&&(a.add(e),s.delete(e)),yield h(n)}else if(n.type===`tool_call_chunk`){if(n.id){let e=s.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),s.set(n.id,e)}}else if(n.type===`server_tool_call`){yield*l();let e=n.id??``;e&&(o.add(e),c.delete(e)),yield h(n)}else if(n.type===`server_tool_call_chunk`){if(n.id){let e=c.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),c.set(n.id,e)}}else if(n.type===`server_tool_call_result`)yield*l(),yield g(n);else if(n.type!==`audio`)if(n.type===`file`){let e=p(n);e&&u([e])}else if(n.type===`image`){let e=f(n);e&&u([e])}else if(n.type===`video`){let e=p(n);e&&u([e])}else n.type===`text-plain`?n.text&&u([r(n.text)]):n.type===`non_standard`&&t&&(yield*l(),yield n.value)}yield*l();for(let[e,t]of s){if(!e||a.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}for(let[e,t]of c){if(!e||o.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}}return Array.from(n())},pI=({messages:e,zdrEnabled:t,model:n})=>e.flatMap(e=>{let r=e.response_metadata;if(r?.output_version===`v1`)return Use(e);let i=e.additional_kwargs,a=UP(e);if(a===`system`&&RP(n)&&(a=`developer`),a===`function`)throw Error(`Function messages are not supported in Responses API`);if(a===`tool`){let t=e;if(i?.type===`computer_call_output`)return{type:`computer_call_output`,output:(()=>{if(typeof t.content==`string`)return{type:`input_image`,image_url:t.content};if(Array.isArray(t.content)){let e=t.content.find(e=>e.type===`input_image`);if(e)return e;let n=t.content.find(e=>e.type===`computer_screenshot`);if(n)return n;let r=t.content.find(e=>e.type===`image_url`);if(r)return{type:`input_image`,image_url:typeof r.image_url==`string`?r.image_url:r.image_url.url}}throw Error(`Invalid computer call output`)})(),call_id:t.tool_call_id};if(t.additional_kwargs?.customTool)return{type:`custom_tool_call_output`,call_id:t.tool_call_id,output:t.content};let n=Array.isArray(t.content)&&t.content.every(e=>typeof e==`object`&&!!e&&`type`in e&&(e.type===`input_file`||e.type===`input_image`||e.type===`input_text`));return{type:`function_call_output`,call_id:t.tool_call_id,id:t.id?.startsWith(`fc_`)?t.id:void 0,output:n||typeof t.content==`string`?t.content:JSON.stringify(t.content)}}if(a===`assistant`){if(!t&&r?.output!=null&&Array.isArray(r?.output)&&r?.output.length>0&&r?.output.every(e=>`type`in e))return r?.output;let n=[],a=i?.reasoning,o=!!a?.encrypted_content;if(a&&(!t||o)){let e=Vse(a);n.push(e)}let{content:s}=e;if(i?.refusal&&(typeof s==`string`&&(s=[{type:`output_text`,text:s,annotations:[]}]),s=[...s,{type:`refusal`,refusal:i.refusal}]),typeof s==`string`||s.length>0){let r={type:`message`,role:`assistant`,...e.id&&!t&&e.id.startsWith(`msg_`)?{id:e.id}:{},content:LP(()=>typeof s==`string`?s:s.flatMap(e=>{if(e.type===`text`){let t=e;return{type:`output_text`,text:t.text,annotations:(t.annotations??[]).map(Bse)}}return e.type===`output_text`||e.type===`refusal`?e:[]})),phase:LP(()=>{if(Array.isArray(s))return s.find(e=>`phase`in e&&typeof e.phase==`string`)?.phase})};n.push(r)}let c=i?.[cI],l=i?.[lI];xS.isInstance(e)&&e.tool_calls?.length?n.push(...e.tool_calls.map(e=>Pae(e,l)?{type:`custom_tool_call`,id:`call_id`in e&&typeof e.call_id==`string`?e.call_id:l?.[e.id??``]??``,call_id:e.id??``,input:e.args.input,name:e.name}:Nae(e)?{type:`computer_call`,id:e.call_id,call_id:e.id??``,action:e.args.action}:{type:`function_call`,name:e.name,arguments:JSON.stringify(e.args),call_id:e.id,...t?{}:{id:c?.[e.id]}})):i?.tool_calls&&n.push(...i.tool_calls.map(e=>({type:`function_call`,name:e.function.name,call_id:e.id,arguments:e.function.arguments,...t?{}:{id:c?.[e.id]}})));let u=r?.output?.length?r?.output:i.tool_outputs,d=[`computer_call`,`mcp_call`,`code_interpreter_call`,`image_generation_call`,`shell_call`,`local_shell_call`];if(u!=null){let e=u?.filter(e=>d.includes(e.type));e.length>0&&n.push(...e)}return n}if(a===`user`||a===`system`||a===`developer`){if(typeof e.content==`string`)return{type:`message`,role:a,content:e.content};let t=[],n=e.content.flatMap(e=>{if(e.type===`mcp_approval_response`&&t.push({type:`mcp_approval_response`,approval_request_id:e.approval_request_id,approve:e.approve}),Ib(e)){if(e.type===`file`){let t=BP(e);if(e.source_type===`url`)return{type:`input_file`,file_url:e.url,...t?{filename:t}:{}};if(e.source_type===`id`)return{type:`input_file`,file_id:e.id,...t?{filename:t}:{}};if(e.source_type===`base64`)return{type:`input_file`,file_data:`data:${e.mime_type??``};base64,${e.data}`,filename:HP(e)}}return Ub(e,oI)}return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`image_url`?{type:`input_image`,image_url:LP(()=>{if(typeof e.image_url==`string`)return e.image_url;if(typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url)return e.image_url.url}),detail:LP(()=>{if(typeof e.image_url==`string`)return`auto`;if(typeof e.image_url==`object`&&e.image_url!==null&&`detail`in e.image_url)return e.image_url.detail})}:e.type===`input_text`||e.type===`input_image`||e.type===`input_file`?e:[]});return n.length>0&&t.push({type:`message`,role:a,content:n}),t}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});async function*Wse(e,t={}){let n=t.streamUsage??!0,r=t.provider??`openai`,i=new Map,a=new Map,o=0,s=!1,c,l,u,d,f=new Set,p=(e,t)=>{let n=a.get(e);if(n!==void 0)return{index:n,isNew:!1};let r=o++;return a.set(e,r),i.set(r,{...t}),{index:r,isNew:!0}},m=function*(){s||(s=!0,yield{event:`message-start`,id:c})},h=function*(e){if(f.has(e))return;let t=i.get(e);t&&(f.add(e),yield{event:`content-block-finish`,index:e,content:nI(t)})};for await(let t of e){if(t.type===`response.created`){c=t.response.id,yield*m(),yield{event:`provider`,provider:r,name:`response.created`,payload:{model:t.response.model,id:t.response.id}};continue}if(t.type===`response.output_text.delta`){yield*m();let{index:e,isNew:n}=p(`text:${t.output_index}:${t.content_index}`,{type:`text`,text:``});n&&(yield{event:`content-block-start`,index:e,content:{type:`text`,text:``}});let r=i.get(e);r.text=(r.text??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`text-delta`,text:t.delta}};continue}if(t.type===`response.reasoning_summary_text.delta`){yield*m();let{index:e,isNew:n}=p(`reasoning:${t.output_index}:${t.summary_index}`,{type:`reasoning`,reasoning:``});n&&(yield{event:`content-block-start`,index:e,content:{type:`reasoning`,reasoning:``}});let r=i.get(e);r.reasoning=(r.reasoning??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`reasoning-delta`,reasoning:t.delta}};continue}if(t.type===`response.output_item.added`&&(t.item.type===`function_call`||t.item.type===`custom_tool_call`)){yield*m();let e=`tool:${t.output_index}`,n=t.item.type===`custom_tool_call`,r=t.item.type===`function_call`?t.item.arguments??``:t.item.input??``,{index:a,isNew:o}=p(e,{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:r,index:t.output_index,...n?{isCustomTool:!0}:{}});if(o&&(yield{event:`content-block-start`,index:a,content:{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:r,index:t.output_index}}),r){let e=i.get(a);yield{event:`content-block-delta`,index:a,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...e.id==null?{}:{id:e.id},...e.name==null?{}:{name:e.name},args:e.args}}}}continue}if(t.type===`response.function_call_arguments.delta`||t.type===`response.custom_tool_call_input.delta`){yield*m();let{index:e,isNew:n}=p(`tool:${t.output_index}`,{type:`tool_call_chunk`,args:``,index:t.output_index,...t.type===`response.custom_tool_call_input.delta`?{isCustomTool:!0}:{}});n&&(yield{event:`content-block-start`,index:e,content:{type:`tool_call_chunk`,args:``,index:t.output_index}});let r=i.get(e);r.args=(r.args??``)+t.delta,yield{event:`content-block-delta`,index:e,delta:{type:`block-delta`,fields:{type:`tool_call_chunk`,...r.id==null?{}:{id:r.id},...r.name==null?{}:{name:r.name},args:r.args}}};continue}if(t.type===`response.output_item.done`&&(t.item.type===`function_call`||t.item.type===`custom_tool_call`)){yield*m();let e=`tool:${t.output_index}`,n=t.item.type===`function_call`?t.item.arguments??``:t.item.input??``,{index:r,isNew:a}=p(e,{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:n,index:t.output_index});if(a)yield{event:`content-block-start`,index:r,content:{type:`tool_call_chunk`,id:t.item.call_id,name:t.item.name,args:n,index:t.output_index}};else{let e=i.get(r);e.args=n,e.id=t.item.call_id,e.name=t.item.name}yield*h(r);continue}if(t.type===`response.completed`||t.type===`response.incomplete`){yield*m(),c=t.response.id,u=Gse(t.response.status,t.type),d={model_provider:r,id:t.response.id,model:t.response.model,status:t.response.status},n&&t.response.usage&&(l=dI(t.response.usage),yield{event:`usage`,usage:l});continue}t.type!==`response.image_generation_call.partial_image`&&(yield*m(),yield{event:`provider`,provider:r,name:t.type,payload:t})}s||(yield{event:`message-start`});for(let[e]of i)f.has(e)||(yield*h(e));yield{event:`message-finish`,reason:u,...l?{usage:l}:{},...d?{responseMetadata:d}:{}}}function Gse(e,t){return t===`response.incomplete`?`length`:e===`completed`?`stop`:e===`incomplete`?`length`:`stop`}var Kse=class extends aI{constructor(e,t){super(iI(e,t))}invocationParams(e){let t;e?.strict!==void 0&&(t=e.strict),t===void 0&&this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:Aae(e?.tool_choice)?e?.tool_choice:(()=>{let t=nF(e?.tool_choice);if(typeof t==`object`&&`type`in t){if(t.type===`function`)return{type:`function`,name:t.function.name};if(t.type===`allowed_tools`)return{type:`allowed_tools`,mode:t.allowed_tools.mode,tools:t.allowed_tools.tools};if(t.type===`custom`)return{type:`custom`,name:t.custom.name}}})(),text:(()=>{if(e?.text)return e.text;let t=this._getResponseFormat(e?.response_format);return t?.type===`json_schema`?t.json_schema.schema==null?void 0:{format:{type:`json_schema`,schema:t.json_schema.schema,description:t.json_schema.description,name:t.json_schema.name,strict:t.json_schema.strict},verbosity:e?.verbosity}:{format:t,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(e);return r!==void 0&&(n.reasoning=r),n}async _generate(e,t,n){t.signal?.throwIfAborted();let r=this.invocationParams(t);if(r.stream){let r=this._streamResponseChunks(e,t,n),i;for await(let e of r)e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},i=i?.concat(e)??e;return{generations:i?[i]:[],llmOutput:{estimatedTokenUsage:i?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:pI({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:n.output_text,message:fI(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:pI({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t),i=this.streamUsage??t.streamUsage;yield*Wse(async function*(e,t){for await(let n of e){if(t?.aborted)return;yield n}}(r,t.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return`openai`}async*_streamResponseChunks(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:pI({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t);try{for await(let e of r){if(t.signal?.aborted)return;let r=Hse(e);r!=null&&(yield r,await n?.handleLLMNewToken(r.text||``,{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:r}))}}catch(e){throw Fb(e)}}async completionWithRetry(e,t){return this.caller.call(async()=>{let n=this._getClientOptions(t);try{return e.text?.format?.type===`json_schema`&&!e.stream?await this.client.responses.parse(e,n):await this.client.responses.create(e,n)}catch(e){throw Fb(e)}})}_reduceChatOpenAITools(e,t){let n=[];for(let r of e)if(rF(r))r.type===`image_generation`&&t?.stream&&(r.partial_images=1),n.push(r);else if(iF(r)){let e=r.metadata.customTool;n.push({type:`custom`,name:e.name,description:e.description,format:e.format})}else if(IF(r)){let e={};for(let[t,n]of Object.entries(r))t!==`type`&&t!==`function`&&(e[t]=n);n.push({type:`function`,name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:t?.strict??null,...e})}else aF(r)&&n.push(Fae(r));return n}},mI=class e extends aI{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,`useResponsesApi`]}get callKeys(){return[...super.callKeys,`useResponsesApi`]}fields;constructor(e,t){let n=iI(e,t);super(n),this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Kse(n),this.completions=n?.completions??new zse(n)}_useResponsesApi(e){let t=e?.tools?.some(rF),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,r=e?.tools?.some(aF)||e?.tools?.some(iF);return this.useResponsesApi||t||n||r||WP(this.model)}getLsParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(t):this.completions.getLsParams(t)}invocationParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(t):this.completions.invocationParams(t)}async _generate(e,t,n){return this._useResponsesApi(t)?this.responses._generate(e,t,n):this.completions._generate(e,t,n)}async*_streamChatModelEvents(e,t,n){if(this._useResponsesApi(t)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(t),n);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(t),n)}async*_streamResponseChunks(e,t,n){if(this._useResponsesApi(t)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(t),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(t),n)}withConfig(t){let n=new e(this.fields);return n.defaultOptions={...this.defaultOptions,...t},n}};CM(),oF();var hI=class extends LF{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return[`langchain`,`tools`]}responseFormat=`content`;defaultConfig;constructor(e){super(e??{}),this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}async invoke(e,t){let n,r=$O(QO(this.defaultConfig,t));return oS(e)?(n=e.args,r={...r,toolCall:e}):n=e,this.call(n,r)}async call(e,t,n){let r=oS(e)?e.args:e,i;if(rA(this.schema))try{i=await aA(this.schema,r)}catch(t){let n=`Received tool input did not match expected schema`;throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.message}`),vA(t)&&(n=`${n}\n\n${st(t)}`),new sS(n,JSON.stringify(e))}else{let t=rP(r,this.schema);if(!t.valid){let n=`Received tool input did not match expected schema`;throw this.verboseParsingErrors&&(n=`${n}\nDetails: ${t.errors.map(e=>`${e.keywordLocation}: ${e.error}`).join(`
|
|
148
|
+
`)}`),new sS(n,JSON.stringify(e))}i=r}let a=WO(t),o=qO.configure(a.callbacks,this.callbacks,a.tags||n,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),s;oS(e)&&(s=e.id),!s&&cne(a)&&(s=a.toolCall.id);let c=await o?.handleToolStart(this.toJSON(),typeof e==`string`?e:JSON.stringify(e),a.runId,void 0,void 0,void 0,a.runName,s);delete a.runId;let l;try{let e=await this._call(i,c,a);l=gP(e)?await _P(e,async e=>{try{await c?.handleToolEvent(e)}catch(e){await c?.handleToolError(e)}}):e}catch(e){throw await c?.handleToolError(e),e}let u,d;if(this.responseFormat===`content_and_artifact`)if(Array.isArray(l)&&l.length===2)[u,d]=l;else throw Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(l)}`);else u=l;let f=Zse({content:u,artifact:d,toolCallId:s,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(f),f}},qse=class extends hI{schema=bM({input:vM().optional()}).transform(e=>e.input);constructor(e){super(e)}call(e,t){let n=typeof e==`string`||e==null?{input:e}:e;return super.call(n,t)}},Jse=class extends qse{static lc_name(){return`DynamicTool`}name;description;func;constructor(e){super(e),this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}async call(e,t){let n=WO(t);return n.runName===void 0&&(n.runName=this.name),super.call(e,n)}_call(e,t,n){return this.func(e,t,n)}},Yse=class extends hI{static lc_name(){return`DynamicStructuredTool`}description;func;schema;constructor(e){super(e),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,n){let r=WO(t);return r.runName===void 0&&(r.runName=this.name),super.call(e,r,n)}_call(e,t,n){return this.func(e,t,n)}};function gI(e,t){let n=sA(t.schema),r=oP(t.schema);if(!t.schema||n||r)return new Jse({...t,description:t.description??t.schema?.description??`${t.name} tool`,func:async(t,n,r)=>new Promise((i,a)=>{let o=ek(r,{callbacks:n?.getChild()});XO.runWithConfig(tk(o),async()=>{try{i(e(t,o))}catch(e){a(e)}})})});let i=t.schema,a=t.description??t.schema.description??`${t.name} tool`;return new Yse({...t,description:a,schema:i,func:async(t,n,r)=>new Promise((i,a)=>{let o,s=()=>{r?.signal&&o&&r.signal.removeEventListener(`abort`,o)};r?.signal&&(o=()=>{s(),a(rk(r.signal))},r.signal.addEventListener(`abort`,o,{once:!0}));let c=ek(r,{callbacks:n?.getChild()});XO.runWithConfig(tk(c),async()=>{try{let n=await e(t,c);if(gP(n)){i(n);return}if(r?.signal?.aborted){s();return}s(),i(n)}catch(e){s(),a(e)}})})})}function Xse(e){return typeof e==`object`&&!!e&&`type`in e}function Zse(e){let{content:t,artifact:n,toolCallId:r,metadata:i}=e;return r&&!Jte(t)?typeof t==`string`||Array.isArray(t)&&t.every(Xse)?new Jx({status:`success`,content:t,artifact:n,tool_call_id:r,name:e.name,metadata:i}):new Jx({status:`success`,content:Qse(t),artifact:n,tool_call_id:r,name:e.name,metadata:i}):t}function Qse(e){try{return JSON.stringify(e)??``}catch{return`${e}`}}oF(),F({action:ef([F({type:I(`screenshot`)}),F({type:I(`click`),x:Nd(),y:Nd(),button:df([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),F({type:I(`double_click`),x:Nd(),y:Nd(),button:df([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),F({type:I(`drag`),path:P(F({x:Nd(),y:Nd()}))}),F({type:I(`keypress`),keys:P(N())}),F({type:I(`move`),x:Nd(),y:Nd()}),F({type:I(`scroll`),x:Nd(),y:Nd(),scroll_x:Nd(),scroll_y:Nd()}),F({type:I(`type`),text:N()}),F({type:I(`wait`),duration:Nd().optional()})])}),oF(),ef([F({type:I(`exec`),command:P(N()),env:of(N(),N()).optional(),working_directory:N().optional(),timeout_ms:Nd().optional(),user:N().optional()})]),oF(),F({commands:P(N()).describe(`Array of shell commands to execute`),timeout_ms:Nd().optional().describe(`Optional timeout in milliseconds for the commands`),max_output_length:Nd().optional().describe(`Optional maximum number of characters to return from each command`)}),oF(),ef([F({type:I(`create_file`),path:N(),diff:N()}),F({type:I(`update_file`),path:N(),diff:N()}),F({type:I(`delete_file`),path:N()})]);function $se(e){return!!(e==null||typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob||e instanceof URLSearchParams||e instanceof FormData)}function ece(e){let t=e.model||`gpt-3.5-turbo`,n=e.temperature,r=e.maxTokens,i=e.baseUrl;if(e.mode===`direct`){let a=!1;try{a=typeof location<`u`&&location.protocol===`https:`&&![`localhost`,`127.0.0.1`,`0.0.0.0`].includes(location.hostname)}catch{}if(a){if(e.throwOnDirectInProduction)throw Error(`[page-agent-sdk][proxyLlm] direct 模式在生产环境(https + 非本地)会泄露 apiKey(进 bundle),建议改用 proxy 模式(throwOnDirectInProduction 已启用强安全闸;若确需生产直连,设为 false 显式承认风险)`);console.warn(`[page-agent-sdk][proxyLlm] direct 模式在生产环境(https + 非本地)会泄露 apiKey(进 bundle),建议改用 proxy 模式`)}if(!e.apiKey)throw Error(`[page-agent-sdk][proxyLlm] direct 模式需提供 apiKey(开发环境用真实 key)`);return new mI({apiKey:e.apiKey,model:t,temperature:n,maxTokens:r,configuration:i?{baseURL:i}:void 0})}i||console.warn(`[page-agent-sdk][proxyLlm] proxy 模式未配 baseUrl,将打到页面 origin(通常不是预期);请传代理地址如 '/api/llm'`);let a=e.userToken||`proxy`,o=null;function s(){return e.refreshToken?(o||=e.refreshToken().finally(()=>{o=null}),o):Promise.resolve(a)}return new mI({apiKey:a,model:t,temperature:n,maxTokens:r,configuration:{baseURL:i||`/`,fetch:async(t,n)=>{let r,i;typeof t==`string`?(r=t,i=n?.headers):t instanceof URL?(r=t.toString(),i=n?.headers):(r=t.url,i=n?.headers??t.headers);let o=new Headers(i);if(o.set(`Authorization`,`Bearer ${a}`),e.headers)for(let[t,n]of Object.entries(e.headers))o.set(t,n);let c=()=>fetch(r,{...n,headers:o}),l=await c();if(l.status===401&&e.refreshToken&&$se(n?.body))try{a=await s(),o.set(`Authorization`,`Bearer ${a}`),l=await c()}catch{}return l}}})}function _I(e,t={}){return new mI({apiKey:e.apiKey,model:e.model,temperature:t.temperature??e.temperature,maxTokens:t.maxTokens??e.maxTokens,configuration:{...e.baseUrl?{baseURL:e.baseUrl}:{},...e.extraConfig},...e.extraBody?{modelKwargs:e.extraBody}:{}})}async function vI(e,t={}){if((e.provider??`openai`)===`openai`)return _I(e,t);let{ChatAnthropic:n}=await import(`@langchain/anthropic`);return new n({apiKey:e.apiKey,model:e.model,temperature:t.temperature??e.temperature,maxTokens:t.maxTokens??e.maxTokens,...e.baseUrl?{anthropicApiUrl:e.baseUrl}:{},...e.extraConfig?{clientOptions:e.extraConfig}:{}})}function yI(e){let t=e.content;return typeof t==`string`?t:Array.isArray(t)?t.map(e=>typeof e==`string`?e:e?.type===`text`&&typeof e.text==`string`?e.text:``).join(``):``}function bI(e){let t=e.additional_kwargs||{},n=t.reasoning_content||t.reasoning||``;return!n&&Array.isArray(e.content)&&(n=e.content.map(e=>e?.type===`thinking`?e.thinking??``:e?.type===`thinking_delta`?e.delta??e.thinking??``:``).join(``)),n}function xI(e){let t=e;return t?.additional_kwargs?.usage??t?.response_metadata?.usage??t?.response_metadata?.token_usage??void 0}function SI(e){let t=Object.create(null);for(let n of e.split(`,`))t[n]=1;return e=>e in t}var CI={},wI=[],TI=()=>{},EI=()=>!1,DI=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),OI=e=>e.startsWith(`onUpdate:`),kI=Object.assign,AI=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},tce=Object.prototype.hasOwnProperty,jI=(e,t)=>tce.call(e,t),MI=Array.isArray,NI=e=>HI(e)===`[object Map]`,PI=e=>HI(e)===`[object Set]`,FI=e=>HI(e)===`[object Date]`,II=e=>typeof e==`function`,LI=e=>typeof e==`string`,RI=e=>typeof e==`symbol`,zI=e=>typeof e==`object`&&!!e,BI=e=>(zI(e)||II(e))&&II(e.then)&&II(e.catch),VI=Object.prototype.toString,HI=e=>VI.call(e),nce=e=>HI(e).slice(8,-1),UI=e=>HI(e)===`[object Object]`,WI=e=>LI(e)&&e!==`NaN`&&e[0]!==`-`&&``+parseInt(e,10)===e,GI=SI(`,key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted`),KI=e=>{let t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},rce=/-\w/g,qI=KI(e=>e.replace(rce,e=>e.slice(1).toUpperCase())),ice=/\B([A-Z])/g,JI=KI(e=>e.replace(ice,`-$1`).toLowerCase()),YI=KI(e=>e.charAt(0).toUpperCase()+e.slice(1)),XI=KI(e=>e?`on${YI(e)}`:``),ZI=(e,t)=>!Object.is(e,t),QI=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},$I=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},eL=e=>{let t=parseFloat(e);return isNaN(t)?e:t},ace=e=>{let t=LI(e)?Number(e):NaN;return isNaN(t)?e:t},oce,tL=()=>oce||=typeof globalThis<`u`?globalThis:typeof self<`u`?self:typeof window<`u`?window:typeof global<`u`?global:{};function nL(e){if(MI(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=LI(r)?uce(r):nL(r);if(i)for(let e in i)t[e]=i[e]}return t}else if(LI(e)||zI(e))return e}var sce=/;(?![^(]*\))/g,cce=/:([^]+)/,lce=/\/\*[^]*?\*\//g;function uce(e){let t={};return e.replace(lce,``).split(sce).forEach(e=>{if(e){let n=e.split(cce);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function rL(e){let t=``;if(LI(e))t=e;else if(MI(e))for(let n=0;n<e.length;n++){let r=rL(e[n]);r&&(t+=r+` `)}else if(zI(e))for(let n in e)e[n]&&(t+=n+` `);return t.trim()}var iL=`itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`,dce=SI(iL);iL+``;function aL(e){return!!e||e===``}function fce(e,t){if(e.length!==t.length)return!1;let n=!0;for(let r=0;n&&r<e.length;r++)n=oL(e[r],t[r]);return n}function oL(e,t){if(e===t)return!0;let n=FI(e),r=FI(t);if(n||r)return n&&r?e.getTime()===t.getTime():!1;if(n=RI(e),r=RI(t),n||r)return e===t;if(n=MI(e),r=MI(t),n||r)return n&&r?fce(e,t):!1;if(n=zI(e),r=zI(t),n||r){if(!n||!r||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e){let r=e.hasOwnProperty(n),i=t.hasOwnProperty(n);if(r&&!i||!r&&i||!oL(e[n],t[n]))return!1}}return String(e)===String(t)}var sL=e=>!!(e&&e.__v_isRef===!0),q=e=>LI(e)?e:e==null?``:MI(e)||zI(e)&&(e.toString===VI||!II(e.toString))?sL(e)?q(e.value):JSON.stringify(e,cL,2):String(e),cL=(e,t)=>sL(t)?cL(e,t.value):NI(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((e,[t,n],r)=>(e[lL(t,r)+` =>`]=n,e),{})}:PI(t)?{[`Set(${t.size})`]:[...t.values()].map(e=>lL(e))}:RI(t)?lL(t):zI(t)&&!MI(t)&&!UI(t)?String(t):t,lL=(e,t=``)=>RI(e)?`Symbol(${e.description??t})`:e,uL,pce=class{constructor(e=!1){this.detached=e,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!e&&uL&&(uL.active?(this.parent=uL,this.index=(uL.scopes||=[]).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let e,t;if(this.scopes)for(e=0,t=this.scopes.length;e<t;e++)this.scopes[e].pause();for(e=0,t=this.effects.length;e<t;e++)this.effects[e].pause()}}resume(){if(this._active&&this._isPaused){this._isPaused=!1;let e,t;if(this.scopes)for(e=0,t=this.scopes.length;e<t;e++)this.scopes[e].resume();for(e=0,t=this.effects.length;e<t;e++)this.effects[e].resume()}}run(e){if(this._active){let t=uL;try{return uL=this,e()}finally{uL=t}}}on(){++this._on===1&&(this.prevScope=uL,uL=this)}off(){if(this._on>0&&--this._on===0){if(uL===this)uL=this.prevScope;else{let e=uL;for(;e;){if(e.prevScope===this){e.prevScope=this.prevScope;break}e=e.prevScope}}this.prevScope=void 0}}stop(e){if(this._active){this._active=!1;let t,n;for(t=0,n=this.effects.length;t<n;t++)this.effects[t].stop();for(this.effects.length=0,t=0,n=this.cleanups.length;t<n;t++)this.cleanups[t]();if(this.cleanups.length=0,this.scopes){for(t=0,n=this.scopes.length;t<n;t++)this.scopes[t].stop(!0);this.scopes.length=0}if(!this.detached&&this.parent&&!e){let e=this.parent.scopes.pop();e&&e!==this&&(this.parent.scopes[this.index]=e,e.index=this.index)}this.parent=void 0}}};function mce(){return uL}var dL,fL=new WeakSet,pL=class{constructor(e){this.fn=e,this.deps=void 0,this.depsTail=void 0,this.flags=5,this.next=void 0,this.cleanup=void 0,this.scheduler=void 0,uL&&(uL.active?uL.effects.push(this):this.flags&=-2)}pause(){this.flags|=64}resume(){this.flags&64&&(this.flags&=-65,fL.has(this)&&(fL.delete(this),this.trigger()))}notify(){this.flags&2&&!(this.flags&32)||this.flags&8||_L(this)}run(){if(!(this.flags&1))return this.fn();this.flags|=2,kL(this),bL(this);let e=dL,t=TL;dL=this,TL=!0;try{return this.fn()}finally{xL(this),dL=e,TL=t,this.flags&=-3}}stop(){if(this.flags&1){for(let e=this.deps;e;e=e.nextDep)wL(e);this.deps=this.depsTail=void 0,kL(this),this.onStop&&this.onStop(),this.flags&=-2}}trigger(){this.flags&64?fL.add(this):this.scheduler?this.scheduler():this.runIfDirty()}runIfDirty(){SL(this)&&this.run()}get dirty(){return SL(this)}},mL=0,hL,gL;function _L(e,t=!1){if(e.flags|=8,t){e.next=gL,gL=e;return}e.next=hL,hL=e}function vL(){mL++}function yL(){if(--mL>0)return;if(gL){let e=gL;for(gL=void 0;e;){let t=e.next;e.next=void 0,e.flags&=-9,e=t}}let e;for(;hL;){let t=hL;for(hL=void 0;t;){let n=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(t){e||=t}t=n}}if(e)throw e}function bL(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function xL(e){let t,n=e.depsTail,r=n;for(;r;){let e=r.prevDep;r.version===-1?(r===n&&(n=e),wL(r),hce(r)):t=r,r.dep.activeLink=r.prevActiveLink,r.prevActiveLink=void 0,r=e}e.deps=t,e.depsTail=n}function SL(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(CL(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function CL(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===AL)||(e.globalVersion=AL,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!SL(e))))return;e.flags|=2;let t=e.dep,n=dL,r=TL;dL=e,TL=!0;try{bL(e);let n=e.fn(e._value);(t.version===0||ZI(n,e._value))&&(e.flags|=128,e._value=n,t.version++)}catch(e){throw t.version++,e}finally{dL=n,TL=r,xL(e),e.flags&=-3}}function wL(e,t=!1){let{dep:n,prevSub:r,nextSub:i}=e;if(r&&(r.nextSub=i,e.prevSub=void 0),i&&(i.prevSub=r,e.nextSub=void 0),n.subs===e&&(n.subs=r,!r&&n.computed)){n.computed.flags&=-5;for(let e=n.computed.deps;e;e=e.nextDep)wL(e,!0)}!t&&!--n.sc&&n.map&&n.map.delete(n.key)}function hce(e){let{prevDep:t,nextDep:n}=e;t&&(t.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=t,e.nextDep=void 0)}var TL=!0,EL=[];function DL(){EL.push(TL),TL=!1}function OL(){let e=EL.pop();TL=e===void 0||e}function kL(e){let{cleanup:t}=e;if(e.cleanup=void 0,t){let e=dL;dL=void 0;try{t()}finally{dL=e}}}var AL=0,gce=class{constructor(e,t){this.sub=e,this.dep=t,this.version=t.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}},jL=class{constructor(e){this.computed=e,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(e){if(!dL||!TL||dL===this.computed)return;let t=this.activeLink;if(t===void 0||t.sub!==dL)t=this.activeLink=new gce(dL,this),dL.deps?(t.prevDep=dL.depsTail,dL.depsTail.nextDep=t,dL.depsTail=t):dL.deps=dL.depsTail=t,ML(t);else if(t.version===-1&&(t.version=this.version,t.nextDep)){let e=t.nextDep;e.prevDep=t.prevDep,t.prevDep&&(t.prevDep.nextDep=e),t.prevDep=dL.depsTail,t.nextDep=void 0,dL.depsTail.nextDep=t,dL.depsTail=t,dL.deps===t&&(dL.deps=e)}return t}trigger(e){this.version++,AL++,this.notify(e)}notify(e){vL();try{for(let e=this.subs;e;e=e.prevSub)e.sub.notify()&&e.sub.dep.notify()}finally{yL()}}};function ML(e){if(e.dep.sc++,e.sub.flags&4){let t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let e=t.deps;e;e=e.nextDep)ML(e)}let n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}var NL=new WeakMap,PL=Symbol(``),FL=Symbol(``),IL=Symbol(``);function LL(e,t,n){if(TL&&dL){let t=NL.get(e);t||NL.set(e,t=new Map);let r=t.get(n);r||(t.set(n,r=new jL),r.map=t,r.key=n),r.track()}}function RL(e,t,n,r,i,a){let o=NL.get(e);if(!o){AL++;return}let s=e=>{e&&e.trigger()};if(vL(),t===`clear`)o.forEach(s);else{let i=MI(e),a=i&&WI(n);if(i&&n===`length`){let e=Number(r);o.forEach((t,n)=>{(n===`length`||n===IL||!RI(n)&&n>=e)&&s(t)})}else switch((n!==void 0||o.has(void 0))&&s(o.get(n)),a&&s(o.get(IL)),t){case`add`:i?a&&s(o.get(`length`)):(s(o.get(PL)),NI(e)&&s(o.get(FL)));break;case`delete`:i||(s(o.get(PL)),NI(e)&&s(o.get(FL)));break;case`set`:NI(e)&&s(o.get(PL));break}}yL()}function zL(e){let t=wR(e);return t===e?t:(LL(t,`iterate`,IL),SR(e)?t:t.map(ER))}function BL(e){return LL(e=wR(e),`iterate`,IL),e}function VL(e,t){return xR(e)?DR(bR(e)?ER(t):t):ER(t)}var _ce={__proto__:null,[Symbol.iterator](){return HL(this,Symbol.iterator,e=>VL(this,e))},concat(...e){return zL(this).concat(...e.map(e=>MI(e)?zL(e):e))},entries(){return HL(this,`entries`,e=>(e[1]=VL(this,e[1]),e))},every(e,t){return UL(this,`every`,e,t,void 0,arguments)},filter(e,t){return UL(this,`filter`,e,t,e=>e.map(e=>VL(this,e)),arguments)},find(e,t){return UL(this,`find`,e,t,e=>VL(this,e),arguments)},findIndex(e,t){return UL(this,`findIndex`,e,t,void 0,arguments)},findLast(e,t){return UL(this,`findLast`,e,t,e=>VL(this,e),arguments)},findLastIndex(e,t){return UL(this,`findLastIndex`,e,t,void 0,arguments)},forEach(e,t){return UL(this,`forEach`,e,t,void 0,arguments)},includes(...e){return GL(this,`includes`,e)},indexOf(...e){return GL(this,`indexOf`,e)},join(e){return zL(this).join(e)},lastIndexOf(...e){return GL(this,`lastIndexOf`,e)},map(e,t){return UL(this,`map`,e,t,void 0,arguments)},pop(){return KL(this,`pop`)},push(...e){return KL(this,`push`,e)},reduce(e,...t){return WL(this,`reduce`,e,t)},reduceRight(e,...t){return WL(this,`reduceRight`,e,t)},shift(){return KL(this,`shift`)},some(e,t){return UL(this,`some`,e,t,void 0,arguments)},splice(...e){return KL(this,`splice`,e)},toReversed(){return zL(this).toReversed()},toSorted(e){return zL(this).toSorted(e)},toSpliced(...e){return zL(this).toSpliced(...e)},unshift(...e){return KL(this,`unshift`,e)},values(){return HL(this,`values`,e=>VL(this,e))}};function HL(e,t,n){let r=BL(e),i=r[t]();return r!==e&&!SR(e)&&(i._next=i.next,i.next=()=>{let e=i._next();return e.done||(e.value=n(e.value)),e}),i}var vce=Array.prototype;function UL(e,t,n,r,i,a){let o=BL(e),s=o!==e&&!SR(e),c=o[t];if(c!==vce[t]){let t=c.apply(e,a);return s?ER(t):t}let l=n;o!==e&&(s?l=function(t,r){return n.call(this,VL(e,t),r,e)}:n.length>2&&(l=function(t,r){return n.call(this,t,r,e)}));let u=c.call(o,l,r);return s&&i?i(u):u}function WL(e,t,n,r){let i=BL(e),a=i!==e&&!SR(e),o=n,s=!1;i!==e&&(a?(s=r.length===0,o=function(t,r,i){return s&&(s=!1,t=VL(e,t)),n.call(this,t,VL(e,r),i,e)}):n.length>3&&(o=function(t,r,i){return n.call(this,t,r,i,e)}));let c=i[t](o,...r);return s?VL(e,c):c}function GL(e,t,n){let r=wR(e);LL(r,`iterate`,IL);let i=r[t](...n);return(i===-1||i===!1)&&CR(n[0])?(n[0]=wR(n[0]),r[t](...n)):i}function KL(e,t,n=[]){DL(),vL();let r=wR(e)[t].apply(e,n);return yL(),OL(),r}var qL=SI(`__proto__,__v_isRef,__isVue`),JL=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!==`arguments`&&e!==`caller`).map(e=>Symbol[e]).filter(RI));function YL(e){RI(e)||(e=String(e));let t=wR(this);return LL(t,`has`,e),t.hasOwnProperty(e)}var XL=class{constructor(e=!1,t=!1){this._isReadonly=e,this._isShallow=t}get(e,t,n){if(t===`__v_skip`)return e.__v_skip;let r=this._isReadonly,i=this._isShallow;if(t===`__v_isReactive`)return!r;if(t===`__v_isReadonly`)return r;if(t===`__v_isShallow`)return i;if(t===`__v_raw`)return n===(r?i?mR:pR:i?fR:dR).get(e)||Object.getPrototypeOf(e)===Object.getPrototypeOf(n)?e:void 0;let a=MI(e);if(!r){let e;if(a&&(e=_ce[t]))return e;if(t===`hasOwnProperty`)return YL}let o=Reflect.get(e,t,OR(e)?e:n);if((RI(t)?JL.has(t):qL(t))||(r||LL(e,`get`,t),i))return o;if(OR(o)){let e=a&&WI(t)?o:o.value;return r&&zI(e)?vR(e):e}return zI(o)?r?vR(o):gR(o):o}},ZL=class extends XL{constructor(e=!1){super(!1,e)}set(e,t,n,r){let i=e[t],a=MI(e)&&WI(t);if(!this._isShallow){let e=xR(i);if(!SR(n)&&!xR(n)&&(i=wR(i),n=wR(n)),!a&&OR(i)&&!OR(n))return e||(i.value=n),!0}let o=a?Number(t)<e.length:jI(e,t),s=Reflect.set(e,t,n,OR(e)?e:r);return e===wR(r)&&s&&(o?ZI(n,i)&&RL(e,`set`,t,n,i):RL(e,`add`,t,n)),s}deleteProperty(e,t){let n=jI(e,t),r=e[t],i=Reflect.deleteProperty(e,t);return i&&n&&RL(e,`delete`,t,void 0,r),i}has(e,t){let n=Reflect.has(e,t);return(!RI(t)||!JL.has(t))&&LL(e,`has`,t),n}ownKeys(e){return LL(e,`iterate`,MI(e)?`length`:PL),Reflect.ownKeys(e)}},QL=class extends XL{constructor(e=!1){super(!0,e)}set(e,t){return!0}deleteProperty(e,t){return!0}},$L=new ZL,eR=new QL,tR=new ZL(!0),nR=e=>e,rR=e=>Reflect.getPrototypeOf(e);function iR(e,t,n){return function(...r){let i=this.__v_raw,a=wR(i),o=NI(a),s=e===`entries`||e===Symbol.iterator&&o,c=e===`keys`&&o,l=i[e](...r),u=n?nR:t?DR:ER;return!t&&LL(a,`iterate`,c?FL:PL),kI(Object.create(l),{next(){let{value:e,done:t}=l.next();return t?{value:e,done:t}:{value:s?[u(e[0]),u(e[1])]:u(e),done:t}}})}}function aR(e){return function(...t){return e===`delete`?!1:e===`clear`?void 0:this}}function oR(e,t){let n={get(n){let r=this.__v_raw,i=wR(r),a=wR(n);e||(ZI(n,a)&&LL(i,`get`,n),LL(i,`get`,a));let{has:o}=rR(i),s=t?nR:e?DR:ER;if(o.call(i,n))return s(r.get(n));if(o.call(i,a))return s(r.get(a));r!==i&&r.get(n)},get size(){let t=this.__v_raw;return!e&&LL(wR(t),`iterate`,PL),t.size},has(t){let n=this.__v_raw,r=wR(n),i=wR(t);return e||(ZI(t,i)&&LL(r,`has`,t),LL(r,`has`,i)),t===i?n.has(t):n.has(t)||n.has(i)},forEach(n,r){let i=this,a=i.__v_raw,o=wR(a),s=t?nR:e?DR:ER;return!e&&LL(o,`iterate`,PL),a.forEach((e,t)=>n.call(r,s(e),s(t),i))}};return kI(n,e?{add:aR(`add`),set:aR(`set`),delete:aR(`delete`),clear:aR(`clear`)}:{add(e){let n=wR(this),r=rR(n),i=wR(e),a=!t&&!SR(e)&&!xR(e)?i:e;return r.has.call(n,a)||ZI(e,a)&&r.has.call(n,e)||ZI(i,a)&&r.has.call(n,i)||(n.add(a),RL(n,`add`,a,a)),this},set(e,n){!t&&!SR(n)&&!xR(n)&&(n=wR(n));let r=wR(this),{has:i,get:a}=rR(r),o=i.call(r,e);o||=(e=wR(e),i.call(r,e));let s=a.call(r,e);return r.set(e,n),o?ZI(n,s)&&RL(r,`set`,e,n,s):RL(r,`add`,e,n),this},delete(e){let t=wR(this),{has:n,get:r}=rR(t),i=n.call(t,e);i||=(e=wR(e),n.call(t,e));let a=r?r.call(t,e):void 0,o=t.delete(e);return i&&RL(t,`delete`,e,void 0,a),o},clear(){let e=wR(this),t=e.size!==0,n=e.clear();return t&&RL(e,`clear`,void 0,void 0,void 0),n}}),[`keys`,`values`,`entries`,Symbol.iterator].forEach(r=>{n[r]=iR(r,e,t)}),n}function sR(e,t){let n=oR(e,t);return(t,r,i)=>r===`__v_isReactive`?!e:r===`__v_isReadonly`?e:r===`__v_raw`?t:Reflect.get(jI(n,r)&&r in t?n:t,r,i)}var cR={get:sR(!1,!1)},lR={get:sR(!1,!0)},uR={get:sR(!0,!1)},dR=new WeakMap,fR=new WeakMap,pR=new WeakMap,mR=new WeakMap;function hR(e){switch(e){case`Object`:case`Array`:return 1;case`Map`:case`Set`:case`WeakMap`:case`WeakSet`:return 2;default:return 0}}function gR(e){return xR(e)?e:yR(e,!1,$L,cR,dR)}function _R(e){return yR(e,!1,tR,lR,fR)}function vR(e){return yR(e,!0,eR,uR,pR)}function yR(e,t,n,r,i){if(!zI(e)||e.__v_raw&&!(t&&e.__v_isReactive)||e.__v_skip||!Object.isExtensible(e))return e;let a=i.get(e);if(a)return a;let o=hR(nce(e));if(o===0)return e;let s=new Proxy(e,o===2?r:n);return i.set(e,s),s}function bR(e){return xR(e)?bR(e.__v_raw):!!(e&&e.__v_isReactive)}function xR(e){return!!(e&&e.__v_isReadonly)}function SR(e){return!!(e&&e.__v_isShallow)}function CR(e){return e?!!e.__v_raw:!1}function wR(e){let t=e&&e.__v_raw;return t?wR(t):e}function TR(e){return!jI(e,`__v_skip`)&&Object.isExtensible(e)&&$I(e,`__v_skip`,!0),e}var ER=e=>zI(e)?gR(e):e,DR=e=>zI(e)?vR(e):e;function OR(e){return e?e.__v_isRef===!0:!1}function kR(e){return jR(e,!1)}function AR(e){return jR(e,!0)}function jR(e,t){return OR(e)?e:new MR(e,t)}var MR=class{constructor(e,t){this.dep=new jL,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=t?e:wR(e),this._value=t?e:ER(e),this.__v_isShallow=t}get value(){return this.dep.track(),this._value}set value(e){let t=this._rawValue,n=this.__v_isShallow||SR(e)||xR(e);e=n?e:wR(e),ZI(e,t)&&(this._rawValue=e,this._value=n?e:ER(e),this.dep.trigger())}};function NR(e){e.dep&&e.dep.trigger()}function J(e){return OR(e)?e.value:e}var PR={get:(e,t,n)=>t===`__v_raw`?e:J(Reflect.get(e,t,n)),set:(e,t,n,r)=>{let i=e[t];return OR(i)&&!OR(n)?(i.value=n,!0):Reflect.set(e,t,n,r)}};function FR(e){return bR(e)?e:new Proxy(e,PR)}var IR=class{constructor(e,t,n){this.fn=e,this.setter=t,this._value=void 0,this.dep=new jL(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=AL-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!t,this.isSSR=n}notify(){if(this.flags|=16,!(this.flags&8)&&dL!==this)return _L(this,!0),!0}get value(){let e=this.dep.track();return CL(this),e&&(e.version=this.dep.version),this._value}set value(e){this.setter&&this.setter(e)}};function LR(e,t,n=!1){let r,i;return II(e)?r=e:(r=e.get,i=e.set),new IR(r,i,n)}var RR={},zR=new WeakMap,BR=void 0;function VR(e,t=!1,n=BR){if(n){let t=zR.get(n);t||zR.set(n,t=[]),t.push(e)}}function HR(e,t,n=CI){let{immediate:r,deep:i,once:a,scheduler:o,augmentJob:s,call:c}=n,l=e=>i?e:SR(e)||i===!1||i===0?UR(e,1):UR(e),u,d,f,p,m=!1,h=!1;if(OR(e)?(d=()=>e.value,m=SR(e)):bR(e)?(d=()=>l(e),m=!0):MI(e)?(h=!0,m=e.some(e=>bR(e)||SR(e)),d=()=>e.map(e=>{if(OR(e))return e.value;if(bR(e))return l(e);if(II(e))return c?c(e,2):e()})):d=II(e)?t?c?()=>c(e,2):e:()=>{if(f){DL();try{f()}finally{OL()}}let t=BR;BR=u;try{return c?c(e,3,[p]):e(p)}finally{BR=t}}:TI,t&&i){let e=d,t=i===!0?1/0:i;d=()=>UR(e(),t)}let g=mce(),_=()=>{u.stop(),g&&g.active&&AI(g.effects,u)};if(a&&t){let e=t;t=(...t)=>{let n=e(...t);return _(),n}}let v=h?Array(e.length).fill(RR):RR,y=e=>{if(!(!(u.flags&1)||!u.dirty&&!e))if(t){let n=u.run();if(e||i||m||(h?n.some((e,t)=>ZI(e,v[t])):ZI(n,v))){f&&f();let e=BR;BR=u;try{let e=[n,v===RR?void 0:h&&v[0]===RR?[]:v,p];v=n,c?c(t,3,e):t(...e)}finally{BR=e}}}else u.run()};return s&&s(y),u=new pL(d),u.scheduler=o?()=>o(y,!1):y,p=e=>VR(e,!1,u),f=u.onStop=()=>{let e=zR.get(u);if(e){if(c)c(e,4);else for(let t of e)t();zR.delete(u)}},t?r?y(!0):v=u.run():o?o(y.bind(null,!0),!0):u.run(),_.pause=u.pause.bind(u),_.resume=u.resume.bind(u),_.stop=_,_}function UR(e,t=1/0,n){if(t<=0||!zI(e)||e.__v_skip||(n||=new Map,(n.get(e)||0)>=t))return e;if(n.set(e,t),t--,OR(e))UR(e.value,t,n);else if(MI(e))for(let r=0;r<e.length;r++)UR(e[r],t,n);else if(PI(e)||NI(e))e.forEach(e=>{UR(e,t,n)});else if(UI(e)){for(let r in e)UR(e[r],t,n);for(let r of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,r)&&UR(e[r],t,n)}return e}function WR(e,t,n,r){try{return r?e(...r):e()}catch(e){KR(e,t,n)}}function GR(e,t,n,r){if(II(e)){let i=WR(e,t,n,r);return i&&BI(i)&&i.catch(e=>{KR(e,t,n)}),i}if(MI(e)){let i=[];for(let a=0;a<e.length;a++)i.push(GR(e[a],t,n,r));return i}}function KR(e,t,n,r=!0){let i=t?t.vnode:null,{errorHandler:a,throwUnhandledErrorInProduction:o}=t&&t.appContext.config||CI;if(t){let r=t.parent,i=t.proxy,o=`https://vuejs.org/error-reference/#runtime-${n}`;for(;r;){let t=r.ec;if(t){for(let n=0;n<t.length;n++)if(t[n](e,i,o)===!1)return}r=r.parent}if(a){DL(),WR(a,null,10,[e,i,o]),OL();return}}qR(e,n,i,r,o)}function qR(e,t,n,r=!0,i=!1){if(i)throw e;console.error(e)}var JR=[],YR=-1,XR=[],ZR=null,QR=0,$R=Promise.resolve(),ez=null;function tz(e){let t=ez||$R;return e?t.then(this?e.bind(this):e):t}function nz(e){let t=YR+1,n=JR.length;for(;t<n;){let r=t+n>>>1,i=JR[r],a=cz(i);a<e||a===e&&i.flags&2?t=r+1:n=r}return t}function rz(e){if(!(e.flags&1)){let t=cz(e),n=JR[JR.length-1];!n||!(e.flags&2)&&t>=cz(n)?JR.push(e):JR.splice(nz(t),0,e),e.flags|=1,iz()}}function iz(){ez||=$R.then(lz)}function az(e){MI(e)?XR.push(...e):ZR&&e.id===-1?ZR.splice(QR+1,0,e):e.flags&1||(XR.push(e),e.flags|=1),iz()}function oz(e,t,n=YR+1){for(;n<JR.length;n++){let t=JR[n];if(t&&t.flags&2){if(e&&t.id!==e.uid)continue;JR.splice(n,1),n--,t.flags&4&&(t.flags&=-2),t(),t.flags&4||(t.flags&=-2)}}}function sz(e){if(XR.length){let e=[...new Set(XR)].sort((e,t)=>cz(e)-cz(t));if(XR.length=0,ZR){ZR.push(...e);return}for(ZR=e,QR=0;QR<ZR.length;QR++){let e=ZR[QR];e.flags&4&&(e.flags&=-2),e.flags&8||e(),e.flags&=-2}ZR=null,QR=0}}var cz=e=>e.id==null?e.flags&2?-1:1/0:e.id;function lz(e){try{for(YR=0;YR<JR.length;YR++){let e=JR[YR];e&&!(e.flags&8)&&(e.flags&4&&(e.flags&=-2),WR(e,e.i,e.i?15:14),e.flags&4||(e.flags&=-2))}}finally{for(;YR<JR.length;YR++){let e=JR[YR];e&&(e.flags&=-2)}YR=-1,JR.length=0,sz(e),ez=null,(JR.length||XR.length)&&lz(e)}}var uz=null,dz=null;function fz(e){let t=uz;return uz=e,dz=e&&e.type.__scopeId||null,t}function pz(e,t=uz,n){if(!t||e._n)return e;let r=(...n)=>{r._d&&JV(-1);let i=fz(t),a;try{a=e(...n)}finally{fz(i),r._d&&JV(1)}return a};return r._n=!0,r._c=!0,r._d=!0,r}function mz(e,t){if(uz===null)return e;let n=AH(uz),r=e.dirs||=[];for(let e=0;e<t.length;e++){let[i,a,o,s=CI]=t[e];i&&(II(i)&&(i={mounted:i,updated:i}),i.deep&&UR(a),r.push({dir:i,instance:n,value:a,oldValue:void 0,arg:o,modifiers:s}))}return e}function hz(e,t,n,r){let i=e.dirs,a=t&&t.dirs;for(let o=0;o<i.length;o++){let s=i[o];a&&(s.oldValue=a[o].value);let c=s.dir[r];c&&(DL(),GR(c,n,8,[e.el,s,e,t]),OL())}}function gz(e,t){if(mH){let n=mH.provides,r=mH.parent&&mH.parent.provides;r===n&&(n=mH.provides=Object.create(r)),n[e]=t}}function _z(e,t,n=!1){let r=hH();if(r||XB){let i=XB?XB._context.provides:r?r.parent==null||r.ce?r.vnode.appContext&&r.vnode.appContext.provides:r.parent.provides:void 0;if(i&&e in i)return i[e];if(arguments.length>1)return n&&II(t)?t.call(r&&r.proxy):t}}var vz=Symbol.for(`v-scx`),yz=()=>_z(vz);function bz(e,t,n){return xz(e,t,n)}function xz(e,t,n=CI){let{immediate:r,deep:i,flush:a,once:o}=n,s=kI({},n),c=t&&r||!t&&a!==`post`,l;if(xH){if(a===`sync`){let e=yz();l=e.__watcherHandles||=[]}else if(!c){let e=()=>{};return e.stop=TI,e.resume=TI,e.pause=TI,e}}let u=mH;s.call=(e,t,n)=>GR(e,u,t,n);let d=!1;a===`post`?s.scheduler=e=>{DV(e,u&&u.suspense)}:a!==`sync`&&(d=!0,s.scheduler=(e,t)=>{t?e():rz(e)}),s.augmentJob=e=>{t&&(e.flags|=4),d&&(e.flags|=2,u&&(e.id=u.uid,e.i=u))};let f=HR(e,t,s);return xH&&(l?l.push(f):c&&f()),f}function Sz(e,t,n){let r=this.proxy,i=LI(e)?e.includes(`.`)?Cz(r,e):()=>r[e]:e.bind(r,r),a;II(t)?a=t:(a=t.handler,n=t);let o=vH(this),s=xz(i,a.bind(r),n);return o(),s}function Cz(e,t){let n=t.split(`.`);return()=>{let t=e;for(let e=0;e<n.length&&t;e++)t=t[n[e]];return t}}var wz=new WeakMap,Tz=Symbol(`_vte`),Ez=e=>e.__isTeleport,Dz=e=>e&&(e.disabled||e.disabled===``),Oz=e=>e&&(e.defer||e.defer===``),kz=e=>typeof SVGElement<`u`&&e instanceof SVGElement,Az=e=>typeof MathMLElement==`function`&&e instanceof MathMLElement,jz=(e,t)=>{let n=e&&e.to;return LI(n)?t?t(n):null:n},Mz={name:`Teleport`,__isTeleport:!0,process(e,t,n,r,i,a,o,s,c,l){let{mc:u,pc:d,pbc:f,o:{insert:p,querySelector:m,createText:h,createComment:g,parentNode:_}}=l,v=Dz(t.props),{dynamicChildren:y}=t,b=(e,t,n)=>{e.shapeFlag&16&&u(e.children,t,n,i,a,o,s,c)},x=(e=t)=>{let n=Dz(e.props),r=e.target=jz(e.props,m),a=Lz(r,e,h,p);r&&(o!==`svg`&&kz(r)?o=`svg`:o!==`mathml`&&Az(r)&&(o=`mathml`),i&&i.isCE&&(i.ce._teleportTargets||(i.ce._teleportTargets=new Set)).add(r),n||(b(e,r,a),Iz(e,!1)))},S=e=>{let t=()=>{if(wz.get(e)===t){if(wz.delete(e),Dz(e.props)){let t=_(e.el)||n;b(e,t,e.anchor),Iz(e,!0)}x(e)}};wz.set(e,t),DV(t,a)};if(e==null){let e=t.el=h(``),i=t.anchor=h(``);if(p(e,n,r),p(i,n,r),Oz(t.props)||a&&a.pendingBranch){S(t);return}v&&(b(t,n,i),Iz(t,!0)),x()}else{t.el=e.el;let r=t.anchor=e.anchor,u=wz.get(e);if(u){u.flags|=8,wz.delete(e),S(t);return}t.targetStart=e.targetStart;let p=t.target=e.target,h=t.targetAnchor=e.targetAnchor,g=Dz(e.props),_=g?n:p,b=g?r:h;if(o===`svg`||kz(p)?o=`svg`:(o===`mathml`||Az(p))&&(o=`mathml`),y?(f(e.dynamicChildren,y,_,i,a,o,s),NV(e,t,!0)):c||d(e,t,_,b,i,a,o,s,!1),v)g?t.props&&e.props&&t.props.to!==e.props.to&&(t.props.to=e.props.to):Nz(t,n,r,l,1);else if((t.props&&t.props.to)!==(e.props&&e.props.to)){let e=jz(t.props,m);e&&(t.target=e,Nz(t,e,null,l,0))}else g&&Nz(t,p,h,l,1);Iz(t,v)}},remove(e,t,n,{um:r,o:{remove:i}},a){let{shapeFlag:o,children:s,anchor:c,targetStart:l,targetAnchor:u,target:d,props:f}=e,p=Dz(f),m=a||!p,h=wz.get(e);if(h&&(h.flags|=8,wz.delete(e)),d&&(i(l),i(u)),a&&i(c),!h&&(p||d)&&o&16)for(let e=0;e<s.length;e++){let i=s[e];r(i,t,n,m,!!i.dynamicChildren)}},move:Nz,hydrate:Pz};function Nz(e,t,n,{o:{insert:r},m:i},a=2){a===0&&r(e.targetAnchor,t,n);let{el:o,anchor:s,shapeFlag:c,children:l,props:u}=e,d=a===2;if(d&&r(o,t,n),!wz.has(e)&&(!d||Dz(u))&&c&16)for(let e=0;e<l.length;e++)i(l[e],t,n,2);d&&r(s,t,n)}function Pz(e,t,n,r,i,a,{o:{nextSibling:o,parentNode:s,querySelector:c,insert:l,createText:u}},d){function f(e,n){let r=n;for(;r;){if(r&&r.nodeType===8){if(r.data===`teleport start anchor`)t.targetStart=r;else if(r.data===`teleport anchor`){t.targetAnchor=r,e._lpa=t.targetAnchor&&o(t.targetAnchor);break}}r=o(r)}}function p(e,t){t.anchor=d(o(e),t,s(e),n,r,i,a)}let m=t.target=jz(t.props,c),h=Dz(t.props);if(m){let c=m._lpa||m.firstChild;t.shapeFlag&16&&(h?(p(e,t),f(m,c),t.targetAnchor||Lz(m,t,u,l,s(e)===m?e:null)):(t.anchor=o(e),f(m,c),t.targetAnchor||Lz(m,t,u,l),d(c&&o(c),t,m,n,r,i,a))),Iz(t,h)}else h&&t.shapeFlag&16&&(p(e,t),t.targetStart=e,t.targetAnchor=o(e));return t.anchor&&o(t.anchor)}var Fz=Mz;function Iz(e,t){let n=e.ctx;if(n&&n.ut){let r,i;for(t?(r=e.el,i=e.anchor):(r=e.targetStart,i=e.targetAnchor);r&&r!==i;)r.nodeType===1&&r.setAttribute(`data-v-owner`,n.uid),r=r.nextSibling;n.ut()}}function Lz(e,t,n,r,i=null){let a=t.targetStart=n(``),o=t.targetAnchor=n(``);return a[Tz]=o,e&&(r(a,e,i),r(o,e,i)),o}var Rz=Symbol(`_leaveCb`),zz=Symbol(`_enterCb`);function Bz(){let e={isMounted:!1,isLeaving:!1,isUnmounting:!1,leavingVNodes:new Map};return mB(()=>{e.isMounted=!0}),_B(()=>{e.isUnmounting=!0}),e}var Vz=[Function,Array],Hz={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:Vz,onEnter:Vz,onAfterEnter:Vz,onEnterCancelled:Vz,onBeforeLeave:Vz,onLeave:Vz,onAfterLeave:Vz,onLeaveCancelled:Vz,onBeforeAppear:Vz,onAppear:Vz,onAfterAppear:Vz,onAppearCancelled:Vz},Uz=e=>{let t=e.subTree;return t.component?Uz(t.component):t},Wz={name:`BaseTransition`,props:Hz,setup(e,{slots:t}){let n=hH(),r=Bz();return()=>{let i=t.default&&Qz(t.default(),!0),a=i&&i.length?Gz(i):n.subTree?Q():void 0;if(!a)return;let o=wR(e),{mode:s}=o;if(r.isLeaving)return Yz(a);let c=Xz(a);if(!c)return Yz(a);let l=Jz(c,o,r,n,e=>l=e);c.type!==HV&&Zz(c,l);let u=n.subTree&&Xz(n.subTree);if(u&&u.type!==HV&&!QV(u,c)&&Uz(n).type!==HV){let e=Jz(u,o,r,n);if(Zz(u,e),s===`out-in`&&c.type!==HV)return r.isLeaving=!0,e.afterLeave=()=>{r.isLeaving=!1,n.job.flags&8||n.update(),delete e.afterLeave,u=void 0},Yz(a);s===`in-out`&&c.type!==HV?e.delayLeave=(e,t,n)=>{let i=qz(r,u);i[String(u.key)]=u,e[Rz]=()=>{t(),e[Rz]=void 0,delete l.delayedLeave,u=void 0},l.delayedLeave=()=>{n(),delete l.delayedLeave,u=void 0}}:u=void 0}else u&&=void 0;return a}}};function Gz(e){let t=e[0];if(e.length>1){for(let n of e)if(n.type!==HV){t=n;break}}return t}var Kz=Wz;function qz(e,t){let{leavingVNodes:n}=e,r=n.get(t.type);return r||(r=Object.create(null),n.set(t.type,r)),r}function Jz(e,t,n,r,i){let{appear:a,mode:o,persisted:s=!1,onBeforeEnter:c,onEnter:l,onAfterEnter:u,onEnterCancelled:d,onBeforeLeave:f,onLeave:p,onAfterLeave:m,onLeaveCancelled:h,onBeforeAppear:g,onAppear:_,onAfterAppear:v,onAppearCancelled:y}=t,b=String(e.key),x=qz(n,e),S=(e,t)=>{e&&GR(e,r,9,t)},ee=(e,t)=>{let n=t[1];S(e,t),MI(e)?e.every(e=>e.length<=1)&&n():e.length<=1&&n()},C={mode:o,persisted:s,beforeEnter(t){let r=c;if(!n.isMounted)if(a)r=g||c;else return;t[Rz]&&t[Rz](!0);let i=x[b];i&&QV(e,i)&&i.el[Rz]&&i.el[Rz](),S(r,[t])},enter(t){if(x[b]===e)return;let r=l,i=u,o=d;if(!n.isMounted)if(a)r=_||l,i=v||u,o=y||d;else return;let s=!1;t[zz]=e=>{s||(s=!0,S(e?o:i,[t]),C.delayedLeave&&C.delayedLeave(),t[zz]=void 0)};let c=t[zz].bind(null,!1);r?ee(r,[t,c]):c()},leave(t,r){let i=String(e.key);if(t[zz]&&t[zz](!0),n.isUnmounting)return r();S(f,[t]);let a=!1;t[Rz]=n=>{a||(a=!0,r(),S(n?h:m,[t]),t[Rz]=void 0,x[i]===e&&delete x[i])};let o=t[Rz].bind(null,!1);x[i]=e,p?ee(p,[t,o]):o()},clone(e){let a=Jz(e,t,n,r,i);return i&&i(a),a}};return C}function Yz(e){if(oB(e))return e=iH(e),e.children=null,e}function Xz(e){if(!oB(e))return Ez(e.type)&&e.children?Gz(e.children):e;if(e.component)return e.component.subTree;let{shapeFlag:t,children:n}=e;if(n){if(t&16)return n[0];if(t&32&&II(n.default))return n.default()}}function Zz(e,t){e.shapeFlag&6&&e.component?(e.transition=t,Zz(e.component.subTree,t)):e.shapeFlag&128?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function Qz(e,t=!1,n){let r=[],i=0;for(let a=0;a<e.length;a++){let o=e[a],s=n==null?o.key:String(n)+String(o.key==null?a:o.key);o.type===BV?(o.patchFlag&128&&i++,r=r.concat(Qz(o.children,t,s))):(t||o.type!==HV)&&r.push(s==null?o:iH(o,{key:s}))}if(i>1)for(let e=0;e<r.length;e++)r[e].patchFlag=-2;return r}function $z(e,t){return II(e)?kI({name:e.name},t,{setup:e}):e}function eB(e){e.ids=[e.ids[0]+e.ids[2]+++`-`,0,0]}function tB(e,t){let n;return!!((n=Object.getOwnPropertyDescriptor(e,t))&&!n.configurable)}var nB=new WeakMap;function rB(e,t,n,r,i=!1){if(MI(e)){e.forEach((e,a)=>rB(e,t&&(MI(t)?t[a]:t),n,r,i));return}if(aB(r)&&!i){r.shapeFlag&512&&r.type.__asyncResolved&&r.component.subTree.component&&rB(e,t,n,r.component.subTree);return}let a=r.shapeFlag&4?AH(r.component):r.el,o=i?null:a,{i:s,r:c}=e,l=t&&t.r,u=s.refs===CI?s.refs={}:s.refs,d=s.setupState,f=wR(d),p=d===CI?EI:e=>!tB(u,e)&&jI(f,e),m=(e,t)=>!(t&&tB(u,t));if(l!=null&&l!==c){if(iB(t),LI(l))u[l]=null,p(l)&&(d[l]=null);else if(OR(l)){let e=t;m(l,e.k)&&(l.value=null),e.k&&(u[e.k]=null)}}if(II(c)){DL();try{WR(c,s,12,[o,u])}finally{OL()}}else{let t=LI(c),r=OR(c);if(t||r){let s=()=>{if(e.f){let n=t?p(c)?d[c]:u[c]:m(c)||!e.k?c.value:u[e.k];if(i)MI(n)&&AI(n,a);else if(MI(n))n.includes(a)||n.push(a);else if(t)u[c]=[a],p(c)&&(d[c]=u[c]);else{let t=[a];m(c,e.k)&&(c.value=t),e.k&&(u[e.k]=t)}}else t?(u[c]=o,p(c)&&(d[c]=o)):r&&(m(c,e.k)&&(c.value=o),e.k&&(u[e.k]=o))};if(o){let t=()=>{s(),nB.delete(e)};t.id=-1,nB.set(e,t),DV(t,n)}else iB(e),s()}}}function iB(e){let t=nB.get(e);t&&(t.flags|=8,nB.delete(e))}tL().requestIdleCallback,tL().cancelIdleCallback;var aB=e=>!!e.type.__asyncLoader,oB=e=>e.type.__isKeepAlive;function sB(e,t){lB(e,`a`,t)}function cB(e,t){lB(e,`da`,t)}function lB(e,t,n=mH){let r=e.__wdc||=()=>{let t=n;for(;t;){if(t.isDeactivated)return;t=t.parent}return e()};if(dB(t,r,n),n){let e=n.parent;for(;e&&e.parent;)oB(e.parent.vnode)&&uB(r,t,n,e),e=e.parent}}function uB(e,t,n,r){let i=dB(t,e,r,!0);vB(()=>{AI(r[t],i)},n)}function dB(e,t,n=mH,r=!1){if(n){let i=n[e]||(n[e]=[]),a=t.__weh||=(...r)=>{DL();let i=vH(n),a=GR(t,n,e,r);return i(),OL(),a};return r?i.unshift(a):i.push(a),a}}var fB=e=>(t,n=mH)=>{(!xH||e===`sp`)&&dB(e,(...e)=>t(...e),n)},pB=fB(`bm`),mB=fB(`m`),hB=fB(`bu`),gB=fB(`u`),_B=fB(`bum`),vB=fB(`um`),yB=fB(`sp`),bB=fB(`rtg`),xB=fB(`rtc`);function SB(e,t=mH){dB(`ec`,e,t)}var CB=Symbol.for(`v-ndc`);function wB(e,t,n,r){let i,a=n&&n[r],o=MI(e);if(o||LI(e)){let n=o&&bR(e),r=!1,s=!1;n&&(r=!SR(e),s=xR(e),e=BL(e)),i=Array(e.length);for(let n=0,o=e.length;n<o;n++)i[n]=t(r?s?DR(ER(e[n])):ER(e[n]):e[n],n,void 0,a&&a[n])}else if(typeof e==`number`){i=Array(e);for(let n=0;n<e;n++)i[n]=t(n+1,n,void 0,a&&a[n])}else if(zI(e))if(e[Symbol.iterator])i=Array.from(e,(e,n)=>t(e,n,void 0,a&&a[n]));else{let n=Object.keys(e);i=Array(n.length);for(let r=0,o=n.length;r<o;r++){let o=n[r];i[r]=t(e[o],o,r,a&&a[r])}}else i=[];return n&&(n[r]=i),i}function TB(e,t,n={},r,i){if(uz.ce||uz.parent&&aB(uz.parent)&&uz.parent.ce){let e=Object.keys(n).length>0;return t!=="default"&&(n.name=t),Y(),XV(BV,null,[tH(`slot`,n,r&&r())],e?-2:64)}let a=e[t];a&&a._c&&(a._d=!1),Y();let o=a&&EB(a(n)),s=n.key||o&&o.key,c=XV(BV,{key:(s&&!RI(s)?s:`_${t}`)+(!o&&r?`_fb`:``)},o||(r?r():[]),o&&e._===1?64:-2);return!i&&c.scopeId&&(c.slotScopeIds=[c.scopeId+`-s`]),a&&a._c&&(a._d=!0),c}function EB(e){return e.some(e=>!ZV(e)||!(e.type===HV||e.type===BV&&!EB(e.children)))?e:null}var DB=e=>e?bH(e)?AH(e):DB(e.parent):null,OB=kI(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>DB(e.parent),$root:e=>DB(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>LB(e),$forceUpdate:e=>e.f||=()=>{rz(e.update)},$nextTick:e=>e.n||=tz.bind(e.proxy),$watch:e=>Sz.bind(e)}),kB=(e,t)=>e!==CI&&!e.__isScriptSetup&&jI(e,t),AB={get({_:e},t){if(t===`__v_skip`)return!0;let{ctx:n,setupState:r,data:i,props:a,accessCache:o,type:s,appContext:c}=e;if(t[0]!==`$`){let e=o[t];if(e!==void 0)switch(e){case 1:return r[t];case 2:return i[t];case 4:return n[t];case 3:return a[t]}else if(kB(r,t))return o[t]=1,r[t];else if(i!==CI&&jI(i,t))return o[t]=2,i[t];else if(jI(a,t))return o[t]=3,a[t];else if(n!==CI&&jI(n,t))return o[t]=4,n[t];else MB&&(o[t]=0)}let l=OB[t],u,d;if(l)return t===`$attrs`&&LL(e.attrs,`get`,``),l(e);if((u=s.__cssModules)&&(u=u[t]))return u;if(n!==CI&&jI(n,t))return o[t]=4,n[t];if(d=c.config.globalProperties,jI(d,t))return d[t]},set({_:e},t,n){let{data:r,setupState:i,ctx:a}=e;return kB(i,t)?(i[t]=n,!0):r!==CI&&jI(r,t)?(r[t]=n,!0):jI(e.props,t)||t[0]===`$`&&t.slice(1)in e?!1:(a[t]=n,!0)},has({_:{data:e,setupState:t,accessCache:n,ctx:r,appContext:i,props:a,type:o}},s){let c;return!!(n[s]||e!==CI&&s[0]!==`$`&&jI(e,s)||kB(t,s)||jI(a,s)||jI(r,s)||jI(OB,s)||jI(i.config.globalProperties,s)||(c=o.__cssModules)&&c[s])},defineProperty(e,t,n){return n.get==null?jI(n,`value`)&&this.set(e,t,n.value,null):e._.accessCache[t]=0,Reflect.defineProperty(e,t,n)}};function jB(e){return MI(e)?e.reduce((e,t)=>(e[t]=null,e),{}):e}var MB=!0;function NB(e){let t=LB(e),n=e.proxy,r=e.ctx;MB=!1,t.beforeCreate&&FB(t.beforeCreate,e,`bc`);let{data:i,computed:a,methods:o,watch:s,provide:c,inject:l,created:u,beforeMount:d,mounted:f,beforeUpdate:p,updated:m,activated:h,deactivated:g,beforeDestroy:_,beforeUnmount:v,destroyed:y,unmounted:b,render:x,renderTracked:S,renderTriggered:ee,errorCaptured:C,serverPrefetch:te,expose:ne,inheritAttrs:w,components:re,directives:ie,filters:T}=t;if(l&&PB(l,r,null),o)for(let e in o){let t=o[e];II(t)&&(r[e]=t.bind(n))}if(i){let t=i.call(n,n);zI(t)&&(e.data=gR(t))}if(MB=!0,a)for(let e in a){let t=a[e],i=MH({get:II(t)?t.bind(n,n):II(t.get)?t.get.bind(n,n):TI,set:!II(t)&&II(t.set)?t.set.bind(n):TI});Object.defineProperty(r,e,{enumerable:!0,configurable:!0,get:()=>i.value,set:e=>i.value=e})}if(s)for(let e in s)IB(s[e],r,n,e);if(c){let e=II(c)?c.call(n):c;Reflect.ownKeys(e).forEach(t=>{gz(t,e[t])})}u&&FB(u,e,`c`);function ae(e,t){MI(t)?t.forEach(t=>e(t.bind(n))):t&&e(t.bind(n))}if(ae(pB,d),ae(mB,f),ae(hB,p),ae(gB,m),ae(sB,h),ae(cB,g),ae(SB,C),ae(xB,S),ae(bB,ee),ae(_B,v),ae(vB,b),ae(yB,te),MI(ne))if(ne.length){let t=e.exposed||={};ne.forEach(e=>{Object.defineProperty(t,e,{get:()=>n[e],set:t=>n[e]=t,enumerable:!0})})}else e.exposed||={};x&&e.render===TI&&(e.render=x),w!=null&&(e.inheritAttrs=w),re&&(e.components=re),ie&&(e.directives=ie),te&&eB(e)}function PB(e,t,n=TI){MI(e)&&(e=HB(e));for(let n in e){let r=e[n],i;i=zI(r)?`default`in r?_z(r.from||n,r.default,!0):_z(r.from||n):_z(r),OR(i)?Object.defineProperty(t,n,{enumerable:!0,configurable:!0,get:()=>i.value,set:e=>i.value=e}):t[n]=i}}function FB(e,t,n){GR(MI(e)?e.map(e=>e.bind(t.proxy)):e.bind(t.proxy),t,n)}function IB(e,t,n,r){let i=r.includes(`.`)?Cz(n,r):()=>n[r];if(LI(e)){let n=t[e];II(n)&&bz(i,n)}else if(II(e))bz(i,e.bind(n));else if(zI(e))if(MI(e))e.forEach(e=>IB(e,t,n,r));else{let r=II(e.handler)?e.handler.bind(n):t[e.handler];II(r)&&bz(i,r,e)}}function LB(e){let t=e.type,{mixins:n,extends:r}=t,{mixins:i,optionsCache:a,config:{optionMergeStrategies:o}}=e.appContext,s=a.get(t),c;return s?c=s:!i.length&&!n&&!r?c=t:(c={},i.length&&i.forEach(e=>RB(c,e,o,!0)),RB(c,t,o)),zI(t)&&a.set(t,c),c}function RB(e,t,n,r=!1){let{mixins:i,extends:a}=t;a&&RB(e,a,n,!0),i&&i.forEach(t=>RB(e,t,n,!0));for(let i in t)if(!(r&&i===`expose`)){let r=zB[i]||n&&n[i];e[i]=r?r(e[i],t[i]):t[i]}return e}var zB={data:BB,props:GB,emits:GB,methods:WB,computed:WB,beforeCreate:UB,created:UB,beforeMount:UB,mounted:UB,beforeUpdate:UB,updated:UB,beforeDestroy:UB,beforeUnmount:UB,destroyed:UB,unmounted:UB,activated:UB,deactivated:UB,errorCaptured:UB,serverPrefetch:UB,components:WB,directives:WB,watch:KB,provide:BB,inject:VB};function BB(e,t){return t?e?function(){return kI(II(e)?e.call(this,this):e,II(t)?t.call(this,this):t)}:t:e}function VB(e,t){return WB(HB(e),HB(t))}function HB(e){if(MI(e)){let t={};for(let n=0;n<e.length;n++)t[e[n]]=e[n];return t}return e}function UB(e,t){return e?[...new Set([].concat(e,t))]:t}function WB(e,t){return e?kI(Object.create(null),e,t):t}function GB(e,t){return e?MI(e)&&MI(t)?[...new Set([...e,...t])]:kI(Object.create(null),jB(e),jB(t??{})):t}function KB(e,t){if(!e)return t;if(!t)return e;let n=kI(Object.create(null),e);for(let r in t)n[r]=UB(e[r],t[r]);return n}function qB(){return{app:null,config:{isNativeTag:EI,performance:!1,globalProperties:{},optionMergeStrategies:{},errorHandler:void 0,warnHandler:void 0,compilerOptions:{}},mixins:[],components:{},directives:{},provides:Object.create(null),optionsCache:new WeakMap,propsCache:new WeakMap,emitsCache:new WeakMap}}var JB=0;function YB(e,t){return function(n,r=null){II(n)||(n=kI({},n)),r!=null&&!zI(r)&&(r=null);let i=qB(),a=new WeakSet,o=[],s=!1,c=i.app={_uid:JB++,_component:n,_props:r,_container:null,_context:i,_instance:null,version:PH,get config(){return i.config},set config(e){},use(e,...t){return a.has(e)||(e&&II(e.install)?(a.add(e),e.install(c,...t)):II(e)&&(a.add(e),e(c,...t))),c},mixin(e){return i.mixins.includes(e)||i.mixins.push(e),c},component(e,t){return t?(i.components[e]=t,c):i.components[e]},directive(e,t){return t?(i.directives[e]=t,c):i.directives[e]},mount(a,o,l){if(!s){let u=c._ceVNode||tH(n,r);return u.appContext=i,l===!0?l=`svg`:l===!1&&(l=void 0),o&&t?t(u,a):e(u,a,l),s=!0,c._container=a,a.__vue_app__=c,AH(u.component)}},onUnmount(e){o.push(e)},unmount(){s&&(GR(o,c._instance,16),e(null,c._container),delete c._container.__vue_app__)},provide(e,t){return i.provides[e]=t,c},runWithContext(e){let t=XB;XB=c;try{return e()}finally{XB=t}}};return c}}var XB=null,ZB=(e,t)=>t===`modelValue`||t===`model-value`?e.modelModifiers:e[`${t}Modifiers`]||e[`${qI(t)}Modifiers`]||e[`${JI(t)}Modifiers`];function QB(e,t,...n){if(e.isUnmounted)return;let r=e.vnode.props||CI,i=n,a=t.startsWith(`update:`),o=a&&ZB(r,t.slice(7));o&&(o.trim&&(i=n.map(e=>LI(e)?e.trim():e)),o.number&&(i=n.map(eL)));let s,c=r[s=XI(t)]||r[s=XI(qI(t))];!c&&a&&(c=r[s=XI(JI(t))]),c&&GR(c,e,6,i);let l=r[s+`Once`];if(l){if(!e.emitted)e.emitted={};else if(e.emitted[s])return;e.emitted[s]=!0,GR(l,e,6,i)}}var $B=new WeakMap;function eV(e,t,n=!1){let r=n?$B:t.emitsCache,i=r.get(e);if(i!==void 0)return i;let a=e.emits,o={},s=!1;if(!II(e)){let r=e=>{let n=eV(e,t,!0);n&&(s=!0,kI(o,n))};!n&&t.mixins.length&&t.mixins.forEach(r),e.extends&&r(e.extends),e.mixins&&e.mixins.forEach(r)}return!a&&!s?(zI(e)&&r.set(e,null),null):(MI(a)?a.forEach(e=>o[e]=null):kI(o,a),zI(e)&&r.set(e,o),o)}function tV(e,t){return!e||!DI(t)?!1:(t=t.slice(2),t=t===`Once`?t:t.replace(/Once$/,``),jI(e,t[0].toLowerCase()+t.slice(1))||jI(e,JI(t))||jI(e,t))}function nV(e){let{type:t,vnode:n,proxy:r,withProxy:i,propsOptions:[a],slots:o,attrs:s,emit:c,render:l,renderCache:u,props:d,data:f,setupState:p,ctx:m,inheritAttrs:h}=e,g=fz(e),_,v;try{if(n.shapeFlag&4){let e=i||r,t=e;_=oH(l.call(t,e,u,d,p,f,m)),v=s}else{let e=t;_=oH(e.length>1?e(d,{attrs:s,slots:o,emit:c}):e(d,null)),v=t.props?s:rV(s)}}catch(t){WV.length=0,KR(t,e,1),_=tH(HV)}let y=_;if(v&&h!==!1){let e=Object.keys(v),{shapeFlag:t}=y;e.length&&t&7&&(a&&e.some(OI)&&(v=iV(v,a)),y=iH(y,v,!1,!0))}return n.dirs&&(y=iH(y,null,!1,!0),y.dirs=y.dirs?y.dirs.concat(n.dirs):n.dirs),n.transition&&Zz(y,n.transition),_=y,fz(g),_}var rV=e=>{let t;for(let n in e)(n===`class`||n===`style`||DI(n))&&((t||={})[n]=e[n]);return t},iV=(e,t)=>{let n={};for(let r in e)(!OI(r)||!(r.slice(9)in t))&&(n[r]=e[r]);return n};function aV(e,t,n){let{props:r,children:i,component:a}=e,{props:o,children:s,patchFlag:c}=t,l=a.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&c>=0){if(c&1024)return!0;if(c&16)return r?oV(r,o,l):!!o;if(c&8){let e=t.dynamicProps;for(let t=0;t<e.length;t++){let n=e[t];if(sV(o,r,n)&&!tV(l,n))return!0}}}else return(i||s)&&(!s||!s.$stable)?!0:r===o?!1:r?!o||oV(r,o,l):!!o;return!1}function oV(e,t,n){let r=Object.keys(t);if(r.length!==Object.keys(e).length)return!0;for(let i=0;i<r.length;i++){let a=r[i];if(sV(t,e,a)&&!tV(n,a))return!0}return!1}function sV(e,t,n){let r=e[n],i=t[n];return n===`style`&&zI(r)&&zI(i)?!oL(r,i):r!==i}function cV({vnode:e,parent:t,suspense:n},r){for(;t;){let n=t.subTree;if(n.suspense&&n.suspense.activeBranch===e&&(n.suspense.vnode.el=n.el=r,e=n),n===e)(e=t.vnode).el=r,t=t.parent;else break}n&&n.activeBranch===e&&(n.vnode.el=r)}var lV={},uV=()=>Object.create(lV),dV=e=>Object.getPrototypeOf(e)===lV;function fV(e,t,n,r=!1){let i={},a=uV();e.propsDefaults=Object.create(null),mV(e,t,i,a);for(let t in e.propsOptions[0])t in i||(i[t]=void 0);n?e.props=r?i:_R(i):e.type.props?e.props=i:e.props=a,e.attrs=a}function pV(e,t,n,r){let{props:i,attrs:a,vnode:{patchFlag:o}}=e,s=wR(i),[c]=e.propsOptions,l=!1;if((r||o>0)&&!(o&16)){if(o&8){let n=e.vnode.dynamicProps;for(let r=0;r<n.length;r++){let o=n[r];if(tV(e.emitsOptions,o))continue;let u=t[o];if(c)if(jI(a,o))u!==a[o]&&(a[o]=u,l=!0);else{let t=qI(o);i[t]=hV(c,s,t,u,e,!1)}else u!==a[o]&&(a[o]=u,l=!0)}}}else{mV(e,t,i,a)&&(l=!0);let r;for(let a in s)(!t||!jI(t,a)&&((r=JI(a))===a||!jI(t,r)))&&(c?n&&(n[a]!==void 0||n[r]!==void 0)&&(i[a]=hV(c,s,a,void 0,e,!0)):delete i[a]);if(a!==s)for(let e in a)(!t||!jI(t,e))&&(delete a[e],l=!0)}l&&RL(e.attrs,`set`,``)}function mV(e,t,n,r){let[i,a]=e.propsOptions,o=!1,s;if(t)for(let c in t){if(GI(c))continue;let l=t[c],u;i&&jI(i,u=qI(c))?!a||!a.includes(u)?n[u]=l:(s||={})[u]=l:tV(e.emitsOptions,c)||(!(c in r)||l!==r[c])&&(r[c]=l,o=!0)}if(a){let t=wR(n),r=s||CI;for(let o=0;o<a.length;o++){let s=a[o];n[s]=hV(i,t,s,r[s],e,!jI(r,s))}}return o}function hV(e,t,n,r,i,a){let o=e[n];if(o!=null){let e=jI(o,`default`);if(e&&r===void 0){let e=o.default;if(o.type!==Function&&!o.skipFactory&&II(e)){let{propsDefaults:a}=i;if(n in a)r=a[n];else{let o=vH(i);r=a[n]=e.call(null,t),o()}}else r=e;i.ce&&i.ce._setProp(n,r)}o[0]&&(a&&!e?r=!1:o[1]&&(r===``||r===JI(n))&&(r=!0))}return r}var gV=new WeakMap;function _V(e,t,n=!1){let r=n?gV:t.propsCache,i=r.get(e);if(i)return i;let a=e.props,o={},s=[],c=!1;if(!II(e)){let r=e=>{c=!0;let[n,r]=_V(e,t,!0);kI(o,n),r&&s.push(...r)};!n&&t.mixins.length&&t.mixins.forEach(r),e.extends&&r(e.extends),e.mixins&&e.mixins.forEach(r)}if(!a&&!c)return zI(e)&&r.set(e,wI),wI;if(MI(a))for(let e=0;e<a.length;e++){let t=qI(a[e]);vV(t)&&(o[t]=CI)}else if(a)for(let e in a){let t=qI(e);if(vV(t)){let n=a[e],r=o[t]=MI(n)||II(n)?{type:n}:kI({},n),i=r.type,c=!1,l=!0;if(MI(i))for(let e=0;e<i.length;++e){let t=i[e],n=II(t)&&t.name;if(n===`Boolean`){c=!0;break}else n===`String`&&(l=!1)}else c=II(i)&&i.name===`Boolean`;r[0]=c,r[1]=l,(c||jI(r,`default`))&&s.push(t)}}let l=[o,s];return zI(e)&&r.set(e,l),l}function vV(e){return e[0]!==`$`&&!GI(e)}var yV=e=>e===`_`||e===`_ctx`||e===`$stable`,bV=e=>MI(e)?e.map(oH):[oH(e)],xV=(e,t,n)=>{if(t._n)return t;let r=pz((...e)=>bV(t(...e)),n);return r._c=!1,r},SV=(e,t,n)=>{let r=e._ctx;for(let n in e){if(yV(n))continue;let i=e[n];if(II(i))t[n]=xV(n,i,r);else if(i!=null){let e=bV(i);t[n]=()=>e}}},CV=(e,t)=>{let n=bV(t);e.slots.default=()=>n},wV=(e,t,n)=>{for(let r in t)(n||!yV(r))&&(e[r]=t[r])},TV=(e,t,n)=>{let r=e.slots=uV();if(e.vnode.shapeFlag&32){let e=t._;e?(wV(r,t,n),n&&$I(r,`_`,e,!0)):SV(t,r)}else t&&CV(e,t)},EV=(e,t,n)=>{let{vnode:r,slots:i}=e,a=!0,o=CI;if(r.shapeFlag&32){let e=t._;e?n&&e===1?a=!1:wV(i,t,n):(a=!t.$stable,SV(t,i)),o=t}else t&&(CV(e,t),o={default:1});if(a)for(let e in i)!yV(e)&&o[e]==null&&delete i[e]},DV=zV;function OV(e){return kV(e)}function kV(e,t){let n=tL();n.__VUE__=!0;let{insert:r,remove:i,patchProp:a,createElement:o,createText:s,createComment:c,setText:l,setElementText:u,parentNode:d,nextSibling:f,setScopeId:p=TI,insertStaticContent:m}=e,h=(e,t,n,r=null,i=null,a=null,o=void 0,s=null,c=!!t.dynamicChildren)=>{if(e===t)return;e&&!QV(e,t)&&(r=me(e),ue(e,i,a,!0),e=null),t.patchFlag===-2&&(c=!1,t.dynamicChildren=null);let{type:l,ref:u,shapeFlag:d}=t;switch(l){case VV:g(e,t,n,r);break;case HV:_(e,t,n,r);break;case UV:e??v(t,n,r,o);break;case BV:re(e,t,n,r,i,a,o,s,c);break;default:d&1?x(e,t,n,r,i,a,o,s,c):d&6?ie(e,t,n,r,i,a,o,s,c):(d&64||d&128)&&l.process(e,t,n,r,i,a,o,s,c,_e)}u!=null&&i?rB(u,e&&e.ref,a,t||e,!t):u==null&&e&&e.ref!=null&&rB(e.ref,null,a,e,!0)},g=(e,t,n,i)=>{if(e==null)r(t.el=s(t.children),n,i);else{let n=t.el=e.el;t.children!==e.children&&l(n,t.children)}},_=(e,t,n,i)=>{e==null?r(t.el=c(t.children||``),n,i):t.el=e.el},v=(e,t,n,r)=>{[e.el,e.anchor]=m(e.children,t,n,r,e.el,e.anchor)},y=({el:e,anchor:t},n,i)=>{let a;for(;e&&e!==t;)a=f(e),r(e,n,i),e=a;r(t,n,i)},b=({el:e,anchor:t})=>{let n;for(;e&&e!==t;)n=f(e),i(e),e=n;i(t)},x=(e,t,n,r,i,a,o,s,c)=>{if(t.type===`svg`?o=`svg`:t.type===`math`&&(o=`mathml`),e==null)S(t,n,r,i,a,o,s,c);else{let n=e.el&&e.el._isVueCE?e.el:null;try{n&&n._beginPatch(),te(e,t,i,a,o,s,c)}finally{n&&n._endPatch()}}},S=(e,t,n,i,s,c,l,d)=>{let f,p,{props:m,shapeFlag:h,transition:g,dirs:_}=e;if(f=e.el=o(e.type,c,m&&m.is,m),h&8?u(f,e.children):h&16&&C(e.children,f,null,i,s,AV(e,c),l,d),_&&hz(e,null,i,`created`),ee(f,e,e.scopeId,l,i),m){for(let e in m)e!==`value`&&!GI(e)&&a(f,e,null,m[e],c,i);`value`in m&&a(f,`value`,null,m.value,c),(p=m.onVnodeBeforeMount)&&uH(p,i,e)}_&&hz(e,null,i,`beforeMount`);let v=MV(s,g);v&&g.beforeEnter(f),r(f,t,n),((p=m&&m.onVnodeMounted)||v||_)&&DV(()=>{try{p&&uH(p,i,e),v&&g.enter(f),_&&hz(e,null,i,`mounted`)}finally{}},s)},ee=(e,t,n,r,i)=>{if(n&&p(e,n),r)for(let t=0;t<r.length;t++)p(e,r[t]);if(i){let n=i.subTree;if(t===n||RV(n.type)&&(n.ssContent===t||n.ssFallback===t)){let t=i.vnode;ee(e,t,t.scopeId,t.slotScopeIds,i.parent)}}},C=(e,t,n,r,i,a,o,s,c=0)=>{for(let l=c;l<e.length;l++){let c=e[l]=s?sH(e[l]):oH(e[l]);h(null,c,t,n,r,i,a,o,s)}},te=(e,t,n,r,i,o,s)=>{let c=t.el=e.el,{patchFlag:l,dynamicChildren:d,dirs:f}=t;l|=e.patchFlag&16;let p=e.props||CI,m=t.props||CI,h;if(n&&jV(n,!1),(h=m.onVnodeBeforeUpdate)&&uH(h,n,t,e),f&&hz(t,e,n,`beforeUpdate`),n&&jV(n,!0),d&&(!e.dynamicChildren||e.dynamicChildren.length!==d.length)&&(l=0,s=!1,d=null),(p.innerHTML&&m.innerHTML==null||p.textContent&&m.textContent==null)&&u(c,``),d?ne(e.dynamicChildren,d,c,n,r,AV(t,i),o):s||se(e,t,c,null,n,r,AV(t,i),o,!1),l>0){if(l&16)w(c,p,m,n,i);else if(l&2&&p.class!==m.class&&a(c,`class`,null,m.class,i),l&4&&a(c,`style`,p.style,m.style,i),l&8){let e=t.dynamicProps;for(let t=0;t<e.length;t++){let r=e[t],o=p[r],s=m[r];(s!==o||r===`value`)&&a(c,r,o,s,i,n)}}l&1&&e.children!==t.children&&u(c,t.children)}else!s&&d==null&&w(c,p,m,n,i);((h=m.onVnodeUpdated)||f)&&DV(()=>{h&&uH(h,n,t,e),f&&hz(t,e,n,`updated`)},r)},ne=(e,t,n,r,i,a,o)=>{for(let s=0;s<t.length;s++){let c=e[s],l=t[s],u=c.el&&(c.type===BV||!QV(c,l)||c.shapeFlag&198)?d(c.el):n;h(c,l,u,null,r,i,a,o,!0)}},w=(e,t,n,r,i)=>{if(t!==n){if(t!==CI)for(let o in t)!GI(o)&&!(o in n)&&a(e,o,t[o],null,i,r);for(let o in n){if(GI(o))continue;let s=n[o],c=t[o];s!==c&&o!==`value`&&a(e,o,c,s,i,r)}`value`in n&&a(e,`value`,t.value,n.value,i)}},re=(e,t,n,i,a,o,c,l,u)=>{let d=t.el=e?e.el:s(``),f=t.anchor=e?e.anchor:s(``),{patchFlag:p,dynamicChildren:m,slotScopeIds:h}=t;h&&(l=l?l.concat(h):h),e==null?(r(d,n,i),r(f,n,i),C(t.children||[],n,f,a,o,c,l,u)):p>0&&p&64&&m&&e.dynamicChildren&&e.dynamicChildren.length===m.length?(ne(e.dynamicChildren,m,n,a,o,c,l),(t.key!=null||a&&t===a.subTree)&&NV(e,t,!0)):se(e,t,n,f,a,o,c,l,u)},ie=(e,t,n,r,i,a,o,s,c)=>{t.slotScopeIds=s,e==null?t.shapeFlag&512?i.ctx.activate(t,n,r,o,c):T(t,n,r,i,a,o,c):ae(e,t,c)},T=(e,t,n,r,i,a,o)=>{let s=e.component=pH(e,r,i);if(oB(e)&&(s.ctx.renderer=_e),SH(s,!1,o),s.asyncDep){if(i&&i.registerDep(s,E,o),!e.el){let r=s.subTree=tH(HV);_(null,r,t,n),e.placeholder=r.el}}else E(s,e,t,n,i,a,o)},ae=(e,t,n)=>{let r=t.component=e.component;if(aV(e,t,n))if(r.asyncDep&&!r.asyncResolved){oe(r,t,n);return}else r.next=t,r.update();else t.el=e.el,r.vnode=t},E=(e,t,n,r,i,a,o)=>{let s=()=>{if(e.isMounted){let{next:t,bu:n,u:r,parent:s,vnode:c}=e;{let n=FV(e);if(n){t&&(t.el=c.el,oe(e,t,o)),n.asyncDep.then(()=>{DV(()=>{e.isUnmounted||l()},i)});return}}let u=t,f;jV(e,!1),t?(t.el=c.el,oe(e,t,o)):t=c,n&&QI(n),(f=t.props&&t.props.onVnodeBeforeUpdate)&&uH(f,s,t,c),jV(e,!0);let p=nV(e),m=e.subTree;e.subTree=p,h(m,p,d(m.el),me(m),e,i,a),t.el=p.el,u===null&&cV(e,p.el),r&&DV(r,i),(f=t.props&&t.props.onVnodeUpdated)&&DV(()=>uH(f,s,t,c),i)}else{let o,{el:s,props:c}=t,{bm:l,m:u,parent:d,root:f,type:p}=e,m=aB(t);if(jV(e,!1),l&&QI(l),!m&&(o=c&&c.onVnodeBeforeMount)&&uH(o,d,t),jV(e,!0),s&&ye){let t=()=>{e.subTree=nV(e),ye(s,e.subTree,e,i,null)};m&&p.__asyncHydrate?p.__asyncHydrate(s,e,t):t()}else{f.ce&&f.ce._hasShadowRoot()&&f.ce._injectChildStyle(p,e.parent?e.parent.type:void 0);let o=e.subTree=nV(e);h(null,o,n,r,e,i,a),t.el=o.el}if(u&&DV(u,i),!m&&(o=c&&c.onVnodeMounted)){let e=t;DV(()=>uH(o,d,e),i)}(t.shapeFlag&256||d&&aB(d.vnode)&&d.vnode.shapeFlag&256)&&e.a&&DV(e.a,i),e.isMounted=!0,t=n=r=null}};e.scope.on();let c=e.effect=new pL(s);e.scope.off();let l=e.update=c.run.bind(c),u=e.job=c.runIfDirty.bind(c);u.i=e,u.id=e.uid,c.scheduler=()=>rz(u),jV(e,!0),l()},oe=(e,t,n)=>{t.component=e;let r=e.vnode.props;e.vnode=t,e.next=null,pV(e,t.props,r,n),EV(e,t.children,n),DL(),oz(e),OL()},se=(e,t,n,r,i,a,o,s,c=!1)=>{let l=e&&e.children,d=e?e.shapeFlag:0,f=t.children,{patchFlag:p,shapeFlag:m}=t;if(p>0){if(p&128){D(l,f,n,r,i,a,o,s,c);return}else if(p&256){ce(l,f,n,r,i,a,o,s,c);return}}m&8?(d&16&&pe(l,i,a),f!==l&&u(n,f)):d&16?m&16?D(l,f,n,r,i,a,o,s,c):pe(l,i,a,!0):(d&8&&u(n,``),m&16&&C(f,n,r,i,a,o,s,c))},ce=(e,t,n,r,i,a,o,s,c)=>{e||=wI,t||=wI;let l=e.length,u=t.length,d=Math.min(l,u),f;for(f=0;f<d;f++){let r=t[f]=c?sH(t[f]):oH(t[f]);h(e[f],r,n,null,i,a,o,s,c)}l>u?pe(e,i,a,!0,!1,d):C(t,n,r,i,a,o,s,c,d)},D=(e,t,n,r,i,a,o,s,c)=>{let l=0,u=t.length,d=e.length-1,f=u-1;for(;l<=d&&l<=f;){let r=e[l],u=t[l]=c?sH(t[l]):oH(t[l]);if(QV(r,u))h(r,u,n,null,i,a,o,s,c);else break;l++}for(;l<=d&&l<=f;){let r=e[d],l=t[f]=c?sH(t[f]):oH(t[f]);if(QV(r,l))h(r,l,n,null,i,a,o,s,c);else break;d--,f--}if(l>d){if(l<=f){let e=f+1,d=e<u?t[e].el:r;for(;l<=f;)h(null,t[l]=c?sH(t[l]):oH(t[l]),n,d,i,a,o,s,c),l++}}else if(l>f)for(;l<=d;)ue(e[l],i,a,!0),l++;else{let p=l,m=l,g=new Map;for(l=m;l<=f;l++){let e=t[l]=c?sH(t[l]):oH(t[l]);e.key!=null&&g.set(e.key,l)}let _,v=0,y=f-m+1,b=!1,x=0,S=Array(y);for(l=0;l<y;l++)S[l]=0;for(l=p;l<=d;l++){let r=e[l];if(v>=y){ue(r,i,a,!0);continue}let u;if(r.key!=null)u=g.get(r.key);else for(_=m;_<=f;_++)if(S[_-m]===0&&QV(r,t[_])){u=_;break}u===void 0?ue(r,i,a,!0):(S[u-m]=l+1,u>=x?x=u:b=!0,h(r,t[u],n,null,i,a,o,s,c),v++)}let ee=b?PV(S):wI;for(_=ee.length-1,l=y-1;l>=0;l--){let e=m+l,d=t[e],f=t[e+1],p=e+1<u?f.el||LV(f):r;S[l]===0?h(null,d,n,p,i,a,o,s,c):b&&(_<0||l!==ee[_]?le(d,n,p,2):_--)}}},le=(e,t,n,a,o=null)=>{let{el:s,type:c,transition:l,children:u,shapeFlag:d}=e;if(d&6){le(e.component.subTree,t,n,a);return}if(d&128){e.suspense.move(t,n,a);return}if(d&64){c.move(e,t,n,_e);return}if(c===BV){r(s,t,n);for(let e=0;e<u.length;e++)le(u[e],t,n,a);r(e.anchor,t,n);return}if(c===UV){y(e,t,n);return}if(a!==2&&d&1&&l)if(a===0)l.persisted&&!s[Rz]?r(s,t,n):(l.beforeEnter(s),r(s,t,n),DV(()=>l.enter(s),o));else{let{leave:a,delayLeave:o,afterLeave:c}=l,u=()=>{e.ctx.isUnmounted?i(s):r(s,t,n)},d=()=>{let e=s._isLeaving||!!s[Rz];s._isLeaving&&s[Rz](!0),l.persisted&&!e?u():a(s,()=>{u(),c&&c()})};o?o(s,u,d):d()}else r(s,t,n)},ue=(e,t,n,r=!1,i=!1)=>{let{type:a,props:o,ref:s,children:c,dynamicChildren:l,shapeFlag:u,patchFlag:d,dirs:f,cacheIndex:p,memo:m}=e;if(d===-2&&(i=!1),s!=null&&(DL(),rB(s,null,n,e,!0),OL()),p!=null&&(t.renderCache[p]=void 0),u&256){t.ctx.deactivate(e);return}let h=u&1&&f,g=!aB(e),_;if(g&&(_=o&&o.onVnodeBeforeUnmount)&&uH(_,t,e),u&6)fe(e.component,n,r);else{if(u&128){e.suspense.unmount(n,r);return}h&&hz(e,null,t,`beforeUnmount`),u&64?e.type.remove(e,t,n,_e,r):l&&!l.hasOnce&&(a!==BV||d>0&&d&64)?pe(l,t,n,!1,!0):(a===BV&&d&384||!i&&u&16)&&pe(c,t,n),r&&O(e)}let v=m!=null&&p==null;(g&&(_=o&&o.onVnodeUnmounted)||h||v)&&DV(()=>{_&&uH(_,t,e),h&&hz(e,null,t,`unmounted`),v&&(e.el=null)},n)},O=e=>{let{type:t,el:n,anchor:r,transition:a}=e;if(t===BV){de(n,r);return}if(t===UV){b(e);return}let o=()=>{i(n),a&&!a.persisted&&a.afterLeave&&a.afterLeave()};if(e.shapeFlag&1&&a&&!a.persisted){let{leave:t,delayLeave:r}=a,i=()=>t(n,o);r?r(e.el,o,i):i()}else o()},de=(e,t)=>{let n;for(;e!==t;)n=f(e),i(e),e=n;i(t)},fe=(e,t,n)=>{let{bum:r,scope:i,job:a,subTree:o,um:s,m:c,a:l}=e;IV(c),IV(l),r&&QI(r),i.stop(),a&&(a.flags|=8,ue(o,e,t,n)),s&&DV(s,t),DV(()=>{e.isUnmounted=!0},t)},pe=(e,t,n,r=!1,i=!1,a=0)=>{for(let o=a;o<e.length;o++)ue(e[o],t,n,r,i)},me=e=>{if(e.shapeFlag&6)return me(e.component.subTree);if(e.shapeFlag&128)return e.suspense.next();let t=f(e.anchor||e.el),n=t&&t[Tz];return n?f(n):t},he=!1,ge=(e,t,n)=>{let r;e==null?t._vnode&&(ue(t._vnode,null,null,!0),r=t._vnode.component):h(t._vnode||null,e,t,null,null,null,n),t._vnode=e,he||=(he=!0,oz(r),sz(),!1)},_e={p:h,um:ue,m:le,r:O,mt:T,mc:C,pc:se,pbc:ne,n:me,o:e},ve,ye;return t&&([ve,ye]=t(_e)),{render:ge,hydrate:ve,createApp:YB(ge,ve)}}function AV({type:e,props:t},n){return n===`svg`&&e===`foreignObject`||n===`mathml`&&e===`annotation-xml`&&t&&t.encoding&&t.encoding.includes(`html`)?void 0:n}function jV({effect:e,job:t},n){n?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function MV(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function NV(e,t,n=!1){let r=e.children,i=t.children;if(MI(r)&&MI(i))for(let e=0;e<r.length;e++){let t=r[e],a=i[e];a.shapeFlag&1&&!a.dynamicChildren&&((a.patchFlag<=0||a.patchFlag===32)&&(a=i[e]=sH(i[e]),a.el=t.el),!n&&a.patchFlag!==-2&&NV(t,a)),a.type===VV&&(a.patchFlag===-1&&(a=i[e]=sH(a)),a.el=t.el),a.type===HV&&!a.el&&(a.el=t.el)}}function PV(e){let t=e.slice(),n=[0],r,i,a,o,s,c=e.length;for(r=0;r<c;r++){let c=e[r];if(c!==0){if(i=n[n.length-1],e[i]<c){t[r]=i,n.push(r);continue}for(a=0,o=n.length-1;a<o;)s=a+o>>1,e[n[s]]<c?a=s+1:o=s;c<e[n[a]]&&(a>0&&(t[r]=n[a-1]),n[a]=r)}}for(a=n.length,o=n[a-1];a-->0;)n[a]=o,o=t[o];return n}function FV(e){let t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:FV(t)}function IV(e){if(e)for(let t=0;t<e.length;t++)e[t].flags|=8}function LV(e){if(e.placeholder)return e.placeholder;let t=e.component;return t?LV(t.subTree):null}var RV=e=>e.__isSuspense;function zV(e,t){t&&t.pendingBranch?MI(e)?t.effects.push(...e):t.effects.push(e):az(e)}var BV=Symbol.for(`v-fgt`),VV=Symbol.for(`v-txt`),HV=Symbol.for(`v-cmt`),UV=Symbol.for(`v-stc`),WV=[],GV=null;function Y(e=!1){WV.push(GV=e?null:[])}function KV(){WV.pop(),GV=WV[WV.length-1]||null}var qV=1;function JV(e,t=!1){qV+=e,e<0&&GV&&t&&(GV.hasOnce=!0)}function YV(e){return e.dynamicChildren=qV>0?GV||wI:null,KV(),qV>0&&GV&&GV.push(e),e}function X(e,t,n,r,i,a){return YV(Z(e,t,n,r,i,a,!0))}function XV(e,t,n,r,i){return YV(tH(e,t,n,r,i,!0))}function ZV(e){return e?e.__v_isVNode===!0:!1}function QV(e,t){return e.type===t.type&&e.key===t.key}var $V=({key:e})=>e??null,eH=({ref:e,ref_key:t,ref_for:n})=>(typeof e==`number`&&(e=``+e),e==null?null:LI(e)||OR(e)||II(e)?{i:uz,r:e,k:t,f:!!n}:e);function Z(e,t=null,n=null,r=0,i=null,a=e===BV?0:1,o=!1,s=!1){let c={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&$V(t),ref:t&&eH(t),scopeId:dz,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:a,patchFlag:r,dynamicProps:i,dynamicChildren:null,appContext:null,ctx:uz};return s?(cH(c,n),a&128&&e.normalize(c)):n&&(c.shapeFlag|=LI(n)?8:16),qV>0&&!o&&GV&&(c.patchFlag>0||a&6)&&c.patchFlag!==32&&GV.push(c),c}var tH=nH;function nH(e,t=null,n=null,r=0,i=null,a=!1){if((!e||e===CB)&&(e=HV),ZV(e)){let r=iH(e,t,!0);return n&&cH(r,n),qV>0&&!a&&GV&&(r.shapeFlag&6?GV[GV.indexOf(e)]=r:GV.push(r)),r.patchFlag=-2,r}if(jH(e)&&(e=e.__vccOpts),t){t=rH(t);let{class:e,style:n}=t;e&&!LI(e)&&(t.class=rL(e)),zI(n)&&(CR(n)&&!MI(n)&&(n=kI({},n)),t.style=nL(n))}let o=LI(e)?1:RV(e)?128:Ez(e)?64:zI(e)?4:II(e)?2:0;return Z(e,t,n,r,i,o,a,!0)}function rH(e){return e?CR(e)||dV(e)?kI({},e):e:null}function iH(e,t,n=!1,r=!1){let{props:i,ref:a,patchFlag:o,children:s,transition:c}=e,l=t?lH(i||{},t):i,u={__v_isVNode:!0,__v_skip:!0,type:e.type,props:l,key:l&&$V(l),ref:t&&t.ref?n&&a?MI(a)?a.concat(eH(t)):[a,eH(t)]:eH(t):a,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:s,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==BV?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:c,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&iH(e.ssContent),ssFallback:e.ssFallback&&iH(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce};return c&&r&&Zz(u,c.clone(u)),u}function aH(e=` `,t=0){return tH(VV,null,e,t)}function Q(e=``,t=!1){return t?(Y(),XV(HV,null,e)):tH(HV,null,e)}function oH(e){return e==null||typeof e==`boolean`?tH(HV):MI(e)?tH(BV,null,e.slice()):ZV(e)?sH(e):tH(VV,null,String(e))}function sH(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:iH(e)}function cH(e,t){let n=0,{shapeFlag:r}=e;if(t==null)t=null;else if(MI(t))n=16;else if(typeof t==`object`)if(r&65){let n=t.default;n&&(n._c&&(n._d=!1),cH(e,n()),n._c&&(n._d=!0));return}else{n=32;let r=t._;!r&&!dV(t)?t._ctx=uz:r===3&&uz&&(uz.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else if(II(t)){if(r&65){cH(e,{default:t});return}t={default:t,_ctx:uz},n=32}else t=String(t),r&64?(n=16,t=[aH(t)]):n=8;e.children=t,e.shapeFlag|=n}function lH(...e){let t={};for(let n=0;n<e.length;n++){let r=e[n];for(let e in r)if(e===`class`)t.class!==r.class&&(t.class=rL([t.class,r.class]));else if(e===`style`)t.style=nL([t.style,r.style]);else if(DI(e)){let n=t[e],i=r[e];i&&n!==i&&!(MI(n)&&n.includes(i))?t[e]=n?[].concat(n,i):i:i==null&&n==null&&!OI(e)&&(t[e]=i)}else e!==``&&(t[e]=r[e])}return t}function uH(e,t,n,r=null){GR(e,t,7,[n,r])}var dH=qB(),fH=0;function pH(e,t,n){let r=e.type,i=(t?t.appContext:e.appContext)||dH,a={uid:fH++,vnode:e,type:r,parent:t,appContext:i,root:null,next:null,subTree:null,effect:null,update:null,job:null,scope:new pce(!0),render:null,proxy:null,exposed:null,exposeProxy:null,withProxy:null,provides:t?t.provides:Object.create(i.provides),ids:t?t.ids:[``,0,0],accessCache:null,renderCache:[],components:null,directives:null,propsOptions:_V(r,i),emitsOptions:eV(r,i),emit:null,emitted:null,propsDefaults:CI,inheritAttrs:r.inheritAttrs,ctx:CI,data:CI,props:CI,attrs:CI,slots:CI,refs:CI,setupState:CI,setupContext:null,suspense:n,suspenseId:n?n.pendingId:0,asyncDep:null,asyncResolved:!1,isMounted:!1,isUnmounted:!1,isDeactivated:!1,bc:null,c:null,bm:null,m:null,bu:null,u:null,um:null,bum:null,da:null,a:null,rtg:null,rtc:null,ec:null,sp:null};return a.ctx={_:a},a.root=t?t.root:a,a.emit=QB.bind(null,a),e.ce&&e.ce(a),a}var mH=null,hH=()=>mH||uz,gH,_H;{let e=tL(),t=(t,n)=>{let r;return(r=e[t])||(r=e[t]=[]),r.push(n),e=>{r.length>1?r.forEach(t=>t(e)):r[0](e)}};gH=t(`__VUE_INSTANCE_SETTERS__`,e=>mH=e),_H=t(`__VUE_SSR_SETTERS__`,e=>xH=e)}var vH=e=>{let t=mH;return gH(e),e.scope.on(),()=>{e.scope.off(),gH(t)}},yH=()=>{mH&&mH.scope.off(),gH(null)};function bH(e){return e.vnode.shapeFlag&4}var xH=!1;function SH(e,t=!1,n=!1){t&&_H(t);let{props:r,children:i}=e.vnode,a=bH(e);fV(e,r,a,t),TV(e,i,n||t);let o=a?CH(e,t):void 0;return t&&_H(!1),o}function CH(e,t){let n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,AB);let{setup:r}=n;if(r){DL();let n=e.setupContext=r.length>1?kH(e):null,i=vH(e),a=WR(r,e,0,[e.props,n]),o=BI(a);if(OL(),i(),(o||e.sp)&&!aB(e)&&eB(e),o){if(a.then(yH,yH),t)return a.then(n=>{wH(e,n,t)}).catch(t=>{KR(t,e,0)});e.asyncDep=a}else wH(e,a,t)}else DH(e,t)}function wH(e,t,n){II(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:zI(t)&&(e.setupState=FR(t)),DH(e,n)}var TH,EH;function DH(e,t,n){let r=e.type;if(!e.render){if(!t&&TH&&!r.render){let t=r.template||LB(e).template;if(t){let{isCustomElement:n,compilerOptions:i}=e.appContext.config,{delimiters:a,compilerOptions:o}=r;r.render=TH(t,kI(kI({isCustomElement:n,delimiters:a},i),o))}}e.render=r.render||TI,EH&&EH(e)}{let t=vH(e);DL();try{NB(e)}finally{OL(),t()}}}var OH={get(e,t){return LL(e,`get`,``),e[t]}};function kH(e){return{attrs:new Proxy(e.attrs,OH),slots:e.slots,emit:e.emit,expose:t=>{e.exposed=t||{}}}}function AH(e){return e.exposed?e.exposeProxy||=new Proxy(FR(TR(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in OB)return OB[n](e)},has(e,t){return t in e||t in OB}}):e.proxy}function jH(e){return II(e)&&`__vccOpts`in e}var MH=(e,t)=>LR(e,t,xH);function NH(e,t,n){try{JV(-1);let r=arguments.length;return r===2?zI(t)&&!MI(t)?ZV(t)?tH(e,null,[t]):tH(e,t):tH(e,null,t):(r>3?n=Array.prototype.slice.call(arguments,2):r===3&&ZV(n)&&(n=[n]),tH(e,t,n))}finally{JV(1)}}var PH=`3.5.39`,FH=void 0,IH=typeof window<`u`&&window.trustedTypes;if(IH)try{FH=IH.createPolicy(`vue`,{createHTML:e=>e})}catch{}var LH=FH?e=>FH.createHTML(e):e=>e,RH=`http://www.w3.org/2000/svg`,zH=`http://www.w3.org/1998/Math/MathML`,BH=typeof document<`u`?document:null,VH=BH&&BH.createElement(`template`),HH={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{let t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,r)=>{let i=t===`svg`?BH.createElementNS(RH,e):t===`mathml`?BH.createElementNS(zH,e):n?BH.createElement(e,{is:n}):BH.createElement(e);return e===`select`&&r&&r.multiple!=null&&i.setAttribute(`multiple`,r.multiple),i},createText:e=>BH.createTextNode(e),createComment:e=>BH.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>BH.querySelector(e),setScopeId(e,t){e.setAttribute(t,``)},insertStaticContent(e,t,n,r,i,a){let o=n?n.previousSibling:t.lastChild;if(i&&(i===a||i.nextSibling))for(;t.insertBefore(i.cloneNode(!0),n),!(i===a||!(i=i.nextSibling)););else{VH.innerHTML=LH(r===`svg`?`<svg>${e}</svg>`:r===`mathml`?`<math>${e}</math>`:e);let i=VH.content;if(r===`svg`||r===`mathml`){let e=i.firstChild;for(;e.firstChild;)i.appendChild(e.firstChild);i.removeChild(e)}t.insertBefore(i,n)}return[o?o.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},UH=`transition`,WH=`animation`,GH=Symbol(`_vtc`),KH={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},qH=kI({},Hz,KH),JH=(e=>(e.displayName=`Transition`,e.props=qH,e))((e,{slots:t})=>NH(Kz,ZH(e),t)),YH=(e,t=[])=>{MI(e)?e.forEach(e=>e(...t)):e&&e(...t)},XH=e=>e?MI(e)?e.some(e=>e.length>1):e.length>1:!1;function ZH(e){let t={};for(let n in e)n in KH||(t[n]=e[n]);if(e.css===!1)return t;let{name:n=`v`,type:r,duration:i,enterFromClass:a=`${n}-enter-from`,enterActiveClass:o=`${n}-enter-active`,enterToClass:s=`${n}-enter-to`,appearFromClass:c=a,appearActiveClass:l=o,appearToClass:u=s,leaveFromClass:d=`${n}-leave-from`,leaveActiveClass:f=`${n}-leave-active`,leaveToClass:p=`${n}-leave-to`}=e,m=QH(i),h=m&&m[0],g=m&&m[1],{onBeforeEnter:_,onEnter:v,onEnterCancelled:y,onLeave:b,onLeaveCancelled:x,onBeforeAppear:S=_,onAppear:ee=v,onAppearCancelled:C=y}=t,te=(e,t,n,r)=>{e._enterCancelled=r,tU(e,t?u:s),tU(e,t?l:o),n&&n()},ne=(e,t)=>{e._isLeaving=!1,tU(e,d),tU(e,p),tU(e,f),t&&t()},w=e=>(t,n)=>{let i=e?ee:v,o=()=>te(t,e,n);YH(i,[t,o]),nU(()=>{tU(t,e?c:a),eU(t,e?u:s),XH(i)||iU(t,r,h,o)})};return kI(t,{onBeforeEnter(e){YH(_,[e]),eU(e,a),eU(e,o)},onBeforeAppear(e){YH(S,[e]),eU(e,c),eU(e,l)},onEnter:w(!1),onAppear:w(!0),onLeave(e,t){e._isLeaving=!0;let n=()=>ne(e,t);eU(e,d),e._enterCancelled?(eU(e,f),cU(e)):(cU(e),eU(e,f)),nU(()=>{e._isLeaving&&(tU(e,d),eU(e,p),XH(b)||iU(e,r,g,n))}),YH(b,[e,n])},onEnterCancelled(e){te(e,!1,void 0,!0),YH(y,[e])},onAppearCancelled(e){te(e,!0,void 0,!0),YH(C,[e])},onLeaveCancelled(e){ne(e),YH(x,[e])}})}function QH(e){if(e==null)return null;if(zI(e))return[$H(e.enter),$H(e.leave)];{let t=$H(e);return[t,t]}}function $H(e){return ace(e)}function eU(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.add(t)),(e[GH]||(e[GH]=new Set)).add(t)}function tU(e,t){t.split(/\s+/).forEach(t=>t&&e.classList.remove(t));let n=e[GH];n&&(n.delete(t),n.size||(e[GH]=void 0))}function nU(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}var rU=0;function iU(e,t,n,r){let i=e._endId=++rU,a=()=>{i===e._endId&&r()};if(n!=null)return setTimeout(a,n);let{type:o,timeout:s,propCount:c}=aU(e,t);if(!o)return r();let l=o+`end`,u=0,d=()=>{e.removeEventListener(l,f),a()},f=t=>{t.target===e&&++u>=c&&d()};setTimeout(()=>{u<c&&d()},s+1),e.addEventListener(l,f)}function aU(e,t){let n=window.getComputedStyle(e),r=e=>(n[e]||``).split(`, `),i=r(`${UH}Delay`),a=r(`${UH}Duration`),o=oU(i,a),s=r(`${WH}Delay`),c=r(`${WH}Duration`),l=oU(s,c),u=null,d=0,f=0;t===UH?o>0&&(u=UH,d=o,f=a.length):t===WH?l>0&&(u=WH,d=l,f=c.length):(d=Math.max(o,l),u=d>0?o>l?UH:WH:null,f=u?u===UH?a.length:c.length:0);let p=u===UH&&/\b(?:transform|all)(?:,|$)/.test(r(`${UH}Property`).toString());return{type:u,timeout:d,propCount:f,hasTransform:p}}function oU(e,t){for(;e.length<t.length;)e=e.concat(e);return Math.max(...t.map((t,n)=>sU(t)+sU(e[n])))}function sU(e){return e===`auto`?0:Number(e.slice(0,-1).replace(`,`,`.`))*1e3}function cU(e){return(e?e.ownerDocument:document).body.offsetHeight}function lU(e,t,n){let r=e[GH];r&&(t=(t?[t,...r]:[...r]).join(` `)),t==null?e.removeAttribute(`class`):n?e.setAttribute(`class`,t):e.className=t}var uU=Symbol(`_vod`),dU=Symbol(`_vsh`),fU={name:`show`,beforeMount(e,{value:t},{transition:n}){e[uU]=e.style.display===`none`?``:e.style.display,n&&t?n.beforeEnter(e):pU(e,t)},mounted(e,{value:t},{transition:n}){n&&t&&n.enter(e)},updated(e,{value:t,oldValue:n},{transition:r}){!t!=!n&&(r?t?(r.beforeEnter(e),pU(e,!0),r.enter(e)):r.leave(e,()=>{pU(e,!1)}):pU(e,t))},beforeUnmount(e,{value:t}){pU(e,t)}};function pU(e,t){e.style.display=t?e[uU]:`none`,e[dU]=!t}var mU=Symbol(``),hU=/(?:^|;)\s*display\s*:/;function gU(e,t,n){let r=e.style,i=LI(n),a=!1;if(n&&!i){if(t)if(LI(t))for(let e of t.split(`;`)){let t=e.slice(0,e.indexOf(`:`)).trim();n[t]??vU(r,t,``)}else for(let e in t)n[e]??vU(r,e,``);for(let i in n){i===`display`&&(a=!0);let o=n[i];o==null?vU(r,i,``):SU(e,i,!LI(t)&&t?t[i]:void 0,o)||vU(r,i,o)}}else if(i){if(t!==n){let e=r[mU];e&&(n+=`;`+e),r.cssText=n,a=hU.test(n)}}else t&&e.removeAttribute(`style`);uU in e&&(e[uU]=a?r.display:``,e[dU]&&(r.display=`none`))}var _U=/\s*!important$/;function vU(e,t,n){if(MI(n))n.forEach(n=>vU(e,t,n));else if(n??=``,t.startsWith(`--`))e.setProperty(t,n);else{let r=xU(e,t);_U.test(n)?e.setProperty(JI(r),n.replace(_U,``),`important`):e[r]=n}}var yU=[`Webkit`,`Moz`,`ms`],bU={};function xU(e,t){let n=bU[t];if(n)return n;let r=qI(t);if(r!==`filter`&&r in e)return bU[t]=r;r=YI(r);for(let n=0;n<yU.length;n++){let i=yU[n]+r;if(i in e)return bU[t]=i}return t}function SU(e,t,n,r){return e.tagName===`TEXTAREA`&&(t===`width`||t===`height`)&&LI(r)&&n===r}var CU=`http://www.w3.org/1999/xlink`;function wU(e,t,n,r,i,a=dce(t)){r&&t.startsWith(`xlink:`)?n==null?e.removeAttributeNS(CU,t.slice(6,t.length)):e.setAttributeNS(CU,t,n):n==null||a&&!aL(n)?e.removeAttribute(t):e.setAttribute(t,a?``:RI(n)?String(n):n)}function TU(e,t,n,r,i){if(t===`innerHTML`||t===`textContent`){n!=null&&(e[t]=t===`innerHTML`?LH(n):n);return}let a=e.tagName;if(t===`value`&&a!==`PROGRESS`&&!a.includes(`-`)){let r=a===`OPTION`?e.getAttribute(`value`)||``:e.value,i=n==null?e.type===`checkbox`?`on`:``:String(n);(r!==i||!(`_value`in e))&&(e.value=i),n??e.removeAttribute(t),e._value=n;return}let o=!1;if(n===``||n==null){let r=typeof e[t];r===`boolean`?n=aL(n):n==null&&r===`string`?(n=``,o=!0):r===`number`&&(n=0,o=!0)}try{e[t]=n}catch{}o&&e.removeAttribute(i||t)}function EU(e,t,n,r){e.addEventListener(t,n,r)}function DU(e,t,n,r){e.removeEventListener(t,n,r)}var OU=Symbol(`_vei`);function kU(e,t,n,r,i=null){let a=e[OU]||(e[OU]={}),o=a[t];if(r&&o)o.value=r;else{let[n,s]=MU(t);r?EU(e,n,a[t]=IU(r,i),s):o&&(DU(e,n,o,s),a[t]=void 0)}}var AU=/(Once|Passive|Capture)$/,jU=/^on:?(?:Once|Passive|Capture)$/;function MU(e){let t,n;for(;(n=e.match(AU))&&!jU.test(e);)t||={},e=e.slice(0,e.length-n[1].length),t[n[1].toLowerCase()]=!0;return[e[2]===`:`?e.slice(3):JI(e.slice(2)),t]}var NU=0,PU=Promise.resolve(),FU=()=>NU||=(PU.then(()=>NU=0),Date.now());function IU(e,t){let n=e=>{if(!e._vts)e._vts=Date.now();else if(e._vts<=n.attached)return;let r=n.value;if(MI(r)){let n=e.stopImmediatePropagation;e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0};let i=r.slice(),a=[e];for(let n=0;n<i.length&&!e._stopped;n++){let e=i[n];e&&GR(e,t,5,a)}}else GR(r,t,5,[e])};return n.value=e,n.attached=FU(),n}var LU=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,RU=(e,t,n,r,i,a)=>{let o=i===`svg`;t===`class`?lU(e,r,o):t===`style`?gU(e,n,r):DI(t)?OI(t)||kU(e,t,n,r,a):(t[0]===`.`?(t=t.slice(1),!0):t[0]===`^`?(t=t.slice(1),!1):zU(e,t,r,o))?(TU(e,t,r),!e.tagName.includes(`-`)&&(t===`value`||t===`checked`||t===`selected`)&&wU(e,t,r,o,a,t!==`value`)):e._isVueCE&&(BU(e,t)||e._def.__asyncLoader&&(/[A-Z]/.test(t)||!LI(r)))?TU(e,qI(t),r,a,t):(t===`true-value`?e._trueValue=r:t===`false-value`&&(e._falseValue=r),wU(e,t,r,o))};function zU(e,t,n,r){if(r)return!!(t===`innerHTML`||t===`textContent`||t in e&&LU(t)&&II(n));if(t===`spellcheck`||t===`draggable`||t===`translate`||t===`autocorrect`||t===`sandbox`&&e.tagName===`IFRAME`||t===`form`||t===`list`&&e.tagName===`INPUT`||t===`type`&&e.tagName===`TEXTAREA`)return!1;if(t===`width`||t===`height`){let t=e.tagName;if(t===`IMG`||t===`VIDEO`||t===`CANVAS`||t===`SOURCE`)return!1}return LU(t)&&LI(n)?!1:t in e}function BU(e,t){let n=e._def.props;if(!n)return!1;let r=qI(t);return Array.isArray(n)?n.some(e=>qI(e)===r):Object.keys(n).some(e=>qI(e)===r)}var VU=e=>{let t=e.props[`onUpdate:modelValue`]||!1;return MI(t)?e=>QI(t,e):t};function HU(e){e.target.composing=!0}function UU(e){let t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event(`input`)))}var WU=Symbol(`_assign`);function GU(e,t,n){return t&&(e=e.trim()),n&&(e=eL(e)),e}var KU={created(e,{modifiers:{lazy:t,trim:n,number:r}},i){e[WU]=VU(i);let a=r||i.props&&i.props.type===`number`;EU(e,t?`change`:`input`,t=>{t.target.composing||e[WU](GU(e.value,n,a))}),(n||a)&&EU(e,`change`,()=>{e.value=GU(e.value,n,a)}),t||(EU(e,`compositionstart`,HU),EU(e,`compositionend`,UU),EU(e,`change`,UU))},mounted(e,{value:t}){e.value=t??``},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[WU]=VU(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?eL(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},qU=[`ctrl`,`shift`,`alt`,`meta`],JU={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>qU.some(n=>e[`${n}Key`]&&!t.includes(n))},YU=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=JU[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},XU={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},ZU=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=JI(n.key);if(t.some(e=>e===r||XU[e]===r))return e(n)}))},QU=kI({patchProp:RU},HH),$U;function eW(){return $U||=OV(QU)}var tW=((...e)=>{let t=eW().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=rW(e);if(!r)return;let i=t._component;!II(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,nW(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t});function nW(e){if(e instanceof SVGElement)return`svg`;if(typeof MathMLElement==`function`&&e instanceof MathMLElement)return`mathml`}function rW(e){return LI(e)?document.querySelector(e):e}function iW(e,t){return t?.aborted?!0:e?.name===`AbortError`}function aW(e,t){if(iW(e,t))return!1;let n=e;return n?n.name===`TimeoutError`||n.status===void 0||n.status===429||n.lc_error_code===`MODEL_RATE_LIMIT`||n.status>=500:!1}function oW(){let e=Error(`Aborted`);return e.name=`AbortError`,e}function sW(e,t){return new Promise((n,r)=>{if(t?.aborted){r(oW());return}let i=()=>{clearTimeout(a),r(oW())},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}async function cW(e,t={}){let n=t.maxRetries??2,r=t.baseDelayMs??500,i=0;for(;;)try{return await e()}catch(e){if(iW(e,t.signal)||i>=n||!aW(e,t.signal))throw e;let a=r*2**i+Math.floor(Math.random()*r*.5);t.onRetry?.({attempt:i+1,error:e,waitMs:a}),await sW(a,t.signal),i++}}function lW(e={}){let{fetchResponse:t,fetchStream:n,onPersist:r,onClear:i}=e,a=gR({messages:e.messages??[],loading:!1,error:null}),o=kR(null),s=kR(!0),c=null,l=kR([]),u=kR(null);function d(){}function f(e){let t=o.value;e.deltaY<0?s.value=!1:t&&(s.value=t.scrollHeight-t.scrollTop-t.clientHeight<64)}function p(){o.value&&requestAnimationFrame(()=>{let e=o.value;!e||!s.value||(e.scrollTop=e.scrollHeight)})}function m(e,t,n){a.messages.push({role:e,content:t,timestamp:Date.now(),...n&&n.length?{focuses:n}:{}}),s.value=!0,p()}async function h(e){if(s.value=!0,n){let t=gR({role:`assistant`,content:``,timestamp:Date.now(),reasoning:``,steps:[]}),r=!1;a.messages.push(t);try{await n(a.messages.slice(0,-1),e=>{switch(e.type){case`round_start`:e.round>1&&(t.content||t.reasoning)&&(r=!0);break;case`reasoning`:r&&=(t.reasoning+=`
|
|
149
149
|
`,!1),t.reasoning+=e.delta;break;case`text`:r&&=(t.content+=`
|
|
150
150
|
`,!1),t.content+=e.delta;break;case`tool_call`:t.steps.push({name:e.name,args:e.args,status:`running`});break;case`tool_result`:for(let n=t.steps.length-1;n>=0;n--)if(t.steps[n].name===e.name&&t.steps[n].status===`running`){t.steps[n].result=e.result,t.steps[n].status=e.status,t.steps[n].durationMs=e.durationMs;break}break;case`subagent`:{let n=t.steps[t.steps.length-1];if(!n)break;n.children||=[];let r=e.label?`[${e.label}] ${e.name}`:e.name;if(e.kind===`tool_call`)n.children.push({name:r,args:e.args,status:`running`});else for(let t=n.children.length-1;t>=0;t--)if(n.children[t].status===`running`&&n.children[t].name===r){n.children[t].result=e.result,n.children[t].status=e.status||`done`;break}break}case`approval_request`:u.value={toolName:e.toolName,args:e.args,resolve:e.resolve};break}p()},e)}catch(n){if(iW(n,e)||(a.error=n.message||`请求失败,请重试`),!t.content&&!t.reasoning){let e=a.messages.indexOf(t);e>=0&&a.messages.splice(e,1)}}finally{await g()}return}try{m(`assistant`,await(t||b)(a.messages,e))}catch(t){iW(t,e)||(a.error=t.message||`请求失败,请重试`)}finally{await g()}}async function g(){try{await r?.(a.messages)}catch{}a.loading=!1,c=null;let e=l.value.shift();e!==void 0&&(m(`user`,e),a.loading=!0,a.error=null,c=new AbortController,await h(c.signal))}function _(e){l.value.splice(e,1)}async function v(e,t){if(e.trim()){if(a.loading){l.value.push(e.trim());return}m(`user`,e.trim(),t),a.loading=!0,a.error=null,c=new AbortController,await h(c.signal)}}async function y(){if(a.loading)return;let e=a.messages;for(let t=e.length-1;t>=0;t--)if(e[t].role===`assistant`){e.splice(t);break}e.some(e=>e.role===`user`)&&(a.loading=!0,a.error=null,c=new AbortController,await h(c.signal))}async function b(e){return await new Promise(e=>setTimeout(e,800+Math.random()*1200)),`收到你的消息:"${e.filter(e=>e.role===`user`).pop()?.content}"。这是一个模拟回复,请接入实际的 AI API。`}function x(){i?.(),a.messages.splice(0,a.messages.length),a.error=null}function S(){l.value=[],c?.abort()}function ee(){l.value=[],c?.abort(),c=null,a.loading=!1,a.error=null,u.value=null}function C(e){let t=u.value;t&&(u.value=null,t.resolve(e))}async function te(){if(!a.error)return;let e=a.messages,t=-1;for(let n=e.length-1;n>=0;n--)if(e[n].role===`user`){t=n;break}if(t<0)return;let n=e[t].content;e.splice(t),a.error=null,await v(n)}return{state:a,scrollContainer:o,pendingApproval:u,queuedTasks:l,sendMessage:v,removeQueuedTask:_,clearMessages:x,stop:S,reset:ee,retry:te,regenerate:y,resolveApproval:C,onScroll:d,onWheel:f}}async function uW(e){try{let t=globalThis.navigator?.clipboard;if(t&&typeof t.writeText==`function`)return await t.writeText(e),!0}catch{}try{let t=globalThis.document;if(!t||!t.body)return!1;let n=t.createElement(`textarea`);n.value=e,n.setAttribute(`readonly`,``),n.style.position=`fixed`,n.style.top=`0`,n.style.left=`0`,n.style.opacity=`0`,t.body.appendChild(n),n.select();let r=t.execCommand(`copy`);return t.body.removeChild(n),r}catch{return!1}}var dW=Symbol(`chatContext`);function fW(e={}){let t=lW({fetchResponse:e.fetchResponse,fetchStream:e.fetchStream,messages:e.messages,onPersist:e.onPersist,onClear:e.onClear}),{state:n,sendMessage:r,removeQueuedTask:i,queuedTasks:a}=t,o=kR(``),s=kR(!0),c=()=>{s.value=!s.value},l=kR(!1),u=()=>{l.value=!0},d=()=>{l.value=!1},f=kR(!1),p=()=>{f.value=!0},m=()=>{f.value=!1},h=kR({}),g=e=>h.value[e]!==!1,_=e=>{h.value[e]=!g(e)},v=kR(!1),y=e=>{uW(e).then(e=>{e&&(v.value=!0,setTimeout(()=>{v.value=!1},1500))})},b=MH(()=>{let t=e.getInfo?.();return{mcp:t?.mcp?.servers?.length??0,tools:t?.tools?.length??0}}),x=MH(()=>(n.messages.length,typeof e.canUndo==`function`&&!!e.canUndo())),S=()=>{e.onUndo?.()&&(n.error=null)},ee=e=>new Date(e).toLocaleTimeString(`zh-CN`,{hour:`2-digit`,minute:`2-digit`}),C=()=>{o.value.trim()&&(r(o.value,re.value),o.value=``)},te=e=>{e.isComposing||e.keyCode===229||e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),C())},ne=e=>{o.value=a.value[e]||``,i(e)},w=e=>{let t=n.messages,r=t[e];if(!r||r.role!==`assistant`)return!1;let i=`reasoning`in r?r.reasoning:void 0;return n.loading&&e===t.length-1&&!r.content&&!i},re=MH(()=>(e.infoTick?.value,e.getFocuses?.()??[]));return{chat:t,inputText:o,isExpanded:s,toggleCollapse:c,debugVisible:l,openDebug:u,closeDebug:d,skillVisible:f,openSkill:p,closeSkill:m,reasoningExpanded:h,isReasoningExpanded:g,toggleReasoning:_,copiedMsg:v,copyMessage:y,summary:b,canUndo:x,undo:S,formatTime:ee,send:C,keydown:te,editQueued:ne,isPendingAssistant:w,focuses:re,addFocus:t=>e.onAddFocus?e.onAddFocus(t):{ok:!1,error:`focus 未启用`},removeFocus:t=>{e.onRemoveFocus?.(t)},clearFocus:()=>{e.onClearFocus?.()},focusChipClick:t=>{e.onFocusChipClick?.(t)}}}function pW(){let e=_z(dW);if(!e)throw Error(`useChatContext 必须在 provide(chatContextKey) 的组件子树内调用`);return e}var mW={class:`chat-header`},hW={class:`header-left`},gW={class:`header-title`},_W={key:0,class:`status-dot pulse`},vW=[`data-sid`,`onClick`],yW={class:`hist-title`},bW={class:`hist-meta`},xW=[`onClick`],SW={key:0,class:`debug-badge`},CW={key:0,class:`more-item-badge`},wW=[`disabled`],TW=$z({__name:`ChatHeader`,props:{title:{},drawer:{type:Boolean},debugLogs:{},skillAvailable:{type:Boolean},sessions:{},currentSessionId:{},onNewSession:{type:Function},onOpenSession:{type:Function},onRemoveSession:{type:Function}},emits:[`close`],setup(e){let t=e,n=pW(),{chat:r}=n,{state:i,reset:a,clearMessages:o}=r,s=kR(!1),c=kR(!1),l=MH(()=>i.messages.length>0),u=MH(()=>(t.debugLogs?.length??0)>0);function d(e){let t=Date.now()-e;return t<6e4?`刚刚`:t<36e5?Math.floor(t/6e4)+`分钟前`:new Date(e).toLocaleString()}function f(){a(),t.onNewSession?.()}function p(e){a(),t.onOpenSession?.(e)}return(t,r)=>(Y(),X(`div`,mW,[Z(`div`,hW,[r[10]||=Z(`span`,{class:`header-icon`},`🤖`,-1),Z(`span`,gW,q(e.title),1),J(i).loading?(Y(),X(`span`,_W)):Q(``,!0)]),Z(`div`,{class:`header-actions`,onClick:r[8]||=YU(()=>{},[`stop`])},[e.sessions?(Y(),X(`button`,{key:0,class:`action-btn`,"data-test":`new-chat`,title:`新建会话`,onClick:f},[...r[11]||=[Z(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`2`},[Z(`path`,{d:`M12 5v14M5 12h14`})],-1)]])):Q(``,!0),e.sessions?(Y(),X(`button`,{key:1,class:rL([`action-btn`,{active:c.value}]),"data-test":`toggle-history`,title:`历史记录`,onClick:r[0]||=e=>{s.value=!1,c.value=!c.value}},[...r[12]||=[Z(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`2`},[Z(`path`,{d:`M3 12a9 9 0 1 0 3-6.7L3 8`}),Z(`path`,{d:`M3 3v5h5`}),Z(`path`,{d:`M12 7v5l3 2`})],-1)]],2)):Q(``,!0),e.sessions&&c.value?(Y(),X(`div`,{key:2,class:`cs-history-menu`,onClick:r[1]||=YU(()=>{},[`stop`])},[(Y(!0),X(BV,null,wB(e.sessions,t=>(Y(),X(`div`,{key:t.sessionId,class:rL([`hist-item`,{active:e.currentSessionId===t.sessionId}]),"data-sid":t.sessionId,onClick:e=>p(t.sessionId)},[Z(`div`,yW,q(t.title||`会话 `+t.sessionId.slice(-6)),1),Z(`div`,bW,[Z(`span`,null,q(d(t.lastAccessed)),1),e.currentSessionId===t.sessionId?Q(``,!0):(Y(),X(`button`,{key:0,class:`hist-del`,"data-test":`del-btn`,onClick:YU(n=>e.onRemoveSession?.(t.sessionId),[`stop`])},`✕`,8,xW))])],10,vW))),128))])):Q(``,!0),Z(`button`,{class:rL([`action-btn more-btn`,{active:s.value}]),title:`更多`,onClick:r[2]||=e=>{c.value=!1,s.value=!s.value}},[r[13]||=Z(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`currentColor`},[Z(`circle`,{cx:`12`,cy:`5`,r:`1.6`}),Z(`circle`,{cx:`12`,cy:`12`,r:`1.6`}),Z(`circle`,{cx:`12`,cy:`19`,r:`1.6`})],-1),u.value?(Y(),X(`span`,SW,q(e.debugLogs?.length),1)):Q(``,!0)],2),s.value?(Y(),X(`div`,{key:3,class:`more-menu`,onClick:r[6]||=YU(()=>{},[`stop`])},[Z(`button`,{class:`more-item`,title:`日志 / 执行流程 / Agent 信息`,onClick:r[3]||=e=>{J(n).openDebug(),s.value=!1}},[r[14]||=Z(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`2`},[Z(`path`,{d:`M9 2v8l-3 3v2h12v-2l-3-3V2`}),Z(`path`,{d:`M9 2h6`}),Z(`path`,{d:`M9 18h6`})],-1),r[15]||=Z(`span`,null,`调试 / 日志`,-1),u.value?(Y(),X(`span`,CW,q(e.debugLogs?.length),1)):Q(``,!0)]),e.skillAvailable?(Y(),X(`button`,{key:0,class:`more-item`,title:`创建 / 管理自定义 Skill`,onClick:r[4]||=e=>{J(n).openSkill(),s.value=!1}},[...r[16]||=[Z(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`2`},[Z(`path`,{d:`M12 2l2.4 7.4H22l-6 4.4 2.3 7.2L12 16.8 5.7 21l2.3-7.2-6-4.4h7.6z`})],-1),Z(`span`,null,`Skill 管理`,-1)]])):Q(``,!0),Z(`button`,{class:`more-item`,title:`清空对话`,disabled:!l.value,onClick:r[5]||=e=>{J(o)(),s.value=!1}},[...r[17]||=[Z(`svg`,{width:`15`,height:`15`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`2`},[Z(`polyline`,{points:`3 6 5 6 21 6`}),Z(`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`})],-1),Z(`span`,null,`清空对话`,-1)]],8,wW)])):Q(``,!0),e.drawer?(Y(),X(`button`,{key:4,class:`action-btn`,title:`关闭`,onClick:r[7]||=e=>t.$emit(`close`)},[...r[18]||=[Z(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`2`},[Z(`path`,{d:`M18 6L6 18M6 6l12 12`})],-1)]])):Q(``,!0)]),s.value||c.value?(Y(),X(`div`,{key:0,class:`more-overlay`,onClick:r[9]||=e=>{s.value=!1,c.value=!1}})):Q(``,!0)]))}}),EW=(e,t)=>{let n=e.__vccOpts||e;for(let[e,r]of t)n[e]=r;return n},DW=EW(TW,[[`__scopeId`,`data-v-faeba147`]]),OW={key:0,class:`focus-bar`},kW={class:`focus-bar-text`},AW={key:0,class:`focus-bar-label`},jW={class:`focus-bar-path`},MW={key:0,class:`focus-edit-row`},NW=EW($z({__name:`FocusBar`,props:{getFocus:{type:Function},onSetFocus:{type:Function},onClearFocus:{type:Function},infoTick:{}},setup(e){let t=e,n=MH(()=>(t.infoTick?.value,t.getFocus?.())),r=kR(!1),i=kR(``),a=kR(``);function o(){let e=i.value.trim();if(!e||!t.onSetFocus)return;let n=a.value.trim();t.onSetFocus({path:e,...n?{label:n}:{}})?.ok&&(r.value=!1,i.value=``,a.value=``)}function s(){t.onClearFocus?.(),r.value=!1}return(e,t)=>n.value?(Y(),X(`div`,OW,[t[3]||=Z(`span`,{class:`focus-bar-icon`},`🎯`,-1),Z(`span`,kW,[n.value.label?(Y(),X(`span`,AW,q(n.value.label),1)):Q(``,!0),Z(`code`,jW,q(n.value.path),1)]),Z(`button`,{class:`focus-bar-btn`,title:`切换聚焦路径`,onClick:t[0]||=e=>r.value=!r.value},`▾`),Z(`button`,{class:`focus-bar-btn`,title:`退出精修`,"data-test":`focus-clear`,onClick:s},`✕`),r.value?(Y(),X(`div`,MW,[mz(Z(`input`,{"onUpdate:modelValue":t[1]||=e=>i.value=e,class:`focus-edit-input`,placeholder:`jsonPath,如 components.3`,"data-test":`focus-path-input`,onKeyup:ZU(o,[`enter`])},null,544),[[KU,i.value]]),mz(Z(`input`,{"onUpdate:modelValue":t[2]||=e=>a.value=e,class:`focus-edit-input focus-edit-label`,placeholder:`标签(可选)`,onKeyup:ZU(o,[`enter`])},null,544),[[KU,a.value]]),Z(`button`,{class:`focus-edit-go`,"data-test":`focus-submit`,onClick:o},`聚焦`)])):Q(``,!0)])):Q(``,!0)}}),[[`__scopeId`,`data-v-0d078a41`]]),PW={class:`reasoning-toggle`},FW={key:0,class:`reasoning-body`},IW=EW($z({__name:`MessageReasoning`,props:{text:{},expanded:{type:Boolean}},emits:[`toggle`],setup(e){return(t,n)=>e.text?(Y(),X(`div`,{key:0,class:rL([`reasoning-block`,{expanded:e.expanded}])},[Z(`div`,{class:`reasoning-header`,onClick:n[0]||=e=>t.$emit(`toggle`)},[n[1]||=Z(`span`,{class:`status-dot ok`},null,-1),n[2]||=Z(`span`,{class:`reasoning-title`},`思考过程`,-1),Z(`span`,PW,q(e.expanded?`收起`:`展开`),1)]),e.expanded?(Y(),X(`div`,FW,q(e.text),1)):Q(``,!0)],2)):Q(``,!0)}}),[[`__scopeId`,`data-v-01f28016`]]),LW={key:0,class:`steps-block`},RW={class:`step-head`},zW={class:`step-name`},BW={key:0,class:`step-count`},VW={key:1,class:`step-duration`},HW={key:0,class:`step-children`},UW={class:`step-name`},WW={key:0,class:`step-status running`},GW=EW($z({__name:`MessageSteps`,props:{steps:{}},setup(e){let t=e;function n(e){return e===`running`?`执行中`:e===`error`?`失败`:`成功`}function r(e){let t=[];for(let n of e){let e=t.length?t[t.length-1]:null;e&&e.name===n.name?(e.count++,n.status===`running`&&(e.hasRunning=!0),n.status===`error`&&(e.hasError=!0),n.durationMs&&(e.totalMs+=n.durationMs),n.children?.length&&e.children.push(...n.children)):t.push({name:n.name,count:1,hasRunning:n.status===`running`,hasError:n.status===`error`,children:n.children?.length?[...n.children]:[],totalMs:n.durationMs??0})}return t.map(e=>({name:e.name,count:e.count,status:e.hasError?`error`:e.hasRunning?`running`:`done`,children:e.children,durationMs:e.totalMs||void 0}))}let i=MH(()=>r(t.steps));return(t,r)=>e.steps.length?(Y(),X(`div`,LW,[(Y(!0),X(BV,null,wB(i.value,(e,t)=>(Y(),X(`div`,{key:t,class:rL([`step-item`,e.status])},[Z(`div`,RW,[Z(`span`,{class:rL([`status-dot`,e.status])},null,2),Z(`span`,zW,q(e.name),1),e.count>1?(Y(),X(`span`,BW,`×`+q(e.count),1)):Q(``,!0),Z(`span`,{class:rL([`step-status`,e.status])},q(n(e.status)),3),e.durationMs!=null&&e.status!==`running`?(Y(),X(`span`,VW,q(e.durationMs)+`ms`,1)):Q(``,!0)]),e.children&&e.children.length?(Y(),X(`div`,HW,[r[0]||=Z(`div`,{class:`step-children-label`},`🧬 子 agent 进度`,-1),(Y(!0),X(BV,null,wB(e.children,(e,t)=>(Y(),X(`div`,{key:t,class:rL([`step-child`,e.status])},[Z(`span`,{class:rL([`status-dot sm`,e.status])},null,2),Z(`span`,UW,q(e.name),1),e.status===`running`?(Y(),X(`span`,WW,`…`)):Q(``,!0)],2))),128))])):Q(``,!0)],2))),128))])):Q(``,!0)}}),[[`__scopeId`,`data-v-c9f48455`]]);function KW(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var qW=KW();function JW(e){qW=e}var YW={exec:()=>null};function XW(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function ZW(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace($W.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var QW=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),$W={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:XW(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:XW(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:XW(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:XW(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:XW(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:XW(e=>RegExp(`^ {0,${e}}>`))},eG=/^(?:[ \t]*(?:\n|$))+/,tG=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,nG=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,rG=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,iG=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,aG=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,oG=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,sG=ZW(oG).replace(/bull/g,aG).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),cG=ZW(oG).replace(/bull/g,aG).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),lG=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,uG=/^[^\n]+/,dG=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,fG=ZW(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,dG).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),pG=ZW(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,aG).getRegex(),mG=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,hG=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,gG=ZW(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n+|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n+|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n+|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,hG).replace(`tag`,mG).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),_G=e=>ZW(lG).replace(`hr`,rG).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,e).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,mG).getRegex(),vG=_G(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),yG=_G(/ {0,3}(?:[*+-]|\d{1,9}[.)])[ \t]+[^ \t\n]/),bG={blockquote:ZW(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,yG).getRegex(),code:tG,def:fG,fences:nG,heading:iG,hr:rG,html:gG,lheading:sG,list:pG,newline:eG,paragraph:vG,table:YW,text:uG},xG=ZW(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,rG).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,mG).getRegex(),SG={...bG,lheading:cG,table:xG,paragraph:ZW(lG).replace(`hr`,rG).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,xG).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,mG).getRegex()},CG={...bG,html:ZW(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,hG).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:YW,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:ZW(lG).replace(`hr`,rG).replace(`heading`,` *#{1,6} *[^
|
|
151
151
|
]`).replace(`lheading`,sG).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},wG=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,TG=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,EG=/^( {2,}|\\)\n(?!\s*$)/,DG=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,OG=/[\p{P}\p{S}]/u,kG=/[\s\p{P}\p{S}]/u,AG=/[^\s\p{P}\p{S}]/u,jG=ZW(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,kG).getRegex(),MG=/(?!~)[\p{P}\p{S}]/u,NG=/(?!~)[\s\p{P}\p{S}]/u,PG=/(?:[^\s\p{P}\p{S}]|~)/u,FG=ZW(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,QW?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),IG=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,LG=ZW(IG,`u`).replace(/punct/g,OG).getRegex(),RG=ZW(IG,`u`).replace(/punct/g,MG).getRegex(),zG=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,BG=ZW(zG,`gu`).replace(/notPunctSpace/g,AG).replace(/punctSpace/g,kG).replace(/punct/g,OG).getRegex(),VG=ZW(zG,`gu`).replace(/notPunctSpace/g,PG).replace(/punctSpace/g,NG).replace(/punct/g,MG).getRegex(),HG=ZW(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,AG).replace(/punctSpace/g,kG).replace(/punct/g,OG).getRegex(),UG=ZW(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,OG).getRegex(),WG=ZW(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,AG).replace(/punctSpace/g,kG).replace(/punct/g,OG).getRegex(),GG=ZW(/\\(punct)/,`gu`).replace(/punct/g,OG).getRegex(),KG=ZW(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),qG=ZW(hG).replace(`(?:-->|$)`,`-->`).getRegex(),JG=ZW(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,qG).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),YG=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,XG=ZW(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,YG).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ZG=ZW(/^!?\[(label)\]\[(ref)\]/).replace(`label`,YG).replace(`ref`,dG).getRegex(),QG=ZW(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,dG).getRegex(),$G=ZW(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,ZG).replace(`nolink`,QG).getRegex(),eK=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,tK={_backpedal:YW,anyPunctuation:GG,autolink:KG,blockSkip:FG,br:EG,code:TG,del:YW,delLDelim:YW,delRDelim:YW,emStrongLDelim:LG,emStrongRDelimAst:BG,emStrongRDelimUnd:HG,escape:wG,link:XG,nolink:QG,punctuation:jG,reflink:ZG,reflinkSearch:$G,tag:JG,text:DG,url:YW},nK={...tK,link:ZW(/^!?\[(label)\]\((.*?)\)/).replace(`label`,YG).getRegex(),reflink:ZW(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,YG).getRegex()},rK={...tK,emStrongRDelimAst:VG,emStrongLDelim:RG,delLDelim:UG,delRDelim:WG,url:ZW(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,eK).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:ZW(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,eK).getRegex()},iK={...rK,br:ZW(EG).replace(`{2,}`,`*`).getRegex(),text:ZW(rK.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},aK={normal:bG,gfm:SG,pedantic:CG},oK={normal:tK,gfm:rK,breaks:iK,pedantic:nK},sK={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},cK=e=>sK[e];function lK(e,t){if(t){if($W.escapeTest.test(e))return e.replace($W.escapeReplace,cK)}else if($W.escapeTestNoEncode.test(e))return e.replace($W.escapeReplaceNoEncode,cK);return e}function uK(e){try{e=encodeURI(e).replace($W.percentDecode,`%`)}catch{return null}return e}function dK(e,t){let n=e.replace($W.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split($W.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace($W.slashPipe,`|`);return n}function fK(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function pK(e){let t=e.split(`
|
|
@@ -257,7 +257,7 @@ app.mount('#app');
|
|
|
257
257
|
`+t+`
|
|
258
258
|
提示:改某组件深层字段前,先 schema_data({jsonPath}) 查完整约束(advanced);或 read 子路径见实际值。`}return n}return e?.description||`(用 read 查看实际形状)`}var l0=new Set([`set_data`,`edit_data`,`delete_data`,`write`,`vfs_write`,`vfs_edit`]);function u0(e){let t=e??{},n=new Set;if(typeof t.jsonPath==`string`&&t.jsonPath&&n.add(t.jsonPath),typeof t.path==`string`&&t.path&&n.add(t.path),t.patch&&typeof t.patch.jsonPath==`string`&&t.patch.jsonPath&&n.add(t.patch.jsonPath),Array.isArray(t.patches))for(let e of t.patches)e&&typeof e.jsonPath==`string`&&e.jsonPath&&n.add(e.jsonPath);return[...n]}function d0(e,t){return e===t||e.startsWith(t+`.`)}function f0(e){let t=e.initialFocuses?[...e.initialFocuses]:[];return{name:`focus`,beforeAgent:()=>t.length?{focuses:[...t],focus:t[0]}:{},augmentPrompt:()=>{if(!t.length)return;let n=[`## 当前精修目标`,t.map(e=>`· ${e.path}${e.label?`(${e.label})`:``}`).join(`
|
|
259
259
|
`),`仅操作上述 ${t.length} 个聚焦子树${t.length>1?`之一`:``},不要改动其他组件;需改其他组件请先 remove_focus / clear_focus 或换焦点。`],r=e.getSchema();if(r){let e=t.map(e=>{let t=P1(r,e.path);return t?s0(t):null}).filter(e=>!!e);e.length&&n.push(``,`## 焦点子树结构(仅此范围可操作)`,...e)}return n.join(`
|
|
260
|
-
`)},wrapToolCall:async(e,n)=>{if(t.length&&l0.has(e.name)){let n=u0(e.args);for(let e of n)if(!t.some(t=>d0(e,t.path)))return{content:`PATH_DENIED · 聚焦越界:当前聚焦 [${t.map(e=>e.label?`${e.path}(${e.label})`:e.path).join(`, `)}],不可操作「${e}」。请先 remove_focus / clear_focus 或换焦点后重试。`,status:`error`}}return n(e)},setFocus:e=>{t=e?[e]:[]},getFocus:()=>t[0],getFocuses:()=>[...t],addFocus:e=>{let n=t.findIndex(t=>t.path===e.path);n>=0?t[n]=e:t.push(e)},removeFocus:e=>{t=t.filter(t=>t.path!==e)},clearFocus:()=>{t=[]},reset:()=>{t=[]}}}var p0=10,
|
|
260
|
+
`)},wrapToolCall:async(e,n)=>{if(t.length&&l0.has(e.name)){let n=u0(e.args);for(let e of n)if(!t.some(t=>d0(e,t.path)))return{content:`PATH_DENIED · 聚焦越界:当前聚焦 [${t.map(e=>e.label?`${e.path}(${e.label})`:e.path).join(`, `)}],不可操作「${e}」。请先 remove_focus / clear_focus 或换焦点后重试。`,status:`error`}}return n(e)},setFocus:e=>{t=e?[e]:[]},getFocus:()=>t[0],getFocuses:()=>[...t],addFocus:e=>{let n=t.findIndex(t=>t.path===e.path);n>=0?t[n]=e:t.push(e)},removeFocus:e=>{t=t.filter(t=>t.path!==e)},clearFocus:()=>{t=[]},reset:()=>{t=[]}}}var p0=10,m0=new Set([`read`,`query_data`,`search_data`]);function yce(){let e=[],t={},n=()=>e.length===0&&Object.keys(t).length===0,r=()=>({locatedPaths:[...e],lastHashes:{...t}});function i(t){if(!t)return;let n=e.indexOf(t);for(n>=0&&e.splice(n,1),e.unshift(t);e.length>p0;)e.pop()}function a(e,n){if(t[e]===n)return;delete t[e],t[e]=n;let r=Object.keys(t);for(;r.length>p0;){let e=r.shift();delete t[e]}}return{name:`workingMemory`,beforeAgent:()=>n()?void 0:{workingMemory:r()},beforeModel:()=>n()?void 0:{workingMemory:r()},wrapToolCall:async(e,t)=>{let n=await t(e);if(n.status===`done`&&m0.has(e.name)){let t=typeof n.content==`string`?n.content:``;if(e.name===`read`){let n=e.args?.jsonPath||`(root)`;i(n);let r=t.match(/hash=([0-9a-f]{6,})/i);r&&a(n,r[1])}else{let n=e.args?.jsonPath||``;n&&i(n);let r=t.match(/@\s([a-zA-Z0-9_.[\]]+)/g);r&&r.forEach(e=>i(e.replace(/^@\s/,``)))}}return n},augmentPrompt:e=>{let t=e.workingMemory;if(!t||t.locatedPaths.length===0&&Object.keys(t.lastHashes).length===0)return;let n=[`## 工作记忆(跨压缩保留,勿重复检索)`];return t.locatedPaths.length&&n.push(`最近定位:`+t.locatedPaths.join(`, `)),Object.keys(t.lastHashes).length&&n.push(`最近 hash:`+Object.entries(t.lastHashes).map(([e,t])=>`${e}=${t.slice(0,8)}`).join(`, `)),n.join(`
|
|
261
261
|
`)},getWorkingMemory:()=>n()?void 0:r(),reset:()=>{e.length=0;for(let e of Object.keys(t))delete t[e]},restore:n=>{e.length=0,e.push(...n.locatedPaths.slice(0,p0));for(let e of Object.keys(t))delete t[e];Object.assign(t,n.lastHashes)}}}function h0(e){let t=(t,n)=>{try{Object.defineProperty(e,t,{configurable:!1,writable:!1,value:n})}catch{}};if(t(`fetch`,()=>{throw Error(`fetch 已被沙箱禁用`)}),t(`XMLHttpRequest`,function(){throw Error(`XMLHttpRequest 已被沙箱禁用`)}),t(`importScripts`,()=>{throw Error(`importScripts 已被沙箱禁用`)}),t(`WebSocket`,function(){throw Error(`WebSocket 已被沙箱禁用`)}),t(`indexedDB`,void 0),t(`caches`,void 0),t(`Worker`,void 0),t(`SharedWorker`,void 0),t(`EventSource`,void 0),t(`BroadcastChannel`,void 0),e.navigator)try{Object.defineProperty(e.navigator,"sendBeacon",{configurable:!1,writable:!1,value:()=>{throw Error(`sendBeacon 已被沙箱禁用`)}})}catch{}}var g0=`(${h0.toString()})(self);`,_0=[{re:/\bimport\s*\(/,msg:`动态 import() 拉外网模块`},{re:/\bimport\s+[\w'"]/,msg:`import 语句`},{re:/\beval\s*\(/,msg:`eval() 动态执行`},{re:/\bFunction\s*\(/,msg:`Function() 构造`},{re:/new\s+Function\b/,msg:`new Function() 构造`},{re:/\brequire\s*\(/,msg:`require() 拉模块`}];function v0(e,t=3e3){return async n=>{for(let{re:t,msg:n}of _0)if(t.test(e))return{ok:!1,error:`沙箱拒绝执行:脚本含禁用模式(${n})`,elapsedMs:0};return new Promise(r=>{let i=Date.now(),a=!1,o=e=>{if(!a){a=!0,clearTimeout(u);try{l.terminate()}catch{}URL.revokeObjectURL(c),r({...e,elapsedMs:Date.now()-i})}},s=g0+`
|
|
262
262
|
self.onmessage = async (e) => {
|
|
263
263
|
try {
|
|
@@ -331,6 +331,6 @@ ${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.t
|
|
|
331
331
|
`)}catch(t){let r=t?.message||String(t);return n.signal.aborted?`获取失败:请求超时(${A9}ms,${e})。`:/Failed to fetch|NetworkError|CORS|blocked/i.test(r)?`获取失败:可能是 CORS 跨域拦截或网络错误(${r})。浏览器仅能 GET 同源或服务端已配置 CORS 的资源;跨域抓取需后端代理。`:`获取失败:${r}`}finally{clearTimeout(r)}},{name:`fetch_document`,description:`以 GET 请求抓取文档/网页/接口文本。仅支持同源或已配置 CORS 的 URL;跨域会被浏览器拦截。大结果自动外存到虚拟工作区,可用 vfs_read / vfs_grep 回读。`,schema:F({url:N().describe(`要抓取的 URL(同源或已配 CORS)`),as:df([`text`,`markdown`]).optional().describe(`返回格式标签,默认 text`)})})];bm();var Mfe=[`id`,`class`,`href`,`src`,`alt`,`title`,`style`,`role`,`aria-label`,`name`,`type`],Nfe=/^(value|srcdoc|formaction|on\w+)$/i,Pfe=/token|secret|password|passwd|api[-_]?key|auth|cred|csrf|session/i;function M9(e,t){if(!e)return null;let{depth:n,attrs:r,includeText:i=!0}=t,a=r!==void 0,o=r??Mfe,s=e=>{let t={};for(let n of Array.from(e.attributes))(a?o.includes(n.name):o.includes(n.name)||n.name.startsWith(`data-`))&&(Nfe.test(n.name)||Pfe.test(n.name)||(t[n.name]=n.value));return t},c=(e,t)=>{let n={tag:e.tagName.toLowerCase(),attrs:s(e)};if(i){let t=Array.from(e.childNodes).filter(e=>e.nodeType===3).map(e=>e.textContent||``).join(``).trim();t&&(n.text=t)}let r=Array.from(e.children);return t>0?r.length&&(n.children=r.map(e=>c(e,t-1))):r.length&&(n.childCount=r.length),n};return c(e,n)}var N9=gI(({selector:e,depth:t,attrs:n,includeText:r})=>{let i=e?document.querySelector(e):document.body;if(!i)return`未找到匹配元素:selector="${e}"`;let a=M9(i,{depth:t??3,attrs:n,includeText:r??!0});return a?JSON.stringify(a,null,2):`selector="${e}" 未匹配到元素`},{name:`get_dom`,description:`读取页面渲染后的 DOM 结构(结构化返回 tag/attrs/text/children)。用于检查实际渲染效果、定位元素、验证修改是否生效(改完数据看页面是否如期变化)。depth 控制遍历深度(默认 3,防大 DOM 爆 token),attrs 限定返回属性(默认 id/class/style/href 等常用 + data-*)。大结果自动外存 vfs。`,schema:F({selector:N().optional().describe(`CSS 选择器(默认 body,读整个页面)`),depth:Nd().int().min(0).max(10).optional().describe(`遍历深度(默认 3;0 只读根节点)`),attrs:P(N()).optional().describe(`属性白名单(传了 = 严格白名单;不传 = 默认常用 + data-*)`),includeText:zd().optional().describe(`是否包含直接文本(默认 true)`)})}),P9=[N9];bm();function Ffe(e){let t=e;return typeof t.tagName==`string`||typeof t.nodeType==`number`&&typeof t.nodeName==`string`}function F9(e,t=3,n=2e3,r){if(e==null)return e;if(typeof e==`string`)return e.length>n?e.slice(0,n)+`…(已截断)`:e;if(typeof e==`number`||typeof e==`boolean`)return e;if(typeof e==`function`)return`[Function: ${e.name||`anonymous`}]`;if(typeof e==`symbol`)return e.toString();if(typeof e==`bigint`)return`${e.toString()}n`;if(typeof e!=`object`)return String(e);let i=e;if(Ffe(i)){let e=i;return e.tagName?`[Element: <${e.tagName.toLowerCase()}>]`:`[Node: ${e.nodeName}]`}if(r?.has(i))return`[Circular]`;let a=r??new WeakSet;if(a.add(i),Array.isArray(e)){let r=e.slice(0,100).map(e=>F9(e,t-1,n,a));return e.length>100&&r.push(`…(共 ${e.length} 项,已截断)`),r}if(t<0)return`(对象,已截断)`;let o={},s=Object.keys(i);for(let e=0;e<s.length;e++){let r=s[e];if(e>=50){o[`…`]=`(共 ${s.length} 键,已截断)`;break}try{o[r]=F9(i[r],t-1,n,a)}catch{o[r]=`(getter 抛错)`}}return o}function I9(e){let t=e??(typeof window<`u`?window:{}),n=t.navigator,r=t.location,i=t.document;return{location:{href:r?.href,origin:r?.origin,protocol:r?.protocol,host:r?.host,hostname:r?.hostname,pathname:r?.pathname,search:r?.search},navigator:{userAgent:n?.userAgent,language:n?.language,languages:n?.languages,platform:n?.platform,onLine:n?.onLine},viewport:{innerWidth:t.innerWidth,innerHeight:t.innerHeight,devicePixelRatio:t.devicePixelRatio,scrollX:t.scrollX,scrollY:t.scrollY},document:i?{title:i.title,readyState:i.readyState,characterSet:i.characterSet}:`(无 document)`}}var Ife=/^(localStorage|sessionStorage|cookie|document|frames|frameElement|opener|parent|top|self|window|globalThis|closed|history|navigation|trustedTypes|origin|crossOriginIsolated)$/,Lfe=/token|secret|password|passwd|api[-_]?key|auth|cred|csrf|session|ticket/i,L9=gI(({key:e})=>{if(e){if(Ife.test(e)||Lfe.test(e))return JSON.stringify({key:e,denied:!0,reason:`安全:该 key 在 denylist(localStorage/sessionStorage/cookie/document 或敏感命名 token/secret/key/auth),不读取防泄漏`},null,2);let t=(typeof window<`u`?window:{})[e];return JSON.stringify({key:e,exists:t!==void 0,type:typeof t,value:F9(t)},null,2)}return JSON.stringify(I9(),null,2)},{name:`inspect_env`,description:`读取宿主页面环境信息(排查调试用,默认开启)。不传参 = 返回环境摘要(location 的 URL/origin/path、navigator 的浏览器/语言、viewport 视口尺寸、document 的 title/readyState);传 key = 读取指定 window 属性值(如 inspect_env({key:"appConfig"}) 读集成方挂的调试变量 window.appConfig)。用于排查「当前页面在哪/什么浏览器/视口多大/调试变量值是什么」。轻量只读,大结果自动外存 vfs。`,schema:F({key:N().optional().describe(`要读取的 window 属性名(如 "appConfig"/"__DEBUG__");不传 = 返回环境摘要`)})}),R9=[L9];function Rfe(e,t,n){let r=0;return{name:`budget`,beforeAgent:()=>{r=Date.now()},wrapModelCall:async(i,a)=>{let{tokenBudget:o,timeBudgetMs:s}=t,c=o!=null&&(e.total_tokens??0)>o,l=s!=null&&Date.now()-r>s;return c||l?(n({type:`error`,severity:`observable`,code:`BUDGET_EXCEEDED`,message:`资源预算超限:${c?`token 超限(累计 ${e.total_tokens??0} > 上限 ${o})`:`时间超限(${Date.now()-r}ms > 上限 ${s}ms)`},agent 已停止(未完成部分可用 restoreLastCheckpoint 回退)。`}),{message:new xS({content:``}),content:``,toolCalls:[],aborted:!0}):a(i)}}}bm();var z9=/^[a-zA-Z][a-zA-Z0-9_]*$/;function B9(e){let t=[];for(let[n,r]of Object.entries(e)){if(!z9.test(n)){console.warn(`[page-agent-sdk][actions] 动作名 "${n}" 非法(须匹配 ${z9}),已跳过`);continue}let e=r.description||`宿主动作 ${n}`;t.push(gI(async e=>{try{let t=await r.run(e||{});return t===void 0?`动作 ${n} 执行完成。`:typeof t==`string`?t:JSON.stringify(t)}catch(e){let t=e?.message||String(e);return`动作 ${n} 执行失败:${t}`}},{name:n,description:e,schema:r.params??F({})}))}return t}function V9(e){let t={};for(let[n,r]of Object.entries(e))z9.test(n)&&(t[n]={description:r.description,hasParams:!!r.params});return t}var zfe=j9,Bfe=P9;function Vfe(e,t){return k9(e,t)}function H9(e,t,n,r,i){let a=N7(e);return[...a.dataOps?t:[],...a.fetch?n:[],...a.domInspect&&r?r:[],...a.inspectEnv&&i?i:[]]}function Hfe(e){let t=new Map,n=[];for(let r of e)for(let e of r.tools){let i=t.get(e.name);i&&n.push({name:e.name,winner:r.label,loser:i.label}),t.set(e.name,{tool:e,label:r.label})}return{tools:[...t.values()].map(e=>e.tool),collisions:n}}var U9=.7;function W9(e,t,n=`simple`,r=!1){let i=N7(e),a=n!==`advanced`;return{name:`usageHints`,augmentPrompt:()=>{let n=[];if(i.planning&&(n.push(`【自适应规划】按任务复杂度决定是否先规划,不要对简单任务过度编排:`),n.push(` · 简单/明确任务(改单字段、调样式、查值)→ 直接 read/write 执行,不必 write_todos。`),n.push(` · 复杂任务(多步、大改、有歧义、不可逆)→ 先 write_todos 拆解,首个任务标 in_progress,逐项推进。`),n.push(` · 执行中发现步骤要改/补/细分 → 用 update_todo({id, content?, status?}) 按 id 增量改单项,不必重传整个清单。`),n.push(` · 规划出多步方案若需用户拍板 → 先 request_human_confirmation 给方案选项,确认后再执行。`),n.push(` · 规划阶段有轮次预算(maxPlanRevisions,默认 5):勿反复调研/改计划而不执行,规划充分后即开始 write 落地。`)),t&&(a?(n.push(`读写主数据用 read/write(高层入口,自动乐观锁 + 自动快照)。read({jsonPath}) 读子路径当前值(返回含 hash,write 时自动比对,无需手动传);read() 不传读整个主数据 + 说明。write 改值两姿势:① 改单个字段/子路径用 write({patch:{op:"set", jsonPath:"路径.字段", value:新值}})——patch.value 就是该字段的新值(类型匹配:string 直传字符串、number 传数字、对象传对象),不要包成 {字段:值} 对象(字段名已在 jsonPath);也兼容 write({value:新值, patch:{op,jsonPath}}) 顶层 value(向后兼容,但优先 patch.value,避免与整体 set 的 value 混淆);② 替换整个对象用 write({value:{整个新对象}})。op:set 设值 / remove 删 / merge 合并对象 / append 追加数组;批量多改动 write({patches:[{op,jsonPath,value},...]});删子路径 write({patch:{jsonPath:"路径"}, del:true})。写入自动经 schema 校验(失败不写,按错误提示改值类型/形状后重试)+ 自动存快照(出错可用 restore_data 回退)。`),n.push(`修改大对象/数组优先用 write 的 patch 增量(只发改动部分),避免整体重传被 max_tokens 截断致 JSON 不完整。`),n.push(`读大数组(read 返回 hasMore=true)用 read({jsonPath,offset,limit}) 分页(offset+=limit 续读,默认 limit=50);一次读多个不相关子路径用 read({jsonPaths:[...]}) 省轮次;复杂 patches 改动先 write({patches,dryRun:true}) 预检(走完整校验不落盘)。`),n.push(`read/describe 返回按 schema 投影:仅 schema 声明的字段可见(未声明字段自动隐藏,防误操作);要操作某字段需集成方在 schema 声明,查任意路径完整约束用 schema_data({jsonPath})。`),n.push(`查历史快照值(看上一版长啥样 / 冲突诊断 / 用户问"刚才改了啥")用 history_data({id?,jsonPath?})(只读不改当前);对比当前与历史快照的差异需切 advanced 用 diff_data(返回结构化 path→from/to)。`),n.push(`在大数组里按条件筛选用 query_data(JSONPath,如 $.components[?(@.type=="card" && @.price<100)]),返回匹配元素 path/index;定位后用 write patch 改。找名字记不清的元素用 search_data(substring/regex/fuzzy)。批量过滤/映射/聚合/重写大数组用 eval_script(沙箱脚本,mode=query 只读/transform 落地)。`)):(n.push(`改主数据前先 get_data({jsonPath}) 读其当前真实值与 hash(返回末尾 hash=xxx),基于真实值改,不要凭记忆。写入(set/edit/delete)时回传 expectedHash=该 hash 启用乐观锁——若主数据在你 get 之后被外部代码/其他 agent/用户手动改过,会触发冲突:集成方若开启人工介入,工具会挂起等用户决定(保留外部/强制覆盖/回退),你应等待工具返回后按结果继续(保留外部→重新 get 再改;强制覆盖→已写入,继续;回退→已回退到历史快照,基于回退值重写);未开启人工介入时返回 VERSION_CONFLICT 不写入,重新 get 拿最新值与 hash 再改。`),n.push(`不确定主数据字段结构时用 describe_data 查看说明。`),n.push(`修改大对象/数组优先用 edit_data 增量 patch(只发改动部分),避免 set_data 整体重传被 max_tokens 截断导致 JSON 不完整、校验失败。`),n.push(`修改主数据出错时可用 restore_data 回退最近一次。`),n.push(`在大数组里按条件筛选元素用 query_data(JSONPath,如 $.components[?(@.type=="card" && @.price<100)]),返回匹配元素的 path/index;定位后再 edit_data 改。`),n.push(`找名字记不清的元素用 search_data(支持 substring/regex/fuzzy 模糊搜索)。`),n.push(`需要过滤/映射/聚合/批量重写大数组时用 eval_script(沙箱脚本,入参 data);只读探查用 mode=query,批量重写用 mode=transform(返回值经校验后落地)。`),n.push(`读大数组用 read({jsonPath,offset,limit}) 分页(返回 hasMore=true 时 offset+=limit 续读);一次读多个不相关子路径用 read({jsonPaths});复杂改动先 write({...,dryRun:true}) 预检不落盘。`),n.push(`对比当前与历史快照(或一段 JSON against)的差异用 diff_data({snapshotId?,against?})(返回结构化 path→from/to,verify 自纠/操作审计/"刚才改了啥");只读查历史快照值用 history_data({id?,jsonPath?})。`))),i.subagent&&n.push(`独立子任务可 spawn_agent 委派(只读工具,过程不占主上下文)。`),i.inspectEnv&&n.push(`排查页面环境(当前 URL/浏览器/视口/集成方调试变量)用 inspect_env——不传参返回环境摘要(location/navigator/viewport/document),传 key 读特定 window 属性(如 inspect_env({key:"appConfig"}) 读 window.appConfig)。改完数据看渲染、定位"为何没生效"时用它(只读,不改数据)。`),i.domInspect&&n.push(`改完数据想确认渲染是否生效(或定位元素/辅助 UI 设计问答)用 get_dom({selector?,depth?}) 读渲染后 DOM(结构化返回 tag/attrs/text/children,depth 控制深度防爆炸,只读)。配合宿主 actions(save_draft/publish 等)形成"改数据→get_dom 看渲染→触发动作"闭环。`),i.draftWrite&&n.push(`生成超大 JSON(如 50+ 组件页面,单次 write 受 max_tokens 限制装不下)用 draft_write 分块构建 → draft_commit 原子提交:draft_write({draftId, chunk, mode}) mode:"start" 新建/"append" 追加(拼 JSON 片段到 drafts 池);累积完 draft_commit({draftId}) 合并 + schema 校验 + 写主数据(失败草稿保留可修后重试,成功自动清草稿)。小改仍用 write patch,只在大 JSON 从零生成时用 draft。`),i.draftWrite&&n.push(`⚠️ 大 JSON 分块构建是典型多轮工具调用(draft_write×N + draft_commit + read 确认 + 调研 read/query),默认 maxToolRounds=10 可能触顶被 while 截断导致草稿写不完;目标组件数大时集成方应在 createChatSdk 配 maxToolRounds ≥ 20(或按 N+5 估算)。draft_commit 提交同样走乐观锁(改前 read 拿 hash,bind 被改过会触发冲突介入,不静默覆盖)。`),i.todoDeps&&n.push(`复杂任务可用 todos 层级依赖:write_todos 时给 todo 传 parentId(父任务 id,表达层级)+ deps(依赖的 todo id 数组,必须先完成)。有依赖的任务,deps 全 completed 后再标 in_progress;完成时 update_todo({id, status:"completed", evidence:"完成证据"}) 记证据。无依赖关系的任务不传 parentId/deps(扁平)。`),i.focus&&!a&&(n.push(`【上下文聚焦】判断任务范围,用 set_focus/add_focus/remove_focus/clear_focus 自动收敛工作范围:`),n.push(` · 局部任务(只改某一组件/区域,如「调导航栏」「改 components.3 样式」)→ 先 read 定位 jsonPath,再 set_focus({path:"该子树路径"}) 聚焦;聚焦后每轮只看该子树结构,写其他位置会被 PATH_DENIED 拒绝。`),n.push(` · 多个相关组件(如「同时改导航栏和页脚」)→ set_focus 聚焦首个后用 add_focus({path}) 追加其余;聚焦后可写任一焦点子树,越界仍被拒;移除单个用 remove_focus({path})。`),n.push(` · 全局任务(多处/整体结构,如「重排所有组件」「换主题」)→ 不要聚焦,保持全量视野直接写。`),n.push(` · 完成局部精修、要转向其他区域或做整体改动 → 调 clear_focus 退出聚焦(清空全部焦点),恢复全部读写权限。`),n.push(` · set_focus/add_focus 的 path 必须在 schema 内(类型校验);不确定路径先 read/describe_data 查。`)),r&&(n.push(`【受保护资源·精确值保护】部分字段被 freeze/verbatim 保护(集成方在 data.resources 声明):`),n.push(` · read 受保护路径返回占位符 ⟦frozen:path⟧(freeze,精确值不入消息流)或 ⟦res:handle⟧(verbatim,原值在资源池),非真值。`),n.push(` · 确需真值用 resource_get({path})(仅受保护路径);freeze 字段完全不可改,撞 FROZEN_FIELD 即放弃该字段改动。`),n.push(` · verbatim 字段改新值:先 resource_update({path,value}) 更新资源池(同步 bind),再 write 写回句柄 ⟦res:handle⟧;直接写新值 → VERBATIM_MISMATCH。`),n.push(` · 撞 RESOURCE_EVICTED(资源被池淘汰)→ 重新 read 该字段懒注册重建句柄;撞 RESOURCE_NOT_FOUND → 重新 read。`)),e?.subagents?.length){let t=e.subagents.filter(e=>(e.temperature??0)>=U9||/规划|创意|设计|方案|brainstorm|plan/i.test(e.description)),r=e.subagents.filter(e=>(e.temperature??0)<U9&&/反思|审查|挑刺|校验|review|critique|reflect/i.test(e.description));n.push(`【规划-反思-执行·路由】按任务性质选模式,不要对简单任务过度编排:`),t.length&&(n.push(` · 创作/设计/开放性需求(如"设计主题风格""换个感觉")→ 先调 ${t.map(e=>`use_`+e.id).join(`/`)} 出 2-3 套方案(高温创意),`),n.push(` 不要自己拍板;拿到方案后,若需用户拍板用 request_human_confirmation 弹选项。`)),r.length&&n.push(` · 严谨/易错/校验类 → 可先调 ${r.map(e=>`use_`+e.id).join(`/`)} 反思挑刺(低温审查),据反馈修订。`),n.push(a?` · 方案定稿后,由你(主 agent)用 write 落地成 JSON(低温度执行 + schema 校验 + 写前确认)。`:` · 方案定稿后,由你(主 agent)用 edit_data 落地成 JSON(低温度执行 + schema 校验 + 写前确认)。`),n.push(` · 简单/明确任务(如"标题改红色")直接执行,不必走规划-反思。`)}return e?.humanConfirm&&(n.push(`【人工确认·必读】以下情形必须先调 request_human_confirmation 征询用户、拿到答复后再继续,不要自行拍板:`),n.push(` 1) 用户让你「给方案/列选项/我来选/挑一个」时:把每个方案作为一个 option,调 request_human_confirmation(question=简述, options=[方案A,方案B,...], recommendation=你推荐的)。不要只回文字罗列方案让用户自己回复——要用工具把选项做成可点选按钮。`),n.push(` 2) 需求有歧义/不确定时:调工具问清楚(options 不传则用户答同意或拒绝)。`),n.push(` 3) 即将执行高风险不可逆操作(删除/覆盖/批量改动)前:调工具确认。`),n.push(` 4) 规划出多步方案需用户确认时:把整个方案(或关键分步)作为 option 调 request_human_confirmation,确认后再执行。`),n.push(`用户在选项里选了哪个,就按那个方案继续;选「拒绝」则停止并询问如何调整。`)),n.length&&n.unshift(`调用工具务必用标准 function calling(工具调用)格式发起,不要在回复正文里输出伪 XML/标签(如 deepseek 的 tool_calls 标签、invoke、function_call、tool_call 等)或 JSON 文本——那不会被识别为工具调用,会被当普通文字,工具不执行。`),n.length?`## 能力使用提示
|
|
332
332
|
`+n.join(`
|
|
333
333
|
`):void 0}}}function Ufe(e){return{name:`resourcesPin`,augmentPrompt:()=>{let t=e.getResourcesSnapshot();if(!t.length)return;let n=[`## 受保护资源(跨压缩保留 · 精确值保护)`];for(let e of t)e.mode===`freeze`?n.push(`- ${e.path} (freeze 已冻结,不可改)`):n.push(`- ${e.path} (verbatim 原样保留)${e.handle?` ⟦res:${e.handle}⟧`:``}`);return n.push(`读到 ⟦frozen:path⟧/⟦res:handle⟧ 占位符 = 精确值在冻结区/资源池(不入消息流);需真值用 resource_get({path});freeze 字段不可写(撞 FROZEN_FIELD 即放弃);verbatim 直接写新值会 VERBATIM_MISMATCH,先 resource_update 再写回句柄;撞 RESOURCE_EVICTED/RESOURCE_NOT_FOUND 重新 read 懒注册。`),n.join(`
|
|
334
|
-
`)}}}var G9=`v:1::skill-store`,Wfe=`chat-sdk`;function K9(e,t,n){return`${G9}::${e}::${t}::${n}`}function q9(e,t){return`${G9}::${e}::${t}::`}function J9(e={}){let t=e.dbName??Wfe,n=e.backend??`indexed`,r=e.id??``,i,a,o=new Promise(e=>{a=e});return(async()=>{try{if(n===`indexed`){if(typeof indexedDB>`u`)throw Error(`indexedDB 不可用`);i=await E7(t),a(!0)}else if(n===`session`){if(typeof sessionStorage>`u`)throw Error(`sessionStorage 不可用`);i=D7(sessionStorage),a(!0)}else if(n===`local`){if(typeof localStorage>`u`)throw Error(`localStorage 不可用`);i=D7(localStorage),a(!0)}else i=T7(),a(!1)}catch{i=T7(),a(!1)}})(),{ready:o,async list(){let e=[];return await i.scan(q9(t,r),(t,n)=>{e.push(n)}),e},async get(e){return await i.get(K9(t,r,e))},async put(e){try{await i.set(K9(t,r,e.name),e)}catch(e){b7(e)&&(i=T7())}},async remove(e){let n=K9(t,r,e);return await i.get(n)==null?!1:(await i.del(n),!0)},async clear(){await i.clearPrefix(q9(t,r))},dispose(){}}}var Y9=/large_results\/[^\s"'`),]+\.txt/g;function X9(e){let t=new Set,n=e=>{if(typeof e!=`string`||!e)return;let n;for(Y9.lastIndex=0;(n=Y9.exec(e))!==null;)t.add(n[0])};for(let t of e)if(n(t.content),t.steps)for(let e of t.steps)n(e.result);return t}function Gfe(e,t){let n=[];for(let r of Object.keys(e))r.startsWith(`large_results/`)&&!t.has(r)&&n.push(r);return n}function Z9(){let e=Promise.resolve();return function(t){let n=e.then(t,t);return e=n.then(()=>void 0,()=>void 0),n}}bm();var Kfe=30,Q9=new Map;function qfe(e,t){return e===`set_data`?`set`:e===`edit_data`?`edit`:e===`delete_data`?`delete`:e===`restore_data`?`restore`:e===`write`?t?.del?`delete`:t?.patch?`edit`:`set`:null}function Jfe(e,t,n,r){let i=0;return{name:`sdk-events`,wrapToolCall:async(t,r)=>{let i=await r(t),a=qfe(t.name,t.args);return a&&e({type:`data_change`,operation:a,value:n()?.bind}),i},afterModel:t=>{let n=t.message.additional_kwargs||{},a=t.message.response_metadata||{},o=n.usage||a.usage||a.token_usage||a.tokenUsage;if(o&&typeof o==`object`){let t=Number(o.prompt_tokens??o.promptTokens??0)||0,n=Number(o.completion_tokens??o.completionTokens??0)||0,a=Number(o.total_tokens??o.totalTokens??t+n)||0,s={prompt_tokens:t,completion_tokens:n,total_tokens:a};r.prompt_tokens=(r.prompt_tokens??0)+t,r.completion_tokens=(r.completion_tokens??0)+n,r.total_tokens=(r.total_tokens??0)+a,i++,e({type:`usage`,round:i,usage:s,cumulative:{prompt_tokens:r.prompt_tokens,completion_tokens:r.completion_tokens,total_tokens:r.total_tokens}})}},afterAgent:async()=>{e({type:`message_update`,count:t.length})}}}function $9(e,t,n,r,i){if(!n)return i&&console.warn(`[page-agent-sdk][focus] capabilities.focus 关闭,${t} 忽略`),{ok:!1,error:`capabilities.focus 关闭`};if(!e||!e.path)return i&&console.warn(`[page-agent-sdk][focus] ${t} 拒绝:path 必填且非空`),{ok:!1,error:`path 必填且非空`};let a=r();return a?P1(a,e.path)?{ok:!0}:(i&&console.warn(`[page-agent-sdk][focus] ${t} 拒绝:path "${e.path}" 不在 schema 内(getSchemaAtPath 返 null;数组组件须 z.array(...) 包裹,裸 discriminatedUnion/Union 会降级)`),{ok:!1,error:`path "${e.path}" 不在 schema 内`}):(i&&console.warn(`[page-agent-sdk][focus] ${t} 拒绝:当前无主数据 schema`),{ok:!1,error:`当前无主数据 schema,无法聚焦`})}function Yfe(e,t){let n={prompt_tokens:0,completion_tokens:0,total_tokens:0},r=h7(()=>Qe),i=kR(0),a=A7(e.storage);e.debug&&a&&a.onEvent(e=>console.log(`[page-agent-sdk][storage]`,e));let{modelCaps:o,summaryLlmInvoke:s,titleLlmInvoke:c,compressDecisionInvoke:l}=m7(e),u=o;if(e.debug&&console.log(`[page-agent-sdk][modelCaps]`,u),u.contextWindow<2e5)throw Error(`[page-agent-sdk] 模型上下文窗口 ${u.contextWindow} 小于最小支持 ${i1}(需 ≥200K 窗口模型,如 GLM-5.2/Claude/Kimi/Qwen-1M/DeepSeek-v4)`);let d=I7(e,u.contextWindow),f=d.enableLLMSummary!==!1,p=(e.contextOptions&&e.contextOptions.preserveLastToolResults)??sfe[e.contextPreset??`auto`],m=new Set(p),h=e.llm;e.debug&&!s&&console.warn(`[page-agent-sdk][summarization] 未构造 llmInvoke(apiKey 缺失?),摘要回退零成本索引摘要`);let g=gR([]),_=e9(e.vfs?.initialFiles,{persist:a?{save:e=>{M.sessionId&&a&&a.save(t,M.sessionId,{vfs:e})}}:void 0,maxBytes:e.vfs?.maxBytes,poolBytes:e.vfs?.poolBytes}),v=Z1([],{maxPlanRevisions:e.maxPlanRevisions}),y=t0(),b=f0({getSchema:()=>O()?.schema}),x=
|
|
334
|
+
`)}}}var G9=`v:1::skill-store`,Wfe=`chat-sdk`;function K9(e,t,n){return`${G9}::${e}::${t}::${n}`}function q9(e,t){return`${G9}::${e}::${t}::`}function J9(e={}){let t=e.dbName??Wfe,n=e.backend??`indexed`,r=e.id??``,i,a,o=new Promise(e=>{a=e});return(async()=>{try{if(n===`indexed`){if(typeof indexedDB>`u`)throw Error(`indexedDB 不可用`);i=await E7(t),a(!0)}else if(n===`session`){if(typeof sessionStorage>`u`)throw Error(`sessionStorage 不可用`);i=D7(sessionStorage),a(!0)}else if(n===`local`){if(typeof localStorage>`u`)throw Error(`localStorage 不可用`);i=D7(localStorage),a(!0)}else i=T7(),a(!1)}catch{i=T7(),a(!1)}})(),{ready:o,async list(){let e=[];return await i.scan(q9(t,r),(t,n)=>{e.push(n)}),e},async get(e){return await i.get(K9(t,r,e))},async put(e){try{await i.set(K9(t,r,e.name),e)}catch(e){b7(e)&&(i=T7())}},async remove(e){let n=K9(t,r,e);return await i.get(n)==null?!1:(await i.del(n),!0)},async clear(){await i.clearPrefix(q9(t,r))},dispose(){}}}var Y9=/large_results\/[^\s"'`),]+\.txt/g;function X9(e){let t=new Set,n=e=>{if(typeof e!=`string`||!e)return;let n;for(Y9.lastIndex=0;(n=Y9.exec(e))!==null;)t.add(n[0])};for(let t of e)if(n(t.content),t.steps)for(let e of t.steps)n(e.result);return t}function Gfe(e,t){let n=[];for(let r of Object.keys(e))r.startsWith(`large_results/`)&&!t.has(r)&&n.push(r);return n}function Z9(){let e=Promise.resolve();return function(t){let n=e.then(t,t);return e=n.then(()=>void 0,()=>void 0),n}}bm();var Kfe=30,Q9=new Map;function qfe(e,t){return e===`set_data`?`set`:e===`edit_data`?`edit`:e===`delete_data`?`delete`:e===`restore_data`?`restore`:e===`write`?t?.del?`delete`:t?.patch?`edit`:`set`:null}function Jfe(e,t,n,r){let i=0;return{name:`sdk-events`,wrapToolCall:async(t,r)=>{let i=await r(t),a=qfe(t.name,t.args);return a&&e({type:`data_change`,operation:a,value:n()?.bind}),i},afterModel:t=>{let n=t.message.additional_kwargs||{},a=t.message.response_metadata||{},o=n.usage||a.usage||a.token_usage||a.tokenUsage;if(o&&typeof o==`object`){let t=Number(o.prompt_tokens??o.promptTokens??0)||0,n=Number(o.completion_tokens??o.completionTokens??0)||0,a=Number(o.total_tokens??o.totalTokens??t+n)||0,s={prompt_tokens:t,completion_tokens:n,total_tokens:a};r.prompt_tokens=(r.prompt_tokens??0)+t,r.completion_tokens=(r.completion_tokens??0)+n,r.total_tokens=(r.total_tokens??0)+a,i++,e({type:`usage`,round:i,usage:s,cumulative:{prompt_tokens:r.prompt_tokens,completion_tokens:r.completion_tokens,total_tokens:r.total_tokens}})}},afterAgent:async()=>{e({type:`message_update`,count:t.length})}}}function $9(e,t,n,r,i){if(!n)return i&&console.warn(`[page-agent-sdk][focus] capabilities.focus 关闭,${t} 忽略`),{ok:!1,error:`capabilities.focus 关闭`};if(!e||!e.path)return i&&console.warn(`[page-agent-sdk][focus] ${t} 拒绝:path 必填且非空`),{ok:!1,error:`path 必填且非空`};let a=r();return a?P1(a,e.path)?{ok:!0}:(i&&console.warn(`[page-agent-sdk][focus] ${t} 拒绝:path "${e.path}" 不在 schema 内(getSchemaAtPath 返 null;数组组件须 z.array(...) 包裹,裸 discriminatedUnion/Union 会降级)`),{ok:!1,error:`path "${e.path}" 不在 schema 内`}):(i&&console.warn(`[page-agent-sdk][focus] ${t} 拒绝:当前无主数据 schema`),{ok:!1,error:`当前无主数据 schema,无法聚焦`})}function Yfe(e,t){let n={prompt_tokens:0,completion_tokens:0,total_tokens:0},r=h7(()=>Qe),i=kR(0),a=A7(e.storage);e.debug&&a&&a.onEvent(e=>console.log(`[page-agent-sdk][storage]`,e));let{modelCaps:o,summaryLlmInvoke:s,titleLlmInvoke:c,compressDecisionInvoke:l}=m7(e),u=o;if(e.debug&&console.log(`[page-agent-sdk][modelCaps]`,u),u.contextWindow<2e5)throw Error(`[page-agent-sdk] 模型上下文窗口 ${u.contextWindow} 小于最小支持 ${i1}(需 ≥200K 窗口模型,如 GLM-5.2/Claude/Kimi/Qwen-1M/DeepSeek-v4)`);let d=I7(e,u.contextWindow),f=d.enableLLMSummary!==!1,p=(e.contextOptions&&e.contextOptions.preserveLastToolResults)??sfe[e.contextPreset??`auto`],m=new Set(p),h=e.llm;e.debug&&!s&&console.warn(`[page-agent-sdk][summarization] 未构造 llmInvoke(apiKey 缺失?),摘要回退零成本索引摘要`);let g=gR([]),_=e9(e.vfs?.initialFiles,{persist:a?{save:e=>{M.sessionId&&a&&a.save(t,M.sessionId,{vfs:e})}}:void 0,maxBytes:e.vfs?.maxBytes,poolBytes:e.vfs?.poolBytes}),v=Z1([],{maxPlanRevisions:e.maxPlanRevisions}),y=t0(),b=f0({getSchema:()=>O()?.schema}),x=yce(),S=M0(e.memory||``);typeof e.memory==`function`&&S.refresh();let ee={current:null},C=e.data?{...e.data,description:e.data.description??`主数据对象`}:void 0,te=e.checkpoint,ne=te!==void 0&&te!==!1,w=ne?H0({getData:()=>O()?.bind,consumeDataDirty:()=>le?.consumeDataDirty?.()??!0,slotPaths:C?[``]:[],vfsStore:_,todosMw:v,getTodos:()=>ee.current?.getState?.()?.todos??[],messages:g,maxCheckpoints:te&&typeof te==`object`?te.maxCheckpoints:void 0}):null,re=!te||typeof te!=`object`||te.auto!==!1,ie=N7(e.capabilities),T=ie.dataOps,ae=ie.draftWrite,E=ie.tracing,oe=ie.automation,se=a7(e),ce=T&&C?k9(C,{onAudit:e.onAudit??(e.debug?e=>console.log(`[page-agent-sdk][data audit]`,e):void 0),maxSnapshots:e.maxSnapshots,onConflict:r.set,autoLock:e.autoLock,interceptors:e.interceptors,vfsStore:ae||C?.resources?.length?_:void 0}):[],D=T?E9(ce,e.toolMode):[],le=T&&C?ce.controller??null:null,ue=T&&C?.resources?.length&&le?.getResourcesSnapshot?Ufe({getResourcesSnapshot:()=>le?.getResourcesSnapshot?.()??[]}):void 0,O=()=>le?.get()??C,de=new Map,fe=H9(ie,D,j9,P9,R9);fe.forEach(e=>de.set(e.name,`builtin`));let pe=[...e.tools||[]];pe.forEach(e=>de.set(e.name,`user`));let me=B9(e.actions??{});me.forEach(e=>de.set(e.name,`action`));let he=[],ge=e.humanConfirm!==!1&&(!e.approval||e.approval.humanConfirmTool!==!1),_e=ge?L0():null;_e&&de.set(I0,`builtin`);let ve=ne&&w?[gI(async()=>{let e=w.list();return e.length?w.restore()?`已回退到最近一次正常状态(checkpoint #${e[e.length-1].id})。对话历史、主数据、vfs、todos 已整体还原。请基于回退后的状态重新判断并继续。`:`回退失败:无可用 checkpoint。`:`无可用 checkpoint,无法回退。`},{name:`restore_last_checkpoint`,description:`回退到最近一次正常状态(整体还原对话历史 + 主数据 + vfs + todos)。当本轮操作出错、页面被改坏、或走偏时调用,回到本轮起点重新来过。不传参数即回退最近一次。`,schema:F({}).optional()}),gI(async()=>{let e=w.list();return e.length?`可用 checkpoint:
|
|
335
335
|
`+e.map(e=>`#${e.id} [${e.label??`auto`}] 消息数=${e.messageCount} 时间=${new Date(e.timestamp).toLocaleTimeString()}`).join(`
|
|
336
|
-
`):`无可用 checkpoint。`},{name:`list_checkpoints`,description:`列出可用会话 checkpoint(回退点)。`,schema:F({}).optional()})]:[];ve.forEach(e=>de.set(e.name,`builtin`));let ye=ie.focus,be=gI(async({path:e,label:t})=>{let n=O()?.schema;return n?P1(n,e)?(b.setFocus({path:e,...t?{label:t}:{}}),`已聚焦到 ${e}${t?`(${t})`:``}。后续仅可写该子树(越界被拒),每轮只看到该组件结构。完成精修后调 clear_focus 退出。`):`PATH_DENIED · 聚焦失败:path "${e}" 不在 schema 内。请先用 read 查看可操作路径再聚焦。`:`聚焦失败:当前无主数据 schema,无法聚焦。`},{name:`set_focus`,description:`聚焦到指定组件子树(如 components.3)精修,替换全部已有焦点(非累积;要保留已有焦点追加用 add_focus)。聚焦后:仅可写该子树(越界 PATH_DENIED)+ 每轮只看到该组件结构。多组件页面精修其中一个时用,避免改到别处。先 read 定位 path 再聚焦;完成调 clear_focus。`,schema:F({path:N().describe(`要聚焦的组件 jsonPath,如 components.3`),label:N().optional().describe(`人类可读标签,如「导航栏」`)})}),xe=gI(async()=>(b.clearFocus(),`已清除聚焦,恢复全量可操作范围(可读写所有组件)。`),{name:`clear_focus`,description:`清除当前聚焦,退出精修模式,恢复对全部组件的读写权限。`,schema:F({}).optional()}),Se=gI(async({path:e,label:t})=>{let n=O()?.schema;if(!n)return`聚焦失败:当前无主数据 schema,无法聚焦。`;if(!P1(n,e))return`PATH_DENIED · 聚焦失败:path "${e}" 不在 schema 内。请先用 read 查看可操作路径再聚焦。`;b.addFocus({path:e,...t?{label:t}:{}});let r=b.getFocuses();return`已聚焦 ${e}${t?`(${t})`:``}(当前共 ${r.length} 个焦点:${r.map(e=>e.path).join(`, `)})。后续仅可写这些子树之一(越界被拒)。`},{name:`add_focus`,description:`追加聚焦一个组件子树(multi-focus,可同时聚焦多个相关组件)。校验 path 在 schema 内。聚焦后仅可写已聚焦的子树之一(越界 PATH_DENIED)。与 set_focus(替换全部)不同:本工具累积追加,不清除已有焦点。`,schema:F({path:N().describe(`要追加聚焦的组件 jsonPath,如 components.3`),label:N().optional().describe(`人类可读标签`)})}),k=gI(async({path:e})=>{let t=b.getFocuses().length;b.removeFocus(e);let n=b.getFocuses();return n.length===t?`path "${e}" 不在当前焦点列表中(当前:${n.map(e=>e.path).join(`, `)||`无`})。`:n.length?`已移除焦点 ${e}(剩余 ${n.length} 个:${n.map(e=>e.path).join(`, `)})。`:`已移除焦点 ${e},聚焦已清空,恢复全量操作范围。`},{name:`remove_focus`,description:`移除单个聚焦焦点(by path),保留其他焦点。移除最后一个等价退出精修。全部退出用 clear_focus。`,schema:F({path:N().describe(`要移除的焦点 jsonPath`)})}),Ce=ye&&e.toolMode===`advanced`?[be,xe,Se,k]:[];Ce.forEach(e=>de.set(e.name,`builtin`));let A=[],we=new Map,j=Te();function Te(){let{tools:e,collisions:t}=Hfe([{label:`builtin`,tools:fe},{label:`user`,tools:pe},{label:`action`,tools:me},{label:`humanConfirm`,tools:_e?[_e]:[]},{label:`checkpoint`,tools:ve},{label:`focus`,tools:Ce},{label:`mcp`,tools:he},{label:`skill`,tools:A}]);return t.length&&console.warn(`[page-agent-sdk] 工具重名,后注册覆盖先注册:`,t.map(e=>`${e.name}(${e.loser}→${e.winner})`).join(`, `)),e}let Ee=ie.planning,De=ie.missionAnchor,Oe=ie.workingMemory,ke=ie.skills,Ae=ie.vfs;if(Ae)for(let e of hfe)de.set(e,`builtin`);if(Ee)for(let e of v.tools??[])de.set(e.name,`builtin`);let je=ie.summarization,Me=ie.agentCompression&&!!l;e.debug&&ie.agentCompression&&!l&&console.warn(`[page-agent-sdk][agentCompression] agentCompression 开启但 summaryLlm 不可用(或缺 apiKey / 模型不支持工具),压缩决策不启用,回退静态压缩`);let Ne=ie.memory,Pe=ie.subagent,Fe=e.verify?.maxAttempts??2,Ie=ie.verify&&e.verify?.enabled!==!1&&Fe>0,Le=ie.contextInspector;e.verify?.check&&!ie.verify&&console.warn(`[page-agent-sdk][verify] 检测到 verify.check 但 capabilities.verify 未开启,verify 未装载`);let Re=e.subagent,ze=Re?.allowedTools??[],Be=!Pe||Re?.enabled===!1?void 0:J0({llm:Re?.llm??e.llm,allTools:()=>j,allowedTools:ze.length?ze:void 0,systemPrompt:Re?.systemPrompt,temperature:Re?.temperature,maxTokens:Re?.maxTokens,skills:Re?.skills,maxDepth:Re?.maxDepth,maxParallel:Re?.maxParallel,debug:e.debug,getFocuses:()=>b.getFocuses(),getSchema:()=>O()?.schema??null}),Ve=Pe&&e.subagents!==void 0?Y0(e.subagents,{llm:e.llm,allTools:()=>j,debug:e.debug,getFocuses:()=>b.getFocuses(),getSchema:()=>O()?.schema??null}):void 0,He=Ve?Ve.controller:null,Ue=[`get_data`,`describe_data`,`read`,`fetch_document`],We=j.filter(e=>Ue.includes(e.name)),Ge=Ie?X0({check:e.verify.check??Z0({schemas:()=>O()?{"":O().schema}:{},root:()=>O()?.bind}),adversarial:e.verify?.adversarial?{llm:e.llm,tools:We}:void 0}):void 0,Ke=Le?n2({contextWindow:u.contextWindow,thresholdRatio:I7(e,u.contextWindow).summaryThresholdRatio}):void 0,qe=W9({...ie,humanConfirm:ge,subagents:e.subagents?.map(e=>({id:e.id,description:e.description,temperature:e.temperature}))},T&&!!C,e.toolMode,!!C?.resources?.length),Je=C?{name:`dataHint`,augmentPrompt:()=>i7(O(),e.schemaHint)||void 0}:null,Ye=e.augmentSystem?{name:`augmentSystem`,augmentPrompt:t=>{try{return e.augmentSystem({state:t,data:O()})}catch(t){e.debug&&console.log(`[page-agent-sdk][augmentSystem] 回调抛错,降级跳过:`,t.message);return}}}:null,Xe=e.onEvent,Ze=P7(e.onEvent),Qe=Ze.emit,$e,et=[],tt=e=>({name:e.name,description:e.description,content:typeof e.getContent==`function`?e.getContent():``}),nt=e=>({name:e.name,description:e.description,getContent:()=>e.content}),rt=e.skillStorage===!1?null:J9({...typeof e.skillStorage==`object`?e.skillStorage:{},id:e.skillStorage&&typeof e.skillStorage==`object`&&e.skillStorage.id?e.skillStorage.id:`agent::${t}`}),it=()=>{let t=$e?$e.controller:null;if(t){let n=(e.skills||[]).filter(e=>!et.some(t=>t.name===e.name));t.set([...n,...et])}M.infoTick.value++},at=async()=>{if(rt)try{let t=await rt.list();if(t.length){et=t.map(nt);let n=$e?$e.controller:null;if(n){let t=(e.skills||[]).filter(e=>!et.some(t=>t.name===e.name));n.set([...t,...et])}M.infoTick.value++}}catch{}},ot=je?Ude({...d,llmInvoke:s,getRegisteredData:()=>O()?[{description:O().description??`主数据对象`}]:[],preserveLastToolResults:p,...Me?{decideInvoke:l,getSnapshot:()=>Ke?.getSnapshot()}:{}}):void 0,st=lfe([...Je?[Je]:[],qe,...De?[y]:[],...Ee?[v]:[],...ke?[$e=j0(e.skills||[],{readVfs:Ae?e=>_.files[e]?.content:void 0,hostScriptEnabled:ie.skillHostScript,onToolsReady:(e,t)=>{for(let n of t){let t=A.findIndex(e=>e.name===n.name);t>=0&&A.splice(t,1),A.push(n),we.set(n.name,e),de.set(n.name,`skill:${e}`)}j=Te(),M.agent&&M.agent.setTools(j),M.infoTick.value++}})]:[],...Ae?[_fe(_)]:[],...ot?[ot]:[],...Oe?[x]:[],...ye?[b]:[],...ue?[ue]:[],...Ne?[S]:[],...e.permissions?.length?[Cce(e.permissions)]:[],...ne&&re&&w?[U0(w)]:[],...ge?[R0()]:[],...e.approval&&(e.approval.tools!==void 0||e.approval.confirm)?[F0(e.approval)]:[],...Ge?[Ge]:[],...Be?[Be]:[],...Ve?[Ve]:[],...Ye?[Ye]:[],...Ke?[Ke]:[],...e.middleware||[],...oe?[Rfe(n,{tokenBudget:e.tokenBudget,timeBudgetMs:e.timeBudgetMs},Qe)]:[],Jfe(Qe,g,O,n)]),ct=e.maxMemoryRounds??Kfe,lt=kR([]);async function ut(){a&&(lt.value=(await a.listSessions(t)).sort((e,t)=>t.lastAccessed-e.lastAccessed))}let M={agentId:t,store:a,messages:g,vfsStore:_,listeners:Ze.listeners,todosMw:v,memoryMw:S,missionMw:y,workingMemoryMw:x,focusMw:b,agent:null,initDone:Promise.resolve(),sessionId:``,refCount:0,mcpClosers:[],mcpServers:[],checkpoint:w,dataOpsController:le,skillsController:$e?$e.controller:null,infoTick:i,pendingConflict:r.pendingConflict,sessions:lt,refreshSessions:ut,liveData:O,usage:n,emit:Qe,unloadSkillTools(e){if(e){let t=A.length;if(A=A.filter(t=>we.get(t.name)===e?(de.delete(t.name),we.delete(t.name),!1):!0),A.length===t)return}else{if(!A.length)return;for(let e of A)de.delete(e.name),we.delete(e.name);A=[]}j=Te(),M.agent&&M.agent.setTools(j)},applySnapshot(t){if(t.messages?.length&&g.push(...t.messages),t.vfs&&_.hydrate&&_.hydrate(t.vfs),t.todos?.length&&v.reset(t.todos),t.memory&&!e.memory&&S.reset(t.memory),t.checkpoints?.length&&w&&w.importStack(t.checkpoints),t.usage&&Object.assign(n,t.usage),t.mission&&De&&y.setMission(t.mission),t.workingMemory&&Oe&&x.restore(t.workingMemory),ye){let n=t.focus,r=n?Array.isArray(n)?n:[n]:[];if(r.length){let t=O()?.schema,n=t?r.filter(e=>P1(t,e.path)):[];if(n.length&&(b.setFocus(null),n.forEach(e=>b.addFocus(e))),e.debug&&n.length<r.length){let e=r.filter(e=>!n.includes(e)).map(e=>e.path);console.warn(`[page-agent-sdk][focus] 恢复的焦点部分 path 已失效(schema 变化/无 schema),剔除:`,e)}}}mt()},addSkill(e){let t=et.findIndex(t=>t.name===e.name);t>=0?et[t]=e:et.push(e),it(),rt&&rt.put(tt(e))},removeSkill(e){let t=et.findIndex(t=>t.name===e);return t<0?!1:(et.splice(t,1),it(),rt&&rt.remove(e),!0)},listUserSkills(){return et.map(e=>e.name)},getUserSkill(e){let t=et.find(t=>t.name===e);if(t)return{name:t.name,description:t.description,content:typeof t.getContent==`function`?t.getContent():``}},afterRound(){ht(),vt()},async send(e,t){await M.initDone,t??={},t?.mission&&De&&y.setMission(t.mission);let n=e;if(t.interceptors?.input)try{let r=t.interceptors.input(e);typeof r==`string`&&(n=r)}catch{}let r=oe?t.maxAutoRetries??1:0,i=0,o=!1;for(;;){o||=(g.push({role:`user`,content:n,timestamp:Date.now()}),!0);try{let e=await M.agent.invoke(g);if(t.interceptors?.output)try{let n=t.interceptors.output(e);typeof n==`string`&&(e=n)}catch{}return g.push({role:`assistant`,content:e,timestamp:Date.now()}),M.afterRound(),a&&await a.flush(),e}catch(e){let t=X$(e,`fatal`);if(i<r&&w?.canRestore()){i+=1,w.restore(),o=!0,Qe({type:`error`,message:`致命错误自动恢复(${i}/${r}):${t.message},已回退 checkpoint 重试`,severity:`observable`,code:`AUTO_RECOVER_RETRY`,context:{attempt:i,cause:t.code??t.message.slice(0,120)}});continue}throw Qe({type:`error`,message:t.message,severity:t.severity,...t.code?{code:t.code}:{},...t.context===void 0?{}:{context:t.context}}),e}}},async batch(e,t){if(await M.initDone,!e.length)return[];let n=[];for(let r=0;r<e.length;r++){let i=e[r];w&&w.save(`batch:${r}`);let o=g.length;try{g.push({role:`user`,content:i,timestamp:Date.now()});let o=await M.agent.invoke(g);g.push({role:`assistant`,content:o,timestamp:Date.now()}),M.afterRound(),a&&await a.flush(),n.push({index:r,task:i,reply:o,ok:!0}),t?.({done:r+1,total:e.length,task:i,ok:!0})}catch(a){g.length>o&&g.splice(o);let s=X$(a,`fatal`);Qe({type:`error`,message:`批量任务 ${r+1}/${e.length} 失败:${s.message}`,severity:`observable`,code:`BATCH_TASK_FAILED`,context:{index:r,task:i.slice(0,100)}}),n.push({index:r,task:i,error:s.message,ok:!1}),t?.({done:r+1,total:e.length,task:i,ok:!1})}}return n},async switchSession(n){if(await M.initDone,!a)throw Error(`page-agent-sdk: storage 未开启,无法切换会话(请传 storage 选项)`);if(r.resolve(`keep_external`),M.sessionId&&a){if(De){let e=y.getMission();e&&a.save(t,M.sessionId,{mission:e})}if(Oe){let e=x.getWorkingMemory();e&&a.save(t,M.sessionId,{workingMemory:e})}if(ye){let e=b.getFocuses();a.save(t,M.sessionId,{focus:e.length?e:null})}}_.flush?.(),await a.flush();let i=n??``,o;return i?(o=await a.load(t,i),o||await a.createSession(t,e.session?.title,i)):i=await a.createSession(t,e.session?.title),M.sessionId=i,g.splice(0,g.length),_.clear?.(),v.reset([]),e.memory||S.reset(``),y.reset(),x.reset(),b.reset(),w&&w.importStack([]),M.agent.debugLogs.value=[],o||=await a.load(t,i),o&&(M.applySnapshot(o),Qe({type:`session_restored`,sessionId:i,rounds:o.messages?.length??0})),e.memory&&a.save(t,M.sessionId,{memory:S.get()||(typeof e.memory==`string`?e.memory:``)}),ut(),gt=void 0,_t=!1,i},resetSession:()=>{a&&(M.sessionId=g7(),_.clear?.(),v.reset([]),e.memory||S.reset(``),y.reset(),x.reset(),b.reset(),w&&w.importStack([]),M.agent&&(M.agent.debugLogs.value=[]),a.createSession(M.agentId,e.session?.title,M.sessionId),Qe({type:`session_restored`,sessionId:M.sessionId,rounds:0}),ut(),gt=void 0,_t=!1)},stream:(e,t,n)=>{if(!M.agent)throw Error(`page-agent-sdk: agent 尚未初始化完成,请先 await mount()`);_?.setProtectedRefs?.(X9(e));let i=Xe?e=>{t?.(e),Qe(e)}:t;if(n){let e=()=>r.resolve(`keep_external`);n.aborted?e():n.addEventListener(`abort`,e,{once:!0})}return M.agent.stream(e,i,n)},release(){if(M.refCount--,M.refCount<=0){a&&(_.flush?.(),a.flush(),a.dispose()),rt&&rt.dispose();let e=M.mcpClosers.splice(0);e.length&&Promise.allSettled(e.map(e=>e())),Q9.delete(t)}},resolveConflict:r.resolve,setTools(e){pe.length=0,e.forEach(e=>{pe.push(e),de.set(e.name,`user`)}),j=Te(),M.agent&&M.agent.setTools(j),M.infoTick.value++},addTool(e){j.some(t=>t.name===e.name)&&console.warn(`[page-agent-sdk] 工具 "${e.name}" 已存在,新工具覆盖(后注册覆盖先注册)`);for(let t=pe.length-1;t>=0;t--)pe[t].name===e.name&&pe.splice(t,1);pe.push(e),de.set(e.name,`user`),j=Te(),M.agent&&M.agent.setTools(j),M.infoTick.value++},removeTool(e){let t=pe.findIndex(t=>t.name===e);return t<0?!1:(pe.splice(t,1),de.delete(e),j=Te(),M.agent&&M.agent.setTools(j),M.infoTick.value++,!0)},setLlm(t){let n;if(l7(t))n=t;else{let e=t;if((e.provider??`openai`)===`anthropic`)throw Error(`[page-agent-sdk][setLlm] 切换到 Anthropic 需传 BaseChatModel 实例(动态 import 无法同步);请先 const { ChatAnthropic } = await import("@langchain/anthropic") 构造实例后传入`);n=_I(e)}typeof n.bindTools!=`function`&&e.debug&&console.warn(`[page-agent-sdk][setLlm] 新模型不支持 bindTools(tool calling 会失效)`),h=t;let r=l7(t)?void 0:t;if(u=a1({model:r?.model??t.model??t.modelName,contextWindow:e.contextWindow??r?.contextWindow,maxOutputTokens:e.maxOutputTokens??r?.maxOutputTokens}),u.contextWindow<2e5)throw Error(`[page-agent-sdk][setLlm] 新模型上下文窗口 ${u.contextWindow} 小于最小支持 ${i1}(需 ≥200K 窗口模型)`);M.agent&&(M.agent.setLlm(n),M.agent.setModelCaps?.(u)),ot?.setContextWindow?.(u.contextWindow),Ke?.setContextWindow?.(u.contextWindow),M.infoTick.value++,e.debug&&console.log(`[page-agent-sdk][setLlm] 重解析 modelCaps + 回灌:`,u)},setMemory(e){S.reset(e),typeof e==`function`&&S.refresh(),M.infoTick.value++},refreshMemory(){return S.refresh()},setSubagents(t){if(!He){e.debug&&console.warn(`[page-agent-sdk][setSubagents] 未配 subagents:[] 或 capabilities.subagent 关闭,忽略`);return}He.set(t),M.infoTick.value++},addSubagent(t){if(!He){e.debug&&console.warn(`[page-agent-sdk][addSubagent] 未配 subagents:[] 或 capabilities.subagent 关闭,忽略`);return}He.add(t),M.infoTick.value++},removeSubagent(t){if(!He)return e.debug&&console.warn(`[page-agent-sdk][removeSubagent] 未配 subagents:[] 或 capabilities.subagent 关闭,忽略`),!1;let n=He.remove(t);return n&&M.infoTick.value++,n},getInfo(){return{id:t,sessionId:M.sessionId,model:l7(h)?h.model??h.modelName:h.model,systemPrompt:M.agent?.getEffectiveSystemPrompt?.()??se+i7(O(),e.schemaHint),tools:(M.agent?.allTools??j).map(e=>({name:e.name,description:e.description,schema:e.schema,source:de.get(e.name)||`user`})),skills:($e?$e.controller.get():e.skills??[]).map(e=>({name:e.name,description:e.description})),data:O()?{description:O().description,schema:O().schema}:void 0,contextPreset:e.contextPreset??`auto`,memory:S.get(),middleware:st.map(e=>e.name),todos:(M.agent?.getState?.()?.todos??[]).map(e=>({id:e.id,content:e.content,status:e.status,...e.parentId===void 0?{}:{parentId:e.parentId},...e.deps===void 0?{}:{deps:e.deps},...e.criteria===void 0?{}:{criteria:e.criteria},...e.evidence===void 0?{}:{evidence:e.evidence}})),planPhase:v.getPlanPhase(),mission:De?y.getMission():void 0,workingMemory:Oe?x.getWorkingMemory():void 0,focus:ye?b.getFocus():void 0,focuses:ye?b.getFocuses():[],trace:E&&M.agent?.spans?{spans:M.agent.spans.value,metrics:l1(M.agent.spans.value)}:void 0,actions:V9(e.actions??{}),subagent:{enabled:!!Be,maxDepth:e.subagent?.maxDepth??1,maxParallel:e.subagent?.maxParallel??4,allowedTools:e.subagent?.allowedTools??[],subagents:He?.get()??[]},verify:{enabled:!!Ge,maxAttempts:Ie?Fe:0,adversarial:Ie&&!!e.verify?.adversarial},context:(()=>{let e=Ke?.getSnapshot();if(e){let t=M.agent?.getState?.()?.lastCompression;t&&(e.compression=t)}return e})(),mcp:{servers:M.mcpServers},lastCompression:M.agent?.getState?.()?.lastCompression,checkpoints:w?{enabled:!0,auto:re,list:w.list()}:void 0}},getMission(){return De?y.getMission():void 0},setMission(t){if(!De){e.debug&&console.warn(`[page-agent-sdk][mission] capabilities.missionAnchor 关闭,setMission 忽略`);return}y.setMission(t),M.infoTick.value++},getFocus(){return ye?b.getFocus():void 0},getFocuses(){return ye?b.getFocuses():[]},setFocus(t){let n=$9(t,`setFocus`,ye,()=>O()?.schema,e.debug);return n.ok?(b.setFocus(t),M.infoTick.value++,{ok:!0}):n},addFocus(t){let n=$9(t,`addFocus`,ye,()=>O()?.schema,e.debug);return n.ok?b.getFocuses().length>=8?(e.debug&&console.warn(`[page-agent-sdk][focus] addFocus 拒绝:焦点数已达上限 8(augmentPrompt 注入每焦点子树 schema,过多致 system prompt 超预算)`),{ok:!1,error:`焦点数上限 8(避免 system prompt 撑爆)`}):(b.addFocus(t),M.infoTick.value++,{ok:!0}):n},removeFocus(e){ye&&(b.removeFocus(e),M.infoTick.value++)},clearFocus(){ye&&(b.clearFocus(),M.infoTick.value++)}};async function dt(){if(!a)return;await a.ready;let n=e.session||{};if(n.id){M.sessionId=n.id;let e=await a.load(t,M.sessionId);e?(M.applySnapshot(e),Qe({type:`session_restored`,sessionId:M.sessionId,rounds:e.messages?.length??0})):await a.createSession(t,n.title,M.sessionId)}else if(n.autoResume!==!1){let r=await a.listSessions(t);if(e.debug&&console.log(`[page-agent-sdk][restore] listSessions`,t,r.length,r.map(e=>e.sessionId)),r.length){M.sessionId=r[0].sessionId;let n=await a.load(t,M.sessionId);n?(M.applySnapshot(n),Qe({type:`session_restored`,sessionId:M.sessionId,rounds:n.messages?.length??0}),e.debug&&console.log(`[page-agent-sdk][restore] 恢复会话`,M.sessionId,`${n.messages?.length??0} msgs`)):e.debug&&console.log(`[page-agent-sdk][restore] 会话 meta 存在但快照为空`,M.sessionId)}else M.sessionId=await a.createSession(t,n.title),e.debug&&console.log(`[page-agent-sdk][restore] 新建会话(无历史)`,M.sessionId)}else M.sessionId=await a.createSession(t,n.title);e.memory&&a.save(t,M.sessionId,{memory:S.get()||(typeof e.memory==`string`?e.memory:``)}),ut()}async function ft(){await at()}function pt(e){let t={};for(let n of X9(e)){let e=_.files[n];e&&(t[n]=e.content)}return t}function mt(){let e=Gfe(_.files,X9(g));for(let t of e)delete _.files[t]}function ht(){let e=Bde(g,ct);if(!e.trimmed)return;let{older:t,summary:n}=e;if(Qe({type:`context_trimmed`,dropped:t.map(e=>({round:e.round,user:e.userMsg.content,assistant:e.assistantMsgs.map(e=>e.content),steps:e.assistantMsgs.flatMap(e=>e.steps??[])})),vfsResults:pt(t.flatMap(e=>[e.userMsg,...e.assistantMsgs])),summary:n.content,reason:`max_memory_rounds`}),g.splice(e.deleteFrom,e.deleteCount,n),mt(),f&&s){let n=e.summary,{prevSeg:r}=e;(async()=>{try{let e=await s(e7(t,m)),i=g.indexOf(n);if(i<0)return;g[i].content=zde(t,r,e),vt()}catch{}})()}}let gt,_t=!1;function vt(){if(!M.sessionId||!a)return;let r=JSON.parse(JSON.stringify(g));a.save(t,M.sessionId,{messages:r});let i=M.agent?.getState?.()?.todos??[];if(a.save(t,M.sessionId,{todos:i}),De){let e=y.getMission();e&&a.save(t,M.sessionId,{mission:e})}if(Oe){let e=x.getWorkingMemory();e&&a.save(t,M.sessionId,{workingMemory:e})}if(ye){let e=b.getFocuses();a.save(t,M.sessionId,{focus:e.length?e:null})}oe&&w&&(a.save(t,M.sessionId,{checkpoints:w.exportStack()}),a.save(t,M.sessionId,{usage:n}));let o=c7(g);o&&o!==gt&&(gt=o,a.updateTitle(t,M.sessionId,o)),e.autoTitle!==!1&&c&&!_t&&g.some(e=>e.role===`user`)&&g.some(e=>e.role===`assistant`)&&(_t=!0,(async()=>{let e=await c(g);e&&(await a.updateTitle(t,M.sessionId,e),await ut())})()),e.debug&&console.log(`[page-agent-sdk][persist] save`,M.sessionId,`${g.length} msgs`)}return M.initDone=(async()=>{if(await dt(),await ft(),e.mcp?.length){let t=await Promise.allSettled(e.mcp.map(e=>W5(e)));M.mcpClosers=t.flatMap(e=>e.status===`fulfilled`?[e.value.close]:[]),M.mcpServers=[],t.forEach((t,n)=>{let r=e.mcp[n],i=r.name??r.url;t.status===`fulfilled`?(M.mcpServers.push({name:i,url:r.url,toolCount:t.value.tools.length}),t.value.tools.forEach(e=>de.set(e.name,`mcp:${i}`)),he.push(...t.value.tools)):console.warn(`[page-agent-sdk][mcp] server ${i} 连接失败:`,t.reason)}),j=Te(),e.debug&&console.log(`[page-agent-sdk][mcp] 注入 ${he.length} 个工具,${M.mcpServers.length} 个 server`)}let t=l7(e.llm)?e.llm:await vI(e.llm);M.agent=A1({llm:t,systemPrompt:se,tools:j,middleware:st,maxToolRounds:e.maxToolRounds,maxRetries:e.maxRetries,maxParallelTools:e.maxParallelTools,contextWindow:u.contextWindow,maxOutputTokens:u.maxOutputTokens,maxVerifyAttempts:Ie?Fe:0,onLlmChange:e=>{h=e},onTrace:E?(e,t)=>{try{Qe({type:`trace`,spans:e,metrics:t})}catch{}}:void 0,debug:e.debug}),ee.current=M.agent,Ve&&Ve.setReconfigureHook&&Ve.setReconfigureHook(()=>{M.agent&&M.agent.setTools(Te())})})(),M}function Xfe(e){let t=e.id??g7();e.id||console.warn(`[page-agent-sdk] 未传 options.id,已生成随机 id "${t}"。刷新后持久化数据无法恢复,请传稳定 id。`);let n=e.streaming??!0,r=e.ui??`default`,i,a=e.shareContext?Q9.get(t):void 0;a?i=a:(i=Yfe(e,t),e.shareContext&&Q9.set(t,i)),i.refCount++;let o=null,s=null,c=j7(e),l=null,u=null;async function d(a){if(await i.initDone,o){m();return}if(a!==void 0&&(e.container=a),r===!1){i.store&&(l=()=>{i.vfsStore.flush?.(),i.store.flush()},u=()=>{document.visibilityState===`hidden`&&i.store.flush()},typeof window<`u`&&window.addEventListener(`pagehide`,l),typeof document<`u`&&document.addEventListener(`visibilitychange`,u));return}let d=typeof e.container==`string`?document.querySelector(e.container):e.container;if(!d)throw Error(`createChatSdk: 挂载点未找到(${e.container})`);s=d;let g=i.agent.debugLogs;o=tW($z({setup(){return()=>NH(G$,{fetchStream:n?i.stream:void 0,fetchResponse:n?void 0:(e,t)=>{if(t){let e=()=>i.resolveConflict(`keep_external`);t.aborted?e():t.addEventListener(`abort`,e,{once:!0})}return i.agent.invoke(e,t)},title:c.title,placeholder:c.placeholder,debugLogs:g.value,initialMessages:i.messages,getInfo:()=>i.getInfo(),onUndo:i.checkpoint?()=>i.checkpoint.restore():void 0,canUndo:i.checkpoint?()=>i.checkpoint.canRestore():void 0,onPersist:async()=>{i.afterRound(),i.store&&await i.store.flush()},onClear:()=>i.resetSession(),pendingConflict:i.pendingConflict.value,onResolveConflict:e=>i.resolveConflict(e),infoTick:i.infoTick,getSkillContent:i.skillsController?e=>i.skillsController.getContent(e):void 0,onAddSkill:i.skillsController?e=>i.addSkill(e):void 0,onRemoveSkill:i.skillsController?e=>i.removeSkill(e):void 0,getUserSkillNames:i.skillsController?()=>i.listUserSkills():void 0,onGetSkill:i.skillsController?e=>i.getUserSkill(e):void 0,drawer:c.drawer===!0,drawerWidth:c.drawerWidth,drawerHidden:c.drawerHidden===!0,inputRows:c.inputRows,sections:c.sections,getFocus:()=>i.getFocus(),getFocuses:()=>i.getFocuses(),onSetFocus:e=>i.setFocus(e),onAddFocus:e=>i.addFocus(e),onRemoveFocus:e=>i.removeFocus(e),onClearFocus:()=>i.clearFocus(),onFocusChipClick:e=>i.emit({type:`focus_chip_click`,path:e.path,label:e.label}),onClose:c.onClose??(c.drawer===!0?()=>p():()=>f()),...i.store?{sessions:i.sessions.value,currentSessionId:i.sessionId,onNewSession:()=>{h(()=>i.switchSession())},onOpenSession:e=>{h(()=>i.switchSession(e))},onRemoveSession:async e=>{e!==i.sessionId&&(await i.store.deleteSession(t,e),await i.refreshSessions())}}:{}})}})),o.mount(d),c.drawer===!0&&c.drawerHidden===!0&&p(),i.store&&(l=()=>{i.vfsStore.flush?.(),i.store.flush()},u=()=>{document.visibilityState===`hidden`&&i.store.flush()},typeof window<`u`&&window.addEventListener(`pagehide`,l),typeof document<`u`&&document.addEventListener(`visibilitychange`,u))}function f(){i.resolveConflict(`keep_external`),l&&typeof window<`u`&&window.removeEventListener(`pagehide`,l),u&&typeof document<`u`&&document.removeEventListener(`visibilitychange`,u),l=null,u=null;let e=s?.querySelector?.(`.chat-dialog`);if(o&&e){e.classList.add(`cs-leaving`);let t=s?.querySelector?.(`.chat-mask`);t&&t.classList.add(`cs-leaving`);let n=!1,r=()=>{n||(n=!0,o?.unmount(),o=null,s=null,i.release())};e.addEventListener(`transitionend`,r,{once:!0}),setTimeout(r,320);return}o?.unmount(),o=null,s=null,i.release()}function p(){if(!o)return;let e=s?.querySelector?.(`.chat-dialog`),t=s?.querySelector?.(`.chat-mask`);e&&e.classList.add(`cs-hidden`),t&&t.classList.add(`cs-hidden`)}function m(){if(!o)return;let e=s?.querySelector?.(`.chat-dialog`),t=s?.querySelector?.(`.chat-mask`);e&&e.classList.remove(`cs-hidden`),t&&t.classList.remove(`cs-hidden`)}let h=Z9();return{mount:d,unmount:f,hide:p,show:m,send:(...e)=>h(()=>i.send(...e)),batch:(...e)=>h(()=>i.batch(...e)),switchSession:(...e)=>h(()=>i.switchSession(...e)),sessions:i.sessions,async listSessions(){return i.store?i.store.listSessions(t):[]},async deleteSession(e){if(i.store){if(e===i.sessionId){console.warn(`[page-agent-sdk] deleteSession 忽略:不能删除当前会话,请先 switchSession 切到其他会话`);return}await i.store.deleteSession(t,e),await i.refreshSessions()}},get sessionId(){return i.sessionId},stream:i.stream,inspect:i.getInfo,inspectContext:()=>i.getInfo().context,getMission:i.getMission,setMission:i.setMission,getFocus:i.getFocus,getFocuses:i.getFocuses,setFocus:i.setFocus,addFocus:i.addFocus,removeFocus:i.removeFocus,clearFocus:i.clearFocus,messages:i.messages,restoreLastCheckpoint:()=>i.checkpoint?.restore()??!1,listCheckpoints:()=>i.checkpoint?.list()??[],hook:e=>(i.listeners.add(e),()=>i.listeners.delete(e)),setData:e=>{if(!i.dataOpsController){console.warn(`[page-agent-sdk] setData 忽略:dataOps 已关闭(capabilities.dataOps:false)`);return}i.dataOpsController.set(e),i.infoTick.value++},getData:()=>i.liveData(),setSkills:e=>{let t=i.skillsController;if(!t){console.warn(`[page-agent-sdk] setSkills 忽略:skills 已关闭(capabilities.skills:false)`);return}t.set(e),i.unloadSkillTools?.(),i.infoTick.value++},addSkill:e=>{if(!i.skillsController){console.warn(`[page-agent-sdk] addSkill 忽略:skills 已关闭(capabilities.skills:false)`);return}i.addSkill(e),i.unloadSkillTools?.(e.name)},removeSkill:e=>{if(!i.skillsController)return console.warn(`[page-agent-sdk] removeSkill 忽略:skills 已关闭(capabilities.skills:false)`),!1;let t=i.removeSkill(e);return t&&i.unloadSkillTools?.(e),t},listUserSkills:()=>i.listUserSkills(),getUserSkill:e=>i.getUserSkill(e),invalidateSkillCache:e=>{let t=i.skillsController;if(!t){console.warn(`[page-agent-sdk] invalidateSkillCache 忽略:skills 已关闭(capabilities.skills:false)`);return}t.invalidateCache(e),i.unloadSkillTools?.(e)},exportData:()=>{let e=i.liveData()?.bind;return e==null?null:JSON.parse(JSON.stringify(e))},importData:(e,t)=>{let n=i.liveData();if(!n||!i.dataOpsController)return{ok:!1,error:`dataOps 未开启或无主数据`};let r=n.bind;if(typeof r!=`object`||!r)return{ok:!1,error:`主数据 bind 非对象,无法就地还原(集成方应用对象包裹)`};if(t?.validate!==!1){let t=n.schema.safeParse(e);if(!t.success)return{ok:!1,error:`schema 校验失败:`+(t.error?.message??`未知错误`)}}return V0(r,e),i.dataOpsController?.markDataDirty?.(),t?.emit!==!1&&i.emit({type:`data_change`,operation:`set`,value:r}),{ok:!0}},createResource:(e,t)=>{let n=i.dataOpsController;if(!n?.createResource)throw Error(`[page-agent-sdk] createResource 不可用:需配 data.resources + vfsStore(capabilities.vfs 默认开)`);return n.createResource(e,t)},getResource:e=>i.dataOpsController?.getResource?.(e),updateResource:(e,t)=>{let n=i.dataOpsController;if(!n?.updateResource)throw Error(`[page-agent-sdk] updateResource 不可用:需配 data.resources + vfsStore`);n.updateResource(e,t)},deleteResource:e=>i.dataOpsController?.deleteResource?.(e)??!1,listResources:()=>i.dataOpsController?.listResources?.()??[],releaseResources:e=>{let t=i.dataOpsController;if(!(!t?.listResources||!t.deleteResource))if(e&&e.length)for(let n of e)t.deleteResource(n);else for(let e of t.listResources())t.deleteResource(e.path)},usage:i.usage,pendingConflict:i.pendingConflict,resolveConflict:e=>i.resolveConflict(e),setTools:e=>i.setTools(e),addTool:e=>i.addTool(e),removeTool:e=>i.removeTool(e),setLlm:e=>i.setLlm(e),setMemory:e=>i.setMemory(e),refreshMemory:()=>i.refreshMemory(),setSubagents:e=>i.setSubagents(e),addSubagent:e=>i.addSubagent(e),removeSubagent:e=>i.removeSubagent(e)}}return bm(),e.ApprovalBar=RY,e.CAPABILITIES=M7,e.CONTEXT_PRESETS=F7,e.ChatDialog=G$,e.ChatHeader=DW,e.ChatInput=sX,e.CodePreview=YJ,e.CompressDecisionSchema=s7,e.ConflictBar=YY,e.DEFAULT_SYSTEM_PROMPT=r7,e.FocusBar=NW,e.HUMAN_CONFIRM_TOOL_NAME=I0,e.MIN_CONTEXT_WINDOW=i1,e.MessageContent=ZJ,e.MessageList=yY,e.MessageRow=fY,e.QueuedBar=DY,e.STOP_WORDS=X5,e.SkillPanel=W$,e.UNSAFE_KEYS=L7,e.actionsToInspectInfo=V9,e.actionsToTools=B9,e.agentError=Z$,e.analyzeContext=t2,e.applyPatchToClone=Y7,e.applyPatchToLive=dfe,e.asAgentError=X$,e.buildDataPrompt=i7,e.buildSystemPrompt=a7,e.chatContextKey=dW,e.commitSetToBind=D9,e.connectMcp=W5,e.constructLlmFromConfig=vI,e.constructOpenLlmSync=_I,e.copyText=uW,e.createAgent=A1,e.createApprovalMiddleware=F0,e.createChatContext=fW,e.createChatSdk=Xfe,e.createCheckpointManager=H0,e.createCheckpointMiddleware=U0,e.createConflictManager=h7,e.createContextInspectorMiddleware=n2,e.createDataOps=k9,e.createHumanConfirmMiddleware=R0,e.createHumanConfirmTool=L0,e.createMemoryBackend=T7,e.createMemoryMiddleware=M0,e.createProxyLlm=ece,e.createSandboxRunner=v0,e.createSdkEvents=P7,e.createSerialRunner=Z9,e.createSessionStore=k7,e.createSkillStore=J9,e.createSubagentMiddleware=J0,e.createSubagentsMiddleware=Y0,e.createUsageHintsMiddleware=W9,e.createVerifyMiddleware=X0,e.createVfs=e9,e.createWebStorageBackend=D7,e.createWriteBackCheck=Z0,e.deepClone=U7,e.defineDataToolset=Vfe,e.defineSkill=b0,e.defineTool=o7,e.deleteByPath=H7,e.deriveTitle=c7,e.describeSchemaNode=H1,e.detectGarbledToolCall=b1,e.diffObjects=Q7,e.domToStructure=M9,e.domTools=P9,e.domToolsStatic=Bfe,e.estimateMessageTokens=Q5,e.estimateRoundTokens=$5,e.estimateTokens=o1,e.extractReasoningDelta=bI,e.extractSchemaHint=s0,e.extractText=U5,e.extractTextDelta=yI,e.extractUsage=xI,e.fetchDocTools=j9,e.fetchTools=zfe,e.filterByToolMode=E9,e.formatConstraints=U1,e.formatZodIssues=K$,e.getByPath=B7,e.getDomTool=N9,e.getEnvSummary=I9,e.getSchemaAtPath=P1,e.getSchemaTopKeys=j1,e.getTraceMetrics=l1,e.hashValue=J7,e.indexSummarize=e7,e.inspectEnvTool=L9,e.inspectTools=R9,e.isChatModel=l7,e.isContextLengthError=d1,e.isPathAllowed=M1,e.isQuotaError=b7,e.isUnsafePath=R7,e.jpEval=l9,e.jsonParseError=J$,e.limitDepth=K7,e.maybeParseValue=W7,e.offloadPassThroughChars=c1,e.offloadThresholdChars=s1,e.presets=n0,e.projectBySchema=I1,e.projectBySchemaDeep=F1,e.projectFields=G7,e.recallRounds=t7,e.renderSchemaHint=W1,e.renderSchemaOverview=G1,e.renderSchemaShallow=q1,e.resolveCapabilities=N7,e.resolveContextOptions=I7,e.resolveDialogConfig=j7,e.resolveLlm=m7,e.resolveModelCaps=a1,e.resolveStorage=A7,e.restoreInPlace=Z7,e.restoreLive=X7,e.routeError=Y$,e.runHostScript=y0,e.runSandboxedScript=f9,e.safeMerge=z7,e.safeSerialize=F9,e.safeStringify=q7,e.searchJson=u9,e.selectBuiltinTools=H9,e.setByPath=V7,e.shouldTriggerCompression=n7,e.systemPromptHelpers=r0,e.tokenize=Z5,e.toolError=$,e.unwrapSchema=N1,e.useChat=lW,e.useChatContext=pW,Object.defineProperty(e,"z",{enumerable:!0,get:function(){return ym}}),e.zodError=q$,e})({});
|
|
336
|
+
`):`无可用 checkpoint。`},{name:`list_checkpoints`,description:`列出可用会话 checkpoint(回退点)。`,schema:F({}).optional()})]:[];ve.forEach(e=>de.set(e.name,`builtin`));let ye=ie.focus,be=gI(async({path:e,label:t})=>{let n=O()?.schema;return n?P1(n,e)?(b.setFocus({path:e,...t?{label:t}:{}}),`已聚焦到 ${e}${t?`(${t})`:``}。后续仅可写该子树(越界被拒),每轮只看到该组件结构。完成精修后调 clear_focus 退出。`):`PATH_DENIED · 聚焦失败:path "${e}" 不在 schema 内。请先用 read 查看可操作路径再聚焦。`:`聚焦失败:当前无主数据 schema,无法聚焦。`},{name:`set_focus`,description:`聚焦到指定组件子树(如 components.3)精修,替换全部已有焦点(非累积;要保留已有焦点追加用 add_focus)。聚焦后:仅可写该子树(越界 PATH_DENIED)+ 每轮只看到该组件结构。多组件页面精修其中一个时用,避免改到别处。先 read 定位 path 再聚焦;完成调 clear_focus。`,schema:F({path:N().describe(`要聚焦的组件 jsonPath,如 components.3`),label:N().optional().describe(`人类可读标签,如「导航栏」`)})}),xe=gI(async()=>(b.clearFocus(),`已清除聚焦,恢复全量可操作范围(可读写所有组件)。`),{name:`clear_focus`,description:`清除当前聚焦,退出精修模式,恢复对全部组件的读写权限。`,schema:F({}).optional()}),Se=gI(async({path:e,label:t})=>{let n=O()?.schema;if(!n)return`聚焦失败:当前无主数据 schema,无法聚焦。`;if(!P1(n,e))return`PATH_DENIED · 聚焦失败:path "${e}" 不在 schema 内。请先用 read 查看可操作路径再聚焦。`;b.addFocus({path:e,...t?{label:t}:{}});let r=b.getFocuses();return`已聚焦 ${e}${t?`(${t})`:``}(当前共 ${r.length} 个焦点:${r.map(e=>e.path).join(`, `)})。后续仅可写这些子树之一(越界被拒)。`},{name:`add_focus`,description:`追加聚焦一个组件子树(multi-focus,可同时聚焦多个相关组件)。校验 path 在 schema 内。聚焦后仅可写已聚焦的子树之一(越界 PATH_DENIED)。与 set_focus(替换全部)不同:本工具累积追加,不清除已有焦点。`,schema:F({path:N().describe(`要追加聚焦的组件 jsonPath,如 components.3`),label:N().optional().describe(`人类可读标签`)})}),k=gI(async({path:e})=>{let t=b.getFocuses().length;b.removeFocus(e);let n=b.getFocuses();return n.length===t?`path "${e}" 不在当前焦点列表中(当前:${n.map(e=>e.path).join(`, `)||`无`})。`:n.length?`已移除焦点 ${e}(剩余 ${n.length} 个:${n.map(e=>e.path).join(`, `)})。`:`已移除焦点 ${e},聚焦已清空,恢复全量操作范围。`},{name:`remove_focus`,description:`移除单个聚焦焦点(by path),保留其他焦点。移除最后一个等价退出精修。全部退出用 clear_focus。`,schema:F({path:N().describe(`要移除的焦点 jsonPath`)})}),Ce=ye&&e.toolMode===`advanced`?[be,xe,Se,k]:[];Ce.forEach(e=>de.set(e.name,`builtin`));let A=[],we=new Map,j=Te();function Te(){let{tools:e,collisions:t}=Hfe([{label:`builtin`,tools:fe},{label:`user`,tools:pe},{label:`action`,tools:me},{label:`humanConfirm`,tools:_e?[_e]:[]},{label:`checkpoint`,tools:ve},{label:`focus`,tools:Ce},{label:`mcp`,tools:he},{label:`skill`,tools:A}]);return t.length&&console.warn(`[page-agent-sdk] 工具重名,后注册覆盖先注册:`,t.map(e=>`${e.name}(${e.loser}→${e.winner})`).join(`, `)),e}let Ee=ie.planning,De=ie.missionAnchor,Oe=ie.workingMemory,ke=ie.skills,Ae=ie.vfs;if(Ae)for(let e of hfe)de.set(e,`builtin`);if(Ee)for(let e of v.tools??[])de.set(e.name,`builtin`);let je=ie.summarization,Me=ie.agentCompression&&!!l;e.debug&&ie.agentCompression&&!l&&console.warn(`[page-agent-sdk][agentCompression] agentCompression 开启但 summaryLlm 不可用(或缺 apiKey / 模型不支持工具),压缩决策不启用,回退静态压缩`);let Ne=ie.memory,Pe=ie.subagent,Fe=e.verify?.maxAttempts??2,Ie=ie.verify&&e.verify?.enabled!==!1&&Fe>0,Le=ie.contextInspector;e.verify?.check&&!ie.verify&&console.warn(`[page-agent-sdk][verify] 检测到 verify.check 但 capabilities.verify 未开启,verify 未装载`);let Re=e.subagent,ze=Re?.allowedTools??[],Be=!Pe||Re?.enabled===!1?void 0:J0({llm:Re?.llm??e.llm,allTools:()=>j,allowedTools:ze.length?ze:void 0,systemPrompt:Re?.systemPrompt,temperature:Re?.temperature,maxTokens:Re?.maxTokens,skills:Re?.skills,maxDepth:Re?.maxDepth,maxParallel:Re?.maxParallel,debug:e.debug,getFocuses:()=>b.getFocuses(),getSchema:()=>O()?.schema??null}),Ve=Pe&&e.subagents!==void 0?Y0(e.subagents,{llm:e.llm,allTools:()=>j,debug:e.debug,getFocuses:()=>b.getFocuses(),getSchema:()=>O()?.schema??null}):void 0,He=Ve?Ve.controller:null,Ue=[`get_data`,`describe_data`,`read`,`fetch_document`],We=j.filter(e=>Ue.includes(e.name)),Ge=Ie?X0({check:e.verify.check??Z0({schemas:()=>O()?{"":O().schema}:{},root:()=>O()?.bind}),adversarial:e.verify?.adversarial?{llm:e.llm,tools:We}:void 0}):void 0,Ke=Le?n2({contextWindow:u.contextWindow,thresholdRatio:I7(e,u.contextWindow).summaryThresholdRatio}):void 0,qe=W9({...ie,humanConfirm:ge,subagents:e.subagents?.map(e=>({id:e.id,description:e.description,temperature:e.temperature}))},T&&!!C,e.toolMode,!!C?.resources?.length),Je=C?{name:`dataHint`,augmentPrompt:()=>i7(O(),e.schemaHint)||void 0}:null,Ye=e.augmentSystem?{name:`augmentSystem`,augmentPrompt:t=>{try{return e.augmentSystem({state:t,data:O()})}catch(t){e.debug&&console.log(`[page-agent-sdk][augmentSystem] 回调抛错,降级跳过:`,t.message);return}}}:null,Xe=e.onEvent,Ze=P7(e.onEvent),Qe=Ze.emit,$e,et=[],tt=e=>({name:e.name,description:e.description,content:typeof e.getContent==`function`?e.getContent():``}),nt=e=>({name:e.name,description:e.description,getContent:()=>e.content}),rt=e.skillStorage===!1?null:J9({...typeof e.skillStorage==`object`?e.skillStorage:{},id:e.skillStorage&&typeof e.skillStorage==`object`&&e.skillStorage.id?e.skillStorage.id:`agent::${t}`}),it=()=>{let t=$e?$e.controller:null;if(t){let n=(e.skills||[]).filter(e=>!et.some(t=>t.name===e.name));t.set([...n,...et])}M.infoTick.value++},at=async()=>{if(rt)try{let t=await rt.list();if(t.length){et=t.map(nt);let n=$e?$e.controller:null;if(n){let t=(e.skills||[]).filter(e=>!et.some(t=>t.name===e.name));n.set([...t,...et])}M.infoTick.value++}}catch{}},ot=je?Ude({...d,llmInvoke:s,getRegisteredData:()=>O()?[{description:O().description??`主数据对象`}]:[],preserveLastToolResults:p,...Me?{decideInvoke:l,getSnapshot:()=>Ke?.getSnapshot()}:{}}):void 0,st=lfe([...Je?[Je]:[],qe,...De?[y]:[],...Ee?[v]:[],...ke?[$e=j0(e.skills||[],{readVfs:Ae?e=>_.files[e]?.content:void 0,hostScriptEnabled:ie.skillHostScript,onToolsReady:(e,t)=>{for(let n of t){let t=A.findIndex(e=>e.name===n.name);t>=0&&A.splice(t,1),A.push(n),we.set(n.name,e),de.set(n.name,`skill:${e}`)}j=Te(),M.agent&&M.agent.setTools(j),M.infoTick.value++}})]:[],...Ae?[_fe(_)]:[],...ot?[ot]:[],...Oe?[x]:[],...ye?[b]:[],...ue?[ue]:[],...Ne?[S]:[],...e.permissions?.length?[Cce(e.permissions)]:[],...ne&&re&&w?[U0(w)]:[],...ge?[R0()]:[],...e.approval&&(e.approval.tools!==void 0||e.approval.confirm)?[F0(e.approval)]:[],...Ge?[Ge]:[],...Be?[Be]:[],...Ve?[Ve]:[],...Ye?[Ye]:[],...Ke?[Ke]:[],...e.middleware||[],...oe?[Rfe(n,{tokenBudget:e.tokenBudget,timeBudgetMs:e.timeBudgetMs},Qe)]:[],Jfe(Qe,g,O,n)]),ct=e.maxMemoryRounds??Kfe,lt=kR([]);async function ut(){a&&(lt.value=(await a.listSessions(t)).sort((e,t)=>t.lastAccessed-e.lastAccessed))}let M={agentId:t,store:a,messages:g,vfsStore:_,listeners:Ze.listeners,todosMw:v,memoryMw:S,missionMw:y,workingMemoryMw:x,focusMw:b,agent:null,initDone:Promise.resolve(),sessionId:``,refCount:0,mcpClosers:[],mcpServers:[],checkpoint:w,dataOpsController:le,skillsController:$e?$e.controller:null,infoTick:i,pendingConflict:r.pendingConflict,sessions:lt,refreshSessions:ut,liveData:O,usage:n,emit:Qe,unloadSkillTools(e){if(e){let t=A.length;if(A=A.filter(t=>we.get(t.name)===e?(de.delete(t.name),we.delete(t.name),!1):!0),A.length===t)return}else{if(!A.length)return;for(let e of A)de.delete(e.name),we.delete(e.name);A=[]}j=Te(),M.agent&&M.agent.setTools(j)},applySnapshot(t){if(t.messages?.length&&g.push(...t.messages),t.vfs&&_.hydrate&&_.hydrate(t.vfs),t.todos?.length&&v.reset(t.todos),t.memory&&!e.memory&&S.reset(t.memory),t.checkpoints?.length&&w&&w.importStack(t.checkpoints),t.usage&&Object.assign(n,t.usage),t.mission&&De&&y.setMission(t.mission),t.workingMemory&&Oe&&x.restore(t.workingMemory),ye){let n=t.focus,r=n?Array.isArray(n)?n:[n]:[];if(r.length){let t=O()?.schema,n=t?r.filter(e=>P1(t,e.path)):[];if(n.length&&(b.setFocus(null),n.forEach(e=>b.addFocus(e))),e.debug&&n.length<r.length){let e=r.filter(e=>!n.includes(e)).map(e=>e.path);console.warn(`[page-agent-sdk][focus] 恢复的焦点部分 path 已失效(schema 变化/无 schema),剔除:`,e)}}}mt()},addSkill(e){let t=et.findIndex(t=>t.name===e.name);t>=0?et[t]=e:et.push(e),it(),rt&&rt.put(tt(e))},removeSkill(e){let t=et.findIndex(t=>t.name===e);return t<0?!1:(et.splice(t,1),it(),rt&&rt.remove(e),!0)},listUserSkills(){return et.map(e=>e.name)},getUserSkill(e){let t=et.find(t=>t.name===e);if(t)return{name:t.name,description:t.description,content:typeof t.getContent==`function`?t.getContent():``}},afterRound(){ht(),vt()},async send(e,t){await M.initDone,t??={},t?.mission&&De&&y.setMission(t.mission);let n=e;if(t.interceptors?.input)try{let r=t.interceptors.input(e);typeof r==`string`&&(n=r)}catch{}let r=oe?t.maxAutoRetries??1:0,i=0,o=!1;for(;;){o||=(g.push({role:`user`,content:n,timestamp:Date.now()}),!0);try{let e=await M.agent.invoke(g);if(t.interceptors?.output)try{let n=t.interceptors.output(e);typeof n==`string`&&(e=n)}catch{}return g.push({role:`assistant`,content:e,timestamp:Date.now()}),M.afterRound(),a&&await a.flush(),e}catch(e){let t=X$(e,`fatal`);if(i<r&&w?.canRestore()){i+=1,w.restore(),o=!0,Qe({type:`error`,message:`致命错误自动恢复(${i}/${r}):${t.message},已回退 checkpoint 重试`,severity:`observable`,code:`AUTO_RECOVER_RETRY`,context:{attempt:i,cause:t.code??t.message.slice(0,120)}});continue}throw Qe({type:`error`,message:t.message,severity:t.severity,...t.code?{code:t.code}:{},...t.context===void 0?{}:{context:t.context}}),e}}},async batch(e,t){if(await M.initDone,!e.length)return[];let n=[];for(let r=0;r<e.length;r++){let i=e[r];w&&w.save(`batch:${r}`);let o=g.length;try{g.push({role:`user`,content:i,timestamp:Date.now()});let o=await M.agent.invoke(g);g.push({role:`assistant`,content:o,timestamp:Date.now()}),M.afterRound(),a&&await a.flush(),n.push({index:r,task:i,reply:o,ok:!0}),t?.({done:r+1,total:e.length,task:i,ok:!0})}catch(a){g.length>o&&g.splice(o);let s=X$(a,`fatal`);Qe({type:`error`,message:`批量任务 ${r+1}/${e.length} 失败:${s.message}`,severity:`observable`,code:`BATCH_TASK_FAILED`,context:{index:r,task:i.slice(0,100)}}),n.push({index:r,task:i,error:s.message,ok:!1}),t?.({done:r+1,total:e.length,task:i,ok:!1})}}return n},async switchSession(n){if(await M.initDone,!a)throw Error(`page-agent-sdk: storage 未开启,无法切换会话(请传 storage 选项)`);if(r.resolve(`keep_external`),M.sessionId&&a){if(De){let e=y.getMission();e&&a.save(t,M.sessionId,{mission:e})}if(Oe){let e=x.getWorkingMemory();e&&a.save(t,M.sessionId,{workingMemory:e})}if(ye){let e=b.getFocuses();a.save(t,M.sessionId,{focus:e.length?e:null})}}_.flush?.(),await a.flush();let i=n??``,o;return i?(o=await a.load(t,i),o||await a.createSession(t,e.session?.title,i)):i=await a.createSession(t,e.session?.title),M.sessionId=i,g.splice(0,g.length),_.clear?.(),v.reset([]),e.memory||S.reset(``),y.reset(),x.reset(),b.reset(),w&&w.importStack([]),M.agent.debugLogs.value=[],o||=await a.load(t,i),o&&(M.applySnapshot(o),Qe({type:`session_restored`,sessionId:i,rounds:o.messages?.length??0})),e.memory&&a.save(t,M.sessionId,{memory:S.get()||(typeof e.memory==`string`?e.memory:``)}),ut(),gt=void 0,_t=!1,i},resetSession:()=>{a&&(M.sessionId=g7(),_.clear?.(),v.reset([]),e.memory||S.reset(``),y.reset(),x.reset(),b.reset(),w&&w.importStack([]),M.agent&&(M.agent.debugLogs.value=[]),a.createSession(M.agentId,e.session?.title,M.sessionId),Qe({type:`session_restored`,sessionId:M.sessionId,rounds:0}),ut(),gt=void 0,_t=!1)},stream:(e,t,n)=>{if(!M.agent)throw Error(`page-agent-sdk: agent 尚未初始化完成,请先 await mount()`);_?.setProtectedRefs?.(X9(e));let i=Xe?e=>{t?.(e),Qe(e)}:t;if(n){let e=()=>r.resolve(`keep_external`);n.aborted?e():n.addEventListener(`abort`,e,{once:!0})}return M.agent.stream(e,i,n)},release(){if(M.refCount--,M.refCount<=0){a&&(_.flush?.(),a.flush(),a.dispose()),rt&&rt.dispose();let e=M.mcpClosers.splice(0);e.length&&Promise.allSettled(e.map(e=>e())),Q9.delete(t)}},resolveConflict:r.resolve,setTools(e){pe.length=0,e.forEach(e=>{pe.push(e),de.set(e.name,`user`)}),j=Te(),M.agent&&M.agent.setTools(j),M.infoTick.value++},addTool(e){j.some(t=>t.name===e.name)&&console.warn(`[page-agent-sdk] 工具 "${e.name}" 已存在,新工具覆盖(后注册覆盖先注册)`);for(let t=pe.length-1;t>=0;t--)pe[t].name===e.name&&pe.splice(t,1);pe.push(e),de.set(e.name,`user`),j=Te(),M.agent&&M.agent.setTools(j),M.infoTick.value++},removeTool(e){let t=pe.findIndex(t=>t.name===e);return t<0?!1:(pe.splice(t,1),de.delete(e),j=Te(),M.agent&&M.agent.setTools(j),M.infoTick.value++,!0)},setLlm(t){let n;if(l7(t))n=t;else{let e=t;if((e.provider??`openai`)===`anthropic`)throw Error(`[page-agent-sdk][setLlm] 切换到 Anthropic 需传 BaseChatModel 实例(动态 import 无法同步);请先 const { ChatAnthropic } = await import("@langchain/anthropic") 构造实例后传入`);n=_I(e)}typeof n.bindTools!=`function`&&e.debug&&console.warn(`[page-agent-sdk][setLlm] 新模型不支持 bindTools(tool calling 会失效)`),h=t;let r=l7(t)?void 0:t;if(u=a1({model:r?.model??t.model??t.modelName,contextWindow:e.contextWindow??r?.contextWindow,maxOutputTokens:e.maxOutputTokens??r?.maxOutputTokens}),u.contextWindow<2e5)throw Error(`[page-agent-sdk][setLlm] 新模型上下文窗口 ${u.contextWindow} 小于最小支持 ${i1}(需 ≥200K 窗口模型)`);M.agent&&(M.agent.setLlm(n),M.agent.setModelCaps?.(u)),ot?.setContextWindow?.(u.contextWindow),Ke?.setContextWindow?.(u.contextWindow),M.infoTick.value++,e.debug&&console.log(`[page-agent-sdk][setLlm] 重解析 modelCaps + 回灌:`,u)},setMemory(e){S.reset(e),typeof e==`function`&&S.refresh(),M.infoTick.value++},refreshMemory(){return S.refresh()},setSubagents(t){if(!He){e.debug&&console.warn(`[page-agent-sdk][setSubagents] 未配 subagents:[] 或 capabilities.subagent 关闭,忽略`);return}He.set(t),M.infoTick.value++},addSubagent(t){if(!He){e.debug&&console.warn(`[page-agent-sdk][addSubagent] 未配 subagents:[] 或 capabilities.subagent 关闭,忽略`);return}He.add(t),M.infoTick.value++},removeSubagent(t){if(!He)return e.debug&&console.warn(`[page-agent-sdk][removeSubagent] 未配 subagents:[] 或 capabilities.subagent 关闭,忽略`),!1;let n=He.remove(t);return n&&M.infoTick.value++,n},getInfo(){return{id:t,sessionId:M.sessionId,model:l7(h)?h.model??h.modelName:h.model,systemPrompt:M.agent?.getEffectiveSystemPrompt?.()??se+i7(O(),e.schemaHint),tools:(M.agent?.allTools??j).map(e=>({name:e.name,description:e.description,schema:e.schema,source:de.get(e.name)||`user`})),skills:($e?$e.controller.get():e.skills??[]).map(e=>({name:e.name,description:e.description})),data:O()?{description:O().description,schema:O().schema}:void 0,contextPreset:e.contextPreset??`auto`,memory:S.get(),middleware:st.map(e=>e.name),todos:(M.agent?.getState?.()?.todos??[]).map(e=>({id:e.id,content:e.content,status:e.status,...e.parentId===void 0?{}:{parentId:e.parentId},...e.deps===void 0?{}:{deps:e.deps},...e.criteria===void 0?{}:{criteria:e.criteria},...e.evidence===void 0?{}:{evidence:e.evidence}})),planPhase:v.getPlanPhase(),mission:De?y.getMission():void 0,workingMemory:Oe?x.getWorkingMemory():void 0,focus:ye?b.getFocus():void 0,focuses:ye?b.getFocuses():[],trace:E&&M.agent?.spans?{spans:M.agent.spans.value,metrics:l1(M.agent.spans.value)}:void 0,actions:V9(e.actions??{}),subagent:{enabled:!!Be,maxDepth:e.subagent?.maxDepth??1,maxParallel:e.subagent?.maxParallel??4,allowedTools:e.subagent?.allowedTools??[],subagents:He?.get()??[]},verify:{enabled:!!Ge,maxAttempts:Ie?Fe:0,adversarial:Ie&&!!e.verify?.adversarial},context:(()=>{let e=Ke?.getSnapshot();if(e){let t=M.agent?.getState?.()?.lastCompression;t&&(e.compression=t)}return e})(),mcp:{servers:M.mcpServers},lastCompression:M.agent?.getState?.()?.lastCompression,checkpoints:w?{enabled:!0,auto:re,list:w.list()}:void 0}},getMission(){return De?y.getMission():void 0},setMission(t){if(!De){e.debug&&console.warn(`[page-agent-sdk][mission] capabilities.missionAnchor 关闭,setMission 忽略`);return}y.setMission(t),M.infoTick.value++},getFocus(){return ye?b.getFocus():void 0},getFocuses(){return ye?b.getFocuses():[]},setFocus(t){let n=$9(t,`setFocus`,ye,()=>O()?.schema,e.debug);return n.ok?(b.setFocus(t),M.infoTick.value++,{ok:!0}):n},addFocus(t){let n=$9(t,`addFocus`,ye,()=>O()?.schema,e.debug);return n.ok?b.getFocuses().length>=8?(e.debug&&console.warn(`[page-agent-sdk][focus] addFocus 拒绝:焦点数已达上限 8(augmentPrompt 注入每焦点子树 schema,过多致 system prompt 超预算)`),{ok:!1,error:`焦点数上限 8(避免 system prompt 撑爆)`}):(b.addFocus(t),M.infoTick.value++,{ok:!0}):n},removeFocus(e){ye&&(b.removeFocus(e),M.infoTick.value++)},clearFocus(){ye&&(b.clearFocus(),M.infoTick.value++)}};async function dt(){if(!a)return;await a.ready;let n=e.session||{};if(n.id){M.sessionId=n.id;let e=await a.load(t,M.sessionId);e?(M.applySnapshot(e),Qe({type:`session_restored`,sessionId:M.sessionId,rounds:e.messages?.length??0})):await a.createSession(t,n.title,M.sessionId)}else if(n.autoResume!==!1){let r=await a.listSessions(t);if(e.debug&&console.log(`[page-agent-sdk][restore] listSessions`,t,r.length,r.map(e=>e.sessionId)),r.length){M.sessionId=r[0].sessionId;let n=await a.load(t,M.sessionId);n?(M.applySnapshot(n),Qe({type:`session_restored`,sessionId:M.sessionId,rounds:n.messages?.length??0}),e.debug&&console.log(`[page-agent-sdk][restore] 恢复会话`,M.sessionId,`${n.messages?.length??0} msgs`)):e.debug&&console.log(`[page-agent-sdk][restore] 会话 meta 存在但快照为空`,M.sessionId)}else M.sessionId=await a.createSession(t,n.title),e.debug&&console.log(`[page-agent-sdk][restore] 新建会话(无历史)`,M.sessionId)}else M.sessionId=await a.createSession(t,n.title);e.memory&&a.save(t,M.sessionId,{memory:S.get()||(typeof e.memory==`string`?e.memory:``)}),ut()}async function ft(){await at()}function pt(e){let t={};for(let n of X9(e)){let e=_.files[n];e&&(t[n]=e.content)}return t}function mt(){let e=Gfe(_.files,X9(g));for(let t of e)delete _.files[t]}function ht(){let e=Bde(g,ct);if(!e.trimmed)return;let{older:t,summary:n}=e;if(Qe({type:`context_trimmed`,dropped:t.map(e=>({round:e.round,user:e.userMsg.content,assistant:e.assistantMsgs.map(e=>e.content),steps:e.assistantMsgs.flatMap(e=>e.steps??[])})),vfsResults:pt(t.flatMap(e=>[e.userMsg,...e.assistantMsgs])),summary:n.content,reason:`max_memory_rounds`}),g.splice(e.deleteFrom,e.deleteCount,n),mt(),f&&s){let n=e.summary,{prevSeg:r}=e;(async()=>{try{let e=await s(e7(t,m)),i=g.indexOf(n);if(i<0)return;g[i].content=zde(t,r,e),vt()}catch{}})()}}let gt,_t=!1;function vt(){if(!M.sessionId||!a)return;let r=JSON.parse(JSON.stringify(g));a.save(t,M.sessionId,{messages:r});let i=M.agent?.getState?.()?.todos??[];if(a.save(t,M.sessionId,{todos:i}),De){let e=y.getMission();e&&a.save(t,M.sessionId,{mission:e})}if(Oe){let e=x.getWorkingMemory();e&&a.save(t,M.sessionId,{workingMemory:e})}if(ye){let e=b.getFocuses();a.save(t,M.sessionId,{focus:e.length?e:null})}oe&&w&&(a.save(t,M.sessionId,{checkpoints:w.exportStack()}),a.save(t,M.sessionId,{usage:n}));let o=c7(g);o&&o!==gt&&(gt=o,a.updateTitle(t,M.sessionId,o)),e.autoTitle!==!1&&c&&!_t&&g.some(e=>e.role===`user`)&&g.some(e=>e.role===`assistant`)&&(_t=!0,(async()=>{let e=await c(g);e&&(await a.updateTitle(t,M.sessionId,e),await ut())})()),e.debug&&console.log(`[page-agent-sdk][persist] save`,M.sessionId,`${g.length} msgs`)}return M.initDone=(async()=>{if(await dt(),await ft(),e.mcp?.length){let t=await Promise.allSettled(e.mcp.map(e=>W5(e)));M.mcpClosers=t.flatMap(e=>e.status===`fulfilled`?[e.value.close]:[]),M.mcpServers=[],t.forEach((t,n)=>{let r=e.mcp[n],i=r.name??r.url;t.status===`fulfilled`?(M.mcpServers.push({name:i,url:r.url,toolCount:t.value.tools.length}),t.value.tools.forEach(e=>de.set(e.name,`mcp:${i}`)),he.push(...t.value.tools)):console.warn(`[page-agent-sdk][mcp] server ${i} 连接失败:`,t.reason)}),j=Te(),e.debug&&console.log(`[page-agent-sdk][mcp] 注入 ${he.length} 个工具,${M.mcpServers.length} 个 server`)}let t=l7(e.llm)?e.llm:await vI(e.llm);M.agent=A1({llm:t,systemPrompt:se,tools:j,middleware:st,maxToolRounds:e.maxToolRounds,maxRetries:e.maxRetries,maxParallelTools:e.maxParallelTools,contextWindow:u.contextWindow,maxOutputTokens:u.maxOutputTokens,maxVerifyAttempts:Ie?Fe:0,onLlmChange:e=>{h=e},onTrace:E?(e,t)=>{try{Qe({type:`trace`,spans:e,metrics:t})}catch{}}:void 0,debug:e.debug}),ee.current=M.agent,Ve&&Ve.setReconfigureHook&&Ve.setReconfigureHook(()=>{M.agent&&M.agent.setTools(Te())})})(),M}function Xfe(e){let t=e.id??g7();e.id||console.warn(`[page-agent-sdk] 未传 options.id,已生成随机 id "${t}"。刷新后持久化数据无法恢复,请传稳定 id。`);let n=e.streaming??!0,r=e.ui??`default`,i,a=e.shareContext?Q9.get(t):void 0;a?i=a:(i=Yfe(e,t),e.shareContext&&Q9.set(t,i)),i.refCount++;let o=null,s=null,c=j7(e),l=null,u=null;async function d(a){if(await i.initDone,o){m();return}if(a!==void 0&&(e.container=a),r===!1){i.store&&(l=()=>{i.vfsStore.flush?.(),i.store.flush()},u=()=>{document.visibilityState===`hidden`&&i.store.flush()},typeof window<`u`&&window.addEventListener(`pagehide`,l),typeof document<`u`&&document.addEventListener(`visibilitychange`,u));return}let d=typeof e.container==`string`?document.querySelector(e.container):e.container;if(!d)throw Error(`createChatSdk: 挂载点未找到(${e.container})`);s=d;let g=i.agent.debugLogs;o=tW($z({setup(){return()=>NH(G$,{fetchStream:n?i.stream:void 0,fetchResponse:n?void 0:(e,t)=>{if(t){let e=()=>i.resolveConflict(`keep_external`);t.aborted?e():t.addEventListener(`abort`,e,{once:!0})}return i.agent.invoke(e,t)},title:c.title,placeholder:c.placeholder,debugLogs:g.value,initialMessages:i.messages,getInfo:()=>i.getInfo(),onUndo:i.checkpoint?()=>i.checkpoint.restore():void 0,canUndo:i.checkpoint?()=>i.checkpoint.canRestore():void 0,onPersist:async()=>{i.afterRound(),i.store&&await i.store.flush()},onClear:()=>i.resetSession(),pendingConflict:i.pendingConflict.value,onResolveConflict:e=>i.resolveConflict(e),infoTick:i.infoTick,getSkillContent:i.skillsController?e=>i.skillsController.getContent(e):void 0,onAddSkill:i.skillsController?e=>i.addSkill(e):void 0,onRemoveSkill:i.skillsController?e=>i.removeSkill(e):void 0,getUserSkillNames:i.skillsController?()=>i.listUserSkills():void 0,onGetSkill:i.skillsController?e=>i.getUserSkill(e):void 0,drawer:c.drawer===!0,drawerWidth:c.drawerWidth,drawerHidden:c.drawerHidden===!0,inputRows:c.inputRows,sections:c.sections,getFocus:()=>i.getFocus(),getFocuses:()=>i.getFocuses(),onSetFocus:e=>i.setFocus(e),onAddFocus:e=>i.addFocus(e),onRemoveFocus:e=>i.removeFocus(e),onClearFocus:()=>i.clearFocus(),onFocusChipClick:e=>i.emit({type:`focus_chip_click`,path:e.path,label:e.label}),onClose:c.onClose??(c.drawer===!0?()=>p():()=>f()),...i.store?{sessions:i.sessions.value,currentSessionId:i.sessionId,onNewSession:()=>{h(()=>i.switchSession())},onOpenSession:e=>{h(()=>i.switchSession(e))},onRemoveSession:async e=>{e!==i.sessionId&&(await i.store.deleteSession(t,e),await i.refreshSessions())}}:{}})}})),o.mount(d),c.drawer===!0&&c.drawerHidden===!0&&p(),i.store&&(l=()=>{i.vfsStore.flush?.(),i.store.flush()},u=()=>{document.visibilityState===`hidden`&&i.store.flush()},typeof window<`u`&&window.addEventListener(`pagehide`,l),typeof document<`u`&&document.addEventListener(`visibilitychange`,u))}function f(){i.resolveConflict(`keep_external`),l&&typeof window<`u`&&window.removeEventListener(`pagehide`,l),u&&typeof document<`u`&&document.removeEventListener(`visibilitychange`,u),l=null,u=null;let e=s?.querySelector?.(`.chat-dialog`);if(o&&e){e.classList.add(`cs-leaving`);let t=s?.querySelector?.(`.chat-mask`);t&&t.classList.add(`cs-leaving`);let n=!1,r=()=>{n||(n=!0,o?.unmount(),o=null,s=null,i.release())};e.addEventListener(`transitionend`,r,{once:!0}),setTimeout(r,320);return}o?.unmount(),o=null,s=null,i.release()}function p(){if(!o)return;let e=s?.querySelector?.(`.chat-dialog`),t=s?.querySelector?.(`.chat-mask`);e&&e.classList.add(`cs-hidden`),t&&t.classList.add(`cs-hidden`)}function m(){if(!o)return;let e=s?.querySelector?.(`.chat-dialog`),t=s?.querySelector?.(`.chat-mask`);e&&e.classList.remove(`cs-hidden`),t&&t.classList.remove(`cs-hidden`)}let h=Z9();return{mount:d,unmount:f,hide:p,show:m,send:(...e)=>h(()=>i.send(...e)),batch:(...e)=>h(()=>i.batch(...e)),switchSession:(...e)=>h(()=>i.switchSession(...e)),sessions:i.sessions,async listSessions(){return i.store?i.store.listSessions(t):[]},async deleteSession(e){if(i.store){if(e===i.sessionId){console.warn(`[page-agent-sdk] deleteSession 忽略:不能删除当前会话,请先 switchSession 切到其他会话`);return}await i.store.deleteSession(t,e),await i.refreshSessions()}},get sessionId(){return i.sessionId},stream:i.stream,afterRound:i.afterRound,get debugLogs(){return i.agent.debugLogs},infoTick:i.infoTick,inspect:i.getInfo,inspectContext:()=>i.getInfo().context,getMission:i.getMission,setMission:i.setMission,getFocus:i.getFocus,getFocuses:i.getFocuses,setFocus:i.setFocus,addFocus:i.addFocus,removeFocus:i.removeFocus,clearFocus:i.clearFocus,messages:i.messages,restoreLastCheckpoint:()=>i.checkpoint?.restore()??!1,listCheckpoints:()=>i.checkpoint?.list()??[],hook:e=>(i.listeners.add(e),()=>i.listeners.delete(e)),setData:e=>{if(!i.dataOpsController){console.warn(`[page-agent-sdk] setData 忽略:dataOps 已关闭(capabilities.dataOps:false)`);return}i.dataOpsController.set(e),i.infoTick.value++},getData:()=>i.liveData(),setSkills:e=>{let t=i.skillsController;if(!t){console.warn(`[page-agent-sdk] setSkills 忽略:skills 已关闭(capabilities.skills:false)`);return}t.set(e),i.unloadSkillTools?.(),i.infoTick.value++},addSkill:e=>{if(!i.skillsController){console.warn(`[page-agent-sdk] addSkill 忽略:skills 已关闭(capabilities.skills:false)`);return}i.addSkill(e),i.unloadSkillTools?.(e.name)},removeSkill:e=>{if(!i.skillsController)return console.warn(`[page-agent-sdk] removeSkill 忽略:skills 已关闭(capabilities.skills:false)`),!1;let t=i.removeSkill(e);return t&&i.unloadSkillTools?.(e),t},listUserSkills:()=>i.listUserSkills(),getUserSkill:e=>i.getUserSkill(e),invalidateSkillCache:e=>{let t=i.skillsController;if(!t){console.warn(`[page-agent-sdk] invalidateSkillCache 忽略:skills 已关闭(capabilities.skills:false)`);return}t.invalidateCache(e),i.unloadSkillTools?.(e)},exportData:()=>{let e=i.liveData()?.bind;return e==null?null:JSON.parse(JSON.stringify(e))},importData:(e,t)=>{let n=i.liveData();if(!n||!i.dataOpsController)return{ok:!1,error:`dataOps 未开启或无主数据`};let r=n.bind;if(typeof r!=`object`||!r)return{ok:!1,error:`主数据 bind 非对象,无法就地还原(集成方应用对象包裹)`};if(t?.validate!==!1){let t=n.schema.safeParse(e);if(!t.success)return{ok:!1,error:`schema 校验失败:`+(t.error?.message??`未知错误`)}}return V0(r,e),i.dataOpsController?.markDataDirty?.(),t?.emit!==!1&&i.emit({type:`data_change`,operation:`set`,value:r}),{ok:!0}},createResource:(e,t)=>{let n=i.dataOpsController;if(!n?.createResource)throw Error(`[page-agent-sdk] createResource 不可用:需配 data.resources + vfsStore(capabilities.vfs 默认开)`);return n.createResource(e,t)},getResource:e=>i.dataOpsController?.getResource?.(e),updateResource:(e,t)=>{let n=i.dataOpsController;if(!n?.updateResource)throw Error(`[page-agent-sdk] updateResource 不可用:需配 data.resources + vfsStore`);n.updateResource(e,t)},deleteResource:e=>i.dataOpsController?.deleteResource?.(e)??!1,listResources:()=>i.dataOpsController?.listResources?.()??[],releaseResources:e=>{let t=i.dataOpsController;if(!(!t?.listResources||!t.deleteResource))if(e&&e.length)for(let n of e)t.deleteResource(n);else for(let e of t.listResources())t.deleteResource(e.path)},usage:i.usage,pendingConflict:i.pendingConflict,resolveConflict:e=>i.resolveConflict(e),setTools:e=>i.setTools(e),addTool:e=>i.addTool(e),removeTool:e=>i.removeTool(e),setLlm:e=>i.setLlm(e),setMemory:e=>i.setMemory(e),refreshMemory:()=>i.refreshMemory(),setSubagents:e=>i.setSubagents(e),addSubagent:e=>i.addSubagent(e),removeSubagent:e=>i.removeSubagent(e)}}return bm(),e.ApprovalBar=RY,e.CAPABILITIES=M7,e.CONTEXT_PRESETS=F7,e.ChatDialog=G$,e.ChatHeader=DW,e.ChatInput=sX,e.CodePreview=YJ,e.CompressDecisionSchema=s7,e.ConflictBar=YY,e.DEFAULT_SYSTEM_PROMPT=r7,e.DebugDrawer=D$,e.FocusBar=NW,e.HUMAN_CONFIRM_TOOL_NAME=I0,e.MIN_CONTEXT_WINDOW=i1,e.MessageContent=ZJ,e.MessageList=yY,e.MessageRow=fY,e.QueuedBar=DY,e.STOP_WORDS=X5,e.SkillPanel=W$,e.UNSAFE_KEYS=L7,e.actionsToInspectInfo=V9,e.actionsToTools=B9,e.agentError=Z$,e.analyzeContext=t2,e.applyPatchToClone=Y7,e.applyPatchToLive=dfe,e.asAgentError=X$,e.buildDataPrompt=i7,e.buildSystemPrompt=a7,e.chatContextKey=dW,e.commitSetToBind=D9,e.connectMcp=W5,e.constructLlmFromConfig=vI,e.constructOpenLlmSync=_I,e.copyText=uW,e.createAgent=A1,e.createApprovalMiddleware=F0,e.createChatContext=fW,e.createChatSdk=Xfe,e.createCheckpointManager=H0,e.createCheckpointMiddleware=U0,e.createConflictManager=h7,e.createContextInspectorMiddleware=n2,e.createDataOps=k9,e.createHumanConfirmMiddleware=R0,e.createHumanConfirmTool=L0,e.createMemoryBackend=T7,e.createMemoryMiddleware=M0,e.createProxyLlm=ece,e.createSandboxRunner=v0,e.createSdkEvents=P7,e.createSerialRunner=Z9,e.createSessionStore=k7,e.createSkillStore=J9,e.createSubagentMiddleware=J0,e.createSubagentsMiddleware=Y0,e.createUsageHintsMiddleware=W9,e.createVerifyMiddleware=X0,e.createVfs=e9,e.createWebStorageBackend=D7,e.createWriteBackCheck=Z0,e.deepClone=U7,e.defineDataToolset=Vfe,e.defineSkill=b0,e.defineTool=o7,e.deleteByPath=H7,e.deriveTitle=c7,e.describeSchemaNode=H1,e.detectGarbledToolCall=b1,e.diffObjects=Q7,e.domToStructure=M9,e.domTools=P9,e.domToolsStatic=Bfe,e.estimateMessageTokens=Q5,e.estimateRoundTokens=$5,e.estimateTokens=o1,e.extractReasoningDelta=bI,e.extractSchemaHint=s0,e.extractText=U5,e.extractTextDelta=yI,e.extractUsage=xI,e.fetchDocTools=j9,e.fetchTools=zfe,e.filterByToolMode=E9,e.formatConstraints=U1,e.formatZodIssues=K$,e.getByPath=B7,e.getDomTool=N9,e.getEnvSummary=I9,e.getSchemaAtPath=P1,e.getSchemaTopKeys=j1,e.getTraceMetrics=l1,e.hashValue=J7,e.indexSummarize=e7,e.inspectEnvTool=L9,e.inspectTools=R9,e.isChatModel=l7,e.isContextLengthError=d1,e.isPathAllowed=M1,e.isQuotaError=b7,e.isUnsafePath=R7,e.jpEval=l9,e.jsonParseError=J$,e.limitDepth=K7,e.maybeParseValue=W7,e.offloadPassThroughChars=c1,e.offloadThresholdChars=s1,e.presets=n0,e.projectBySchema=I1,e.projectBySchemaDeep=F1,e.projectFields=G7,e.recallRounds=t7,e.renderSchemaHint=W1,e.renderSchemaOverview=G1,e.renderSchemaShallow=q1,e.resolveCapabilities=N7,e.resolveContextOptions=I7,e.resolveDialogConfig=j7,e.resolveLlm=m7,e.resolveModelCaps=a1,e.resolveStorage=A7,e.restoreInPlace=Z7,e.restoreLive=X7,e.routeError=Y$,e.runHostScript=y0,e.runSandboxedScript=f9,e.safeMerge=z7,e.safeSerialize=F9,e.safeStringify=q7,e.searchJson=u9,e.selectBuiltinTools=H9,e.setByPath=V7,e.shouldTriggerCompression=n7,e.systemPromptHelpers=r0,e.tokenize=Z5,e.toolError=$,e.unwrapSchema=N1,e.useChat=lW,e.useChatContext=pW,Object.defineProperty(e,"z",{enumerable:!0,get:function(){return ym}}),e.zodError=q$,e})({});
|