agestra 4.10.2 → 4.10.4
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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/dist/bundle.js +189 -170
- package/package.json +1 -1
package/dist/bundle.js
CHANGED
|
@@ -1,59 +1,63 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as ___cr } from 'module';import { fileURLToPath as ___fu } from 'url';import { dirname as ___dn } from 'path';const __filename = ___fu(import.meta.url);const __dirname = ___dn(__filename);const require = ___cr(import.meta.url);
|
|
3
|
-
var
|
|
4
|
-
`),dn=Object.freeze({auto:Object.freeze({name:"auto",description:"Auto-detect build profile from project structure (package.json scripts, tsconfig, vitest config, etc.).",command:"npx",args:Object.freeze([])}),tsc:Object.freeze({name:"tsc",description:"TypeScript project-references build via `npx tsc -b --noEmit`.",command:"npx",args:Object.freeze(["tsc","-b","--noEmit"])}),vitest:Object.freeze({name:"vitest",description:"Run the Vitest unit-test suite in CI mode.",command:"npx",args:Object.freeze(["vitest","run","--reporter=dot"])}),"npm-build":Object.freeze({name:"npm-build",description:"Run the project's `npm run build` script.",command:"npm",args:Object.freeze(["run","build"])}),"npm-test":Object.freeze({name:"npm-test",description:"Run the project's `npm test` script.",command:"npm",args:Object.freeze(["test","--","--run"])})})});import{execFileSync as CS}from"child_process";function pn(t){if(!Number.isFinite(t)||t<=0)return{delivered:!1};if(process.platform==="win32")try{return CS("taskkill",["/PID",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0}),{delivered:!0}}catch{try{return process.kill(t),{delivered:!0}}catch{return{delivered:!1}}}try{return process.kill(-t,"SIGTERM"),{delivered:!0}}catch{try{return process.kill(t,"SIGTERM"),{delivered:!0}}catch{return{delivered:!1}}}}function er(t,e=3e3){let r=t.pid;if(r)pn(r);else try{t.kill("SIGTERM")}catch{}setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},e)}var ho=an(()=>{"use strict"});import{execFileSync as DS,spawn as zS}from"child_process";import{existsSync as OS}from"fs";function NS(t){return process.platform!=="win32"||t.includes("/")||t.includes("\\")?!1:MS.has(t.toLowerCase())}function jS(t){if(t.includes("\0"))throw new Error(`Windows shim arg contains null byte: ${JSON.stringify(t)}`);if(t.includes("%"))throw new Error(`Windows shim arg contains '%' which would trigger cmd.exe env expansion: ${JSON.stringify(t)}`);return/[\s"&^<>|()!]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function LS(t){let e=t.toLowerCase();if(fn.has(e))return fn.get(e)??null;try{let n=DS("where.exe",[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0}).split(/\r?\n/).map(a=>a.trim()).filter(Boolean);if(n.length===0)return fn.set(e,null),null;let o=n.find(a=>/\.(cmd|bat)$/i.test(a));if(o){let a={type:"cmd",path:o};return fn.set(e,a),a}let i=`${n[0]}.ps1`;if(OS(i)){let a={type:"powershell",path:i};return fn.set(e,a),a}}catch{}return fn.set(e,null),null}function Lt(t,e){if(!NS(t))return{command:t,args:e};let r=LS(t);return r?r.type==="cmd"?{command:"cmd.exe",args:["/d","/s","/c",r.path,...e.map(n=>jS(n))]}:{command:"powershell.exe",args:["-NoProfile","-ExecutionPolicy","RemoteSigned","-File",r.path,...e]}:{command:t,args:e}}function ze(t){let{command:e,args:r,timeout:n=12e4,cwd:o,env:s,stdin:i,maxBuffer:a=10485760,onStderrChunk:c}=t;return new Promise((u,l)=>{let d=Lt(e,r),p=zS(d.command,d.args,{cwd:o,env:s?{...process.env,...s}:void 0,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),f="",m="",g=0,y=0,_=!1,x=null,v=!1,P=()=>{!v&&g+y>a&&(_=!0,v=!0,er(p))};p.stdout.on("data",Z=>{g+=Z.length,g<=a&&(f+=Z.toString()),P()}),p.stderr.on("data",Z=>{y+=Z.length;let De=Z.toString();if(y<=a&&(m+=De),P(),!v&&c){let Y=c(De);Y&&(x=Y,v=!0,er(p))}}),i&&p.stdin&&(p.stdin.write(i),p.stdin.end());let S=()=>{er(p),l(new Error(`CLI timeout after ${n}ms of inactivity: ${e} ${r.join(" ")}`))},N=setTimeout(S,n),L=()=>{clearTimeout(N),N=setTimeout(S,n)};p.stdout.on("data",L),p.stderr.on("data",L),p.on("close",Z=>{if(clearTimeout(N),x){l(x);return}u({stdout:f,stderr:m,exitCode:Z??1,truncated:_})}),p.on("error",Z=>{clearTimeout(N),l(new Error(`CLI spawn error: ${Z.message}`))})})}var MS,fn,mn=an(()=>{"use strict";ho();MS=new Set(["codex","gemini","npm","npx"]),fn=new Map});import{writeFileSync as ck,mkdirSync as bo,openSync as Fc,writeSync as Zc,fsyncSync as Df,closeSync as Uc,renameSync as uk,unlinkSync as lk,appendFileSync as dk}from"fs";import{dirname as wo,join as pk}from"path";import{randomUUID as fk}from"crypto";function se(t,e){let r=wo(t);bo(r,{recursive:!0});let n=pk(r,`.tmp-${fk().slice(0,8)}`);try{ck(n,e,"utf-8"),uk(n,t)}catch(o){try{lk(n)}catch{}throw o}}function Ue(t,e){se(t,JSON.stringify(e,null,2))}function ni(t,e){let r=wo(t);bo(r,{recursive:!0});let n=Fc(t,"a");try{Zc(n,e),Df(n)}finally{Uc(n)}}var ri,oi=an(()=>{"use strict";ri=class{buffer=new Map;flushTimer=null;flushIntervalMs;maxBufferSize;auditFsync;destroyed=!1;constructor(e){this.flushIntervalMs=e?.flushIntervalMs??2e3,this.maxBufferSize=e?.maxBufferSize??100,this.auditFsync=e?.auditFsync??!0,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>this.flush(),this.flushIntervalMs),this.flushTimer&&typeof this.flushTimer.unref=="function"&&this.flushTimer.unref())}append(e,r,n){if(this.destroyed)throw new Error("DurableAppendWriter has been destroyed");if(n==="audit"){if(this.auditFsync)ni(e,r);else{let s=wo(e);bo(s,{recursive:!0}),dk(e,r)}return}let o=this.buffer.get(e);o||(o=[],this.buffer.set(e,o)),o.push(r),o.length>=this.maxBufferSize&&this.flushFile(e),this.flushIntervalMs===0&&this.flushFile(e)}flush(){for(let e of this.buffer.keys())this.flushFile(e)}panicFlush(){for(let[e,r]of this.buffer)if(r.length!==0)try{let n=wo(e);bo(n,{recursive:!0});let o=Fc(e,"a");try{Zc(o,r.join("")),Df(o)}finally{Uc(o)}}catch{}this.buffer.clear()}destroy(){this.destroyed||(this.destroyed=!0,this.flushTimer!==null&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush())}flushFile(e){let r=this.buffer.get(e);if(!r||r.length===0)return;let n=wo(e);bo(n,{recursive:!0});let o=Fc(e,"a");try{Zc(o,r.join(""))}finally{Uc(o)}this.buffer.delete(e)}}});import{existsSync as zf,realpathSync as mk}from"fs";import{basename as hk,dirname as gk,isAbsolute as Nf,join as yk,normalize as vk,resolve as qc,relative as _k}from"path";function bk(t){return t===""||!t.startsWith("..")&&!Nf(t)}function Of(t){let e=[],r=qc(t);for(;!zf(r);){let o=gk(r);if(o===r)break;e.unshift(hk(r)),r=o}let n=zf(r)?mk(r):r;return e.reduce((o,s)=>yk(o,s),n)}function jf(t,e){let r=Of(e),n=Of(t),o=_k(r,n);return bk(o)}function Vc(t,e){let r=qc(e,t);return jf(r,e)}function ht(t,e){let r=qc(e,t);if(!jf(r,e))throw new Error(`Path traversal blocked: ${t} escapes ${e}`);return r}function Me(t,e){if(t.length===0)throw new Error("Filename must not be empty");if(t.includes("\0"))throw new Error(`Filename contains null byte: ${JSON.stringify(t)}`);if(t.includes("/")||t.includes("\\"))throw new Error(`Filename must not contain path separators: ${JSON.stringify(t)}`);if(t.includes(".."))throw new Error(`Filename must not contain '..': ${JSON.stringify(t)}`);return ht(t,e)}function Bt(t,e){if(Nf(t)){let r=vk(t);if(!Vc(r,e))throw new Error(`Read path outside base directory: ${t} is not within ${e}`);return r}return ht(t,e)}function si(t){return wk.test(t)}function ii(t,e){if(!t||typeof t!="string")throw new tt(String(t),"command must be a non-empty string");if(t.includes("\0"))throw new tt(t,"command contains null byte");if(t.includes("/")||t.includes("\\"))throw new tt(t,"command must not contain path separators");if(!Mf.has(t))throw new tt(t,`command is not in the allowlist (${[...Mf].join(", ")})`);for(let r of e){if(typeof r!="string")throw new tt(t,`args contain a non-string entry: ${JSON.stringify(r)}`);if(r.includes("\0"))throw new tt(t,`arg contains null byte: ${JSON.stringify(r)}`);if(xk.has(r))throw new tt(t,`arg ${JSON.stringify(r)} is a code-execution flag and is not permitted`)}}var wk,Mf,xk,tt,xo=an(()=>{"use strict";wk=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;Mf=new Set(["gemini","codex","npx","node","npm","tsc"]),xk=new Set(["-e","--eval","-c","--command","-E","--execute","--exec"]),tt=class extends Error{command;reason;constructor(e,r){super(`CLI command rejected: ${e} \u2014 ${r}`),this.command=e,this.reason=r,this.name="CliCommandRejectedError"}}});var Zf={};Ze(Zf,{CLI_PROVIDERS:()=>Lf,resolveCliConfig:()=>Ff});import{readFileSync as Bc}from"fs";import{join as rt}from"path";import{spawn as Sk}from"child_process";function Ff(t){let e=$k[t.provider]??t.provider;return Lf[e]??null}function Fr(t,e){let r=rt(t,"status.json"),n=JSON.parse(Bc(r,"utf-8"));Ue(r,{...n,...e})}async function kk(){let t=process.argv[2];t||process.exit(1);let e;try{e=JSON.parse(Bc(rt(t,"job.json"),"utf-8"))}catch{try{Ue(rt(t,"status.json"),{id:"unknown",state:"error",provider:"unknown",completedAt:new Date().toISOString()}),se(rt(t,"error.txt"),"Failed to read job.json")}catch{}process.exit(1)}let r=Ff(e);r||(Fr(t,{state:"missing_cli",completedAt:new Date().toISOString()}),se(rt(t,"error.txt"),`No CLI mapping for provider: ${e.provider}`),process.exit(1));let{command:n,buildArgs:o}=r;Fr(t,{state:"running",startedAt:new Date().toISOString()});let s=Bc(rt(t,"prompt.txt"),"utf-8"),i=o(s);try{ii(n,i)}catch(c){let u=c instanceof tt?c.message:`Argv rejected: ${c.message}`;Fr(t,{state:"error",completedAt:new Date().toISOString()}),se(rt(t,"error.txt"),u);return}let a;if(e.cwd)try{a=ht(e.cwd,process.cwd())}catch(c){Fr(t,{state:"error",completedAt:new Date().toISOString()}),se(rt(t,"error.txt"),`Rejected descriptor.cwd: ${c.message}`);return}return new Promise(c=>{let u=Lt(n,i),l=Sk(u.command,u.args,{cwd:a,stdio:["ignore","pipe","pipe"],windowsHide:!0}),d="",p="",f=0,m=0;l.stdout.on("data",y=>{f+=y.length,f<=10485760&&(d+=y.toString())}),l.stderr.on("data",y=>{m+=y.length,m<=10485760&&(p+=y.toString())});let g=setTimeout(()=>{er(l),se(rt(t,"output.txt"),d),se(rt(t,"error.txt"),p),Fr(t,{state:"timed_out",completedAt:new Date().toISOString()}),c()},e.timeout);l.on("close",y=>{clearTimeout(g),se(rt(t,"output.txt"),d),se(rt(t,"error.txt"),p);let _=d.trim().length>0;Fr(t,{state:y===0||_?"completed":"error",exitCode:y??1,completedAt:new Date().toISOString()}),c()}),l.on("error",y=>{clearTimeout(g);let _=y.code==="ENOENT"?"missing_cli":"error";se(rt(t,"error.txt"),y.message),Fr(t,{state:_,completedAt:new Date().toISOString()}),c()})})}var $k,Lf,Pk,Uf=an(()=>{"use strict";oi();ho();xo();mn();$k={"gemini-cli":"gemini","codex-cli":"codex"},Lf={gemini:{command:"gemini",buildArgs:t=>["-p",t]},codex:{command:"codex",buildArgs:t=>["exec","--skip-git-repo-check","--full-auto","--ephemeral",t]}};Pk=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");Pk&&kk().catch(()=>process.exit(1))});var cs=E(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.regexpCode=ne.getEsmExportName=ne.getProperty=ne.safeStringify=ne.stringify=ne.strConcat=ne.addCodeArg=ne.str=ne._=ne.nil=ne._Code=ne.Name=ne.IDENTIFIER=ne._CodeOrName=void 0;var is=class{};ne._CodeOrName=is;ne.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Jr=class extends is{constructor(e){if(super(),!ne.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};ne.Name=Jr;var lt=class extends is{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Jr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ne._Code=lt;ne.nil=new lt("");function Uv(t,...e){let r=[t[0]],n=0;for(;n<e.length;)$l(r,e[n]),r.push(t[++n]);return new lt(r)}ne._=Uv;var Sl=new lt("+");function qv(t,...e){let r=[as(t[0])],n=0;for(;n<e.length;)r.push(Sl),$l(r,e[n]),r.push(Sl,as(t[++n]));return SR(r),new lt(r)}ne.str=qv;function $l(t,e){e instanceof lt?t.push(...e._items):e instanceof Jr?t.push(e):t.push(PR(e))}ne.addCodeArg=$l;function SR(t){let e=1;for(;e<t.length-1;){if(t[e]===Sl){let r=$R(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function $R(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Jr||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Jr))return`"${t}${e.slice(1)}`}function kR(t,e){return e.emptyStr()?t:t.emptyStr()?e:qv`${t}${e}`}ne.strConcat=kR;function PR(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:as(Array.isArray(t)?t.join(","):t)}function TR(t){return new lt(as(t))}ne.stringify=TR;function as(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ne.safeStringify=as;function ER(t){return typeof t=="string"&&ne.IDENTIFIER.test(t)?new lt(`.${t}`):Uv`[${t}]`}ne.getProperty=ER;function RR(t){if(typeof t=="string"&&ne.IDENTIFIER.test(t))return new lt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}ne.getEsmExportName=RR;function IR(t){return new lt(t.toString())}ne.regexpCode=IR});var Tl=E(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Ye=cs(),kl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},pa;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(pa||(Qe.UsedValueState=pa={}));Qe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var fa=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Qe.Scope=fa;var ma=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Qe.ValueScopeName=ma;var AR=(0,Ye._)`\n`,Pl=class extends fa{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?AR:Ye.nil}}get(){return this._scope}name(e){return new ma(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ye._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ye.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,pa.Started);let l=r(u);if(l){let d=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Ye._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Ye._)`${s}${l}${this.opts._n}`;else throw new kl(u);c.set(u,pa.Completed)})}return s}};Qe.ValueScope=Pl});var H=E(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.or=K.and=K.not=K.CodeGen=K.operators=K.varKinds=K.ValueScopeName=K.ValueScope=K.Scope=K.Name=K.regexpCode=K.stringify=K.getProperty=K.nil=K.strConcat=K.str=K._=void 0;var te=cs(),_t=Tl(),fr=cs();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return fr._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return fr.str}});Object.defineProperty(K,"strConcat",{enumerable:!0,get:function(){return fr.strConcat}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return fr.nil}});Object.defineProperty(K,"getProperty",{enumerable:!0,get:function(){return fr.getProperty}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return fr.stringify}});Object.defineProperty(K,"regexpCode",{enumerable:!0,get:function(){return fr.regexpCode}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return fr.Name}});var va=Tl();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return va.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return va.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return va.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return va.varKinds}});K.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var Kt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},El=class extends Kt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?_t.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Un(this.rhs,e,r)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},ha=class extends Kt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Un(this.rhs,e,r),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return ya(e,this.rhs)}},Rl=class extends ha{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Il=class extends Kt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Al=class extends Kt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Cl=class extends Kt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Dl=class extends Kt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Un(this.code,e,r),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},us=class extends Kt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(CR(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Xr(e,r.names),{})}},Gt=class extends us{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},zl=class extends us{},Zn=class extends Gt{};Zn.kind="else";var Yr=class t extends Gt{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Zn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Vv(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Un(this.condition,e,r),this}get names(){let e=super.names;return ya(e,this.condition),this.else&&Xr(e,this.else.names),e}};Yr.kind="if";var Qr=class extends Gt{};Qr.kind="for";var Ol=class extends Qr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Un(this.iteration,e,r),this}get names(){return Xr(super.names,this.iteration.names)}},Ml=class extends Qr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?_t.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=ya(super.names,this.from);return ya(e,this.to)}},ga=class extends Qr{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Un(this.iterable,e,r),this}get names(){return Xr(super.names,this.iterable.names)}},ls=class extends Gt{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ls.kind="func";var ds=class extends us{render(e){return"return "+super.render(e)}};ds.kind="return";var Nl=class extends Gt{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Xr(e,this.catch.names),this.finally&&Xr(e,this.finally.names),e}},ps=class extends Gt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ps.kind="catch";var fs=class extends Gt{render(e){return"finally"+super.render(e)}};fs.kind="finally";var jl=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
5
|
-
`:""},this._extScope=e,this._scope=new _t.Scope({parent:e}),this._nodes=[new zl]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new El(e,s,n)),s}const(e,r,n){return this._def(_t.varKinds.const,e,r,n)}let(e,r,n){return this._def(_t.varKinds.let,e,r,n)}var(e,r,n){return this._def(_t.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new ha(e,r,n))}add(e,r){return this._leafNode(new Rl(e,K.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new Dl(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,te.addCodeArg)(r,o));return r.push("}"),new te._Code(r)}if(e,r,n){if(this._blockNode(new Yr(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Yr(e))}else(){return this._elseNode(new Zn)}endIf(){return this._endBlockNode(Yr,Zn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Ol(e),r)}forRange(e,r,n,o,s=this.opts.es5?_t.varKinds.var:_t.varKinds.let){let i=this._scope.toName(e);return this._for(new Ml(s,i,r,n),()=>o(i))}forOf(e,r,n,o=_t.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof te.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,te._)`${i}.length`,a=>{this.var(s,(0,te._)`${i}[${a}]`),n(s)})}return this._for(new ga("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?_t.varKinds.var:_t.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,te._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new ga("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Qr)}label(e){return this._leafNode(new Il(e))}break(e){return this._leafNode(new Al(e))}return(e){let r=new ds;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ds)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Nl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new ps(s),r(s)}return n&&(this._currNode=o.finally=new fs,this.code(n)),this._endBlockNode(ps,fs)}throw(e){return this._leafNode(new Cl(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=te.nil,n,o){return this._blockNode(new ls(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ls)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Yr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};K.CodeGen=jl;function Xr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ya(t,e){return e instanceof te._CodeOrName?Xr(t,e.names):t}function Un(t,e,r){if(t instanceof te.Name)return n(t);if(!o(t))return t;return new te._Code(t._items.reduce((s,i)=>(i instanceof te.Name&&(i=n(i)),i instanceof te._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof te._Code&&s._items.some(i=>i instanceof te.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function CR(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Vv(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,te._)`!${Ll(t)}`}K.not=Vv;var DR=Bv(K.operators.AND);function zR(...t){return t.reduce(DR)}K.and=zR;var OR=Bv(K.operators.OR);function MR(...t){return t.reduce(OR)}K.or=MR;function Bv(t){return(e,r)=>e===te.nil?r:r===te.nil?e:(0,te._)`${Ll(e)} ${t} ${Ll(r)}`}function Ll(t){return t instanceof te.Name?t:(0,te._)`(${t})`}});var oe=E(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.checkStrictMode=G.getErrorPath=G.Type=G.useFunc=G.setEvaluated=G.evaluatedPropsToName=G.mergeEvaluated=G.eachItem=G.unescapeJsonPointer=G.escapeJsonPointer=G.escapeFragment=G.unescapeFragment=G.schemaRefOrVal=G.schemaHasRulesButRef=G.schemaHasRules=G.checkUnknownRules=G.alwaysValidSchema=G.toHash=void 0;var le=H(),NR=cs();function jR(t){let e={};for(let r of t)e[r]=!0;return e}G.toHash=jR;function LR(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Kv(t,e),!Gv(e,t.self.RULES.all))}G.alwaysValidSchema=LR;function Kv(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Qv(t,`unknown keyword: "${s}"`)}G.checkUnknownRules=Kv;function Gv(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}G.schemaHasRules=Gv;function FR(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}G.schemaHasRulesButRef=FR;function ZR({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,le._)`${r}`}return(0,le._)`${t}${e}${(0,le.getProperty)(n)}`}G.schemaRefOrVal=ZR;function UR(t){return Jv(decodeURIComponent(t))}G.unescapeFragment=UR;function qR(t){return encodeURIComponent(Zl(t))}G.escapeFragment=qR;function Zl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}G.escapeJsonPointer=Zl;function Jv(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}G.unescapeJsonPointer=Jv;function VR(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}G.eachItem=VR;function Wv({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof le.Name?(s instanceof le.Name?t(o,s,i):e(o,s,i),i):s instanceof le.Name?(e(o,i,s),s):r(s,i);return a===le.Name&&!(c instanceof le.Name)?n(o,c):c}}G.mergeEvaluated={props:Wv({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,le._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,le._)`${r} || {}`).code((0,le._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,le._)`${r} || {}`),Ul(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Yv}),items:Wv({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,le._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,le._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Yv(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,le._)`{}`);return e!==void 0&&Ul(t,r,e),r}G.evaluatedPropsToName=Yv;function Ul(t,e,r){Object.keys(r).forEach(n=>t.assign((0,le._)`${e}${(0,le.getProperty)(n)}`,!0))}G.setEvaluated=Ul;var Hv={};function BR(t,e){return t.scopeValue("func",{ref:e,code:Hv[e.code]||(Hv[e.code]=new NR._Code(e.code))})}G.useFunc=BR;var Fl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Fl||(G.Type=Fl={}));function WR(t,e,r){if(t instanceof le.Name){let n=e===Fl.Num;return r?n?(0,le._)`"[" + ${t} + "]"`:(0,le._)`"['" + ${t} + "']"`:n?(0,le._)`"/" + ${t}`:(0,le._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,le.getProperty)(t).toString():"/"+Zl(t)}G.getErrorPath=WR;function Qv(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}G.checkStrictMode=Qv});var Jt=E(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var je=H(),HR={data:new je.Name("data"),valCxt:new je.Name("valCxt"),instancePath:new je.Name("instancePath"),parentData:new je.Name("parentData"),parentDataProperty:new je.Name("parentDataProperty"),rootData:new je.Name("rootData"),dynamicAnchors:new je.Name("dynamicAnchors"),vErrors:new je.Name("vErrors"),errors:new je.Name("errors"),this:new je.Name("this"),self:new je.Name("self"),scope:new je.Name("scope"),json:new je.Name("json"),jsonPos:new je.Name("jsonPos"),jsonLen:new je.Name("jsonLen"),jsonPart:new je.Name("jsonPart")};ql.default=HR});var ms=E(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extendErrors=Le.resetErrorsCount=Le.reportExtraError=Le.reportError=Le.keyword$DataError=Le.keywordError=void 0;var re=H(),_a=oe(),Be=Jt();Le.keywordError={message:({keyword:t})=>(0,re.str)`must pass "${t}" keyword validation`};Le.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,re.str)`"${t}" keyword must be ${e} ($data)`:(0,re.str)`"${t}" keyword is invalid ($data)`};function KR(t,e=Le.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=t_(t,e,r);n??(i||a)?Xv(s,c):e_(o,(0,re._)`[${c}]`)}Le.reportError=KR;function GR(t,e=Le.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=t_(t,e,r);Xv(o,a),s||i||e_(n,Be.default.vErrors)}Le.reportExtraError=GR;function JR(t,e){t.assign(Be.default.errors,e),t.if((0,re._)`${Be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,re._)`${Be.default.vErrors}.length`,e),()=>t.assign(Be.default.vErrors,null)))}Le.resetErrorsCount=JR;function YR({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Be.default.errors,a=>{t.const(i,(0,re._)`${Be.default.vErrors}[${a}]`),t.if((0,re._)`${i}.instancePath === undefined`,()=>t.assign((0,re._)`${i}.instancePath`,(0,re.strConcat)(Be.default.instancePath,s.errorPath))),t.assign((0,re._)`${i}.schemaPath`,(0,re.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,re._)`${i}.schema`,r),t.assign((0,re._)`${i}.data`,n))})}Le.extendErrors=YR;function Xv(t,e){let r=t.const("err",e);t.if((0,re._)`${Be.default.vErrors} === null`,()=>t.assign(Be.default.vErrors,(0,re._)`[${r}]`),(0,re._)`${Be.default.vErrors}.push(${r})`),t.code((0,re._)`${Be.default.errors}++`)}function e_(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,re._)`new ${t.ValidationError}(${e})`):(r.assign((0,re._)`${n}.errors`,e),r.return(!1))}var en={keyword:new re.Name("keyword"),schemaPath:new re.Name("schemaPath"),params:new re.Name("params"),propertyName:new re.Name("propertyName"),message:new re.Name("message"),schema:new re.Name("schema"),parentSchema:new re.Name("parentSchema")};function t_(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,re._)`{}`:QR(t,e,r)}function QR(t,e,r={}){let{gen:n,it:o}=t,s=[XR(o,r),eI(t,r)];return tI(t,e,s),n.object(...s)}function XR({errorPath:t},{instancePath:e}){let r=e?(0,re.str)`${t}${(0,_a.getErrorPath)(e,_a.Type.Str)}`:t;return[Be.default.instancePath,(0,re.strConcat)(Be.default.instancePath,r)]}function eI({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,re.str)`${e}/${t}`;return r&&(o=(0,re.str)`${o}${(0,_a.getErrorPath)(r,_a.Type.Str)}`),[en.schemaPath,o]}function tI(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([en.keyword,o],[en.params,typeof e=="function"?e(t):e||(0,re._)`{}`]),c.messages&&n.push([en.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([en.schema,i],[en.parentSchema,(0,re._)`${l}${d}`],[Be.default.data,s]),u&&n.push([en.propertyName,u])}});var n_=E(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.boolOrEmptySchema=qn.topBoolOrEmptySchema=void 0;var rI=ms(),nI=H(),oI=Jt(),sI={message:"boolean schema is false"};function iI(t){let{gen:e,schema:r,validateName:n}=t;r===!1?r_(t,!1):typeof r=="object"&&r.$async===!0?e.return(oI.default.data):(e.assign((0,nI._)`${n}.errors`,null),e.return(!0))}qn.topBoolOrEmptySchema=iI;function aI(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),r_(t)):r.var(e,!0)}qn.boolOrEmptySchema=aI;function r_(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,rI.reportError)(o,sI,void 0,e)}});var Vl=E(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.getRules=Vn.isJSONType=void 0;var cI=["string","number","integer","boolean","null","object","array"],uI=new Set(cI);function lI(t){return typeof t=="string"&&uI.has(t)}Vn.isJSONType=lI;function dI(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Vn.getRules=dI});var Bl=E(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.shouldUseRule=mr.shouldUseGroup=mr.schemaHasRulesForType=void 0;function pI({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&o_(t,n)}mr.schemaHasRulesForType=pI;function o_(t,e){return e.rules.some(r=>s_(t,r))}mr.shouldUseGroup=o_;function s_(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}mr.shouldUseRule=s_});var hs=E(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.reportTypeError=Fe.checkDataTypes=Fe.checkDataType=Fe.coerceAndCheckDataType=Fe.getJSONTypes=Fe.getSchemaTypes=Fe.DataType=void 0;var fI=Vl(),mI=Bl(),hI=ms(),q=H(),i_=oe(),Bn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Bn||(Fe.DataType=Bn={}));function gI(t){let e=a_(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Fe.getSchemaTypes=gI;function a_(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(fI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Fe.getJSONTypes=a_;function yI(t,e){let{gen:r,data:n,opts:o}=t,s=vI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,mI.schemaHasRulesForType)(t,e[0]));if(i){let a=Hl(e,n,o.strictNumbers,Bn.Wrong);r.if(a,()=>{s.length?_I(t,e,s):Kl(t)})}return i}Fe.coerceAndCheckDataType=yI;var c_=new Set(["string","number","integer","boolean","null"]);function vI(t,e){return e?t.filter(r=>c_.has(r)||e==="array"&&r==="array"):[]}function _I(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,q._)`typeof ${o}`),a=n.let("coerced",(0,q._)`undefined`);s.coerceTypes==="array"&&n.if((0,q._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,q._)`${o}[0]`).assign(i,(0,q._)`typeof ${o}`).if(Hl(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,q._)`${a} !== undefined`);for(let u of r)(c_.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Kl(t),n.endIf(),n.if((0,q._)`${a} !== undefined`,()=>{n.assign(o,a),bI(t,a)});function c(u){switch(u){case"string":n.elseIf((0,q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,q._)`"" + ${o}`).elseIf((0,q._)`${o} === null`).assign(a,(0,q._)`""`);return;case"number":n.elseIf((0,q._)`${i} == "boolean" || ${o} === null
|
|
3
|
+
var FS=Object.create;var Mc=Object.defineProperty;var ZS=Object.getOwnPropertyDescriptor;var US=Object.getOwnPropertyNames;var qS=Object.getPrototypeOf,VS=Object.prototype.hasOwnProperty;var Tr=(t,e)=>()=>(t&&(e=t(t=0)),e);var E=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Be=(t,e)=>{for(var r in e)Mc(t,r,{get:e[r],enumerable:!0})},BS=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of US(e))!VS.call(t,o)&&o!==r&&Mc(t,o,{get:()=>e[o],enumerable:!(n=ZS(e,o))||n.enumerable});return t};var df=(t,e,r)=>(r=t!=null?FS(qS(t)):{},BS(e||!t||!t.__esModule?Mc(r,"default",{value:t,enumerable:!0}):r,t));var pf,_o,ff,mf,hf,gf,yf,bo,vf,Hs,_f,bf,wf,xf,Sf,$f,Ks,Nc,jc,Qj,kf,gn,Lc,Fc,Pf,Tf,Gs,Er,Zc,Ef,Rf,yn,Vt=Tr(()=>{"use strict";pf="4.10.4",_o="http://localhost:11434",ff="llama3",mf=".agestra/.jobs",hf=".agestra/traces",gf=".agestra/worktrees",yf=".agestra/sessions",bo=".agestra/workspace",vf="individual",Hs="debates",_f="synthesis",bf="issue",wf=".agestra/workers",xf=Object.freeze(["PATH","HOME","USER","USERPROFILE","APPDATA","LOCALAPPDATA","TEMP","TMP","TMPDIR","SHELL","LANG","LC_ALL","NODE_PATH","SystemRoot","SystemDrive","COMSPEC","ComSpec","windir"]),Sf=2,$f=6e4,Ks=20,Nc=5e4,jc=10,Qj=Object.freeze([3,5,10]),kf=Object.freeze(["agree","disagree","abstain","revise"]),gn="votes",Lc=2,Fc=2,Pf=1440*60*1e3,Tf=3600*1e3,Gs=Object.freeze(["ko","zh","ja","en"]),Er="ko",Zc="en",Ef="[REDACTED]",Rf=["","--- REQUIRED RESPONSE FORMAT ---","Respond with JSON only, matching exactly this shape:",'{ "agrees": true | false, "feedback": "specific issues or why you agree", "suggestions": "concrete changes if you disagree (optional, may be omitted)" }',"No prose, markdown, or explanation outside the JSON object. The JSON must be the entire response or wrapped in a single ```json code fence.","-------------------------------"].join(`
|
|
4
|
+
`),yn=Object.freeze({auto:Object.freeze({name:"auto",description:"Auto-detect build profile from project structure (package.json scripts, tsconfig, vitest config, etc.).",command:"npx",args:Object.freeze([])}),tsc:Object.freeze({name:"tsc",description:"TypeScript project-references build via `npx tsc -b --noEmit`.",command:"npx",args:Object.freeze(["tsc","-b","--noEmit"])}),vitest:Object.freeze({name:"vitest",description:"Run the Vitest unit-test suite in CI mode.",command:"npx",args:Object.freeze(["vitest","run","--reporter=dot"])}),"npm-build":Object.freeze({name:"npm-build",description:"Run the project's `npm run build` script.",command:"npm",args:Object.freeze(["run","build"])}),"npm-test":Object.freeze({name:"npm-test",description:"Run the project's `npm test` script.",command:"npm",args:Object.freeze(["test","--","--run"])})})});import{execFileSync as WS}from"child_process";function vn(t){if(!Number.isFinite(t)||t<=0)return{delivered:!1};if(process.platform==="win32")try{return WS("taskkill",["/PID",String(t),"/T","/F"],{stdio:"ignore",windowsHide:!0}),{delivered:!0}}catch{try{return process.kill(t),{delivered:!0}}catch{return{delivered:!1}}}try{return process.kill(-t,"SIGTERM"),{delivered:!0}}catch{try{return process.kill(t,"SIGTERM"),{delivered:!0}}catch{return{delivered:!1}}}}function At(t,e=3e3){let r=t.pid;if(r)vn(r);else try{t.kill("SIGTERM")}catch{}setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},e).unref?.()}var wo=Tr(()=>{"use strict"});import{execFileSync as HS,spawn as KS}from"child_process";import{existsSync as GS}from"fs";function YS(t){return process.platform!=="win32"||t.includes("/")||t.includes("\\")?!1:JS.has(t.toLowerCase())}function XS(t){if(t.includes("\0"))throw new Error(`Windows shim arg contains null byte: ${JSON.stringify(t)}`);if(t.includes("%"))throw new Error(`Windows shim arg contains '%' which would trigger cmd.exe env expansion: ${JSON.stringify(t)}`);return/[\s"&^<>|()!]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function QS(t){let e=t.toLowerCase();if(_n.has(e))return _n.get(e)??null;try{let n=HS("where.exe",[t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:5e3}).split(/\r?\n/).map(a=>a.trim()).filter(Boolean);if(n.length===0)return _n.set(e,null),null;let o=n.find(a=>/\.(cmd|bat)$/i.test(a));if(o){let a={type:"cmd",path:o};return _n.set(e,a),a}let i=`${n[0]}.ps1`;if(GS(i)){let a={type:"powershell",path:i};return _n.set(e,a),a}}catch{}return _n.set(e,null),null}function Bt(t,e){if(!YS(t))return{command:t,args:e};let r=QS(t);return r?r.type==="cmd"?{command:"cmd.exe",args:["/d","/s","/c",r.path,...e.map(n=>XS(n))]}:{command:"powershell.exe",args:["-NoProfile","-ExecutionPolicy","RemoteSigned","-File",r.path,...e]}:{command:t,args:e}}function Me(t){let{command:e,args:r,timeout:n=12e4,cwd:o,env:s,stdin:i,maxBuffer:a=10485760,onStderrChunk:c,signal:u}=t;return new Promise((l,d)=>{if(u?.aborted){d(new at(u.reason));return}let p=Bt(e,r),f=KS(p.command,p.args,{cwd:o,env:s?{...process.env,...s}:void 0,stdio:[i?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),m="",g="",y=0,v=0,S=!1,w=null,_=!1,P=null,A=()=>{P&&u&&u.removeEventListener("abort",P)},D=!1,U=()=>{!D&&y+v>a&&(S=!0,D=!0,At(f))},$e=()=>{_||(At(f),_=!0,A(),d(new Error(`CLI timeout after ${n}ms of inactivity: ${e} ${r.join(" ")}`)))},G=setTimeout($e,n);u&&(P=()=>{_||(_=!0,clearTimeout(G),At(f),A(),d(new at(u.reason)))},u.addEventListener("abort",P));let _t=()=>{D||(clearTimeout(G),G=setTimeout($e,n))};if(f.stdout.on("data",Te=>{y+=Te.length,y<=a&&(m+=Te.toString()),U(),_t()}),f.stderr.on("data",Te=>{v+=Te.length;let Pr=Te.toString();if(v<=a&&(g+=Pr),U(),!D&&c){let fn=c(Pr);fn&&(w=fn,D=!0,At(f))}_t()}),i&&f.stdin){f.stdin.on("error",()=>{});try{f.stdin.write(i),f.stdin.end()}catch{}}f.on("close",Te=>{if(clearTimeout(G),!_){if(w){_=!0,A(),d(w);return}_=!0,A(),l({stdout:m,stderr:g,exitCode:Te??1,truncated:S})}}),f.on("error",Te=>{clearTimeout(G),!_&&(_=!0,A(),d(new Error(`CLI spawn error: ${Te.message}`)))})})}var at,JS,_n,bn=Tr(()=>{"use strict";wo();at=class extends Error{constructor(e){let r=e instanceof Error?`: ${e.message}`:typeof e=="string"&&e?`: ${e}`:"";super(`CLI aborted${r}`),this.name="CliAbortedError"}},JS=new Set(["codex","gemini","npm","npx"]),_n=new Map});import{writeFileSync as xk,mkdirSync as Po,openSync as Wc,writeSync as Hc,fsyncSync as Kf,closeSync as Kc,renameSync as Sk,unlinkSync as Hf,appendFileSync as $k,copyFileSync as kk}from"fs";import{dirname as To,join as Pk}from"path";import{randomUUID as Tk}from"crypto";function oe(t,e){let r=To(t);Po(r,{recursive:!0});let n=Pk(r,`.tmp-${Tk().slice(0,8)}`);try{xk(n,e,"utf-8");try{Sk(n,t)}catch(o){if(o.code!=="EXDEV")throw o;kk(n,t),Hf(n)}}catch(o){try{Hf(n)}catch{}throw o}}function je(t,e){oe(t,JSON.stringify(e,null,2))}function ai(t,e){let r=To(t);Po(r,{recursive:!0});let n=Wc(t,"a");try{Hc(n,e),Kf(n)}finally{Kc(n)}}var ii,ci=Tr(()=>{"use strict";ii=class{buffer=new Map;flushTimer=null;flushIntervalMs;maxBufferSize;auditFsync;destroyed=!1;constructor(e){this.flushIntervalMs=e?.flushIntervalMs??2e3,this.maxBufferSize=e?.maxBufferSize??100,this.auditFsync=e?.auditFsync??!0,this.flushIntervalMs>0&&(this.flushTimer=setInterval(()=>this.flush(),this.flushIntervalMs),this.flushTimer&&typeof this.flushTimer.unref=="function"&&this.flushTimer.unref())}append(e,r,n){if(this.destroyed)throw new Error("DurableAppendWriter has been destroyed");if(n==="audit"){if(this.auditFsync)ai(e,r);else{let s=To(e);Po(s,{recursive:!0}),$k(e,r)}return}let o=this.buffer.get(e);o||(o=[],this.buffer.set(e,o)),o.push(r),o.length>=this.maxBufferSize&&this.flushFile(e),this.flushIntervalMs===0&&this.flushFile(e)}flush(){for(let e of this.buffer.keys())this.flushFile(e)}panicFlush(){for(let[e,r]of this.buffer)if(r.length!==0)try{let n=To(e);Po(n,{recursive:!0});let o=Wc(e,"a");try{Hc(o,r.join("")),Kf(o)}finally{Kc(o)}}catch{}this.buffer.clear()}destroy(){this.destroyed||(this.destroyed=!0,this.flushTimer!==null&&(clearInterval(this.flushTimer),this.flushTimer=null),this.flush())}flushFile(e){let r=this.buffer.get(e);if(!r||r.length===0)return;let n=To(e);Po(n,{recursive:!0});let o=Wc(e,"a");try{Hc(o,r.join(""))}finally{Kc(o)}this.buffer.delete(e)}}});import{openSync as Ek,writeSync as Rk,closeSync as Ik,unlinkSync as Gf,statSync as Ak,mkdirSync as Ck}from"fs";import{dirname as Dk}from"path";function Nk(t){if(t<=0)return;let e=new SharedArrayBuffer(4),r=new Int32Array(e);Atomics.wait(r,0,0,t)}function Wr(t,e,r={}){let n=r.staleMs??zk,o=r.acquireTimeoutMs??Ok,s=r.pollMs??Mk;Ck(Dk(t),{recursive:!0});let i=Date.now(),a=null;for(;a===null;)try{a=Ek(t,"wx")}catch(c){if(c.code!=="EEXIST")throw c;let l=!1;try{let p=Ak(t);l=Date.now()-p.mtimeMs>n}catch{continue}if(l){try{Gf(t)}catch{}continue}let d=Date.now()-i;if(d>=o)throw new Gc(t,d);Nk(s)}try{try{Rk(a,`${process.pid}@${Date.now()}
|
|
5
|
+
`)}catch{}return e()}finally{try{Ik(a)}catch{}try{Gf(t)}catch{}}}var zk,Ok,Mk,Gc,Jc=Tr(()=>{"use strict";zk=3e4,Ok=5e3,Mk=10,Gc=class extends Error{constructor(e,r){super(`withFileLock: timed out after ${r}ms waiting for ${e}`),this.name="FileLockTimeoutError"}}});import{existsSync as Jf,realpathSync as jk}from"fs";import{basename as Lk,dirname as Fk,isAbsolute as Xc,join as Zk,normalize as Xf,resolve as Qc,relative as Uk}from"path";function qk(t){return t===""||!t.startsWith("..")&&!Xc(t)}function Yc(t){let e=[],r=Qc(t);for(;!Jf(r);){let o=Fk(r);if(o===r)break;e.unshift(Lk(r)),r=o}let n=Jf(r)?jk(r):r;return e.reduce((o,s)=>Zk(o,s),n)}function Qf(t,e){let r=Yc(e),n=Yc(t),o=Uk(r,n);return qk(o)}function eu(t,e){let r=Qc(e,t);return Qf(r,e)}function dt(t,e){let r=Qc(e,t);if(!Qf(r,e))throw new Error(`Path traversal blocked: ${t} escapes ${e}`);return r}function Le(t,e){if(t.length===0)throw new Error("Filename must not be empty");if(t.includes("\0"))throw new Error(`Filename contains null byte: ${JSON.stringify(t)}`);if(t.includes("/")||t.includes("\\"))throw new Error(`Filename must not contain path separators: ${JSON.stringify(t)}`);if(t.includes(".."))throw new Error(`Filename must not contain '..': ${JSON.stringify(t)}`);return dt(t,e)}function Yt(t,e){if(Xc(t)){let r=Xf(t);if(!eu(r,e))throw new Error(`Read path outside base directory: ${t} is not within ${e}`);return r}return dt(t,e)}function tu(t,e){return Xc(t)?Yc(Xf(t)):dt(t,e)}function dr(t){return Vk.test(t)}function ui(t,e){if(!t||typeof t!="string")throw new ot(String(t),"command must be a non-empty string");if(t.includes("\0"))throw new ot(t,"command contains null byte");if(t.includes("/")||t.includes("\\"))throw new ot(t,"command must not contain path separators");if(!Yf.has(t))throw new ot(t,`command is not in the allowlist (${[...Yf].join(", ")})`);for(let r of e){if(typeof r!="string")throw new ot(t,`args contain a non-string entry: ${JSON.stringify(r)}`);if(r.includes("\0"))throw new ot(t,`arg contains null byte: ${JSON.stringify(r)}`);if(Bk.has(r))throw new ot(t,`arg ${JSON.stringify(r)} is a code-execution flag and is not permitted`)}}var Vk,Yf,Bk,ot,Eo=Tr(()=>{"use strict";Vk=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;Yf=new Set(["gemini","codex","claude","npx","node","npm","tsc"]),Bk=new Set(["-e","--eval","-c","--command","-E","--execute","--exec"]),ot=class extends Error{command;reason;constructor(e,r){super(`CLI command rejected: ${e} \u2014 ${r}`),this.command=e,this.reason=r,this.name="CliCommandRejectedError"}}});var rm={};Be(rm,{CLI_PROVIDERS:()=>em,resolveCliConfig:()=>tm});import{readFileSync as ru}from"fs";import{join as st}from"path";import{spawn as Wk}from"child_process";function tm(t){let e=Hk[t.provider]??t.provider;return em[e]??null}function Hr(t,e){let r=st(t,"status.json"),n=`${r}.lock`;Wr(n,()=>{let o=JSON.parse(ru(r,"utf-8"));je(r,{...o,...e})})}async function Kk(){let t=process.argv[2];t||process.exit(1);let e;try{e=JSON.parse(ru(st(t,"job.json"),"utf-8"))}catch{try{je(st(t,"status.json"),{id:"unknown",state:"error",provider:"unknown",completedAt:new Date().toISOString()}),oe(st(t,"error.txt"),"Failed to read job.json")}catch{}process.exit(1)}let r=tm(e);r||(Hr(t,{state:"missing_cli",completedAt:new Date().toISOString()}),oe(st(t,"error.txt"),`No CLI mapping for provider: ${e.provider}`),process.exit(1));let{command:n,buildArgs:o}=r;Hr(t,{state:"running",startedAt:new Date().toISOString()});let s=ru(st(t,"prompt.txt"),"utf-8"),i=o(s);try{ui(n,i)}catch(c){let u=c instanceof ot?c.message:`Argv rejected: ${c.message}`;Hr(t,{state:"error",completedAt:new Date().toISOString()}),oe(st(t,"error.txt"),u);return}let a;if(e.cwd)try{a=dt(e.cwd,process.cwd())}catch(c){Hr(t,{state:"error",completedAt:new Date().toISOString()}),oe(st(t,"error.txt"),`Rejected descriptor.cwd: ${c.message}`);return}return new Promise(c=>{let u=Bt(n,i),l=Wk(u.command,u.args,{cwd:a,stdio:["ignore","pipe","pipe"],windowsHide:!0}),d="",p="",f=0,m=0;l.stdout.on("data",y=>{f+=y.length,f<=10485760&&(d+=y.toString())}),l.stderr.on("data",y=>{m+=y.length,m<=10485760&&(p+=y.toString())});let g=setTimeout(()=>{At(l),oe(st(t,"output.txt"),d),oe(st(t,"error.txt"),p),Hr(t,{state:"timed_out",completedAt:new Date().toISOString()}),c()},e.timeout);l.on("close",y=>{clearTimeout(g),oe(st(t,"output.txt"),d),oe(st(t,"error.txt"),p);let v=d.trim().length>0;Hr(t,{state:y===0||v?"completed":"error",exitCode:y??1,completedAt:new Date().toISOString()}),c()}),l.on("error",y=>{clearTimeout(g);let v=y.code==="ENOENT"?"missing_cli":"error";oe(st(t,"error.txt"),y.message),Hr(t,{state:v,completedAt:new Date().toISOString()}),c()})})}var Hk,em,Gk,nm=Tr(()=>{"use strict";ci();Jc();wo();Eo();bn();Hk={"gemini-cli":"gemini","codex-cli":"codex","claude-cli":"claude"},em={gemini:{command:"gemini",buildArgs:t=>["-p",t]},codex:{command:"codex",buildArgs:t=>["exec","--skip-git-repo-check","--full-auto","--ephemeral",t]},claude:{command:"claude",buildArgs:t=>["-p",t]}};Gk=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");Gk&&Kk().catch(()=>process.exit(1))});var hs=E(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.regexpCode=se.getEsmExportName=se.getProperty=se.safeStringify=se.stringify=se.strConcat=se.addCodeArg=se.str=se._=se.nil=se._Code=se.Name=se.IDENTIFIER=se._CodeOrName=void 0;var fs=class{};se._CodeOrName=fs;se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var rn=class extends fs{constructor(e){if(super(),!se.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};se.Name=rn;var ht=class extends fs{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof rn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};se._Code=ht;se.nil=new ht("");function n_(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Nl(r,e[n]),r.push(t[++n]);return new ht(r)}se._=n_;var Ml=new ht("+");function o_(t,...e){let r=[ms(t[0])],n=0;for(;n<e.length;)r.push(Ml),Nl(r,e[n]),r.push(Ml,ms(t[++n]));return HR(r),new ht(r)}se.str=o_;function Nl(t,e){e instanceof ht?t.push(...e._items):e instanceof rn?t.push(e):t.push(JR(e))}se.addCodeArg=Nl;function HR(t){let e=1;for(;e<t.length-1;){if(t[e]===Ml){let r=KR(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function KR(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof rn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof rn))return`"${t}${e.slice(1)}`}function GR(t,e){return e.emptyStr()?t:t.emptyStr()?e:o_`${t}${e}`}se.strConcat=GR;function JR(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ms(Array.isArray(t)?t.join(","):t)}function YR(t){return new ht(ms(t))}se.stringify=YR;function ms(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}se.safeStringify=ms;function XR(t){return typeof t=="string"&&se.IDENTIFIER.test(t)?new ht(`.${t}`):n_`[${t}]`}se.getProperty=XR;function QR(t){if(typeof t=="string"&&se.IDENTIFIER.test(t))return new ht(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}se.getEsmExportName=QR;function eI(t){return new ht(t.toString())}se.regexpCode=eI});var Fl=E(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.ValueScope=tt.ValueScopeName=tt.Scope=tt.varKinds=tt.UsedValueState=void 0;var et=hs(),jl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ha;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ha||(tt.UsedValueState=ha={}));tt.varKinds={const:new et.Name("const"),let:new et.Name("let"),var:new et.Name("var")};var ga=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof et.Name?e:this.name(e)}name(e){return new et.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};tt.Scope=ga;var ya=class extends et.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,et._)`.${new et.Name(r)}[${n}]`}};tt.ValueScopeName=ya;var tI=(0,et._)`\n`,Ll=class extends ga{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?tI:et.nil}}get(){return this._scope}name(e){return new ya(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,et._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=et.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,ha.Started);let l=r(u);if(l){let d=this.opts.es5?tt.varKinds.var:tt.varKinds.const;s=(0,et._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,et._)`${s}${l}${this.opts._n}`;else throw new jl(u);c.set(u,ha.Completed)})}return s}};tt.ValueScope=Ll});var H=E(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.or=K.and=K.not=K.CodeGen=K.operators=K.varKinds=K.ValueScopeName=K.ValueScope=K.Scope=K.Name=K.regexpCode=K.stringify=K.getProperty=K.nil=K.strConcat=K.str=K._=void 0;var re=hs(),$t=Fl(),vr=hs();Object.defineProperty(K,"_",{enumerable:!0,get:function(){return vr._}});Object.defineProperty(K,"str",{enumerable:!0,get:function(){return vr.str}});Object.defineProperty(K,"strConcat",{enumerable:!0,get:function(){return vr.strConcat}});Object.defineProperty(K,"nil",{enumerable:!0,get:function(){return vr.nil}});Object.defineProperty(K,"getProperty",{enumerable:!0,get:function(){return vr.getProperty}});Object.defineProperty(K,"stringify",{enumerable:!0,get:function(){return vr.stringify}});Object.defineProperty(K,"regexpCode",{enumerable:!0,get:function(){return vr.regexpCode}});Object.defineProperty(K,"Name",{enumerable:!0,get:function(){return vr.Name}});var wa=Fl();Object.defineProperty(K,"Scope",{enumerable:!0,get:function(){return wa.Scope}});Object.defineProperty(K,"ValueScope",{enumerable:!0,get:function(){return wa.ValueScope}});Object.defineProperty(K,"ValueScopeName",{enumerable:!0,get:function(){return wa.ValueScopeName}});Object.defineProperty(K,"varKinds",{enumerable:!0,get:function(){return wa.varKinds}});K.operators={GT:new re._Code(">"),GTE:new re._Code(">="),LT:new re._Code("<"),LTE:new re._Code("<="),EQ:new re._Code("==="),NEQ:new re._Code("!=="),NOT:new re._Code("!"),OR:new re._Code("||"),AND:new re._Code("&&"),ADD:new re._Code("+")};var er=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Zl=class extends er{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?$t.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Hn(this.rhs,e,r)),this}get names(){return this.rhs instanceof re._CodeOrName?this.rhs.names:{}}},va=class extends er{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof re.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Hn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof re.Name?{}:{...this.lhs.names};return ba(e,this.rhs)}},Ul=class extends va{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},ql=class extends er{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Vl=class extends er{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Bl=class extends er{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Wl=class extends er{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Hn(this.code,e,r),this}get names(){return this.code instanceof re._CodeOrName?this.code.names:{}}},gs=class extends er{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(rI(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>sn(e,r.names),{})}},tr=class extends gs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Hl=class extends gs{},Wn=class extends tr{};Wn.kind="else";var nn=class t extends tr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Wn(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(s_(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Hn(this.condition,e,r),this}get names(){let e=super.names;return ba(e,this.condition),this.else&&sn(e,this.else.names),e}};nn.kind="if";var on=class extends tr{};on.kind="for";var Kl=class extends on{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Hn(this.iteration,e,r),this}get names(){return sn(super.names,this.iteration.names)}},Gl=class extends on{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?$t.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=ba(super.names,this.from);return ba(e,this.to)}},_a=class extends on{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Hn(this.iterable,e,r),this}get names(){return sn(super.names,this.iterable.names)}},ys=class extends tr{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ys.kind="func";var vs=class extends gs{render(e){return"return "+super.render(e)}};vs.kind="return";var Jl=class extends tr{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&sn(e,this.catch.names),this.finally&&sn(e,this.finally.names),e}},_s=class extends tr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};_s.kind="catch";var bs=class extends tr{render(e){return"finally"+super.render(e)}};bs.kind="finally";var Yl=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
6
|
+
`:""},this._extScope=e,this._scope=new $t.Scope({parent:e}),this._nodes=[new Hl]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Zl(e,s,n)),s}const(e,r,n){return this._def($t.varKinds.const,e,r,n)}let(e,r,n){return this._def($t.varKinds.let,e,r,n)}var(e,r,n){return this._def($t.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new va(e,r,n))}add(e,r){return this._leafNode(new Ul(e,K.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==re.nil&&this._leafNode(new Wl(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,re.addCodeArg)(r,o));return r.push("}"),new re._Code(r)}if(e,r,n){if(this._blockNode(new nn(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new nn(e))}else(){return this._elseNode(new Wn)}endIf(){return this._endBlockNode(nn,Wn)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Kl(e),r)}forRange(e,r,n,o,s=this.opts.es5?$t.varKinds.var:$t.varKinds.let){let i=this._scope.toName(e);return this._for(new Gl(s,i,r,n),()=>o(i))}forOf(e,r,n,o=$t.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof re.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,re._)`${i}.length`,a=>{this.var(s,(0,re._)`${i}[${a}]`),n(s)})}return this._for(new _a("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?$t.varKinds.var:$t.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,re._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new _a("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(on)}label(e){return this._leafNode(new ql(e))}break(e){return this._leafNode(new Vl(e))}return(e){let r=new vs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(vs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Jl;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new _s(s),r(s)}return n&&(this._currNode=o.finally=new bs,this.code(n)),this._endBlockNode(_s,bs)}throw(e){return this._leafNode(new Bl(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=re.nil,n,o){return this._blockNode(new ys(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ys)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof nn))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};K.CodeGen=Yl;function sn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ba(t,e){return e instanceof re._CodeOrName?sn(t,e.names):t}function Hn(t,e,r){if(t instanceof re.Name)return n(t);if(!o(t))return t;return new re._Code(t._items.reduce((s,i)=>(i instanceof re.Name&&(i=n(i)),i instanceof re._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof re._Code&&s._items.some(i=>i instanceof re.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function rI(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function s_(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,re._)`!${Xl(t)}`}K.not=s_;var nI=i_(K.operators.AND);function oI(...t){return t.reduce(nI)}K.and=oI;var sI=i_(K.operators.OR);function iI(...t){return t.reduce(sI)}K.or=iI;function i_(t){return(e,r)=>e===re.nil?r:r===re.nil?e:(0,re._)`${Xl(e)} ${t} ${Xl(r)}`}function Xl(t){return t instanceof re.Name?t:(0,re._)`(${t})`}});var ie=E(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.checkStrictMode=J.getErrorPath=J.Type=J.useFunc=J.setEvaluated=J.evaluatedPropsToName=J.mergeEvaluated=J.eachItem=J.unescapeJsonPointer=J.escapeJsonPointer=J.escapeFragment=J.unescapeFragment=J.schemaRefOrVal=J.schemaHasRulesButRef=J.schemaHasRules=J.checkUnknownRules=J.alwaysValidSchema=J.toHash=void 0;var le=H(),aI=hs();function cI(t){let e={};for(let r of t)e[r]=!0;return e}J.toHash=cI;function uI(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(u_(t,e),!l_(e,t.self.RULES.all))}J.alwaysValidSchema=uI;function u_(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||f_(t,`unknown keyword: "${s}"`)}J.checkUnknownRules=u_;function l_(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}J.schemaHasRules=l_;function lI(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}J.schemaHasRulesButRef=lI;function dI({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,le._)`${r}`}return(0,le._)`${t}${e}${(0,le.getProperty)(n)}`}J.schemaRefOrVal=dI;function pI(t){return d_(decodeURIComponent(t))}J.unescapeFragment=pI;function fI(t){return encodeURIComponent(ed(t))}J.escapeFragment=fI;function ed(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}J.escapeJsonPointer=ed;function d_(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}J.unescapeJsonPointer=d_;function mI(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}J.eachItem=mI;function a_({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof le.Name?(s instanceof le.Name?t(o,s,i):e(o,s,i),i):s instanceof le.Name?(e(o,i,s),s):r(s,i);return a===le.Name&&!(c instanceof le.Name)?n(o,c):c}}J.mergeEvaluated={props:a_({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,le._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,le._)`${r} || {}`).code((0,le._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,le._)`${r} || {}`),td(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:p_}),items:a_({mergeNames:(t,e,r)=>t.if((0,le._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,le._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,le._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,le._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function p_(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,le._)`{}`);return e!==void 0&&td(t,r,e),r}J.evaluatedPropsToName=p_;function td(t,e,r){Object.keys(r).forEach(n=>t.assign((0,le._)`${e}${(0,le.getProperty)(n)}`,!0))}J.setEvaluated=td;var c_={};function hI(t,e){return t.scopeValue("func",{ref:e,code:c_[e.code]||(c_[e.code]=new aI._Code(e.code))})}J.useFunc=hI;var Ql;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ql||(J.Type=Ql={}));function gI(t,e,r){if(t instanceof le.Name){let n=e===Ql.Num;return r?n?(0,le._)`"[" + ${t} + "]"`:(0,le._)`"['" + ${t} + "']"`:n?(0,le._)`"/" + ${t}`:(0,le._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,le.getProperty)(t).toString():"/"+ed(t)}J.getErrorPath=gI;function f_(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}J.checkStrictMode=f_});var rr=E(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var Ue=H(),yI={data:new Ue.Name("data"),valCxt:new Ue.Name("valCxt"),instancePath:new Ue.Name("instancePath"),parentData:new Ue.Name("parentData"),parentDataProperty:new Ue.Name("parentDataProperty"),rootData:new Ue.Name("rootData"),dynamicAnchors:new Ue.Name("dynamicAnchors"),vErrors:new Ue.Name("vErrors"),errors:new Ue.Name("errors"),this:new Ue.Name("this"),self:new Ue.Name("self"),scope:new Ue.Name("scope"),json:new Ue.Name("json"),jsonPos:new Ue.Name("jsonPos"),jsonLen:new Ue.Name("jsonLen"),jsonPart:new Ue.Name("jsonPart")};rd.default=yI});var ws=E(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.extendErrors=qe.resetErrorsCount=qe.reportExtraError=qe.reportError=qe.keyword$DataError=qe.keywordError=void 0;var ne=H(),xa=ie(),Ge=rr();qe.keywordError={message:({keyword:t})=>(0,ne.str)`must pass "${t}" keyword validation`};qe.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ne.str)`"${t}" keyword must be ${e} ($data)`:(0,ne.str)`"${t}" keyword is invalid ($data)`};function vI(t,e=qe.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=g_(t,e,r);n??(i||a)?m_(s,c):h_(o,(0,ne._)`[${c}]`)}qe.reportError=vI;function _I(t,e=qe.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=g_(t,e,r);m_(o,a),s||i||h_(n,Ge.default.vErrors)}qe.reportExtraError=_I;function bI(t,e){t.assign(Ge.default.errors,e),t.if((0,ne._)`${Ge.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ne._)`${Ge.default.vErrors}.length`,e),()=>t.assign(Ge.default.vErrors,null)))}qe.resetErrorsCount=bI;function wI({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Ge.default.errors,a=>{t.const(i,(0,ne._)`${Ge.default.vErrors}[${a}]`),t.if((0,ne._)`${i}.instancePath === undefined`,()=>t.assign((0,ne._)`${i}.instancePath`,(0,ne.strConcat)(Ge.default.instancePath,s.errorPath))),t.assign((0,ne._)`${i}.schemaPath`,(0,ne.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ne._)`${i}.schema`,r),t.assign((0,ne._)`${i}.data`,n))})}qe.extendErrors=wI;function m_(t,e){let r=t.const("err",e);t.if((0,ne._)`${Ge.default.vErrors} === null`,()=>t.assign(Ge.default.vErrors,(0,ne._)`[${r}]`),(0,ne._)`${Ge.default.vErrors}.push(${r})`),t.code((0,ne._)`${Ge.default.errors}++`)}function h_(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ne._)`new ${t.ValidationError}(${e})`):(r.assign((0,ne._)`${n}.errors`,e),r.return(!1))}var an={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function g_(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ne._)`{}`:xI(t,e,r)}function xI(t,e,r={}){let{gen:n,it:o}=t,s=[SI(o,r),$I(t,r)];return kI(t,e,s),n.object(...s)}function SI({errorPath:t},{instancePath:e}){let r=e?(0,ne.str)`${t}${(0,xa.getErrorPath)(e,xa.Type.Str)}`:t;return[Ge.default.instancePath,(0,ne.strConcat)(Ge.default.instancePath,r)]}function $I({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ne.str)`${e}/${t}`;return r&&(o=(0,ne.str)`${o}${(0,xa.getErrorPath)(r,xa.Type.Str)}`),[an.schemaPath,o]}function kI(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([an.keyword,o],[an.params,typeof e=="function"?e(t):e||(0,ne._)`{}`]),c.messages&&n.push([an.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([an.schema,i],[an.parentSchema,(0,ne._)`${l}${d}`],[Ge.default.data,s]),u&&n.push([an.propertyName,u])}});var v_=E(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.boolOrEmptySchema=Kn.topBoolOrEmptySchema=void 0;var PI=ws(),TI=H(),EI=rr(),RI={message:"boolean schema is false"};function II(t){let{gen:e,schema:r,validateName:n}=t;r===!1?y_(t,!1):typeof r=="object"&&r.$async===!0?e.return(EI.default.data):(e.assign((0,TI._)`${n}.errors`,null),e.return(!0))}Kn.topBoolOrEmptySchema=II;function AI(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),y_(t)):r.var(e,!0)}Kn.boolOrEmptySchema=AI;function y_(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,PI.reportError)(o,RI,void 0,e)}});var nd=E(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.getRules=Gn.isJSONType=void 0;var CI=["string","number","integer","boolean","null","object","array"],DI=new Set(CI);function zI(t){return typeof t=="string"&&DI.has(t)}Gn.isJSONType=zI;function OI(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Gn.getRules=OI});var od=E(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.shouldUseRule=_r.shouldUseGroup=_r.schemaHasRulesForType=void 0;function MI({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&__(t,n)}_r.schemaHasRulesForType=MI;function __(t,e){return e.rules.some(r=>b_(t,r))}_r.shouldUseGroup=__;function b_(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}_r.shouldUseRule=b_});var xs=E(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.reportTypeError=Ve.checkDataTypes=Ve.checkDataType=Ve.coerceAndCheckDataType=Ve.getJSONTypes=Ve.getSchemaTypes=Ve.DataType=void 0;var NI=nd(),jI=od(),LI=ws(),q=H(),w_=ie(),Jn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Jn||(Ve.DataType=Jn={}));function FI(t){let e=x_(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Ve.getSchemaTypes=FI;function x_(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(NI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ve.getJSONTypes=x_;function ZI(t,e){let{gen:r,data:n,opts:o}=t,s=UI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,jI.schemaHasRulesForType)(t,e[0]));if(i){let a=id(e,n,o.strictNumbers,Jn.Wrong);r.if(a,()=>{s.length?qI(t,e,s):ad(t)})}return i}Ve.coerceAndCheckDataType=ZI;var S_=new Set(["string","number","integer","boolean","null"]);function UI(t,e){return e?t.filter(r=>S_.has(r)||e==="array"&&r==="array"):[]}function qI(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,q._)`typeof ${o}`),a=n.let("coerced",(0,q._)`undefined`);s.coerceTypes==="array"&&n.if((0,q._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,q._)`${o}[0]`).assign(i,(0,q._)`typeof ${o}`).if(id(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,q._)`${a} !== undefined`);for(let u of r)(S_.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),ad(t),n.endIf(),n.if((0,q._)`${a} !== undefined`,()=>{n.assign(o,a),VI(t,a)});function c(u){switch(u){case"string":n.elseIf((0,q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,q._)`"" + ${o}`).elseIf((0,q._)`${o} === null`).assign(a,(0,q._)`""`);return;case"number":n.elseIf((0,q._)`${i} == "boolean" || ${o} === null
|
|
6
7
|
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,q._)`+${o}`);return;case"integer":n.elseIf((0,q._)`${i} === "boolean" || ${o} === null
|
|
7
8
|
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,q._)`+${o}`);return;case"boolean":n.elseIf((0,q._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,q._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,q._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,q._)`${i} === "string" || ${i} === "number"
|
|
8
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,q._)`[${o}]`)}}}function bI({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,q._)`${e} !== undefined`,()=>t.assign((0,q._)`${e}[${r}]`,n))}function Wl(t,e,r,n=Bn.Correct){let o=n===Bn.Correct?q.operators.EQ:q.operators.NEQ,s;switch(t){case"null":return(0,q._)`${e} ${o} null`;case"array":s=(0,q._)`Array.isArray(${e})`;break;case"object":s=(0,q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,q._)`typeof ${e} ${o} ${t}`}return n===Bn.Correct?s:(0,q.not)(s);function i(a=q.nil){return(0,q.and)((0,q._)`typeof ${e} == "number"`,a,r?(0,q._)`isFinite(${e})`:q.nil)}}Fe.checkDataType=Wl;function Hl(t,e,r,n){if(t.length===1)return Wl(t[0],e,r,n);let o,s=(0,i_.toHash)(t);if(s.array&&s.object){let i=(0,q._)`typeof ${e} != "object"`;o=s.null?i:(0,q._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=q.nil;s.number&&delete s.integer;for(let i in s)o=(0,q.and)(o,Wl(i,e,r,n));return o}Fe.checkDataTypes=Hl;var wI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,q._)`{type: ${t}}`:(0,q._)`{type: ${e}}`};function Kl(t){let e=xI(t);(0,hI.reportError)(e,wI)}Fe.reportTypeError=Kl;function xI(t){let{gen:e,data:r,schema:n}=t,o=(0,i_.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var l_=E(ba=>{"use strict";Object.defineProperty(ba,"__esModule",{value:!0});ba.assignDefaults=void 0;var Wn=H(),SI=oe();function $I(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)u_(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>u_(t,s,o.default))}ba.assignDefaults=$I;function u_(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Wn._)`${s}${(0,Wn.getProperty)(e)}`;if(o){(0,SI.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Wn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Wn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Wn._)`${a} = ${(0,Wn.stringify)(r)}`)}});var dt=E(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=H(),Gl=oe(),hr=Jt(),kI=oe();function PI(t,e){let{gen:r,data:n,it:o}=t;r.if(Yl(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}ue.checkReportMissingProp=PI;function TI({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(Yl(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}ue.checkMissingProp=TI;function EI(t,e){t.setParams({missingProperty:e},!0),t.error()}ue.reportMissingProp=EI;function d_(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=d_;function Jl(t,e,r){return(0,ge._)`${d_(t)}.call(${e}, ${r})`}ue.isOwnProperty=Jl;function RI(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${Jl(t,e,r)}`:o}ue.propertyInData=RI;function Yl(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(Jl(t,e,r))):o}ue.noPropertyInData=Yl;function p_(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=p_;function II(t,e){return p_(e).filter(r=>!(0,Gl.alwaysValidSchema)(t,e[r]))}ue.schemaProperties=II;function AI({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ge._)`${t}, ${e}, ${n}${o}`:e,d=[[hr.default.instancePath,(0,ge.strConcat)(hr.default.instancePath,s)],[hr.default.parentData,i.parentData],[hr.default.parentDataProperty,i.parentDataProperty],[hr.default.rootData,hr.default.rootData]];i.opts.dynamicRef&&d.push([hr.default.dynamicAnchors,hr.default.dynamicAnchors]);let p=(0,ge._)`${l}, ${r.object(...d)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${p})`:(0,ge._)`${a}(${p})`}ue.callValidateCode=AI;var CI=(0,ge._)`new RegExp`;function DI({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ge._)`${o.code==="new RegExp"?CI:(0,kI.useFunc)(t,o)}(${r}, ${n})`})}ue.usePattern=DI;function zI(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Gl.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=zI;function OI(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Gl.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ue.validateUnion=OI});var h_=E(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.validateKeywordUsage=Ct.validSchemaType=Ct.funcKeywordCode=Ct.macroKeywordCode=void 0;var We=H(),tn=Jt(),MI=dt(),NI=ms();function jI(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=m_(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:We.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ct.macroKeywordCode=jI;function LI(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;ZI(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=m_(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)g(),e.modifying&&f_(t),y(()=>t.error());else{let _=e.async?f():m();e.modifying&&f_(t),y(()=>FI(t,_))}}function f(){let _=n.let("ruleErrs",null);return n.try(()=>g((0,We._)`await `),x=>n.assign(d,!1).if((0,We._)`${x} instanceof ${c.ValidationError}`,()=>n.assign(_,(0,We._)`${x}.errors`),()=>n.throw(x))),_}function m(){let _=(0,We._)`${l}.errors`;return n.assign(_,null),g(We.nil),_}function g(_=e.async?(0,We._)`await `:We.nil){let x=c.opts.passContext?tn.default.this:tn.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,We._)`${_}${(0,MI.callValidateCode)(t,l,x,v)}`,e.modifying)}function y(_){var x;n.if((0,We.not)((x=e.valid)!==null&&x!==void 0?x:d),_)}}Ct.funcKeywordCode=LI;function f_(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,We._)`${n.parentData}[${n.parentDataProperty}]`))}function FI(t,e){let{gen:r}=t;r.if((0,We._)`Array.isArray(${e})`,()=>{r.assign(tn.default.vErrors,(0,We._)`${tn.default.vErrors} === null ? ${e} : ${tn.default.vErrors}.concat(${e})`).assign(tn.default.errors,(0,We._)`${tn.default.vErrors}.length`),(0,NI.extendErrors)(t)},()=>t.error())}function ZI({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function m_(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,We.stringify)(r)})}function UI(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Ct.validSchemaType=UI;function qI({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Ct.validateKeywordUsage=qI});var y_=E(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.extendSubschemaMode=gr.extendSubschemaData=gr.getSubschema=void 0;var Dt=H(),g_=oe();function VI(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Dt._)`${t.schemaPath}${(0,Dt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Dt._)`${t.schemaPath}${(0,Dt.getProperty)(e)}${(0,Dt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,g_.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}gr.getSubschema=VI;function BI(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,Dt._)`${e.data}${(0,Dt.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Dt.str)`${u}${(0,g_.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Dt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Dt.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}gr.extendSubschemaData=BI;function WI(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}gr.extendSubschemaMode=WI});var Ql=E((C4,v_)=>{"use strict";v_.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var b_=E((D4,__)=>{"use strict";var yr=__.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};wa(e,n,o,t,"",t)};yr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};yr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};yr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};yr.skipKeywords={default:!0,enum:!0,const:!0,required:!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};function wa(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in yr.arrayKeywords)for(var p=0;p<d.length;p++)wa(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in yr.propsKeywords){if(d&&typeof d=="object")for(var f in d)wa(t,e,r,d[f],o+"/"+l+"/"+HI(f),s,o,l,n,f)}else(l in yr.keywords||t.allKeys&&!(l in yr.skipKeywords))&&wa(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function HI(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var gs=E(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.getSchemaRefs=Xe.resolveUrl=Xe.normalizeId=Xe._getFullPath=Xe.getFullPath=Xe.inlineRef=void 0;var KI=oe(),GI=Ql(),JI=b_(),YI=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function QI(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Xl(t):e?w_(t)<=e:!1}Xe.inlineRef=QI;var XI=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Xl(t){for(let e in t){if(XI.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Xl)||typeof r=="object"&&Xl(r))return!0}return!1}function w_(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!YI.has(r)&&(typeof t[r]=="object"&&(0,KI.eachItem)(t[r],n=>e+=w_(n)),e===1/0))return 1/0}return e}function x_(t,e="",r){r!==!1&&(e=Hn(e));let n=t.parse(e);return S_(t,n)}Xe.getFullPath=x_;function S_(t,e){return t.serialize(e).split("#")[0]+"#"}Xe._getFullPath=S_;var eA=/#\/?$/;function Hn(t){return t?t.replace(eA,""):""}Xe.normalizeId=Hn;function tA(t,e,r){return r=Hn(r),t.resolve(e,r)}Xe.resolveUrl=tA;var rA=/^[a-z_][-a-z0-9._]*$/i;function nA(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Hn(t[r]||e),s={"":o},i=x_(n,o,!1),a={},c=new Set;return JI(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let g=i+p,y=s[m];typeof d[r]=="string"&&(y=_.call(this,d[r])),x.call(this,d.$anchor),x.call(this,d.$dynamicAnchor),s[p]=y;function _(v){let P=this.opts.uriResolver.resolve;if(v=Hn(y?P(y,v):v),c.has(v))throw l(v);c.add(v);let S=this.refs[v];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?u(d,S.schema,v):v!==Hn(g)&&(v[0]==="#"?(u(d,a[v],v),a[v]=d):this.refs[v]=g),v}function x(v){if(typeof v=="string"){if(!rA.test(v))throw new Error(`invalid anchor "${v}"`);_.call(this,`#${v}`)}}}),a;function u(d,p,f){if(p!==void 0&&!GI(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Xe.getSchemaRefs=nA});var _s=E(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.getData=vr.KeywordCxt=vr.validateFunctionCode=void 0;var E_=n_(),$_=hs(),td=Bl(),xa=hs(),oA=l_(),vs=h_(),ed=y_(),D=H(),F=Jt(),sA=gs(),Yt=oe(),ys=ms();function iA(t){if(A_(t)&&(C_(t),I_(t))){uA(t);return}R_(t,()=>(0,E_.topBoolOrEmptySchema)(t))}vr.validateFunctionCode=iA;function R_({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,D._)`${F.default.data}, ${F.default.valCxt}`,n.$async,()=>{t.code((0,D._)`"use strict"; ${k_(r,o)}`),cA(t,o),t.code(s)}):t.func(e,(0,D._)`${F.default.data}, ${aA(o)}`,n.$async,()=>t.code(k_(r,o)).code(s))}function aA(t){return(0,D._)`{${F.default.instancePath}="", ${F.default.parentData}, ${F.default.parentDataProperty}, ${F.default.rootData}=${F.default.data}${t.dynamicRef?(0,D._)`, ${F.default.dynamicAnchors}={}`:D.nil}}={}`}function cA(t,e){t.if(F.default.valCxt,()=>{t.var(F.default.instancePath,(0,D._)`${F.default.valCxt}.${F.default.instancePath}`),t.var(F.default.parentData,(0,D._)`${F.default.valCxt}.${F.default.parentData}`),t.var(F.default.parentDataProperty,(0,D._)`${F.default.valCxt}.${F.default.parentDataProperty}`),t.var(F.default.rootData,(0,D._)`${F.default.valCxt}.${F.default.rootData}`),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,D._)`${F.default.valCxt}.${F.default.dynamicAnchors}`)},()=>{t.var(F.default.instancePath,(0,D._)`""`),t.var(F.default.parentData,(0,D._)`undefined`),t.var(F.default.parentDataProperty,(0,D._)`undefined`),t.var(F.default.rootData,F.default.data),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,D._)`{}`)})}function uA(t){let{schema:e,opts:r,gen:n}=t;R_(t,()=>{r.$comment&&e.$comment&&z_(t),mA(t),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&lA(t),D_(t),yA(t)})}function lA(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,D._)`${r}.evaluated`),e.if((0,D._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,D._)`${t.evaluated}.props`,(0,D._)`undefined`)),e.if((0,D._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,D._)`${t.evaluated}.items`,(0,D._)`undefined`))}function k_(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,D._)`/*# sourceURL=${r} */`:D.nil}function dA(t,e){if(A_(t)&&(C_(t),I_(t))){pA(t,e);return}(0,E_.boolOrEmptySchema)(t,e)}function I_({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function A_(t){return typeof t.schema!="boolean"}function pA(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&z_(t),hA(t),gA(t);let s=n.const("_errs",F.default.errors);D_(t,s),n.var(e,(0,D._)`${s} === ${F.default.errors}`)}function C_(t){(0,Yt.checkUnknownRules)(t),fA(t)}function D_(t,e){if(t.opts.jtd)return P_(t,[],!1,e);let r=(0,$_.getSchemaTypes)(t.schema),n=(0,$_.coerceAndCheckDataType)(t,r);P_(t,r,!n,e)}function fA(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Yt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function mA(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Yt.checkStrictMode)(t,"default is ignored in the schema root")}function hA(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,sA.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function gA(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function z_({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,D._)`${F.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,D.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,D._)`${F.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function yA(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,D._)`${F.default.errors} === 0`,()=>e.return(F.default.data),()=>e.throw((0,D._)`new ${o}(${F.default.vErrors})`)):(e.assign((0,D._)`${n}.errors`,F.default.vErrors),s.unevaluated&&vA(t),e.return((0,D._)`${F.default.errors} === 0`))}function vA({gen:t,evaluated:e,props:r,items:n}){r instanceof D.Name&&t.assign((0,D._)`${e}.props`,r),n instanceof D.Name&&t.assign((0,D._)`${e}.items`,n)}function P_(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Yt.schemaHasRulesButRef)(s,l))){o.block(()=>M_(t,"$ref",l.all.$ref.definition));return}c.jtd||_A(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,td.shouldUseGroup)(s,p)&&(p.type?(o.if((0,xa.checkDataType)(p.type,i,c.strictNumbers)),T_(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,xa.reportTypeError)(t)),o.endIf()):T_(t,p),a||o.if((0,D._)`${F.default.errors} === ${n||0}`))}}function T_(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,oA.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,td.shouldUseRule)(n,s)&&M_(t,s.keyword,s.definition,e.type)})}function _A(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(bA(t,e),t.opts.allowUnionTypes||wA(t,e),xA(t,t.dataTypes))}function bA(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{O_(t.dataTypes,r)||rd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),$A(t,e)}}function wA(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&rd(t,"use allowUnionTypes to allow union type keyword")}function xA(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,td.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>SA(e,i))&&rd(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function SA(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function O_(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function $A(t,e){let r=[];for(let n of t.dataTypes)O_(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function rd(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Yt.checkStrictMode)(t,e,t.opts.strictTypes)}var Sa=class{constructor(e,r,n){if((0,vs.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Yt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",N_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,vs.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",F.default.errors))}result(e,r,n){this.failResult((0,D.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,D.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,D._)`${r} !== undefined && (${(0,D.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?ys.reportExtraError:ys.reportError)(this,this.def.error,r)}$dataError(){(0,ys.reportError)(this,this.def.$dataError||ys.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ys.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=D.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=D.nil,r=D.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,D.or)((0,D._)`${o} === undefined`,r)),e!==D.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==D.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,D.or)(i(),a());function i(){if(n.length){if(!(r instanceof D.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,D._)`${(0,xa.checkDataTypes)(c,r,s.opts.strictNumbers,xa.DataType.Wrong)}`}return D.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,D._)`!${c}(${r})`}return D.nil}}subschema(e,r){let n=(0,ed.getSubschema)(this.it,e);(0,ed.extendSubschemaData)(n,this.it,e),(0,ed.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return dA(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Yt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Yt.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,D.Name)),!0}};vr.KeywordCxt=Sa;function M_(t,e,r,n){let o=new Sa(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,vs.funcKeywordCode)(o,r):"macro"in r?(0,vs.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,vs.funcKeywordCode)(o,r)}var kA=/^\/(?:[^~]|~0|~1)*$/,PA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function N_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return F.default.rootData;if(t[0]==="/"){if(!kA.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=F.default.rootData}else{let u=PA.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,D._)`${s}${(0,D.getProperty)((0,Yt.unescapeJsonPointer)(u))}`,i=(0,D._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}vr.getData=N_});var $a=E(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var nd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};od.default=nd});var bs=E(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var sd=gs(),id=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,sd.resolveUrl)(e,r,n),this.missingSchema=(0,sd.normalizeId)((0,sd.getFullPath)(e,this.missingRef))}};ad.default=id});var Pa=E(pt=>{"use strict";Object.defineProperty(pt,"__esModule",{value:!0});pt.resolveSchema=pt.getCompilingSchema=pt.resolveRef=pt.compileSchema=pt.SchemaEnv=void 0;var bt=H(),TA=$a(),rn=Jt(),wt=gs(),j_=oe(),EA=_s(),Kn=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,wt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};pt.SchemaEnv=Kn;function ud(t){let e=L_.call(this,t);if(e)return e;let r=(0,wt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new bt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:TA.default,code:(0,bt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:rn.default.data,parentData:rn.default.parentData,parentDataProperty:rn.default.parentDataProperty,dataNames:[rn.default.data],dataPathArr:[bt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,bt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:bt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,bt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,EA.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(rn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${rn.default.self}`,`${rn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:g}=u;f.evaluated={props:m instanceof bt.Name?void 0:m,items:g instanceof bt.Name?void 0:g,dynamicProps:m instanceof bt.Name,dynamicItems:g instanceof bt.Name},f.source&&(f.source.evaluated=(0,bt.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}pt.compileSchema=ud;function RA(t,e,r){var n;r=(0,wt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=CA.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Kn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=IA.call(this,s)}pt.resolveRef=RA;function IA(t){return(0,wt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:ud.call(this,t)}function L_(t){for(let e of this._compilations)if(AA(e,t))return e}pt.getCompilingSchema=L_;function AA(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function CA(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ka.call(this,t,e)}function ka(t,e){let r=this.opts.uriResolver.parse(e),n=(0,wt._getFullPath)(this.opts.uriResolver,r),o=(0,wt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return cd.call(this,r,t);let s=(0,wt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ka.call(this,t,i);return typeof a?.schema!="object"?void 0:cd.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||ud.call(this,i),s===(0,wt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,wt.resolveUrl)(this.opts.uriResolver,o,u)),new Kn({schema:a,schemaId:c,root:t,baseId:o})}return cd.call(this,r,i)}}pt.resolveSchema=ka;var DA=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function cd(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,j_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!DA.has(a)&&u&&(e=(0,wt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,j_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,wt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ka.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Kn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var F_=E((L4,zA)=>{zA.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var dd=E((F4,V_)=>{"use strict";var OA=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),U_=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function ld(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var MA=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Z_(t){return t.length=0,!0}function NA(t,e,r){if(t.length){let n=ld(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function jA(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=NA;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=Z_}else{o.push(u);continue}}return o.length&&(a===Z_?r.zone=o.join(""):i?n.push(o.join("")):n.push(ld(o))),r.address=n.join(""),r}function q_(t){if(LA(t,":")<2)return{host:t,isIPV6:!1};let e=jA(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function LA(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function FA(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function ZA(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function UA(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!U_(r)){let n=q_(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}V_.exports={nonSimpleDomain:MA,recomposeAuthority:UA,normalizeComponentEncoding:ZA,removeDotSegments:FA,isIPv4:U_,isUUID:OA,normalizeIPv6:q_,stringArrayToHexStripped:ld}});var G_=E((Z4,K_)=>{"use strict";var{isUUID:qA}=dd(),VA=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,BA=["http","https","ws","wss","urn","urn:uuid"];function WA(t){return BA.indexOf(t)!==-1}function pd(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function B_(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function W_(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function HA(t){return t.secure=pd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function KA(t){if((t.port===(pd(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function GA(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(VA);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=fd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function JA(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=fd(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function YA(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!qA(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function QA(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var H_={scheme:"http",domainHost:!0,parse:B_,serialize:W_},XA={scheme:"https",domainHost:H_.domainHost,parse:B_,serialize:W_},Ta={scheme:"ws",domainHost:!0,parse:HA,serialize:KA},eC={scheme:"wss",domainHost:Ta.domainHost,parse:Ta.parse,serialize:Ta.serialize},tC={scheme:"urn",parse:GA,serialize:JA,skipNormalize:!0},rC={scheme:"urn:uuid",parse:YA,serialize:QA,skipNormalize:!0},Ea={http:H_,https:XA,ws:Ta,wss:eC,urn:tC,"urn:uuid":rC};Object.setPrototypeOf(Ea,null);function fd(t){return t&&(Ea[t]||Ea[t.toLowerCase()])||void 0}K_.exports={wsIsSecure:pd,SCHEMES:Ea,isValidSchemeName:WA,getSchemeHandler:fd}});var Q_=E((U4,Ia)=>{"use strict";var{normalizeIPv6:nC,removeDotSegments:ws,recomposeAuthority:oC,normalizeComponentEncoding:Ra,isIPv4:sC,nonSimpleDomain:iC}=dd(),{SCHEMES:aC,getSchemeHandler:J_}=G_();function cC(t,e){return typeof t=="string"?t=zt(Qt(t,e),e):typeof t=="object"&&(t=Qt(zt(t,e),e)),t}function uC(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Y_(Qt(t,n),Qt(e,n),n,!0);return n.skipEscape=!0,zt(o,n)}function Y_(t,e,r,n){let o={};return n||(t=Qt(zt(t,r),r),e=Qt(zt(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ws(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ws(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ws(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=ws(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function lC(t,e,r){return typeof t=="string"?(t=unescape(t),t=zt(Ra(Qt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=zt(Ra(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=zt(Ra(Qt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=zt(Ra(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function zt(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=J_(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=oC(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=ws(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var dC=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Qt(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(dC);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(sC(n.host)===!1){let c=nC(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=J_(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&iC(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var md={SCHEMES:aC,normalize:cC,resolve:uC,resolveComponent:Y_,equal:lC,serialize:zt,parse:Qt};Ia.exports=md;Ia.exports.default=md;Ia.exports.fastUri=md});var eb=E(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var X_=Q_();X_.code='require("ajv/dist/runtime/uri").default';hd.default=X_});var cb=E(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=void 0;var pC=_s();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return pC.KeywordCxt}});var Gn=H();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return Gn._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return Gn.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return Gn.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return Gn.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return Gn.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return Gn.CodeGen}});var fC=$a(),sb=bs(),mC=Vl(),xs=Pa(),hC=H(),Ss=gs(),Aa=hs(),yd=oe(),tb=F_(),gC=eb(),ib=(t,e)=>new RegExp(t,e);ib.code="new RegExp";var yC=["removeAdditional","useDefaults","coerceTypes"],vC=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_C={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},bC={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},rb=200;function wC(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,g,y,_,x,v,P,S,N,L,Z,De;let Y=t.strict,kt=(e=t.code)===null||e===void 0?void 0:e.optimize,wr=kt===!0||kt===void 0?1:kt||0,Fs=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:ib,Zs=(o=t.uriResolver)!==null&&o!==void 0?o:gC.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Y)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:Y)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:Y)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:Y)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:Y)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:wr,regExp:Fs}:{optimize:wr,regExp:Fs},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:rb,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:rb,meta:(_=t.meta)!==null&&_!==void 0?_:!0,messages:(x=t.messages)!==null&&x!==void 0?x:!0,inlineRefs:(v=t.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(P=t.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(S=t.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(N=t.validateSchema)!==null&&N!==void 0?N:!0,validateFormats:(L=t.validateFormats)!==null&&L!==void 0?L:!0,unicodeRegExp:(Z=t.unicodeRegExp)!==null&&Z!==void 0?Z:!0,int32range:(De=t.int32range)!==null&&De!==void 0?De:!0,uriResolver:Zs}}var $s=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...wC(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new hC.ValueScope({scope:{},prefixes:vC,es5:r,lines:n}),this.logger=TC(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,mC.getRules)(),nb.call(this,_C,e,"NOT SUPPORTED"),nb.call(this,bC,e,"DEPRECATED","warn"),this._metaOpts=kC.call(this),e.formats&&SC.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&$C.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),xC.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=tb;n==="id"&&(o={...tb},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof sb.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Ss.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=ob.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new xs.SchemaEnv({schema:{},schemaId:n});if(r=xs.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=ob.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Ss.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(RC.call(this,n,r),!r)return(0,yd.eachItem)(n,s=>gd.call(this,s)),this;AC.call(this,r);let o={...r,type:(0,Aa.getJSONTypes)(r.type),schemaType:(0,Aa.getJSONTypes)(r.schemaType)};return(0,yd.eachItem)(n,o.type.length===0?s=>gd.call(this,s,o):s=>o.type.forEach(i=>gd.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=ab(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Ss.normalizeId)(i||n);let u=Ss.getSchemaRefs.call(this,e,n);return c=new xs.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):xs.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{xs.compileSchema.call(this,e)}finally{this.opts=r}}};$s.ValidationError=fC.default;$s.MissingRefError=sb.default;Ae.default=$s;function nb(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function ob(t){return t=(0,Ss.normalizeId)(t),this.schemas[t]||this.refs[t]}function xC(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function SC(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function $C(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function kC(){let t={...this.opts};for(let e of yC)delete t[e];return t}var PC={log(){},warn(){},error(){}};function TC(t){if(t===!1)return PC;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var EC=/^[a-z_$][a-z0-9_$:-]*$/i;function RC(t,e){let{RULES:r}=this;if((0,yd.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!EC.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function gd(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Aa.getJSONTypes)(e.type),schemaType:(0,Aa.getJSONTypes)(e.schemaType)}};e.before?IC.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function IC(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function AC(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=ab(e)),t.validateSchema=this.compile(e,!0))}var CC={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ab(t){return{anyOf:[t,CC]}}});var ub=E(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var DC={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};vd.default=DC});var fb=E(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.callRef=nn.getValidate=void 0;var zC=bs(),lb=dt(),et=H(),Jn=Jt(),db=Pa(),Ca=oe(),OC={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=db.resolveRef.call(c,u,o,r);if(l===void 0)throw new zC.default(n.opts.uriResolver,o,r);if(l instanceof db.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Da(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Da(t,(0,et._)`${m}.validate`,u,u.$async)}function p(m){let g=pb(t,m);Da(t,g,m,m.$async)}function f(m){let g=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,et.stringify)(m)}:{ref:m}),y=e.name("valid"),_=t.subschema({schema:m,dataTypes:[],schemaPath:et.nil,topSchemaRef:g,errSchemaPath:r},y);t.mergeEvaluated(_),t.ok(y)}}};function pb(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,et._)`${r.scopeValue("wrapper",{ref:e})}.validate`}nn.getValidate=pb;function Da(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Jn.default.this:et.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,et._)`await ${(0,lb.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},g=>{o.if((0,et._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,lb.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let g=(0,et._)`${m}.errors`;o.assign(Jn.default.vErrors,(0,et._)`${Jn.default.vErrors} === null ? ${g} : ${Jn.default.vErrors}.concat(${g})`),o.assign(Jn.default.errors,(0,et._)`${Jn.default.vErrors}.length`)}function f(m){var g;if(!s.opts.unevaluated)return;let y=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Ca.mergeEvaluated.props(o,y.props,s.props));else{let _=o.var("props",(0,et._)`${m}.evaluated.props`);s.props=Ca.mergeEvaluated.props(o,_,s.props,et.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Ca.mergeEvaluated.items(o,y.items,s.items));else{let _=o.var("items",(0,et._)`${m}.evaluated.items`);s.items=Ca.mergeEvaluated.items(o,_,s.items,et.Name)}}}nn.callRef=Da;nn.default=OC});var mb=E(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var MC=ub(),NC=fb(),jC=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",MC.default,NC.default];_d.default=jC});var hb=E(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var za=H(),_r=za.operators,Oa={maximum:{okStr:"<=",ok:_r.LTE,fail:_r.GT},minimum:{okStr:">=",ok:_r.GTE,fail:_r.LT},exclusiveMaximum:{okStr:"<",ok:_r.LT,fail:_r.GTE},exclusiveMinimum:{okStr:">",ok:_r.GT,fail:_r.LTE}},LC={message:({keyword:t,schemaCode:e})=>(0,za.str)`must be ${Oa[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,za._)`{comparison: ${Oa[t].okStr}, limit: ${e}}`},FC={keyword:Object.keys(Oa),type:"number",schemaType:"number",$data:!0,error:LC,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,za._)`${r} ${Oa[e].fail} ${n} || isNaN(${r})`)}};bd.default=FC});var gb=E(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var ks=H(),ZC={message:({schemaCode:t})=>(0,ks.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ks._)`{multipleOf: ${t}}`},UC={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:ZC,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ks._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ks._)`${i} !== parseInt(${i})`;t.fail$data((0,ks._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};wd.default=UC});var vb=E(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});function yb(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}xd.default=yb;yb.code='require("ajv/dist/runtime/ucs2length").default'});var _b=E(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var on=H(),qC=oe(),VC=vb(),BC={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,on.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,on._)`{limit: ${t}}`},WC={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:BC,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?on.operators.GT:on.operators.LT,i=o.opts.unicode===!1?(0,on._)`${r}.length`:(0,on._)`${(0,qC.useFunc)(t.gen,VC.default)}(${r})`;t.fail$data((0,on._)`${i} ${s} ${n}`)}};Sd.default=WC});var bb=E($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var HC=dt(),Ma=H(),KC={message:({schemaCode:t})=>(0,Ma.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ma._)`{pattern: ${t}}`},GC={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:KC,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,Ma._)`(new RegExp(${o}, ${i}))`:(0,HC.usePattern)(t,n);t.fail$data((0,Ma._)`!${a}.test(${e})`)}};$d.default=GC});var wb=E(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var Ps=H(),JC={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Ps.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ps._)`{limit: ${t}}`},YC={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:JC,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Ps.operators.GT:Ps.operators.LT;t.fail$data((0,Ps._)`Object.keys(${r}).length ${o} ${n}`)}};kd.default=YC});var xb=E(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var Ts=dt(),Es=H(),QC=oe(),XC={message:({params:{missingProperty:t}})=>(0,Es.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Es._)`{missingProperty: ${t}}`},eD={keyword:"required",type:"object",schemaType:"array",$data:!0,error:XC,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let g of r)if(f?.[g]===void 0&&!m.has(g)){let y=i.schemaEnv.baseId+i.errSchemaPath,_=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,QC.checkStrictMode)(i,_,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Es.nil,d);else for(let f of r)(0,Ts.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,Ts.checkMissingProp)(t,r,f)),(0,Ts.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Ts.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Ts.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Es.not)(m),()=>{t.error(),e.break()})},Es.nil)}}};Pd.default=eD});var Sb=E(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var Rs=H(),tD={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Rs.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Rs._)`{limit: ${t}}`},rD={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:tD,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Rs.operators.GT:Rs.operators.LT;t.fail$data((0,Rs._)`${r}.length ${o} ${n}`)}};Td.default=rD});var Na=E(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var $b=Ql();$b.code='require("ajv/dist/runtime/equal").default';Ed.default=$b});var kb=E(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var Rd=hs(),Ce=H(),nD=oe(),oD=Na(),sD={message:({params:{i:t,j:e}})=>(0,Ce.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ce._)`{i: ${t}, j: ${e}}`},iD={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:sD,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Rd.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Ce._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,Ce._)`${r}.length`),g=e.let("j");t.setParams({i:m,j:g}),e.assign(c,!0),e.if((0,Ce._)`${m} > 1`,()=>(d()?p:f)(m,g))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,g){let y=e.name("item"),_=(0,Rd.checkDataTypes)(u,y,a.opts.strictNumbers,Rd.DataType.Wrong),x=e.const("indices",(0,Ce._)`{}`);e.for((0,Ce._)`;${m}--;`,()=>{e.let(y,(0,Ce._)`${r}[${m}]`),e.if(_,(0,Ce._)`continue`),u.length>1&&e.if((0,Ce._)`typeof ${y} == "string"`,(0,Ce._)`${y} += "_"`),e.if((0,Ce._)`typeof ${x}[${y}] == "number"`,()=>{e.assign(g,(0,Ce._)`${x}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Ce._)`${x}[${y}] = ${m}`)})}function f(m,g){let y=(0,nD.useFunc)(e,oD.default),_=e.name("outer");e.label(_).for((0,Ce._)`;${m}--;`,()=>e.for((0,Ce._)`${g} = ${m}; ${g}--;`,()=>e.if((0,Ce._)`${y}(${r}[${m}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(_)})))}}};Id.default=iD});var Pb=E(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var Ad=H(),aD=oe(),cD=Na(),uD={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ad._)`{allowedValue: ${t}}`},lD={keyword:"const",$data:!0,error:uD,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Ad._)`!${(0,aD.useFunc)(e,cD.default)}(${r}, ${o})`):t.fail((0,Ad._)`${s} !== ${r}`)}};Cd.default=lD});var Tb=E(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var Is=H(),dD=oe(),pD=Na(),fD={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Is._)`{allowedValues: ${t}}`},mD={keyword:"enum",schemaType:"array",$data:!0,error:fD,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,dD.useFunc)(e,pD.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Is.or)(...o.map((m,g)=>p(f,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Is._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let g=o[m];return typeof g=="object"&&g!==null?(0,Is._)`${u()}(${r}, ${f}[${m}])`:(0,Is._)`${r} === ${g}`}}};Dd.default=mD});var Eb=E(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var hD=hb(),gD=gb(),yD=_b(),vD=bb(),_D=wb(),bD=xb(),wD=Sb(),xD=kb(),SD=Pb(),$D=Tb(),kD=[hD.default,gD.default,yD.default,vD.default,_D.default,bD.default,wD.default,xD.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},SD.default,$D.default];zd.default=kD});var Md=E(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.validateAdditionalItems=void 0;var sn=H(),Od=oe(),PD={message:({params:{len:t}})=>(0,sn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,sn._)`{limit: ${t}}`},TD={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:PD,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Od.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Rb(t,n)}};function Rb(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,sn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,sn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Od.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,sn._)`${a} <= ${e.length}`);r.if((0,sn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Od.Type.Num},u),i.allErrors||r.if((0,sn.not)(u),()=>r.break())})}}As.validateAdditionalItems=Rb;As.default=TD});var Nd=E(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.validateTuple=void 0;var Ib=H(),ja=oe(),ED=dt(),RD={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Ab(t,"additionalItems",e);r.items=!0,!(0,ja.alwaysValidSchema)(r,e)&&t.ok((0,ED.validateArray)(t))}};function Ab(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ja.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Ib._)`${s}.length`);r.forEach((d,p)=>{(0,ja.alwaysValidSchema)(a,d)||(n.if((0,Ib._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,g=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!g){let y=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,ja.checkStrictMode)(a,y,p.strictTuples)}}}Cs.validateTuple=Ab;Cs.default=RD});var Cb=E(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var ID=Nd(),AD={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,ID.validateTuple)(t,"items")};jd.default=AD});var zb=E(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Db=H(),CD=oe(),DD=dt(),zD=Md(),OD={message:({params:{len:t}})=>(0,Db.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Db._)`{limit: ${t}}`},MD={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:OD,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,CD.alwaysValidSchema)(n,e)&&(o?(0,zD.validateAdditionalItems)(t,o):t.ok((0,DD.validateArray)(t)))}};Ld.default=MD});var Ob=E(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var ft=H(),La=oe(),ND={message:({params:{min:t,max:e}})=>e===void 0?(0,ft.str)`must contain at least ${t} valid item(s)`:(0,ft.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ft._)`{minContains: ${t}}`:(0,ft._)`{minContains: ${t}, maxContains: ${e}}`},jD={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:ND,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,ft._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,La.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,La.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,La.alwaysValidSchema)(s,r)){let g=(0,ft._)`${l} >= ${i}`;a!==void 0&&(g=(0,ft._)`${g} && ${l} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,ft._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let g=e.name("_valid"),y=e.let("count",0);f(g,()=>e.if(g,()=>m(y)))}function f(g,y){e.forRange("i",0,l,_=>{t.subschema({keyword:"contains",dataProp:_,dataPropType:La.Type.Num,compositeRule:!0},g),y()})}function m(g){e.code((0,ft._)`${g}++`),a===void 0?e.if((0,ft._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,ft._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,ft._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};Fd.default=jD});var jb=E(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.validateSchemaDeps=Ot.validatePropertyDeps=Ot.error=void 0;var Zd=H(),LD=oe(),Ds=dt();Ot.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Zd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Zd._)`{property: ${t},
|
|
9
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,q._)`[${o}]`)}}}function VI({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,q._)`${e} !== undefined`,()=>t.assign((0,q._)`${e}[${r}]`,n))}function sd(t,e,r,n=Jn.Correct){let o=n===Jn.Correct?q.operators.EQ:q.operators.NEQ,s;switch(t){case"null":return(0,q._)`${e} ${o} null`;case"array":s=(0,q._)`Array.isArray(${e})`;break;case"object":s=(0,q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,q._)`typeof ${e} ${o} ${t}`}return n===Jn.Correct?s:(0,q.not)(s);function i(a=q.nil){return(0,q.and)((0,q._)`typeof ${e} == "number"`,a,r?(0,q._)`isFinite(${e})`:q.nil)}}Ve.checkDataType=sd;function id(t,e,r,n){if(t.length===1)return sd(t[0],e,r,n);let o,s=(0,w_.toHash)(t);if(s.array&&s.object){let i=(0,q._)`typeof ${e} != "object"`;o=s.null?i:(0,q._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=q.nil;s.number&&delete s.integer;for(let i in s)o=(0,q.and)(o,sd(i,e,r,n));return o}Ve.checkDataTypes=id;var BI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,q._)`{type: ${t}}`:(0,q._)`{type: ${e}}`};function ad(t){let e=WI(t);(0,LI.reportError)(e,BI)}Ve.reportTypeError=ad;function WI(t){let{gen:e,data:r,schema:n}=t,o=(0,w_.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var k_=E(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.assignDefaults=void 0;var Yn=H(),HI=ie();function KI(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)$_(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>$_(t,s,o.default))}Sa.assignDefaults=KI;function $_(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Yn._)`${s}${(0,Yn.getProperty)(e)}`;if(o){(0,HI.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Yn._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Yn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Yn._)`${a} = ${(0,Yn.stringify)(r)}`)}});var gt=E(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ge=H(),cd=ie(),br=rr(),GI=ie();function JI(t,e){let{gen:r,data:n,it:o}=t;r.if(ld(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ge._)`${e}`},!0),t.error()})}ue.checkReportMissingProp=JI;function YI({gen:t,data:e,it:{opts:r}},n,o){return(0,ge.or)(...n.map(s=>(0,ge.and)(ld(t,e,s,r.ownProperties),(0,ge._)`${o} = ${s}`)))}ue.checkMissingProp=YI;function XI(t,e){t.setParams({missingProperty:e},!0),t.error()}ue.reportMissingProp=XI;function P_(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ge._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=P_;function ud(t,e,r){return(0,ge._)`${P_(t)}.call(${e}, ${r})`}ue.isOwnProperty=ud;function QI(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} !== undefined`;return n?(0,ge._)`${o} && ${ud(t,e,r)}`:o}ue.propertyInData=QI;function ld(t,e,r,n){let o=(0,ge._)`${e}${(0,ge.getProperty)(r)} === undefined`;return n?(0,ge.or)(o,(0,ge.not)(ud(t,e,r))):o}ue.noPropertyInData=ld;function T_(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=T_;function eA(t,e){return T_(e).filter(r=>!(0,cd.alwaysValidSchema)(t,e[r]))}ue.schemaProperties=eA;function tA({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ge._)`${t}, ${e}, ${n}${o}`:e,d=[[br.default.instancePath,(0,ge.strConcat)(br.default.instancePath,s)],[br.default.parentData,i.parentData],[br.default.parentDataProperty,i.parentDataProperty],[br.default.rootData,br.default.rootData]];i.opts.dynamicRef&&d.push([br.default.dynamicAnchors,br.default.dynamicAnchors]);let p=(0,ge._)`${l}, ${r.object(...d)}`;return c!==ge.nil?(0,ge._)`${a}.call(${c}, ${p})`:(0,ge._)`${a}(${p})`}ue.callValidateCode=tA;var rA=(0,ge._)`new RegExp`;function nA({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ge._)`${o.code==="new RegExp"?rA:(0,GI.useFunc)(t,o)}(${r}, ${n})`})}ue.usePattern=nA;function oA(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,ge._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:cd.Type.Num},s),e.if((0,ge.not)(s),a)})}}ue.validateArray=oA;function sA(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,cd.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ge._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ge.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ue.validateUnion=sA});var I_=E(jt=>{"use strict";Object.defineProperty(jt,"__esModule",{value:!0});jt.validateKeywordUsage=jt.validSchemaType=jt.funcKeywordCode=jt.macroKeywordCode=void 0;var Je=H(),cn=rr(),iA=gt(),aA=ws();function cA(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=R_(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Je.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}jt.macroKeywordCode=cA;function uA(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;dA(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=R_(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)g(),e.modifying&&E_(t),y(()=>t.error());else{let v=e.async?f():m();e.modifying&&E_(t),y(()=>lA(t,v))}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>g((0,Je._)`await `),S=>n.assign(d,!1).if((0,Je._)`${S} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Je._)`${S}.errors`),()=>n.throw(S))),v}function m(){let v=(0,Je._)`${l}.errors`;return n.assign(v,null),g(Je.nil),v}function g(v=e.async?(0,Je._)`await `:Je.nil){let S=c.opts.passContext?cn.default.this:cn.default.self,w=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Je._)`${v}${(0,iA.callValidateCode)(t,l,S,w)}`,e.modifying)}function y(v){var S;n.if((0,Je.not)((S=e.valid)!==null&&S!==void 0?S:d),v)}}jt.funcKeywordCode=uA;function E_(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Je._)`${n.parentData}[${n.parentDataProperty}]`))}function lA(t,e){let{gen:r}=t;r.if((0,Je._)`Array.isArray(${e})`,()=>{r.assign(cn.default.vErrors,(0,Je._)`${cn.default.vErrors} === null ? ${e} : ${cn.default.vErrors}.concat(${e})`).assign(cn.default.errors,(0,Je._)`${cn.default.vErrors}.length`),(0,aA.extendErrors)(t)},()=>t.error())}function dA({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function R_(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Je.stringify)(r)})}function pA(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}jt.validSchemaType=pA;function fA({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}jt.validateKeywordUsage=fA});var C_=E(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.extendSubschemaMode=wr.extendSubschemaData=wr.getSubschema=void 0;var Lt=H(),A_=ie();function mA(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Lt._)`${t.schemaPath}${(0,Lt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Lt._)`${t.schemaPath}${(0,Lt.getProperty)(e)}${(0,Lt.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,A_.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}wr.getSubschema=mA;function hA(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,Lt._)`${e.data}${(0,Lt.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Lt.str)`${u}${(0,A_.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Lt._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Lt.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}wr.extendSubschemaData=hA;function gA(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}wr.extendSubschemaMode=gA});var dd=E((mB,D_)=>{"use strict";D_.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var O_=E((hB,z_)=>{"use strict";var xr=z_.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};$a(e,n,o,t,"",t)};xr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};xr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};xr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};xr.skipKeywords={default:!0,enum:!0,const:!0,required:!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};function $a(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in xr.arrayKeywords)for(var p=0;p<d.length;p++)$a(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in xr.propsKeywords){if(d&&typeof d=="object")for(var f in d)$a(t,e,r,d[f],o+"/"+l+"/"+yA(f),s,o,l,n,f)}else(l in xr.keywords||t.allKeys&&!(l in xr.skipKeywords))&&$a(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function yA(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ss=E(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.getSchemaRefs=rt.resolveUrl=rt.normalizeId=rt._getFullPath=rt.getFullPath=rt.inlineRef=void 0;var vA=ie(),_A=dd(),bA=O_(),wA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function xA(t,e=!0){return typeof t=="boolean"?!0:e===!0?!pd(t):e?M_(t)<=e:!1}rt.inlineRef=xA;var SA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function pd(t){for(let e in t){if(SA.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(pd)||typeof r=="object"&&pd(r))return!0}return!1}function M_(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!wA.has(r)&&(typeof t[r]=="object"&&(0,vA.eachItem)(t[r],n=>e+=M_(n)),e===1/0))return 1/0}return e}function N_(t,e="",r){r!==!1&&(e=Xn(e));let n=t.parse(e);return j_(t,n)}rt.getFullPath=N_;function j_(t,e){return t.serialize(e).split("#")[0]+"#"}rt._getFullPath=j_;var $A=/#\/?$/;function Xn(t){return t?t.replace($A,""):""}rt.normalizeId=Xn;function kA(t,e,r){return r=Xn(r),t.resolve(e,r)}rt.resolveUrl=kA;var PA=/^[a-z_][-a-z0-9._]*$/i;function TA(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Xn(t[r]||e),s={"":o},i=N_(n,o,!1),a={},c=new Set;return bA(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let g=i+p,y=s[m];typeof d[r]=="string"&&(y=v.call(this,d[r])),S.call(this,d.$anchor),S.call(this,d.$dynamicAnchor),s[p]=y;function v(w){let _=this.opts.uriResolver.resolve;if(w=Xn(y?_(y,w):w),c.has(w))throw l(w);c.add(w);let P=this.refs[w];return typeof P=="string"&&(P=this.refs[P]),typeof P=="object"?u(d,P.schema,w):w!==Xn(g)&&(w[0]==="#"?(u(d,a[w],w),a[w]=d):this.refs[w]=g),w}function S(w){if(typeof w=="string"){if(!PA.test(w))throw new Error(`invalid anchor "${w}"`);v.call(this,`#${w}`)}}}),a;function u(d,p,f){if(p!==void 0&&!_A(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}rt.getSchemaRefs=TA});var Ps=E(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.getData=Sr.KeywordCxt=Sr.validateFunctionCode=void 0;var q_=v_(),L_=xs(),md=od(),ka=xs(),EA=k_(),ks=I_(),fd=C_(),O=H(),F=rr(),RA=Ss(),nr=ie(),$s=ws();function IA(t){if(W_(t)&&(H_(t),B_(t))){DA(t);return}V_(t,()=>(0,q_.topBoolOrEmptySchema)(t))}Sr.validateFunctionCode=IA;function V_({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,O._)`${F.default.data}, ${F.default.valCxt}`,n.$async,()=>{t.code((0,O._)`"use strict"; ${F_(r,o)}`),CA(t,o),t.code(s)}):t.func(e,(0,O._)`${F.default.data}, ${AA(o)}`,n.$async,()=>t.code(F_(r,o)).code(s))}function AA(t){return(0,O._)`{${F.default.instancePath}="", ${F.default.parentData}, ${F.default.parentDataProperty}, ${F.default.rootData}=${F.default.data}${t.dynamicRef?(0,O._)`, ${F.default.dynamicAnchors}={}`:O.nil}}={}`}function CA(t,e){t.if(F.default.valCxt,()=>{t.var(F.default.instancePath,(0,O._)`${F.default.valCxt}.${F.default.instancePath}`),t.var(F.default.parentData,(0,O._)`${F.default.valCxt}.${F.default.parentData}`),t.var(F.default.parentDataProperty,(0,O._)`${F.default.valCxt}.${F.default.parentDataProperty}`),t.var(F.default.rootData,(0,O._)`${F.default.valCxt}.${F.default.rootData}`),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,O._)`${F.default.valCxt}.${F.default.dynamicAnchors}`)},()=>{t.var(F.default.instancePath,(0,O._)`""`),t.var(F.default.parentData,(0,O._)`undefined`),t.var(F.default.parentDataProperty,(0,O._)`undefined`),t.var(F.default.rootData,F.default.data),e.dynamicRef&&t.var(F.default.dynamicAnchors,(0,O._)`{}`)})}function DA(t){let{schema:e,opts:r,gen:n}=t;V_(t,()=>{r.$comment&&e.$comment&&G_(t),jA(t),n.let(F.default.vErrors,null),n.let(F.default.errors,0),r.unevaluated&&zA(t),K_(t),ZA(t)})}function zA(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,O._)`${r}.evaluated`),e.if((0,O._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,O._)`${t.evaluated}.props`,(0,O._)`undefined`)),e.if((0,O._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,O._)`${t.evaluated}.items`,(0,O._)`undefined`))}function F_(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,O._)`/*# sourceURL=${r} */`:O.nil}function OA(t,e){if(W_(t)&&(H_(t),B_(t))){MA(t,e);return}(0,q_.boolOrEmptySchema)(t,e)}function B_({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function W_(t){return typeof t.schema!="boolean"}function MA(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&G_(t),LA(t),FA(t);let s=n.const("_errs",F.default.errors);K_(t,s),n.var(e,(0,O._)`${s} === ${F.default.errors}`)}function H_(t){(0,nr.checkUnknownRules)(t),NA(t)}function K_(t,e){if(t.opts.jtd)return Z_(t,[],!1,e);let r=(0,L_.getSchemaTypes)(t.schema),n=(0,L_.coerceAndCheckDataType)(t,r);Z_(t,r,!n,e)}function NA(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,nr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function jA(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,nr.checkStrictMode)(t,"default is ignored in the schema root")}function LA(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,RA.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function FA(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function G_({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,O._)`${F.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,O.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,O._)`${F.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function ZA(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,O._)`${F.default.errors} === 0`,()=>e.return(F.default.data),()=>e.throw((0,O._)`new ${o}(${F.default.vErrors})`)):(e.assign((0,O._)`${n}.errors`,F.default.vErrors),s.unevaluated&&UA(t),e.return((0,O._)`${F.default.errors} === 0`))}function UA({gen:t,evaluated:e,props:r,items:n}){r instanceof O.Name&&t.assign((0,O._)`${e}.props`,r),n instanceof O.Name&&t.assign((0,O._)`${e}.items`,n)}function Z_(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,nr.schemaHasRulesButRef)(s,l))){o.block(()=>Y_(t,"$ref",l.all.$ref.definition));return}c.jtd||qA(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,md.shouldUseGroup)(s,p)&&(p.type?(o.if((0,ka.checkDataType)(p.type,i,c.strictNumbers)),U_(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,ka.reportTypeError)(t)),o.endIf()):U_(t,p),a||o.if((0,O._)`${F.default.errors} === ${n||0}`))}}function U_(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,EA.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,md.shouldUseRule)(n,s)&&Y_(t,s.keyword,s.definition,e.type)})}function qA(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(VA(t,e),t.opts.allowUnionTypes||BA(t,e),WA(t,t.dataTypes))}function VA(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{J_(t.dataTypes,r)||hd(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),KA(t,e)}}function BA(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&hd(t,"use allowUnionTypes to allow union type keyword")}function WA(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,md.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>HA(e,i))&&hd(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function HA(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function J_(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function KA(t,e){let r=[];for(let n of t.dataTypes)J_(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function hd(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,nr.checkStrictMode)(t,e,t.opts.strictTypes)}var Pa=class{constructor(e,r,n){if((0,ks.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,nr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",X_(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ks.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",F.default.errors))}result(e,r,n){this.failResult((0,O.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,O.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,O._)`${r} !== undefined && (${(0,O.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?$s.reportExtraError:$s.reportError)(this,this.def.error,r)}$dataError(){(0,$s.reportError)(this,this.def.$dataError||$s.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,$s.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=O.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=O.nil,r=O.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,O.or)((0,O._)`${o} === undefined`,r)),e!==O.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==O.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,O.or)(i(),a());function i(){if(n.length){if(!(r instanceof O.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,O._)`${(0,ka.checkDataTypes)(c,r,s.opts.strictNumbers,ka.DataType.Wrong)}`}return O.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,O._)`!${c}(${r})`}return O.nil}}subschema(e,r){let n=(0,fd.getSubschema)(this.it,e);(0,fd.extendSubschemaData)(n,this.it,e),(0,fd.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return OA(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=nr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=nr.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,O.Name)),!0}};Sr.KeywordCxt=Pa;function Y_(t,e,r,n){let o=new Pa(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ks.funcKeywordCode)(o,r):"macro"in r?(0,ks.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ks.funcKeywordCode)(o,r)}var GA=/^\/(?:[^~]|~0|~1)*$/,JA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function X_(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return F.default.rootData;if(t[0]==="/"){if(!GA.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=F.default.rootData}else{let u=JA.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,O._)`${s}${(0,O.getProperty)((0,nr.unescapeJsonPointer)(u))}`,i=(0,O._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Sr.getData=X_});var Ta=E(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var gd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};yd.default=gd});var Ts=E(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var vd=Ss(),_d=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,vd.resolveUrl)(e,r,n),this.missingSchema=(0,vd.normalizeId)((0,vd.getFullPath)(e,this.missingRef))}};bd.default=_d});var Ra=E(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.resolveSchema=yt.getCompilingSchema=yt.resolveRef=yt.compileSchema=yt.SchemaEnv=void 0;var kt=H(),YA=Ta(),un=rr(),Pt=Ss(),Q_=ie(),XA=Ps(),Qn=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Pt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};yt.SchemaEnv=Qn;function xd(t){let e=eb.call(this,t);if(e)return e;let r=(0,Pt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new kt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:YA.default,code:(0,kt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:un.default.data,parentData:un.default.parentData,parentDataProperty:un.default.parentDataProperty,dataNames:[un.default.data],dataPathArr:[kt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,kt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:kt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,kt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,XA.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(un.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${un.default.self}`,`${un.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:g}=u;f.evaluated={props:m instanceof kt.Name?void 0:m,items:g instanceof kt.Name?void 0:g,dynamicProps:m instanceof kt.Name,dynamicItems:g instanceof kt.Name},f.source&&(f.source.evaluated=(0,kt.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}yt.compileSchema=xd;function QA(t,e,r){var n;r=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=rC.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Qn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=eC.call(this,s)}yt.resolveRef=QA;function eC(t){return(0,Pt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:xd.call(this,t)}function eb(t){for(let e of this._compilations)if(tC(e,t))return e}yt.getCompilingSchema=eb;function tC(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function rC(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ea.call(this,t,e)}function Ea(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Pt._getFullPath)(this.opts.uriResolver,r),o=(0,Pt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return wd.call(this,r,t);let s=(0,Pt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ea.call(this,t,i);return typeof a?.schema!="object"?void 0:wd.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||xd.call(this,i),s===(0,Pt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Pt.resolveUrl)(this.opts.uriResolver,o,u)),new Qn({schema:a,schemaId:c,root:t,baseId:o})}return wd.call(this,r,i)}}yt.resolveSchema=Ea;var nC=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function wd(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Q_.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!nC.has(a)&&u&&(e=(0,Pt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Q_.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Pt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ea.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Qn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var tb=E((wB,oC)=>{oC.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var $d=E((xB,sb)=>{"use strict";var sC=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),nb=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Sd(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var iC=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function rb(t){return t.length=0,!0}function aC(t,e,r){if(t.length){let n=Sd(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function cC(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=aC;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=rb}else{o.push(u);continue}}return o.length&&(a===rb?r.zone=o.join(""):i?n.push(o.join("")):n.push(Sd(o))),r.address=n.join(""),r}function ob(t){if(uC(t,":")<2)return{host:t,isIPV6:!1};let e=cC(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function uC(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function lC(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function dC(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function pC(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!nb(r)){let n=ob(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}sb.exports={nonSimpleDomain:iC,recomposeAuthority:pC,normalizeComponentEncoding:dC,removeDotSegments:lC,isIPv4:nb,isUUID:sC,normalizeIPv6:ob,stringArrayToHexStripped:Sd}});var lb=E((SB,ub)=>{"use strict";var{isUUID:fC}=$d(),mC=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,hC=["http","https","ws","wss","urn","urn:uuid"];function gC(t){return hC.indexOf(t)!==-1}function kd(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function ib(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function ab(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function yC(t){return t.secure=kd(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function vC(t){if((t.port===(kd(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function _C(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(mC);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Pd(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function bC(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Pd(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function wC(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!fC(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function xC(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var cb={scheme:"http",domainHost:!0,parse:ib,serialize:ab},SC={scheme:"https",domainHost:cb.domainHost,parse:ib,serialize:ab},Ia={scheme:"ws",domainHost:!0,parse:yC,serialize:vC},$C={scheme:"wss",domainHost:Ia.domainHost,parse:Ia.parse,serialize:Ia.serialize},kC={scheme:"urn",parse:_C,serialize:bC,skipNormalize:!0},PC={scheme:"urn:uuid",parse:wC,serialize:xC,skipNormalize:!0},Aa={http:cb,https:SC,ws:Ia,wss:$C,urn:kC,"urn:uuid":PC};Object.setPrototypeOf(Aa,null);function Pd(t){return t&&(Aa[t]||Aa[t.toLowerCase()])||void 0}ub.exports={wsIsSecure:kd,SCHEMES:Aa,isValidSchemeName:gC,getSchemeHandler:Pd}});var fb=E(($B,Da)=>{"use strict";var{normalizeIPv6:TC,removeDotSegments:Es,recomposeAuthority:EC,normalizeComponentEncoding:Ca,isIPv4:RC,nonSimpleDomain:IC}=$d(),{SCHEMES:AC,getSchemeHandler:db}=lb();function CC(t,e){return typeof t=="string"?t=Ft(or(t,e),e):typeof t=="object"&&(t=or(Ft(t,e),e)),t}function DC(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=pb(or(t,n),or(e,n),n,!0);return n.skipEscape=!0,Ft(o,n)}function pb(t,e,r,n){let o={};return n||(t=or(Ft(t,r),r),e=or(Ft(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Es(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Es(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Es(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Es(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function zC(t,e,r){return typeof t=="string"?(t=unescape(t),t=Ft(Ca(or(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Ft(Ca(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Ft(Ca(or(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Ft(Ca(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Ft(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=db(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=EC(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Es(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var OC=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function or(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(OC);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(RC(n.host)===!1){let c=TC(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=db(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&IC(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var Td={SCHEMES:AC,normalize:CC,resolve:DC,resolveComponent:pb,equal:zC,serialize:Ft,parse:or};Da.exports=Td;Da.exports.default=Td;Da.exports.fastUri=Td});var hb=E(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var mb=fb();mb.code='require("ajv/dist/runtime/uri").default';Ed.default=mb});var Sb=E(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.CodeGen=ze.Name=ze.nil=ze.stringify=ze.str=ze._=ze.KeywordCxt=void 0;var MC=Ps();Object.defineProperty(ze,"KeywordCxt",{enumerable:!0,get:function(){return MC.KeywordCxt}});var eo=H();Object.defineProperty(ze,"_",{enumerable:!0,get:function(){return eo._}});Object.defineProperty(ze,"str",{enumerable:!0,get:function(){return eo.str}});Object.defineProperty(ze,"stringify",{enumerable:!0,get:function(){return eo.stringify}});Object.defineProperty(ze,"nil",{enumerable:!0,get:function(){return eo.nil}});Object.defineProperty(ze,"Name",{enumerable:!0,get:function(){return eo.Name}});Object.defineProperty(ze,"CodeGen",{enumerable:!0,get:function(){return eo.CodeGen}});var NC=Ta(),bb=Ts(),jC=nd(),Rs=Ra(),LC=H(),Is=Ss(),za=xs(),Id=ie(),gb=tb(),FC=hb(),wb=(t,e)=>new RegExp(t,e);wb.code="new RegExp";var ZC=["removeAdditional","useDefaults","coerceTypes"],UC=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),qC={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},VC={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},yb=200;function BC(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,g,y,v,S,w,_,P,A,D,U,$e;let G=t.strict,_t=(e=t.code)===null||e===void 0?void 0:e.optimize,Te=_t===!0||_t===void 0?1:_t||0,Pr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:wb,fn=(o=t.uriResolver)!==null&&o!==void 0?o:FC.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:G)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:G)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:G)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:G)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:G)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Te,regExp:Pr}:{optimize:Te,regExp:Pr},loopRequired:(g=t.loopRequired)!==null&&g!==void 0?g:yb,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:yb,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(S=t.messages)!==null&&S!==void 0?S:!0,inlineRefs:(w=t.inlineRefs)!==null&&w!==void 0?w:!0,schemaId:(_=t.schemaId)!==null&&_!==void 0?_:"$id",addUsedSchema:(P=t.addUsedSchema)!==null&&P!==void 0?P:!0,validateSchema:(A=t.validateSchema)!==null&&A!==void 0?A:!0,validateFormats:(D=t.validateFormats)!==null&&D!==void 0?D:!0,unicodeRegExp:(U=t.unicodeRegExp)!==null&&U!==void 0?U:!0,int32range:($e=t.int32range)!==null&&$e!==void 0?$e:!0,uriResolver:fn}}var As=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...BC(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new LC.ValueScope({scope:{},prefixes:UC,es5:r,lines:n}),this.logger=YC(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,jC.getRules)(),vb.call(this,qC,e,"NOT SUPPORTED"),vb.call(this,VC,e,"DEPRECATED","warn"),this._metaOpts=GC.call(this),e.formats&&HC.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&KC.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),WC.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=gb;n==="id"&&(o={...gb},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof bb.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Is.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=_b.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Rs.SchemaEnv({schema:{},schemaId:n});if(r=Rs.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=_b.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Is.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(QC.call(this,n,r),!r)return(0,Id.eachItem)(n,s=>Rd.call(this,s)),this;tD.call(this,r);let o={...r,type:(0,za.getJSONTypes)(r.type),schemaType:(0,za.getJSONTypes)(r.schemaType)};return(0,Id.eachItem)(n,o.type.length===0?s=>Rd.call(this,s,o):s=>o.type.forEach(i=>Rd.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=xb(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Is.normalizeId)(i||n);let u=Is.getSchemaRefs.call(this,e,n);return c=new Rs.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Rs.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Rs.compileSchema.call(this,e)}finally{this.opts=r}}};As.ValidationError=NC.default;As.MissingRefError=bb.default;ze.default=As;function vb(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function _b(t){return t=(0,Is.normalizeId)(t),this.schemas[t]||this.refs[t]}function WC(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function HC(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function KC(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function GC(){let t={...this.opts};for(let e of ZC)delete t[e];return t}var JC={log(){},warn(){},error(){}};function YC(t){if(t===!1)return JC;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var XC=/^[a-z_$][a-z0-9_$:-]*$/i;function QC(t,e){let{RULES:r}=this;if((0,Id.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!XC.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Rd(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,za.getJSONTypes)(e.type),schemaType:(0,za.getJSONTypes)(e.schemaType)}};e.before?eD.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function eD(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function tD(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=xb(e)),t.validateSchema=this.compile(e,!0))}var rD={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function xb(t){return{anyOf:[t,rD]}}});var $b=E(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var nD={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ad.default=nD});var Eb=E(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.callRef=ln.getValidate=void 0;var oD=Ts(),kb=gt(),nt=H(),to=rr(),Pb=Ra(),Oa=ie(),sD={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=Pb.resolveRef.call(c,u,o,r);if(l===void 0)throw new oD.default(n.opts.uriResolver,o,r);if(l instanceof Pb.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Ma(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Ma(t,(0,nt._)`${m}.validate`,u,u.$async)}function p(m){let g=Tb(t,m);Ma(t,g,m,m.$async)}function f(m){let g=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,nt.stringify)(m)}:{ref:m}),y=e.name("valid"),v=t.subschema({schema:m,dataTypes:[],schemaPath:nt.nil,topSchemaRef:g,errSchemaPath:r},y);t.mergeEvaluated(v),t.ok(y)}}};function Tb(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,nt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}ln.getValidate=Tb;function Ma(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?to.default.this:nt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,nt._)`await ${(0,kb.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},g=>{o.if((0,nt._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,kb.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let g=(0,nt._)`${m}.errors`;o.assign(to.default.vErrors,(0,nt._)`${to.default.vErrors} === null ? ${g} : ${to.default.vErrors}.concat(${g})`),o.assign(to.default.errors,(0,nt._)`${to.default.vErrors}.length`)}function f(m){var g;if(!s.opts.unevaluated)return;let y=(g=r?.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Oa.mergeEvaluated.props(o,y.props,s.props));else{let v=o.var("props",(0,nt._)`${m}.evaluated.props`);s.props=Oa.mergeEvaluated.props(o,v,s.props,nt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Oa.mergeEvaluated.items(o,y.items,s.items));else{let v=o.var("items",(0,nt._)`${m}.evaluated.items`);s.items=Oa.mergeEvaluated.items(o,v,s.items,nt.Name)}}}ln.callRef=Ma;ln.default=sD});var Rb=E(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var iD=$b(),aD=Eb(),cD=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",iD.default,aD.default];Cd.default=cD});var Ib=E(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var Na=H(),$r=Na.operators,ja={maximum:{okStr:"<=",ok:$r.LTE,fail:$r.GT},minimum:{okStr:">=",ok:$r.GTE,fail:$r.LT},exclusiveMaximum:{okStr:"<",ok:$r.LT,fail:$r.GTE},exclusiveMinimum:{okStr:">",ok:$r.GT,fail:$r.LTE}},uD={message:({keyword:t,schemaCode:e})=>(0,Na.str)`must be ${ja[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Na._)`{comparison: ${ja[t].okStr}, limit: ${e}}`},lD={keyword:Object.keys(ja),type:"number",schemaType:"number",$data:!0,error:uD,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Na._)`${r} ${ja[e].fail} ${n} || isNaN(${r})`)}};Dd.default=lD});var Ab=E(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var Cs=H(),dD={message:({schemaCode:t})=>(0,Cs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Cs._)`{multipleOf: ${t}}`},pD={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:dD,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Cs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Cs._)`${i} !== parseInt(${i})`;t.fail$data((0,Cs._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};zd.default=pD});var Db=E(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});function Cb(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Od.default=Cb;Cb.code='require("ajv/dist/runtime/ucs2length").default'});var zb=E(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var dn=H(),fD=ie(),mD=Db(),hD={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,dn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,dn._)`{limit: ${t}}`},gD={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:hD,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?dn.operators.GT:dn.operators.LT,i=o.opts.unicode===!1?(0,dn._)`${r}.length`:(0,dn._)`${(0,fD.useFunc)(t.gen,mD.default)}(${r})`;t.fail$data((0,dn._)`${i} ${s} ${n}`)}};Md.default=gD});var Ob=E(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var yD=gt(),La=H(),vD={message:({schemaCode:t})=>(0,La.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,La._)`{pattern: ${t}}`},_D={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:vD,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,La._)`(new RegExp(${o}, ${i}))`:(0,yD.usePattern)(t,n);t.fail$data((0,La._)`!${a}.test(${e})`)}};Nd.default=_D});var Mb=E(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var Ds=H(),bD={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Ds.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ds._)`{limit: ${t}}`},wD={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:bD,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Ds.operators.GT:Ds.operators.LT;t.fail$data((0,Ds._)`Object.keys(${r}).length ${o} ${n}`)}};jd.default=wD});var Nb=E(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var zs=gt(),Os=H(),xD=ie(),SD={message:({params:{missingProperty:t}})=>(0,Os.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Os._)`{missingProperty: ${t}}`},$D={keyword:"required",type:"object",schemaType:"array",$data:!0,error:SD,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let g of r)if(f?.[g]===void 0&&!m.has(g)){let y=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,xD.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Os.nil,d);else for(let f of r)(0,zs.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,zs.checkMissingProp)(t,r,f)),(0,zs.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,zs.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,zs.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Os.not)(m),()=>{t.error(),e.break()})},Os.nil)}}};Ld.default=$D});var jb=E(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var Ms=H(),kD={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ms.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ms._)`{limit: ${t}}`},PD={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:kD,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ms.operators.GT:Ms.operators.LT;t.fail$data((0,Ms._)`${r}.length ${o} ${n}`)}};Fd.default=PD});var Fa=E(Zd=>{"use strict";Object.defineProperty(Zd,"__esModule",{value:!0});var Lb=dd();Lb.code='require("ajv/dist/runtime/equal").default';Zd.default=Lb});var Fb=E(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var Ud=xs(),Oe=H(),TD=ie(),ED=Fa(),RD={message:({params:{i:t,j:e}})=>(0,Oe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Oe._)`{i: ${t}, j: ${e}}`},ID={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:RD,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,Ud.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Oe._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,Oe._)`${r}.length`),g=e.let("j");t.setParams({i:m,j:g}),e.assign(c,!0),e.if((0,Oe._)`${m} > 1`,()=>(d()?p:f)(m,g))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,g){let y=e.name("item"),v=(0,Ud.checkDataTypes)(u,y,a.opts.strictNumbers,Ud.DataType.Wrong),S=e.const("indices",(0,Oe._)`{}`);e.for((0,Oe._)`;${m}--;`,()=>{e.let(y,(0,Oe._)`${r}[${m}]`),e.if(v,(0,Oe._)`continue`),u.length>1&&e.if((0,Oe._)`typeof ${y} == "string"`,(0,Oe._)`${y} += "_"`),e.if((0,Oe._)`typeof ${S}[${y}] == "number"`,()=>{e.assign(g,(0,Oe._)`${S}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Oe._)`${S}[${y}] = ${m}`)})}function f(m,g){let y=(0,TD.useFunc)(e,ED.default),v=e.name("outer");e.label(v).for((0,Oe._)`;${m}--;`,()=>e.for((0,Oe._)`${g} = ${m}; ${g}--;`,()=>e.if((0,Oe._)`${y}(${r}[${m}], ${r}[${g}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};qd.default=ID});var Zb=E(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var Vd=H(),AD=ie(),CD=Fa(),DD={message:"must be equal to constant",params:({schemaCode:t})=>(0,Vd._)`{allowedValue: ${t}}`},zD={keyword:"const",$data:!0,error:DD,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Vd._)`!${(0,AD.useFunc)(e,CD.default)}(${r}, ${o})`):t.fail((0,Vd._)`${s} !== ${r}`)}};Bd.default=zD});var Ub=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var Ns=H(),OD=ie(),MD=Fa(),ND={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ns._)`{allowedValues: ${t}}`},jD={keyword:"enum",schemaType:"array",$data:!0,error:ND,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,OD.useFunc)(e,MD.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,Ns.or)(...o.map((m,g)=>p(f,g)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,Ns._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let g=o[m];return typeof g=="object"&&g!==null?(0,Ns._)`${u()}(${r}, ${f}[${m}])`:(0,Ns._)`${r} === ${g}`}}};Wd.default=jD});var qb=E(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var LD=Ib(),FD=Ab(),ZD=zb(),UD=Ob(),qD=Mb(),VD=Nb(),BD=jb(),WD=Fb(),HD=Zb(),KD=Ub(),GD=[LD.default,FD.default,ZD.default,UD.default,qD.default,VD.default,BD.default,WD.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},HD.default,KD.default];Hd.default=GD});var Gd=E(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.validateAdditionalItems=void 0;var pn=H(),Kd=ie(),JD={message:({params:{len:t}})=>(0,pn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,pn._)`{limit: ${t}}`},YD={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:JD,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Kd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Vb(t,n)}};function Vb(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,pn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,pn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Kd.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,pn._)`${a} <= ${e.length}`);r.if((0,pn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Kd.Type.Num},u),i.allErrors||r.if((0,pn.not)(u),()=>r.break())})}}js.validateAdditionalItems=Vb;js.default=YD});var Jd=E(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.validateTuple=void 0;var Bb=H(),Za=ie(),XD=gt(),QD={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Wb(t,"additionalItems",e);r.items=!0,!(0,Za.alwaysValidSchema)(r,e)&&t.ok((0,XD.validateArray)(t))}};function Wb(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Za.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Bb._)`${s}.length`);r.forEach((d,p)=>{(0,Za.alwaysValidSchema)(a,d)||(n.if((0,Bb._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,g=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!g){let y=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Za.checkStrictMode)(a,y,p.strictTuples)}}}Ls.validateTuple=Wb;Ls.default=QD});var Hb=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var ez=Jd(),tz={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,ez.validateTuple)(t,"items")};Yd.default=tz});var Gb=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var Kb=H(),rz=ie(),nz=gt(),oz=Gd(),sz={message:({params:{len:t}})=>(0,Kb.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Kb._)`{limit: ${t}}`},iz={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:sz,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,rz.alwaysValidSchema)(n,e)&&(o?(0,oz.validateAdditionalItems)(t,o):t.ok((0,nz.validateArray)(t)))}};Xd.default=iz});var Jb=E(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var vt=H(),Ua=ie(),az={message:({params:{min:t,max:e}})=>e===void 0?(0,vt.str)`must contain at least ${t} valid item(s)`:(0,vt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,vt._)`{minContains: ${t}}`:(0,vt._)`{minContains: ${t}, maxContains: ${e}}`},cz={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:az,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,vt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ua.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ua.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ua.alwaysValidSchema)(s,r)){let g=(0,vt._)`${l} >= ${i}`;a!==void 0&&(g=(0,vt._)`${g} && ${l} <= ${a}`),t.pass(g);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,vt._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let g=e.name("_valid"),y=e.let("count",0);f(g,()=>e.if(g,()=>m(y)))}function f(g,y){e.forRange("i",0,l,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:Ua.Type.Num,compositeRule:!0},g),y()})}function m(g){e.code((0,vt._)`${g}++`),a===void 0?e.if((0,vt._)`${g} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,vt._)`${g} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,vt._)`${g} >= ${i}`,()=>e.assign(d,!0)))}}};Qd.default=cz});var Qb=E(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.validateSchemaDeps=Zt.validatePropertyDeps=Zt.error=void 0;var ep=H(),uz=ie(),Fs=gt();Zt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,ep.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,ep._)`{property: ${t},
|
|
9
10
|
missingProperty: ${n},
|
|
10
11
|
depsCount: ${e},
|
|
11
|
-
deps: ${r}}`};var FD={keyword:"dependencies",type:"object",schemaType:"object",error:Ot.error,code(t){let[e,r]=ZD(t);Mb(t,e),Nb(t,r)}};function ZD({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function Mb(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Ds.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Ds.checkReportMissingProp)(t,u)}):(r.if((0,Zd._)`${c} && (${(0,Ds.checkMissingProp)(t,a,s)})`),(0,Ds.reportMissingProp)(t,s),r.else())}}Ot.validatePropertyDeps=Mb;function Nb(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,LD.alwaysValidSchema)(s,e[a])||(r.if((0,Ds.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Ot.validateSchemaDeps=Nb;Ot.default=FD});var Fb=E(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var Lb=H(),UD=oe(),qD={message:"property name must be valid",params:({params:t})=>(0,Lb._)`{propertyName: ${t.propertyName}}`},VD={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:qD,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,UD.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Lb.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Ud.default=VD});var Vd=E(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var Fa=dt(),xt=H(),BD=Jt(),Za=oe(),WD={message:"must NOT have additional properties",params:({params:t})=>(0,xt._)`{additionalProperty: ${t.additionalProperty}}`},HD={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:WD,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Za.alwaysValidSchema)(i,r))return;let u=(0,Fa.allSchemaProperties)(n.properties),l=(0,Fa.allSchemaProperties)(n.patternProperties);d(),t.ok((0,xt._)`${s} === ${BD.default.errors}`);function d(){e.forIn("key",o,y=>{!u.length&&!l.length?m(y):e.if(p(y),()=>m(y))})}function p(y){let _;if(u.length>8){let x=(0,Za.schemaRefOrVal)(i,n.properties,"properties");_=(0,Fa.isOwnProperty)(e,x,y)}else u.length?_=(0,xt.or)(...u.map(x=>(0,xt._)`${y} === ${x}`)):_=xt.nil;return l.length&&(_=(0,xt.or)(_,...l.map(x=>(0,xt._)`${(0,Fa.usePattern)(t,x)}.test(${y})`))),(0,xt.not)(_)}function f(y){e.code((0,xt._)`delete ${o}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Za.alwaysValidSchema)(i,r)){let _=e.name("valid");c.removeAdditional==="failing"?(g(y,_,!1),e.if((0,xt.not)(_),()=>{t.reset(),f(y)})):(g(y,_),a||e.if((0,xt.not)(_),()=>e.break()))}}function g(y,_,x){let v={keyword:"additionalProperties",dataProp:y,dataPropType:Za.Type.Str};x===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(v,_)}}};qd.default=HD});var qb=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var KD=_s(),Zb=dt(),Bd=oe(),Ub=Vd(),GD={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Ub.default.code(new KD.KeywordCxt(s,Ub.default,"additionalProperties"));let i=(0,Zb.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Bd.mergeEvaluated.props(e,(0,Bd.toHash)(i),s.props));let a=i.filter(d=>!(0,Bd.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,Zb.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Wd.default=GD});var Hb=E(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var Vb=dt(),Ua=H(),Bb=oe(),Wb=oe(),JD={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Vb.allSchemaProperties)(r),c=a.filter(g=>(0,Bb.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Ua.Name)&&(s.props=(0,Wb.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let g of a)u&&f(g),s.allErrors?m(g):(e.var(l,!0),m(g),e.if(l))}function f(g){for(let y in u)new RegExp(g).test(y)&&(0,Bb.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){e.forIn("key",n,y=>{e.if((0,Ua._)`${(0,Vb.usePattern)(t,g)}.test(${y})`,()=>{let _=c.includes(g);_||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:Wb.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Ua._)`${d}[${y}]`,!0):!_&&!s.allErrors&&e.if((0,Ua.not)(l),()=>e.break())})})}}};Hd.default=JD});var Kb=E(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var YD=oe(),QD={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,YD.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Kd.default=QD});var Gb=E(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var XD=dt(),ez={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:XD.validateUnion,error:{message:"must match a schema in anyOf"}};Gd.default=ez});var Jb=E(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var qa=H(),tz=oe(),rz={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,qa._)`{passingSchemas: ${t.passing}}`},nz={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:rz,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,tz.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,qa._)`${c} && ${i}`).assign(i,!1).assign(a,(0,qa._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,qa.Name)})})}}};Jd.default=nz});var Yb=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var oz=oe(),sz={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,oz.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Yd.default=sz});var ew=E(Qd=>{"use strict";Object.defineProperty(Qd,"__esModule",{value:!0});var Va=H(),Xb=oe(),iz={message:({params:t})=>(0,Va.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Va._)`{failingKeyword: ${t.ifClause}}`},az={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:iz,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Xb.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Qb(n,"then"),s=Qb(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Va.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Va._)`${l}`):t.setParams({ifClause:l})}}}};function Qb(t,e){let r=t.schema[e];return r!==void 0&&!(0,Xb.alwaysValidSchema)(t,r)}Qd.default=az});var tw=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var cz=oe(),uz={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,cz.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Xd.default=uz});var rw=E(ep=>{"use strict";Object.defineProperty(ep,"__esModule",{value:!0});var lz=Md(),dz=Cb(),pz=Nd(),fz=zb(),mz=Ob(),hz=jb(),gz=Fb(),yz=Vd(),vz=qb(),_z=Hb(),bz=Kb(),wz=Gb(),xz=Jb(),Sz=Yb(),$z=ew(),kz=tw();function Pz(t=!1){let e=[bz.default,wz.default,xz.default,Sz.default,$z.default,kz.default,gz.default,yz.default,hz.default,vz.default,_z.default];return t?e.push(dz.default,fz.default):e.push(lz.default,pz.default),e.push(mz.default),e}ep.default=Pz});var nw=E(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var ke=H(),Tz={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},Ez={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Tz,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,ke._)`${m}[${i}]`),y=r.let("fType"),_=r.let("format");r.if((0,ke._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,ke._)`${g}.type || "string"`).assign(_,(0,ke._)`${g}.validate`),()=>r.assign(y,(0,ke._)`"string"`).assign(_,g)),t.fail$data((0,ke.or)(x(),v()));function x(){return c.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${_}`}function v(){let P=l.$async?(0,ke._)`(${g}.async ? await ${_}(${n}) : ${_}(${n}))`:(0,ke._)`${_}(${n})`,S=(0,ke._)`(typeof ${_} == "function" ? ${P} : ${_}.test(${n}))`;return(0,ke._)`${_} && ${_} !== true && ${y} === ${e} && !${S}`}}function f(){let m=d.formats[s];if(!m){x();return}if(m===!0)return;let[g,y,_]=v(m);g===e&&t.pass(P());function x(){if(c.strictSchema===!1){d.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function v(S){let N=S instanceof RegExp?(0,ke.regexpCode)(S):c.code.formats?(0,ke._)`${c.code.formats}${(0,ke.getProperty)(s)}`:void 0,L=r.scopeValue("formats",{key:s,ref:S,code:N});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,ke._)`${L}.validate`]:["string",S,L]}function P(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ke._)`await ${_}(${n})`}return typeof y=="function"?(0,ke._)`${_}(${n})`:(0,ke._)`${_}.test(${n})`}}}};tp.default=Ez});var ow=E(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});var Rz=nw(),Iz=[Rz.default];rp.default=Iz});var sw=E(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.contentVocabulary=Yn.metadataVocabulary=void 0;Yn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Yn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var aw=E(np=>{"use strict";Object.defineProperty(np,"__esModule",{value:!0});var Az=mb(),Cz=Eb(),Dz=rw(),zz=ow(),iw=sw(),Oz=[Az.default,Cz.default,(0,Dz.default)(),zz.default,iw.metadataVocabulary,iw.contentVocabulary];np.default=Oz});var uw=E(Ba=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});Ba.DiscrError=void 0;var cw;(function(t){t.Tag="tag",t.Mapping="mapping"})(cw||(Ba.DiscrError=cw={}))});var dw=E(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var Qn=H(),op=uw(),lw=Pa(),Mz=bs(),Nz=oe(),jz={message:({params:{discrError:t,tagName:e}})=>t===op.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Qn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Lz={keyword:"discriminator",type:"object",schemaType:"object",error:jz,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Qn._)`${r}${(0,Qn.getProperty)(a)}`);e.if((0,Qn._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:op.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,Qn._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:op.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(g,Qn.Name),m}function p(){var f;let m={},g=_(o),y=!0;for(let P=0;P<i.length;P++){let S=i[P];if(S?.$ref&&!(0,Nz.schemaHasRulesButRef)(S,s.self.RULES)){let L=S.$ref;if(S=lw.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,L),S instanceof lw.SchemaEnv&&(S=S.schema),S===void 0)throw new Mz.default(s.opts.uriResolver,s.baseId,L)}let N=(f=S?.properties)===null||f===void 0?void 0:f[a];if(typeof N!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||_(S)),x(N,P)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function _({required:P}){return Array.isArray(P)&&P.includes(a)}function x(P,S){if(P.const)v(P.const,S);else if(P.enum)for(let N of P.enum)v(N,S);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function v(P,S){if(typeof P!="string"||P in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[P]=S}}}};sp.default=Lz});var pw=E((IB,Fz)=>{Fz.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var ap=E((ye,ip)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var Zz=cb(),Uz=aw(),qz=dw(),fw=pw(),Vz=["/properties"],Wa="http://json-schema.org/draft-07/schema",Xn=class extends Zz.default{_addVocabularies(){super._addVocabularies(),Uz.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(qz.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(fw,Vz):fw;this.addMetaSchema(e,Wa,!1),this.refs["http://json-schema.org/schema"]=Wa}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Wa)?Wa:void 0)}};ye.Ajv=Xn;ip.exports=ye=Xn;ip.exports.Ajv=Xn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Xn;var Bz=_s();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return Bz.KeywordCxt}});var eo=H();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return eo._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return eo.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return eo.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return eo.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return eo.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return eo.CodeGen}});var Wz=$a();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return Wz.default}});var Hz=bs();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return Hz.default}})});var ww=E(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.formatNames=Nt.fastFormats=Nt.fullFormats=void 0;function Mt(t,e){return{validate:t,compare:e}}Nt.fullFormats={date:Mt(yw,dp),time:Mt(up(!0),pp),"date-time":Mt(mw(!0),_w),"iso-time":Mt(up(),vw),"iso-date-time":Mt(mw(),bw),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Xz,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|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-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:iO,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:eO,int32:{type:"number",validate:nO},int64:{type:"number",validate:oO},float:{type:"number",validate:gw},double:{type:"number",validate:gw},password:!0,binary:!0};Nt.fastFormats={...Nt.fullFormats,date:Mt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,dp),time:Mt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,pp),"date-time":Mt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,_w),"iso-time":Mt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,vw),"iso-date-time":Mt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,bw),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Nt.formatNames=Object.keys(Nt.fullFormats);function Kz(t){return t%4===0&&(t%100!==0||t%400===0)}var Gz=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Jz=[0,31,28,31,30,31,30,31,31,30,31,30,31];function yw(t){let e=Gz.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&Kz(r)?29:Jz[n])}function dp(t,e){if(t&&e)return t>e?1:t<e?-1:0}var cp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function up(t){return function(r){let n=cp.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function pp(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function vw(t,e){if(!(t&&e))return;let r=cp.exec(t),n=cp.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var lp=/t|\s/i;function mw(t){let e=up(t);return function(n){let o=n.split(lp);return o.length===2&&yw(o[0])&&e(o[1])}}function _w(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function bw(t,e){if(!(t&&e))return;let[r,n]=t.split(lp),[o,s]=e.split(lp),i=dp(r,o);if(i!==void 0)return i||pp(n,s)}var Yz=/\/|:/,Qz=/^(?:[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 Xz(t){return Yz.test(t)&&Qz.test(t)}var hw=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function eO(t){return hw.lastIndex=0,hw.test(t)}var tO=-(2**31),rO=2**31-1;function nO(t){return Number.isInteger(t)&&t<=rO&&t>=tO}function oO(t){return Number.isInteger(t)}function gw(){return!0}var sO=/[^\\]\\Z/;function iO(t){if(sO.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var xw=E(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.formatLimitDefinition=void 0;var aO=ap(),St=H(),br=St.operators,Ha={formatMaximum:{okStr:"<=",ok:br.LTE,fail:br.GT},formatMinimum:{okStr:">=",ok:br.GTE,fail:br.LT},formatExclusiveMaximum:{okStr:"<",ok:br.LT,fail:br.GTE},formatExclusiveMinimum:{okStr:">",ok:br.GT,fail:br.LTE}},cO={message:({keyword:t,schemaCode:e})=>(0,St.str)`should be ${Ha[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,St._)`{comparison: ${Ha[t].okStr}, limit: ${e}}`};to.formatLimitDefinition={keyword:Object.keys(Ha),type:"string",schemaType:"string",$data:!0,error:cO,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new aO.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,St._)`${p}[${c.schemaCode}]`);t.fail$data((0,St.or)((0,St._)`typeof ${f} != "object"`,(0,St._)`${f} instanceof RegExp`,(0,St._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,St._)`${i.code.formats}${(0,St.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,St._)`${p}.compare(${r}, ${n}) ${Ha[o].fail} 0`}},dependencies:["format"]};var uO=t=>(t.addKeyword(to.formatLimitDefinition),t);to.default=uO});var Pw=E((zs,kw)=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});var ro=ww(),lO=xw(),fp=H(),Sw=new fp.Name("fullFormats"),dO=new fp.Name("fastFormats"),mp=(t,e={keywords:!0})=>{if(Array.isArray(e))return $w(t,e,ro.fullFormats,Sw),t;let[r,n]=e.mode==="fast"?[ro.fastFormats,dO]:[ro.fullFormats,Sw],o=e.formats||ro.formatNames;return $w(t,o,r,n),e.keywords&&(0,lO.default)(t),t};mp.get=(t,e="full")=>{let n=(e==="fast"?ro.fastFormats:ro.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function $w(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,fp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}kw.exports=zs=mp;Object.defineProperty(zs,"__esModule",{value:!0});zs.default=mp});import{readFileSync as mj}from"fs";import{join as Gp}from"path";import{fileURLToPath as hj}from"url";var cn=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},Us=class extends cn{code="PROVIDER_NOT_FOUND";retryable=!1;constructor(e){super(e,`Provider not found: ${e}`)}},me=class extends cn{code="PROVIDER_UNAVAILABLE";retryable=!1;constructor(e,r){super(e,`Provider unavailable: ${r||"not installed or not running"}`)}};var un=class extends cn{timeoutMs;code="PROVIDER_TIMEOUT";retryable=!0;constructor(e,r){super(e,`Timeout after ${r}ms`),this.timeoutMs=r}},He=class extends cn{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(e,r){super(e,`Execution error: ${r}`)}};var gf={ollama:{tier:"tool"},"claude-cli":{tier:"agent",maxComplexity:"complex"},"gemini-cli":{tier:"agent",maxComplexity:"complex"},"codex-cli":{tier:"agent",maxComplexity:"complex"},"claude-host":{tier:"agent",maxComplexity:"complex"},"codex-host":{tier:"agent",maxComplexity:"complex"},"gemini-host":{tier:"agent",maxComplexity:"complex"}},FS={ollama:{invocation:"http",roles:["participant","tool"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"claude-cli":{invocation:"cli",roles:["participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"gemini-cli":{invocation:"cli",roles:["leader","participant","reviewer","worker"],supportsAutonomousExecution:!0,supportsReadOnlyChat:!0},"codex-cli":{invocation:"cli",roles:["leader","participant","reviewer","worker"],supportsAutonomousExecution:!0,supportsReadOnlyChat:!0},"claude-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"codex-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"gemini-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0}};function Mc(t){return t<3?"simple":t<8?"moderate":t<=20?"complex":"advanced"}function Ws(t,e,r,n=t){let o=gf[n]??gf[t]??{},s=o.maxComplexity??"simple";return n==="ollama"&&r!==void 0&&(s=Mc(r)),{providerId:t,tier:o.tier??"tool",strengths:o.strengths??e.strengths,maxComplexity:s}}function tr(t,e){let r=FS[t.type],n=r?.roles?[...r.roles]:["participant"];return{id:t.id,type:t.type,invocation:r?.invocation??"unknown",roles:n,supportsAutonomousExecution:r?.supportsAutonomousExecution??!1,supportsReadOnlyChat:r?.supportsReadOnlyChat??!0,supportsToolUse:e?.supportsToolUse??r?.supportsToolUse??!1}}var Hs={low:0,medium:.5,high:.7},ZS={chat:"low",simple_review:"low",code_review:"medium",code_generation:"medium",design:"medium",writing:"medium",analysis:"medium",ideation:"medium",debate_turn:"medium",architecture:"high",cross_validate:"high",complex_refactor:"high"};function yf(t,e){return e?.[t]??ZS[t]??"low"}function Ks(t,e,r=Hs){return t>=r[e]}var Gs=class{providers=new Map;resolveProvider(e){let r=this.providers.get(e);if(r)return r;if(e==="claude")return this.getAll().find(n=>n.type==="claude-host"||n.type==="claude-cli")}register(e){this.providers.set(e.id,e)}get(e){let r=this.resolveProvider(e);if(!r)throw new Us(e);return r}getAll(){return[...this.providers.values()]}getAvailable(){return this.getAll().filter(e=>e.isAvailable())}getAvailableDescriptors(){return this.getAvailable().map(e=>this.getDescriptor(e.id))}getByCapability(e){return this.getAvailable().filter(r=>r.getCapabilities().strengths.includes(e))}has(e){return this.providers.has(e)}getCapability(e){let r=this.get(e);return Ws(r.id,r.getCapabilities(),void 0,r.type)}getDescriptor(e){let r=this.get(e);return r.getDescriptor?.()??tr(r,r.getCapabilities())}getByTier(e){return this.getAvailable().filter(r=>this.getCapability(r.id).tier===e)}getByRole(e){return this.getAvailable().filter(r=>this.getDescriptor(r.id).roles.includes(e))}getBestForTask(e,r,n,o){let s=this.getAvailable();if(s.length===0)return;if(!r)return s[0];let i=n??yf(e),a=r.getQualityStats(30),c=new Map;for(let[p,f]of a){let m=p.split(":")[0],g=c.get(m)??{totalScore:0,count:0};g.totalScore+=f.avgScore*f.count,g.count+=f.count,c.set(m,g)}let u=s.filter(p=>{let f=c.get(p.id);if(!f)return i==="low";let m=f.totalScore/f.count;return Ks(m,i,o)});if(u.length===0)return;let l,d=-1;for(let p of u){let f=`${p.id}:${e}`,m=a.get(f);m&&m.avgScore>d&&(d=m.avgScore,l=p)}return l??u[0]}};var h={};Ze(h,{BRAND:()=>f$,DIRTY:()=>$r,EMPTY_PATH:()=>BS,INVALID:()=>O,NEVER:()=>Y$,OK:()=>Oe,ParseStatus:()=>Te,Schema:()=>B,ZodAny:()=>or,ZodArray:()=>qt,ZodBigInt:()=>Pr,ZodBoolean:()=>Tr,ZodBranded:()=>yo,ZodCatch:()=>jr,ZodDate:()=>Er,ZodDefault:()=>Nr,ZodDiscriminatedUnion:()=>Qs,ZodEffects:()=>it,ZodEnum:()=>Or,ZodError:()=>Ke,ZodFirstPartyTypeKind:()=>k,ZodFunction:()=>ei,ZodIntersection:()=>Cr,ZodIssueCode:()=>$,ZodLazy:()=>Dr,ZodLiteral:()=>zr,ZodMap:()=>bn,ZodNaN:()=>xn,ZodNativeEnum:()=>Mr,ZodNever:()=>mt,ZodNull:()=>Ir,ZodNullable:()=>Et,ZodNumber:()=>kr,ZodObject:()=>Ge,ZodOptional:()=>ot,ZodParsedType:()=>R,ZodPipeline:()=>vo,ZodPromise:()=>sr,ZodReadonly:()=>Lr,ZodRecord:()=>Xs,ZodSchema:()=>B,ZodSet:()=>wn,ZodString:()=>nr,ZodSymbol:()=>vn,ZodTransformer:()=>it,ZodTuple:()=>Tt,ZodType:()=>B,ZodUndefined:()=>Rr,ZodUnion:()=>Ar,ZodUnknown:()=>Ut,ZodVoid:()=>_n,addIssueToContext:()=>T,any:()=>x$,array:()=>P$,bigint:()=>y$,boolean:()=>Ef,coerce:()=>J$,custom:()=>kf,date:()=>v$,datetimeRegex:()=>Sf,defaultErrorMap:()=>Ft,discriminatedUnion:()=>I$,effect:()=>U$,enum:()=>L$,function:()=>M$,getErrorMap:()=>hn,getParsedType:()=>Pt,instanceof:()=>h$,intersection:()=>A$,isAborted:()=>Js,isAsync:()=>gn,isDirty:()=>Ys,isValid:()=>rr,late:()=>m$,lazy:()=>N$,literal:()=>j$,makeIssue:()=>go,map:()=>z$,nan:()=>g$,nativeEnum:()=>F$,never:()=>$$,null:()=>w$,nullable:()=>V$,number:()=>Tf,object:()=>T$,objectUtil:()=>Nc,oboolean:()=>G$,onumber:()=>K$,optional:()=>q$,ostring:()=>H$,pipeline:()=>W$,preprocess:()=>B$,promise:()=>Z$,quotelessJson:()=>US,record:()=>D$,set:()=>O$,setErrorMap:()=>VS,strictObject:()=>E$,string:()=>Pf,symbol:()=>_$,transformer:()=>U$,tuple:()=>C$,undefined:()=>b$,union:()=>R$,unknown:()=>S$,util:()=>J,void:()=>k$});var J;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(J||(J={}));var Nc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Nc||(Nc={}));var R=J.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Pt=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}};var $=J.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"]),US=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ke=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,J.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ke.create=t=>new Ke(t);var qS=(t,e)=>{let r;switch(t.code){case $.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case $.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,J.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:r=`Unrecognized key(s) in object: ${J.joinValues(t.keys,", ")}`;break;case $.invalid_union:r="Invalid input";break;case $.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${J.joinValues(t.options)}`;break;case $.invalid_enum_value:r=`Invalid enum value. Expected ${J.joinValues(t.options)}, received '${t.received}'`;break;case $.invalid_arguments:r="Invalid function arguments";break;case $.invalid_return_type:r="Invalid function return type";break;case $.invalid_date:r="Invalid date";break;case $.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:J.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case $.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case $.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case $.custom:r="Invalid input";break;case $.invalid_intersection_types:r="Intersection results could not be merged";break;case $.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case $.not_finite:r="Number must be finite";break;default:r=e.defaultError,J.assertNever(t)}return{message:r}},Ft=qS;var vf=Ft;function VS(t){vf=t}function hn(){return vf}var go=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},BS=[];function T(t,e){let r=hn(),n=go({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ft?void 0:Ft].filter(o=>!!o)});t.common.issues.push(n)}var Te=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return O;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return O;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},O=Object.freeze({status:"aborted"}),$r=t=>({status:"dirty",value:t}),Oe=t=>({status:"valid",value:t}),Js=t=>t.status==="aborted",Ys=t=>t.status==="dirty",rr=t=>t.status==="valid",gn=t=>typeof Promise<"u"&&t instanceof Promise;var A;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(A||(A={}));var st=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}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}},_f=(t,e)=>{if(rr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ke(t.common.issues);return this._error=r,this._error}}};function U(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var B=class{get description(){return this._def.description}_getType(e){return Pt(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Te,ctx:{common:e.parent.common,data:e.data,parsedType:Pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(gn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pt(e)},o=this._parseSync({data:e,path:n.path,parent:n});return _f(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pt(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return rr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>rr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Pt(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(gn(o)?o:Promise.resolve(o));return _f(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:$.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new it({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:r=>this["~validate"](r)}}optional(){return ot.create(this,this._def)}nullable(){return Et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return qt.create(this)}promise(){return sr.create(this,this._def)}or(e){return Ar.create([this,e],this._def)}and(e){return Cr.create(this,e,this._def)}transform(e){return new it({...U(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Nr({...U(this._def),innerType:this,defaultValue:r,typeName:k.ZodDefault})}brand(){return new yo({typeName:k.ZodBranded,type:this,...U(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new jr({...U(this._def),innerType:this,catchValue:r,typeName:k.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return vo.create(this,e)}readonly(){return Lr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},WS=/^c[^\s-]{8,}$/i,HS=/^[0-9a-z]+$/,KS=/^[0-9A-HJKMNP-TV-Z]{26}$/i,GS=/^[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,JS=/^[a-z0-9_-]{21}$/i,YS=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,QS=/^[-+]?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)?)??$/,XS=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,e$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",jc,t$=/^(?:(?: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])$/,r$=/^(?:(?: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])$/,n$=/^(([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]))$/,o$=/^(([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])$/,s$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,i$=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,wf="((\\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])))",a$=new RegExp(`^${wf}$`);function xf(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function c$(t){return new RegExp(`^${xf(t)}$`)}function Sf(t){let e=`${wf}T${xf(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function u$(t,e){return!!((e==="v4"||!e)&&t$.test(t)||(e==="v6"||!e)&&n$.test(t))}function l$(t,e){if(!YS.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function d$(t,e){return!!((e==="v4"||!e)&&r$.test(t)||(e==="v6"||!e)&&o$.test(t))}var nr=class t extends B{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.string,received:s.parsedType}),O}let n=new Te,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?T(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&T(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")XS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"email",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")jc||(jc=new RegExp(e$,"u")),jc.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"emoji",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")GS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"uuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")JS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"nanoid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")WS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")HS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid2",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")KS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ulid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),T(o,{validation:"url",code:$.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"regex",code:$.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Sf(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?a$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?c$(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?QS.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?u$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ip",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?l$(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?d$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?s$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?i$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64url",code:$.invalid_string,message:s.message}),n.dirty()):J.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:$.invalid_string,...A.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...A.errToObj(e)})}url(e){return this._addCheck({kind:"url",...A.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...A.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...A.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...A.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...A.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...A.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...A.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...A.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...A.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...A.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...A.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...A.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:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...A.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:typeof e?.precision>"u"?null:e?.precision,...A.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...A.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...A.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...A.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...A.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...A.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...A.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...A.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...A.errToObj(r)})}nonempty(e){return this.min(1,A.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};nr.create=t=>new nr({checks:[],typeName:k.ZodString,coerce:t?.coerce??!1,...U(t)});function p$(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var kr=class t extends B{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)!==R.number){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.number,received:s.parsedType}),O}let n,o=new Te;for(let s of this._def.checks)s.kind==="int"?J.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:$.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?p$(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_finite,message:s.message}),o.dirty()):J.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,A.toString(r))}gt(e,r){return this.setLimit("min",e,!1,A.toString(r))}lte(e,r){return this.setLimit("max",e,!0,A.toString(r))}lt(e,r){return this.setLimit("max",e,!1,A.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:A.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:A.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:A.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:A.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:A.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:A.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:A.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:A.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:A.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:A.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&J.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};kr.create=t=>new kr({checks:[],typeName:k.ZodNumber,coerce:t?.coerce||!1,...U(t)});var Pr=class t extends B{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)!==R.bigint)return this._getInvalidInput(e);let n,o=new Te;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):J.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return T(r,{code:$.invalid_type,expected:R.bigint,received:r.parsedType}),O}gte(e,r){return this.setLimit("min",e,!0,A.toString(r))}gt(e,r){return this.setLimit("min",e,!1,A.toString(r))}lte(e,r){return this.setLimit("max",e,!0,A.toString(r))}lt(e,r){return this.setLimit("max",e,!1,A.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:A.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:A.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:A.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:A.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:A.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:A.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Pr.create=t=>new Pr({checks:[],typeName:k.ZodBigInt,coerce:t?.coerce??!1,...U(t)});var Tr=class extends B{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.boolean,received:n.parsedType}),O}return Oe(e.data)}};Tr.create=t=>new Tr({typeName:k.ZodBoolean,coerce:t?.coerce||!1,...U(t)});var Er=class t extends B{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.date,received:s.parsedType}),O}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_date}),O}let n=new Te,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):J.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:A.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:A.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Er.create=t=>new Er({checks:[],coerce:t?.coerce||!1,typeName:k.ZodDate,...U(t)});var vn=class extends B{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.symbol,received:n.parsedType}),O}return Oe(e.data)}};vn.create=t=>new vn({typeName:k.ZodSymbol,...U(t)});var Rr=class extends B{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.undefined,received:n.parsedType}),O}return Oe(e.data)}};Rr.create=t=>new Rr({typeName:k.ZodUndefined,...U(t)});var Ir=class extends B{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.null,received:n.parsedType}),O}return Oe(e.data)}};Ir.create=t=>new Ir({typeName:k.ZodNull,...U(t)});var or=class extends B{constructor(){super(...arguments),this._any=!0}_parse(e){return Oe(e.data)}};or.create=t=>new or({typeName:k.ZodAny,...U(t)});var Ut=class extends B{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Oe(e.data)}};Ut.create=t=>new Ut({typeName:k.ZodUnknown,...U(t)});var mt=class extends B{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:$.invalid_type,expected:R.never,received:r.parsedType}),O}};mt.create=t=>new mt({typeName:k.ZodNever,...U(t)});var _n=class extends B{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.void,received:n.parsedType}),O}return Oe(e.data)}};_n.create=t=>new _n({typeName:k.ZodVoid,...U(t)});var qt=class t extends B{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==R.array)return T(r,{code:$.invalid_type,expected:R.array,received:r.parsedType}),O;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(T(r,{code:i?$.too_big:$.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(T(r,{code:$.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(T(r,{code:$.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new st(r,i,r.path,a)))).then(i=>Te.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new st(r,i,r.path,a)));return Te.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:A.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:A.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:A.toString(r)}})}nonempty(e){return this.min(1,e)}};qt.create=(t,e)=>new qt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...U(e)});function yn(t){if(t instanceof Ge){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ot.create(yn(n))}return new Ge({...t._def,shape:()=>e})}else return t instanceof qt?new qt({...t._def,type:yn(t.element)}):t instanceof ot?ot.create(yn(t.unwrap())):t instanceof Et?Et.create(yn(t.unwrap())):t instanceof Tt?Tt.create(t.items.map(e=>yn(e))):t}var Ge=class t extends B{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(),r=J.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==R.object){let u=this._getOrReturnCtx(e);return T(u,{code:$.invalid_type,expected:R.object,received:u.parsedType}),O}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof mt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new st(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof mt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(T(o,{code:$.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new st(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Te.mergeObjectSync(n,u)):Te.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return A.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:A.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:k.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of J.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of J.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return yn(this)}partial(e){let r={};for(let n of J.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of J.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ot;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return $f(J.objectKeys(this.shape))}};Ge.create=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strip",catchall:mt.create(),typeName:k.ZodObject,...U(e)});Ge.strictCreate=(t,e)=>new Ge({shape:()=>t,unknownKeys:"strict",catchall:mt.create(),typeName:k.ZodObject,...U(e)});Ge.lazycreate=(t,e)=>new Ge({shape:t,unknownKeys:"strip",catchall:mt.create(),typeName:k.ZodObject,...U(e)});var Ar=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ke(a.ctx.common.issues));return T(r,{code:$.invalid_union,unionErrors:i}),O}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ke(c));return T(r,{code:$.invalid_union,unionErrors:a}),O}}get options(){return this._def.options}};Ar.create=(t,e)=>new Ar({options:t,typeName:k.ZodUnion,...U(e)});var Zt=t=>t instanceof Dr?Zt(t.schema):t instanceof it?Zt(t.innerType()):t instanceof zr?[t.value]:t instanceof Or?t.options:t instanceof Mr?J.objectValues(t.enum):t instanceof Nr?Zt(t._def.innerType):t instanceof Rr?[void 0]:t instanceof Ir?[null]:t instanceof ot?[void 0,...Zt(t.unwrap())]:t instanceof Et?[null,...Zt(t.unwrap())]:t instanceof yo||t instanceof Lr?Zt(t.unwrap()):t instanceof jr?Zt(t._def.innerType):[],Qs=class t extends B{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.object)return T(r,{code:$.invalid_type,expected:R.object,received:r.parsedType}),O;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(T(r,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),O)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Zt(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:k.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...U(n)})}};function Lc(t,e){let r=Pt(t),n=Pt(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.object){let o=J.objectKeys(e),s=J.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Lc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===R.array&&n===R.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Lc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===R.date&&n===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Cr=class extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Js(s)||Js(i))return O;let a=Lc(s.value,i.value);return a.valid?((Ys(s)||Ys(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:$.invalid_intersection_types}),O)};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(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Cr.create=(t,e,r)=>new Cr({left:t,right:e,typeName:k.ZodIntersection,...U(r)});var Tt=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:$.invalid_type,expected:R.array,received:n.parsedType}),O;if(n.data.length<this._def.items.length)return T(n,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),O;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:$.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new st(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Te.mergeArray(r,i)):Te.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Tt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Tt({items:t,typeName:k.ZodTuple,rest:null,...U(e)})};var Xs=class t extends B{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return T(n,{code:$.invalid_type,expected:R.object,received:n.parsedType}),O;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new st(n,a,n.path,a)),value:i._parse(new st(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Te.mergeObjectAsync(r,o):Te.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof B?new t({keyType:e,valueType:r,typeName:k.ZodRecord,...U(n)}):new t({keyType:nr.create(),valueType:e,typeName:k.ZodRecord,...U(r)})}},bn=class extends B{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return T(n,{code:$.invalid_type,expected:R.map,received:n.parsedType}),O;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new st(n,a,n.path,[u,"key"])),value:s._parse(new st(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return O;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return O;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};bn.create=(t,e,r)=>new bn({valueType:e,keyType:t,typeName:k.ZodMap,...U(r)});var wn=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:$.invalid_type,expected:R.set,received:n.parsedType}),O;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(T(n,{code:$.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(T(n,{code:$.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return O;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new st(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:A.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:A.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};wn.create=(t,e)=>new wn({valueType:t,minSize:null,maxSize:null,typeName:k.ZodSet,...U(e)});var ei=class t extends B{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.function)return T(r,{code:$.invalid_type,expected:R.function,received:r.parsedType}),O;function n(a,c){return go({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,hn(),Ft].filter(u=>!!u),issueData:{code:$.invalid_arguments,argumentsError:c}})}function o(a,c){return go({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,hn(),Ft].filter(u=>!!u),issueData:{code:$.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof sr){let a=this;return Oe(async function(...c){let u=new Ke([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(o(d,f)),u})})}else{let a=this;return Oe(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ke([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ke([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Tt.create(e).rest(Ut.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Tt.create([]).rest(Ut.create()),returns:r||Ut.create(),typeName:k.ZodFunction,...U(n)})}},Dr=class extends B{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Dr.create=(t,e)=>new Dr({getter:t,typeName:k.ZodLazy,...U(e)});var zr=class extends B{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:$.invalid_literal,expected:this._def.value}),O}return{status:"valid",value:e.data}}get value(){return this._def.value}};zr.create=(t,e)=>new zr({value:t,typeName:k.ZodLiteral,...U(e)});function $f(t,e){return new Or({values:t,typeName:k.ZodEnum,...U(e)})}var Or=class t extends B{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:J.joinValues(n),received:r.parsedType,code:$.invalid_type}),O}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{received:r.data,code:$.invalid_enum_value,options:n}),O}return Oe(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Or.create=$f;var Mr=class extends B{_parse(e){let r=J.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let o=J.objectValues(r);return T(n,{expected:J.joinValues(o),received:n.parsedType,code:$.invalid_type}),O}if(this._cache||(this._cache=new Set(J.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=J.objectValues(r);return T(n,{received:n.data,code:$.invalid_enum_value,options:o}),O}return Oe(e.data)}get enum(){return this._def.values}};Mr.create=(t,e)=>new Mr({values:t,typeName:k.ZodNativeEnum,...U(e)});var sr=class extends B{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.promise&&r.common.async===!1)return T(r,{code:$.invalid_type,expected:R.promise,received:r.parsedType}),O;let n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return Oe(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};sr.create=(t,e)=>new sr({type:t,typeName:k.ZodPromise,...U(e)});var it=class extends B{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:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{T(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return O;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?O:c.status==="dirty"?$r(c.value):r.value==="dirty"?$r(c.value):c});{if(r.value==="aborted")return O;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?O:a.status==="dirty"?$r(a.value):r.value==="dirty"?$r(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?O:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?O:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!rr(i))return O;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>rr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):O);J.assertNever(o)}};it.create=(t,e,r)=>new it({schema:t,typeName:k.ZodEffects,effect:e,...U(r)});it.createWithPreprocess=(t,e,r)=>new it({schema:e,effect:{type:"preprocess",transform:t},typeName:k.ZodEffects,...U(r)});var ot=class extends B{_parse(e){return this._getType(e)===R.undefined?Oe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ot.create=(t,e)=>new ot({innerType:t,typeName:k.ZodOptional,...U(e)});var Et=class extends B{_parse(e){return this._getType(e)===R.null?Oe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Et.create=(t,e)=>new Et({innerType:t,typeName:k.ZodNullable,...U(e)});var Nr=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Nr.create=(t,e)=>new Nr({innerType:t,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...U(e)});var jr=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return gn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ke(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ke(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};jr.create=(t,e)=>new jr({innerType:t,typeName:k.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...U(e)});var xn=class extends B{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.nan,received:n.parsedType}),O}return{status:"valid",value:e.data}}};xn.create=t=>new xn({typeName:k.ZodNaN,...U(t)});var f$=Symbol("zod_brand"),yo=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},vo=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?O:s.status==="dirty"?(r.dirty(),$r(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?O:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:k.ZodPipeline})}},Lr=class extends B{_parse(e){let r=this._def.innerType._parse(e),n=o=>(rr(o)&&(o.value=Object.freeze(o.value)),o);return gn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Lr.create=(t,e)=>new Lr({innerType:t,typeName:k.ZodReadonly,...U(e)});function bf(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function kf(t,e={},r){return t?or.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=bf(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=bf(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):or.create()}var m$={object:Ge.lazycreate},k;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(k||(k={}));var h$=(t,e={message:`Input not instance of ${t.name}`})=>kf(r=>r instanceof t,e),Pf=nr.create,Tf=kr.create,g$=xn.create,y$=Pr.create,Ef=Tr.create,v$=Er.create,_$=vn.create,b$=Rr.create,w$=Ir.create,x$=or.create,S$=Ut.create,$$=mt.create,k$=_n.create,P$=qt.create,T$=Ge.create,E$=Ge.strictCreate,R$=Ar.create,I$=Qs.create,A$=Cr.create,C$=Tt.create,D$=Xs.create,z$=bn.create,O$=wn.create,M$=ei.create,N$=Dr.create,j$=zr.create,L$=Or.create,F$=Mr.create,Z$=sr.create,U$=it.create,q$=ot.create,V$=Et.create,B$=it.createWithPreprocess,W$=vo.create,H$=()=>Pf().optional(),K$=()=>Tf().optional(),G$=()=>Ef().optional(),J$={string:(t=>nr.create({...t,coerce:!0})),number:(t=>kr.create({...t,coerce:!0})),boolean:(t=>Tr.create({...t,coerce:!0})),bigint:(t=>Pr.create({...t,coerce:!0})),date:(t=>Er.create({...t,coerce:!0}))};var Y$=O;jt();var Q$=h.enum(["read-only","workspace-write","full-auto"]),X$=Q$.default("read-only"),ek=h.object({id:h.string(),type:h.string(),enabled:h.boolean().default(!0),executionPolicy:X$,config:h.record(h.unknown()).default({})}),tk=h.enum(["default-only","auto"]).default("default-only"),rk=h.object({selectionPolicy:tk,locale:h.string().optional(),providers:h.array(ek).min(1,"At least one provider required")});function Vt(t){switch(t){case"ollama":case"gemini-cli":case"codex-cli":return"workspace-write";default:return"read-only"}}function ti(t){return t==="workspace-write"||t==="full-auto"}function nk(t){return Bs.includes(t)}function ok(t){if(t!==void 0)return nk(t)?t:(console.warn(`[config] unknown locale '${t}', falling back to ${xr}`),xr)}function Rf(t){let e=rk.parse(t);return{selectionPolicy:e.selectionPolicy,locale:ok(e.locale),providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}import{mkdirSync as sk}from"fs";import{homedir as ik}from"os";import{dirname as ak,join as If}from"path";var Af="providers.config.json";function _o(){let t=process.env.AGESTRA_CONFIG_PATH;if(t&&t.length>0)return t;let e=process.env.CLAUDE_PLUGIN_ROOT;return e&&e.length>0?If(e,Af):If(ik(),".agestra",Af)}function Cf(t){sk(ak(t),{recursive:!0})}oi();xo();ho();mn();jt();import{mkdirSync as qf,readFileSync as Rt,readdirSync as Wc,existsSync as ir,unlinkSync as Ak,rmdirSync as Ck}from"fs";import{join as ce}from"path";import{spawn as Vf}from"child_process";import{randomUUID as Dk}from"crypto";function Zr(t,e){let r=ce(t,"status.json"),n=JSON.parse(Rt(r,"utf-8"));Ue(r,{...n,...e})}var ai=class{jobsDir;maxJobs;maxAgeDays;submitCount=0;statusCache=new Map;constructor(e=process.cwd(),r){this.jobsDir=ce(e,Xp),qf(this.jobsDir,{recursive:!0}),this.maxJobs=r?.maxJobs??100,this.maxAgeDays=r?.maxAgeDays??7}submit(e){let r=`${e.provider}-${Date.now()}-${Dk().slice(0,6)}`,n=ce(this.jobsDir,r);qf(n,{recursive:!0});let o={id:r,provider:e.provider,prompt:e.prompt,timeout:e.timeout??3e5,createdAt:new Date().toISOString(),cwd:process.cwd()},s={id:r,state:"queued",provider:e.provider};return Ue(ce(n,"job.json"),o),Ue(ce(n,"status.json"),s),se(ce(n,"prompt.txt"),e.prompt),this.statusCache.set(r,s),this.spawnWorker(n),this.submitCount++,this.submitCount%10===0&&this.cleanup(),r}getStatus(e){if(!si(e))return null;let r=["completed","error","timed_out","cancelled","missing_cli"],n=this.statusCache.get(e);if(n&&r.includes(n.state))return n;let o=ce(this.jobsDir,e,"status.json");if(!ir(o))return null;let s=JSON.parse(Rt(o,"utf-8"));if(s.state==="queued"){let i=ce(this.jobsDir,e,"job.json");try{let a=JSON.parse(Rt(i,"utf-8"));if(Date.now()-new Date(a.createdAt).getTime()>6e4){let u={...s,state:"error",completedAt:new Date().toISOString()};return Ue(o,u),se(ce(this.jobsDir,e,"error.txt"),"Job stalled in queued state (worker failed to start)"),this.statusCache.set(e,u),u}}catch{}}return this.statusCache.set(e,s),s}getResult(e){if(!si(e))return null;let r=this.getStatus(e);if(!r)return null;let n=ce(this.jobsDir,e),o={id:e,state:r.state,exitCode:r.exitCode},s=ce(n,"output.txt");ir(s)&&(o.output=Rt(s,"utf-8"));let i=ce(n,"error.txt");return ir(i)&&(o.error=Rt(i,"utf-8")),o}listJobs(){if(!ir(this.jobsDir))return[];let e=Wc(this.jobsDir,{withFileTypes:!0}).filter(n=>n.isDirectory()),r=[];for(let n of e){let o=ce(this.jobsDir,n.name,"status.json");ir(o)&&r.push(JSON.parse(Rt(o,"utf-8")))}return r}cancel(e){if(!si(e))return!1;let r=this.getStatus(e);if(!r||r.state!=="queued"&&r.state!=="running")return!1;r.pid&&pn(r.pid);let n=ce(this.jobsDir,e),o={...r,state:"cancelled",completedAt:new Date().toISOString()};return Ue(ce(n,"status.json"),o),this.statusCache.set(e,o),!0}cleanup(){if(!ir(this.jobsDir))return 0;let e=Wc(this.jobsDir,{withFileTypes:!0}).filter(u=>u.isDirectory()),r=[];for(let u of e){let l=ce(this.jobsDir,u.name,"status.json"),d=ce(this.jobsDir,u.name,"job.json");if(!ir(l))continue;let p=JSON.parse(Rt(l,"utf-8")),f=null;try{f=JSON.parse(Rt(d,"utf-8"))}catch{}r.push({name:u.name,status:p,descriptor:f})}let n=["completed","error","timed_out","cancelled","missing_cli"],o=r.filter(u=>n.includes(u.status.state)).sort((u,l)=>{let d=u.descriptor?.createdAt??"",p=l.descriptor?.createdAt??"";return d.localeCompare(p)}),s=0,i=Date.now(),a=this.maxAgeDays*24*60*60*1e3,c=r.length;for(let u of o){let d=(u.descriptor?.createdAt?i-new Date(u.descriptor.createdAt).getTime():1/0)>a,p=c-s>this.maxJobs;if(!d&&!p)continue;let f=ce(this.jobsDir,u.name);try{let m=Wc(f);for(let g of m)Ak(ce(f,g));Ck(f),this.statusCache.delete(u.name),s++}catch{}}return s}spawnWorker(e){let r=new URL("./job-worker.js",import.meta.url).pathname;if(ir(r)){let n=Vf(process.execPath,[r,e],{detached:!0,stdio:"ignore"});if(n.pid)try{Zr(e,{pid:n.pid})}catch{}n.on("error",o=>{o.code==="ENOENT"?this.runInProcess(e):this.runInProcess(e)}),n.unref()}else this.runInProcess(e)}runInProcess(e){Promise.resolve().then(()=>(Uf(),Zf)).then(({resolveCliConfig:r})=>{let n;try{n=JSON.parse(Rt(ce(e,"job.json"),"utf-8"))}catch{return}let o=r(n);if(!o){Zr(e,{state:"missing_cli",completedAt:new Date().toISOString()}),se(ce(e,"error.txt"),`No CLI mapping for provider: ${n.provider}`);return}let{command:s,buildArgs:i}=o,a=Rt(ce(e,"prompt.txt"),"utf-8"),c=i(a);Zr(e,{state:"running",startedAt:new Date().toISOString()});let u=Lt(s,c),l=Vf(u.command,u.args,{cwd:n.cwd||void 0,stdio:["ignore","pipe","pipe"],windowsHide:!0}),d="",p="",f=0,m=0;l.stdout.on("data",y=>{f+=y.length,f<=10485760&&(d+=y.toString())}),l.stderr.on("data",y=>{m+=y.length,m<=10485760&&(p+=y.toString())});let g=setTimeout(()=>{er(l),se(ce(e,"output.txt"),d),se(ce(e,"error.txt"),p),Zr(e,{state:"timed_out",completedAt:new Date().toISOString()})},n.timeout);l.on("close",y=>{clearTimeout(g),se(ce(e,"output.txt"),d),se(ce(e,"error.txt"),p);let _=d.trim().length>0;Zr(e,{state:y===0||_?"completed":"error",exitCode:y??1,completedAt:new Date().toISOString()})}),l.on("error",y=>{clearTimeout(g);let _=y.code==="ENOENT"?"missing_cli":"error";se(ce(e,"error.txt"),y.message),Zr(e,{state:_,completedAt:new Date().toISOString()})})}).catch(()=>{try{Zr(e,{state:"error",completedAt:new Date().toISOString()}),se(ce(e,"error.txt"),"Failed to load job worker module")}catch{}})}};oi();jt();import{mkdirSync as zk,readdirSync as Bf,readFileSync as Ok,unlinkSync as Mk}from"fs";import{join as So}from"path";function Wf(t){let e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}-${r}-${n}`}function Nk(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function jk(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var ci=class{tracesDir;writer;constructor(e,r){this.tracesDir=So(e,ef),zk(this.tracesDir,{recursive:!0}),this.writer=new ri(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=Wf(new Date(r.timestamp)),o=So(this.tracesDir,`${n}.jsonl`);this.writer.append(o,JSON.stringify(r)+`
|
|
12
|
-
`,"trace")}query(e={}){let r=this.listFiles(e.daysBack),n=[],o=[];for(let i of r){let a=
|
|
13
|
-
`).filter(Boolean);for(let c of a)try{let u=JSON.parse(c);
|
|
14
|
-
`,"audit")}shutdown(){this.writer.destroy()}panicFlush(){this.writer.panicFlush()}getQualityStats(e){let r=this.query({daysBack:e}),n=new Map;for(let s of r){if(!s.quality)continue;let i=`${s.providerId}:${s.task}`,a=n.get(i)??{totalScore:0,count:0,totalLatency:0};a.totalScore+=s.quality.score,a.count+=1,a.totalLatency+=s.latencyMs,n.set(i,a)}let o=new Map;for(let[s,i]of n)o.set(s,{avgScore:i.totalScore/i.count,count:i.count,avgLatencyMs:i.totalLatency/i.count});return o}cleanup(e){let r=new Date;r.setDate(r.getDate()-e);let n=0,o;try{o=
|
|
15
|
-
`),r=[];for(let n=0;n<e.length;n++){let o=e[n];for(let s of
|
|
16
|
-
`);for(let r=0;r<e.length;r++){let n=e[r];for(let o of
|
|
17
|
-
`)}
|
|
18
|
-
`))i.startsWith("worktree ")?n=i.slice(9):i.startsWith("branch refs/heads/")?o=i.slice(18):i===""&&s();return n&&s(),r}cleanOrphans(){let e=this.listOrphans(),r=0;for(let n of e)this.forceRemoveWorktree(n.path),this.gitSafe(["branch","-D",n.branch]),r++;return r}forceRemoveWorktree(e){this.gitSafe(["worktree","remove",e])===null&&this.gitSafe(["worktree","remove","--force",e])===null&&(
|
|
19
|
-
`)}function
|
|
20
|
-
...[truncated]`:s;n.push(`### File: ${o}`),n.push("```"),n.push(i),n.push("```"),n.push("")}catch(s){let i=s instanceof Error?s.message:String(s);n.push(`### File: ${o}`),n.push(`[unavailable: ${i}]`),n.push("")}return r.length>
|
|
21
|
-
`)}var
|
|
12
|
+
deps: ${r}}`};var lz={keyword:"dependencies",type:"object",schemaType:"object",error:Zt.error,code(t){let[e,r]=dz(t);Yb(t,e),Xb(t,r)}};function dz({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function Yb(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Fs.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Fs.checkReportMissingProp)(t,u)}):(r.if((0,ep._)`${c} && (${(0,Fs.checkMissingProp)(t,a,s)})`),(0,Fs.reportMissingProp)(t,s),r.else())}}Zt.validatePropertyDeps=Yb;function Xb(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,uz.alwaysValidSchema)(s,e[a])||(r.if((0,Fs.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Zt.validateSchemaDeps=Xb;Zt.default=lz});var tw=E(tp=>{"use strict";Object.defineProperty(tp,"__esModule",{value:!0});var ew=H(),pz=ie(),fz={message:"property name must be valid",params:({params:t})=>(0,ew._)`{propertyName: ${t.propertyName}}`},mz={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:fz,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,pz.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,ew.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};tp.default=mz});var np=E(rp=>{"use strict";Object.defineProperty(rp,"__esModule",{value:!0});var qa=gt(),Tt=H(),hz=rr(),Va=ie(),gz={message:"must NOT have additional properties",params:({params:t})=>(0,Tt._)`{additionalProperty: ${t.additionalProperty}}`},yz={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:gz,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Va.alwaysValidSchema)(i,r))return;let u=(0,qa.allSchemaProperties)(n.properties),l=(0,qa.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Tt._)`${s} === ${hz.default.errors}`);function d(){e.forIn("key",o,y=>{!u.length&&!l.length?m(y):e.if(p(y),()=>m(y))})}function p(y){let v;if(u.length>8){let S=(0,Va.schemaRefOrVal)(i,n.properties,"properties");v=(0,qa.isOwnProperty)(e,S,y)}else u.length?v=(0,Tt.or)(...u.map(S=>(0,Tt._)`${y} === ${S}`)):v=Tt.nil;return l.length&&(v=(0,Tt.or)(v,...l.map(S=>(0,Tt._)`${(0,qa.usePattern)(t,S)}.test(${y})`))),(0,Tt.not)(v)}function f(y){e.code((0,Tt._)`delete ${o}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Va.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(g(y,v,!1),e.if((0,Tt.not)(v),()=>{t.reset(),f(y)})):(g(y,v),a||e.if((0,Tt.not)(v),()=>e.break()))}}function g(y,v,S){let w={keyword:"additionalProperties",dataProp:y,dataPropType:Va.Type.Str};S===!1&&Object.assign(w,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(w,v)}}};rp.default=yz});var ow=E(sp=>{"use strict";Object.defineProperty(sp,"__esModule",{value:!0});var vz=Ps(),rw=gt(),op=ie(),nw=np(),_z={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&nw.default.code(new vz.KeywordCxt(s,nw.default,"additionalProperties"));let i=(0,rw.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=op.mergeEvaluated.props(e,(0,op.toHash)(i),s.props));let a=i.filter(d=>!(0,op.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,rw.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};sp.default=_z});var cw=E(ip=>{"use strict";Object.defineProperty(ip,"__esModule",{value:!0});var sw=gt(),Ba=H(),iw=ie(),aw=ie(),bz={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,sw.allSchemaProperties)(r),c=a.filter(g=>(0,iw.alwaysValidSchema)(s,r[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Ba.Name)&&(s.props=(0,aw.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let g of a)u&&f(g),s.allErrors?m(g):(e.var(l,!0),m(g),e.if(l))}function f(g){for(let y in u)new RegExp(g).test(y)&&(0,iw.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function m(g){e.forIn("key",n,y=>{e.if((0,Ba._)`${(0,sw.usePattern)(t,g)}.test(${y})`,()=>{let v=c.includes(g);v||t.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:aw.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Ba._)`${d}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,Ba.not)(l),()=>e.break())})})}}};ip.default=bz});var uw=E(ap=>{"use strict";Object.defineProperty(ap,"__esModule",{value:!0});var wz=ie(),xz={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,wz.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};ap.default=xz});var lw=E(cp=>{"use strict";Object.defineProperty(cp,"__esModule",{value:!0});var Sz=gt(),$z={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Sz.validateUnion,error:{message:"must match a schema in anyOf"}};cp.default=$z});var dw=E(up=>{"use strict";Object.defineProperty(up,"__esModule",{value:!0});var Wa=H(),kz=ie(),Pz={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Wa._)`{passingSchemas: ${t.passing}}`},Tz={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Pz,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,kz.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Wa._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Wa._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Wa.Name)})})}}};up.default=Tz});var pw=E(lp=>{"use strict";Object.defineProperty(lp,"__esModule",{value:!0});var Ez=ie(),Rz={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,Ez.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};lp.default=Rz});var hw=E(dp=>{"use strict";Object.defineProperty(dp,"__esModule",{value:!0});var Ha=H(),mw=ie(),Iz={message:({params:t})=>(0,Ha.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ha._)`{failingKeyword: ${t.ifClause}}`},Az={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Iz,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,mw.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=fw(n,"then"),s=fw(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Ha.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Ha._)`${l}`):t.setParams({ifClause:l})}}}};function fw(t,e){let r=t.schema[e];return r!==void 0&&!(0,mw.alwaysValidSchema)(t,r)}dp.default=Az});var gw=E(pp=>{"use strict";Object.defineProperty(pp,"__esModule",{value:!0});var Cz=ie(),Dz={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Cz.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};pp.default=Dz});var yw=E(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});var zz=Gd(),Oz=Hb(),Mz=Jd(),Nz=Gb(),jz=Jb(),Lz=Qb(),Fz=tw(),Zz=np(),Uz=ow(),qz=cw(),Vz=uw(),Bz=lw(),Wz=dw(),Hz=pw(),Kz=hw(),Gz=gw();function Jz(t=!1){let e=[Vz.default,Bz.default,Wz.default,Hz.default,Kz.default,Gz.default,Fz.default,Zz.default,Lz.default,Uz.default,qz.default];return t?e.push(Oz.default,Nz.default):e.push(zz.default,Mz.default),e.push(jz.default),e}fp.default=Jz});var vw=E(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});var Pe=H(),Yz={message:({schemaCode:t})=>(0,Pe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Pe._)`{format: ${t}}`},Xz={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Yz,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),g=r.const("fDef",(0,Pe._)`${m}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,Pe._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>r.assign(y,(0,Pe._)`${g}.type || "string"`).assign(v,(0,Pe._)`${g}.validate`),()=>r.assign(y,(0,Pe._)`"string"`).assign(v,g)),t.fail$data((0,Pe.or)(S(),w()));function S(){return c.strictSchema===!1?Pe.nil:(0,Pe._)`${i} && !${v}`}function w(){let _=l.$async?(0,Pe._)`(${g}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Pe._)`${v}(${n})`,P=(0,Pe._)`(typeof ${v} == "function" ? ${_} : ${v}.test(${n}))`;return(0,Pe._)`${v} && ${v} !== true && ${y} === ${e} && !${P}`}}function f(){let m=d.formats[s];if(!m){S();return}if(m===!0)return;let[g,y,v]=w(m);g===e&&t.pass(_());function S(){if(c.strictSchema===!1){d.logger.warn(P());return}throw new Error(P());function P(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function w(P){let A=P instanceof RegExp?(0,Pe.regexpCode)(P):c.code.formats?(0,Pe._)`${c.code.formats}${(0,Pe.getProperty)(s)}`:void 0,D=r.scopeValue("formats",{key:s,ref:P,code:A});return typeof P=="object"&&!(P instanceof RegExp)?[P.type||"string",P.validate,(0,Pe._)`${D}.validate`]:["string",P,D]}function _(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Pe._)`await ${v}(${n})`}return typeof y=="function"?(0,Pe._)`${v}(${n})`:(0,Pe._)`${v}.test(${n})`}}}};mp.default=Xz});var _w=E(hp=>{"use strict";Object.defineProperty(hp,"__esModule",{value:!0});var Qz=vw(),eO=[Qz.default];hp.default=eO});var bw=E(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.contentVocabulary=ro.metadataVocabulary=void 0;ro.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ro.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var xw=E(gp=>{"use strict";Object.defineProperty(gp,"__esModule",{value:!0});var tO=Rb(),rO=qb(),nO=yw(),oO=_w(),ww=bw(),sO=[tO.default,rO.default,(0,nO.default)(),oO.default,ww.metadataVocabulary,ww.contentVocabulary];gp.default=sO});var $w=E(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.DiscrError=void 0;var Sw;(function(t){t.Tag="tag",t.Mapping="mapping"})(Sw||(Ka.DiscrError=Sw={}))});var Pw=E(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});var no=H(),yp=$w(),kw=Ra(),iO=Ts(),aO=ie(),cO={message:({params:{discrError:t,tagName:e}})=>t===yp.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,no._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},uO={keyword:"discriminator",type:"object",schemaType:"object",error:cO,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,no._)`${r}${(0,no.getProperty)(a)}`);e.if((0,no._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:yp.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,no._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:yp.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),g=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(g,no.Name),m}function p(){var f;let m={},g=v(o),y=!0;for(let _=0;_<i.length;_++){let P=i[_];if(P?.$ref&&!(0,aO.schemaHasRulesButRef)(P,s.self.RULES)){let D=P.$ref;if(P=kw.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,D),P instanceof kw.SchemaEnv&&(P=P.schema),P===void 0)throw new iO.default(s.opts.uriResolver,s.baseId,D)}let A=(f=P?.properties)===null||f===void 0?void 0:f[a];if(typeof A!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||v(P)),S(A,_)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function v({required:_}){return Array.isArray(_)&&_.includes(a)}function S(_,P){if(_.const)w(_.const,P);else if(_.enum)for(let A of _.enum)w(A,P);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function w(_,P){if(typeof _!="string"||_ in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[_]=P}}}};vp.default=uO});var Tw=E((p2,lO)=>{lO.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var bp=E((ye,_p)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var dO=Sb(),pO=xw(),fO=Pw(),Ew=Tw(),mO=["/properties"],Ga="http://json-schema.org/draft-07/schema",oo=class extends dO.default{_addVocabularies(){super._addVocabularies(),pO.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(fO.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Ew,mO):Ew;this.addMetaSchema(e,Ga,!1),this.refs["http://json-schema.org/schema"]=Ga}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ga)?Ga:void 0)}};ye.Ajv=oo;_p.exports=ye=oo;_p.exports.Ajv=oo;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=oo;var hO=Ps();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return hO.KeywordCxt}});var so=H();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return so._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return so.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return so.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return so.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return so.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return so.CodeGen}});var gO=Ta();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return gO.default}});var yO=Ts();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return yO.default}})});var Mw=E(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.formatNames=qt.fastFormats=qt.fullFormats=void 0;function Ut(t,e){return{validate:t,compare:e}}qt.fullFormats={date:Ut(Cw,$p),time:Ut(xp(!0),kp),"date-time":Ut(Rw(!0),zw),"iso-time":Ut(xp(),Dw),"iso-date-time":Ut(Rw(),Ow),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:SO,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|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-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:IO,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:$O,int32:{type:"number",validate:TO},int64:{type:"number",validate:EO},float:{type:"number",validate:Aw},double:{type:"number",validate:Aw},password:!0,binary:!0};qt.fastFormats={...qt.fullFormats,date:Ut(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,$p),time:Ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,kp),"date-time":Ut(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,zw),"iso-time":Ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Dw),"iso-date-time":Ut(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Ow),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};qt.formatNames=Object.keys(qt.fullFormats);function vO(t){return t%4===0&&(t%100!==0||t%400===0)}var _O=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,bO=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Cw(t){let e=_O.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&vO(r)?29:bO[n])}function $p(t,e){if(t&&e)return t>e?1:t<e?-1:0}var wp=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function xp(t){return function(r){let n=wp.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function kp(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function Dw(t,e){if(!(t&&e))return;let r=wp.exec(t),n=wp.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Sp=/t|\s/i;function Rw(t){let e=xp(t);return function(n){let o=n.split(Sp);return o.length===2&&Cw(o[0])&&e(o[1])}}function zw(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Ow(t,e){if(!(t&&e))return;let[r,n]=t.split(Sp),[o,s]=e.split(Sp),i=$p(r,o);if(i!==void 0)return i||kp(n,s)}var wO=/\/|:/,xO=/^(?:[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 SO(t){return wO.test(t)&&xO.test(t)}var Iw=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function $O(t){return Iw.lastIndex=0,Iw.test(t)}var kO=-(2**31),PO=2**31-1;function TO(t){return Number.isInteger(t)&&t<=PO&&t>=kO}function EO(t){return Number.isInteger(t)}function Aw(){return!0}var RO=/[^\\]\\Z/;function IO(t){if(RO.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Nw=E(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.formatLimitDefinition=void 0;var AO=bp(),Et=H(),kr=Et.operators,Ja={formatMaximum:{okStr:"<=",ok:kr.LTE,fail:kr.GT},formatMinimum:{okStr:">=",ok:kr.GTE,fail:kr.LT},formatExclusiveMaximum:{okStr:"<",ok:kr.LT,fail:kr.GTE},formatExclusiveMinimum:{okStr:">",ok:kr.GT,fail:kr.LTE}},CO={message:({keyword:t,schemaCode:e})=>(0,Et.str)`should be ${Ja[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Et._)`{comparison: ${Ja[t].okStr}, limit: ${e}}`};io.formatLimitDefinition={keyword:Object.keys(Ja),type:"string",schemaType:"string",$data:!0,error:CO,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new AO.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,Et._)`${p}[${c.schemaCode}]`);t.fail$data((0,Et.or)((0,Et._)`typeof ${f} != "object"`,(0,Et._)`${f} instanceof RegExp`,(0,Et._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,Et._)`${i.code.formats}${(0,Et.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,Et._)`${p}.compare(${r}, ${n}) ${Ja[o].fail} 0`}},dependencies:["format"]};var DO=t=>(t.addKeyword(io.formatLimitDefinition),t);io.default=DO});var Zw=E((Zs,Fw)=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});var ao=Mw(),zO=Nw(),Pp=H(),jw=new Pp.Name("fullFormats"),OO=new Pp.Name("fastFormats"),Tp=(t,e={keywords:!0})=>{if(Array.isArray(e))return Lw(t,e,ao.fullFormats,jw),t;let[r,n]=e.mode==="fast"?[ao.fastFormats,OO]:[ao.fullFormats,jw],o=e.formats||ao.formatNames;return Lw(t,o,r,n),e.keywords&&(0,zO.default)(t),t};Tp.get=(t,e="full")=>{let n=(e==="fast"?ao.fastFormats:ao.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Lw(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Pp._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Fw.exports=Zs=Tp;Object.defineProperty(Zs,"__esModule",{value:!0});Zs.default=Tp});import{readFileSync as Vj}from"fs";import{join as uf}from"path";import{fileURLToPath as Bj}from"url";var mn=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},Ws=class extends mn{code="PROVIDER_NOT_FOUND";retryable=!1;constructor(e){super(e,`Provider not found: ${e}`)}},de=class extends mn{code="PROVIDER_UNAVAILABLE";retryable=!1;constructor(e,r){super(e,`Provider unavailable: ${r||"not installed or not running"}`)}};var hn=class extends mn{timeoutMs;code="PROVIDER_TIMEOUT";retryable=!0;constructor(e,r){super(e,`Timeout after ${r}ms`),this.timeoutMs=r}},We=class extends mn{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(e,r){super(e,`Execution error: ${r}`)}};var If={ollama:{tier:"tool"},"claude-cli":{tier:"agent",maxComplexity:"complex"},"gemini-cli":{tier:"agent",maxComplexity:"complex"},"codex-cli":{tier:"agent",maxComplexity:"complex"},"claude-host":{tier:"agent",maxComplexity:"complex"},"codex-host":{tier:"agent",maxComplexity:"complex"},"gemini-host":{tier:"agent",maxComplexity:"complex"}},e$={ollama:{invocation:"http",roles:["participant","tool"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"claude-cli":{invocation:"cli",roles:["participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"gemini-cli":{invocation:"cli",roles:["leader","participant","reviewer","worker"],supportsAutonomousExecution:!0,supportsReadOnlyChat:!0},"codex-cli":{invocation:"cli",roles:["leader","participant","reviewer","worker"],supportsAutonomousExecution:!0,supportsReadOnlyChat:!0},"claude-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"codex-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0},"gemini-host":{invocation:"host-bridge",roles:["leader","participant","reviewer"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0}};function Uc(t){return t<3?"simple":t<8?"moderate":t<=20?"complex":"advanced"}function Js(t,e,r,n=t){let o=If[n]??If[t]??{},s=o.maxComplexity??"simple";return n==="ollama"&&r!==void 0&&(s=Uc(r)),{providerId:t,tier:o.tier??"tool",strengths:o.strengths??e.strengths,maxComplexity:s}}function ir(t,e){let r=e$[t.type],n=r?.roles?[...r.roles]:["participant"];return{id:t.id,type:t.type,invocation:r?.invocation??"unknown",roles:n,supportsAutonomousExecution:r?.supportsAutonomousExecution??!1,supportsReadOnlyChat:r?.supportsReadOnlyChat??!0,supportsToolUse:e?.supportsToolUse??r?.supportsToolUse??!1}}var Ys={low:0,medium:.5,high:.7},t$={chat:"low",simple_review:"low",code_review:"medium",code_generation:"medium",design:"medium",writing:"medium",analysis:"medium",ideation:"medium",debate_turn:"medium",architecture:"high",cross_validate:"high",complex_refactor:"high"};function Af(t,e){return e?.[t]??t$[t]??"low"}function Xs(t,e,r=Ys){return t>=r[e]}var Qs=class{providers=new Map;resolveProvider(e){let r=this.providers.get(e);if(r)return r;if(e==="claude")return this.resolveClaudeAlias()}resolveClaudeAlias(){let e,r;for(let n of this.providers.values())n.type==="claude-host"?e=e??n:n.type==="claude-cli"&&(r=r??n);return e??r}register(e){this.providers.set(e.id,e)}get(e){let r=this.resolveProvider(e);if(!r)throw new Ws(e);return r}getAll(){return[...this.providers.values()]}getAvailable(){return this.getAll().filter(e=>e.isAvailable())}getAvailableDescriptors(){return this.getAvailable().map(e=>this.getDescriptor(e.id))}getByCapability(e){return this.getAvailable().filter(r=>r.getCapabilities().strengths.includes(e))}has(e){return this.providers.has(e)}getCapability(e){let r=this.get(e);return Js(r.id,r.getCapabilities(),void 0,r.type)}getDescriptor(e){let r=this.get(e);return r.getDescriptor?.()??ir(r,r.getCapabilities())}getByTier(e){return this.getAvailable().filter(r=>this.getCapability(r.id).tier===e)}getByRole(e){return this.getAvailable().filter(r=>this.getDescriptor(r.id).roles.includes(e))}getBestForTask(e,r,n,o){let s=this.getAvailable();if(s.length===0)return;if(!r)return s[0];let i=n??Af(e),a=r.getQualityStats(30),c=new Map;for(let[p,f]of a){let m=p.split(":")[0],g=c.get(m)??{totalScore:0,count:0};g.totalScore+=f.avgScore*f.count,g.count+=f.count,c.set(m,g)}let u=s.filter(p=>{let f=c.get(p.id);if(!f)return i==="low";let m=f.totalScore/f.count;return Xs(m,i,o)});if(u.length===0)return;let l,d=-1;for(let p of u){let f=`${p.id}:${e}`,m=a.get(f);m&&m.avgScore>d&&(d=m.avgScore,l=p)}return l??u[0]}};var h={};Be(h,{BRAND:()=>T$,DIRTY:()=>Ir,EMPTY_PATH:()=>s$,INVALID:()=>N,NEVER:()=>dk,OK:()=>Ne,ParseStatus:()=>Ie,Schema:()=>B,ZodAny:()=>ur,ZodArray:()=>Gt,ZodBigInt:()=>Cr,ZodBoolean:()=>Dr,ZodBranded:()=>So,ZodCatch:()=>Vr,ZodDate:()=>zr,ZodDefault:()=>qr,ZodDiscriminatedUnion:()=>ri,ZodEffects:()=>lt,ZodEnum:()=>Zr,ZodError:()=>Ye,ZodFirstPartyTypeKind:()=>k,ZodFunction:()=>oi,ZodIntersection:()=>jr,ZodIssueCode:()=>$,ZodLazy:()=>Lr,ZodLiteral:()=>Fr,ZodMap:()=>Pn,ZodNaN:()=>En,ZodNativeEnum:()=>Ur,ZodNever:()=>bt,ZodNull:()=>Mr,ZodNullable:()=>zt,ZodNumber:()=>Ar,ZodObject:()=>Xe,ZodOptional:()=>ct,ZodParsedType:()=>R,ZodPipeline:()=>$o,ZodPromise:()=>lr,ZodReadonly:()=>Br,ZodRecord:()=>ni,ZodSchema:()=>B,ZodSet:()=>Tn,ZodString:()=>cr,ZodSymbol:()=>$n,ZodTransformer:()=>lt,ZodTuple:()=>Dt,ZodType:()=>B,ZodUndefined:()=>Or,ZodUnion:()=>Nr,ZodUnknown:()=>Kt,ZodVoid:()=>kn,addIssueToContext:()=>T,any:()=>M$,array:()=>F$,bigint:()=>A$,boolean:()=>Uf,coerce:()=>lk,custom:()=>Lf,date:()=>C$,datetimeRegex:()=>Nf,defaultErrorMap:()=>Wt,discriminatedUnion:()=>V$,effect:()=>rk,enum:()=>Q$,function:()=>J$,getErrorMap:()=>wn,getParsedType:()=>Ct,instanceof:()=>R$,intersection:()=>B$,isAborted:()=>ei,isAsync:()=>xn,isDirty:()=>ti,isValid:()=>ar,late:()=>E$,lazy:()=>Y$,literal:()=>X$,makeIssue:()=>xo,map:()=>K$,nan:()=>I$,nativeEnum:()=>ek,never:()=>j$,null:()=>O$,nullable:()=>ok,number:()=>Zf,object:()=>Z$,objectUtil:()=>qc,oboolean:()=>uk,onumber:()=>ck,optional:()=>nk,ostring:()=>ak,pipeline:()=>ik,preprocess:()=>sk,promise:()=>tk,quotelessJson:()=>r$,record:()=>H$,set:()=>G$,setErrorMap:()=>o$,strictObject:()=>U$,string:()=>Ff,symbol:()=>D$,transformer:()=>rk,tuple:()=>W$,undefined:()=>z$,union:()=>q$,unknown:()=>N$,util:()=>Y,void:()=>L$});var Y;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(Y||(Y={}));var qc;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(qc||(qc={}));var R=Y.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ct=t=>{switch(typeof t){case"undefined":return R.undefined;case"string":return R.string;case"number":return Number.isNaN(t)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":return Array.isArray(t)?R.array:t===null?R.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?R.promise:typeof Map<"u"&&t instanceof Map?R.map:typeof Set<"u"&&t instanceof Set?R.set:typeof Date<"u"&&t instanceof Date?R.date:R.object;default:return R.unknown}};var $=Y.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"]),r$=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ye=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Y.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ye.create=t=>new Ye(t);var n$=(t,e)=>{let r;switch(t.code){case $.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case $.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,Y.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:r=`Unrecognized key(s) in object: ${Y.joinValues(t.keys,", ")}`;break;case $.invalid_union:r="Invalid input";break;case $.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Y.joinValues(t.options)}`;break;case $.invalid_enum_value:r=`Invalid enum value. Expected ${Y.joinValues(t.options)}, received '${t.received}'`;break;case $.invalid_arguments:r="Invalid function arguments";break;case $.invalid_return_type:r="Invalid function return type";break;case $.invalid_date:r="Invalid date";break;case $.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:Y.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case $.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case $.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case $.custom:r="Invalid input";break;case $.invalid_intersection_types:r="Intersection results could not be merged";break;case $.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case $.not_finite:r="Number must be finite";break;default:r=e.defaultError,Y.assertNever(t)}return{message:r}},Wt=n$;var Cf=Wt;function o$(t){Cf=t}function wn(){return Cf}var xo=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},s$=[];function T(t,e){let r=wn(),n=xo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Wt?void 0:Wt].filter(o=>!!o)});t.common.issues.push(n)}var Ie=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return N;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return N;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},N=Object.freeze({status:"aborted"}),Ir=t=>({status:"dirty",value:t}),Ne=t=>({status:"valid",value:t}),ei=t=>t.status==="aborted",ti=t=>t.status==="dirty",ar=t=>t.status==="valid",xn=t=>typeof Promise<"u"&&t instanceof Promise;var C;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(C||(C={}));var ut=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}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}},Df=(t,e)=>{if(ar(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Ye(t.common.issues);return this._error=r,this._error}}};function Z(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var B=class{get description(){return this._def.description}_getType(e){return Ct(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ie,ctx:{common:e.parent.common,data:e.data,parsedType:Ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(xn(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ct(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Df(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ct(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return ar(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>ar(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ct(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(xn(o)?o:Promise.resolve(o));return Df(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:$.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new lt({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:r=>this["~validate"](r)}}optional(){return ct.create(this,this._def)}nullable(){return zt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Gt.create(this)}promise(){return lr.create(this,this._def)}or(e){return Nr.create([this,e],this._def)}and(e){return jr.create(this,e,this._def)}transform(e){return new lt({...Z(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new qr({...Z(this._def),innerType:this,defaultValue:r,typeName:k.ZodDefault})}brand(){return new So({typeName:k.ZodBranded,type:this,...Z(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Vr({...Z(this._def),innerType:this,catchValue:r,typeName:k.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return $o.create(this,e)}readonly(){return Br.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},i$=/^c[^\s-]{8,}$/i,a$=/^[0-9a-z]+$/,c$=/^[0-9A-HJKMNP-TV-Z]{26}$/i,u$=/^[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,l$=/^[a-z0-9_-]{21}$/i,d$=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,p$=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,f$=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,m$="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Vc,h$=/^(?:(?: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])$/,g$=/^(?:(?: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])$/,y$=/^(([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]))$/,v$=/^(([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])$/,_$=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,b$=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Of="((\\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])))",w$=new RegExp(`^${Of}$`);function Mf(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function x$(t){return new RegExp(`^${Mf(t)}$`)}function Nf(t){let e=`${Of}T${Mf(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function S$(t,e){return!!((e==="v4"||!e)&&h$.test(t)||(e==="v6"||!e)&&y$.test(t))}function $$(t,e){if(!d$.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function k$(t,e){return!!((e==="v4"||!e)&&g$.test(t)||(e==="v6"||!e)&&v$.test(t))}var cr=class t extends B{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.string,received:s.parsedType}),N}let n=new Ie,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?T(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&T(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")f$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"email",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Vc||(Vc=new RegExp(m$,"u")),Vc.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"emoji",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")u$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"uuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")l$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"nanoid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")i$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")a$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cuid2",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")c$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ulid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),T(o,{validation:"url",code:$.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"regex",code:$.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Nf(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?w$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?x$(s).test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{code:$.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?p$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"duration",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?S$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"ip",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?$$(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"jwt",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?k$(e.data,s.version)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"cidr",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?_$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?b$.test(e.data)||(o=this._getOrReturnCtx(e,o),T(o,{validation:"base64url",code:$.invalid_string,message:s.message}),n.dirty()):Y.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:$.invalid_string,...C.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...C.errToObj(e)})}url(e){return this._addCheck({kind:"url",...C.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...C.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...C.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...C.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...C.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...C.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...C.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...C.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...C.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...C.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...C.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...C.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:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...C.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:typeof e?.precision>"u"?null:e?.precision,...C.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...C.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...C.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...C.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...C.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...C.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...C.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...C.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...C.errToObj(r)})}nonempty(e){return this.min(1,C.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};cr.create=t=>new cr({checks:[],typeName:k.ZodString,coerce:t?.coerce??!1,...Z(t)});function P$(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var Ar=class t extends B{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)!==R.number){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.number,received:s.parsedType}),N}let n,o=new Ie;for(let s of this._def.checks)s.kind==="int"?Y.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:$.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?P$(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_finite,message:s.message}),o.dirty()):Y.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,C.toString(r))}gt(e,r){return this.setLimit("min",e,!1,C.toString(r))}lte(e,r){return this.setLimit("max",e,!0,C.toString(r))}lt(e,r){return this.setLimit("max",e,!1,C.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:C.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:C.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:C.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Y.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Ar.create=t=>new Ar({checks:[],typeName:k.ZodNumber,coerce:t?.coerce||!1,...Z(t)});var Cr=class t extends B{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)!==R.bigint)return this._getInvalidInput(e);let n,o=new Ie;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),T(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):Y.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return T(r,{code:$.invalid_type,expected:R.bigint,received:r.parsedType}),N}gte(e,r){return this.setLimit("min",e,!0,C.toString(r))}gt(e,r){return this.setLimit("min",e,!1,C.toString(r))}lte(e,r){return this.setLimit("max",e,!0,C.toString(r))}lt(e,r){return this.setLimit("max",e,!1,C.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:C.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Cr.create=t=>new Cr({checks:[],typeName:k.ZodBigInt,coerce:t?.coerce??!1,...Z(t)});var Dr=class extends B{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.boolean,received:n.parsedType}),N}return Ne(e.data)}};Dr.create=t=>new Dr({typeName:k.ZodBoolean,coerce:t?.coerce||!1,...Z(t)});var zr=class t extends B{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_type,expected:R.date,received:s.parsedType}),N}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return T(s,{code:$.invalid_date}),N}let n=new Ie,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),T(o,{code:$.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):Y.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:C.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:C.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};zr.create=t=>new zr({checks:[],coerce:t?.coerce||!1,typeName:k.ZodDate,...Z(t)});var $n=class extends B{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.symbol,received:n.parsedType}),N}return Ne(e.data)}};$n.create=t=>new $n({typeName:k.ZodSymbol,...Z(t)});var Or=class extends B{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.undefined,received:n.parsedType}),N}return Ne(e.data)}};Or.create=t=>new Or({typeName:k.ZodUndefined,...Z(t)});var Mr=class extends B{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.null,received:n.parsedType}),N}return Ne(e.data)}};Mr.create=t=>new Mr({typeName:k.ZodNull,...Z(t)});var ur=class extends B{constructor(){super(...arguments),this._any=!0}_parse(e){return Ne(e.data)}};ur.create=t=>new ur({typeName:k.ZodAny,...Z(t)});var Kt=class extends B{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ne(e.data)}};Kt.create=t=>new Kt({typeName:k.ZodUnknown,...Z(t)});var bt=class extends B{_parse(e){let r=this._getOrReturnCtx(e);return T(r,{code:$.invalid_type,expected:R.never,received:r.parsedType}),N}};bt.create=t=>new bt({typeName:k.ZodNever,...Z(t)});var kn=class extends B{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.void,received:n.parsedType}),N}return Ne(e.data)}};kn.create=t=>new kn({typeName:k.ZodVoid,...Z(t)});var Gt=class t extends B{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==R.array)return T(r,{code:$.invalid_type,expected:R.array,received:r.parsedType}),N;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(T(r,{code:i?$.too_big:$.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(T(r,{code:$.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(T(r,{code:$.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new ut(r,i,r.path,a)))).then(i=>Ie.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new ut(r,i,r.path,a)));return Ie.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:C.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:C.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:C.toString(r)}})}nonempty(e){return this.min(1,e)}};Gt.create=(t,e)=>new Gt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...Z(e)});function Sn(t){if(t instanceof Xe){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ct.create(Sn(n))}return new Xe({...t._def,shape:()=>e})}else return t instanceof Gt?new Gt({...t._def,type:Sn(t.element)}):t instanceof ct?ct.create(Sn(t.unwrap())):t instanceof zt?zt.create(Sn(t.unwrap())):t instanceof Dt?Dt.create(t.items.map(e=>Sn(e))):t}var Xe=class t extends B{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(),r=Y.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==R.object){let u=this._getOrReturnCtx(e);return T(u,{code:$.invalid_type,expected:R.object,received:u.parsedType}),N}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof bt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ut(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof bt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(T(o,{code:$.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ut(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>Ie.mergeObjectSync(n,u)):Ie.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return C.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:C.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:k.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of Y.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of Y.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Sn(this)}partial(e){let r={};for(let n of Y.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of Y.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof ct;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return jf(Y.objectKeys(this.shape))}};Xe.create=(t,e)=>new Xe({shape:()=>t,unknownKeys:"strip",catchall:bt.create(),typeName:k.ZodObject,...Z(e)});Xe.strictCreate=(t,e)=>new Xe({shape:()=>t,unknownKeys:"strict",catchall:bt.create(),typeName:k.ZodObject,...Z(e)});Xe.lazycreate=(t,e)=>new Xe({shape:t,unknownKeys:"strip",catchall:bt.create(),typeName:k.ZodObject,...Z(e)});var Nr=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ye(a.ctx.common.issues));return T(r,{code:$.invalid_union,unionErrors:i}),N}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ye(c));return T(r,{code:$.invalid_union,unionErrors:a}),N}}get options(){return this._def.options}};Nr.create=(t,e)=>new Nr({options:t,typeName:k.ZodUnion,...Z(e)});var Ht=t=>t instanceof Lr?Ht(t.schema):t instanceof lt?Ht(t.innerType()):t instanceof Fr?[t.value]:t instanceof Zr?t.options:t instanceof Ur?Y.objectValues(t.enum):t instanceof qr?Ht(t._def.innerType):t instanceof Or?[void 0]:t instanceof Mr?[null]:t instanceof ct?[void 0,...Ht(t.unwrap())]:t instanceof zt?[null,...Ht(t.unwrap())]:t instanceof So||t instanceof Br?Ht(t.unwrap()):t instanceof Vr?Ht(t._def.innerType):[],ri=class t extends B{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.object)return T(r,{code:$.invalid_type,expected:R.object,received:r.parsedType}),N;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(T(r,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),N)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Ht(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:k.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...Z(n)})}};function Bc(t,e){let r=Ct(t),n=Ct(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.object){let o=Y.objectKeys(e),s=Y.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Bc(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===R.array&&n===R.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Bc(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===R.date&&n===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var jr=class extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(ei(s)||ei(i))return N;let a=Bc(s.value,i.value);return a.valid?((ti(s)||ti(i))&&r.dirty(),{status:r.value,value:a.data}):(T(n,{code:$.invalid_intersection_types}),N)};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(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};jr.create=(t,e,r)=>new jr({left:t,right:e,typeName:k.ZodIntersection,...Z(r)});var Dt=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return T(n,{code:$.invalid_type,expected:R.array,received:n.parsedType}),N;if(n.data.length<this._def.items.length)return T(n,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),N;!this._def.rest&&n.data.length>this._def.items.length&&(T(n,{code:$.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ut(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Ie.mergeArray(r,i)):Ie.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Dt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dt({items:t,typeName:k.ZodTuple,rest:null,...Z(e)})};var ni=class t extends B{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.object)return T(n,{code:$.invalid_type,expected:R.object,received:n.parsedType}),N;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new ut(n,a,n.path,a)),value:i._parse(new ut(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ie.mergeObjectAsync(r,o):Ie.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof B?new t({keyType:e,valueType:r,typeName:k.ZodRecord,...Z(n)}):new t({keyType:cr.create(),valueType:e,typeName:k.ZodRecord,...Z(r)})}},Pn=class extends B{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.map)return T(n,{code:$.invalid_type,expected:R.map,received:n.parsedType}),N;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new ut(n,a,n.path,[u,"key"])),value:s._parse(new ut(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return N;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return N;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Pn.create=(t,e,r)=>new Pn({valueType:e,keyType:t,typeName:k.ZodMap,...Z(r)});var Tn=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return T(n,{code:$.invalid_type,expected:R.set,received:n.parsedType}),N;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(T(n,{code:$.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(T(n,{code:$.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return N;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new ut(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:C.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:C.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Tn.create=(t,e)=>new Tn({valueType:t,minSize:null,maxSize:null,typeName:k.ZodSet,...Z(e)});var oi=class t extends B{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.function)return T(r,{code:$.invalid_type,expected:R.function,received:r.parsedType}),N;function n(a,c){return xo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,wn(),Wt].filter(u=>!!u),issueData:{code:$.invalid_arguments,argumentsError:c}})}function o(a,c){return xo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,wn(),Wt].filter(u=>!!u),issueData:{code:$.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof lr){let a=this;return Ne(async function(...c){let u=new Ye([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(o(d,f)),u})})}else{let a=this;return Ne(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new Ye([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new Ye([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Dt.create(e).rest(Kt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Dt.create([]).rest(Kt.create()),returns:r||Kt.create(),typeName:k.ZodFunction,...Z(n)})}},Lr=class extends B{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Lr.create=(t,e)=>new Lr({getter:t,typeName:k.ZodLazy,...Z(e)});var Fr=class extends B{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return T(r,{received:r.data,code:$.invalid_literal,expected:this._def.value}),N}return{status:"valid",value:e.data}}get value(){return this._def.value}};Fr.create=(t,e)=>new Fr({value:t,typeName:k.ZodLiteral,...Z(e)});function jf(t,e){return new Zr({values:t,typeName:k.ZodEnum,...Z(e)})}var Zr=class t extends B{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{expected:Y.joinValues(n),received:r.parsedType,code:$.invalid_type}),N}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return T(r,{received:r.data,code:$.invalid_enum_value,options:n}),N}return Ne(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Zr.create=jf;var Ur=class extends B{_parse(e){let r=Y.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let o=Y.objectValues(r);return T(n,{expected:Y.joinValues(o),received:n.parsedType,code:$.invalid_type}),N}if(this._cache||(this._cache=new Set(Y.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=Y.objectValues(r);return T(n,{received:n.data,code:$.invalid_enum_value,options:o}),N}return Ne(e.data)}get enum(){return this._def.values}};Ur.create=(t,e)=>new Ur({values:t,typeName:k.ZodNativeEnum,...Z(e)});var lr=class extends B{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.promise&&r.common.async===!1)return T(r,{code:$.invalid_type,expected:R.promise,received:r.parsedType}),N;let n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return Ne(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};lr.create=(t,e)=>new lr({type:t,typeName:k.ZodPromise,...Z(e)});var lt=class extends B{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:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{T(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return N;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?N:c.status==="dirty"?Ir(c.value):r.value==="dirty"?Ir(c.value):c});{if(r.value==="aborted")return N;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?N:a.status==="dirty"?Ir(a.value):r.value==="dirty"?Ir(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?N:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?N:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ar(i))return N;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>ar(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):N);Y.assertNever(o)}};lt.create=(t,e,r)=>new lt({schema:t,typeName:k.ZodEffects,effect:e,...Z(r)});lt.createWithPreprocess=(t,e,r)=>new lt({schema:e,effect:{type:"preprocess",transform:t},typeName:k.ZodEffects,...Z(r)});var ct=class extends B{_parse(e){return this._getType(e)===R.undefined?Ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ct.create=(t,e)=>new ct({innerType:t,typeName:k.ZodOptional,...Z(e)});var zt=class extends B{_parse(e){return this._getType(e)===R.null?Ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zt.create=(t,e)=>new zt({innerType:t,typeName:k.ZodNullable,...Z(e)});var qr=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===R.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};qr.create=(t,e)=>new qr({innerType:t,typeName:k.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Z(e)});var Vr=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return xn(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ye(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ye(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Vr.create=(t,e)=>new Vr({innerType:t,typeName:k.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Z(e)});var En=class extends B{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return T(n,{code:$.invalid_type,expected:R.nan,received:n.parsedType}),N}return{status:"valid",value:e.data}}};En.create=t=>new En({typeName:k.ZodNaN,...Z(t)});var T$=Symbol("zod_brand"),So=class extends B{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},$o=class t extends B{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?N:s.status==="dirty"?(r.dirty(),Ir(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?N:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:k.ZodPipeline})}},Br=class extends B{_parse(e){let r=this._def.innerType._parse(e),n=o=>(ar(o)&&(o.value=Object.freeze(o.value)),o);return xn(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Br.create=(t,e)=>new Br({innerType:t,typeName:k.ZodReadonly,...Z(e)});function zf(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Lf(t,e={},r){return t?ur.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=zf(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=zf(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):ur.create()}var E$={object:Xe.lazycreate},k;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(k||(k={}));var R$=(t,e={message:`Input not instance of ${t.name}`})=>Lf(r=>r instanceof t,e),Ff=cr.create,Zf=Ar.create,I$=En.create,A$=Cr.create,Uf=Dr.create,C$=zr.create,D$=$n.create,z$=Or.create,O$=Mr.create,M$=ur.create,N$=Kt.create,j$=bt.create,L$=kn.create,F$=Gt.create,Z$=Xe.create,U$=Xe.strictCreate,q$=Nr.create,V$=ri.create,B$=jr.create,W$=Dt.create,H$=ni.create,K$=Pn.create,G$=Tn.create,J$=oi.create,Y$=Lr.create,X$=Fr.create,Q$=Zr.create,ek=Ur.create,tk=lr.create,rk=lt.create,nk=ct.create,ok=zt.create,sk=lt.createWithPreprocess,ik=$o.create,ak=()=>Ff().optional(),ck=()=>Zf().optional(),uk=()=>Uf().optional(),lk={string:(t=>cr.create({...t,coerce:!0})),number:(t=>Ar.create({...t,coerce:!0})),boolean:(t=>Dr.create({...t,coerce:!0})),bigint:(t=>Cr.create({...t,coerce:!0})),date:(t=>zr.create({...t,coerce:!0}))};var dk=N;Vt();var pk=h.enum(["read-only","workspace-write","full-auto"]),fk=pk.default("read-only"),mk=h.object({id:h.string(),type:h.string(),enabled:h.boolean().default(!0),executionPolicy:fk,config:h.record(h.unknown()).default({})}),hk=h.enum(["default-only","auto"]).default("default-only"),gk=h.object({selectionPolicy:hk,locale:h.string().optional(),providers:h.array(mk).min(1,"At least one provider required")});function Jt(t){switch(t){case"ollama":case"gemini-cli":case"codex-cli":case"claude-cli":return"workspace-write";default:return"read-only"}}function si(t){return t==="workspace-write"||t==="full-auto"}function yk(t){return Gs.includes(t)}function vk(t){if(t!==void 0)return yk(t)?t:(console.warn(`[config] unknown locale '${t}', falling back to ${Er}`),Er)}function qf(t){let e=gk.parse(t);return{selectionPolicy:e.selectionPolicy,locale:vk(e.locale),providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}import{mkdirSync as _k}from"fs";import{homedir as bk}from"os";import{dirname as wk,join as Vf}from"path";var Bf="providers.config.json";function ko(){let t=process.env.AGESTRA_CONFIG_PATH;if(t&&t.length>0)return t;let e=process.env.CLAUDE_PLUGIN_ROOT;return e&&e.length>0?Vf(e,Bf):Vf(bk(),".agestra",Bf)}function Wf(t){_k(wk(t),{recursive:!0})}ci();Jc();Eo();wo();bn();Vt();import{mkdirSync as om,readFileSync as Ee,readdirSync as Ro,existsSync as Fe,unlinkSync as e0,rmdirSync as t0}from"fs";import{join as X}from"path";import{spawn as sm}from"child_process";import{randomUUID as r0}from"crypto";var n0=5e3,nu=["completed","error","timed_out","cancelled","missing_cli"];function Ot(t,e){let r=X(t,"status.json"),n=`${r}.lock`;Wr(n,()=>{let o=JSON.parse(Ee(r,"utf-8"));je(r,{...o,...e})})}var li=class{jobsDir;workspaceDir;maxJobs;maxAgeDays;submitCount=0;statusCache=new Map;completionHandler;saveInFlight=new Map;deferredSaveTimers=new Map;constructor(e=process.cwd(),r){this.workspaceDir=e,this.jobsDir=X(e,mf),om(this.jobsDir,{recursive:!0}),this.maxJobs=r?.maxJobs??100,this.maxAgeDays=r?.maxAgeDays??7,this.completionHandler=r?.completionHandler,this.submitCount=this.countExistingJobs()}countExistingJobs(){if(!Fe(this.jobsDir))return 0;try{return Ro(this.jobsDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).length}catch{return 0}}reconcileOrphans(){let e=0,r;try{r=Ro(this.jobsDir)}catch{return 0}for(let n of r){if(!dr(n))continue;let o=X(this.jobsDir,n,"status.json");if(!Fe(o))continue;let s;try{s=JSON.parse(Ee(o,"utf-8"))}catch{continue}if(s.state!=="running"||s.pid!==void 0&&this.isPidAlive(s.pid))continue;let i=`${o}.lock`;try{let a=Wr(i,()=>{let c=JSON.parse(Ee(o,"utf-8"));if(c.state!=="running"||c.pid!==void 0&&this.isPidAlive(c.pid))return null;let u={...c,state:"error",completedAt:new Date().toISOString()};return je(o,u),u});if(!a)continue;oe(X(this.jobsDir,n,"error.txt"),"orphaned (worker process died before completion)"),this.statusCache.set(n,a),e++}catch{}}return e}resolveCreatedAtMs(e){let r=X(this.jobsDir,e,"job.json");try{let o=JSON.parse(Ee(r,"utf-8")),s=new Date(o.createdAt).getTime();if(Number.isFinite(s))return s}catch{}let n=e.split("-");for(let o=n.length-2;o>=0;o--)if(/^\d+$/.test(n[o])){let s=Number(n[o]);if(Number.isFinite(s)&&s>0)return s}return null}isPidAlive(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}submit(e){let r=`${e.provider}-${Date.now()}-${r0().slice(0,6)}`,n=X(this.jobsDir,r);om(n,{recursive:!0});let o=e.timeout??3e5,s={id:r,provider:e.provider,prompt:e.prompt,timeout:o,createdAt:new Date().toISOString(),cwd:this.workspaceDir,saveAsDocument:e.saveAsDocument},i={id:r,state:"queued",provider:e.provider};if(je(X(n,"job.json"),s),je(X(n,"status.json"),i),oe(X(n,"prompt.txt"),e.prompt),this.statusCache.set(r,i),this.spawnWorker(n),e.saveAsDocument&&this.completionHandler){let a=setTimeout(()=>{this.deferredSaveTimers.delete(r),this.maybeTriggerCompletionSave(r).catch(()=>{})},o+n0);a.unref?.(),this.deferredSaveTimers.set(r,a)}return this.submitCount++,this.submitCount%10===0&&this.cleanup(),r}getStatus(e){if(!dr(e))return null;let r=this.statusCache.get(e);if(r&&nu.includes(r.state)&&((r.savedDocumentId?!0:r.saveError!==void 0)||!this.completionHandler))return r;let n=X(this.jobsDir,e,"status.json");if(!Fe(n))return null;let o=JSON.parse(Ee(n,"utf-8"));if(o.state==="queued"){let s=this.resolveCreatedAtMs(e);if(s!==null&&Date.now()-s>6e4){let a=`${n}.lock`;try{let c=Wr(a,()=>{let u=JSON.parse(Ee(n,"utf-8"));if(u.state!=="queued")return null;let l={...u,state:"error",completedAt:new Date().toISOString()};return je(n,l),l});if(c)return oe(X(this.jobsDir,e,"error.txt"),"Job stalled in queued state (worker failed to start)"),this.statusCache.set(e,c),c}catch{}}}return this.statusCache.set(e,o),nu.includes(o.state)&&!o.savedDocumentId&&!o.saveError&&this.completionHandler&&this.maybeTriggerCompletionSave(e).catch(()=>{}),o}getResult(e){if(!dr(e))return null;let r=this.getStatus(e);if(!r)return null;let n=X(this.jobsDir,e),o={id:e,state:r.state,exitCode:r.exitCode,savedDocumentId:r.savedDocumentId,saveError:r.saveError},s=X(n,"output.txt");Fe(s)&&(o.output=Ee(s,"utf-8"));let i=X(n,"error.txt");return Fe(i)&&(o.error=Ee(i,"utf-8")),o}async getResultAwaited(e){return dr(e)?(await this.maybeTriggerCompletionSave(e),this.getResult(e)):null}async invokeHandlerWithRetry(e,r){let n=[200,600],o;for(let s=0;s<n.length+1;s++){if(!Fe(X(r,"status.json")))throw o||new Error("job directory removed during completion save");try{return await e()}catch(i){if(o=i,s>=n.length)break;await new Promise(a=>setTimeout(a,n[s]))}}throw o}async maybeTriggerCompletionSave(e){if(!this.completionHandler||!dr(e))return;let r=X(this.jobsDir,e);if(!Fe(X(r,"status.json")))return;let n=this.saveInFlight.get(e);if(n)return n;let o=this.runCompletionSave(e).finally(()=>{this.saveInFlight.delete(e)});return this.saveInFlight.set(e,o),o}async runCompletionSave(e){if(!this.completionHandler||!dr(e))return;let r=X(this.jobsDir,e),n=X(r,"status.json"),o=X(r,"job.json");if(!Fe(n)||!Fe(o))return;let s=JSON.parse(Ee(n,"utf-8"));if(!nu.includes(s.state)||s.savedDocumentId||s.saveError)return;let i=JSON.parse(Ee(o,"utf-8"));if(!i.saveAsDocument)return;let a={id:e,state:s.state,exitCode:s.exitCode},c=X(r,"output.txt");Fe(c)&&(a.output=Ee(c,"utf-8"));let u=X(r,"error.txt");Fe(u)&&(a.error=Ee(u,"utf-8"));try{let l=await this.invokeHandlerWithRetry(()=>this.completionHandler({jobId:e,descriptor:i,result:a,saveAsDocument:i.saveAsDocument}),r);if(l){let d={savedDocumentId:l.documentId};Ot(r,d),this.statusCache.set(e,{...s,...d})}else{let d={saveError:`skipped (state=${s.state})`};Ot(r,d),this.statusCache.set(e,{...s,...d})}}catch(l){let p={saveError:l instanceof Error?l.message:String(l)};try{Ot(r,p),this.statusCache.set(e,{...s,...p})}catch{}}}listJobs(){if(!Fe(this.jobsDir))return[];let e;try{e=Ro(this.jobsDir,{withFileTypes:!0}).filter(n=>n.isDirectory())}catch{return[]}let r=[];for(let n of e)try{let o=X(this.jobsDir,n.name,"status.json");Fe(o)&&r.push(JSON.parse(Ee(o,"utf-8")))}catch{}return r}cancel(e){if(!dr(e))return!1;let r=this.getStatus(e);if(!r||r.state!=="queued"&&r.state!=="running")return!1;r.pid&&vn(r.pid);let n=X(this.jobsDir,e),o=X(n,"status.json"),s=`${o}.lock`;try{let i=Wr(s,()=>{let a=JSON.parse(Ee(o,"utf-8"));if(a.state!=="queued"&&a.state!=="running")return null;let c={...a,state:"cancelled",completedAt:new Date().toISOString()};return je(o,c),c});i&&this.statusCache.set(e,i)}catch{}return this.clearDeferredSaveTimer(e),!0}clearDeferredSaveTimer(e){let r=this.deferredSaveTimers.get(e);r&&(clearTimeout(r),this.deferredSaveTimers.delete(e))}shutdown(){for(let e of this.deferredSaveTimers.values())clearTimeout(e);this.deferredSaveTimers.clear()}cleanup(){if(!Fe(this.jobsDir))return 0;let e;try{e=Ro(this.jobsDir,{withFileTypes:!0}).filter(u=>u.isDirectory())}catch{return 0}let r=[];for(let u of e)try{let l=X(this.jobsDir,u.name,"status.json"),d=X(this.jobsDir,u.name,"job.json");if(!Fe(l))continue;let p=JSON.parse(Ee(l,"utf-8")),f=null;try{f=JSON.parse(Ee(d,"utf-8"))}catch{}r.push({name:u.name,status:p,descriptor:f})}catch{}let n=["completed","error","timed_out","cancelled","missing_cli"],o=r.filter(u=>n.includes(u.status.state)).sort((u,l)=>{let d=u.descriptor?.createdAt??"",p=l.descriptor?.createdAt??"";return d.localeCompare(p)}),s=0,i=Date.now(),a=this.maxAgeDays*24*60*60*1e3,c=r.length;for(let u of o){let d=(u.descriptor?.createdAt?i-new Date(u.descriptor.createdAt).getTime():1/0)>a,p=c-s>this.maxJobs;if(!d&&!p)continue;let f=X(this.jobsDir,u.name);try{let m=Ro(f);for(let g of m)e0(X(f,g));t0(f),this.statusCache.delete(u.name),this.clearDeferredSaveTimer(u.name),s++}catch{}}return s}spawnWorker(e){let r=new URL("./job-worker.js",import.meta.url).pathname;if(Fe(r)){let n=sm(process.execPath,[r,e],{detached:!0,stdio:"ignore",cwd:this.workspaceDir}),o=typeof n.pid=="number"&&n.pid>0;if(o)try{Ot(e,{pid:n.pid})}catch{}n.on("error",s=>{if(o)return;s.code==="ENOENT"?this.runInProcess(e):this.runInProcess(e)}),n.unref()}else this.runInProcess(e)}runInProcess(e){Promise.resolve().then(()=>(nm(),rm)).then(({resolveCliConfig:r})=>{let n;try{n=JSON.parse(Ee(X(e,"job.json"),"utf-8"))}catch{return}let o=r(n);if(!o){Ot(e,{state:"missing_cli",completedAt:new Date().toISOString()}),oe(X(e,"error.txt"),`No CLI mapping for provider: ${n.provider}`);return}let{command:s,buildArgs:i}=o,a=Ee(X(e,"prompt.txt"),"utf-8"),c=i(a);Ot(e,{state:"running",startedAt:new Date().toISOString()});let u=Bt(s,c),l=sm(u.command,u.args,{cwd:n.cwd||void 0,stdio:["ignore","pipe","pipe"],windowsHide:!0});if(typeof l.pid=="number"&&l.pid>0)try{Ot(e,{pid:l.pid})}catch{}if(!l.stdout||!l.stderr){try{l.kill()}catch{}oe(X(e,"error.txt"),"Worker stdout/stderr streams unavailable (pipe allocation failed)"),Ot(e,{state:"error",completedAt:new Date().toISOString()});return}let d="",p="",f=0,m=0,g=!1,y=!1;l.stdout.on("data",w=>{f+=w.length,f<=10485760?d+=w.toString():g||(g=!0,At(l))}),l.stderr.on("data",w=>{m+=w.length,m<=10485760&&(p+=w.toString())});let v=(w,_)=>{if(!y){y=!0,clearTimeout(S);try{oe(X(e,"output.txt"),d),_!==void 0?oe(X(e,"error.txt"),_):oe(X(e,"error.txt"),p),Ot(e,w)}catch{}}},S=setTimeout(()=>{y||(At(l),v({state:"timed_out",completedAt:new Date().toISOString()}))},n.timeout);l.on("close",w=>{if(y)return;let _=d.trim().length>0;v({state:w===0||_?"completed":"error",exitCode:w??1,completedAt:new Date().toISOString()})}),l.on("error",w=>{if(y)return;let _=w.code==="ENOENT"?"missing_cli":"error";v({state:_,completedAt:new Date().toISOString()},w.message)})}).catch(()=>{try{Ot(e,{state:"error",completedAt:new Date().toISOString()}),oe(X(e,"error.txt"),"Failed to load job worker module")}catch{}})}};ci();Vt();import{mkdirSync as o0,readdirSync as im,readFileSync as s0,unlinkSync as i0}from"fs";import{join as Io}from"path";function am(t){let e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}-${r}-${n}`}function a0(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function c0(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var di=class{tracesDir;writer;constructor(e,r){this.tracesDir=Io(e,hf),o0(this.tracesDir,{recursive:!0}),this.writer=new ii(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=am(new Date(r.timestamp)),o=Io(this.tracesDir,`${n}.jsonl`);this.writer.append(o,JSON.stringify(r)+`
|
|
13
|
+
`,"trace")}query(e={}){let r=this.listFiles(e.daysBack),n=[],o=[];for(let i of r){let a=s0(i,"utf-8").split(`
|
|
14
|
+
`).filter(Boolean);for(let c of a)try{let u=JSON.parse(c);c0(u)?o.push(u):a0(u)&&n.push(u)}catch{}}for(let i of o){let a=n.find(c=>c.traceId===i.traceId&&c.providerId===i.providerId);a&&(a.quality=i.quality)}let s=n;return e.providerId&&(s=s.filter(i=>i.providerId===e.providerId)),e.task&&(s=s.filter(i=>i.task===e.task)),e.traceId&&(s=s.filter(i=>i.traceId===e.traceId)),e.successOnly&&(s=s.filter(i=>i.response.success)),e.failedOnly&&(s=s.filter(i=>!i.response.success)),e.limit!==void 0&&(s=s.slice(0,e.limit)),s}updateQuality(e,r,n){let o=new Date,s={type:"quality_update",traceId:e,providerId:r,timestamp:o.toISOString(),quality:n},i=am(o),a=Io(this.tracesDir,`${i}.jsonl`);this.writer.append(a,JSON.stringify(s)+`
|
|
15
|
+
`,"audit")}shutdown(){this.writer.destroy()}panicFlush(){this.writer.panicFlush()}getQualityStats(e){let r=this.query({daysBack:e}),n=new Map;for(let s of r){if(!s.quality)continue;let i=`${s.providerId}:${s.task}`,a=n.get(i)??{totalScore:0,count:0,totalLatency:0};a.totalScore+=s.quality.score,a.count+=1,a.totalLatency+=s.latencyMs,n.set(i,a)}let o=new Map;for(let[s,i]of n)o.set(s,{avgScore:i.totalScore/i.count,count:i.count,avgLatencyMs:i.totalLatency/i.count});return o}cleanup(e){let r=new Date;r.setDate(r.getDate()-e);let n=0,o;try{o=im(this.tracesDir)}catch{return 0}for(let s of o){if(!s.endsWith(".jsonl"))continue;let i=s.replace(".jsonl",""),a=new Date(i+"T00:00:00.000Z");isNaN(a.getTime())||a<r&&(i0(Io(this.tracesDir,s)),n++)}return n}listFiles(e){let r;try{r=im(this.tracesDir).filter(n=>n.endsWith(".jsonl")).sort()}catch{return[]}if(e!==void 0){let n=new Date;n.setDate(n.getDate()-e),r=r.filter(o=>{let s=o.replace(".jsonl",""),i=new Date(s+"T00:00:00.000Z");return!isNaN(i.getTime())&&i>=n})}return r.map(n=>Io(this.tracesDir,n))}};var u0=/[;|&`$(){}!><\n\r\\]/,pi=new Set(["ls","cat","head","tail","wc","diff","find","grep","sort","uniq"]),l0=new Set(["rm","sudo","chmod","chown","mkfs","dd","curl","wget","kill","pkill","killall","mv","cp","sh","bash","zsh","python","perl","ruby","node","npm","npx","eval","exec","source"]);function cm(t){if(u0.test(t))return{valid:!1,error:"Command contains shell metacharacters (piping, chaining, or subshell operators are not allowed)"};let e=t.split(/\s+/).filter(Boolean);if(e.length===0)return{valid:!1,error:"Empty command"};if(e[0].includes("/")||e[0].includes("\\"))return{valid:!1,error:"Command must not contain path separators (use bare command names only)"};for(let n=1;n<e.length;n++)if(e[n].includes("/")||e[n].includes("\\"))return{valid:!1,error:`Argument must not contain path separators: ${JSON.stringify(e[n])}`};let r=e[0];if(!pi.has(r))return{valid:!1,error:`Command '${r}' is not allowed. Allowed: ${[...pi].join(", ")}`};for(let n of e){let o=n.replace(/^.*\//,"");if(l0.has(o))return{valid:!1,error:`Command contains blocked token '${o}'`}}return{valid:!0}}Vt();var um=[{type:"aws_access_key",regex:/AKIA[0-9A-Z]{16}/,description:"AWS Access Key ID"},{type:"private_key",regex:/-----BEGIN\s+(RSA|EC|DSA|OPENSSH)?\s*PRIVATE KEY-----/,description:"Private key header"},{type:"password_assignment",regex:/(?:password|passwd|pwd)\s*[:=]\s*["']?[^\s"',;]{4,}["']?/i,description:"Password assignment"},{type:"api_key_assignment",regex:/(?:api[_-]?key|apikey|secret[_-]?key)\s*[:=]\s*["']?[^\s"',;]{8,}["']?/i,description:"API key assignment"},{type:"bearer_token",regex:/Bearer\s+[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+/,description:"Bearer JWT token"},{type:"generic_secret",regex:/(?:token|secret|credential)\s*[:=]\s*["'][^"']{8,}["']/i,description:"Generic secret assignment"}],lm=[/\$[A-Z_]+/,/\$\{[A-Z_]+\}/,/process\.env\.\w+/,/<YOUR_[A-Z_]+>/];function dm(t){let e=Array.isArray(t)?t:t.split(`
|
|
16
|
+
`),r=[];for(let n=0;n<e.length;n++){let o=e[n];for(let s of um){let i=s.regex.exec(o);if(!i)continue;let a=i[0];if(!lm.some(u=>u.test(a))){r.push({type:s.type,pattern:s.description,line:n+1,excerpt:o.length>80?o.slice(0,80)+"...":o});break}}}return{clean:r.length===0,findings:r}}function ou(t){if(t.length===0)return t;let e=t.split(`
|
|
17
|
+
`);for(let r=0;r<e.length;r++){let n=e[r];for(let o of um){let s=new RegExp(o.regex.source,o.regex.flags.includes("g")?o.regex.flags:o.regex.flags+"g");n=n.replace(s,i=>lm.some(a=>a.test(i))?i:Ef)}e[r]=n}return e.join(`
|
|
18
|
+
`)}Vt();import{execFileSync as d0}from"child_process";import{existsSync as pm,rmSync as p0,mkdirSync as f0}from"fs";import{join as fm}from"path";var fi=class{baseDir;worktrees=new Map;worktreeBaseDir;constructor(e){this.baseDir=e,this.worktreeBaseDir=fm(e,gf)}create(e){let r=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,60),n=`agestra-worker/${r}`,o=fm(this.worktreeBaseDir,r);f0(this.worktreeBaseDir,{recursive:!0}),pm(o)&&this.forceRemoveWorktree(o),this.gitSafe(["branch","-D",n]),this.git(["worktree","add","-b",n,o,"HEAD"]);let s={id:e,path:o,branch:n};return this.worktrees.set(e,s),s}remove(e){let r=this.worktrees.get(e);r&&(this.forceRemoveWorktree(r.path),this.gitSafe(["branch","-D",r.branch]),this.worktrees.delete(e))}get(e){return this.worktrees.get(e)}list(){return[...this.worktrees.values()]}listOrphans(){let e=this.gitSafe(["worktree","list","--porcelain"]);if(!e)return[];let r=[],n="",o="",s=()=>{n.includes(".agestra/worktrees")&&o.startsWith("agestra-worker/")&&([...this.worktrees.values()].some(a=>a.path===n)||r.push({path:n,branch:o})),n="",o=""};for(let i of e.split(`
|
|
19
|
+
`))i.startsWith("worktree ")?n=i.slice(9):i.startsWith("branch refs/heads/")?o=i.slice(18):i===""&&s();return n&&s(),r}cleanOrphans(){let e=this.listOrphans(),r=0;for(let n of e)this.forceRemoveWorktree(n.path),this.gitSafe(["branch","-D",n.branch]),r++;return r}forceRemoveWorktree(e){this.gitSafe(["worktree","remove",e])===null&&this.gitSafe(["worktree","remove","--force",e])===null&&(pm(e)&&p0(e,{recursive:!0,force:!0}),this.gitSafe(["worktree","prune"]))}git(e){return d0("git",e,{cwd:this.baseDir,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}gitSafe(e){try{return this.git(e)}catch{return null}}};var m0=["npm","node","git","tsc"];function mm(t){return{task:t.taskDescription,files:{readonly:t.filesToRead??[],readwrite:t.filesToModify??[]},constraints:t.constraints,success_criteria:t.successCriteria??[],permissions:{sandbox_root:t.workingDir,allowed_commands:[...m0]},timeout_minutes:t.timeoutMinutes??10}}function hm(t){let e=[];return(!t.task||t.task.trim().length===0)&&e.push("task must not be empty"),(!t.permissions.sandbox_root||t.permissions.sandbox_root.trim().length===0)&&e.push("permissions.sandbox_root must not be empty"),t.timeout_minutes<=0&&e.push("timeout_minutes must be positive"),{valid:e.length===0,errors:e}}var ke;(function(t){t.SPAWNING="SPAWNING",t.RUNNING="RUNNING",t.COLLECTING="COLLECTING",t.COMPLETED="COMPLETED",t.FAILED="FAILED",t.CANCELLING="CANCELLING",t.CANCELLED="CANCELLED",t.TIMEOUT="TIMEOUT"})(ke||(ke={}));var mi=10,su=2e4;import{spawn as b0}from"child_process";import{writeFileSync as au,mkdirSync as w0,readFileSync as _m,existsSync as bm}from"fs";import{isAbsolute as wm,join as Ao,resolve as xm}from"path";import{randomBytes as x0}from"crypto";import{execFileSync as S0}from"child_process";Vt();bn();wo();Eo();Eo();import{readFileSync as gm}from"fs";var iu=class{builders=new Map;register(e,r){this.builders.set(e,r)}has(e){return this.builders.has(e)}build(e,r,n,o){let s=this.builders.get(e);if(!s){let i=[...this.builders.keys()];throw new Error(`No CLI launch builder registered for provider "${e}". Known: [${i.join(", ")}]`)}return s(r,n,o)}knownProviders(){return[...this.builders.keys()]}};function h0(t,e,r){let n=ym(t,e,r);return{command:"codex",args:["exec","--skip-git-repo-check","--full-auto","--ephemeral","-C",e,"-"],stdin:n}}function g0(t,e,r){return{command:"gemini",args:["--approval-mode","yolo","-p",ym(t,e,r)]}}function ym(t,e,r){let n=gm(t,"utf-8"),o=y0(r,e);return["You are an autonomous coding worker operating in the current workspace.","Execute the task manifest below without asking for confirmation.","Stay within the workspace, respect read-only vs read-write boundaries, and summarize changes plus verification at the end.","",n,o].join(`
|
|
20
|
+
`)}function vm(){let t=new iu;return t.register("codex",h0),t.register("gemini",g0),t}function y0(t,e){if(!t||t.length===0)return"";let r=t.filter(o=>!eu(o,e));if(r.length===0)return"";let n=["Read-only file snapshots:","These files may live outside the worker sandbox root. Use the embedded contents below as authoritative context and do not attempt to edit them.",""];for(let o of r.slice(0,mi))try{let s=gm(o,"utf-8"),i=s.length>su?`${s.slice(0,su)}
|
|
21
|
+
...[truncated]`:s;n.push(`### File: ${o}`),n.push("```"),n.push(i),n.push("```"),n.push("")}catch(s){let i=s instanceof Error?s.message:String(s);n.push(`### File: ${o}`),n.push(`[unavailable: ${i}]`),n.push("")}return r.length>mi&&(n.push(`...[${r.length-mi} additional read-only files omitted]`),n.push("")),n.join(`
|
|
22
|
+
`)}var Co=class t{baseDir;workers=new Map;workersBaseDir;worktreeManager;providerPolicies;cliBuilderRegistry;constructor(e,r={}){this.baseDir=e,this.workersBaseDir=Ao(e,wf),this.worktreeManager=new fi(e),this.providerPolicies=r.providerPolicies??new Map,this.cliBuilderRegistry=r.cliBuilderRegistry??vm()}knownProviders(){let e=new Set;for(let r of this.cliBuilderRegistry.knownProviders())e.add(r);for(let r of this.providerPolicies.keys())e.add(r);return[...e]}activeWorkerCount(){let e=0;for(let r of this.workers.values()){let n=r.info.state;(n===ke.RUNNING||n===ke.COLLECTING)&&e++}return e}spawn(e){if(this.activeWorkerCount()>=3)throw new Error(`Worker quota exceeded: ${this.activeWorkerCount()}/${3} workers already active. Wait for existing workers to complete or call stop() before spawning a new one.`);let r=this.validateWorkingDirectory(e.workingDir),n=this.normalizeReadablePaths(e.filesToRead,r),o=this.normalizeWritablePaths(e.filesToModify,r);this.assertAutonomousExecutionAllowed(e.provider);let s=[e.taskDescription,e.constraints??""],i=dm(s);if(!i.clean){let U=i.findings.map($e=>$e.pattern).join(", ");throw new Error(`Secret detected in task input \u2014 spawn blocked. Found: ${U}`)}let a=x0(3).toString("hex"),c=`${e.provider}-${Date.now()}-${a}`,u=Ao(this.workersBaseDir,c);w0(u,{recursive:!0});let l=mm({taskDescription:e.taskDescription,workingDir:r,filesToRead:n,filesToModify:o,constraints:e.constraints,successCriteria:e.successCriteria,timeoutMinutes:e.timeoutMinutes}),d=hm(l);if(!d.valid)throw new Error(`Invalid task manifest: ${d.errors.join(", ")}`);let p=Ao(u,"task-manifest.json");au(p,JSON.stringify(l,null,2),"utf-8");let f=e.useWorktree!==!1?this.tryCreateWorktree(c):null,m=Ao(u,"stdout.log"),g=Ao(u,"stderr.log"),y=f?.path??r,v=this.cliBuilderRegistry.build(e.provider,p,y,n),S=Bt(v.command,v.args),w=b0(S.command,S.args,{cwd:y,env:t.buildWorkerEnv(),detached:!0,stdio:[v.stdin?"pipe":"ignore","pipe","pipe"]}),_=[],P=[];w.stdout?.on("data",U=>_.push(U)),w.stderr?.on("data",U=>P.push(U)),v.stdin!==void 0&&w.stdin?.end(v.stdin),w.unref();let A={workerId:c,provider:e.provider,state:ke.RUNNING,pid:w.pid??null,worktreePath:f?.path??null,worktreeBranch:f?.branch??null,startedAt:Date.now(),retryCount:0,exitCode:null,error:null},D={info:A,process:w,workerDir:u,manifestPath:p,outputPath:m,errorPath:g};if(this.workers.set(c,D),e.timeoutMinutes){let U=e.timeoutMinutes*6e4,$e=setTimeout(()=>{if(D.info.state===ke.RUNNING&&D.process===w){D.info.state=ke.TIMEOUT,D.info.error=`Worker timed out after ${e.timeoutMinutes} minutes`;let G=w.pid;G&&vn(G)}},U);$e.unref(),D.timeoutTimer=$e}return w.on("close",U=>{D.timeoutTimer&&(clearTimeout(D.timeoutTimer),D.timeoutTimer=void 0),D.info.exitCode=U;try{au(m,Buffer.concat(_).toString("utf-8")),au(g,Buffer.concat(P).toString("utf-8"))}catch{}D.info.state===ke.CANCELLING?D.info.state=ke.CANCELLED:U===0?D.info.state=ke.COLLECTING:(D.info.state=ke.FAILED,D.info.error=`Process exited with code ${U}`)}),A}getStatus(e){let r=this.workers.get(e);if(!r)return;let n=Math.floor((Date.now()-r.info.startedAt)/1e3),o="";try{bm(r.outputPath)&&(o=_m(r.outputPath,"utf-8").split(`
|
|
22
23
|
`).slice(-20).join(`
|
|
23
|
-
`))}catch{}return{workerId:r.info.workerId,provider:r.info.provider,state:r.info.state,elapsedSeconds:n,pid:r.info.pid,outputTail:
|
|
24
|
-
`).map(c=>c.trim().slice(3)):[];return a.length>0&&(this.execGit(["commit","-m",s],o),this.execGit(["merge",n.info.worktreeBranch,"--no-edit"],this.baseDir)),this.worktreeManager.remove(n.info.workerId),n.info.worktreePath=null,n.info.worktreeBranch=null,{merged:a}}rejectChanges(e){let r=this.workers.get(e);if(!r)throw new Error(`Worker not found: ${e}`);r.info.worktreePath&&this.worktreeManager.remove(r.info.workerId),r.info.worktreePath=null,r.info.worktreeBranch=null}tryCreateWorktree(e){try{return this.worktreeManager.create(e)}catch{return null}}execGit(e,r){return
|
|
25
|
-
`).map(n=>n.trim().slice(3)).filter(Boolean):[]}static buildWorkerEnv(){let e={};for(let r of
|
|
26
|
-
`)
|
|
27
|
-
`)
|
|
24
|
+
`))}catch{}return{workerId:r.info.workerId,provider:r.info.provider,state:r.info.state,elapsedSeconds:n,pid:r.info.pid,outputTail:ou(o),worktreeBranch:r.info.worktreeBranch,retryCount:r.info.retryCount}}collect(e){let r=this.workers.get(e);if(!r)return;let n="";try{bm(r.outputPath)&&(n=_m(r.outputPath,"utf-8"))}catch{}n=ou(n);let o=null;try{r.info.worktreePath&&(o=this.reviewChanges(r.info.workerId))}catch{o=null}return r.info.state===ke.COLLECTING&&(r.info.state=ke.COMPLETED),{workerId:r.info.workerId,state:r.info.state,exitCode:r.info.exitCode,outputFull:n,gitDiff:o?.fullDiff??"",filesChanged:o?.filesChanged??[],worktreeBranch:r.info.worktreeBranch}}stop(e){let r=this.workers.get(e);if(!r||!r.process||r.info.state!==ke.RUNNING)return;r.info.state=ke.CANCELLING;let n=r.process.pid;if(n)vn(n);else try{r.process.kill("SIGTERM")}catch{}setTimeout(()=>{if(r.info.state===ke.CANCELLING){try{r.process?.kill("SIGKILL")}catch{}r.info.state=ke.CANCELLED}},5e3)}listAll(){return[...this.workers.values()].map(e=>({...e.info}))}reviewChanges(e){let r=this.workers.get(e);if(!r)throw new Error(`Worker not found: ${e}`);if(!r.info.worktreePath)throw new Error(`Worker ${e} has no isolated worktree`);let n=r.info.worktreePath;return this.execGitSafe(["add","-N","."],n),{workerId:r.info.workerId,provider:r.info.provider,worktreePath:r.info.worktreePath,branch:r.info.worktreeBranch,filesChanged:this.listChangedFiles(n),diffStat:this.execGit(["diff","--stat","HEAD"],n),fullDiff:this.execGit(["diff","HEAD"],n)}}acceptChanges(e,r){let n=this.workers.get(e);if(!n)throw new Error(`Worker not found: ${e}`);if(!n.info.worktreePath||!n.info.worktreeBranch)throw new Error(`Worker ${e} has no isolated worktree`);let o=n.info.worktreePath,s=r??`agestra: worker ${e}`;this.execGit(["add","-A"],o);let i=this.execGit(["status","--porcelain"],o),a=i.trim()?i.trim().split(`
|
|
25
|
+
`).map(c=>c.trim().slice(3)):[];return a.length>0&&(this.execGit(["commit","-m",s],o),this.execGit(["merge",n.info.worktreeBranch,"--no-edit"],this.baseDir)),this.worktreeManager.remove(n.info.workerId),n.info.worktreePath=null,n.info.worktreeBranch=null,{merged:a}}rejectChanges(e){let r=this.workers.get(e);if(!r)throw new Error(`Worker not found: ${e}`);r.info.worktreePath&&this.worktreeManager.remove(r.info.workerId),r.info.worktreePath=null,r.info.worktreeBranch=null}tryCreateWorktree(e){try{return this.worktreeManager.create(e)}catch(r){let n=r instanceof Error?r.message:String(r);return console.warn(`[CliWorkerManager] Worker ${e} failed to create isolated worktree: ${n} \u2014 falling back to shared base directory.`),null}}execGit(e,r){return S0("git",e,{cwd:r,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}execGitSafe(e,r){try{return this.execGit(e,r)}catch{return null}}listChangedFiles(e){let r=this.execGitSafe(["status","--porcelain"],e);return r?.trim()?r.trim().split(`
|
|
26
|
+
`).map(n=>n.trim().slice(3)).filter(Boolean):[]}static buildWorkerEnv(){let e={};for(let r of xf){let n=process.env[r];n!==void 0&&(e[r]=n)}for(let[r,n]of Object.entries(process.env))r.startsWith("AGESTRA_")&&n!==void 0&&(e[r]=n);return e}getProviderPolicy(e){let r=this.providerPolicies.get(e);if(r===void 0){let n=[...this.providerPolicies.keys()];throw new Error(`No execution policy configured for provider "${e}". Known: [${n.join(", ")}]`)}return r}assertAutonomousExecutionAllowed(e){let r=this.getProviderPolicy(e);if(!si(r))throw new Error(`Execution policy blocks autonomous worker for provider "${e}" (policy: ${r})`)}validateWorkingDirectory(e){return dt(e,this.baseDir)}normalizeReadablePaths(e,r){return e?.map(n=>{let o=wm(n)?n:xm(r,n);return Yt(o,this.baseDir)})}normalizeWritablePaths(e,r){return e?.map(n=>{let o=wm(n)?n:xm(r,n);return dt(o,this.baseDir)})}};var gi=class{upstream;cached=null;cachedAt=0;cachedDaysBack=0;ttlMs;constructor(e,r){this.upstream=e,this.ttlMs=r?.ttlMs??6e4}getQualityStats(e){let r=Date.now();return this.cached!==null&&this.cachedDaysBack===e&&r-this.cachedAt<this.ttlMs?this.cached:(this.cached=this.upstream.getQualityStats(e),this.cachedAt=r,this.cachedDaysBack=e,this.cached)}invalidate(){this.cached=null,this.cachedAt=0}};var Rn=class{maxConcurrent;maxQueueSize;running=0;queue=[];constructor(e,r=16){this.maxConcurrent=e,this.maxQueueSize=r}async acquire(){if(this.running<this.maxConcurrent){this.running++;return}if(this.queue.length>=this.maxQueueSize)throw new Error(`ConcurrencyLimiter queue full (max ${this.maxQueueSize})`);return new Promise(e=>{this.queue.push(()=>{this.running++,e()})})}release(){this.running--;let e=this.queue.shift();e&&e()}async run(e){await this.acquire();try{return await e()}finally{this.release()}}};bn();Vt();import{spawn as $0}from"child_process";var k0=3e5,P0=3,T0=15e3,E0=3e3,Sm=10*1024*1024,R0=6e5,yi=class{state="idle";process=null;consecutiveFailures=0;lastFailureTime=0;idleTimer=null;pendingRequests=new Map;command;commandPrefix;commandArgs;idleTimeoutMs;maxConsecutiveFailures;startupTimeoutMs;stdoutBuffer="";startupResolve=null;startupReject=null;constructor(e){this.command=e.command,this.commandPrefix=e.commandPrefix??[],this.commandArgs=e.commandArgs??[],this.idleTimeoutMs=e.idleTimeoutMs??k0,this.maxConsecutiveFailures=e.maxConsecutiveFailures??P0,this.startupTimeoutMs=e.startupTimeoutMs??T0}async request(e,r,n){if(this.state==="shutdown")throw new Error("CodexAppServer is shutting down");if(n?.aborted)throw new at(n.reason);if((this.state==="idle"||this.state==="error")&&await this.start(),this.state==="starting"&&await this.waitForReady(),n?.aborted)throw new at(n.reason);if(this.state!=="ready"&&this.state!=="busy")throw new Error(`CodexAppServer in unexpected state: ${this.state}`);return this.sendRequest(e,r??R0,n)}isAlive(){return this.process!==null&&!this.process.killed&&(this.state==="ready"||this.state==="busy"||this.state==="starting")}getState(){return this.state}shouldFallback(){return this.consecutiveFailures<this.maxConsecutiveFailures?!1:Date.now()-this.lastFailureTime>$f?(this.consecutiveFailures=0,!1):!0}resetFailures(){this.consecutiveFailures=0}async shutdown(){if(!this.process||this.state==="shutdown"||this.state==="idle")return;this.state="shutdown",this.clearIdleTimer();for(let[,n]of this.pendingRequests)clearTimeout(n.timer),n.reject(new Error("App server shutting down"));this.pendingRequests.clear(),this.startupReject&&(this.startupReject(new Error("App server shutting down")),this.startupResolve=null,this.startupReject=null);let e=this.process;this.process=null;try{e.kill("SIGTERM")}catch{this.state="idle";return}let r=setTimeout(()=>{try{e.kill("SIGKILL")}catch{}},E0);await new Promise(n=>{e.on("close",()=>{clearTimeout(r),n()}),(e.exitCode!==null||e.signalCode!==null)&&(clearTimeout(r),n())}),this.state="idle"}async start(){if(this.state!=="idle"&&this.state!=="error")return;this.state="starting",this.stdoutBuffer="";let e=[...this.commandPrefix,...this.commandArgs,"app-server"],r=Bt(this.command,e),n=$0(r.command,r.args,{stdio:["pipe","pipe","pipe"],detached:!1,windowsHide:!0});this.process=n;let o=c=>this.handleStdout(c.toString()),s=c=>{process.stderr.write(`[codex-app-server] ${c.toString()}`)},i=(c,u)=>{n.stdout?.off("data",o),n.stderr?.off("data",s),n.off("error",a),this.handleProcessClose(c,u)},a=c=>{n.stdout?.off("data",o),n.stderr?.off("data",s),n.off("close",i),this.handleProcessError(c)};return n.stdout.on("data",o),n.stderr.on("data",s),n.on("close",i),n.on("error",a),this.waitForReady()}waitForReady(){return this.state==="ready"?Promise.resolve():new Promise((e,r)=>{let n=setTimeout(()=>{this.startupResolve=null,this.startupReject=null,this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",r(new Error(`CodexAppServer startup timeout (${this.startupTimeoutMs}ms)`))},this.startupTimeoutMs);this.startupResolve=()=>{clearTimeout(n),e()},this.startupReject=o=>{clearTimeout(n),r(o)}})}handleStdout(e){if(this.stdoutBuffer+=e,this.stdoutBuffer.length>Sm){if(process.stderr.write(`[codex-app-server] stdoutBuffer exceeded ${Sm} bytes \u2014 dropping and restarting
|
|
27
|
+
`),this.stdoutBuffer="",this.state!=="shutdown"){this.state="error",this.consecutiveFailures++,this.lastFailureTime=Date.now();for(let[,o]of this.pendingRequests)clearTimeout(o.timer),o.reject(new Error("App server stdout buffer overflow"));this.pendingRequests.clear();try{this.process?.kill("SIGTERM")}catch{}}return}for(let o of this.pendingRequests.values())o.resetTimer();let r=()=>{this.state="ready",this.consecutiveFailures=0,this.resetIdleTimer(),this.startupResolve&&(this.startupResolve(),this.startupResolve=null,this.startupReject=null)},n;for(;(n=this.stdoutBuffer.indexOf(`
|
|
28
|
+
`))!==-1;){let o=this.stdoutBuffer.slice(0,n).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(n+1),!!o){if(this.state==="starting"&&(o.includes("ready")||o.includes("initialized"))){r();continue}try{let s=JSON.parse(o);if(this.state==="starting"&&r(),s.id&&this.pendingRequests.has(s.id)){let i=this.pendingRequests.get(s.id);this.pendingRequests.delete(s.id),clearTimeout(i.timer),this.consecutiveFailures=0,this.pendingRequests.size===0&&(this.state="ready",this.resetIdleTimer()),i.resolve(s)}}catch{this.state==="starting"&&r()}}}}sendRequest(e,r,n){return new Promise((o,s)=>{if(!this.process||!this.process.stdin){s(new Error("App server process not available"));return}let i=null,a=()=>{i&&n&&(n.removeEventListener("abort",i),i=null)},c=()=>{this.pendingRequests.delete(e.id),a(),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.pendingRequests.size===0&&this.state==="busy"&&(this.state="error"),s(new Error(`App server request timeout (${r}ms of inactivity)`))},u=setTimeout(c,r),l=()=>{clearTimeout(u),u=setTimeout(c,r)},d=f=>{a(),o(f)},p=f=>{a(),s(f)};this.pendingRequests.set(e.id,{resolve:d,reject:p,timer:u,resetTimer:l}),this.state="busy",this.clearIdleTimer(),n&&(i=()=>{let f=this.pendingRequests.get(e.id);f&&(this.pendingRequests.delete(e.id),clearTimeout(f.timer),this.pendingRequests.size===0&&this.state==="busy"&&(this.state="ready",this.resetIdleTimer()),a(),s(new at(n.reason)))},n.addEventListener("abort",i));try{this.process.stdin.write(JSON.stringify(e)+`
|
|
29
|
+
`)}catch(f){clearTimeout(u),this.pendingRequests.delete(e.id),a(),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",s(new Error(`Failed to write to app server: ${f.message}`))}})}handleProcessClose(e,r){for(let[,n]of this.pendingRequests)clearTimeout(n.timer),n.reject(new Error(`App server process exited (code=${e}, signal=${r})`));this.pendingRequests.clear(),this.startupReject&&(this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject(new Error(`App server process exited during startup (code=${e})`)),this.startupResolve=null,this.startupReject=null),this.process=null,this.clearIdleTimer(),this.state!=="shutdown"&&(this.state=this.state==="starting"?"error":"idle")}handleProcessError(e){this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.startupReject&&(this.startupReject(new Error(`App server spawn error: ${e.message}`)),this.startupResolve=null,this.startupReject=null),this.state="error",this.process=null,this.clearIdleTimer()}resetIdleTimer(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{this.state==="ready"&&this.pendingRequests.size===0&&this.shutdown().catch(()=>{})},this.idleTimeoutMs),this.idleTimer&&typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}clearIdleTimer(){this.idleTimer!==null&&(clearTimeout(this.idleTimer),this.idleTimer=null)}};function M(t){return t instanceof Error?t.message:String(t)}function In(t,e,r="... [truncated]"){return t.length<=e?t:t.slice(0,e)+r}bn();async function An(t,e){try{if((await Me({command:t,args:["--version"],timeout:1e4})).exitCode===0)return{available:!0,cliPath:t}}catch{}try{if((await Me({command:"npx",args:[e,"--version"],timeout:3e4})).exitCode===0)return{available:!0,cliPath:"npx"}}catch{}return{available:!1,cliPath:null}}async function $m(t,e,r,n){if(!t)return{status:"error",message:`${n} CLI not installed`};try{let i=await Me({command:t==="npx"?"npx":e,args:t==="npx"?[r,"--version"]:["--version"],timeout:1e4});return i.exitCode===0?{status:"ok",message:`${n} CLI available`}:{status:"error",message:`Exit code: ${i.exitCode}`}}catch(o){return{status:"error",message:o.message}}}function Cn(t,e,r){let n=e.trim()||`Exit code ${t}`,o=n.toLowerCase();if(o.includes("429")||o.includes("rate limit")||o.includes("quota")){let s=new de(r,`Rate limited: ${n}`);throw s.markUnavailable=!0,s}throw o.includes("auth")||o.includes("credential")||o.includes("login")||o.includes("api key")?new de(r,`Authentication issue: ${n}`):new We(r,n)}function km(t){let e="",r=!1;return{feed(n){if(r)return null;e+=n;let o=n.toLowerCase();if(o.includes("429")||o.includes("rate limit")||o.includes("rate-limit")||o.includes("resource_exhausted")||o.includes("quota")){r=!0;let s=new de(t,`Rate limited (detected in stream): ${n.trim().slice(0,200)}`);return s.markUnavailable=!0,s}return o.includes("authentication")||o.includes("credential")||o.includes("api key")?(r=!0,new de(t,`Authentication issue (detected in stream): ${n.trim().slice(0,200)}`)):null},drain(){return e}}}function Kr(t){let e=t.prompt;if(t.system&&(e=`${t.system}
|
|
28
30
|
|
|
29
31
|
${e}`),t.files?.length)for(let r of t.files)r.content&&(e+=`
|
|
30
32
|
|
|
31
33
|
### File: ${r.path}
|
|
32
34
|
\`\`\`
|
|
33
35
|
${r.content}
|
|
34
|
-
\`\`\``);return e}function
|
|
36
|
+
\`\`\``);return e}function vi(t,e){return!!t.files?.length||e.length>4e3}function cu(t){let e=0;return t.replace(/^### File: .+$/gm,()=>(e+=1,`### File ${e}`))}function pr(t,e,r,n){return t==="npx"?{command:"npx",cliArgs:[r,...n]}:{command:e,cliArgs:n}}function Dn(t,e,r){if(t instanceof de||t instanceof We||t instanceof at)throw t;let n=t?.message??"";throw n.startsWith("CLI timeout after ")?new hn(e,r):new We(e,n)}function I0(t){let e=t.prompt;if(t.system&&(e=`${t.system}
|
|
37
|
+
|
|
38
|
+
${e}`),t.files?.length)for(let r of t.files)r.content&&(e+=`
|
|
35
39
|
|
|
36
40
|
### File: ${r.path}
|
|
37
41
|
\`\`\`
|
|
38
42
|
${r.content}
|
|
39
|
-
\`\`\``);return e}function a0(t,e){let r=e?.model;return typeof r=="string"&&r.length>0?r:t}var cr=class{id;type;bridge;modelName;displayName;capabilities;constructor(e){this.id=e.id??e.bridge.providerId,this.type=e.type,this.bridge=e.bridge,this.modelName=e.modelName??e.type,this.displayName=e.displayName,this.capabilities=e.capabilities}async initialize(){}async healthCheck(){return this.bridge.healthCheck?this.bridge.healthCheck():this.bridge.isAvailable()?{status:"ok",message:`${this.displayName} host bridge available`}:{status:"error",message:`${this.displayName} host bridge unavailable`}}getCapabilities(){return{...this.capabilities,models:this.capabilities.models.map((e,r)=>r===0?{...e,name:this.modelName}:{...e})}}getDescriptor(){return tr(this,this.getCapabilities())}isAvailable(){return this.bridge.isAvailable()}async chat(e){if(!this.isAvailable())throw new me(this.id,`${this.displayName} host bridge is not available`);try{let r=i0(e),n={...e.extra??{}};e.model&&(n.model=e.model),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.maxTokens=="number"&&(n.maxTokens=e.maxTokens);let o=await this.bridge.runTurn({prompt:r,system:e.system,metadata:n});return{text:o.text,model:a0(this.modelName,o.metadata),provider:this.id,metadata:o.metadata}}catch(r){let n=r instanceof Error?r.message:String(r);throw/sampling|host bridge unavailable|does not support/i.test(n)?new me(this.id,n):new He(this.id,n)}}};var c0={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["reasoning","review","synthesis","moderation"],models:[{name:"claude-host",description:"Claude host model via MCP sampling bridge",strengths:["reasoning","review","synthesis"]}]},gi=class extends cr{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:c0,modelName:e.modelName??"claude-host"})}};var u0={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["coding","reasoning","review","implementation"],models:[{name:"codex-host",description:"Codex host model via MCP sampling bridge",strengths:["coding","implementation","review"]}]},yi=class extends cr{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:u0,modelName:e.modelName??"codex-host"})}};var l0={maxContext:1e6,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["analysis","reasoning","research","review"],models:[{name:"gemini-host",description:"Gemini host model via MCP sampling bridge",strengths:["analysis","research","review"]}]},vi=class extends cr{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:l0,modelName:e.modelName??"gemini-host"})}};jt();var lm={"report.header.topic":"Topic","report.header.participants":"Participants","report.header.individualDocs":"Individual documents","report.table.proposer":"Proposer","report.table.opinion":"Opinion","report.table.severity":"Severity","report.table.agreement":"Agreement","report.section.mainTable":"Proposal ledger","report.section.dissentDetail":"Dissenting items","report.section.contributionSummary":"AI contribution summary","report.contribution.ai":"AI","report.contribution.proposed":"Proposed","report.contribution.accepted":"Accepted","report.contribution.revises":"Revises issued","report.contribution.abstains":"Abstains","report.footer.synthesisPath":"Final synthesis document","report.footer.debatePath":"Debate transcript","report.footer.pendingSynthesis":"(pending leader approval)","report.status.running":"running","report.status.readyForApproval":"ready for approval","report.status.consensus":"consensus","report.status.escalated":"escalated","report.status.approved":"approved","report.status.rejected":"rejected","report.status.leaderTimeout":"leader timeout","report.status.error":"error","synthesis.status.consensus":"Consensus reached","synthesis.status.escalated":"Partial / escalated","synthesis.section.acceptedItems":"Accepted Items","synthesis.section.rejectedItems":"Rejected / Withdrawn Items","synthesis.section.openItems":"Open Items","synthesis.section.sources":"Sources","synthesis.narration.consensusIn":"Consensus reached in round {round} of {max}.","synthesis.narration.escalated":"Session escalated by user after {round} rounds without consensus.","synthesis.narration.leaderNote":"Leader note","approval.pending":"Awaiting leader approval. Call `agent_debate_approve`, `agent_debate_continue`, or `agent_debate_reject`.","approval.timeout":"Session timed out waiting for leader decision ({hours}h).","moderator.narration.roundHeader":"Round {round} of {max}","moderator.narration.consensusInRound":"Consensus reached after {round} round(s).","moderator.narration.dissentDetailHeader":"Unresolved items","moderator.narration.noInterest":"No interest from participants","moderator.narration.participantDropout":"Participant `{participantId}` marked unavailable after repeated failures.","moderator.narration.participantTimeout":"Participant `{participantId}` did not respond in this round.","moderator.narration.leaderTimeoutFooter":"Leader Timeout","moderator.narration.rejected":"Session rejected by leader.","moderator.narration.approved":"Session approved by leader.","moderator.narration.aliasClarification":"Alias clarification phase","prompt.system.moderator":"You are the moderator of a structured multi-AI debate. You do not author proposals; you aggregate structured votes and produce a neutral synthesis. Respond only in the channels the protocol defines.","error.participantTimeout":"Participant `{participantId}` timed out after {seconds}s.","error.parseFailure":"Could not parse `<{tag}>` block from `{participantId}`.","error.sessionNotFound":"Debate session `{sessionId}` was not found.","error.invalidState":"Operation `{operation}` is not allowed in state `{state}`.","error.unknownLocaleFallback":"Unknown locale `{locale}`; falling back to `{fallback}`.","askUser.escalation.header":"Maximum rounds reached without consensus","askUser.escalation.question":"How would you like to proceed?","askUser.escalation.continue":"Continue +{rounds} rounds","askUser.escalation.escalate":"Escalate without consensus","askUser.escalation.stop":"Stop the debate"};var dm={"report.header.topic":"\uC8FC\uC81C","report.header.participants":"\uCC38\uAC00\uC790","report.header.individualDocs":"\uAC1C\uBCC4 \uAC80\uD1A0 \uBB38\uC11C","report.table.proposer":"\uC81C\uC548\uC790","report.table.opinion":"\uC758\uACAC","report.table.severity":"\uC911\uC694\uB3C4","report.table.agreement":"\uB3D9\uC758\uC728","report.section.mainTable":"\uC81C\uC548 \uC6D0\uC7A5","report.section.dissentDetail":"\uBBF8\uD569\uC758 \uD56D\uBAA9 \uC0C1\uC138","report.section.contributionSummary":"AI \uAE30\uC5EC\uB3C4 \uC694\uC57D","report.contribution.ai":"AI","report.contribution.proposed":"\uC81C\uC548","report.contribution.accepted":"\uCC44\uD0DD","report.contribution.revises":"\uC218\uC815 \uC694\uCCAD","report.contribution.abstains":"\uAE30\uAD8C","report.footer.synthesisPath":"\uCD5C\uC885 \uD569\uC758 \uBB38\uC11C","report.footer.debatePath":"\uD1A0\uB860 \uAE30\uB85D","report.footer.pendingSynthesis":"(\uB9AC\uB354 \uC2B9\uC778 \uB300\uAE30 \uC911)","report.status.running":"\uC9C4\uD589 \uC911","report.status.readyForApproval":"\uC2B9\uC778 \uB300\uAE30","report.status.consensus":"\uD569\uC758 \uB3C4\uB2EC","report.status.escalated":"\uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","report.status.approved":"\uC2B9\uC778\uB428","report.status.rejected":"\uAE30\uAC01\uB428","report.status.leaderTimeout":"\uB9AC\uB354 \uC751\uB2F5 \uC2DC\uAC04 \uCD08\uACFC","report.status.error":"\uC624\uB958","synthesis.status.consensus":"\uD569\uC758 \uB3C4\uB2EC","synthesis.status.escalated":"\uBD80\uBD84 \uD569\uC758 / \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","synthesis.section.acceptedItems":"\uCC44\uD0DD \uD56D\uBAA9","synthesis.section.rejectedItems":"\uAE30\uAC01 / \uCCA0\uD68C \uD56D\uBAA9","synthesis.section.openItems":"\uBBF8\uACB0 \uD56D\uBAA9","synthesis.section.sources":"\uADFC\uAC70","synthesis.narration.consensusIn":"\uC804\uCCB4 {max}\uB77C\uC6B4\uB4DC \uC911 {round}\uB77C\uC6B4\uB4DC\uC5D0\uC11C \uD569\uC758\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC2B5\uB2C8\uB2E4.","synthesis.narration.escalated":"{round}\uB77C\uC6B4\uB4DC \uB3D9\uC548 \uD569\uC758\uC5D0 \uC774\uB974\uC9C0 \uBABB\uD558\uC5EC \uC0AC\uC6A9\uC790 \uD310\uB2E8\uC73C\uB85C \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","synthesis.narration.leaderNote":"\uB9AC\uB354 \uBA54\uBAA8","approval.pending":"\uB9AC\uB354 \uC2B9\uC778\uC744 \uAE30\uB2E4\uB9AC\uACE0 \uC788\uC2B5\uB2C8\uB2E4. `agent_debate_approve`, `agent_debate_continue`, `agent_debate_reject` \uC911 \uD558\uB098\uB97C \uD638\uCD9C\uD574 \uC8FC\uC2ED\uC2DC\uC624.","approval.timeout":"\uB9AC\uB354 \uACB0\uC815\uC744 \uAE30\uB2E4\uB9AC\uB2E4 \uC138\uC158\uC774 \uC2DC\uAC04 \uCD08\uACFC\uB418\uC5C8\uC2B5\uB2C8\uB2E4({hours}\uC2DC\uAC04).","moderator.narration.roundHeader":"{round}/{max} \uB77C\uC6B4\uB4DC","moderator.narration.consensusInRound":"{round}\uB77C\uC6B4\uB4DC \uB9CC\uC5D0 \uD569\uC758\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC2B5\uB2C8\uB2E4.","moderator.narration.dissentDetailHeader":"\uBBF8\uD574\uACB0 \uD56D\uBAA9","moderator.narration.noInterest":"\uCC38\uAC00\uC790 \uAD00\uC2EC \uC5C6\uC74C","moderator.narration.participantDropout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 \uBC18\uBCF5\uC801 \uC2E4\uD328\uB85C \uC778\uD574 \uC0AC\uC6A9 \uBD88\uAC00 \uC0C1\uD0DC\uB85C \uD45C\uC2DC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.participantTimeout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 \uC774\uBC88 \uB77C\uC6B4\uB4DC\uC5D0 \uC751\uB2F5\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.","moderator.narration.leaderTimeoutFooter":"\uB9AC\uB354 \uC751\uB2F5 \uC2DC\uAC04 \uCD08\uACFC","moderator.narration.rejected":"\uB9AC\uB354\uC5D0 \uC758\uD574 \uC138\uC158\uC774 \uAE30\uAC01\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.approved":"\uB9AC\uB354\uC5D0 \uC758\uD574 \uC138\uC158\uC774 \uC2B9\uC778\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.aliasClarification":"\uBCC4\uCE6D \uD655\uC778 \uB2E8\uACC4","prompt.system.moderator":"\uB2F9\uC2E0\uC740 \uAD6C\uC870\uD654\uB41C \uB2E4\uC911 AI \uD1A0\uB860\uC758 \uC911\uC7AC\uC790\uC785\uB2C8\uB2E4. \uC81C\uC548\uC744 \uC9C1\uC811 \uC791\uC131\uD558\uC9C0 \uC54A\uC73C\uBA70, \uAD6C\uC870\uD654\uB41C \uD22C\uD45C\uB97C \uC9D1\uACC4\uD558\uACE0 \uC911\uB9BD\uC801\uC778 \uD569\uC758\uC548\uC744 \uC0B0\uCD9C\uD569\uB2C8\uB2E4. \uD504\uB85C\uD1A0\uCF5C\uC774 \uC815\uC758\uD55C \uCC44\uB110 \uC548\uC5D0\uC11C\uB9CC \uC751\uB2F5\uD558\uC2ED\uC2DC\uC624.","error.participantTimeout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 {seconds}\uCD08 \uB0B4\uC5D0 \uC751\uB2F5\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.","error.parseFailure":"\uCC38\uAC00\uC790 `{participantId}`\uC758 `<{tag}>` \uBE14\uB85D\uC744 \uD574\uC11D\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.","error.sessionNotFound":"\uD1A0\uB860 \uC138\uC158 `{sessionId}`\uC744(\uB97C) \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.","error.invalidState":"\uC0C1\uD0DC `{state}`\uC5D0\uC11C\uB294 `{operation}` \uC791\uC5C5\uC744 \uC218\uD589\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.","error.unknownLocaleFallback":"\uC54C \uC218 \uC5C6\uB294 \uB85C\uCF00\uC77C `{locale}`; \uAE30\uBCF8\uAC12 `{fallback}`(\uC73C)\uB85C \uB300\uCCB4\uD569\uB2C8\uB2E4.","askUser.escalation.header":"\uCD5C\uB300 \uB77C\uC6B4\uB4DC\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC73C\uB098 \uD569\uC758\uC5D0 \uC774\uB974\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4","askUser.escalation.question":"\uC5B4\uB5BB\uAC8C \uC9C4\uD589\uD558\uC2DC\uACA0\uC2B5\uB2C8\uAE4C?","askUser.escalation.continue":"{rounds}\uB77C\uC6B4\uB4DC \uCD94\uAC00 \uC9C4\uD589","askUser.escalation.escalate":"\uD569\uC758 \uC5C6\uC774 \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","askUser.escalation.stop":"\uD1A0\uB860 \uC885\uB8CC"};var pm={"report.header.topic":"\u30C6\u30FC\u30DE","report.header.participants":"\u53C2\u52A0\u8005","report.header.individualDocs":"\u500B\u5225\u30EC\u30D3\u30E5\u30FC\u6587\u66F8","report.table.proposer":"\u63D0\u6848\u8005","report.table.opinion":"\u610F\u898B","report.table.severity":"\u91CD\u5927\u5EA6","report.table.agreement":"\u5408\u610F\u7387","report.section.mainTable":"\u63D0\u6848\u53F0\u5E33","report.section.dissentDetail":"\u672A\u5408\u610F\u9805\u76EE\u306E\u8A73\u7D30","report.section.contributionSummary":"AI \u8CA2\u732E\u5EA6\u30B5\u30DE\u30EA\u30FC","report.contribution.ai":"AI","report.contribution.proposed":"\u63D0\u6848","report.contribution.accepted":"\u63A1\u629E","report.contribution.revises":"\u4FEE\u6B63\u8981\u8ACB","report.contribution.abstains":"\u68C4\u6A29","report.footer.synthesisPath":"\u6700\u7D42\u5408\u610F\u6587\u66F8","report.footer.debatePath":"\u8A0E\u8B70\u8A18\u9332","report.footer.pendingSynthesis":"(\u30EA\u30FC\u30C0\u30FC\u627F\u8A8D\u5F85\u3061)","report.status.running":"\u9032\u884C\u4E2D","report.status.readyForApproval":"\u627F\u8A8D\u5F85\u3061","report.status.consensus":"\u5408\u610F\u5F62\u6210","report.status.escalated":"\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","report.status.approved":"\u627F\u8A8D\u6E08\u307F","report.status.rejected":"\u5374\u4E0B","report.status.leaderTimeout":"\u30EA\u30FC\u30C0\u30FC\u5FDC\u7B54\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8","report.status.error":"\u30A8\u30E9\u30FC","synthesis.status.consensus":"\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F","synthesis.status.escalated":"\u90E8\u5206\u5408\u610F / \u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","synthesis.section.acceptedItems":"\u63A1\u629E\u9805\u76EE","synthesis.section.rejectedItems":"\u5374\u4E0B / \u53D6\u308A\u4E0B\u3052\u9805\u76EE","synthesis.section.openItems":"\u672A\u6C7A\u9805\u76EE","synthesis.section.sources":"\u6839\u62E0","synthesis.narration.consensusIn":"\u5168 {max} \u30E9\u30A6\u30F3\u30C9\u4E2D {round} \u30E9\u30A6\u30F3\u30C9\u76EE\u3067\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F\u3002","synthesis.narration.escalated":"{round} \u30E9\u30A6\u30F3\u30C9\u7D4C\u904E\u3057\u3066\u3082\u5408\u610F\u306B\u81F3\u3089\u305A\u3001\u30E6\u30FC\u30B6\u30FC\u5224\u65AD\u3067\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3\u3055\u308C\u307E\u3057\u305F\u3002","synthesis.narration.leaderNote":"\u30EA\u30FC\u30C0\u30FC\u30E1\u30E2","approval.pending":"\u30EA\u30FC\u30C0\u30FC\u627F\u8A8D\u3092\u5F85\u6A5F\u3057\u3066\u3044\u307E\u3059\u3002`agent_debate_approve`\u3001`agent_debate_continue`\u3001`agent_debate_reject` \u306E\u3044\u305A\u308C\u304B\u3092\u547C\u3073\u51FA\u3057\u3066\u304F\u3060\u3055\u3044\u3002","approval.timeout":"\u30EA\u30FC\u30C0\u30FC\u5224\u65AD\u3092\u5F85\u6A5F\u4E2D\u306B\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8\u3057\u307E\u3057\u305F({hours} \u6642\u9593)\u3002","moderator.narration.roundHeader":"\u30E9\u30A6\u30F3\u30C9 {round}/{max}","moderator.narration.consensusInRound":"{round} \u30E9\u30A6\u30F3\u30C9\u76EE\u3067\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F\u3002","moderator.narration.dissentDetailHeader":"\u672A\u89E3\u6C7A\u9805\u76EE","moderator.narration.noInterest":"\u53C2\u52A0\u8005\u306E\u95A2\u5FC3\u306A\u3057","moderator.narration.participantDropout":"\u53C2\u52A0\u8005 `{participantId}` \u306F\u7E70\u308A\u8FD4\u3057\u306E\u5931\u6557\u306B\u3088\u308A\u5229\u7528\u4E0D\u53EF\u3068\u3057\u3066\u30DE\u30FC\u30AF\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.participantTimeout":"\u53C2\u52A0\u8005 `{participantId}` \u306F\u4ECA\u56DE\u306E\u30E9\u30A6\u30F3\u30C9\u3067\u5FDC\u7B54\u3057\u307E\u305B\u3093\u3067\u3057\u305F\u3002","moderator.narration.leaderTimeoutFooter":"\u30EA\u30FC\u30C0\u30FC\u5FDC\u7B54\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8","moderator.narration.rejected":"\u30EA\u30FC\u30C0\u30FC\u306B\u3088\u308A\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u5374\u4E0B\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.approved":"\u30EA\u30FC\u30C0\u30FC\u306B\u3088\u308A\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u627F\u8A8D\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.aliasClarification":"\u5225\u540D\u78BA\u8A8D\u30D5\u30A7\u30FC\u30BA","prompt.system.moderator":"\u3042\u306A\u305F\u306F\u69CB\u9020\u5316\u30DE\u30EB\u30C1 AI \u8A0E\u8B70\u306E\u30E2\u30C7\u30EC\u30FC\u30BF\u30FC\u3067\u3059\u3002\u63D0\u6848\u3092\u81EA\u3089\u8D77\u6848\u305B\u305A\u3001\u69CB\u9020\u5316\u6295\u7968\u3092\u96C6\u8A08\u3057\u3066\u4E2D\u7ACB\u7684\u306A\u5408\u610F\u6848\u3092\u63D0\u793A\u3057\u307E\u3059\u3002\u30D7\u30ED\u30C8\u30B3\u30EB\u304C\u5B9A\u7FA9\u3059\u308B\u30C1\u30E3\u30CD\u30EB\u306E\u7BC4\u56F2\u5185\u3067\u306E\u307F\u5FDC\u7B54\u3057\u3066\u304F\u3060\u3055\u3044\u3002","error.participantTimeout":"\u53C2\u52A0\u8005 `{participantId}` \u306F {seconds} \u79D2\u4EE5\u5185\u306B\u5FDC\u7B54\u3057\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.parseFailure":"\u53C2\u52A0\u8005 `{participantId}` \u306E `<{tag}>` \u30D6\u30ED\u30C3\u30AF\u3092\u89E3\u6790\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.sessionNotFound":"\u8A0E\u8B70\u30BB\u30C3\u30B7\u30E7\u30F3 `{sessionId}` \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.invalidState":"\u72B6\u614B `{state}` \u3067\u306F\u64CD\u4F5C `{operation}` \u3092\u5B9F\u884C\u3067\u304D\u307E\u305B\u3093\u3002","error.unknownLocaleFallback":"\u672A\u77E5\u306E\u30ED\u30B1\u30FC\u30EB `{locale}`\u3002\u65E2\u5B9A\u5024 `{fallback}` \u306B\u30D5\u30A9\u30FC\u30EB\u30D0\u30C3\u30AF\u3057\u307E\u3059\u3002","askUser.escalation.header":"\u6700\u5927\u30E9\u30A6\u30F3\u30C9\u306B\u9054\u3057\u307E\u3057\u305F\u304C\u5408\u610F\u306B\u81F3\u308A\u307E\u305B\u3093\u3067\u3057\u305F","askUser.escalation.question":"\u3069\u306E\u3088\u3046\u306B\u9032\u3081\u307E\u3059\u304B?","askUser.escalation.continue":"{rounds} \u30E9\u30A6\u30F3\u30C9\u8FFD\u52A0\u3057\u3066\u7D9A\u884C","askUser.escalation.escalate":"\u5408\u610F\u306A\u3057\u3067\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","askUser.escalation.stop":"\u8A0E\u8B70\u3092\u7D42\u4E86"};var fm={"report.header.topic":"\u4E3B\u9898","report.header.participants":"\u53C2\u4E0E\u8005","report.header.individualDocs":"\u4E2A\u4EBA\u8BC4\u5BA1\u6587\u6863","report.table.proposer":"\u63D0\u8BAE\u8005","report.table.opinion":"\u610F\u89C1","report.table.severity":"\u4E25\u91CD\u7A0B\u5EA6","report.table.agreement":"\u540C\u610F\u7387","report.section.mainTable":"\u63D0\u6848\u53F0\u8D26","report.section.dissentDetail":"\u672A\u8FBE\u6210\u4E00\u81F4\u9879\u8BE6\u60C5","report.section.contributionSummary":"AI \u8D21\u732E\u6C47\u603B","report.contribution.ai":"AI","report.contribution.proposed":"\u63D0\u51FA","report.contribution.accepted":"\u91C7\u7EB3","report.contribution.revises":"\u4FEE\u8BA2\u8BF7\u6C42","report.contribution.abstains":"\u5F03\u6743","report.footer.synthesisPath":"\u6700\u7EC8\u5171\u8BC6\u6587\u6863","report.footer.debatePath":"\u8FA9\u8BBA\u8BB0\u5F55","report.footer.pendingSynthesis":"(\u7B49\u5F85\u8D1F\u8D23\u4EBA\u6279\u51C6)","report.status.running":"\u8FDB\u884C\u4E2D","report.status.readyForApproval":"\u5F85\u6279\u51C6","report.status.consensus":"\u5DF2\u8FBE\u6210\u5171\u8BC6","report.status.escalated":"\u5DF2\u5347\u7EA7","report.status.approved":"\u5DF2\u6279\u51C6","report.status.rejected":"\u5DF2\u62D2\u7EDD","report.status.leaderTimeout":"\u8D1F\u8D23\u4EBA\u54CD\u5E94\u8D85\u65F6","report.status.error":"\u9519\u8BEF","synthesis.status.consensus":"\u5DF2\u8FBE\u6210\u5171\u8BC6","synthesis.status.escalated":"\u90E8\u5206\u5171\u8BC6 / \u5DF2\u5347\u7EA7","synthesis.section.acceptedItems":"\u91C7\u7EB3\u9879","synthesis.section.rejectedItems":"\u62D2\u7EDD / \u64A4\u56DE\u9879","synthesis.section.openItems":"\u672A\u51B3\u9879","synthesis.section.sources":"\u4F9D\u636E","synthesis.narration.consensusIn":"\u5728\u5168\u90E8 {max} \u8F6E\u4E2D\u7684\u7B2C {round} \u8F6E\u8FBE\u6210\u5171\u8BC6\u3002","synthesis.narration.escalated":"\u7ECF\u8FC7 {round} \u8F6E\u4ECD\u672A\u8FBE\u6210\u5171\u8BC6,\u7531\u7528\u6237\u51B3\u5B9A\u5347\u7EA7\u5904\u7406\u3002","synthesis.narration.leaderNote":"\u8D1F\u8D23\u4EBA\u5907\u6CE8","approval.pending":"\u7B49\u5F85\u8D1F\u8D23\u4EBA\u6279\u51C6\u3002\u8BF7\u8C03\u7528 `agent_debate_approve`\u3001`agent_debate_continue` \u6216 `agent_debate_reject`\u3002","approval.timeout":"\u7B49\u5F85\u8D1F\u8D23\u4EBA\u51B3\u7B56\u671F\u95F4\u4F1A\u8BDD\u5DF2\u8D85\u65F6({hours} \u5C0F\u65F6)\u3002","moderator.narration.roundHeader":"\u7B2C {round}/{max} \u8F6E","moderator.narration.consensusInRound":"\u5728\u7B2C {round} \u8F6E\u8FBE\u6210\u5171\u8BC6\u3002","moderator.narration.dissentDetailHeader":"\u672A\u89E3\u51B3\u9879","moderator.narration.noInterest":"\u53C2\u4E0E\u8005\u65E0\u5174\u8DA3","moderator.narration.participantDropout":"\u53C2\u4E0E\u8005 `{participantId}` \u56E0\u591A\u6B21\u5931\u8D25\u88AB\u6807\u8BB0\u4E3A\u4E0D\u53EF\u7528\u3002","moderator.narration.participantTimeout":"\u53C2\u4E0E\u8005 `{participantId}` \u5728\u672C\u8F6E\u672A\u4F5C\u51FA\u54CD\u5E94\u3002","moderator.narration.leaderTimeoutFooter":"\u8D1F\u8D23\u4EBA\u54CD\u5E94\u8D85\u65F6","moderator.narration.rejected":"\u8D1F\u8D23\u4EBA\u5DF2\u62D2\u7EDD\u8BE5\u4F1A\u8BDD\u3002","moderator.narration.approved":"\u8D1F\u8D23\u4EBA\u5DF2\u6279\u51C6\u8BE5\u4F1A\u8BDD\u3002","moderator.narration.aliasClarification":"\u522B\u540D\u6F84\u6E05\u9636\u6BB5","prompt.system.moderator":"\u4F60\u662F\u7ED3\u6784\u5316\u591A AI \u8FA9\u8BBA\u7684\u4E3B\u6301\u4EBA\u3002\u4F60\u4E0D\u64B0\u5199\u63D0\u6848,\u800C\u662F\u6C47\u603B\u7ED3\u6784\u5316\u6295\u7968\u5E76\u4EA7\u51FA\u4E2D\u7ACB\u7684\u5171\u8BC6\u65B9\u6848\u3002\u4EC5\u5728\u534F\u8BAE\u5B9A\u4E49\u7684\u901A\u9053\u8303\u56F4\u5185\u4F5C\u51FA\u54CD\u5E94\u3002","error.participantTimeout":"\u53C2\u4E0E\u8005 `{participantId}` \u5728 {seconds} \u79D2\u5185\u672A\u54CD\u5E94\u3002","error.parseFailure":"\u65E0\u6CD5\u89E3\u6790\u53C2\u4E0E\u8005 `{participantId}` \u7684 `<{tag}>` \u5757\u3002","error.sessionNotFound":"\u672A\u627E\u5230\u8FA9\u8BBA\u4F1A\u8BDD `{sessionId}`\u3002","error.invalidState":"\u5728\u72B6\u6001 `{state}` \u4E0B\u4E0D\u5141\u8BB8\u6267\u884C\u64CD\u4F5C `{operation}`\u3002","error.unknownLocaleFallback":"\u672A\u77E5\u533A\u57DF `{locale}`,\u56DE\u9000\u5230 `{fallback}`\u3002","askUser.escalation.header":"\u5DF2\u8FBE\u6700\u5927\u8F6E\u6B21\u4F46\u4ECD\u672A\u8FBE\u6210\u5171\u8BC6","askUser.escalation.question":"\u60A8\u5E0C\u671B\u5982\u4F55\u7EE7\u7EED?","askUser.escalation.continue":"\u518D\u8FDB\u884C {rounds} \u8F6E","askUser.escalation.escalate":"\u4E0D\u8FBE\u6210\u5171\u8BC6\u5373\u5347\u7EA7","askUser.escalation.stop":"\u7ED3\u675F\u8FA9\u8BBA"};var mm=Object.freeze({en:lm,ko:dm,ja:pm,zh:fm});function h0(t){return typeof t=="string"&&Bs.includes(t)}function Yc(t,e){return e===void 0?t:t.replace(/\{(\w+)\}/g,(r,n)=>{if(Object.prototype.hasOwnProperty.call(e,n)){let o=e[n];return typeof o=="number"?String(o):o}return r})}function hm(t){return t===void 0?Qc(xr):h0(t)?Qc(t):(console.warn(`[i18n] unknown locale '${t}', falling back to ${xr}`),Qc(xr))}function g0(t,e,r){let n=new Set;return{locale:t,t(o,s){let i=e[o];if(i!==void 0)return Yc(i,s);let a=r[o];return a!==void 0?(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in locale '${t}', falling back to ${Oc}`)),Yc(a,s)):(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in all bundles; returning raw key`)),Yc(o,s))}}}function Qc(t){return g0(t,mm[t],mm[Oc])}async function gm(t){let e=await fetch(`${t}/api/tags`);if(!e.ok)throw new Error(`Ollama API error: ${e.status}`);return((await e.json()).models||[]).map(n=>({name:n.name||"unknown",size:n.size||0,strengths:y0(n.name||"")}))}function y0(t){let e=["chat"],r=t.toLowerCase();return(r.includes("coder")||r.includes("code"))&&e.push("code_review","code_generation"),r.includes("instruct")&&e.push("instruction_following"),r.includes("embed")&&e.push("embedding"),e}var qr=class t{id;type="ollama";host;defaultModel;maxContext;available=!1;unavailableUntil=0;models=[];timeouts;static RATE_LIMIT_BACKOFF_MS=6e4;constructor(e){this.id=e.id,this.host=e.host,this.defaultModel=e.defaultModel||"auto",this.maxContext=e.maxContext??32768,this.timeouts={default:e.timeouts?.default??3e4,generate:e.timeouts?.generate??3e5,chat:e.timeouts?.chat??3e5}}async initialize(){try{this.models=await gm(this.host),this.available=this.models.length>0}catch{this.available=!1}}async healthCheck(){try{let e=await fetch(`${this.host}/api/tags`);if(!e.ok)return{status:"error",message:`HTTP ${e.status}`};let r=await e.json(),n=r.models?.length??0;return{status:n>0?"ok":"degraded",message:`${n} models available`,details:{models:r.models?.map(o=>o.name)}}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:this.maxContext,supportsSystemPrompt:!0,supportsFiles:!1,supportsStreaming:!0,supportsJsonOutput:!1,supportsToolUse:!0,strengths:[...new Set(this.models.flatMap(e=>e.strengths))],models:this.models.map(e=>({name:e.name,description:`Ollama model (${Math.round(e.size/1e9)}GB)`,strengths:e.strengths,sizeGb:e.size/1e9}))}}isAvailable(){return this.unavailableUntil>0&&Date.now()<this.unavailableUntil?!1:(this.unavailableUntil>0&&Date.now()>=this.unavailableUntil&&(this.unavailableUntil=0),this.available)}async chat(e){if(!this.available)throw new me(this.id,"Ollama not running or no models installed");let r=e.model||this.selectModel(),n={model:r,prompt:e.prompt,system:e.system||"You are a helpful assistant.",stream:!1,...e.extra||{}},o=new AbortController,s=setTimeout(()=>o.abort(),this.timeouts.generate);try{let i=await fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal});if(i.status===429)throw this.unavailableUntil=Date.now()+t.RATE_LIMIT_BACKOFF_MS,new me(this.id,`Rate limited (429) \u2014 temporarily deactivated for ${t.RATE_LIMIT_BACKOFF_MS/1e3}s`);if(!i.ok)throw new He(this.id,`HTTP ${i.status}: ${i.statusText}`);let a=await i.json();return{text:a.response||"",model:a.model||r,provider:this.id}}catch(i){throw i.name==="AbortError"?new un(this.id,this.timeouts.generate):i instanceof He||i instanceof me?i:new He(this.id,i.message)}finally{clearTimeout(s)}}selectModel(){if(this.defaultModel!=="auto")return this.defaultModel;if(this.models.length===0)throw new me(this.id,`No models detected. Install a model first (ollama pull ${Qp})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var _0=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function ym(t){return t.split(`
|
|
40
|
-
`).filter(n=>{let o=n.trim();return o?!
|
|
41
|
-
`).trim()}function
|
|
42
|
-
`);for(let r=e.length-1;r>=0;r--){let n=e[r].trim();if(n.startsWith("{"))try{let o=JSON.parse(n);if(o&&typeof o.response=="string")return o.response}catch{}}}return null}var
|
|
43
|
+
\`\`\``);return e}function A0(t,e){let r=e?.model;return typeof r=="string"&&r.length>0?r:t}var fr=class{id;type;bridge;modelName;displayName;capabilities;constructor(e){this.id=e.id??e.bridge.providerId,this.type=e.type,this.bridge=e.bridge,this.modelName=e.modelName??e.type,this.displayName=e.displayName,this.capabilities=e.capabilities}async initialize(){}async healthCheck(){return this.bridge.healthCheck?this.bridge.healthCheck():this.bridge.isAvailable()?{status:"ok",message:`${this.displayName} host bridge available`}:{status:"error",message:`${this.displayName} host bridge unavailable`}}getCapabilities(){return{...this.capabilities,models:this.capabilities.models.map((e,r)=>r===0?{...e,name:this.modelName}:{...e})}}getDescriptor(){return ir(this,this.getCapabilities())}isAvailable(){return this.bridge.isAvailable()}async chat(e){if(!this.isAvailable())throw new de(this.id,`${this.displayName} host bridge is not available`);try{let r=I0(e),n={...e.extra??{}};e.model&&(n.model=e.model),typeof e.temperature=="number"&&(n.temperature=e.temperature),typeof e.maxTokens=="number"&&(n.maxTokens=e.maxTokens);let o=await this.bridge.runTurn({prompt:r,system:e.system,metadata:n});return{text:o.text,model:A0(this.modelName,o.metadata),provider:this.id,metadata:o.metadata}}catch(r){let n=r instanceof Error?r.message:String(r);throw/sampling|host bridge unavailable|does not support/i.test(n)?new de(this.id,n):new We(this.id,n)}}};var C0={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["reasoning","review","synthesis","moderation"],models:[{name:"claude-host",description:"Claude host model via MCP sampling bridge",strengths:["reasoning","review","synthesis"]}]},_i=class extends fr{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:C0,modelName:e.modelName??"claude-host"})}};var D0={maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["coding","reasoning","review","implementation"],models:[{name:"codex-host",description:"Codex host model via MCP sampling bridge",strengths:["coding","implementation","review"]}]},bi=class extends fr{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:D0,modelName:e.modelName??"codex-host"})}};var z0={maxContext:1e6,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!1,supportsToolUse:!1,strengths:["analysis","reasoning","research","review"],models:[{name:"gemini-host",description:"Gemini host model via MCP sampling bridge",strengths:["analysis","research","review"]}]},wi=class extends fr{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:z0,modelName:e.modelName??"gemini-host"})}};Vt();var Pm={"report.header.topic":"Topic","report.header.participants":"Participants","report.header.individualDocs":"Individual documents","report.table.proposer":"Proposer","report.table.opinion":"Opinion","report.table.severity":"Severity","report.table.agreement":"Agreement","report.section.mainTable":"Proposal ledger","report.section.dissentDetail":"Dissenting items","report.section.contributionSummary":"AI contribution summary","report.contribution.ai":"AI","report.contribution.proposed":"Proposed","report.contribution.accepted":"Accepted","report.contribution.revises":"Revises issued","report.contribution.abstains":"Abstains","report.footer.synthesisPath":"Final synthesis document","report.footer.debatePath":"Debate transcript","report.footer.pendingSynthesis":"(pending leader approval)","report.status.running":"running","report.status.readyForApproval":"ready for approval","report.status.consensus":"consensus","report.status.escalated":"escalated","report.status.approved":"approved","report.status.rejected":"rejected","report.status.leaderTimeout":"leader timeout","report.status.error":"error","synthesis.status.consensus":"Consensus reached","synthesis.status.escalated":"Partial / escalated","synthesis.section.acceptedItems":"Accepted Items","synthesis.section.rejectedItems":"Rejected / Withdrawn Items","synthesis.section.openItems":"Open Items","synthesis.section.sources":"Sources","synthesis.narration.consensusIn":"Consensus reached in round {round} of {max}.","synthesis.narration.escalated":"Session escalated by user after {round} rounds without consensus.","synthesis.narration.leaderNote":"Leader note","approval.pending":"Awaiting leader approval. Call `agent_debate_approve`, `agent_debate_continue`, or `agent_debate_reject`.","approval.timeout":"Session timed out waiting for leader decision ({hours}h).","moderator.narration.roundHeader":"Round {round} of {max}","moderator.narration.consensusInRound":"Consensus reached after {round} round(s).","moderator.narration.dissentDetailHeader":"Unresolved items","moderator.narration.noInterest":"No interest from participants","moderator.narration.participantDropout":"Participant `{participantId}` marked unavailable after repeated failures.","moderator.narration.participantTimeout":"Participant `{participantId}` did not respond in this round.","moderator.narration.leaderTimeoutFooter":"Leader Timeout","moderator.narration.rejected":"Session rejected by leader.","moderator.narration.approved":"Session approved by leader.","moderator.narration.aliasClarification":"Alias clarification phase","prompt.system.moderator":"You are the moderator of a structured multi-AI debate. You do not author proposals; you aggregate structured votes and produce a neutral synthesis. Respond only in the channels the protocol defines.","error.participantTimeout":"Participant `{participantId}` timed out after {seconds}s.","error.parseFailure":"Could not parse `<{tag}>` block from `{participantId}`.","error.sessionNotFound":"Debate session `{sessionId}` was not found.","error.invalidState":"Operation `{operation}` is not allowed in state `{state}`.","error.unknownLocaleFallback":"Unknown locale `{locale}`; falling back to `{fallback}`.","askUser.escalation.header":"Maximum rounds reached without consensus","askUser.escalation.question":"How would you like to proceed?","askUser.escalation.continue":"Continue +{rounds} rounds","askUser.escalation.escalate":"Escalate without consensus","askUser.escalation.stop":"Stop the debate"};var Tm={"report.header.topic":"\uC8FC\uC81C","report.header.participants":"\uCC38\uAC00\uC790","report.header.individualDocs":"\uAC1C\uBCC4 \uAC80\uD1A0 \uBB38\uC11C","report.table.proposer":"\uC81C\uC548\uC790","report.table.opinion":"\uC758\uACAC","report.table.severity":"\uC911\uC694\uB3C4","report.table.agreement":"\uB3D9\uC758\uC728","report.section.mainTable":"\uC81C\uC548 \uC6D0\uC7A5","report.section.dissentDetail":"\uBBF8\uD569\uC758 \uD56D\uBAA9 \uC0C1\uC138","report.section.contributionSummary":"AI \uAE30\uC5EC\uB3C4 \uC694\uC57D","report.contribution.ai":"AI","report.contribution.proposed":"\uC81C\uC548","report.contribution.accepted":"\uCC44\uD0DD","report.contribution.revises":"\uC218\uC815 \uC694\uCCAD","report.contribution.abstains":"\uAE30\uAD8C","report.footer.synthesisPath":"\uCD5C\uC885 \uD569\uC758 \uBB38\uC11C","report.footer.debatePath":"\uD1A0\uB860 \uAE30\uB85D","report.footer.pendingSynthesis":"(\uB9AC\uB354 \uC2B9\uC778 \uB300\uAE30 \uC911)","report.status.running":"\uC9C4\uD589 \uC911","report.status.readyForApproval":"\uC2B9\uC778 \uB300\uAE30","report.status.consensus":"\uD569\uC758 \uB3C4\uB2EC","report.status.escalated":"\uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","report.status.approved":"\uC2B9\uC778\uB428","report.status.rejected":"\uAE30\uAC01\uB428","report.status.leaderTimeout":"\uB9AC\uB354 \uC751\uB2F5 \uC2DC\uAC04 \uCD08\uACFC","report.status.error":"\uC624\uB958","synthesis.status.consensus":"\uD569\uC758 \uB3C4\uB2EC","synthesis.status.escalated":"\uBD80\uBD84 \uD569\uC758 / \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","synthesis.section.acceptedItems":"\uCC44\uD0DD \uD56D\uBAA9","synthesis.section.rejectedItems":"\uAE30\uAC01 / \uCCA0\uD68C \uD56D\uBAA9","synthesis.section.openItems":"\uBBF8\uACB0 \uD56D\uBAA9","synthesis.section.sources":"\uADFC\uAC70","synthesis.narration.consensusIn":"\uC804\uCCB4 {max}\uB77C\uC6B4\uB4DC \uC911 {round}\uB77C\uC6B4\uB4DC\uC5D0\uC11C \uD569\uC758\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC2B5\uB2C8\uB2E4.","synthesis.narration.escalated":"{round}\uB77C\uC6B4\uB4DC \uB3D9\uC548 \uD569\uC758\uC5D0 \uC774\uB974\uC9C0 \uBABB\uD558\uC5EC \uC0AC\uC6A9\uC790 \uD310\uB2E8\uC73C\uB85C \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","synthesis.narration.leaderNote":"\uB9AC\uB354 \uBA54\uBAA8","approval.pending":"\uB9AC\uB354 \uC2B9\uC778\uC744 \uAE30\uB2E4\uB9AC\uACE0 \uC788\uC2B5\uB2C8\uB2E4. `agent_debate_approve`, `agent_debate_continue`, `agent_debate_reject` \uC911 \uD558\uB098\uB97C \uD638\uCD9C\uD574 \uC8FC\uC2ED\uC2DC\uC624.","approval.timeout":"\uB9AC\uB354 \uACB0\uC815\uC744 \uAE30\uB2E4\uB9AC\uB2E4 \uC138\uC158\uC774 \uC2DC\uAC04 \uCD08\uACFC\uB418\uC5C8\uC2B5\uB2C8\uB2E4({hours}\uC2DC\uAC04).","moderator.narration.roundHeader":"{round}/{max} \uB77C\uC6B4\uB4DC","moderator.narration.consensusInRound":"{round}\uB77C\uC6B4\uB4DC \uB9CC\uC5D0 \uD569\uC758\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC2B5\uB2C8\uB2E4.","moderator.narration.dissentDetailHeader":"\uBBF8\uD574\uACB0 \uD56D\uBAA9","moderator.narration.noInterest":"\uCC38\uAC00\uC790 \uAD00\uC2EC \uC5C6\uC74C","moderator.narration.participantDropout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 \uBC18\uBCF5\uC801 \uC2E4\uD328\uB85C \uC778\uD574 \uC0AC\uC6A9 \uBD88\uAC00 \uC0C1\uD0DC\uB85C \uD45C\uC2DC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.participantTimeout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 \uC774\uBC88 \uB77C\uC6B4\uB4DC\uC5D0 \uC751\uB2F5\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.","moderator.narration.leaderTimeoutFooter":"\uB9AC\uB354 \uC751\uB2F5 \uC2DC\uAC04 \uCD08\uACFC","moderator.narration.rejected":"\uB9AC\uB354\uC5D0 \uC758\uD574 \uC138\uC158\uC774 \uAE30\uAC01\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.approved":"\uB9AC\uB354\uC5D0 \uC758\uD574 \uC138\uC158\uC774 \uC2B9\uC778\uB418\uC5C8\uC2B5\uB2C8\uB2E4.","moderator.narration.aliasClarification":"\uBCC4\uCE6D \uD655\uC778 \uB2E8\uACC4","prompt.system.moderator":"\uB2F9\uC2E0\uC740 \uAD6C\uC870\uD654\uB41C \uB2E4\uC911 AI \uD1A0\uB860\uC758 \uC911\uC7AC\uC790\uC785\uB2C8\uB2E4. \uC81C\uC548\uC744 \uC9C1\uC811 \uC791\uC131\uD558\uC9C0 \uC54A\uC73C\uBA70, \uAD6C\uC870\uD654\uB41C \uD22C\uD45C\uB97C \uC9D1\uACC4\uD558\uACE0 \uC911\uB9BD\uC801\uC778 \uD569\uC758\uC548\uC744 \uC0B0\uCD9C\uD569\uB2C8\uB2E4. \uD504\uB85C\uD1A0\uCF5C\uC774 \uC815\uC758\uD55C \uCC44\uB110 \uC548\uC5D0\uC11C\uB9CC \uC751\uB2F5\uD558\uC2ED\uC2DC\uC624.","error.participantTimeout":"\uCC38\uAC00\uC790 `{participantId}`\uAC00 {seconds}\uCD08 \uB0B4\uC5D0 \uC751\uB2F5\uD558\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.","error.parseFailure":"\uCC38\uAC00\uC790 `{participantId}`\uC758 `<{tag}>` \uBE14\uB85D\uC744 \uD574\uC11D\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4.","error.sessionNotFound":"\uD1A0\uB860 \uC138\uC158 `{sessionId}`\uC744(\uB97C) \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.","error.invalidState":"\uC0C1\uD0DC `{state}`\uC5D0\uC11C\uB294 `{operation}` \uC791\uC5C5\uC744 \uC218\uD589\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.","error.unknownLocaleFallback":"\uC54C \uC218 \uC5C6\uB294 \uB85C\uCF00\uC77C `{locale}`; \uAE30\uBCF8\uAC12 `{fallback}`(\uC73C)\uB85C \uB300\uCCB4\uD569\uB2C8\uB2E4.","askUser.escalation.header":"\uCD5C\uB300 \uB77C\uC6B4\uB4DC\uC5D0 \uB3C4\uB2EC\uD558\uC600\uC73C\uB098 \uD569\uC758\uC5D0 \uC774\uB974\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4","askUser.escalation.question":"\uC5B4\uB5BB\uAC8C \uC9C4\uD589\uD558\uC2DC\uACA0\uC2B5\uB2C8\uAE4C?","askUser.escalation.continue":"{rounds}\uB77C\uC6B4\uB4DC \uCD94\uAC00 \uC9C4\uD589","askUser.escalation.escalate":"\uD569\uC758 \uC5C6\uC774 \uC5D0\uC2A4\uCEEC\uB808\uC774\uC158","askUser.escalation.stop":"\uD1A0\uB860 \uC885\uB8CC"};var Em={"report.header.topic":"\u30C6\u30FC\u30DE","report.header.participants":"\u53C2\u52A0\u8005","report.header.individualDocs":"\u500B\u5225\u30EC\u30D3\u30E5\u30FC\u6587\u66F8","report.table.proposer":"\u63D0\u6848\u8005","report.table.opinion":"\u610F\u898B","report.table.severity":"\u91CD\u5927\u5EA6","report.table.agreement":"\u5408\u610F\u7387","report.section.mainTable":"\u63D0\u6848\u53F0\u5E33","report.section.dissentDetail":"\u672A\u5408\u610F\u9805\u76EE\u306E\u8A73\u7D30","report.section.contributionSummary":"AI \u8CA2\u732E\u5EA6\u30B5\u30DE\u30EA\u30FC","report.contribution.ai":"AI","report.contribution.proposed":"\u63D0\u6848","report.contribution.accepted":"\u63A1\u629E","report.contribution.revises":"\u4FEE\u6B63\u8981\u8ACB","report.contribution.abstains":"\u68C4\u6A29","report.footer.synthesisPath":"\u6700\u7D42\u5408\u610F\u6587\u66F8","report.footer.debatePath":"\u8A0E\u8B70\u8A18\u9332","report.footer.pendingSynthesis":"(\u30EA\u30FC\u30C0\u30FC\u627F\u8A8D\u5F85\u3061)","report.status.running":"\u9032\u884C\u4E2D","report.status.readyForApproval":"\u627F\u8A8D\u5F85\u3061","report.status.consensus":"\u5408\u610F\u5F62\u6210","report.status.escalated":"\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","report.status.approved":"\u627F\u8A8D\u6E08\u307F","report.status.rejected":"\u5374\u4E0B","report.status.leaderTimeout":"\u30EA\u30FC\u30C0\u30FC\u5FDC\u7B54\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8","report.status.error":"\u30A8\u30E9\u30FC","synthesis.status.consensus":"\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F","synthesis.status.escalated":"\u90E8\u5206\u5408\u610F / \u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","synthesis.section.acceptedItems":"\u63A1\u629E\u9805\u76EE","synthesis.section.rejectedItems":"\u5374\u4E0B / \u53D6\u308A\u4E0B\u3052\u9805\u76EE","synthesis.section.openItems":"\u672A\u6C7A\u9805\u76EE","synthesis.section.sources":"\u6839\u62E0","synthesis.narration.consensusIn":"\u5168 {max} \u30E9\u30A6\u30F3\u30C9\u4E2D {round} \u30E9\u30A6\u30F3\u30C9\u76EE\u3067\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F\u3002","synthesis.narration.escalated":"{round} \u30E9\u30A6\u30F3\u30C9\u7D4C\u904E\u3057\u3066\u3082\u5408\u610F\u306B\u81F3\u3089\u305A\u3001\u30E6\u30FC\u30B6\u30FC\u5224\u65AD\u3067\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3\u3055\u308C\u307E\u3057\u305F\u3002","synthesis.narration.leaderNote":"\u30EA\u30FC\u30C0\u30FC\u30E1\u30E2","approval.pending":"\u30EA\u30FC\u30C0\u30FC\u627F\u8A8D\u3092\u5F85\u6A5F\u3057\u3066\u3044\u307E\u3059\u3002`agent_debate_approve`\u3001`agent_debate_continue`\u3001`agent_debate_reject` \u306E\u3044\u305A\u308C\u304B\u3092\u547C\u3073\u51FA\u3057\u3066\u304F\u3060\u3055\u3044\u3002","approval.timeout":"\u30EA\u30FC\u30C0\u30FC\u5224\u65AD\u3092\u5F85\u6A5F\u4E2D\u306B\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8\u3057\u307E\u3057\u305F({hours} \u6642\u9593)\u3002","moderator.narration.roundHeader":"\u30E9\u30A6\u30F3\u30C9 {round}/{max}","moderator.narration.consensusInRound":"{round} \u30E9\u30A6\u30F3\u30C9\u76EE\u3067\u5408\u610F\u306B\u9054\u3057\u307E\u3057\u305F\u3002","moderator.narration.dissentDetailHeader":"\u672A\u89E3\u6C7A\u9805\u76EE","moderator.narration.noInterest":"\u53C2\u52A0\u8005\u306E\u95A2\u5FC3\u306A\u3057","moderator.narration.participantDropout":"\u53C2\u52A0\u8005 `{participantId}` \u306F\u7E70\u308A\u8FD4\u3057\u306E\u5931\u6557\u306B\u3088\u308A\u5229\u7528\u4E0D\u53EF\u3068\u3057\u3066\u30DE\u30FC\u30AF\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.participantTimeout":"\u53C2\u52A0\u8005 `{participantId}` \u306F\u4ECA\u56DE\u306E\u30E9\u30A6\u30F3\u30C9\u3067\u5FDC\u7B54\u3057\u307E\u305B\u3093\u3067\u3057\u305F\u3002","moderator.narration.leaderTimeoutFooter":"\u30EA\u30FC\u30C0\u30FC\u5FDC\u7B54\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8","moderator.narration.rejected":"\u30EA\u30FC\u30C0\u30FC\u306B\u3088\u308A\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u5374\u4E0B\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.approved":"\u30EA\u30FC\u30C0\u30FC\u306B\u3088\u308A\u30BB\u30C3\u30B7\u30E7\u30F3\u304C\u627F\u8A8D\u3055\u308C\u307E\u3057\u305F\u3002","moderator.narration.aliasClarification":"\u5225\u540D\u78BA\u8A8D\u30D5\u30A7\u30FC\u30BA","prompt.system.moderator":"\u3042\u306A\u305F\u306F\u69CB\u9020\u5316\u30DE\u30EB\u30C1 AI \u8A0E\u8B70\u306E\u30E2\u30C7\u30EC\u30FC\u30BF\u30FC\u3067\u3059\u3002\u63D0\u6848\u3092\u81EA\u3089\u8D77\u6848\u305B\u305A\u3001\u69CB\u9020\u5316\u6295\u7968\u3092\u96C6\u8A08\u3057\u3066\u4E2D\u7ACB\u7684\u306A\u5408\u610F\u6848\u3092\u63D0\u793A\u3057\u307E\u3059\u3002\u30D7\u30ED\u30C8\u30B3\u30EB\u304C\u5B9A\u7FA9\u3059\u308B\u30C1\u30E3\u30CD\u30EB\u306E\u7BC4\u56F2\u5185\u3067\u306E\u307F\u5FDC\u7B54\u3057\u3066\u304F\u3060\u3055\u3044\u3002","error.participantTimeout":"\u53C2\u52A0\u8005 `{participantId}` \u306F {seconds} \u79D2\u4EE5\u5185\u306B\u5FDC\u7B54\u3057\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.parseFailure":"\u53C2\u52A0\u8005 `{participantId}` \u306E `<{tag}>` \u30D6\u30ED\u30C3\u30AF\u3092\u89E3\u6790\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.sessionNotFound":"\u8A0E\u8B70\u30BB\u30C3\u30B7\u30E7\u30F3 `{sessionId}` \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3067\u3057\u305F\u3002","error.invalidState":"\u72B6\u614B `{state}` \u3067\u306F\u64CD\u4F5C `{operation}` \u3092\u5B9F\u884C\u3067\u304D\u307E\u305B\u3093\u3002","error.unknownLocaleFallback":"\u672A\u77E5\u306E\u30ED\u30B1\u30FC\u30EB `{locale}`\u3002\u65E2\u5B9A\u5024 `{fallback}` \u306B\u30D5\u30A9\u30FC\u30EB\u30D0\u30C3\u30AF\u3057\u307E\u3059\u3002","askUser.escalation.header":"\u6700\u5927\u30E9\u30A6\u30F3\u30C9\u306B\u9054\u3057\u307E\u3057\u305F\u304C\u5408\u610F\u306B\u81F3\u308A\u307E\u305B\u3093\u3067\u3057\u305F","askUser.escalation.question":"\u3069\u306E\u3088\u3046\u306B\u9032\u3081\u307E\u3059\u304B?","askUser.escalation.continue":"{rounds} \u30E9\u30A6\u30F3\u30C9\u8FFD\u52A0\u3057\u3066\u7D9A\u884C","askUser.escalation.escalate":"\u5408\u610F\u306A\u3057\u3067\u30A8\u30B9\u30AB\u30EC\u30FC\u30B7\u30E7\u30F3","askUser.escalation.stop":"\u8A0E\u8B70\u3092\u7D42\u4E86"};var Rm={"report.header.topic":"\u4E3B\u9898","report.header.participants":"\u53C2\u4E0E\u8005","report.header.individualDocs":"\u4E2A\u4EBA\u8BC4\u5BA1\u6587\u6863","report.table.proposer":"\u63D0\u8BAE\u8005","report.table.opinion":"\u610F\u89C1","report.table.severity":"\u4E25\u91CD\u7A0B\u5EA6","report.table.agreement":"\u540C\u610F\u7387","report.section.mainTable":"\u63D0\u6848\u53F0\u8D26","report.section.dissentDetail":"\u672A\u8FBE\u6210\u4E00\u81F4\u9879\u8BE6\u60C5","report.section.contributionSummary":"AI \u8D21\u732E\u6C47\u603B","report.contribution.ai":"AI","report.contribution.proposed":"\u63D0\u51FA","report.contribution.accepted":"\u91C7\u7EB3","report.contribution.revises":"\u4FEE\u8BA2\u8BF7\u6C42","report.contribution.abstains":"\u5F03\u6743","report.footer.synthesisPath":"\u6700\u7EC8\u5171\u8BC6\u6587\u6863","report.footer.debatePath":"\u8FA9\u8BBA\u8BB0\u5F55","report.footer.pendingSynthesis":"(\u7B49\u5F85\u8D1F\u8D23\u4EBA\u6279\u51C6)","report.status.running":"\u8FDB\u884C\u4E2D","report.status.readyForApproval":"\u5F85\u6279\u51C6","report.status.consensus":"\u5DF2\u8FBE\u6210\u5171\u8BC6","report.status.escalated":"\u5DF2\u5347\u7EA7","report.status.approved":"\u5DF2\u6279\u51C6","report.status.rejected":"\u5DF2\u62D2\u7EDD","report.status.leaderTimeout":"\u8D1F\u8D23\u4EBA\u54CD\u5E94\u8D85\u65F6","report.status.error":"\u9519\u8BEF","synthesis.status.consensus":"\u5DF2\u8FBE\u6210\u5171\u8BC6","synthesis.status.escalated":"\u90E8\u5206\u5171\u8BC6 / \u5DF2\u5347\u7EA7","synthesis.section.acceptedItems":"\u91C7\u7EB3\u9879","synthesis.section.rejectedItems":"\u62D2\u7EDD / \u64A4\u56DE\u9879","synthesis.section.openItems":"\u672A\u51B3\u9879","synthesis.section.sources":"\u4F9D\u636E","synthesis.narration.consensusIn":"\u5728\u5168\u90E8 {max} \u8F6E\u4E2D\u7684\u7B2C {round} \u8F6E\u8FBE\u6210\u5171\u8BC6\u3002","synthesis.narration.escalated":"\u7ECF\u8FC7 {round} \u8F6E\u4ECD\u672A\u8FBE\u6210\u5171\u8BC6,\u7531\u7528\u6237\u51B3\u5B9A\u5347\u7EA7\u5904\u7406\u3002","synthesis.narration.leaderNote":"\u8D1F\u8D23\u4EBA\u5907\u6CE8","approval.pending":"\u7B49\u5F85\u8D1F\u8D23\u4EBA\u6279\u51C6\u3002\u8BF7\u8C03\u7528 `agent_debate_approve`\u3001`agent_debate_continue` \u6216 `agent_debate_reject`\u3002","approval.timeout":"\u7B49\u5F85\u8D1F\u8D23\u4EBA\u51B3\u7B56\u671F\u95F4\u4F1A\u8BDD\u5DF2\u8D85\u65F6({hours} \u5C0F\u65F6)\u3002","moderator.narration.roundHeader":"\u7B2C {round}/{max} \u8F6E","moderator.narration.consensusInRound":"\u5728\u7B2C {round} \u8F6E\u8FBE\u6210\u5171\u8BC6\u3002","moderator.narration.dissentDetailHeader":"\u672A\u89E3\u51B3\u9879","moderator.narration.noInterest":"\u53C2\u4E0E\u8005\u65E0\u5174\u8DA3","moderator.narration.participantDropout":"\u53C2\u4E0E\u8005 `{participantId}` \u56E0\u591A\u6B21\u5931\u8D25\u88AB\u6807\u8BB0\u4E3A\u4E0D\u53EF\u7528\u3002","moderator.narration.participantTimeout":"\u53C2\u4E0E\u8005 `{participantId}` \u5728\u672C\u8F6E\u672A\u4F5C\u51FA\u54CD\u5E94\u3002","moderator.narration.leaderTimeoutFooter":"\u8D1F\u8D23\u4EBA\u54CD\u5E94\u8D85\u65F6","moderator.narration.rejected":"\u8D1F\u8D23\u4EBA\u5DF2\u62D2\u7EDD\u8BE5\u4F1A\u8BDD\u3002","moderator.narration.approved":"\u8D1F\u8D23\u4EBA\u5DF2\u6279\u51C6\u8BE5\u4F1A\u8BDD\u3002","moderator.narration.aliasClarification":"\u522B\u540D\u6F84\u6E05\u9636\u6BB5","prompt.system.moderator":"\u4F60\u662F\u7ED3\u6784\u5316\u591A AI \u8FA9\u8BBA\u7684\u4E3B\u6301\u4EBA\u3002\u4F60\u4E0D\u64B0\u5199\u63D0\u6848,\u800C\u662F\u6C47\u603B\u7ED3\u6784\u5316\u6295\u7968\u5E76\u4EA7\u51FA\u4E2D\u7ACB\u7684\u5171\u8BC6\u65B9\u6848\u3002\u4EC5\u5728\u534F\u8BAE\u5B9A\u4E49\u7684\u901A\u9053\u8303\u56F4\u5185\u4F5C\u51FA\u54CD\u5E94\u3002","error.participantTimeout":"\u53C2\u4E0E\u8005 `{participantId}` \u5728 {seconds} \u79D2\u5185\u672A\u54CD\u5E94\u3002","error.parseFailure":"\u65E0\u6CD5\u89E3\u6790\u53C2\u4E0E\u8005 `{participantId}` \u7684 `<{tag}>` \u5757\u3002","error.sessionNotFound":"\u672A\u627E\u5230\u8FA9\u8BBA\u4F1A\u8BDD `{sessionId}`\u3002","error.invalidState":"\u5728\u72B6\u6001 `{state}` \u4E0B\u4E0D\u5141\u8BB8\u6267\u884C\u64CD\u4F5C `{operation}`\u3002","error.unknownLocaleFallback":"\u672A\u77E5\u533A\u57DF `{locale}`,\u56DE\u9000\u5230 `{fallback}`\u3002","askUser.escalation.header":"\u5DF2\u8FBE\u6700\u5927\u8F6E\u6B21\u4F46\u4ECD\u672A\u8FBE\u6210\u5171\u8BC6","askUser.escalation.question":"\u60A8\u5E0C\u671B\u5982\u4F55\u7EE7\u7EED?","askUser.escalation.continue":"\u518D\u8FDB\u884C {rounds} \u8F6E","askUser.escalation.escalate":"\u4E0D\u8FBE\u6210\u5171\u8BC6\u5373\u5347\u7EA7","askUser.escalation.stop":"\u7ED3\u675F\u8FA9\u8BBA"};var Im=Object.freeze({en:Pm,ko:Tm,ja:Em,zh:Rm});function L0(t){return typeof t=="string"&&Gs.includes(t)}function uu(t,e){return e===void 0?t:t.replace(/\{(\w+)\}/g,(r,n)=>{if(Object.prototype.hasOwnProperty.call(e,n)){let o=e[n];return typeof o=="number"?String(o):o}return r})}function du(t){return t===void 0?lu(Er):L0(t)?lu(t):(console.warn(`[i18n] unknown locale '${t}', falling back to ${Er}`),lu(Er))}function F0(t,e,r){let n=new Set;return{locale:t,t(o,s){let i=e[o];if(i!==void 0)return uu(i,s);let a=r[o];return a!==void 0?(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in locale '${t}', falling back to ${Zc}`)),uu(a,s)):(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in all bundles; returning raw key`)),uu(o,s))}}}function lu(t){return F0(t,Im[t],Im[Zc])}async function Am(t){let e=await fetch(`${t}/api/tags`);if(!e.ok)throw new Error(`Ollama API error: ${e.status}`);return((await e.json()).models||[]).map(n=>({name:n.name||"unknown",size:n.size||0,strengths:Z0(n.name||"")}))}function Z0(t){let e=["chat"],r=t.toLowerCase();return(r.includes("coder")||r.includes("code"))&&e.push("code_review","code_generation"),r.includes("instruct")&&e.push("instruction_following"),r.includes("embed")&&e.push("embedding"),e}var Gr=class t{id;type="ollama";host;defaultModel;maxContext;available=!1;unavailableUntil=0;models=[];timeouts;static RATE_LIMIT_BACKOFF_MS=6e4;constructor(e){this.id=e.id,this.host=e.host,this.defaultModel=e.defaultModel||"auto",this.maxContext=e.maxContext??32768,this.timeouts={default:e.timeouts?.default??3e4,generate:e.timeouts?.generate??3e5,chat:e.timeouts?.chat??3e5}}async initialize(){try{this.models=await Am(this.host),this.available=this.models.length>0,this.available&&(this.unavailableUntil=0)}catch{this.available=!1}}async healthCheck(){try{let e=await fetch(`${this.host}/api/tags`);if(!e.ok)return{status:"error",message:`HTTP ${e.status}`};let r=await e.json(),n=r.models?.length??0;return{status:n>0?"ok":"degraded",message:`${n} models available`,details:{models:r.models?.map(o=>o.name)}}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:this.maxContext,supportsSystemPrompt:!0,supportsFiles:!1,supportsStreaming:!0,supportsJsonOutput:!1,supportsToolUse:!0,strengths:[...new Set(this.models.flatMap(e=>e.strengths))],models:this.models.map(e=>({name:e.name,description:`Ollama model (${Math.round(e.size/1e9)}GB)`,strengths:e.strengths,sizeGb:e.size/1e9}))}}isAvailable(){return this.unavailableUntil>0&&Date.now()<this.unavailableUntil?!1:(this.unavailableUntil>0&&Date.now()>=this.unavailableUntil&&(this.unavailableUntil=0),this.available)}async chat(e){if(!this.available)throw new de(this.id,"Ollama not running or no models installed");let r=e.model||this.selectModel(),n={model:r,prompt:e.prompt,system:e.system||"You are a helpful assistant.",stream:!1,...e.extra||{}},o=new AbortController,s=setTimeout(()=>o.abort(),this.timeouts.generate),i=()=>o.abort(e.signal.reason);e.signal&&(e.signal.aborted?o.abort(e.signal.reason):e.signal.addEventListener("abort",i));try{let a=await fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal});if(a.status===429)throw this.unavailableUntil=Date.now()+t.RATE_LIMIT_BACKOFF_MS,new de(this.id,`Rate limited (429) \u2014 temporarily deactivated for ${t.RATE_LIMIT_BACKOFF_MS/1e3}s`);if(!a.ok)throw new We(this.id,`HTTP ${a.status}: ${a.statusText}`);let c=await a.json();return{text:c.response||"",model:c.model||r,provider:this.id}}catch(a){throw a.name==="AbortError"?new hn(this.id,this.timeouts.generate):a instanceof We||a instanceof de?a:new We(this.id,a.message)}finally{clearTimeout(s),e.signal&&e.signal.removeEventListener("abort",i)}}selectModel(){if(this.defaultModel!=="auto")return this.defaultModel;if(this.models.length===0)throw new de(this.id,`No models detected. Install a model first (ollama pull ${ff})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var q0=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function Cm(t){return t.split(`
|
|
44
|
+
`).filter(n=>{let o=n.trim();return o?!q0.some(s=>s.test(o)):!1}).join(`
|
|
45
|
+
`).trim()}function Dm(t){try{let e=JSON.parse(t.trim());if(e&&typeof e.response=="string")return e.response}catch{let e=t.split(`
|
|
46
|
+
`);for(let r=e.length-1;r>=0;r--){let n=e[r].trim();if(n.startsWith("{"))try{let o=JSON.parse(n);if(o&&typeof o.response=="string")return o.response}catch{}}}return null}var pu="gemini",fu="@google/gemini-cli",Jr=class{id;type="gemini-cli";timeout;available=!1;cliPath=null;limiter=new Rn(Sf);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await An(pu,fu);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){if(!this.available)return{status:"error",message:"Gemini CLI not installed"};try{let{command:e,cliArgs:r}=pr(this.cliPath,pu,fu,["--version"]),n=await Me({command:e,args:r,timeout:1e4});return n.exitCode===0?{status:"ok",message:"Gemini CLI available"}:{status:"error",message:`Exit code: ${n.exitCode}`}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:1e6,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!1,strengths:["long_context","file_analysis","translation","summarization"],models:[{name:"gemini-2.5-pro",description:"Google Gemini 2.5 Pro via CLI",strengths:["long_context","reasoning"]}]}}isAvailable(){return this.available}async chat(e){return this.limiter.run(()=>this.chatInternal(e))}async chatInternal(e){if(!this.available)throw new de(this.id,"Gemini CLI not installed");let r=Kr(e),n=vi(e,r),s=["-p",n?"Use the full instructions and file contents provided on stdin.":r,"-o","json"],{command:i,cliArgs:a}=pr(this.cliPath,pu,fu,s),c=km(this.id);try{let u=await Me({command:i,args:a,stdin:n?r:void 0,timeout:this.timeout,onStderrChunk:p=>c.feed(p),signal:e.signal});if(u.exitCode!==0)try{Cn(u.exitCode,u.stderr,this.id)}catch(p){throw p.markUnavailable&&(this.available=!1),p}let l=Dm(u.stdout);if(l!==null){let p=V0(u.stdout);return{text:l,model:p,provider:this.id}}return{text:Cm(u.stdout),model:"gemini",provider:this.id}}catch(u){if(u instanceof de)throw u.markUnavailable&&(this.available=!1),u;Dn(u,this.id,this.timeout)}}};function V0(t){try{let e=JSON.parse(t.trim());if(e?.stats?.models){for(let[n,o]of Object.entries(e.stats.models))if(o?.roles?.main)return n;let r=Object.keys(e.stats.models);if(r.length>0)return r[0]}}catch{}return"gemini"}import{randomUUID as B0}from"crypto";function mu(t){let e=t.trim().split(`
|
|
43
47
|
`),r=[];for(let n of e)try{let o=JSON.parse(n);o.type==="item.completed"&&o.item?.type==="agent_message"&&o.item.text&&r.push(o.item.text)}catch{n.trim()&&r.push(n.trim())}return r.join(`
|
|
44
|
-
`)||t.trim()}var
|
|
45
|
-
`);for(let n=r.length-1;n>=0;n--){let o=r[n].trim();if(!o.startsWith("{"))continue;let s=
|
|
46
|
-
`).trim();try{
|
|
48
|
+
`)||t.trim()}var xi="codex",Si="@openai/codex";function W0(t){return["-C",t]}function H0(t,e,r){return["exec","--skip-git-repo-check","-C",r,"--full-auto","--ephemeral","--json","--",e?"-":t]}var Yr=class{id;type="codex-cli";timeout;available=!1;cliPath=null;appServer=null;defaultCwd;constructor(e){this.id=e.id,this.timeout=e.timeout??6e5,this.defaultCwd=e.workspaceBaseDir??process.cwd()}async initialize(){let e=await An(xi,Si);this.available=e.available,this.cliPath=e.cliPath,this.available&&this.cliPath&&(this.appServer=new yi({command:this.cliPath==="npx"?"npx":xi,commandPrefix:this.cliPath==="npx"?[Si]:void 0,commandArgs:W0(this.defaultCwd)}))}async healthCheck(){if(!this.available)return{status:"error",message:"Codex CLI not installed"};try{let{command:e,cliArgs:r}=pr(this.cliPath,xi,Si,["--version"]),n=await Me({command:e,args:r,timeout:1e4});return n.exitCode===0?{status:"ok",message:"Codex CLI available"}:{status:"error",message:`Exit code: ${n.exitCode}`}}catch(e){return{status:"error",message:e.message}}}getCapabilities(){return{maxContext:128e3,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!0,strengths:["code_generation","code_review","autonomous_execution"],models:[{name:"codex",description:"OpenAI Codex CLI",strengths:["code_generation"]}]}}isAvailable(){return this.available}async chat(e){if(!this.available)throw new de(this.id,"Codex CLI not installed");let r=e.workspaceBaseDir,n=typeof r=="string"&&r.length>0&&r!==this.defaultCwd;if(this.appServer&&!this.appServer.shouldFallback()&&!n)try{return await this.chatViaAppServer(e)}catch(o){if(!this.shouldFallbackFrom(o))throw o}return this.chatViaCli(e)}shouldFallbackFrom(e){return!(e instanceof at||e instanceof de||e instanceof We)}async shutdown(){this.appServer&&await this.appServer.shutdown()}async chatViaAppServer(e){let r={method:"exec",params:{prompt:cu(Kr(e)),fullAuto:!0,ephemeral:!0},id:B0()},n=await this.appServer.request(r,this.timeout,e.signal);if(n.error)throw new We(this.id,n.error.message);return{text:mu(JSON.stringify(n.result)),model:"codex",provider:this.id}}async chatViaCli(e){let r=cu(Kr(e)),n=process.platform==="win32"||vi(e,r),o=e.workspaceBaseDir??this.defaultCwd,s=H0(r,n,o),{command:i,cliArgs:a}=pr(this.cliPath,xi,Si,s);try{let c=await Me({command:i,args:a,stdin:n?r:void 0,timeout:this.timeout,signal:e.signal});if(c.exitCode!==0)try{Cn(c.exitCode,c.stderr,this.id)}catch(l){throw l.markUnavailable&&(this.available=!1),l}return{text:mu(c.stdout),model:"codex",provider:this.id}}catch(c){Dn(c,this.id,this.timeout)}}};function zm(t){try{return JSON.parse(t.trim())}catch{return null}}function Om(t){let e=zm(t);if(e)return e;let r=t.split(`
|
|
49
|
+
`);for(let n=r.length-1;n>=0;n--){let o=r[n].trim();if(!o.startsWith("{"))continue;let s=zm(o);if(s)return s}return null}function Mm(t){let e=Om(t);return e?typeof e.result=="string"?e.result:typeof e.response=="string"?e.response:null:null}function Nm(t){let e=Om(t);return typeof e?.model=="string"?e.model:"claude"}var K0=1,hu="claude",gu="@anthropic-ai/claude-code",Xr=class{id;type="claude-cli";timeout;available=!1;cliPath=null;limiter=new Rn(K0);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4}async initialize(){let e=await An(hu,gu);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){return $m(this.cliPath,hu,gu,"Claude")}getCapabilities(){return{maxContext:2e5,supportsSystemPrompt:!0,supportsFiles:!0,supportsStreaming:!1,supportsJsonOutput:!0,supportsToolUse:!1,strengths:["reasoning","review","synthesis","moderation"],models:[{name:"claude",description:"Anthropic Claude Code CLI",strengths:["reasoning","review","synthesis"]}]}}isAvailable(){return this.available}async chat(e){return this.limiter.run(()=>this.chatInternal(e))}async chatInternal(e){if(!this.available||!this.cliPath)throw new de(this.id,"Claude CLI not installed");let r=Kr(e),n=["-p","--output-format","json"];e.model&&n.push("--model",e.model),n.push(r);let{command:o,cliArgs:s}=pr(this.cliPath,hu,gu,n);try{let i=await Me({command:o,args:s,timeout:this.timeout,signal:e.signal});if(i.exitCode!==0){let c=[i.stderr,i.stdout].filter(Boolean).join(`
|
|
50
|
+
`).trim();try{Cn(i.exitCode,c,this.id)}catch(u){throw(u.markUnavailable||/auth|credential|login|api key|oauth|token|401/i.test(c))&&(this.available=!1),u}}return{text:Mm(i.stdout)??i.stdout.trim(),model:Nm(i.stdout),provider:this.id}}catch(i){Dn(i,this.id,this.timeout)}}};import{randomUUID as G0}from"crypto";var J0=7200*1e3,zo=class{debates=new Map;create(e){this.purgeStaleDebates();let r=G0(),n=new Date().toISOString(),o={id:r,topic:e.topic,goal:e.goal,providerIds:e.providerIds,turns:[],status:"active",documentId:e.documentId,createdAt:n};return this.debates.set(r,o),o}addTurn(e,r,n){let o=this.getState(e);if(!o)throw new Error(`Debate not found: ${e}`);if(o.status==="concluded")throw new Error(`Debate already concluded: ${e}`);let s={turnNumber:o.turns.length+1,speaker:r,content:n,timestamp:new Date().toISOString()};return o.turns.push(s),o}buildPromptForProvider(e,r){let n=this.getState(e);if(!n)throw new Error(`Debate not found: ${e}`);let o=`Topic: ${n.topic}
|
|
47
51
|
`;if(n.goal&&(o+=`Goal: ${n.goal}
|
|
48
52
|
`),n.turns.length>0){o+=`
|
|
49
53
|
=== Conversation History ===
|
|
50
54
|
|
|
51
|
-
`;let i=n.turns.length;if(i>
|
|
55
|
+
`;let i=n.turns.length;if(i>Ks){let u=i-Ks,l=[...new Set(n.turns.slice(0,u).map(d=>d.speaker))];o+=`[${u} earlier turn(s) omitted \u2014 participants: ${l.join(", ")}]
|
|
52
56
|
|
|
53
|
-
`}let a=n.turns.slice(-
|
|
57
|
+
`}let a=n.turns.slice(-Ks),c="";for(let u of a){let l=`[Turn ${u.turnNumber}] ${u.speaker}:
|
|
54
58
|
${u.content}
|
|
55
59
|
|
|
56
|
-
`;if(c.length+l.length>
|
|
60
|
+
`;if(c.length+l.length>Nc){c+=`[... history truncated at ${Nc} characters]
|
|
57
61
|
|
|
58
62
|
`;break}c+=l}o+=c,o+=`===
|
|
59
63
|
|
|
@@ -89,31 +93,31 @@ Evaluation goal: ${n.goal}
|
|
|
89
93
|
|
|
90
94
|
${o.content}
|
|
91
95
|
|
|
92
|
-
`;return n}purgeStaleDebates(){let e=Date.now();for(let[r,n]of this.debates){if(n.status!=="active")continue;let o=new Date(n.createdAt).getTime();e-o>
|
|
96
|
+
`;return n}purgeStaleDebates(){let e=Date.now();for(let[r,n]of this.debates){if(n.status!=="active")continue;let o=new Date(n.createdAt).getTime();e-o>J0&&this.debates.delete(r)}}};import{mkdirSync as Y0,readFileSync as jm,readdirSync as yu,existsSync as $i,renameSync as X0,rmdirSync as Q0}from"fs";import{join as eP}from"path";import{randomUUID as tP}from"crypto";function vu(t){if(t.providers<=0)throw new Error(`deriveTerminalStatus: providers must be positive, got ${t.providers}`);if(t.failed<0||t.failed>t.providers)throw new Error(`deriveTerminalStatus: failed (${t.failed}) out of range [0, ${t.providers}]`);return t.failed===0?"completed":t.failed===t.providers?"failed":"completed_with_errors"}var Lm=new Set(["completed","completed_with_errors","failed"]);function Fm(t,e){return Lm.has(t)?!1:!!(t==="pending"&&e==="in_progress"||t==="in_progress"&&Lm.has(e)||t==="in_progress"&&e==="in_progress")}function Zm(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.status=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}var Oo=class{sessionDir;sessions;fullyLoaded=!1;constructor(e){this.sessionDir=e,Y0(this.sessionDir,{recursive:!0}),this.migrateLegacyNestedSessions(),this.sessions=new Map}migrateLegacyNestedSessions(){let e=eP(this.sessionDir,"sessions");if(!$i(e))return;let r;try{r=yu(e)}catch(o){console.warn(`[SessionManager] failed to read legacy nested dir ${e}: ${String(o)}`);return}let n=r.filter(o=>o.endsWith(".json"));for(let o of n){let s,i;try{s=Le(o,e),i=Le(o,this.sessionDir)}catch(a){console.warn(`[SessionManager] skipped legacy file ${JSON.stringify(o)}: ${String(a)}`);continue}if($i(i)){console.warn(`[SessionManager] migration skipped ${o}: destination already exists at ${i}`);continue}try{X0(s,i)}catch(a){console.warn(`[SessionManager] migration failed for ${o}: ${String(a)}`)}}try{yu(e).length===0&&Q0(e)}catch(o){console.warn(`[SessionManager] could not remove legacy nested dir ${e}: ${String(o)}`)}}createSession(e,r){let n=new Date().toISOString(),o={id:tP(),type:e,status:"pending",config:r,createdAt:n,updatedAt:n};return this.sessions.set(o.id,o),this.persist(o),o}getSession(e){let r=this.sessions.get(e);if(r)return r;if(!this.fullyLoaded){let n;try{n=Le(`${e}.json`,this.sessionDir)}catch{return}if($i(n))try{let o=jm(n,"utf-8"),s=JSON.parse(o);return Zm(s)?(this.sessions.set(s.id,s),s):void 0}catch{}}}listSessions(){return this.ensureFullyLoaded(),[...this.sessions.values()]}updateSessionStatus(e,r){let n=this.getSession(e);if(!n)throw new Error(`Session not found: ${e}`);if(!Fm(n.status,r))throw new Error(`Illegal session transition: ${n.id} ${n.status} -> ${r}`);n.status=r,n.updatedAt=new Date().toISOString(),this.persist(n)}transitionSession(e,r,n){let o=this.getSession(e);if(!o)throw new Error(`Session not found: ${e}`);if(!Fm(o.status,r))throw new Error(`Illegal session transition: ${o.id} ${o.status} -> ${r}`);o.status=r,n!==void 0&&(o.result=n),o.updatedAt=new Date().toISOString(),this.persist(o)}completeSession(e,r){this.transitionSession(e,"completed",r)}persist(e){let r=Le(`${e.id}.json`,this.sessionDir);je(r,e)}ensureFullyLoaded(){if(this.fullyLoaded)return;if(!$i(this.sessionDir)){this.fullyLoaded=!0;return}let e=yu(this.sessionDir).filter(r=>r.endsWith(".json"));for(let r of e){let n=r.replace(/\.json$/,"");if(!this.sessions.has(n))try{let o=Le(r,this.sessionDir),s=jm(o,"utf-8"),i=JSON.parse(s);if(!Zm(i))continue;this.sessions.set(i.id,i)}catch{}}this.fullyLoaded=!0}};function zn(t){if(!t||!t.trim())return null;try{return JSON.parse(t.trim())}catch{}let e=[],r=0,n=-1;for(let o=0;o<t.length;o++){let s=t[o];s==="{"?(r===0&&(n=o),r++):s==="}"&&(r--,r===0&&n>=0&&(e.push(t.slice(n,o+1)),n=-1),r<0&&(r=0))}if(e.length===0)return null;for(let o=e.length-1;o>=0;o--)try{return JSON.parse(e[o])}catch{continue}return null}function Um(t,e,r){try{let n=zn(t);if(n&&typeof n=="object")return e(n)}catch{}return r(t)}var Mo=class{registry;chatAdapter;constructor(e,r){this.registry=e,this.chatAdapter=r}async chatWith(e,r){return this.chatAdapter?this.chatAdapter.chat(e,r):e.chat(r)}canValidate(e){if(this.chatAdapter){let r=this.registry.getCapability(e);return r.tier==="agent"||r.tier==="tool"}return this.isAgentTier(e)}async validate(e){let{items:r,criteria:n}=e,o=this.resolveValidators(e),s=[];for(let l of r)for(let d of o)d.id!==l.providerId&&s.push(this.reviewItem(l,d,n));let i=await Promise.all(s),a=this.detectConflicts(i),c=i.length>0&&i.every(l=>l.passed),u=i.length===0?this.chatAdapter?"No validators available for cross-validation.":"No agent-tier validators available for cross-validation.":void 0;return{reviews:i,overallPass:c,conflicts:a,message:u}}resolveValidators(e){if(e.validators)return e.validators.filter(o=>this.canValidate(o.id));let r=new Set,n=[];for(let o of e.items)r.has(o.providerId)||(r.add(o.providerId),this.canValidate(o.providerId)&&n.push(this.registry.get(o.providerId)));return n}isAgentTier(e){return this.registry.getCapability(e).tier==="agent"}async reviewItem(e,r,n){let o=n?`
|
|
93
97
|
Additional criteria: ${n}`:"",s=[`You are a cross-validator reviewing work from provider "${e.providerId}".`,`Task: ${e.task}`,`Content to review:
|
|
94
98
|
${e.content}`,o,"",'Respond with JSON only: { "passed": boolean, "feedback": "string", "suggestedFixes": "string or omit" }'].join(`
|
|
95
|
-
`),i=await this.chatWith(r,{prompt:s});return this.parseReview(e.providerId,r.id,i.text)}parseReview(e,r,n){return
|
|
99
|
+
`),i=await this.chatWith(r,{prompt:s});return this.parseReview(e.providerId,r.id,i.text)}parseReview(e,r,n){return Um(n,o=>({targetProvider:e,reviewerProvider:r,passed:!!o.passed,feedback:String(o.feedback??""),suggestedFixes:o.suggestedFixes?String(o.suggestedFixes):void 0}),o=>({targetProvider:e,reviewerProvider:r,passed:!1,feedback:o}))}detectConflicts(e){let r=[],n=new Map;for(let o of e){let s=o.targetProvider;n.has(s)||n.set(s,[]),n.get(s).push(o)}for(let[o,s]of n){if(s.length<2)continue;let i=s.filter(c=>c.passed),a=s.filter(c=>!c.passed);if(i.length>0&&a.length>0){let c=i.map(l=>l.reviewerProvider).join(", "),u=a.map(l=>l.reviewerProvider).join(", ");r.push(`Conflict on "${o}": passed by [${c}], failed by [${u}]`)}}return r}};import{readFileSync as Bm,readdirSync as Wm,statSync as Pi}from"fs";import{join as Hm,relative as oP}from"path";var qm=50*1024,ki=500,Vm=100;function sP(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}function iP(t,e){let r=[],n=o=>{let s=Pi(o);if(s.isFile()){r.push(o);return}if(s.isDirectory())for(let i of Wm(o)){let a=Hm(o,i),c=Pi(a);c.isFile()?r.push(a):e&&c.isDirectory()&&n(a)}};return n(t),r}function aP(t,e){if(process.platform!=="win32")return{command:t,args:e};let r=n=>`'${n.replace(/'/g,"''")}'`;switch(t){case"ls":{let n=e.length>0?r(e[0]):".",o=e.slice(1).map(r);return{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`Get-ChildItem -Name -LiteralPath ${n}${o.length?" "+o.join(" "):""}`]}}case"cat":return e.length===0?{command:t,args:e}:{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`Get-Content -LiteralPath ${e.map(r).join(",")}`]};default:return{command:t,args:e}}}var Km={name:"file_read",description:"Read the contents of a file. Returns the text content.",parameters:{path:{type:"string",description:"File path relative to workspace",required:!0},offset:{type:"number",description:"Line offset to start reading from (0-based)"},limit:{type:"number",description:"Maximum number of lines to read"}},async execute(t,e){let r=Yt(String(t.path??""),e),n=Bm(r,"utf-8");if(t.offset!==void 0||t.limit!==void 0){let o=n.split(`
|
|
96
100
|
`),s=Number(t.offset??0),i=Number(t.limit??o.length);n=o.slice(s,s+i).join(`
|
|
97
|
-
`)}return Buffer.byteLength(n,"utf-8")>
|
|
98
|
-
... [truncated]`)),n}},
|
|
99
|
-
... [truncated at ${
|
|
100
|
-
`)+i}},
|
|
101
|
+
`)}return Buffer.byteLength(n,"utf-8")>qm&&(n=In(n,qm,`
|
|
102
|
+
... [truncated]`)),n}},cP={name:"file_write",description:"Write content to a file. Creates parent directories if needed. Overwrites existing files.",parameters:{path:{type:"string",description:"File path relative to workspace",required:!0},content:{type:"string",description:"Content to write",required:!0}},async execute(t,e){let r=dt(String(t.path??""),e),n=String(t.content??"");return oe(r,n),`File written: ${t.path} (${Buffer.byteLength(n,"utf-8")} bytes)`}},Gm={name:"file_list",description:"List files and directories at the given path.",parameters:{path:{type:"string",description:"Directory path relative to workspace (default: '.')"},recursive:{type:"boolean",description:"List recursively (default: false)"}},async execute(t,e){let r=Yt(String(t.path??"."),e),n=!!t.recursive,o=[];function s(a,c){if(o.length>=ki)return;let u=Wm(a);for(let l of u){if(o.length>=ki)break;let d=Hm(a,l),p=c?`${c}/${l}`:l;try{let f=Pi(d);o.push(f.isDirectory()?`${p}/`:p),n&&f.isDirectory()&&s(d,p)}catch{}}}s(r,"");let i=o.length>=ki?`
|
|
103
|
+
... [truncated at ${ki} entries]`:"";return o.join(`
|
|
104
|
+
`)+i}},Jm={name:"grep_search",description:"Search file contents with a regex pattern. Returns matching lines with file paths and line numbers.",parameters:{pattern:{type:"string",description:"Regular expression pattern to search for",required:!0},path:{type:"string",description:"Directory or file path to search in (default: '.')"},glob:{type:"string",description:"Glob pattern to filter files (e.g., '*.ts')"}},async execute(t,e){let r=String(t.pattern??""),n=Yt(String(t.path??"."),e),o=t.glob?sP(String(t.glob)):null,s=Pi(n).isDirectory(),i=iP(n,s);try{let a=new RegExp(r),c=[];for(let u of i){let l=oP(e,u).replace(/\\/g,"/");if(o&&!o.test(l.split("/").pop()??l))continue;let d;try{d=Bm(u,"utf-8")}catch{continue}let p=d.split(/\r?\n/);for(let f=0;f<p.length;f++)if(a.test(p[f])&&(c.push(`${l}:${f+1}:${p[f]}`),c.length>=Vm))return c.join(`
|
|
101
105
|
`)+`
|
|
102
|
-
... [truncated at ${
|
|
103
|
-
`)||"No matches found."}catch{return"No matches found."}}},
|
|
106
|
+
... [truncated at ${Vm} matches]`}return c.join(`
|
|
107
|
+
`)||"No matches found."}catch{return"No matches found."}}},uP={name:"shell_exec",description:`Execute a shell command. Only safe, read-oriented commands are allowed (${[...pi].join(", ")}). Shell operators (pipes, chaining, subshells) are blocked.`,parameters:{command:{type:"string",description:"Shell command to execute",required:!0}},async execute(t,e){let r=String(t.command??"").trim();if(!r)return"Error: empty command";let n=cm(r);if(!n.valid)return`Error: ${n.error}`;let o=r.split(/\s+/).filter(Boolean),s=o[0],i=o.slice(1),a=aP(s,i);try{let c=await Me({command:a.command,args:a.args,timeout:3e4,cwd:e,maxBuffer:102400}),u=c.stdout;return c.stderr&&(u+=(u?`
|
|
104
108
|
`:"")+`[stderr] ${c.stderr}`),c.exitCode!==0&&(u+=`
|
|
105
109
|
[exit code: ${c.exitCode}]`),c.truncated&&(u+=`
|
|
106
|
-
... [output truncated]`),u||"(no output)"}catch(c){return`Error: ${
|
|
110
|
+
... [output truncated]`),u||"(no output)"}catch(c){return`Error: ${M(c)}`}}};function _u(){return[Km,cP,Gm,Jm,uP]}function Ti(){return[Km,Gm,Jm]}function bu(t){return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:{type:"object",properties:e.parameters,required:Object.entries(e.parameters).filter(([,r])=>r.required===!0).map(([r])=>r)}}}))}var lP=15,dP=30,pP=3e5,fP=2e3,mP=`You are a coding assistant with access to tools for reading, writing, and searching files in a workspace. Use the provided tools when you need to inspect or modify code. When your task is complete, respond with your final answer without making any tool calls.
|
|
107
111
|
|
|
108
112
|
Guidelines:
|
|
109
113
|
- Read files before modifying them to understand the existing code.
|
|
110
114
|
- Use grep_search to find relevant code across the workspace.
|
|
111
115
|
- Write complete file contents when using file_write (not just diffs).
|
|
112
|
-
- Provide a clear summary of what you did when finished.`,
|
|
116
|
+
- Provide a clear summary of what you did when finished.`,Ei=class{host;model;baseDir;maxIterations;timeoutMs;systemPrompt;tools;toolDefs;toolMap;constructor(e){this.host=e.providerHost.replace(/\/$/,""),this.model=e.model,this.baseDir=e.baseDir,this.maxIterations=Math.min(e.maxIterations??lP,dP),this.timeoutMs=e.timeoutMs??pP,this.systemPrompt=e.systemPrompt??mP,this.tools=e.tools??_u(),this.toolDefs=bu(this.tools),this.toolMap=new Map(this.tools.map(r=>[r.name,r]))}async run(e){let r=Date.now(),n=[],o="",s=[{role:"system",content:this.systemPrompt},{role:"user",content:e}];for(let i=0;i<this.maxIterations;i++){if(Date.now()-r>this.timeoutMs)return{success:!1,output:o||"Agent loop timed out before completion.",iterations:i,toolCalls:n,error:`Timed out after ${this.timeoutMs}ms`};let a;try{a=await this.callOllama(s)}catch(u){let l=M(u);return{success:!1,output:o||"",iterations:i,toolCalls:n,error:`Ollama API error: ${l}`}}let c=a.message;if(c.content&&(o=c.content),!c.tool_calls||c.tool_calls.length===0)return{success:!0,output:o,iterations:i+1,toolCalls:n};s.push(c);for(let u of c.tool_calls){let l=u.function.name,d=u.function.arguments,p;if(typeof d=="string"){let y=zn(d);p=y&&typeof y=="object"&&!Array.isArray(y)?y:{}}else p=d??{};let f=this.toolMap.get(l),m=Date.now(),g;if(!f)g=`Error: unknown tool '${l}'. Available tools: ${[...this.toolMap.keys()].join(", ")}`;else try{g=await f.execute(p,this.baseDir)}catch(y){g=`Error: ${M(y)}`}n.push({iteration:i,toolName:l,arguments:p,result:In(g,fP,"... [truncated in log]"),durationMs:Date.now()-m}),s.push({role:"tool",content:g})}}return{success:!1,output:o||"Agent loop reached max iterations without completing.",iterations:this.maxIterations,toolCalls:n,error:`Max iterations (${this.maxIterations}) reached`}}async callOllama(e){let r=`${this.host}/api/chat`,n={model:this.model,messages:e,tools:this.toolDefs,stream:!1},o=new AbortController,s=setTimeout(()=>o.abort(),this.timeoutMs);try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal});if(!i.ok){let a=await i.text().catch(()=>"");throw new Error(`HTTP ${i.status}: ${a.slice(0,200)}`)}return await i.json()}finally{clearTimeout(s)}}};function Ym(t){if(t.type!=="ollama")return null;let e=t;return typeof e.getConnectionInfo=="function"?e.getConnectionInfo():null}var On=class{tools;baseDir;constructor(e){this.tools=e.tools,this.baseDir=e.baseDir}async chat(e,r){if(Js(e.id,e.getCapabilities(),void 0,e.type).tier!=="tool")return e.chat(r);let o=Ym(e);return o?{text:(await new Ei({providerHost:o.host,model:o.model,baseDir:this.baseDir,tools:this.tools}).run(r.prompt)).output,model:o.model,provider:e.id}:e.chat(r)}};import{existsSync as No,readFileSync as yP,readdirSync as vP}from"fs";import{join as Mn}from"path";var jo=class{baseDir;constructor(e){this.baseDir=e}async run(e={}){let r=e.timeoutMs??12e4,n=e.buildProfile??"auto",o=this.resolveProfile(n),s=e.designDoc??this.detectDesignDoc(),i=o?await this.runProfile(o,r):{exitCode:0,output:"(no build profile resolved)"},a=i.exitCode===0,c=i.output,u=[];o?u.push(`${o.name}: ${a?"PASS":"FAIL"}`):u.push("No profile resolved"),s&&u.push(`Design doc: ${s}`);let d=`**AutoQA: ${a?"PASS":"FAIL"}**
|
|
113
117
|
${u.join(`
|
|
114
|
-
`)}`;return{buildPassed:a,buildOutput:c,testsPassed:a,testOutput:c,designDoc:s??void 0,summary:d}}resolveProfile(e){if(e==="auto"){let n=this.detectBuildProfile();return n?{name:n.name,command:n.command,args:n.args}:null}let r=
|
|
115
|
-
${n.stderr}`.trim(),s
|
|
116
|
-
... [truncated]`);return{exitCode:n.exitCode,output:s}}catch(n){return{exitCode:1,output:n.message??"AutoQA run failed"}}}};var
|
|
118
|
+
`)}`;return{buildPassed:a,buildOutput:c,testsPassed:a,testOutput:c,designDoc:s??void 0,summary:d}}resolveProfile(e){if(e==="auto"){let n=this.detectBuildProfile();return n?{name:n.name,command:n.command,args:n.args}:null}let r=yn[e];return r?{name:r.name,command:r.command,args:r.args}:null}detectBuildProfile(){if(No(Mn(this.baseDir,"tsconfig.json")))return yn.tsc;if(No(Mn(this.baseDir,"vitest.config.ts"))||No(Mn(this.baseDir,"vitest.config.js")))return yn.vitest;let e=this.getPackageScripts();return e?.build?yn["npm-build"]:e?.test&&e.test!=='echo "Error: no test specified" && exit 1'?yn["npm-test"]:null}detectDesignDoc(){let e=Mn(this.baseDir,"docs","plans");if(!No(e))return null;try{let r=vP(e).filter(n=>n.endsWith(".md")).sort().reverse();if(r.length>0)return Mn("docs","plans",r[0])}catch{}return null}getPackageScripts(){let e=Mn(this.baseDir,"package.json");if(!No(e))return null;try{return JSON.parse(yP(e,"utf-8")).scripts??null}catch{return null}}async runProfile(e,r){try{ui(e.command,e.args)}catch(n){return{exitCode:1,output:n instanceof ot?n.message:`Profile ${e.name} rejected: ${n.message}`}}try{let n=await Me({command:e.command,args:[...e.args],cwd:this.baseDir,timeout:r,maxBuffer:10485760}),o=n.exitCode===0?n.stdout:`${n.stdout}
|
|
119
|
+
${n.stderr}`.trim(),s=In(o,1e4,`
|
|
120
|
+
... [truncated]`);return{exitCode:n.exitCode,output:s}}catch(n){return{exitCode:1,output:n.message??"AutoQA run failed"}}}};var _P=new Set(["","hello","hi","thanks","thank you","sure","okay","i agree","great question"]),bP=/[\w./\\]+\.[a-z]{1,4}/gi,wP=/\b\d+\.?\d*\b/g,xP=/`[^`\n]+`/g,SP=/https?:\/\/\S+/g,$P=/\b[a-z][a-zA-Z]*[A-Z][a-zA-Z]*\b|\b[a-z]+(?:_[a-z]+)+\b/g;function Ri(t){return Math.max(0,Math.min(1,t))}function Xt(t,e){return t.match(e)?.length??0}function kP(t){let r=t.split(/[.!?]+|\n+(?=\S)/g).map(n=>n.trim()).filter(n=>n.length>0);return r.length>0?r:t.trim().length>0?[t.trim()]:[]}function PP(t){let e=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim();return _P.has(e)?!0:e.replace(/\s+/g,"").length<5}function TP(t){let e=kP(t);if(e.length===0)return .1;let r=e.filter(PP).length,n=(e.length-r)/e.length;return Math.max(.1,Ri(n))}function EP(t){let e=Xt(t,/^\s*#\s+/gm),r=Xt(t,/^\s*(?:[-*]|\d+\.)\s+/gm),n=Math.ceil(Xt(t,/^\s*```/gm)/2),o=Xt(t,/^\s*.*\|.*\s*$/gm),s=e+r+n+o;return Ri(s/3)}function RP(t){let e=Xt(t,bP)+Xt(t,wP)+Xt(t,xP)+Xt(t,SP)+Xt(t,$P);return Ri(e/3)}function Xm(t){let e=t.toLowerCase().match(/\b[\w-]+\b/g)??[];return new Set(e.filter(r=>r.length>=4))}function IP(t,e){if(e.length===0)return .5;let r=new Set;for(let i of e)for(let a of Xm(i.content))r.add(a);if(r.size===0)return 0;let n=Xm(t),o=0;for(let i of r)n.has(i)&&(o+=1);let s=Math.max(1,r.size*.3);return Ri(o/s)}function Lo(t,e,r){let n={substanceRatio:TP(t),structureScore:EP(t),specificityScore:RP(t),engagementScore:IP(t,e)};return{score:(n.substanceRatio+n.structureScore+n.specificityScore+n.engagementScore)/4,breakdown:n}}import{mkdirSync as Ii,readFileSync as Qm,readdirSync as wu,existsSync as Fo,statSync as CP,unlinkSync as DP}from"fs";import{basename as eh,join as Zo,relative as th,sep as rh}from"path";import{randomUUID as zP}from"crypto";var OP="reviews";function Nn(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"untitled"}function MP(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"anonymous"}function jn(){let t=new Date,e=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return`${e}${r}${n}`}function nh(t){return rh==="/"?t:t.split(rh).join("/")}var Uo=class{reviewDir;individualDir;debateDir;synthesisDir;constructor(e){this.reviewDir=Zo(e,OP),this.individualDir=Zo(e,vf),this.debateDir=Zo(e,Hs),this.synthesisDir=Zo(e,_f),Ii(this.reviewDir,{recursive:!0}),Ii(this.individualDir,{recursive:!0}),Ii(this.debateDir,{recursive:!0}),Ii(this.synthesisDir,{recursive:!0})}get allDirs(){return[this.individualDir,this.debateDir,this.synthesisDir,this.reviewDir]}nextSequenceGlobal(e){let r=0,n=new RegExp(`_${e}_(\\d{3})\\.md$`);for(let o of this.allDirs){if(!Fo(o))continue;let s;try{s=wu(o)}catch{continue}for(let i of s){let a=i.match(n);if(a){let c=parseInt(a[1],10);c>r&&(r=c)}}}return String(r+1).padStart(3,"0")}resolveDocPath(e){let r;for(let n of this.allDirs)try{let o=Le(`${e}.md`,n);if(Fo(o))return o}catch(o){r===void 0&&(r=o)}throw r!==void 0?r:new Error(`Document not found: ${e}`)}async createReview(e){let r=jn(),n=e.topic?Nn(e.topic):zP().slice(0,8),o=this.nextSequenceGlobal(r),s=e.provider?`${e.provider}_${n}_${r}_${o}`:`${n}_${r}_${o}`,i=Le(`${s}.md`,this.reviewDir),a=`# Review: ${e.topic??s}
|
|
117
121
|
|
|
118
122
|
`;a+=`**Date:** ${new Date().toISOString().slice(0,10)}
|
|
119
123
|
`,e.provider&&(a+=`**Provider:** ${e.provider}
|
|
@@ -128,7 +132,7 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
|
|
|
128
132
|
`}return a+=`
|
|
129
133
|
---
|
|
130
134
|
|
|
131
|
-
`,
|
|
135
|
+
`,oe(i,a),{id:s,content:a,path:i}}async createDebateDocument(e){let r=jn(),n=Nn(e.topic),o=this.nextSequenceGlobal(r),s=`${n}_${r}_${o}`,i=Le(`${s}.md`,this.debateDir),a=`# Debate: ${e.topic}
|
|
132
136
|
|
|
133
137
|
`;return a+=`**Date:** ${new Date().toISOString().slice(0,10)}
|
|
134
138
|
`,a+=`**Participants:** ${e.providers.join(", ")}
|
|
@@ -136,7 +140,7 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
|
|
|
136
140
|
`),a+=`
|
|
137
141
|
---
|
|
138
142
|
|
|
139
|
-
`,
|
|
143
|
+
`,oe(i,a),{id:s,content:a,path:i}}async createIndividualReview(e){let r=jn(),n=MP(e.participantId),o=Nn(e.topic),s=this.nextSequenceGlobal(r),i=`${n}_${o}_${r}_${s}`,a=Le(`${i}.md`,this.individualDir),c=`# ${e.topic} \u2014 ${e.participantId}
|
|
140
144
|
|
|
141
145
|
`;if(c+=`**Date:** ${new Date().toISOString().slice(0,10)}
|
|
142
146
|
`,c+=`**Participant:** ${e.participantId}
|
|
@@ -151,7 +155,7 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
|
|
|
151
155
|
`,c+=e.content,c+=`
|
|
152
156
|
|
|
153
157
|
---
|
|
154
|
-
`,
|
|
158
|
+
`,oe(a,c),{id:i,content:c,path:a}}async createIssueDocument(e){let r=jn(),n=e.sessionId.slice(0,8),o=this.nextSequenceGlobal(r),s=`${bf}_${n}_${r}_${o}`,i=Le(`${s}.md`,this.individualDir),a=`# Rejection Issue Report \u2014 ${e.topic}
|
|
155
159
|
|
|
156
160
|
`;if(a+=`**Session:** ${e.sessionId}
|
|
157
161
|
`,a+=`**Rejected at:** ${new Date().toISOString()}
|
|
@@ -170,7 +174,7 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
|
|
|
170
174
|
`}a+=`
|
|
171
175
|
`}return a+=`
|
|
172
176
|
---
|
|
173
|
-
`,
|
|
177
|
+
`,oe(i,a),{id:s,content:a,path:i}}async createSynthesis(e){let r=jn(),n=Nn(e.topic),o=this.nextSequenceGlobal(r),s=`${n}_${r}_${o}`,i=Le(`${s}.md`,this.synthesisDir),a=nh(th(this.synthesisDir,e.debatePath)),c=e.individualPaths.map(l=>nh(th(this.synthesisDir,l))),u=`# Synthesis: ${e.topic}
|
|
174
178
|
|
|
175
179
|
`;if(u+=`**Date:** ${new Date().toISOString().slice(0,10)}
|
|
176
180
|
`,u+=`**Status:** ${e.status}
|
|
@@ -181,16 +185,16 @@ ${n.stderr}`.trim(),s=$n(o,1e4,`
|
|
|
181
185
|
`;if(u+=`
|
|
182
186
|
## Sources
|
|
183
187
|
|
|
184
|
-
`,u+=`- Debate transcript: [${
|
|
188
|
+
`,u+=`- Debate transcript: [${eh(e.debatePath)}](${a})
|
|
185
189
|
`,e.individualPaths.length>0){u+=`- Individual reviews:
|
|
186
|
-
`;for(let l=0;l<e.individualPaths.length;l++){let d=e.individualPaths[l];u+=` - [${
|
|
190
|
+
`;for(let l=0;l<e.individualPaths.length;l++){let d=e.individualPaths[l];u+=` - [${eh(d)}](${c[l]})
|
|
187
191
|
`}}return u+=`
|
|
188
192
|
---
|
|
189
193
|
|
|
190
194
|
`,u+=e.body,u+=`
|
|
191
195
|
|
|
192
196
|
---
|
|
193
|
-
`,
|
|
197
|
+
`,oe(i,u),{id:s,content:u,path:i}}async appendToSynthesis(e,r){let n=Le(`${e}.md`,this.synthesisDir);if(!Fo(n))throw new Error(`Synthesis document not found: ${e}`);ai(n,`
|
|
194
198
|
${r}
|
|
195
199
|
`)}async addComment(e,r){let n=this.resolveDocPath(e),o=`
|
|
196
200
|
## Comment by ${r.author}
|
|
@@ -198,66 +202,78 @@ ${r}
|
|
|
198
202
|
${r.content}
|
|
199
203
|
|
|
200
204
|
---
|
|
201
|
-
`;
|
|
205
|
+
`;ai(n,o)}async read(e){let r=this.resolveDocPath(e),n=Qm(r,"utf-8");return{id:e,content:n,path:r}}resolveKindDir(e){switch(e){case"individual":return this.individualDir;case"debate":return this.debateDir;case"synthesis":return this.synthesisDir;case"general":return this.reviewDir}}async createDocument(e){let r=e.kind??"general",n=this.resolveKindDir(r),o=jn(),s=e.topic?Nn(e.topic):Nn(e.title),i=this.nextSequenceGlobal(o),a=`${s}_${o}_${i}`,c=Le(`${a}.md`,n),u=`# ${e.title}
|
|
202
206
|
|
|
203
207
|
`;if(e.metadata){for(let[l,d]of Object.entries(e.metadata))u+=`**${l}:** ${d}
|
|
204
208
|
`;u+=`
|
|
205
209
|
`}return u+=e.content,u+=`
|
|
206
210
|
|
|
207
211
|
---
|
|
208
|
-
`,se(c,u),{id:a,content:u,path:c}}async list(){let e=[];for(let r of this.allDirs){if(!zo(r))continue;let n=cu(r).filter(o=>o.endsWith(".md"));for(let o of n){let s=o.replace(".md",""),i=Me(o,r),a=jm(i,"utf-8");e.push({id:s,content:a,path:i})}}return e}cleanup(e={}){let r=e.maxAgeDays??30,n=e.maxFiles??100,o=Date.now(),s=r*24*60*60*1e3,i=0;for(let a of this.allDirs){if(!zo(a))continue;let c=cu(a).filter(u=>u.endsWith(".md")).map(u=>{let l=Do(a,u),d=cP(l);return{path:l,mtime:d.mtimeMs}}).sort((u,l)=>l.mtime-u.mtime);for(let u=0;u<c.length;u++){let l=o-c[u].mtime;if(u>=n||l>s)try{uP(c[u].path),i++}catch{}}}return{removed:i}}};var bZ=Object.freeze({status:"aborted"});function w(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Ht=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ei={};function at(t){return t&&Object.assign(Ei,t),Ei}var ie={};Ze(ie,{BIGINT_FORMAT_RANGES:()=>Vm,Class:()=>lu,NUMBER_FORMAT_RANGES:()=>vu,aborted:()=>Kr,allowsEval:()=>hu,assert:()=>yP,assertEqual:()=>fP,assertIs:()=>hP,assertNever:()=>gP,assertNotEqual:()=>mP,assignProp:()=>mu,cached:()=>No,captureStackTrace:()=>Ii,cleanEnum:()=>IP,cleanRegex:()=>Lo,clone:()=>It,createTransparentProxy:()=>SP,defineLazy:()=>de,esc:()=>Hr,escapeRegex:()=>ur,extend:()=>PP,finalizeIssue:()=>gt,floatSafeRemainder:()=>fu,getElementAtPath:()=>vP,getEnumValues:()=>du,getLengthableOrigin:()=>Fo,getParsedType:()=>xP,getSizableOrigin:()=>Bm,isObject:()=>zn,isPlainObject:()=>On,issue:()=>_u,joinValues:()=>Ri,jsonStringifyReplacer:()=>pu,merge:()=>TP,normalizeParams:()=>M,nullish:()=>jo,numKeys:()=>wP,omit:()=>kP,optionalKeys:()=>yu,partial:()=>EP,pick:()=>$P,prefixIssues:()=>At,primitiveTypes:()=>qm,promiseAllObject:()=>_P,propertyKeyTypes:()=>gu,randomString:()=>bP,required:()=>RP,stringifyPrimitive:()=>Ai,unwrapMessage:()=>Mo});function fP(t){return t}function mP(t){return t}function hP(t){}function gP(t){throw new Error}function yP(t){}function du(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ri(t,e="|"){return t.map(r=>Ai(r)).join(e)}function pu(t,e){return typeof e=="bigint"?e.toString():e}function No(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function jo(t){return t==null}function Lo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function fu(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function de(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function mu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function vP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function _P(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function bP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Hr(t){return JSON.stringify(t)}var Ii=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function zn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var hu=No(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function On(t){if(zn(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(zn(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function wP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var xP=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},gu=new Set(["string","number","symbol"]),qm=new Set(["string","number","bigint","boolean","symbol","undefined"]);function ur(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function It(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function M(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function SP(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Ai(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function yu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var vu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Vm={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function $P(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return It(t,{...t._zod.def,shape:r,checks:[]})}function kP(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return It(t,{...t._zod.def,shape:r,checks:[]})}function PP(t,e){if(!On(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return mu(this,"shape",n),n},checks:[]};return It(t,r)}function TP(t,e){return It(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return mu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function EP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return It(e,{...e._zod.def,shape:o,checks:[]})}function RP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return It(e,{...e._zod.def,shape:o,checks:[]})}function Kr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function At(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Mo(t){return typeof t=="string"?t:t?.message}function gt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Mo(t.inst?._zod.def?.error?.(t))??Mo(e?.error?.(t))??Mo(r.customError?.(t))??Mo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Bm(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Fo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _u(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function IP(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var lu=class{constructor(...e){}};var Wm=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,pu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ci=w("$ZodError",Wm),bu=w("$ZodError",Wm,{Parent:Error});function Hm(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Km(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var Gm=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Ht;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gt(c,s,at())));throw Ii(a,o?.callee),a}return i.value};var Jm=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>gt(c,s,at())));throw Ii(a,o?.callee),a}return i.value};var wu=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ht;return s.issues.length?{success:!1,error:new(t??Ci)(s.issues.map(i=>gt(i,o,at())))}:{success:!0,data:s.value}},Zo=wu(bu),xu=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>gt(i,o,at())))}:{success:!0,data:s.value}},Di=xu(bu);var Ym=/^[cC][^\s-]{8,}$/,Qm=/^[0-9a-z]+$/,Xm=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,eh=/^[0-9a-vA-V]{20}$/,th=/^[A-Za-z0-9]{27}$/,rh=/^[a-zA-Z0-9_-]{21}$/,nh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var oh=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Su=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var sh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var CP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function ih(){return new RegExp(CP,"u")}var ah=/^(?:(?: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])$/,ch=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,uh=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,lh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,dh=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,$u=/^[A-Za-z0-9_-]*$/,ph=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var fh=/^\+(?:[0-9]){6,14}[0-9]$/,mh="(?:(?:\\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])))",hh=new RegExp(`^${mh}$`);function gh(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function yh(t){return new RegExp(`^${gh(t)}$`)}function vh(t){let e=gh({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${mh}T(?:${n})$`)}var _h=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var bh=/^\d+$/,wh=/^-?\d+(?:\.\d+)?/i,xh=/true|false/i,Sh=/null/i;var $h=/^[^A-Z]*$/,kh=/^[^a-z]*$/;var Ne=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Ph={number:"number",bigint:"bigint",object:"date"},Pu=w("$ZodCheckLessThan",(t,e)=>{Ne.init(t,e);let r=Ph[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Tu=w("$ZodCheckGreaterThan",(t,e)=>{Ne.init(t,e);let r=Ph[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Th=w("$ZodCheckMultipleOf",(t,e)=>{Ne.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):fu(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Eh=w("$ZodCheckNumberFormat",(t,e)=>{Ne.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=vu[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=bh)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}});var Rh=w("$ZodCheckMaxLength",(t,e)=>{var r;Ne.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!jo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Fo(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ih=w("$ZodCheckMinLength",(t,e)=>{var r;Ne.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!jo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Fo(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Ah=w("$ZodCheckLengthEquals",(t,e)=>{var r;Ne.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!jo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Fo(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Uo=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Ne.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Ch=w("$ZodCheckRegex",(t,e)=>{Uo.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Dh=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=$h),Uo.init(t,e)}),zh=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=kh),Uo.init(t,e)}),Oh=w("$ZodCheckIncludes",(t,e)=>{Ne.init(t,e);let r=ur(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Mh=w("$ZodCheckStartsWith",(t,e)=>{Ne.init(t,e);let r=new RegExp(`^${ur(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Nh=w("$ZodCheckEndsWith",(t,e)=>{Ne.init(t,e);let r=new RegExp(`.*${ur(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var jh=w("$ZodCheckOverwrite",(t,e)=>{Ne.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var zi=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
212
|
+
`,oe(c,u),{id:a,content:u,path:c}}async list(){let e=[];for(let r of this.allDirs){if(!Fo(r))continue;let n=wu(r).filter(o=>o.endsWith(".md"));for(let o of n){let s=o.replace(".md",""),i=Le(o,r),a=Qm(i,"utf-8");e.push({id:s,content:a,path:i})}}return e}cleanup(e={}){let r=e.maxAgeDays??30,n=e.maxFilesPerDir??e.maxFiles??100,o=Date.now(),s=r*24*60*60*1e3,i=0;for(let a of this.allDirs){if(!Fo(a))continue;let c=wu(a).filter(u=>u.endsWith(".md")).map(u=>{let l=Zo(a,u),d=CP(l);return{path:l,mtime:d.mtimeMs}}).sort((u,l)=>l.mtime-u.mtime);for(let u=0;u<c.length;u++){let l=o-c[u].mtime;if(u>=n||l>s)try{DP(c[u].path),i++}catch{}}}return{removed:i}}};var rU=Object.freeze({status:"aborted"});function x(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Qt=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ai={};function pt(t){return t&&Object.assign(Ai,t),Ai}var ae={};Be(ae,{BIGINT_FORMAT_RANGES:()=>sh,Class:()=>Su,NUMBER_FORMAT_RANGES:()=>Au,aborted:()=>en,allowsEval:()=>Eu,assert:()=>ZP,assertEqual:()=>NP,assertIs:()=>LP,assertNever:()=>FP,assertNotEqual:()=>jP,assignProp:()=>Tu,cached:()=>Vo,captureStackTrace:()=>Di,cleanEnum:()=>eT,cleanRegex:()=>Wo,clone:()=>Mt,createTransparentProxy:()=>HP,defineLazy:()=>pe,esc:()=>Qr,escapeRegex:()=>mr,extend:()=>JP,finalizeIssue:()=>wt,floatSafeRemainder:()=>Pu,getElementAtPath:()=>UP,getEnumValues:()=>$u,getLengthableOrigin:()=>Ho,getParsedType:()=>WP,getSizableOrigin:()=>ih,isObject:()=>Ln,isPlainObject:()=>Fn,issue:()=>Cu,joinValues:()=>Ci,jsonStringifyReplacer:()=>ku,merge:()=>YP,normalizeParams:()=>j,nullish:()=>Bo,numKeys:()=>BP,omit:()=>GP,optionalKeys:()=>Iu,partial:()=>XP,pick:()=>KP,prefixIssues:()=>Nt,primitiveTypes:()=>oh,promiseAllObject:()=>qP,propertyKeyTypes:()=>Ru,randomString:()=>VP,required:()=>QP,stringifyPrimitive:()=>zi,unwrapMessage:()=>qo});function NP(t){return t}function jP(t){return t}function LP(t){}function FP(t){throw new Error}function ZP(t){}function $u(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ci(t,e="|"){return t.map(r=>zi(r)).join(e)}function ku(t,e){return typeof e=="bigint"?e.toString():e}function Vo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Bo(t){return t==null}function Wo(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Pu(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function pe(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Tu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function UP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function qP(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function VP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Qr(t){return JSON.stringify(t)}var Di=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ln(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Eu=Vo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Fn(t){if(Ln(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Ln(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function BP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var WP=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Ru=new Set(["string","number","symbol"]),oh=new Set(["string","number","bigint","boolean","symbol","undefined"]);function mr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Mt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function j(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function HP(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function zi(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Iu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Au={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},sh={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function KP(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Mt(t,{...t._zod.def,shape:r,checks:[]})}function GP(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Mt(t,{...t._zod.def,shape:r,checks:[]})}function JP(t,e){if(!Fn(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Tu(this,"shape",n),n},checks:[]};return Mt(t,r)}function YP(t,e){return Mt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Tu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function XP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Mt(e,{...e._zod.def,shape:o,checks:[]})}function QP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Mt(e,{...e._zod.def,shape:o,checks:[]})}function en(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Nt(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function qo(t){return typeof t=="string"?t:t?.message}function wt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=qo(t.inst?._zod.def?.error?.(t))??qo(e?.error?.(t))??qo(r.customError?.(t))??qo(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function ih(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ho(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Cu(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function eT(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Su=class{constructor(...e){}};var ah=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,ku,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Oi=x("$ZodError",ah),Du=x("$ZodError",ah,{Parent:Error});function ch(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function uh(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var lh=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Qt;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>wt(c,s,pt())));throw Di(a,o?.callee),a}return i.value};var dh=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>wt(c,s,pt())));throw Di(a,o?.callee),a}return i.value};var zu=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Qt;return s.issues.length?{success:!1,error:new(t??Oi)(s.issues.map(i=>wt(i,o,pt())))}:{success:!0,data:s.value}},Ko=zu(Du),Ou=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>wt(i,o,pt())))}:{success:!0,data:s.value}},Mi=Ou(Du);var ph=/^[cC][^\s-]{8,}$/,fh=/^[0-9a-z]+$/,mh=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,hh=/^[0-9a-vA-V]{20}$/,gh=/^[A-Za-z0-9]{27}$/,yh=/^[a-zA-Z0-9_-]{21}$/,vh=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var _h=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Mu=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var bh=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var rT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function wh(){return new RegExp(rT,"u")}var xh=/^(?:(?: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])$/,Sh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,$h=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,kh=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ph=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Nu=/^[A-Za-z0-9_-]*$/,Th=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Eh=/^\+(?:[0-9]){6,14}[0-9]$/,Rh="(?:(?:\\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])))",Ih=new RegExp(`^${Rh}$`);function Ah(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Ch(t){return new RegExp(`^${Ah(t)}$`)}function Dh(t){let e=Ah({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Rh}T(?:${n})$`)}var zh=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Oh=/^\d+$/,Mh=/^-?\d+(?:\.\d+)?/i,Nh=/true|false/i,jh=/null/i;var Lh=/^[^A-Z]*$/,Fh=/^[^a-z]*$/;var Ze=x("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Zh={number:"number",bigint:"bigint",object:"date"},Lu=x("$ZodCheckLessThan",(t,e)=>{Ze.init(t,e);let r=Zh[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Fu=x("$ZodCheckGreaterThan",(t,e)=>{Ze.init(t,e);let r=Zh[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Uh=x("$ZodCheckMultipleOf",(t,e)=>{Ze.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Pu(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),qh=x("$ZodCheckNumberFormat",(t,e)=>{Ze.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Au[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Oh)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}});var Vh=x("$ZodCheckMaxLength",(t,e)=>{var r;Ze.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Bo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Ho(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Bh=x("$ZodCheckMinLength",(t,e)=>{var r;Ze.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Bo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Ho(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Wh=x("$ZodCheckLengthEquals",(t,e)=>{var r;Ze.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Bo(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Ho(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Go=x("$ZodCheckStringFormat",(t,e)=>{var r,n;Ze.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Hh=x("$ZodCheckRegex",(t,e)=>{Go.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Kh=x("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Lh),Go.init(t,e)}),Gh=x("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Fh),Go.init(t,e)}),Jh=x("$ZodCheckIncludes",(t,e)=>{Ze.init(t,e);let r=mr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Yh=x("$ZodCheckStartsWith",(t,e)=>{Ze.init(t,e);let r=new RegExp(`^${mr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Xh=x("$ZodCheckEndsWith",(t,e)=>{Ze.init(t,e);let r=new RegExp(`.*${mr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var Qh=x("$ZodCheckOverwrite",(t,e)=>{Ze.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Ni=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
|
|
209
213
|
`).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
|
|
210
|
-
`))}};var
|
|
211
|
-
if (${
|
|
212
|
-
if (input[${
|
|
213
|
-
if (${
|
|
214
|
-
newResult[${
|
|
214
|
+
`))}};var tg={major:4,minor:0,patch:0};var fe=x("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=tg;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=en(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Qt;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=en(s,d)))});else{if(s.issues.length===d)continue;c||(c=en(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Qt;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Ko(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Mi(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Li=x("$ZodString",(t,e)=>{fe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??zh(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),he=x("$ZodStringFormat",(t,e)=>{Go.init(t,e),Li.init(t,e)}),dg=x("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=_h),he.init(t,e)}),pg=x("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Mu(n))}else e.pattern??(e.pattern=Mu());he.init(t,e)}),fg=x("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=bh),he.init(t,e)}),mg=x("$ZodURL",(t,e)=>{he.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Th.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),hg=x("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=wh()),he.init(t,e)}),gg=x("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=yh),he.init(t,e)}),yg=x("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=ph),he.init(t,e)}),vg=x("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=fh),he.init(t,e)}),_g=x("$ZodULID",(t,e)=>{e.pattern??(e.pattern=mh),he.init(t,e)}),bg=x("$ZodXID",(t,e)=>{e.pattern??(e.pattern=hh),he.init(t,e)}),wg=x("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=gh),he.init(t,e)}),xg=x("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Dh(e)),he.init(t,e)}),Sg=x("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ih),he.init(t,e)}),$g=x("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ch(e)),he.init(t,e)}),kg=x("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=vh),he.init(t,e)}),Pg=x("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=xh),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Tg=x("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Sh),he.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Eg=x("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=$h),he.init(t,e)}),Rg=x("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=kh),he.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function Ig(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Ag=x("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ph),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Ig(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function nT(t){if(!Nu.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Ig(r)}var Cg=x("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Nu),he.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{nT(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Dg=x("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Eh),he.init(t,e)});function oT(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var zg=x("$ZodJWT",(t,e)=>{he.init(t,e),t._zod.check=r=>{oT(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Uu=x("$ZodNumber",(t,e)=>{fe.init(t,e),t._zod.pattern=t._zod.bag.pattern??Mh,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Og=x("$ZodNumber",(t,e)=>{qh.init(t,e),Uu.init(t,e)}),Mg=x("$ZodBoolean",(t,e)=>{fe.init(t,e),t._zod.pattern=Nh,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}});var Ng=x("$ZodNull",(t,e)=>{fe.init(t,e),t._zod.pattern=jh,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}});var jg=x("$ZodUnknown",(t,e)=>{fe.init(t,e),t._zod.parse=r=>r}),Lg=x("$ZodNever",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function rg(t,e,r){t.issues.length&&e.issues.push(...Nt(r,t.issues)),e.value[r]=t.value}var Fg=x("$ZodArray",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>rg(u,r,i))):rg(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function ji(t,e,r){t.issues.length&&e.issues.push(...Nt(r,t.issues)),e.value[r]=t.value}function ng(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...Nt(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var Zg=x("$ZodObject",(t,e)=>{fe.init(t,e);let r=Vo(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof fe))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=Iu(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});pe(t._zod,"propValues",()=>{let d=e.shape,p={};for(let f in d){let m=d[f]._zod;if(m.values){p[f]??(p[f]=new Set);for(let g of m.values)p[f].add(g)}}return p});let n=d=>{let p=new Ni(["shape","payload","ctx"]),f=r.value,m=S=>{let w=Qr(S);return`shape[${w}]._zod.run({ value: input[${w}], issues: [] }, ctx)`};p.write("const input = payload.value;");let g=Object.create(null),y=0;for(let S of f.keys)g[S]=`key_${y++}`;p.write("const newResult = {}");for(let S of f.keys)if(f.optionalKeys.has(S)){let w=g[S];p.write(`const ${w} = ${m(S)};`);let _=Qr(S);p.write(`
|
|
215
|
+
if (${w}.issues.length) {
|
|
216
|
+
if (input[${_}] === undefined) {
|
|
217
|
+
if (${_} in input) {
|
|
218
|
+
newResult[${_}] = undefined;
|
|
215
219
|
}
|
|
216
220
|
} else {
|
|
217
221
|
payload.issues = payload.issues.concat(
|
|
218
|
-
${
|
|
222
|
+
${w}.issues.map((iss) => ({
|
|
219
223
|
...iss,
|
|
220
|
-
path: iss.path ? [${
|
|
224
|
+
path: iss.path ? [${_}, ...iss.path] : [${_}],
|
|
221
225
|
}))
|
|
222
226
|
);
|
|
223
227
|
}
|
|
224
|
-
} else if (${
|
|
225
|
-
if (${
|
|
228
|
+
} else if (${w}.value === undefined) {
|
|
229
|
+
if (${_} in input) newResult[${_}] = undefined;
|
|
226
230
|
} else {
|
|
227
|
-
newResult[${
|
|
231
|
+
newResult[${_}] = ${w}.value;
|
|
228
232
|
}
|
|
229
|
-
`)}else{let
|
|
230
|
-
if (${
|
|
233
|
+
`)}else{let w=g[S];p.write(`const ${w} = ${m(S)};`),p.write(`
|
|
234
|
+
if (${w}.issues.length) payload.issues = payload.issues.concat(${w}.issues.map(iss => ({
|
|
231
235
|
...iss,
|
|
232
|
-
path: iss.path ? [${
|
|
233
|
-
})));`),p.write(`newResult[${Hr(x)}] = ${v}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let _=p.compile();return(x,v)=>_(d,x,v)},o,s=zn,i=!Ei.jitless,c=i&&hu.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let f=d.value;if(!s(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(e.shape)),d=o(d,p);else{d.value={};let v=l.shape;for(let P of l.keys){let S=v[P],N=S._zod.run({value:f[P],issues:[]},p),L=S._zod.optin==="optional"&&S._zod.optout==="optional";N instanceof Promise?m.push(N.then(Z=>L?Uh(Z,d,P,f):Oi(Z,d,P))):L?Uh(N,d,P,f):Oi(N,d,P)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let g=[],y=l.keySet,_=u._zod,x=_.def.type;for(let v of Object.keys(f)){if(y.has(v))continue;if(x==="never"){g.push(v);continue}let P=_.run({value:f[v],issues:[]},p);P instanceof Promise?m.push(P.then(S=>Oi(S,d,v))):Oi(P,d,v)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function qh(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>gt(s,n,at())))}),e}var Iu=w("$ZodUnion",(t,e)=>{pe.init(t,e),de(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),de(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),de(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),de(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Lo(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>qh(i,r,t,n)):qh(s,r,t,n)}}),Tg=w("$ZodDiscriminatedUnion",(t,e)=>{Iu.init(t,e);let r=t._zod.parse;de(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=No(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!zn(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Eg=w("$ZodIntersection",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Vh(r,c,u)):Vh(r,s,i)}});function Eu(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(On(t)&&On(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Eu(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Eu(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Vh(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Kr(t))return t;let n=Eu(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var Rg=w("$ZodRecord",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!On(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...At(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...At(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>gt(u,n,at())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...At(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...At(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Ig=w("$ZodEnum",(t,e)=>{pe.init(t,e);let r=du(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>gu.has(typeof n)).map(n=>typeof n=="string"?ur(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Ag=w("$ZodLiteral",(t,e)=>{pe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?ur(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}});var Cg=w("$ZodTransform",(t,e)=>{pe.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Ht;return r.value=o,r}}),Dg=w("$ZodOptional",(t,e)=>{pe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Lo(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),zg=w("$ZodNullable",(t,e)=>{pe.init(t,e),de(t._zod,"optin",()=>e.innerType._zod.optin),de(t._zod,"optout",()=>e.innerType._zod.optout),de(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Lo(r.source)}|null)$`):void 0}),de(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Og=w("$ZodDefault",(t,e)=>{pe.init(t,e),t._zod.optin="optional",de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Bh(s,e)):Bh(o,e)}});function Bh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Mg=w("$ZodPrefault",(t,e)=>{pe.init(t,e),t._zod.optin="optional",de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Ng=w("$ZodNonOptional",(t,e)=>{pe.init(t,e),de(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Wh(s,t)):Wh(o,t)}});function Wh(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var jg=w("$ZodCatch",(t,e)=>{pe.init(t,e),t._zod.optin="optional",de(t._zod,"optout",()=>e.innerType._zod.optout),de(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>gt(i,n,at()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>gt(s,n,at()))},input:r.value}),r.issues=[]),r)}});var Lg=w("$ZodPipe",(t,e)=>{pe.init(t,e),de(t._zod,"values",()=>e.in._zod.values),de(t._zod,"optin",()=>e.in._zod.optin),de(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>Hh(s,e,n)):Hh(o,e,n)}});function Hh(t,e,r){return Kr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Fg=w("$ZodReadonly",(t,e)=>{pe.init(t,e),de(t._zod,"propValues",()=>e.innerType._zod.propValues),de(t._zod,"values",()=>e.innerType._zod.values),de(t._zod,"optin",()=>e.innerType._zod.optin),de(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(Kh):Kh(o)}});function Kh(t){return t.value=Object.freeze(t.value),t}var Zg=w("$ZodCustom",(t,e)=>{Ne.init(t,e),pe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>Gh(s,r,n,t));Gh(o,r,n,t)}});function Gh(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(_u(o))}}var OP=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},MP=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${OP(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ai(n.values[0])}`:`Invalid option: expected one of ${Ri(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ri(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function Ug(){return{localeError:MP()}}var Au=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function NP(){return new Au}var qo=NP();function qg(t,e){return new t({type:"string",...M(e)})}function Vg(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...M(e)})}function Cu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...M(e)})}function Bg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...M(e)})}function Wg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...M(e)})}function Hg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...M(e)})}function Kg(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...M(e)})}function Gg(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...M(e)})}function Jg(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...M(e)})}function Yg(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...M(e)})}function Qg(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...M(e)})}function Xg(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...M(e)})}function ey(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...M(e)})}function ty(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...M(e)})}function ry(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...M(e)})}function ny(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...M(e)})}function oy(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...M(e)})}function sy(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...M(e)})}function iy(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...M(e)})}function ay(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...M(e)})}function cy(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...M(e)})}function uy(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...M(e)})}function ly(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...M(e)})}function dy(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...M(e)})}function py(t,e){return new t({type:"string",format:"date",check:"string_format",...M(e)})}function fy(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...M(e)})}function my(t,e){return new t({type:"string",format:"duration",check:"string_format",...M(e)})}function hy(t,e){return new t({type:"number",checks:[],...M(e)})}function gy(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...M(e)})}function yy(t,e){return new t({type:"boolean",...M(e)})}function vy(t,e){return new t({type:"null",...M(e)})}function _y(t){return new t({type:"unknown"})}function by(t,e){return new t({type:"never",...M(e)})}function Ni(t,e){return new Pu({check:"less_than",...M(e),value:t,inclusive:!1})}function Vo(t,e){return new Pu({check:"less_than",...M(e),value:t,inclusive:!0})}function ji(t,e){return new Tu({check:"greater_than",...M(e),value:t,inclusive:!1})}function Bo(t,e){return new Tu({check:"greater_than",...M(e),value:t,inclusive:!0})}function Li(t,e){return new Th({check:"multiple_of",...M(e),value:t})}function Fi(t,e){return new Rh({check:"max_length",...M(e),maximum:t})}function Mn(t,e){return new Ih({check:"min_length",...M(e),minimum:t})}function Zi(t,e){return new Ah({check:"length_equals",...M(e),length:t})}function Du(t,e){return new Ch({check:"string_format",format:"regex",...M(e),pattern:t})}function zu(t){return new Dh({check:"string_format",format:"lowercase",...M(t)})}function Ou(t){return new zh({check:"string_format",format:"uppercase",...M(t)})}function Mu(t,e){return new Oh({check:"string_format",format:"includes",...M(e),includes:t})}function Nu(t,e){return new Mh({check:"string_format",format:"starts_with",...M(e),prefix:t})}function ju(t,e){return new Nh({check:"string_format",format:"ends_with",...M(e),suffix:t})}function Gr(t){return new jh({check:"overwrite",tx:t})}function Lu(t){return Gr(e=>e.normalize(t))}function Fu(){return Gr(t=>t.trim())}function Zu(){return Gr(t=>t.toLowerCase())}function Uu(){return Gr(t=>t.toUpperCase())}function wy(t,e,r){return new t({type:"array",element:e,...M(r)})}function xy(t,e,r){let n=M(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Sy(t,e,r){return new t({type:"custom",check:"custom",fn:e,...M(r)})}function Nn(t){return!!t._zod}function lr(t,e){return Nn(t)?Zo(t,e):t.safeParse(e)}function Ui(t){if(!t)return;let e;if(Nn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function $y(t){if(Nn(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Ho={};Ze(Ho,{ZodISODate:()=>Py,ZodISODateTime:()=>ky,ZodISODuration:()=>Ey,ZodISOTime:()=>Ty,date:()=>Vu,datetime:()=>qu,duration:()=>Wu,time:()=>Bu});var ky=w("ZodISODateTime",(t,e)=>{ag.init(t,e),ve.init(t,e)});function qu(t){return dy(ky,t)}var Py=w("ZodISODate",(t,e)=>{cg.init(t,e),ve.init(t,e)});function Vu(t){return py(Py,t)}var Ty=w("ZodISOTime",(t,e)=>{ug.init(t,e),ve.init(t,e)});function Bu(t){return fy(Ty,t)}var Ey=w("ZodISODuration",(t,e)=>{lg.init(t,e),ve.init(t,e)});function Wu(t){return my(Ey,t)}var Ry=(t,e)=>{Ci.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Km(t,r)},flatten:{value:r=>Hm(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},fU=w("ZodError",Ry),Ko=w("ZodError",Ry,{Parent:Error});var Iy=Gm(Ko),Ay=Jm(Ko),Cy=wu(Ko),Dy=xu(Ko);var Se=w("ZodType",(t,e)=>(pe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>It(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Iy(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Cy(t,r,n),t.parseAsync=async(r,n)=>Ay(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Dy(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(zT(r,n)),t.superRefine=r=>t.check(OT(r)),t.overwrite=r=>t.check(Gr(r)),t.optional=()=>xe(t),t.nullable=()=>My(t),t.nullish=()=>xe(My(t)),t.nonoptional=r=>TT(t,r),t.array=()=>Q(t),t.or=r=>fe([t,r]),t.and=r=>Vi(t,r),t.transform=r=>Ku(t,Zy(r)),t.default=r=>$T(t,r),t.prefault=r=>PT(t,r),t.catch=r=>RT(t,r),t.pipe=r=>Ku(t,r),t.readonly=()=>CT(t),t.describe=r=>{let n=t.clone();return qo.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return qo.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return qo.get(t);let n=t.clone();return qo.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Ny=w("_ZodString",(t,e)=>{Mi.init(t,e),Se.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Du(...n)),t.includes=(...n)=>t.check(Mu(...n)),t.startsWith=(...n)=>t.check(Nu(...n)),t.endsWith=(...n)=>t.check(ju(...n)),t.min=(...n)=>t.check(Mn(...n)),t.max=(...n)=>t.check(Fi(...n)),t.length=(...n)=>t.check(Zi(...n)),t.nonempty=(...n)=>t.check(Mn(1,...n)),t.lowercase=n=>t.check(zu(n)),t.uppercase=n=>t.check(Ou(n)),t.trim=()=>t.check(Fu()),t.normalize=(...n)=>t.check(Lu(...n)),t.toLowerCase=()=>t.check(Zu()),t.toUpperCase=()=>t.check(Uu())}),WP=w("ZodString",(t,e)=>{Mi.init(t,e),Ny.init(t,e),t.email=r=>t.check(Vg(HP,r)),t.url=r=>t.check(Gg(KP,r)),t.jwt=r=>t.check(ly(uT,r)),t.emoji=r=>t.check(Jg(GP,r)),t.guid=r=>t.check(Cu(zy,r)),t.uuid=r=>t.check(Bg(qi,r)),t.uuidv4=r=>t.check(Wg(qi,r)),t.uuidv6=r=>t.check(Hg(qi,r)),t.uuidv7=r=>t.check(Kg(qi,r)),t.nanoid=r=>t.check(Yg(JP,r)),t.guid=r=>t.check(Cu(zy,r)),t.cuid=r=>t.check(Qg(YP,r)),t.cuid2=r=>t.check(Xg(QP,r)),t.ulid=r=>t.check(ey(XP,r)),t.base64=r=>t.check(ay(iT,r)),t.base64url=r=>t.check(cy(aT,r)),t.xid=r=>t.check(ty(eT,r)),t.ksuid=r=>t.check(ry(tT,r)),t.ipv4=r=>t.check(ny(rT,r)),t.ipv6=r=>t.check(oy(nT,r)),t.cidrv4=r=>t.check(sy(oT,r)),t.cidrv6=r=>t.check(iy(sT,r)),t.e164=r=>t.check(uy(cT,r)),t.datetime=r=>t.check(qu(r)),t.date=r=>t.check(Vu(r)),t.time=r=>t.check(Bu(r)),t.duration=r=>t.check(Wu(r))});function b(t){return qg(WP,t)}var ve=w("ZodStringFormat",(t,e)=>{he.init(t,e),Ny.init(t,e)}),HP=w("ZodEmail",(t,e)=>{Qh.init(t,e),ve.init(t,e)});var zy=w("ZodGUID",(t,e)=>{Jh.init(t,e),ve.init(t,e)});var qi=w("ZodUUID",(t,e)=>{Yh.init(t,e),ve.init(t,e)});var KP=w("ZodURL",(t,e)=>{Xh.init(t,e),ve.init(t,e)});var GP=w("ZodEmoji",(t,e)=>{eg.init(t,e),ve.init(t,e)});var JP=w("ZodNanoID",(t,e)=>{tg.init(t,e),ve.init(t,e)});var YP=w("ZodCUID",(t,e)=>{rg.init(t,e),ve.init(t,e)});var QP=w("ZodCUID2",(t,e)=>{ng.init(t,e),ve.init(t,e)});var XP=w("ZodULID",(t,e)=>{og.init(t,e),ve.init(t,e)});var eT=w("ZodXID",(t,e)=>{sg.init(t,e),ve.init(t,e)});var tT=w("ZodKSUID",(t,e)=>{ig.init(t,e),ve.init(t,e)});var rT=w("ZodIPv4",(t,e)=>{dg.init(t,e),ve.init(t,e)});var nT=w("ZodIPv6",(t,e)=>{pg.init(t,e),ve.init(t,e)});var oT=w("ZodCIDRv4",(t,e)=>{fg.init(t,e),ve.init(t,e)});var sT=w("ZodCIDRv6",(t,e)=>{mg.init(t,e),ve.init(t,e)});var iT=w("ZodBase64",(t,e)=>{gg.init(t,e),ve.init(t,e)});var aT=w("ZodBase64URL",(t,e)=>{yg.init(t,e),ve.init(t,e)});var cT=w("ZodE164",(t,e)=>{vg.init(t,e),ve.init(t,e)});var uT=w("ZodJWT",(t,e)=>{_g.init(t,e),ve.init(t,e)});var jy=w("ZodNumber",(t,e)=>{Ru.init(t,e),Se.init(t,e),t.gt=(n,o)=>t.check(ji(n,o)),t.gte=(n,o)=>t.check(Bo(n,o)),t.min=(n,o)=>t.check(Bo(n,o)),t.lt=(n,o)=>t.check(Ni(n,o)),t.lte=(n,o)=>t.check(Vo(n,o)),t.max=(n,o)=>t.check(Vo(n,o)),t.int=n=>t.check(Oy(n)),t.safe=n=>t.check(Oy(n)),t.positive=n=>t.check(ji(0,n)),t.nonnegative=n=>t.check(Bo(0,n)),t.negative=n=>t.check(Ni(0,n)),t.nonpositive=n=>t.check(Vo(0,n)),t.multipleOf=(n,o)=>t.check(Li(n,o)),t.step=(n,o)=>t.check(Li(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ae(t){return hy(jy,t)}var lT=w("ZodNumberFormat",(t,e)=>{bg.init(t,e),jy.init(t,e)});function Oy(t){return gy(lT,t)}var dT=w("ZodBoolean",(t,e)=>{wg.init(t,e),Se.init(t,e)});function Pe(t){return yy(dT,t)}var pT=w("ZodNull",(t,e)=>{xg.init(t,e),Se.init(t,e)});function Gu(t){return vy(pT,t)}var fT=w("ZodUnknown",(t,e)=>{Sg.init(t,e),Se.init(t,e)});function _e(){return _y(fT)}var mT=w("ZodNever",(t,e)=>{$g.init(t,e),Se.init(t,e)});function hT(t){return by(mT,t)}var gT=w("ZodArray",(t,e)=>{kg.init(t,e),Se.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Mn(r,n)),t.nonempty=r=>t.check(Mn(1,r)),t.max=(r,n)=>t.check(Fi(r,n)),t.length=(r,n)=>t.check(Zi(r,n)),t.unwrap=()=>t.element});function Q(t,e){return wy(gT,t,e)}var Ly=w("ZodObject",(t,e)=>{Pg.init(t,e),Se.init(t,e),ie.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Je(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:_e()}),t.loose=()=>t.clone({...t._zod.def,catchall:_e()}),t.strict=()=>t.clone({...t._zod.def,catchall:hT()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ie.extend(t,r),t.merge=r=>ie.merge(t,r),t.pick=r=>ie.pick(t,r),t.omit=r=>ie.omit(t,r),t.partial=(...r)=>ie.partial(Uy,t,r[0]),t.required=(...r)=>ie.required(qy,t,r[0])});function I(t,e){let r={type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},...ie.normalizeParams(e)};return new Ly(r)}function qe(t,e){return new Ly({type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},catchall:_e(),...ie.normalizeParams(e)})}var Fy=w("ZodUnion",(t,e)=>{Iu.init(t,e),Se.init(t,e),t.options=e.options});function fe(t,e){return new Fy({type:"union",options:t,...ie.normalizeParams(e)})}var yT=w("ZodDiscriminatedUnion",(t,e)=>{Fy.init(t,e),Tg.init(t,e)});function Ju(t,e,r){return new yT({type:"union",options:e,discriminator:t,...ie.normalizeParams(r)})}var vT=w("ZodIntersection",(t,e)=>{Eg.init(t,e),Se.init(t,e)});function Vi(t,e){return new vT({type:"intersection",left:t,right:e})}var _T=w("ZodRecord",(t,e)=>{Rg.init(t,e),Se.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,r){return new _T({type:"record",keyType:t,valueType:e,...ie.normalizeParams(r)})}var Hu=w("ZodEnum",(t,e)=>{Ig.init(t,e),Se.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Hu({...e,checks:[],...ie.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Hu({...e,checks:[],...ie.normalizeParams(o),entries:s})}});function Je(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Hu({type:"enum",entries:r,...ie.normalizeParams(e)})}var bT=w("ZodLiteral",(t,e)=>{Ag.init(t,e),Se.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function C(t,e){return new bT({type:"literal",values:Array.isArray(t)?t:[t],...ie.normalizeParams(e)})}var wT=w("ZodTransform",(t,e)=>{Cg.init(t,e),Se.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ie.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ie.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Zy(t){return new wT({type:"transform",transform:t})}var Uy=w("ZodOptional",(t,e)=>{Dg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xe(t){return new Uy({type:"optional",innerType:t})}var xT=w("ZodNullable",(t,e)=>{zg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function My(t){return new xT({type:"nullable",innerType:t})}var ST=w("ZodDefault",(t,e)=>{Og.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function $T(t,e){return new ST({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var kT=w("ZodPrefault",(t,e)=>{Mg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function PT(t,e){return new kT({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var qy=w("ZodNonOptional",(t,e)=>{Ng.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function TT(t,e){return new qy({type:"nonoptional",innerType:t,...ie.normalizeParams(e)})}var ET=w("ZodCatch",(t,e)=>{jg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function RT(t,e){return new ET({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var IT=w("ZodPipe",(t,e)=>{Lg.init(t,e),Se.init(t,e),t.in=e.in,t.out=e.out});function Ku(t,e){return new IT({type:"pipe",in:t,out:e})}var AT=w("ZodReadonly",(t,e)=>{Fg.init(t,e),Se.init(t,e)});function CT(t){return new AT({type:"readonly",innerType:t})}var Vy=w("ZodCustom",(t,e)=>{Zg.init(t,e),Se.init(t,e)});function DT(t){let e=new Ne({check:"custom"});return e._zod.check=t,e}function By(t,e){return xy(Vy,t??(()=>!0),e)}function zT(t,e={}){return Sy(Vy,t,e)}function OT(t){let e=DT(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ie.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ie.issue(o))}},t(r.value,r)));return e}function Yu(t,e){return Ku(Zy(t),e)}at(Ug());var Xu="2025-11-25";var Wy=[Xu,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],dr="io.modelcontextprotocol/related-task",Wi="2.0",Ee=By(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Hy=fe([b(),ae().int()]),Ky=b(),iq=qe({ttl:fe([ae(),Gu()]).optional(),pollInterval:ae().optional()}),MT=I({ttl:ae().optional()}),NT=I({taskId:b()}),el=qe({progressToken:Hy.optional(),[dr]:NT.optional()}),nt=I({_meta:el.optional()}),Go=nt.extend({task:MT.optional()}),Gy=t=>Go.safeParse(t).success,Re=I({method:b(),params:nt.loose().optional()}),ct=I({_meta:el.optional()}),ut=I({method:b(),params:ct.loose().optional()}),Ie=qe({_meta:el.optional()}),Hi=fe([b(),ae().int()]),Jy=I({jsonrpc:C(Wi),id:Hi,...Re.shape}).strict(),tl=t=>Jy.safeParse(t).success,Yy=I({jsonrpc:C(Wi),...ut.shape}).strict(),Qy=t=>Yy.safeParse(t).success,rl=I({jsonrpc:C(Wi),id:Hi,result:Ie}).strict(),Jo=t=>rl.safeParse(t).success;var X;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(X||(X={}));var nl=I({jsonrpc:C(Wi),id:Hi.optional(),error:I({code:ae().int(),message:b(),data:_e().optional()})}).strict();var Xy=t=>nl.safeParse(t).success;var ev=fe([Jy,Yy,rl,nl]),aq=fe([rl,nl]),Ki=Ie.strict(),jT=ct.extend({requestId:Hi.optional(),reason:b().optional()}),Gi=ut.extend({method:C("notifications/cancelled"),params:jT}),LT=I({src:b(),mimeType:b().optional(),sizes:Q(b()).optional(),theme:Je(["light","dark"]).optional()}),Yo=I({icons:Q(LT).optional()}),jn=I({name:b(),title:b().optional()}),tv=jn.extend({...jn.shape,...Yo.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),FT=Vi(I({applyDefaults:Pe().optional()}),be(b(),_e())),ZT=Yu(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Vi(I({form:FT.optional(),url:Ee.optional()}),be(b(),_e()).optional())),UT=qe({list:Ee.optional(),cancel:Ee.optional(),requests:qe({sampling:qe({createMessage:Ee.optional()}).optional(),elicitation:qe({create:Ee.optional()}).optional()}).optional()}),qT=qe({list:Ee.optional(),cancel:Ee.optional(),requests:qe({tools:qe({call:Ee.optional()}).optional()}).optional()}),VT=I({experimental:be(b(),Ee).optional(),sampling:I({context:Ee.optional(),tools:Ee.optional()}).optional(),elicitation:ZT.optional(),roots:I({listChanged:Pe().optional()}).optional(),tasks:UT.optional()}),BT=nt.extend({protocolVersion:b(),capabilities:VT,clientInfo:tv}),ol=Re.extend({method:C("initialize"),params:BT});var WT=I({experimental:be(b(),Ee).optional(),logging:Ee.optional(),completions:Ee.optional(),prompts:I({listChanged:Pe().optional()}).optional(),resources:I({subscribe:Pe().optional(),listChanged:Pe().optional()}).optional(),tools:I({listChanged:Pe().optional()}).optional(),tasks:qT.optional()}),HT=Ie.extend({protocolVersion:b(),capabilities:WT,serverInfo:tv,instructions:b().optional()}),sl=ut.extend({method:C("notifications/initialized"),params:ct.optional()});var Ji=Re.extend({method:C("ping"),params:nt.optional()}),KT=I({progress:ae(),total:xe(ae()),message:xe(b())}),GT=I({...ct.shape,...KT.shape,progressToken:Hy}),Yi=ut.extend({method:C("notifications/progress"),params:GT}),JT=nt.extend({cursor:Ky.optional()}),Qo=Re.extend({params:JT.optional()}),Xo=Ie.extend({nextCursor:Ky.optional()}),YT=Je(["working","input_required","completed","failed","cancelled"]),es=I({taskId:b(),status:YT,ttl:fe([ae(),Gu()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:xe(ae()),statusMessage:xe(b())}),Ln=Ie.extend({task:es}),QT=ct.merge(es),ts=ut.extend({method:C("notifications/tasks/status"),params:QT}),Qi=Re.extend({method:C("tasks/get"),params:nt.extend({taskId:b()})}),Xi=Ie.merge(es),ea=Re.extend({method:C("tasks/result"),params:nt.extend({taskId:b()})}),cq=Ie.loose(),ta=Qo.extend({method:C("tasks/list")}),ra=Xo.extend({tasks:Q(es)}),na=Re.extend({method:C("tasks/cancel"),params:nt.extend({taskId:b()})}),rv=Ie.merge(es),nv=I({uri:b(),mimeType:xe(b()),_meta:be(b(),_e()).optional()}),ov=nv.extend({text:b()}),il=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),sv=nv.extend({blob:il}),rs=Je(["user","assistant"]),Fn=I({audience:Q(rs).optional(),priority:ae().min(0).max(1).optional(),lastModified:Ho.datetime({offset:!0}).optional()}),iv=I({...jn.shape,...Yo.shape,uri:b(),description:xe(b()),mimeType:xe(b()),annotations:Fn.optional(),_meta:xe(qe({}))}),XT=I({...jn.shape,...Yo.shape,uriTemplate:b(),description:xe(b()),mimeType:xe(b()),annotations:Fn.optional(),_meta:xe(qe({}))}),eE=Qo.extend({method:C("resources/list")}),tE=Xo.extend({resources:Q(iv)}),rE=Qo.extend({method:C("resources/templates/list")}),nE=Xo.extend({resourceTemplates:Q(XT)}),al=nt.extend({uri:b()}),oE=al,sE=Re.extend({method:C("resources/read"),params:oE}),iE=Ie.extend({contents:Q(fe([ov,sv]))}),aE=ut.extend({method:C("notifications/resources/list_changed"),params:ct.optional()}),cE=al,uE=Re.extend({method:C("resources/subscribe"),params:cE}),lE=al,dE=Re.extend({method:C("resources/unsubscribe"),params:lE}),pE=ct.extend({uri:b()}),fE=ut.extend({method:C("notifications/resources/updated"),params:pE}),mE=I({name:b(),description:xe(b()),required:xe(Pe())}),hE=I({...jn.shape,...Yo.shape,description:xe(b()),arguments:xe(Q(mE)),_meta:xe(qe({}))}),gE=Qo.extend({method:C("prompts/list")}),yE=Xo.extend({prompts:Q(hE)}),vE=nt.extend({name:b(),arguments:be(b(),b()).optional()}),_E=Re.extend({method:C("prompts/get"),params:vE}),cl=I({type:C("text"),text:b(),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),ul=I({type:C("image"),data:il,mimeType:b(),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),ll=I({type:C("audio"),data:il,mimeType:b(),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),bE=I({type:C("tool_use"),name:b(),id:b(),input:be(b(),_e()),_meta:be(b(),_e()).optional()}),wE=I({type:C("resource"),resource:fe([ov,sv]),annotations:Fn.optional(),_meta:be(b(),_e()).optional()}),xE=iv.extend({type:C("resource_link")}),dl=fe([cl,ul,ll,xE,wE]),SE=I({role:rs,content:dl}),$E=Ie.extend({description:b().optional(),messages:Q(SE)}),kE=ut.extend({method:C("notifications/prompts/list_changed"),params:ct.optional()}),PE=I({title:b().optional(),readOnlyHint:Pe().optional(),destructiveHint:Pe().optional(),idempotentHint:Pe().optional(),openWorldHint:Pe().optional()}),TE=I({taskSupport:Je(["required","optional","forbidden"]).optional()}),av=I({...jn.shape,...Yo.shape,description:b().optional(),inputSchema:I({type:C("object"),properties:be(b(),Ee).optional(),required:Q(b()).optional()}).catchall(_e()),outputSchema:I({type:C("object"),properties:be(b(),Ee).optional(),required:Q(b()).optional()}).catchall(_e()).optional(),annotations:PE.optional(),execution:TE.optional(),_meta:be(b(),_e()).optional()}),pl=Qo.extend({method:C("tools/list")}),EE=Xo.extend({tools:Q(av)}),oa=Ie.extend({content:Q(dl).default([]),structuredContent:be(b(),_e()).optional(),isError:Pe().optional()}),uq=oa.or(Ie.extend({toolResult:_e()})),RE=Go.extend({name:b(),arguments:be(b(),_e()).optional()}),ns=Re.extend({method:C("tools/call"),params:RE}),IE=ut.extend({method:C("notifications/tools/list_changed"),params:ct.optional()}),lq=I({autoRefresh:Pe().default(!0),debounceMs:ae().int().nonnegative().default(300)}),os=Je(["debug","info","notice","warning","error","critical","alert","emergency"]),AE=nt.extend({level:os}),fl=Re.extend({method:C("logging/setLevel"),params:AE}),CE=ct.extend({level:os,logger:b().optional(),data:_e()}),DE=ut.extend({method:C("notifications/message"),params:CE}),zE=I({name:b().optional()}),OE=I({hints:Q(zE).optional(),costPriority:ae().min(0).max(1).optional(),speedPriority:ae().min(0).max(1).optional(),intelligencePriority:ae().min(0).max(1).optional()}),ME=I({mode:Je(["auto","required","none"]).optional()}),NE=I({type:C("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Q(dl).default([]),structuredContent:I({}).loose().optional(),isError:Pe().optional(),_meta:be(b(),_e()).optional()}),jE=Ju("type",[cl,ul,ll]),Bi=Ju("type",[cl,ul,ll,bE,NE]),LE=I({role:rs,content:fe([Bi,Q(Bi)]),_meta:be(b(),_e()).optional()}),FE=Go.extend({messages:Q(LE),modelPreferences:OE.optional(),systemPrompt:b().optional(),includeContext:Je(["none","thisServer","allServers"]).optional(),temperature:ae().optional(),maxTokens:ae().int(),stopSequences:Q(b()).optional(),metadata:Ee.optional(),tools:Q(av).optional(),toolChoice:ME.optional()}),ZE=Re.extend({method:C("sampling/createMessage"),params:FE}),ml=Ie.extend({model:b(),stopReason:xe(Je(["endTurn","stopSequence","maxTokens"]).or(b())),role:rs,content:jE}),hl=Ie.extend({model:b(),stopReason:xe(Je(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:rs,content:fe([Bi,Q(Bi)])}),UE=I({type:C("boolean"),title:b().optional(),description:b().optional(),default:Pe().optional()}),qE=I({type:C("string"),title:b().optional(),description:b().optional(),minLength:ae().optional(),maxLength:ae().optional(),format:Je(["email","uri","date","date-time"]).optional(),default:b().optional()}),VE=I({type:Je(["number","integer"]),title:b().optional(),description:b().optional(),minimum:ae().optional(),maximum:ae().optional(),default:ae().optional()}),BE=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Q(b()),default:b().optional()}),WE=I({type:C("string"),title:b().optional(),description:b().optional(),oneOf:Q(I({const:b(),title:b()})),default:b().optional()}),HE=I({type:C("string"),title:b().optional(),description:b().optional(),enum:Q(b()),enumNames:Q(b()).optional(),default:b().optional()}),KE=fe([BE,WE]),GE=I({type:C("array"),title:b().optional(),description:b().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:I({type:C("string"),enum:Q(b())}),default:Q(b()).optional()}),JE=I({type:C("array"),title:b().optional(),description:b().optional(),minItems:ae().optional(),maxItems:ae().optional(),items:I({anyOf:Q(I({const:b(),title:b()}))}),default:Q(b()).optional()}),YE=fe([GE,JE]),QE=fe([HE,KE,YE]),XE=fe([QE,UE,qE,VE]),eR=Go.extend({mode:C("form").optional(),message:b(),requestedSchema:I({type:C("object"),properties:be(b(),XE),required:Q(b()).optional()})}),tR=Go.extend({mode:C("url"),message:b(),elicitationId:b(),url:b().url()}),rR=fe([eR,tR]),nR=Re.extend({method:C("elicitation/create"),params:rR}),oR=ct.extend({elicitationId:b()}),sR=ut.extend({method:C("notifications/elicitation/complete"),params:oR}),sa=Ie.extend({action:Je(["accept","decline","cancel"]),content:Yu(t=>t===null?void 0:t,be(b(),fe([b(),ae(),Pe(),Q(b())])).optional())}),iR=I({type:C("ref/resource"),uri:b()});var aR=I({type:C("ref/prompt"),name:b()}),cR=nt.extend({ref:fe([aR,iR]),argument:I({name:b(),value:b()}),context:I({arguments:be(b(),b()).optional()}).optional()}),uR=Re.extend({method:C("completion/complete"),params:cR});var lR=Ie.extend({completion:qe({values:Q(b()).max(100),total:xe(ae().int()),hasMore:xe(Pe())})}),dR=I({uri:b().startsWith("file://"),name:b().optional(),_meta:be(b(),_e()).optional()}),pR=Re.extend({method:C("roots/list"),params:nt.optional()}),gl=Ie.extend({roots:Q(dR)}),fR=ut.extend({method:C("notifications/roots/list_changed"),params:ct.optional()}),dq=fe([Ji,ol,uR,fl,_E,gE,eE,rE,sE,uE,dE,ns,pl,Qi,ea,ta,na]),pq=fe([Gi,Yi,sl,fR,ts]),fq=fe([Ki,ml,hl,sa,gl,Xi,ra,Ln]),mq=fe([Ji,ZE,nR,pR,Qi,ea,ta,na]),hq=fe([Gi,Yi,DE,fE,aE,IE,kE,ts,sR]),gq=fe([Ki,HT,lR,$E,yE,tE,nE,iE,oa,EE,Xi,ra,Ln]),W=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===X.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Qu(o.elicitations,r)}return new t(e,r,n)}},Qu=class extends W{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(X.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function pr(t){return t==="completed"||t==="failed"||t==="cancelled"}var uv=Symbol("Let zodToJsonSchema decide on which parser to use");var cv={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"},lv=t=>typeof t=="string"?{...cv,name:t}:{...cv,...t};var dv=t=>{let e=lv(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function yl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ee(t,e,r,n,o){t[e]=r,yl(t,e,n,o)}var ia=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?ia(e,t.currentPath):e.join("/")}}function pv(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==k.ZodAny&&(r.items=j(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ee(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ee(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ee(r,"minItems",t.exactLength.value,t.exactLength.message,e),ee(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function fv(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function mv(){return{type:"boolean"}}function aa(t,e){return j(t.type._def,e)}var hv=(t,e)=>j(t.innerType._def,e);function vl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>vl(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return mR(t,e)}}var mR=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ee(r,"minimum",n.value,n.message,e);break;case"max":ee(r,"maximum",n.value,n.message,e);break}return r};function gv(t,e){return{...j(t.innerType._def,e),default:t.defaultValue()}}function yv(t,e){return e.effectStrategy==="input"?j(t.schema._def,e):we(e)}function vv(t){return{type:"string",enum:Array.from(t.values)}}var hR=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function _v(t,e){let r=[j(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),j(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(hR(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function bv(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var _l,yt={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:()=>(_l===void 0&&(_l=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),_l),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 ca(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":vt(r,"email",n.message,e);break;case"format:idn-email":vt(r,"idn-email",n.message,e);break;case"pattern:zod":Ve(r,yt.email,n.message,e);break}break;case"url":vt(r,"uri",n.message,e);break;case"uuid":vt(r,"uuid",n.message,e);break;case"regex":Ve(r,n.regex,n.message,e);break;case"cuid":Ve(r,yt.cuid,n.message,e);break;case"cuid2":Ve(r,yt.cuid2,n.message,e);break;case"startsWith":Ve(r,RegExp(`^${bl(n.value,e)}`),n.message,e);break;case"endsWith":Ve(r,RegExp(`${bl(n.value,e)}$`),n.message,e);break;case"datetime":vt(r,"date-time",n.message,e);break;case"date":vt(r,"date",n.message,e);break;case"time":vt(r,"time",n.message,e);break;case"duration":vt(r,"duration",n.message,e);break;case"length":ee(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ee(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ve(r,RegExp(bl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&vt(r,"ipv4",n.message,e),n.version!=="v4"&&vt(r,"ipv6",n.message,e);break}case"base64url":Ve(r,yt.base64url,n.message,e);break;case"jwt":Ve(r,yt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ve(r,yt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ve(r,yt.ipv6Cidr,n.message,e);break}case"emoji":Ve(r,yt.emoji(),n.message,e);break;case"ulid":{Ve(r,yt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{vt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ee(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ve(r,yt.base64,n.message,e);break}}break}case"nanoid":Ve(r,yt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function bl(t,e){return e.patternStrategy==="escape"?yR(t):t}var gR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function yR(t){let e="";for(let r=0;r<t.length;r++)gR.has(t[r])||(e+="\\"),e+=t[r];return e}function vt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ee(t,"format",e,r,n)}function Ve(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:wv(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ee(t,"pattern",wv(e,n),r,n)}function wv(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
236
|
+
path: iss.path ? [${Qr(S)}, ...iss.path] : [${Qr(S)}]
|
|
237
|
+
})));`),p.write(`newResult[${Qr(S)}] = ${w}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let v=p.compile();return(S,w)=>v(d,S,w)},o,s=Ln,i=!Ai.jitless,c=i&&Eu.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let f=d.value;if(!s(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(e.shape)),d=o(d,p);else{d.value={};let w=l.shape;for(let _ of l.keys){let P=w[_],A=P._zod.run({value:f[_],issues:[]},p),D=P._zod.optin==="optional"&&P._zod.optout==="optional";A instanceof Promise?m.push(A.then(U=>D?ng(U,d,_,f):ji(U,d,_))):D?ng(A,d,_,f):ji(A,d,_)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let g=[],y=l.keySet,v=u._zod,S=v.def.type;for(let w of Object.keys(f)){if(y.has(w))continue;if(S==="never"){g.push(w);continue}let _=v.run({value:f[w],issues:[]},p);_ instanceof Promise?m.push(_.then(P=>ji(P,d,w))):ji(_,d,w)}return g.length&&d.issues.push({code:"unrecognized_keys",keys:g,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function og(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>wt(s,n,pt())))}),e}var qu=x("$ZodUnion",(t,e)=>{fe.init(t,e),pe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),pe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),pe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),pe(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Wo(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>og(i,r,t,n)):og(s,r,t,n)}}),Ug=x("$ZodDiscriminatedUnion",(t,e)=>{qu.init(t,e);let r=t._zod.parse;pe(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Vo(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!Ln(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),qg=x("$ZodIntersection",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>sg(r,c,u)):sg(r,s,i)}});function Zu(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Fn(t)&&Fn(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Zu(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Zu(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function sg(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),en(t))return t;let n=Zu(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var Vg=x("$ZodRecord",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Fn(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...Nt(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Nt(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>wt(u,n,pt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Nt(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Nt(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Bg=x("$ZodEnum",(t,e)=>{fe.init(t,e);let r=$u(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Ru.has(typeof n)).map(n=>typeof n=="string"?mr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Wg=x("$ZodLiteral",(t,e)=>{fe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?mr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}});var Hg=x("$ZodTransform",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Qt;return r.value=o,r}}),Kg=x("$ZodOptional",(t,e)=>{fe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",pe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),pe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Wo(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Gg=x("$ZodNullable",(t,e)=>{fe.init(t,e),pe(t._zod,"optin",()=>e.innerType._zod.optin),pe(t._zod,"optout",()=>e.innerType._zod.optout),pe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Wo(r.source)}|null)$`):void 0}),pe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Jg=x("$ZodDefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",pe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>ig(s,e)):ig(o,e)}});function ig(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Yg=x("$ZodPrefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",pe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Xg=x("$ZodNonOptional",(t,e)=>{fe.init(t,e),pe(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>ag(s,t)):ag(o,t)}});function ag(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Qg=x("$ZodCatch",(t,e)=>{fe.init(t,e),t._zod.optin="optional",pe(t._zod,"optout",()=>e.innerType._zod.optout),pe(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>wt(i,n,pt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>wt(s,n,pt()))},input:r.value}),r.issues=[]),r)}});var ey=x("$ZodPipe",(t,e)=>{fe.init(t,e),pe(t._zod,"values",()=>e.in._zod.values),pe(t._zod,"optin",()=>e.in._zod.optin),pe(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>cg(s,e,n)):cg(o,e,n)}});function cg(t,e,r){return en(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var ty=x("$ZodReadonly",(t,e)=>{fe.init(t,e),pe(t._zod,"propValues",()=>e.innerType._zod.propValues),pe(t._zod,"values",()=>e.innerType._zod.values),pe(t._zod,"optin",()=>e.innerType._zod.optin),pe(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(ug):ug(o)}});function ug(t){return t.value=Object.freeze(t.value),t}var ry=x("$ZodCustom",(t,e)=>{Ze.init(t,e),fe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>lg(s,r,n,t));lg(o,r,n,t)}});function lg(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Cu(o))}}var sT=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},iT=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${sT(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${zi(n.values[0])}`:`Invalid option: expected one of ${Ci(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ci(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function ny(){return{localeError:iT()}}var Vu=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function aT(){return new Vu}var Jo=aT();function oy(t,e){return new t({type:"string",...j(e)})}function sy(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...j(e)})}function Bu(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...j(e)})}function iy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...j(e)})}function ay(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...j(e)})}function cy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...j(e)})}function uy(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...j(e)})}function ly(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...j(e)})}function dy(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...j(e)})}function py(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...j(e)})}function fy(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...j(e)})}function my(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...j(e)})}function hy(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...j(e)})}function gy(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...j(e)})}function yy(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...j(e)})}function vy(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...j(e)})}function _y(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...j(e)})}function by(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...j(e)})}function wy(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...j(e)})}function xy(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...j(e)})}function Sy(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...j(e)})}function $y(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...j(e)})}function ky(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...j(e)})}function Py(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...j(e)})}function Ty(t,e){return new t({type:"string",format:"date",check:"string_format",...j(e)})}function Ey(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...j(e)})}function Ry(t,e){return new t({type:"string",format:"duration",check:"string_format",...j(e)})}function Iy(t,e){return new t({type:"number",checks:[],...j(e)})}function Ay(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...j(e)})}function Cy(t,e){return new t({type:"boolean",...j(e)})}function Dy(t,e){return new t({type:"null",...j(e)})}function zy(t){return new t({type:"unknown"})}function Oy(t,e){return new t({type:"never",...j(e)})}function Fi(t,e){return new Lu({check:"less_than",...j(e),value:t,inclusive:!1})}function Yo(t,e){return new Lu({check:"less_than",...j(e),value:t,inclusive:!0})}function Zi(t,e){return new Fu({check:"greater_than",...j(e),value:t,inclusive:!1})}function Xo(t,e){return new Fu({check:"greater_than",...j(e),value:t,inclusive:!0})}function Ui(t,e){return new Uh({check:"multiple_of",...j(e),value:t})}function qi(t,e){return new Vh({check:"max_length",...j(e),maximum:t})}function Zn(t,e){return new Bh({check:"min_length",...j(e),minimum:t})}function Vi(t,e){return new Wh({check:"length_equals",...j(e),length:t})}function Wu(t,e){return new Hh({check:"string_format",format:"regex",...j(e),pattern:t})}function Hu(t){return new Kh({check:"string_format",format:"lowercase",...j(t)})}function Ku(t){return new Gh({check:"string_format",format:"uppercase",...j(t)})}function Gu(t,e){return new Jh({check:"string_format",format:"includes",...j(e),includes:t})}function Ju(t,e){return new Yh({check:"string_format",format:"starts_with",...j(e),prefix:t})}function Yu(t,e){return new Xh({check:"string_format",format:"ends_with",...j(e),suffix:t})}function tn(t){return new Qh({check:"overwrite",tx:t})}function Xu(t){return tn(e=>e.normalize(t))}function Qu(){return tn(t=>t.trim())}function el(){return tn(t=>t.toLowerCase())}function tl(){return tn(t=>t.toUpperCase())}function My(t,e,r){return new t({type:"array",element:e,...j(r)})}function Ny(t,e,r){let n=j(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function jy(t,e,r){return new t({type:"custom",check:"custom",fn:e,...j(r)})}function Un(t){return!!t._zod}function hr(t,e){return Un(t)?Ko(t,e):t.safeParse(e)}function Bi(t){if(!t)return;let e;if(Un(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ly(t){if(Un(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var es={};Be(es,{ZodISODate:()=>Zy,ZodISODateTime:()=>Fy,ZodISODuration:()=>qy,ZodISOTime:()=>Uy,date:()=>nl,datetime:()=>rl,duration:()=>sl,time:()=>ol});var Fy=x("ZodISODateTime",(t,e)=>{xg.init(t,e),ve.init(t,e)});function rl(t){return Py(Fy,t)}var Zy=x("ZodISODate",(t,e)=>{Sg.init(t,e),ve.init(t,e)});function nl(t){return Ty(Zy,t)}var Uy=x("ZodISOTime",(t,e)=>{$g.init(t,e),ve.init(t,e)});function ol(t){return Ey(Uy,t)}var qy=x("ZodISODuration",(t,e)=>{kg.init(t,e),ve.init(t,e)});function sl(t){return Ry(qy,t)}var Vy=(t,e)=>{Oi.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>uh(t,r)},flatten:{value:r=>ch(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},GU=x("ZodError",Vy),ts=x("ZodError",Vy,{Parent:Error});var By=lh(ts),Wy=dh(ts),Hy=zu(ts),Ky=Ou(ts);var Se=x("ZodType",(t,e)=>(fe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Mt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>By(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Hy(t,r,n),t.parseAsync=async(r,n)=>Wy(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ky(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(oE(r,n)),t.superRefine=r=>t.check(sE(r)),t.overwrite=r=>t.check(tn(r)),t.optional=()=>xe(t),t.nullable=()=>Yy(t),t.nullish=()=>xe(Yy(t)),t.nonoptional=r=>YT(t,r),t.array=()=>Q(t),t.or=r=>me([t,r]),t.and=r=>Hi(t,r),t.transform=r=>al(t,rv(r)),t.default=r=>KT(t,r),t.prefault=r=>JT(t,r),t.catch=r=>QT(t,r),t.pipe=r=>al(t,r),t.readonly=()=>rE(t),t.describe=r=>{let n=t.clone();return Jo.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Jo.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Jo.get(t);let n=t.clone();return Jo.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Xy=x("_ZodString",(t,e)=>{Li.init(t,e),Se.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Wu(...n)),t.includes=(...n)=>t.check(Gu(...n)),t.startsWith=(...n)=>t.check(Ju(...n)),t.endsWith=(...n)=>t.check(Yu(...n)),t.min=(...n)=>t.check(Zn(...n)),t.max=(...n)=>t.check(qi(...n)),t.length=(...n)=>t.check(Vi(...n)),t.nonempty=(...n)=>t.check(Zn(1,...n)),t.lowercase=n=>t.check(Hu(n)),t.uppercase=n=>t.check(Ku(n)),t.trim=()=>t.check(Qu()),t.normalize=(...n)=>t.check(Xu(...n)),t.toLowerCase=()=>t.check(el()),t.toUpperCase=()=>t.check(tl())}),gT=x("ZodString",(t,e)=>{Li.init(t,e),Xy.init(t,e),t.email=r=>t.check(sy(yT,r)),t.url=r=>t.check(ly(vT,r)),t.jwt=r=>t.check(ky(DT,r)),t.emoji=r=>t.check(dy(_T,r)),t.guid=r=>t.check(Bu(Gy,r)),t.uuid=r=>t.check(iy(Wi,r)),t.uuidv4=r=>t.check(ay(Wi,r)),t.uuidv6=r=>t.check(cy(Wi,r)),t.uuidv7=r=>t.check(uy(Wi,r)),t.nanoid=r=>t.check(py(bT,r)),t.guid=r=>t.check(Bu(Gy,r)),t.cuid=r=>t.check(fy(wT,r)),t.cuid2=r=>t.check(my(xT,r)),t.ulid=r=>t.check(hy(ST,r)),t.base64=r=>t.check(xy(IT,r)),t.base64url=r=>t.check(Sy(AT,r)),t.xid=r=>t.check(gy($T,r)),t.ksuid=r=>t.check(yy(kT,r)),t.ipv4=r=>t.check(vy(PT,r)),t.ipv6=r=>t.check(_y(TT,r)),t.cidrv4=r=>t.check(by(ET,r)),t.cidrv6=r=>t.check(wy(RT,r)),t.e164=r=>t.check($y(CT,r)),t.datetime=r=>t.check(rl(r)),t.date=r=>t.check(nl(r)),t.time=r=>t.check(ol(r)),t.duration=r=>t.check(sl(r))});function b(t){return oy(gT,t)}var ve=x("ZodStringFormat",(t,e)=>{he.init(t,e),Xy.init(t,e)}),yT=x("ZodEmail",(t,e)=>{fg.init(t,e),ve.init(t,e)});var Gy=x("ZodGUID",(t,e)=>{dg.init(t,e),ve.init(t,e)});var Wi=x("ZodUUID",(t,e)=>{pg.init(t,e),ve.init(t,e)});var vT=x("ZodURL",(t,e)=>{mg.init(t,e),ve.init(t,e)});var _T=x("ZodEmoji",(t,e)=>{hg.init(t,e),ve.init(t,e)});var bT=x("ZodNanoID",(t,e)=>{gg.init(t,e),ve.init(t,e)});var wT=x("ZodCUID",(t,e)=>{yg.init(t,e),ve.init(t,e)});var xT=x("ZodCUID2",(t,e)=>{vg.init(t,e),ve.init(t,e)});var ST=x("ZodULID",(t,e)=>{_g.init(t,e),ve.init(t,e)});var $T=x("ZodXID",(t,e)=>{bg.init(t,e),ve.init(t,e)});var kT=x("ZodKSUID",(t,e)=>{wg.init(t,e),ve.init(t,e)});var PT=x("ZodIPv4",(t,e)=>{Pg.init(t,e),ve.init(t,e)});var TT=x("ZodIPv6",(t,e)=>{Tg.init(t,e),ve.init(t,e)});var ET=x("ZodCIDRv4",(t,e)=>{Eg.init(t,e),ve.init(t,e)});var RT=x("ZodCIDRv6",(t,e)=>{Rg.init(t,e),ve.init(t,e)});var IT=x("ZodBase64",(t,e)=>{Ag.init(t,e),ve.init(t,e)});var AT=x("ZodBase64URL",(t,e)=>{Cg.init(t,e),ve.init(t,e)});var CT=x("ZodE164",(t,e)=>{Dg.init(t,e),ve.init(t,e)});var DT=x("ZodJWT",(t,e)=>{zg.init(t,e),ve.init(t,e)});var Qy=x("ZodNumber",(t,e)=>{Uu.init(t,e),Se.init(t,e),t.gt=(n,o)=>t.check(Zi(n,o)),t.gte=(n,o)=>t.check(Xo(n,o)),t.min=(n,o)=>t.check(Xo(n,o)),t.lt=(n,o)=>t.check(Fi(n,o)),t.lte=(n,o)=>t.check(Yo(n,o)),t.max=(n,o)=>t.check(Yo(n,o)),t.int=n=>t.check(Jy(n)),t.safe=n=>t.check(Jy(n)),t.positive=n=>t.check(Zi(0,n)),t.nonnegative=n=>t.check(Xo(0,n)),t.negative=n=>t.check(Fi(0,n)),t.nonpositive=n=>t.check(Yo(0,n)),t.multipleOf=(n,o)=>t.check(Ui(n,o)),t.step=(n,o)=>t.check(Ui(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ce(t){return Iy(Qy,t)}var zT=x("ZodNumberFormat",(t,e)=>{Og.init(t,e),Qy.init(t,e)});function Jy(t){return Ay(zT,t)}var OT=x("ZodBoolean",(t,e)=>{Mg.init(t,e),Se.init(t,e)});function Re(t){return Cy(OT,t)}var MT=x("ZodNull",(t,e)=>{Ng.init(t,e),Se.init(t,e)});function cl(t){return Dy(MT,t)}var NT=x("ZodUnknown",(t,e)=>{jg.init(t,e),Se.init(t,e)});function _e(){return zy(NT)}var jT=x("ZodNever",(t,e)=>{Lg.init(t,e),Se.init(t,e)});function LT(t){return Oy(jT,t)}var FT=x("ZodArray",(t,e)=>{Fg.init(t,e),Se.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Zn(r,n)),t.nonempty=r=>t.check(Zn(1,r)),t.max=(r,n)=>t.check(qi(r,n)),t.length=(r,n)=>t.check(Vi(r,n)),t.unwrap=()=>t.element});function Q(t,e){return My(FT,t,e)}var ev=x("ZodObject",(t,e)=>{Zg.init(t,e),Se.init(t,e),ae.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Qe(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:_e()}),t.loose=()=>t.clone({...t._zod.def,catchall:_e()}),t.strict=()=>t.clone({...t._zod.def,catchall:LT()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ae.extend(t,r),t.merge=r=>ae.merge(t,r),t.pick=r=>ae.pick(t,r),t.omit=r=>ae.omit(t,r),t.partial=(...r)=>ae.partial(nv,t,r[0]),t.required=(...r)=>ae.required(ov,t,r[0])});function I(t,e){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},...ae.normalizeParams(e)};return new ev(r)}function He(t,e){return new ev({type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},catchall:_e(),...ae.normalizeParams(e)})}var tv=x("ZodUnion",(t,e)=>{qu.init(t,e),Se.init(t,e),t.options=e.options});function me(t,e){return new tv({type:"union",options:t,...ae.normalizeParams(e)})}var ZT=x("ZodDiscriminatedUnion",(t,e)=>{tv.init(t,e),Ug.init(t,e)});function ul(t,e,r){return new ZT({type:"union",options:e,discriminator:t,...ae.normalizeParams(r)})}var UT=x("ZodIntersection",(t,e)=>{qg.init(t,e),Se.init(t,e)});function Hi(t,e){return new UT({type:"intersection",left:t,right:e})}var qT=x("ZodRecord",(t,e)=>{Vg.init(t,e),Se.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,r){return new qT({type:"record",keyType:t,valueType:e,...ae.normalizeParams(r)})}var il=x("ZodEnum",(t,e)=>{Bg.init(t,e),Se.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new il({...e,checks:[],...ae.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new il({...e,checks:[],...ae.normalizeParams(o),entries:s})}});function Qe(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new il({type:"enum",entries:r,...ae.normalizeParams(e)})}var VT=x("ZodLiteral",(t,e)=>{Wg.init(t,e),Se.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function z(t,e){return new VT({type:"literal",values:Array.isArray(t)?t:[t],...ae.normalizeParams(e)})}var BT=x("ZodTransform",(t,e)=>{Hg.init(t,e),Se.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ae.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ae.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function rv(t){return new BT({type:"transform",transform:t})}var nv=x("ZodOptional",(t,e)=>{Kg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xe(t){return new nv({type:"optional",innerType:t})}var WT=x("ZodNullable",(t,e)=>{Gg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Yy(t){return new WT({type:"nullable",innerType:t})}var HT=x("ZodDefault",(t,e)=>{Jg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function KT(t,e){return new HT({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var GT=x("ZodPrefault",(t,e)=>{Yg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function JT(t,e){return new GT({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var ov=x("ZodNonOptional",(t,e)=>{Xg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType});function YT(t,e){return new ov({type:"nonoptional",innerType:t,...ae.normalizeParams(e)})}var XT=x("ZodCatch",(t,e)=>{Qg.init(t,e),Se.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function QT(t,e){return new XT({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var eE=x("ZodPipe",(t,e)=>{ey.init(t,e),Se.init(t,e),t.in=e.in,t.out=e.out});function al(t,e){return new eE({type:"pipe",in:t,out:e})}var tE=x("ZodReadonly",(t,e)=>{ty.init(t,e),Se.init(t,e)});function rE(t){return new tE({type:"readonly",innerType:t})}var sv=x("ZodCustom",(t,e)=>{ry.init(t,e),Se.init(t,e)});function nE(t){let e=new Ze({check:"custom"});return e._zod.check=t,e}function iv(t,e){return Ny(sv,t??(()=>!0),e)}function oE(t,e={}){return jy(sv,t,e)}function sE(t){let e=nE(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ae.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(ae.issue(o))}},t(r.value,r)));return e}function ll(t,e){return al(rv(t),e)}pt(ny());var pl="2025-11-25";var av=[pl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],gr="io.modelcontextprotocol/related-task",Gi="2.0",Ae=iv(t=>t!==null&&(typeof t=="object"||typeof t=="function")),cv=me([b(),ce().int()]),uv=b(),Uq=He({ttl:me([ce(),cl()]).optional(),pollInterval:ce().optional()}),iE=I({ttl:ce().optional()}),aE=I({taskId:b()}),fl=He({progressToken:cv.optional(),[gr]:aE.optional()}),it=I({_meta:fl.optional()}),rs=it.extend({task:iE.optional()}),lv=t=>rs.safeParse(t).success,Ce=I({method:b(),params:it.loose().optional()}),ft=I({_meta:fl.optional()}),mt=I({method:b(),params:ft.loose().optional()}),De=He({_meta:fl.optional()}),Ji=me([b(),ce().int()]),dv=I({jsonrpc:z(Gi),id:Ji,...Ce.shape}).strict(),ml=t=>dv.safeParse(t).success,pv=I({jsonrpc:z(Gi),...mt.shape}).strict(),fv=t=>pv.safeParse(t).success,hl=I({jsonrpc:z(Gi),id:Ji,result:De}).strict(),ns=t=>hl.safeParse(t).success;var ee;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ee||(ee={}));var gl=I({jsonrpc:z(Gi),id:Ji.optional(),error:I({code:ce().int(),message:b(),data:_e().optional()})}).strict();var mv=t=>gl.safeParse(t).success;var hv=me([dv,pv,hl,gl]),qq=me([hl,gl]),Yi=De.strict(),cE=ft.extend({requestId:Ji.optional(),reason:b().optional()}),Xi=mt.extend({method:z("notifications/cancelled"),params:cE}),uE=I({src:b(),mimeType:b().optional(),sizes:Q(b()).optional(),theme:Qe(["light","dark"]).optional()}),os=I({icons:Q(uE).optional()}),qn=I({name:b(),title:b().optional()}),gv=qn.extend({...qn.shape,...os.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),lE=Hi(I({applyDefaults:Re().optional()}),be(b(),_e())),dE=ll(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Hi(I({form:lE.optional(),url:Ae.optional()}),be(b(),_e()).optional())),pE=He({list:Ae.optional(),cancel:Ae.optional(),requests:He({sampling:He({createMessage:Ae.optional()}).optional(),elicitation:He({create:Ae.optional()}).optional()}).optional()}),fE=He({list:Ae.optional(),cancel:Ae.optional(),requests:He({tools:He({call:Ae.optional()}).optional()}).optional()}),mE=I({experimental:be(b(),Ae).optional(),sampling:I({context:Ae.optional(),tools:Ae.optional()}).optional(),elicitation:dE.optional(),roots:I({listChanged:Re().optional()}).optional(),tasks:pE.optional()}),hE=it.extend({protocolVersion:b(),capabilities:mE,clientInfo:gv}),yl=Ce.extend({method:z("initialize"),params:hE});var gE=I({experimental:be(b(),Ae).optional(),logging:Ae.optional(),completions:Ae.optional(),prompts:I({listChanged:Re().optional()}).optional(),resources:I({subscribe:Re().optional(),listChanged:Re().optional()}).optional(),tools:I({listChanged:Re().optional()}).optional(),tasks:fE.optional()}),yE=De.extend({protocolVersion:b(),capabilities:gE,serverInfo:gv,instructions:b().optional()}),vl=mt.extend({method:z("notifications/initialized"),params:ft.optional()});var Qi=Ce.extend({method:z("ping"),params:it.optional()}),vE=I({progress:ce(),total:xe(ce()),message:xe(b())}),_E=I({...ft.shape,...vE.shape,progressToken:cv}),ea=mt.extend({method:z("notifications/progress"),params:_E}),bE=it.extend({cursor:uv.optional()}),ss=Ce.extend({params:bE.optional()}),is=De.extend({nextCursor:uv.optional()}),wE=Qe(["working","input_required","completed","failed","cancelled"]),as=I({taskId:b(),status:wE,ttl:me([ce(),cl()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:xe(ce()),statusMessage:xe(b())}),Vn=De.extend({task:as}),xE=ft.merge(as),cs=mt.extend({method:z("notifications/tasks/status"),params:xE}),ta=Ce.extend({method:z("tasks/get"),params:it.extend({taskId:b()})}),ra=De.merge(as),na=Ce.extend({method:z("tasks/result"),params:it.extend({taskId:b()})}),Vq=De.loose(),oa=ss.extend({method:z("tasks/list")}),sa=is.extend({tasks:Q(as)}),ia=Ce.extend({method:z("tasks/cancel"),params:it.extend({taskId:b()})}),yv=De.merge(as),vv=I({uri:b(),mimeType:xe(b()),_meta:be(b(),_e()).optional()}),_v=vv.extend({text:b()}),_l=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),bv=vv.extend({blob:_l}),us=Qe(["user","assistant"]),Bn=I({audience:Q(us).optional(),priority:ce().min(0).max(1).optional(),lastModified:es.datetime({offset:!0}).optional()}),wv=I({...qn.shape,...os.shape,uri:b(),description:xe(b()),mimeType:xe(b()),annotations:Bn.optional(),_meta:xe(He({}))}),SE=I({...qn.shape,...os.shape,uriTemplate:b(),description:xe(b()),mimeType:xe(b()),annotations:Bn.optional(),_meta:xe(He({}))}),$E=ss.extend({method:z("resources/list")}),kE=is.extend({resources:Q(wv)}),PE=ss.extend({method:z("resources/templates/list")}),TE=is.extend({resourceTemplates:Q(SE)}),bl=it.extend({uri:b()}),EE=bl,RE=Ce.extend({method:z("resources/read"),params:EE}),IE=De.extend({contents:Q(me([_v,bv]))}),AE=mt.extend({method:z("notifications/resources/list_changed"),params:ft.optional()}),CE=bl,DE=Ce.extend({method:z("resources/subscribe"),params:CE}),zE=bl,OE=Ce.extend({method:z("resources/unsubscribe"),params:zE}),ME=ft.extend({uri:b()}),NE=mt.extend({method:z("notifications/resources/updated"),params:ME}),jE=I({name:b(),description:xe(b()),required:xe(Re())}),LE=I({...qn.shape,...os.shape,description:xe(b()),arguments:xe(Q(jE)),_meta:xe(He({}))}),FE=ss.extend({method:z("prompts/list")}),ZE=is.extend({prompts:Q(LE)}),UE=it.extend({name:b(),arguments:be(b(),b()).optional()}),qE=Ce.extend({method:z("prompts/get"),params:UE}),wl=I({type:z("text"),text:b(),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),xl=I({type:z("image"),data:_l,mimeType:b(),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),Sl=I({type:z("audio"),data:_l,mimeType:b(),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),VE=I({type:z("tool_use"),name:b(),id:b(),input:be(b(),_e()),_meta:be(b(),_e()).optional()}),BE=I({type:z("resource"),resource:me([_v,bv]),annotations:Bn.optional(),_meta:be(b(),_e()).optional()}),WE=wv.extend({type:z("resource_link")}),$l=me([wl,xl,Sl,WE,BE]),HE=I({role:us,content:$l}),KE=De.extend({description:b().optional(),messages:Q(HE)}),GE=mt.extend({method:z("notifications/prompts/list_changed"),params:ft.optional()}),JE=I({title:b().optional(),readOnlyHint:Re().optional(),destructiveHint:Re().optional(),idempotentHint:Re().optional(),openWorldHint:Re().optional()}),YE=I({taskSupport:Qe(["required","optional","forbidden"]).optional()}),xv=I({...qn.shape,...os.shape,description:b().optional(),inputSchema:I({type:z("object"),properties:be(b(),Ae).optional(),required:Q(b()).optional()}).catchall(_e()),outputSchema:I({type:z("object"),properties:be(b(),Ae).optional(),required:Q(b()).optional()}).catchall(_e()).optional(),annotations:JE.optional(),execution:YE.optional(),_meta:be(b(),_e()).optional()}),kl=ss.extend({method:z("tools/list")}),XE=is.extend({tools:Q(xv)}),aa=De.extend({content:Q($l).default([]),structuredContent:be(b(),_e()).optional(),isError:Re().optional()}),Bq=aa.or(De.extend({toolResult:_e()})),QE=rs.extend({name:b(),arguments:be(b(),_e()).optional()}),ls=Ce.extend({method:z("tools/call"),params:QE}),eR=mt.extend({method:z("notifications/tools/list_changed"),params:ft.optional()}),Wq=I({autoRefresh:Re().default(!0),debounceMs:ce().int().nonnegative().default(300)}),ds=Qe(["debug","info","notice","warning","error","critical","alert","emergency"]),tR=it.extend({level:ds}),Pl=Ce.extend({method:z("logging/setLevel"),params:tR}),rR=ft.extend({level:ds,logger:b().optional(),data:_e()}),nR=mt.extend({method:z("notifications/message"),params:rR}),oR=I({name:b().optional()}),sR=I({hints:Q(oR).optional(),costPriority:ce().min(0).max(1).optional(),speedPriority:ce().min(0).max(1).optional(),intelligencePriority:ce().min(0).max(1).optional()}),iR=I({mode:Qe(["auto","required","none"]).optional()}),aR=I({type:z("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:Q($l).default([]),structuredContent:I({}).loose().optional(),isError:Re().optional(),_meta:be(b(),_e()).optional()}),cR=ul("type",[wl,xl,Sl]),Ki=ul("type",[wl,xl,Sl,VE,aR]),uR=I({role:us,content:me([Ki,Q(Ki)]),_meta:be(b(),_e()).optional()}),lR=rs.extend({messages:Q(uR),modelPreferences:sR.optional(),systemPrompt:b().optional(),includeContext:Qe(["none","thisServer","allServers"]).optional(),temperature:ce().optional(),maxTokens:ce().int(),stopSequences:Q(b()).optional(),metadata:Ae.optional(),tools:Q(xv).optional(),toolChoice:iR.optional()}),dR=Ce.extend({method:z("sampling/createMessage"),params:lR}),Tl=De.extend({model:b(),stopReason:xe(Qe(["endTurn","stopSequence","maxTokens"]).or(b())),role:us,content:cR}),El=De.extend({model:b(),stopReason:xe(Qe(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:us,content:me([Ki,Q(Ki)])}),pR=I({type:z("boolean"),title:b().optional(),description:b().optional(),default:Re().optional()}),fR=I({type:z("string"),title:b().optional(),description:b().optional(),minLength:ce().optional(),maxLength:ce().optional(),format:Qe(["email","uri","date","date-time"]).optional(),default:b().optional()}),mR=I({type:Qe(["number","integer"]),title:b().optional(),description:b().optional(),minimum:ce().optional(),maximum:ce().optional(),default:ce().optional()}),hR=I({type:z("string"),title:b().optional(),description:b().optional(),enum:Q(b()),default:b().optional()}),gR=I({type:z("string"),title:b().optional(),description:b().optional(),oneOf:Q(I({const:b(),title:b()})),default:b().optional()}),yR=I({type:z("string"),title:b().optional(),description:b().optional(),enum:Q(b()),enumNames:Q(b()).optional(),default:b().optional()}),vR=me([hR,gR]),_R=I({type:z("array"),title:b().optional(),description:b().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:I({type:z("string"),enum:Q(b())}),default:Q(b()).optional()}),bR=I({type:z("array"),title:b().optional(),description:b().optional(),minItems:ce().optional(),maxItems:ce().optional(),items:I({anyOf:Q(I({const:b(),title:b()}))}),default:Q(b()).optional()}),wR=me([_R,bR]),xR=me([yR,vR,wR]),SR=me([xR,pR,fR,mR]),$R=rs.extend({mode:z("form").optional(),message:b(),requestedSchema:I({type:z("object"),properties:be(b(),SR),required:Q(b()).optional()})}),kR=rs.extend({mode:z("url"),message:b(),elicitationId:b(),url:b().url()}),PR=me([$R,kR]),TR=Ce.extend({method:z("elicitation/create"),params:PR}),ER=ft.extend({elicitationId:b()}),RR=mt.extend({method:z("notifications/elicitation/complete"),params:ER}),ca=De.extend({action:Qe(["accept","decline","cancel"]),content:ll(t=>t===null?void 0:t,be(b(),me([b(),ce(),Re(),Q(b())])).optional())}),IR=I({type:z("ref/resource"),uri:b()});var AR=I({type:z("ref/prompt"),name:b()}),CR=it.extend({ref:me([AR,IR]),argument:I({name:b(),value:b()}),context:I({arguments:be(b(),b()).optional()}).optional()}),DR=Ce.extend({method:z("completion/complete"),params:CR});var zR=De.extend({completion:He({values:Q(b()).max(100),total:xe(ce().int()),hasMore:xe(Re())})}),OR=I({uri:b().startsWith("file://"),name:b().optional(),_meta:be(b(),_e()).optional()}),MR=Ce.extend({method:z("roots/list"),params:it.optional()}),Rl=De.extend({roots:Q(OR)}),NR=mt.extend({method:z("notifications/roots/list_changed"),params:ft.optional()}),Hq=me([Qi,yl,DR,Pl,qE,FE,$E,PE,RE,DE,OE,ls,kl,ta,na,oa,ia]),Kq=me([Xi,ea,vl,NR,cs]),Gq=me([Yi,Tl,El,ca,Rl,ra,sa,Vn]),Jq=me([Qi,dR,TR,MR,ta,na,oa,ia]),Yq=me([Xi,ea,nR,NE,AE,eR,GE,cs,RR]),Xq=me([Yi,yE,zR,KE,ZE,kE,TE,IE,aa,XE,ra,sa,Vn]),W=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===ee.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new dl(o.elicitations,r)}return new t(e,r,n)}},dl=class extends W{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(ee.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function yr(t){return t==="completed"||t==="failed"||t==="cancelled"}var $v=Symbol("Let zodToJsonSchema decide on which parser to use");var Sv={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"},kv=t=>typeof t=="string"?{...Sv,name:t}:{...Sv,...t};var Pv=t=>{let e=kv(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Il(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function te(t,e,r,n,o){t[e]=r,Il(t,e,n,o)}var ua=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?ua(e,t.currentPath):e.join("/")}}function Tv(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==k.ZodAny&&(r.items=L(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&te(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&te(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(te(r,"minItems",t.exactLength.value,t.exactLength.message,e),te(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function Ev(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?te(r,"minimum",n.value,n.message,e):te(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),te(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?te(r,"maximum",n.value,n.message,e):te(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),te(r,"maximum",n.value,n.message,e));break;case"multipleOf":te(r,"multipleOf",n.value,n.message,e);break}return r}function Rv(){return{type:"boolean"}}function la(t,e){return L(t.type._def,e)}var Iv=(t,e)=>L(t.innerType._def,e);function Al(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Al(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return jR(t,e)}}var jR=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":te(r,"minimum",n.value,n.message,e);break;case"max":te(r,"maximum",n.value,n.message,e);break}return r};function Av(t,e){return{...L(t.innerType._def,e),default:t.defaultValue()}}function Cv(t,e){return e.effectStrategy==="input"?L(t.schema._def,e):we(e)}function Dv(t){return{type:"string",enum:Array.from(t.values)}}var LR=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function zv(t,e){let r=[L(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),L(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(LR(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function Ov(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Cl,xt={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:()=>(Cl===void 0&&(Cl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Cl),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 da(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":te(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":te(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":St(r,"email",n.message,e);break;case"format:idn-email":St(r,"idn-email",n.message,e);break;case"pattern:zod":Ke(r,xt.email,n.message,e);break}break;case"url":St(r,"uri",n.message,e);break;case"uuid":St(r,"uuid",n.message,e);break;case"regex":Ke(r,n.regex,n.message,e);break;case"cuid":Ke(r,xt.cuid,n.message,e);break;case"cuid2":Ke(r,xt.cuid2,n.message,e);break;case"startsWith":Ke(r,RegExp(`^${Dl(n.value,e)}`),n.message,e);break;case"endsWith":Ke(r,RegExp(`${Dl(n.value,e)}$`),n.message,e);break;case"datetime":St(r,"date-time",n.message,e);break;case"date":St(r,"date",n.message,e);break;case"time":St(r,"time",n.message,e);break;case"duration":St(r,"duration",n.message,e);break;case"length":te(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),te(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ke(r,RegExp(Dl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&St(r,"ipv4",n.message,e),n.version!=="v4"&&St(r,"ipv6",n.message,e);break}case"base64url":Ke(r,xt.base64url,n.message,e);break;case"jwt":Ke(r,xt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ke(r,xt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ke(r,xt.ipv6Cidr,n.message,e);break}case"emoji":Ke(r,xt.emoji(),n.message,e);break;case"ulid":{Ke(r,xt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{St(r,"binary",n.message,e);break}case"contentEncoding:base64":{te(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ke(r,xt.base64,n.message,e);break}}break}case"nanoid":Ke(r,xt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Dl(t,e){return e.patternStrategy==="escape"?ZR(t):t}var FR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ZR(t){let e="";for(let r=0;r<t.length;r++)FR.has(t[r])||(e+="\\"),e+=t[r];return e}function St(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):te(t,"format",e,r,n)}function Ke(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Mv(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):te(t,"pattern",Mv(e,n),r,n)}function Mv(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
|
|
234
238
|
]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
|
|
235
239
|
]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
|
|
236
240
|
`:`[${n[c]}\r
|
|
237
|
-
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function ua(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===k.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===k.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=ca(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===k.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===k.ZodBranded&&t.keyType._def.type._def.typeName===k.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=aa(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function xv(t,e){if(e.mapStrategy==="record")return ua(t,e);let r=j(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=j(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function Sv(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function $v(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function kv(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ss={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Tv(t,e){if(e.target==="openApi3")return Pv(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ss&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ss[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Pv(t,e)}var Pv=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>j(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function Ev(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:ss[t.innerType._def.typeName],nullable:!0}:{type:[ss[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=j(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=j(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Rv(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",yl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ee(r,"minimum",n.value,n.message,e):ee(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ee(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ee(r,"maximum",n.value,n.message,e):ee(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ee(r,"maximum",n.value,n.message,e));break;case"multipleOf":ee(r,"multipleOf",n.value,n.message,e);break}return r}function Iv(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=_R(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=j(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=vR(t,e);return i!==void 0&&(n.additionalProperties=i),n}function vR(t,e){if(t.catchall._def.typeName!=="ZodNever")return j(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function _R(t){try{return t.isOptional()}catch{return!0}}var Av=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return j(t.innerType._def,e);let r=j(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var Cv=(t,e)=>{if(e.pipeStrategy==="input")return j(t.in._def,e);if(e.pipeStrategy==="output")return j(t.out._def,e);let r=j(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=j(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Dv(t,e){return j(t.type._def,e)}function zv(t,e){let n={type:"array",uniqueItems:!0,items:j(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ee(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ee(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Ov(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>j(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:j(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>j(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Mv(t){return{not:we(t)}}function Nv(t){return we(t)}var jv=(t,e)=>j(t.innerType._def,e);var Lv=(t,e,r)=>{switch(e){case k.ZodString:return ca(t,r);case k.ZodNumber:return Rv(t,r);case k.ZodObject:return Iv(t,r);case k.ZodBigInt:return fv(t,r);case k.ZodBoolean:return mv();case k.ZodDate:return vl(t,r);case k.ZodUndefined:return Mv(r);case k.ZodNull:return kv(r);case k.ZodArray:return pv(t,r);case k.ZodUnion:case k.ZodDiscriminatedUnion:return Tv(t,r);case k.ZodIntersection:return _v(t,r);case k.ZodTuple:return Ov(t,r);case k.ZodRecord:return ua(t,r);case k.ZodLiteral:return bv(t,r);case k.ZodEnum:return vv(t);case k.ZodNativeEnum:return Sv(t);case k.ZodNullable:return Ev(t,r);case k.ZodOptional:return Av(t,r);case k.ZodMap:return xv(t,r);case k.ZodSet:return zv(t,r);case k.ZodLazy:return()=>t.getter()._def;case k.ZodPromise:return Dv(t,r);case k.ZodNaN:case k.ZodNever:return $v(r);case k.ZodEffects:return yv(t,r);case k.ZodAny:return we(r);case k.ZodUnknown:return Nv(r);case k.ZodDefault:return gv(t,r);case k.ZodBranded:return aa(t,r);case k.ZodReadonly:return jv(t,r);case k.ZodCatch:return hv(t,r);case k.ZodPipeline:return Cv(t,r);case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:return;default:return(n=>{})(e)}};function j(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==uv)return a}if(n&&!r){let a=bR(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Lv(t,t.typeName,e),i=typeof s=="function"?j(s(),e):s;if(i&&wR(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var bR=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ia(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},wR=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var la=(t,e)=>{let r=dv(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:j(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??we(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=j(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??we(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function wl(t){let r=Ui(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=$y(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function xl(t,e){let r=lr(t,e);if(!r.success)throw r.error;return r.data}var xR=6e4,da=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Gi,r=>{this._oncancel(r)}),this.setNotificationHandler(Yi,r=>{this._onprogress(r)}),this.setRequestHandler(Ji,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Qi,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(X.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ea,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new W(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new W(X.InvalidParams,`Task not found: ${s}`);if(!pr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(pr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[dr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ta,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new W(X.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(na,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(X.InvalidParams,`Task not found: ${r.params.taskId}`);if(pr(o.status))throw new W(X.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new W(X.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof W?o:new W(X.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),W.fromError(X.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Jo(s)||Xy(s)?this._onresponse(s):tl(s)?this._onrequest(s,i):Qy(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=W.fromError(X.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[dr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:X.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Gy(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:X.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Jo(e))n(e);else{let i=new W(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Jo(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Jo(e))o(e);else{let i=W.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof W?i:new W(X.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Ln,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new W(X.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},pr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new W(X.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new W(X.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof W?i:new W(X.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=x=>{l(x)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(x){d(x);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[dr]:c}});let m=x=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(x)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let v=x instanceof W?x:new W(X.RequestTimeout,String(x));l(v)};this._responseHandlers.set(p,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return l(x);try{let v=lr(r,x.result);v.success?u(v.data):l(v.error)}catch(v){l(v)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let g=n?.timeout??xR,y=()=>m(W.fromError(X.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let x=v=>{let P=this._responseHandlers.get(p);P?P(v):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,x),this._enqueueTaskMessage(_,{type:"request",message:f,timestamp:Date.now()}).catch(v=>{this._cleanupTimeout(p),l(v)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(x=>{this._cleanupTimeout(p),l(x)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Xi,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},ra,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},rv,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[dr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[dr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[dr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=wl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=xl(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=wl(e);this._notificationHandlers.set(n,o=>{let s=xl(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&tl(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new W(X.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new W(X.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new W(X.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new W(X.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=ts.parse({method:"notifications/tasks/status",params:a});await this.notification(c),pr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new W(X.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(pr(a.status))throw new W(X.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=ts.parse({method:"notifications/tasks/status",params:c});await this.notification(u),pr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Fv(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Zv(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];Fv(i)&&Fv(s)?r[o]={...i,...s}:r[o]=s}return r}var Tw=Jp(ap(),1),Ew=Jp(Pw(),1);function pO(){let t=new Tw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ew.default)(t),t}var Ka=class{constructor(e){this._ajv=e??pO()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Ga=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Rw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Iw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Ja=class extends da{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(os.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ka,this.setRequestHandler(ol,n=>this._oninitialize(n)),this.setNotificationHandler(sl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(fl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=os.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ga(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Zv(this._capabilities,e)}setRequestHandler(e,r){let o=Ui(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Nn(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=lr(ns,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new W(X.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=lr(Ln,p);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new W(X.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let f=lr(oa,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new W(X.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Iw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Rw(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Wy.includes(r)?r:Xu,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Ki)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},hl,r):this.request({method:"sampling/createMessage",params:e},ml,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},sa,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},sa,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new W(X.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof W?i:new W(X.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},gl,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import Cw from"node:process";var Ya=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
238
|
-
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
239
|
-
`}var
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
**
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
${
|
|
241
|
+
]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function pa(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===k.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===k.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=da(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===k.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===k.ZodBranded&&t.keyType._def.type._def.typeName===k.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=la(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function Nv(t,e){if(e.mapStrategy==="record")return pa(t,e);let r=L(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function jv(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function Lv(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}function Fv(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ps={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Uv(t,e){if(e.target==="openApi3")return Zv(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ps&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ps[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return Zv(t,e)}var Zv=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>L(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function qv(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:ps[t.innerType._def.typeName],nullable:!0}:{type:[ps[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=L(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=L(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function Vv(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Il(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?te(r,"minimum",n.value,n.message,e):te(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),te(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?te(r,"maximum",n.value,n.message,e):te(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),te(r,"maximum",n.value,n.message,e));break;case"multipleOf":te(r,"multipleOf",n.value,n.message,e);break}return r}function Bv(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=qR(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=L(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=UR(t,e);return i!==void 0&&(n.additionalProperties=i),n}function UR(t,e){if(t.catchall._def.typeName!=="ZodNever")return L(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function qR(t){try{return t.isOptional()}catch{return!0}}var Wv=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return L(t.innerType._def,e);let r=L(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)};var Hv=(t,e)=>{if(e.pipeStrategy==="input")return L(t.in._def,e);if(e.pipeStrategy==="output")return L(t.out._def,e);let r=L(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=L(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function Kv(t,e){return L(t.type._def,e)}function Gv(t,e){let n={type:"array",uniqueItems:!0,items:L(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&te(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&te(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function Jv(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>L(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:L(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>L(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function Yv(t){return{not:we(t)}}function Xv(t){return we(t)}var Qv=(t,e)=>L(t.innerType._def,e);var e_=(t,e,r)=>{switch(e){case k.ZodString:return da(t,r);case k.ZodNumber:return Vv(t,r);case k.ZodObject:return Bv(t,r);case k.ZodBigInt:return Ev(t,r);case k.ZodBoolean:return Rv();case k.ZodDate:return Al(t,r);case k.ZodUndefined:return Yv(r);case k.ZodNull:return Fv(r);case k.ZodArray:return Tv(t,r);case k.ZodUnion:case k.ZodDiscriminatedUnion:return Uv(t,r);case k.ZodIntersection:return zv(t,r);case k.ZodTuple:return Jv(t,r);case k.ZodRecord:return pa(t,r);case k.ZodLiteral:return Ov(t,r);case k.ZodEnum:return Dv(t);case k.ZodNativeEnum:return jv(t);case k.ZodNullable:return qv(t,r);case k.ZodOptional:return Wv(t,r);case k.ZodMap:return Nv(t,r);case k.ZodSet:return Gv(t,r);case k.ZodLazy:return()=>t.getter()._def;case k.ZodPromise:return Kv(t,r);case k.ZodNaN:case k.ZodNever:return Lv(r);case k.ZodEffects:return Cv(t,r);case k.ZodAny:return we(r);case k.ZodUnknown:return Xv(r);case k.ZodDefault:return Av(t,r);case k.ZodBranded:return la(t,r);case k.ZodReadonly:return Qv(t,r);case k.ZodCatch:return Iv(t,r);case k.ZodPipeline:return Hv(t,r);case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:return;default:return(n=>{})(e)}};function L(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==$v)return a}if(n&&!r){let a=VR(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=e_(t,t.typeName,e),i=typeof s=="function"?L(s(),e):s;if(i&&BR(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var VR=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ua(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},BR=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var fa=(t,e)=>{let r=Pv(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:L(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??we(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=L(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??we(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function zl(t){let r=Bi(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ly(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ol(t,e){let r=hr(t,e);if(!r.success)throw r.error;return r.data}var WR=6e4,ma=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Xi,r=>{this._oncancel(r)}),this.setNotificationHandler(ea,r=>{this._onprogress(r)}),this.setRequestHandler(Qi,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ta,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(ee.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(na,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new W(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new W(ee.InvalidParams,`Task not found: ${s}`);if(!yr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(yr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[gr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(oa,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new W(ee.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ia,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new W(ee.InvalidParams,`Task not found: ${r.params.taskId}`);if(yr(o.status))throw new W(ee.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new W(ee.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof W?o:new W(ee.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),W.fromError(ee.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),ns(s)||mv(s)?this._onresponse(s):ml(s)?this._onrequest(s,i):fv(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();let r=W.fromError(ee.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[gr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:ee.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=lv(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:ee.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ns(e))n(e);else{let i=new W(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(ns(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),ns(e))o(e);else{let i=W.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof W?i:new W(ee.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Vn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new W(ee.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},yr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new W(ee.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new W(ee.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof W?i:new W(ee.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=S=>{l(S)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(S){d(S);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[gr]:c}});let m=S=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(S)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>this._onerror(new Error(`Failed to send cancellation: ${_}`)));let w=S instanceof W?S:new W(ee.RequestTimeout,String(S));l(w)};this._responseHandlers.set(p,S=>{if(!n?.signal?.aborted){if(S instanceof Error)return l(S);try{let w=hr(r,S.result);w.success?u(w.data):l(w.error)}catch(w){l(w)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let g=n?.timeout??WR,y=()=>m(W.fromError(ee.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(p,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let S=w=>{let _=this._responseHandlers.get(p);_?_(w):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,S),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(w=>{this._cleanupTimeout(p),l(w)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(S=>{this._cleanupTimeout(p),l(S)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},ra,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},sa,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},yv,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[gr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[gr]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[gr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=zl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Ol(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=zl(e);this._notificationHandlers.set(n,o=>{let s=Ol(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&ml(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new W(ee.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new W(ee.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new W(ee.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new W(ee.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=cs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),yr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new W(ee.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(yr(a.status))throw new W(ee.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=cs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),yr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function t_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function r_(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];t_(i)&&t_(s)?r[o]={...i,...s}:r[o]=s}return r}var Uw=df(bp(),1),qw=df(Zw(),1);function MO(){let t=new Uw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,qw.default)(t),t}var Ya=class{constructor(e){this._ajv=e??MO()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var Xa=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Vw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Bw(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Qa=class extends ma{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ds.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ya,this.setRequestHandler(yl,n=>this._oninitialize(n)),this.setNotificationHandler(vl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Pl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ds.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Xa(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=r_(this._capabilities,e)}setRequestHandler(e,r){let o=Bi(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Un(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=hr(ls,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new W(ee.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=hr(Vn,p);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new W(ee.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let f=hr(aa,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new W(ee.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Bw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Vw(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:av.includes(r)?r:pl,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Yi)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},El,r):this.request({method:"sampling/createMessage",params:e},Tl,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},ca,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},ca,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new W(ee.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof W?i:new W(ee.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Rl,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import Hw from"node:process";var ec=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
242
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),NO(r)}clear(){this._buffer=void 0}};function NO(t){return hv.parse(JSON.parse(t))}function Ww(t){return JSON.stringify(t)+`
|
|
243
|
+
`}var tc=class{constructor(e=Hw.stdin,r=Hw.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new ec,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Ww(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{fileURLToPath as Pj}from"url";var Ep={};Be(Ep,{AI_CHAT_TIMEOUT_MS:()=>Xw,getTools:()=>ZO,handleTool:()=>BO});import{readFileSync as Kw}from"fs";import{join as jO}from"path";import{randomUUID as LO}from"crypto";function V(t){let e=fa(t,{target:"jsonSchema7"});return delete e.$schema,delete e.additionalProperties,e.type==="object"&&!e.required&&(e.required=[]),e}var FO=h.object({title:h.string().describe("Document title"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' (per-provider initial analysis) \u2192 individual/, 'debate' (round-by-round working docs) \u2192 debates/, 'synthesis' (final consensus) \u2192 synthesis/, 'general' (default, legacy) \u2192 reviews/.")}).optional(),Gw=h.object({provider:h.string().describe("Provider ID (e.g. 'ollama', 'gemini', 'codex', 'claude')"),prompt:h.string().describe("Chat prompt to send"),model:h.string().optional().describe("Model override"),system:h.string().optional().describe("System prompt"),files:h.array(h.string()).optional().describe("File paths to include as context"),allow_external_paths:h.boolean().optional().describe("Opt-in: allow absolute file paths outside the workspace base directory. Default false. Relative paths remain sandboxed either way. Audit trail is the call log \u2014 use sparingly."),save_as_document:FO.describe("If provided, automatically save the response as a workspace document with the given title and metadata. Returns document ID in the result.")}),Jw=h.object({provider:h.string().describe("Provider ID"),file_paths:h.array(h.string()).min(1).describe("File paths to analyze"),question:h.string().describe("Question to ask about the files"),save_to_file:h.string().optional().describe("Path to save the analysis result"),allow_external_paths:h.boolean().optional().describe("Opt-in: allow absolute file paths outside the workspace base directory. Default false.")}),Yw=h.object({providers:h.array(h.string()).min(1).describe("List of provider IDs to compare"),prompt:h.string().describe("Prompt to send to all providers"),aggregate_provider:h.string().optional().describe("Provider ID to synthesize all responses into a unified document. If omitted, returns raw comparisons only."),aggregate_prompt:h.string().optional().describe("Custom synthesis prompt. Default: synthesize and identify agreements/disagreements.")}),Xw=9e4;function Qw(t,e,r){let n=`${r.tool}-${Date.now()}-${LO().slice(0,8)}`,o=jO(t,".agestra","pending-saves",`${n}.md`),s=[["id",n],["tool",r.tool],["provider",e.provider],["model",e.model],["created_at",new Date().toISOString()]];if(r.title&&s.push(["title",r.title]),r.originalTarget&&s.push(["original_target",r.originalTarget]),r.extraMetadata)for(let[a,c]of Object.entries(r.extraMetadata))c!=null&&c!==""&&s.push([a,c]);let i=["---",...s.map(([a,c])=>`${a}: ${JSON.stringify(c)}`),"---",""].join(`
|
|
244
|
+
`);return oe(o,i+`
|
|
245
|
+
`+e.text),o}function ZO(){return[{name:"ai_chat",title:"AI Chat",description:"Chat with a specific AI provider. Sends a prompt and returns the response. Optionally saves the response as a workspace document.",inputSchema:V(Gw)},{name:"ai_analyze_files",title:"Analyze Files with AI",description:"Analyze files with an AI provider. Reads files from disk, sends contents with a question, and optionally saves the result.",inputSchema:V(Jw)},{name:"ai_compare",title:"Compare AI Providers",description:"Send the same prompt to multiple providers and return a comparison. Optionally aggregate results into a unified synthesis using a designated provider.",inputSchema:V(Yw)}]}async function UO(t,e){let r=Gw.parse(t),n=e.workspaceBaseDir??process.cwd(),o=e.qualityStatsProvider??e.traceWriter,s=r.provider==="auto"?e.registry.getBestForTask("chat",o)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!s)throw new Error("No providers available for auto-routing");let i=r.allow_external_paths?tu:Yt,a=e.aiChatTimeoutMs??Xw,c=new AbortController,u=!1,l,d=s.chat({prompt:r.prompt,model:r.model,system:r.system,workspaceBaseDir:n,signal:c.signal,files:r.files?.map(g=>{let y=i(g,n);return{path:y,content:Kw(y,"utf-8")}})});d.catch(()=>{});let p;try{p=await Promise.race([d,new Promise((g,y)=>{l=setTimeout(()=>{u=!0,c.abort(new Error("__AI_CHAT_TIMEOUT__")),y(new Error("__AI_CHAT_TIMEOUT__"))},a)})])}catch(g){if(u&&e.jobManager){let y=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:3e5,saveAsDocument:r.save_as_document}),v=r.save_as_document?`
|
|
246
|
+
**Save on complete:** ${r.save_as_document.title}`:"";return{content:[{type:"text",text:`\u23F1 Provider "${r.provider}" timed out after ${a/1e3}s. Auto-submitted as background job.
|
|
247
|
+
|
|
248
|
+
**Job ID:** ${y}${v}
|
|
249
|
+
|
|
250
|
+
Use \`cli_job_status\` to check progress.`}]}}throw g}finally{l!==void 0&&clearTimeout(l)}let f="",m=!1;if(r.save_as_document&&e.documentManager)try{f=`
|
|
251
|
+
**Document ID:** ${(await e.documentManager.createDocument({title:r.save_as_document.title,content:p.text,metadata:{...r.save_as_document.metadata,Provider:p.provider,Model:p.model},kind:r.save_as_document.kind})).id}`}catch(g){m=!0;let y=M(g);try{let v=Qw(n,p,{tool:"ai_chat",title:r.save_as_document.title,extraMetadata:{kind:r.save_as_document.kind,...r.save_as_document.metadata}});f=`
|
|
252
|
+
\u26A0 Document save failed: ${y}
|
|
253
|
+
**Pending save:** ${v}`}catch(v){f=`
|
|
254
|
+
\u26A0 Document save failed: ${y}
|
|
255
|
+
\u26A0 Pending-save dump also failed: ${M(v)}`}}return{content:[{type:"text",text:`**Provider:** ${p.provider}
|
|
256
|
+
**Model:** ${p.model}${f}
|
|
257
|
+
|
|
258
|
+
${p.text}`}],...m?{isError:!0}:{}}}async function qO(t,e){let r=Jw.parse(t),n=e.workspaceBaseDir??process.cwd(),o=e.qualityStatsProvider??e.traceWriter,s=r.provider==="auto"?e.registry.getBestForTask("analysis",o)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!s)throw new Error("No providers available for auto-routing");let i=r.allow_external_paths?tu:Yt,c=`${r.file_paths.map(p=>{let f=i(p,n),m=Kw(f,"utf-8");return`--- ${f} ---
|
|
259
|
+
${m}`}).join(`
|
|
250
260
|
|
|
251
261
|
`)}
|
|
252
262
|
|
|
253
263
|
---
|
|
254
264
|
|
|
255
|
-
Question: ${r.question}`,
|
|
265
|
+
Question: ${r.question}`,u=await s.chat({prompt:c,workspaceBaseDir:n}),l="",d=!1;if(r.save_to_file)try{let p=dt(r.save_to_file,n);oe(p,u.text),l=`
|
|
266
|
+
|
|
267
|
+
_Result saved to: ${r.save_to_file}_`}catch(p){d=!0;let f=M(p);try{let m=Qw(n,u,{tool:"ai_analyze_files",originalTarget:r.save_to_file,extraMetadata:{question:r.question,file_paths:r.file_paths.join(", ")}});l=`
|
|
268
|
+
|
|
269
|
+
\u26A0 Save to ${r.save_to_file} failed: ${f}
|
|
270
|
+
**Pending save:** ${m}`}catch(m){l=`
|
|
256
271
|
|
|
257
|
-
|
|
272
|
+
\u26A0 Save to ${r.save_to_file} failed: ${f}
|
|
273
|
+
\u26A0 Pending-save dump also failed: ${M(m)}`}}return{content:[{type:"text",text:`**Provider:** ${u.provider}
|
|
258
274
|
**Files analyzed:** ${r.file_paths.join(", ")}
|
|
259
275
|
|
|
260
|
-
${
|
|
276
|
+
${u.text}${l}`}],...d?{isError:!0}:{}}}async function VO(t,e){let r=Yw.parse(t),n=r.providers.map(c=>e.registry.get(c)),o=await Promise.all(n.map(async c=>{try{let u=await c.chat({prompt:r.prompt});return{provider:c.id,text:u.text,error:null}}catch(u){return{provider:c.id,text:null,error:M(u)}}})),s=`# Comparison
|
|
261
277
|
|
|
262
278
|
**Prompt:** ${r.prompt}
|
|
263
279
|
|
|
@@ -272,48 +288,48 @@ ${c.text}${u}`}]}}async function vO(t,e){let r=Mw.parse(t),n=r.providers.map(c=>
|
|
|
272
288
|
|
|
273
289
|
---
|
|
274
290
|
|
|
275
|
-
${s}`;try{i=(await c.chat({prompt:d})).text}catch(p){i=`[Aggregation failed: ${
|
|
291
|
+
${s}`;try{i=(await c.chat({prompt:d})).text}catch(p){i=`[Aggregation failed: ${M(p)}]`}}}let a=s;return i&&(a+=`---
|
|
276
292
|
|
|
277
293
|
# Synthesis
|
|
278
294
|
|
|
279
|
-
${i}`),{content:[{type:"text",text:a}]}}async function
|
|
295
|
+
${i}`),{content:[{type:"text",text:a}]}}async function BO(t,e,r){switch(t){case"ai_chat":return UO(e,r);case"ai_analyze_files":return qO(e,r);case"ai_compare":return VO(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var qp={};Be(qp,{getTools:()=>Rp,handleTool:()=>tS});var rc=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate"),max_rounds:h.number().int().positive().optional().default(3).describe("Maximum debate rounds"),goal:h.string().optional().describe("Quality goal for enhanced debate mode (enables quality validation loop)"),validator:h.string().optional().describe("Provider ID for quality validation (agent-tier recommended)"),min_rounds:h.number().int().positive().optional().default(2).describe("Minimum rounds before validation (default: 2)")}),nc=h.object({items:h.array(h.object({provider:h.string().describe("Provider that produced the content"),content:h.string().describe("Content to validate"),task:h.string().describe("Original task description")})).min(1).describe("Items to cross-validate"),validators:h.array(h.string()).optional().describe("Provider IDs to use as validators (agent-tier only)"),criteria:h.string().optional().describe("Custom validation criteria")}),oc=h.object({session_id:h.string().describe("Session ID to check")}),sc=h.object({topic:h.string().describe("Topic for the debate"),providers:h.array(h.string()).min(1).describe("Provider IDs to participate"),goal:h.string().optional().describe("Quality goal for the debate"),save_document:h.boolean().optional().default(!0).describe("Save debate as a workspace document (default: true)")}),ic=h.object({debate_id:h.string().describe("Debate session ID"),provider:h.string().describe(`Provider ID to take this turn. Use "claude" to record Claude's own opinion as an independent turn (requires claude_comment).`),claude_comment:h.string().optional().describe(`Claude's opinion. When provider is "claude", this becomes the turn content. Otherwise, injected before the provider responds.`),auto_specialist:h.boolean().optional().default(!1).describe("When true with provider 'claude', automatically select and record a specialist agent recommendation based on the debate topic.")}),ac=h.object({debate_id:h.string().describe("Debate session ID to conclude"),summary:h.string().optional().describe("Claude's final summary of the debate"),quality_scores:h.array(h.object({provider:h.string(),score:h.number().min(0).max(1),feedback:h.string()})).optional().describe("Quality assessment of each provider's contribution")}),cc=h.object({document:h.string().describe("Document content to review"),providers:h.array(h.string()).min(1).describe("Provider IDs to review the document"),review_prompt:h.string().optional().describe("Custom review instructions (default: agree/disagree with feedback)"),debate_id:h.string().optional().describe("Link reviews to an existing debate session's workspace document")}),uc=h.object({task_id:h.string().describe("Task ID to review changes for")}),lc=h.object({task_id:h.string().describe("Task ID whose changes to accept"),message:h.string().optional().describe("Commit message for the merge")}),dc=h.object({task_id:h.string().describe("Task ID whose changes to reject"),reason:h.string().optional().describe("Reason for rejection")}),ex=h.object({agrees:h.union([h.boolean(),h.enum(["true","false"])]).transform(t=>typeof t=="boolean"?t:t==="true"),feedback:h.string().optional().default(""),suggestions:h.string().optional()}),pc=h.object({topic:h.string().min(1).describe("Topic for the structured debate"),scope:h.string().optional().describe("What the leader wants debated (file list or task framing). Defaults to topic when omitted."),goal:h.string().optional().describe("Optional quality goal for the debate"),leader:h.string().optional().describe("Participant ID authorized to approve the final synthesis. Defaults to the session-context leader or the first participant."),participants:h.array(h.string()).min(1).describe("Participant IDs. When `auto_inject_specialists` is true (default), `claude-reviewer` and/or `claude-qa` may be added based on the topic."),exclude_participants:h.array(h.string()).optional().describe("Participant IDs to never inject/include. Applied regardless of `auto_inject_specialists`."),auto_inject_specialists:h.boolean().optional().default(!0).describe("When true (default), topic-matching Claude specialists are added to `participants` honoring `exclude_participants`. When false, `participants` is used verbatim."),max_rounds:h.number().int().positive().max(50).optional().describe("Maximum number of rounds. Default: STRUCTURED_DEBATE_DEFAULT_MAX_ROUNDS."),individual_review_prompt:h.string().optional().describe("Override the system prompt used for individual-review fan-out."),files:h.array(h.string()).optional().describe("Optional list of files to pass to participants as context."),locale:h.enum(["ko","zh","ja","en"]).optional().describe("Override config locale for moderator text in this debate only.")}),fc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),leader_note:h.string().optional().describe("Optional note appended to the synthesis footer under 'Leader approval notes'.")}),mc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),additional_rounds:h.union([h.literal(3),h.literal(5),h.literal(10)]).describe("How many extra rounds to run beyond the current round count. Choose one of 3, 5, or 10.")}),hc=h.object({session_id:h.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),reason:h.string().optional().describe("Optional rejection reason, captured in the debate transcript footer."),spawn_issue:h.boolean().optional().default(!1).describe("If true, write an issue_{sessionIdShort}_{YYYYMMDD}_{seq}.md under individual/ listing all non-accepted proposals (rejected/withdrawn/open/inconclusive/superseded). Default false.")});var gc="agent_debate_structured",co="agent_debate_approve",uo="agent_debate_continue",lo="agent_debate_reject";function yc(t){return t.moderatorEngine?t.structuredSessionRegistry?null:{content:[{type:"text",text:"Structured session registry is not initialized for this workspace."}],isError:!0}:{content:[{type:"text",text:"Structured debate engine is not initialized for this workspace. Check MCP server wiring."}],isError:!0}}async function tx(t,e){let r=yc(e);if(r)return r;let n;try{n=pc.parse(t)}catch(s){return sr(`Invalid arguments: ${M(s)}`)}let o=WO(n.leader,n.participants,e);if(!o)return sr("Cannot resolve a leader. Provide `leader` explicitly or ensure the session context exposes one.");try{let s=await e.moderatorEngine.startDebate({topic:n.topic,...n.scope!==void 0?{scope:n.scope}:{},...n.goal!==void 0?{goal:n.goal}:{},leader:o,participants:n.participants,...n.exclude_participants!==void 0?{excludeParticipants:n.exclude_participants}:{},...n.auto_inject_specialists!==void 0?{autoInjectSpecialists:n.auto_inject_specialists}:{},...n.max_rounds!==void 0?{maxRounds:n.max_rounds}:{},...n.locale!==void 0?{locale:n.locale}:{},...n.individual_review_prompt!==void 0?{individualReviewPrompt:n.individual_review_prompt}:{},...n.files!==void 0?{files:n.files}:{}}),i=[s.terminalReport];return i.push(sx(s.sessionId,s.snapshot.status)),s.snapshot.status==="escalated"?i.push(ax(s.sessionId)):s.snapshot.status==="ready-for-approval"?i.push(ix(s.sessionId)):s.snapshot.status==="error"&&i.push(`Engine reported an error: ${s.errorMessage??"(no message)"}.`),{content:[{type:"text",text:i.filter(Boolean).join(`
|
|
280
296
|
|
|
281
|
-
`)}],...s.snapshot.status==="error"?{isError:!0}:{}}}catch(s){return
|
|
297
|
+
`)}],...s.snapshot.status==="error"?{isError:!0}:{}}}catch(s){return sr(`Failed to start structured debate: ${M(s)}`)}}async function rx(t,e){let r=yc(e);if(r)return r;let n;try{n=fc.parse(t)}catch(o){return sr(`Invalid arguments: ${M(o)}`)}try{let o=await e.moderatorEngine.approve({sessionId:n.session_id,...n.leader_note!==void 0?{leaderNote:n.leader_note}:{}}),s=[o.terminalReport];return s.push(`Synthesis document: ${o.synthesisPath}`),s.push(`Status: ${o.snapshot.status} (session ${n.session_id})`),o.idempotentReplay&&s.push("(idempotent replay of existing approved state \u2014 no new synthesis written)"),{content:[{type:"text",text:s.join(`
|
|
282
298
|
|
|
283
|
-
`)}]}}catch(o){return
|
|
299
|
+
`)}]}}catch(o){return sr(`Approve failed: ${M(o)}`)}}async function nx(t,e){let r=yc(e);if(r)return r;let n;try{n=mc.parse(t)}catch(o){return sr(`Invalid arguments: ${M(o)}`)}try{let o=await e.moderatorEngine.continueDebate({sessionId:n.session_id,additionalRounds:n.additional_rounds}),s=[o.terminalReport];return s.push(sx(n.session_id,o.snapshot.status)),o.snapshot.status==="escalated"?s.push(ax(n.session_id)):o.snapshot.status==="ready-for-approval"&&s.push(ix(n.session_id)),{content:[{type:"text",text:s.join(`
|
|
284
300
|
|
|
285
|
-
`)}]}}catch(o){return
|
|
286
|
-
`)}]}}catch(o){return
|
|
287
|
-
`)}function
|
|
288
|
-
`)}function
|
|
301
|
+
`)}]}}catch(o){return sr(`Continue failed: ${M(o)}`)}}async function ox(t,e){let r=yc(e);if(r)return r;let n;try{n=hc.parse(t)}catch(o){return sr(`Invalid arguments: ${M(o)}`)}try{let o=await e.moderatorEngine.reject({sessionId:n.session_id,...n.reason!==void 0?{reason:n.reason}:{},...n.spawn_issue!==void 0?{spawnIssue:n.spawn_issue}:{}}),s=o.snapshot.documentPaths.debate,i=[`Structured debate session ${n.session_id} rejected.`];return n.reason&&i.push(`Reason: ${n.reason}`),i.push(`Transcript: ${s}`),o.issuePath&&i.push(`Issue document: ${o.issuePath}`),o.idempotentReplay&&i.push("(idempotent replay of existing rejected state \u2014 no new artifacts written)"),{content:[{type:"text",text:i.join(`
|
|
302
|
+
`)}]}}catch(o){return sr(`Reject failed: ${M(o)}`)}}function WO(t,e,r){if(t&&t.length>0)return t;let n=r.sessionContext?.leaderProviderId;return n&&e.includes(n)||n?n:e[0]}function sx(t,e){return`Session ID: ${t} \u2014 status: ${e}`}function ix(t){return["Next step \u2014 choose one:",`- Approve synthesis: call \`${co}\` with { session_id: "${t}" }`,`- Extend debate: call \`${uo}\` with { session_id: "${t}", additional_rounds: 3 | 5 | 10 }`,`- Abandon session: call \`${lo}\` with { session_id: "${t}" }`].join(`
|
|
303
|
+
`)}function ax(t){return["Debate escalated \u2014 max rounds exhausted with open proposals.","The leader should choose one of:",`- \`${uo}\` with additional_rounds = 3 | 5 | 10 to run more rounds.`,`- \`${co}\` to accept the current synthesis with open items captured.`,`- \`${lo}\` to abandon the session.`,`Session ID: ${t}`].join(`
|
|
304
|
+
`)}function sr(t){return{content:[{type:"text",text:t}],isError:!0}}function Rp(){return[{name:"agent_debate_start",title:"Start AI Debate",description:"Start a multi-provider debate on a topic. Optionally enable enhanced mode with goal-based quality validation.",inputSchema:V(rc)},{name:"agent_debate_status",title:"Check Debate Status",description:"Check the status and result of a debate session.",inputSchema:V(oc)},{name:"agent_cross_validate",title:"Cross-Validate Outputs",description:"Cross-validate work outputs. Each item is reviewed by agent-tier providers. Tool-tier providers cannot be validators.",inputSchema:V(nc)},{name:"agent_debate_create",title:"Create Turn-Based Debate",description:"Create a turn-based debate session. Returns a debate ID for use with agent_debate_turn and agent_debate_conclude.",inputSchema:V(sc)},{name:"agent_debate_turn",title:"Execute Debate Turn",description:`Execute one provider's turn in a debate. Optionally inject Claude's comment before the provider responds. Returns the provider's response. Use provider: "claude" with claude_comment to record Claude's own independent opinion as a debate turn.`,inputSchema:V(ic)},{name:"agent_debate_conclude",title:"Conclude Debate",description:"End a debate session and generate the final transcript. Optionally add Claude's summary and quality scores for each provider.",inputSchema:V(ac)},{name:"agent_debate_review",title:"Review Document with Providers",description:"Send a document to multiple providers for structured review. Each provider responds with agree/disagree and feedback. Use iteratively: review \u2192 revise document based on feedback \u2192 review again until all agree.",inputSchema:V(cc)},{name:"agent_changes_review",title:"Review File Changes",description:"Review file changes made by an external AI in an isolated worktree. Shows diff stat and full diff.",inputSchema:V(uc)},{name:"agent_changes_accept",title:"Accept File Changes",description:"Accept and merge file changes from an isolated worktree back to the main branch.",inputSchema:V(lc)},{name:"agent_changes_reject",title:"Reject File Changes",description:"Reject file changes and clean up the isolated worktree.",inputSchema:V(dc)},{name:gc,title:"Start Structured Debate",description:"Start a structured, approval-gated debate. Each participant submits an individual review, then rounds run until consensus or max rounds. Output is a ready-for-approval session \u2014 call agent_debate_approve/continue/reject to finalize. No synthesis is written until approved.",inputSchema:V(pc)},{name:co,title:"Approve Structured Debate",description:"Leader-approve a ready-for-approval structured-debate session. Writes the synthesis document and marks the session approved.",inputSchema:V(fc)},{name:uo,title:"Continue Structured Debate",description:"Run additional rounds on a ready-for-approval (or escalated) structured-debate session. Choose 3, 5, or 10 extra rounds.",inputSchema:V(mc)},{name:lo,title:"Reject Structured Debate",description:"Reject a ready-for-approval (or escalated/leader-timeout) structured-debate session. Transcript is marked rejected; no synthesis is written.",inputSchema:V(hc)}]}import{join as dN}from"path";import{readFileSync as KO}from"fs";import{join as fx}from"path";function cx(t,e){let r=`${t} ${e??""}`.toLowerCase(),n=[{patterns:[/\breview\b/,/\bcode\s*quality\b/,/\bsecurity\b/,/\baudit\b/,/리뷰/,/보안/,/코드\s*품질/],agent:"agestra-reviewer"},{patterns:[/\bdesign\b/,/\barchitect/,/\bstructur/,/설계/,/아키텍처/,/구조/],agent:"agestra-designer"},{patterns:[/\bidea\b/,/\bimprov/,/\bcompare\b/,/\balternativ/,/\bbrainstorm/,/개선/,/아이디어/,/비교/,/대안/],agent:"agestra-ideator"},{patterns:[/\bverif/,/\bvalidat/,/\bqa\b/,/\btest\b/,/\bcheck\b/,/검증/,/테스트/,/확인/],agent:"agestra-qa"}];for(let o of n)if(o.patterns.some(s=>s.test(r)))return o.agent;return null}var vc="claude-reviewer",_c="claude-qa",HO={"agestra-reviewer":vc,"agestra-qa":_c};function ux(t){let{topic:e,goal:r,participants:n,excludeParticipants:o,autoInjectSpecialists:s}=t,i=new Set(o),a=n.filter(d=>!i.has(d)),c=cx(e,r),u=c!==null?HO[c]??null:null,l=[];return u===null?{participants:a,skipped:l}:s?i.has(u)?(l.push({participantId:u,reason:"explicitly-excluded"}),{participants:a,skipped:l}):a.includes(u)?(l.push({participantId:u,reason:"already-listed"}),{participants:a,skipped:l}):{participants:[...a,u],skipped:l}:(l.push({participantId:u,reason:"auto-disabled"}),{participants:a,skipped:l})}var Ap="claude",Cp="claude-cli",GO=new Set([vc,_c]),Dp=Object.freeze({[vc]:"agestra-reviewer",[_c]:"agestra-qa"});function JO(t){if(!t.startsWith("---"))return t;let e=t.indexOf(`
|
|
289
305
|
`,3);if(e<0)return t;let r=t.indexOf(`
|
|
290
306
|
---`,e);if(r<0)return t;let n=t.indexOf(`
|
|
291
|
-
`,r+4);return n<0?"":t.slice(n+1)}function kO(t,e){return SO.has(t)?e==="claude-code"?{transport:"task-subagent",agentName:bp[t]}:{transport:"cli-bridge",providerId:_p,agentName:bp[t]}:t===vp?e==="claude-code"?{transport:"read-only-chat",providerId:vp}:{transport:"cli-bridge",providerId:_p}:{transport:"read-only-chat",providerId:t}}function Kw(t){if(!(!t||t.length===0))return t.map(e=>({path:e}))}var Gw=18e4;function yp(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Participant "${e}" stalled (no response after ${Gw/1e3}s)`)),Gw))])}function Jw(t,e,r,n,o){if(e.system!==void 0)return e.system;let s=bp[t];if(s===void 0)return;if(o.has(s))return o.get(s)??void 0;let i=Yw(r,`${s}.md`);try{let a=$O(n(i)).trim(),c=a.length>0?a:null;return o.set(s,c),c??void 0}catch{o.set(s,null);return}}var wp=class{registry;readOnlyAdapter;hostKind;agentsDir;readFile;subagentSpawner;sysPromptCache=new Map;constructor(e){this.registry=e.registry,this.readOnlyAdapter=e.readOnlyAdapter,this.hostKind=e.hostKind,this.agentsDir=e.agentsDir??Yw(process.cwd(),"agents"),this.readFile=e.agentsFileReader??(r=>xO(r,"utf-8")),this.subagentSpawner=e.subagentSpawner}describe(e){return this.resolveDescriptor(e)}async requestTurn(e,r){let n=this.resolveDescriptor(e),o=performance.now();try{switch(n.transport){case"task-subagent":{if(!this.subagentSpawner)return this.buildFailure(e,o,"subagent spawner not wired (integration pending \u2014 T10/T12)");let s=await yp(this.subagentSpawner({agentName:n.agentName??e,prompt:r.prompt,system:r.system}),e);return this.buildSuccess(e,o,s.text)}case"cli-bridge":{let s=n.providerId??_p,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`CLI provider "${s}" not registered`);let a=Jw(e,r,this.agentsDir,this.readFile,this.sysPromptCache),c=await yp(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:Kw(r.files)}:{}}),e);return this.buildSuccess(e,o,c.text)}case"read-only-chat":{let s=n.providerId??e,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`provider "${s}" not registered`);let a=n.agentName!==void 0?Jw(e,r,this.agentsDir,this.readFile,this.sysPromptCache):r.system,c=await yp(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:Kw(r.files)}:{}}),e);return this.buildSuccess(e,o,c.text)}default:{let s=n.transport;return this.buildFailure(e,o,`unknown transport: ${String(s)}`)}}}catch(s){return this.buildFailure(e,o,z(s))}}lookupProviderOrNull(e){try{return this.registry.get(e)}catch{return null}}resolveDescriptor(e){let r=kO(e,this.hostKind);return r.transport==="task-subagent"&&!this.subagentSpawner&&this.hostKind==="claude-code"?{transport:"read-only-chat",providerId:vp,agentName:r.agentName}:r}buildSuccess(e,r,n){return{participantId:e,text:n,latencyMs:Math.round(performance.now()-r),failed:!1}}buildFailure(e,r,n){return{participantId:e,text:"",latencyMs:Math.round(performance.now()-r),failed:!0,failureReason:n}}};function Qw(t){return new wp(t)}function Xw(t,e){return e(t)}var PO=/[.,!?;:]/g,TO=/\s+/g;function ex(t){return t.toLowerCase().replace(PO," ").replace(TO," ").trim()}function tx(t){return typeof t.location=="string"&&t.location.length>0}function rx(t,e){if(e.length===0)return t;let r=new Set(t),n=t.slice();for(let o of e)r.has(o)||(r.add(o),n.push(o));return n}function EO(t){let e={id:t.id,proposerIds:t.proposerIds.slice(),title:t.title,severity:t.severity,roundOpened:t.roundOpened,status:t.status,votes:new Map};t.location!==void 0&&(e.location=t.location),t.description!==void 0&&(e.description=t.description),t.supersededBy!==void 0&&(e.supersededBy=t.supersededBy),t.mergedInto!==void 0&&(e.mergedInto=t.mergedInto);for(let[r,n]of t.votes)e.votes.set(r,{...n});return e}function RO(t,e){let r=t.proposerIds[0],n=e.proposerIds[0];if(r===n)return{kind:"unrelated"};let o=ex(t.title)===ex(e.title),s=t.severity===e.severity,a=tx(t)&&tx(e)&&t.location===e.location,c=[];if(o&&c.push("title"),s&&c.push("severity"),a&&c.push("location"),c.length===0)return{kind:"unrelated"};if(o&&s&&a)return{kind:"hard-merge"};let l;return o?s?l="location":l="severity":l="title",{kind:"alias",pair:{proposalA:t.id,proposalB:e.id,matchedFields:c,missingField:l}}}var io=class t{_proposals=new Map;_aliasCandidates=[];get proposals(){return this._proposals}get aliasCandidates(){return this._aliasCandidates.slice()}addProposal(e){if(this._proposals.has(e.id))throw new Error(`ProposalLedger.addProposal: duplicate id "${e.id}"`);let r={id:e.id,proposerIds:e.proposerIds.slice(),title:e.title,severity:e.severity,roundOpened:e.roundOpened,status:e.status??"open",votes:new Map};e.location!==void 0&&(r.location=e.location),e.description!==void 0&&(r.description=e.description),this._proposals.set(r.id,r)}recordVote(e,r,n){let o=this._proposals.get(e);if(!o)throw new Error(`ProposalLedger.recordVote: unknown proposal id "${e}"`);o.votes.set(r,{...n}),o.proposerIds.includes(r)&&n.vote==="revise"&&o.status==="open"&&(o.status="withdrawn-by-author")}countRevisesThisRound(e,r){let n=this._proposals.get(e);if(!n)return 0;let o=0;for(let[s,i]of n.votes)i.vote==="revise"&&i.roundRecorded===r&&(n.proposerIds.includes(s)||(o+=1));return o}markSuperseded(e,r,n){let o=this._proposals.get(e);if(!o)throw new Error(`ProposalLedger.markSuperseded: unknown old id "${e}"`);if(!this._proposals.has(r))throw new Error(`ProposalLedger.markSuperseded: successor id "${r}" not registered`);o.status="superseded",o.supersededBy=r;for(let s of o.votes.values())s.supersededAt===void 0&&(s.supersededAt=n)}applyAliasMerge(e,r){if(e===r)throw new Error(`ProposalLedger.applyAliasMerge: cannot merge id "${e}" into itself`);let n=this._proposals.get(e),o=this._proposals.get(r);if(!n)throw new Error(`ProposalLedger.applyAliasMerge: unknown primary id "${e}"`);if(!o)throw new Error(`ProposalLedger.applyAliasMerge: unknown alias id "${r}"`);n.proposerIds=rx(n.proposerIds,o.proposerIds);for(let[s,i]of o.votes){let a=n.votes.get(s);if(!a){n.votes.set(s,{...i});continue}i.roundRecorded>a.roundRecorded&&n.votes.set(s,{...i})}o.status="merged",o.mergedInto=e;for(let s=this._aliasCandidates.length-1;s>=0;s-=1){let i=this._aliasCandidates[s];(i.proposalA===r||i.proposalB===r||i.proposalA===e||i.proposalB===e)&&this._aliasCandidates.splice(s,1)}}setStatus(e,r){let n=this._proposals.get(e);if(!n)throw new Error(`ProposalLedger.setStatus: unknown proposal id "${e}"`);n.status=r}aggregateRound(e,r,n=[]){let o=new Set(n),s=[];for(let i of this._proposals.values()){if(i.status!=="open")continue;let a={agree:0,disagree:0,abstain:0,revise:0,missing:0};for(let u of r){if(i.proposerIds.includes(u))continue;let l=i.votes.get(u);if(l===void 0||l.roundRecorded!==e){o.has(u)?a.abstain+=1:a.missing+=1;continue}switch(l.vote){case"agree":a.agree+=1;break;case"disagree":a.disagree+=1;break;case"abstain":a.abstain+=1;break;case"revise":a.revise+=1;break;default:{let d=l.vote}}}let c=IO(a);s.push({proposalId:i.id,tally:a,verdict:c})}return s}getOpenProposals(){return this.selectByStatus("open")}getConsensusProposals(){return this.selectByStatus("consensus")}getUnresolved(){return this.selectByStatus("unresolved")}selectByStatus(e){let r=[];for(let n of this._proposals.values())n.status===e&&r.push(EO(n));return r}toJSON(){let e=Array.from(this._proposals.values()).map(n=>{let o=[];for(let[i,a]of n.votes){let c={voter:i,vote:a.vote,roundRecorded:a.roundRecorded};a.reason!==void 0&&(c.reason=a.reason),a.supersededAt!==void 0&&(c.supersededAt=a.supersededAt),o.push(c)}let s={id:n.id,proposerIds:n.proposerIds.slice(),title:n.title,severity:n.severity,roundOpened:n.roundOpened,status:n.status,votes:o};return n.location!==void 0&&(s.location=n.location),n.description!==void 0&&(s.description=n.description),n.supersededBy!==void 0&&(s.supersededBy=n.supersededBy),n.mergedInto!==void 0&&(s.mergedInto=n.mergedInto),s}),r=this._aliasCandidates.map(n=>({proposalA:n.proposalA,proposalB:n.proposalB,matchedFields:n.matchedFields.slice(),missingField:n.missingField}));return{proposals:e,aliasCandidates:r}}static fromJSON(e){let r=new t,n=new Set;for(let o of e.proposals){if(n.has(o.id))throw new Error(`ProposalLedger.fromJSON: duplicate proposal id "${o.id}"`);n.add(o.id);let s={id:o.id,proposerIds:o.proposerIds.slice(),title:o.title,severity:o.severity,roundOpened:o.roundOpened,status:o.status,votes:new Map};o.location!==void 0&&(s.location=o.location),o.description!==void 0&&(s.description=o.description),o.supersededBy!==void 0&&(s.supersededBy=o.supersededBy),o.mergedInto!==void 0&&(s.mergedInto=o.mergedInto);for(let i of o.votes){let a={vote:i.vote,roundRecorded:i.roundRecorded};i.reason!==void 0&&(a.reason=i.reason),i.supersededAt!==void 0&&(a.supersededAt=i.supersededAt),s.votes.set(i.voter,a)}r._proposals.set(s.id,s)}for(let o of e.aliasCandidates)r._aliasCandidates.push({proposalA:o.proposalA,proposalB:o.proposalB,matchedFields:o.matchedFields.slice(),missingField:o.missingField});return r}_rawProposal(e){return this._proposals.get(e)}_pushAliasCandidate(e){this._aliasCandidates.push(e)}_extendProposers(e,r){let n=this._proposals.get(e);n&&(n.proposerIds=rx(n.proposerIds,r))}_maybeReplaceDescription(e,r){let n=this._proposals.get(e);if(!n||r===void 0)return;let o=n.description??"";r.length>o.length&&(n.description=r)}};function IO(t){return t.disagree>0||t.revise>0?"dissent":t.missing>0?"pending":t.agree>0?"consensus":"pending"}function nx(t){let e=new io,r=new Set;for(let s of t){if(r.has(s.id))throw new Error(`buildInitialLedger: duplicate proposal id "${s.id}"`);r.add(s.id),e.addProposal({id:s.id,proposerIds:[s.proposerId],title:s.title,severity:s.severity,...s.location!==void 0?{location:s.location}:{},...s.description!==void 0?{description:s.description}:{},roundOpened:s.roundOpened??1,status:"open"})}let n=new Set,o=t.map(s=>s.id);for(let s=0;s<o.length;s+=1){let i=o[s];if(n.has(i))continue;let a=e._rawProposal(i);if(a)for(let c=s+1;c<o.length;c+=1){let u=o[c];if(n.has(u))continue;let l=e._rawProposal(u);if(!l)continue;let d=RO(a,l);if(d.kind==="hard-merge"){e._extendProposers(i,l.proposerIds),e._maybeReplaceDescription(i,l.description),e._proposals.delete(u),n.add(u);continue}d.kind==="alias"&&e._pushAliasCandidate(d.pair)}}return{ledger:e,aliasCandidates:e.aliasCandidates}}var AO=new Set(df);function CO(t){return AO.has(t)}var DO=new Set(["disagree","revise"]);function zO(t){let e=`<${ln}>`,r=`</${ln}>`,n=t.lastIndexOf(r);if(n<0)return null;let o=t.lastIndexOf(e,n);return o<0?null:{inner:t.slice(o+e.length,n)}}function OO(t){let e=`<${ln}>`;return t.includes(e)}var MO=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function NO(t){return t.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g,(e,r)=>{if(r.startsWith("#x")||r.startsWith("#X")){let o=parseInt(r.slice(2),16);return Number.isFinite(o)?String.fromCodePoint(o):e}if(r.startsWith("#")){let o=parseInt(r.slice(1),10);return Number.isFinite(o)?String.fromCodePoint(o):e}return MO[r]??e})}function jO(t){let e={},r=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,n=0,o;for(;(o=r.exec(t))!==null;){if(t.slice(n,o.index).trim().length>0)return null;let i=o[1],a=o[2],c=o[3],u=a!==void 0?a:c??"";if(Object.prototype.hasOwnProperty.call(e,i))return null;e[i]=NO(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function xp(t,e){let r=zO(t);if(!r)return OO(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${ln}> without matching </${ln}>`}}:{ok:!1,error:{kind:"missing-block"}};let n=new Set(e),o=/<item\b([^>]*?)\/>/g,s=[],i;for(;(i=o.exec(r.inner))!==null;)s.push({raw:i[0],attrString:i[1],index:i.index,length:i[0].length});let a=0;for(let p of s){let f=r.inner.slice(a,p.index);if(!ox(f))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected content between <item> elements: ${JSON.stringify(f.slice(0,40))}`}};a=p.index+p.length}let c=r.inner.slice(a);if(!ox(c))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected trailing content: ${JSON.stringify(c.slice(0,40))}`}};let u=[],l=[],d=new Set;for(let p of s){let f=jO(p.attrString);if(f===null){l.push({reason:"malformed-entry",raw:p.raw});continue}let m=f.id,g=f.vote;if(typeof m!="string"||m.length===0||typeof g!="string"){l.push({proposalId:typeof m=="string"&&m.length>0?m:void 0,reason:"malformed-entry",raw:p.raw});continue}if(!CO(g)){l.push({proposalId:m,reason:"unknown-vote",raw:p.raw});continue}if(!n.has(m)){l.push({proposalId:m,reason:"unknown-id",raw:p.raw});continue}if(d.has(m)){l.push({proposalId:m,reason:"duplicate-id",raw:p.raw});continue}let y=f.reason,_=typeof y=="string"&&y.length>0?y:void 0;if(DO.has(g)&&_===void 0){d.add(m),l.push({proposalId:m,reason:"missing-reason",raw:p.raw});continue}d.add(m);let x={proposalId:m,vote:g};_!==void 0&&(x.reason=_),u.push(x)}return{ok:!0,entries:u,entryErrors:l}}function ox(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}var LO=Object.freeze(["same","different","unsure"]),Os="alias-votes",FO=new Set(LO);function ZO(t){return FO.has(t)}function UO(t){let e=`<${Os}>`,r=`</${Os}>`,n=t.lastIndexOf(r);if(n<0)return null;let o=t.lastIndexOf(e,n);return o<0?null:{inner:t.slice(o+e.length,n)}}function qO(t){let e=`<${Os}>`;return t.includes(e)}var VO=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function BO(t){return t.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g,(e,r)=>{if(r.startsWith("#x")||r.startsWith("#X")){let o=parseInt(r.slice(2),16);return Number.isFinite(o)?String.fromCodePoint(o):e}if(r.startsWith("#")){let o=parseInt(r.slice(1),10);return Number.isFinite(o)?String.fromCodePoint(o):e}return VO[r]??e})}function WO(t){let e={},r=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,n=0,o;for(;(o=r.exec(t))!==null;){if(t.slice(n,o.index).trim().length>0)return null;let i=o[1],a=o[2],c=o[3],u=a!==void 0?a:c??"";if(Object.prototype.hasOwnProperty.call(e,i))return null;e[i]=BO(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function sx(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}function Sp(t,e){let r=UO(t);if(!r)return qO(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${Os}> without matching </${Os}>`}}:{ok:!1,error:{kind:"missing-block"}};let n=new Set(e),o=/<item\b([^>]*?)\/>/g,s=[],i;for(;(i=o.exec(r.inner))!==null;)s.push({raw:i[0],attrString:i[1],index:i.index,length:i[0].length});let a=0;for(let p of s){let f=r.inner.slice(a,p.index);if(!sx(f))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected content between <item> elements: ${JSON.stringify(f.slice(0,40))}`}};a=p.index+p.length}let c=r.inner.slice(a);if(!sx(c))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected trailing content: ${JSON.stringify(c.slice(0,40))}`}};let u=[],l=[],d=new Set;for(let p of s){let f=WO(p.attrString);if(f===null){l.push({reason:"malformed-entry",raw:p.raw});continue}let m=f.pair,g=f.vote;if(typeof m!="string"||m.length===0||typeof g!="string"){l.push({pair:typeof m=="string"&&m.length>0?m:void 0,reason:"malformed-entry",raw:p.raw});continue}if(!ZO(g)){l.push({pair:m,reason:"unknown-vote",raw:p.raw});continue}if(!n.has(m)){l.push({pair:m,reason:"unknown-pair",raw:p.raw});continue}if(d.has(m)){l.push({pair:m,reason:"duplicate-pair",raw:p.raw});continue}let y=f.reason,_=typeof y=="string"&&y.length>0?y:void 0;d.add(m);let x={pair:m,vote:g};_!==void 0&&(x.reason=_),u.push(x)}return{ok:!0,entries:u,entryErrors:l}}var HO="__";function KO(t){return`${t.proposalA}${HO}${t.proposalB}`}var GO=["You are participating in the alias clarification phase of a structured debate.","The moderator has detected the following proposal pairs that partially match","on title / severity / location but did not satisfy the automatic hard-merge","rule. For each pair, decide whether the two proposals describe the SAME","underlying issue or DIFFERENT issues. If you cannot tell from the material","given, answer `unsure` \u2014 there is no penalty for uncertainty here, this","phase is not the main debate."].join(" "),JO=["For every pair below, emit exactly one `<item>` element inside the","`<alias-votes>` block. The `pair` attribute must match the identifier","printed with each pair. The `vote` attribute must be one of:","`same`, `different`, `unsure`. A `reason` attribute is optional but","encouraged when you answer `different` or `unsure`."].join(" "),YO=["Response format \u2014 append the following block at the end of your reply","(moderator parses only this block; preamble is ignored):","","<alias-votes>",' <item pair="P1__P2" vote="same"/>',' <item pair="P3__P4" vote="different" reason="P3 concerns cache invalidation; P4 concerns read-through."/>',' <item pair="P5__P6" vote="unsure" reason="Insufficient detail on location."/>',"</alias-votes>"].join(`
|
|
292
|
-
`)
|
|
293
|
-
`)}async function
|
|
294
|
-
`)}function
|
|
295
|
-
`)}function
|
|
296
|
-
`)}function px(){return{renderTerminal:uM,renderSynthesis:lM}}var dM=Object.freeze({running:"report.status.running","ready-for-approval":"report.status.readyForApproval",consensus:"report.status.consensus",escalated:"report.status.escalated",approved:"report.status.approved",rejected:"report.status.rejected","leader-timeout":"report.status.leaderTimeout",error:"report.status.error"});function pM(t,e){let r=e.t(dM[t.status]),n=e.t("report.header.topic"),o=e.t("report.header.participants"),s=e.t("report.header.individualDocs"),i=[`## ${n}: ${t.topic} (${t.rounds}/${t.maxRounds} \u2014 ${r})`,`## ${o}: ${t.participantIds.join(", ")}`,`## ${s}:`],a=Math.min(t.participantIds.length,t.individualPaths.length);for(let c=0;c<a;c+=1)i.push(` - ${t.participantIds[c]}: ${t.individualPaths[c]}`);return i}function fx(t,e){let r=[`## ${e.t("report.section.mainTable")}`,"",`| ${e.t("report.table.proposer")} | ${e.t("report.table.opinion")} | ${e.t("report.table.severity")} | ${e.t("report.table.agreement")} |`,"|---|---|---|---|"];for(let n of t.proposals){let o=n.proposerIds.join(", "),s=fM(n);r.push(`| ${o} | ${n.title} | ${n.severity} | ${s} |`)}return r}function fM(t){let e=`${t.agreeCount}/${t.totalVoters}`;return t.accepted||t.dissentSummary===void 0||t.dissentSummary.length===0?e:`${e} (${t.dissentSummary})`}function mx(t,e){if(t.dissentDetails.length===0)return[];let r=[`## ${e.t("report.section.dissentDetail")}`];for(let n of t.dissentDetails){r.push(""),r.push(`### ${n.proposalTitle} (${n.severity})`);for(let o of n.perParticipant)r.push(Tp(o))}return r}function Tp(t){let e=`- **${t.participantId}:** ${t.vote}`;return t.reason===void 0||t.reason.length===0?e:`${e} \u2014 ${t.reason}`}function hx(t,e){let r=`| ${e.t("report.contribution.ai")} | ${e.t("report.contribution.proposed")} | ${e.t("report.contribution.accepted")} | ${e.t("report.contribution.revises")} | ${e.t("report.contribution.abstains")} |`,n=[`## ${e.t("report.section.contributionSummary")}`,"",r,"|---|---|---|---|---|"];for(let o of t.contributionSummary){let s=o.proposed===0?"\u2014":String(o.consensusReceived);n.push(`| ${o.participantId} | ${o.proposed} | ${s} | ${o.revisesProposed} | ${o.abstains} |`)}return n}function mM(t,e){let r=e.t("report.footer.synthesisPath"),n=e.t("report.footer.debatePath"),o=t.synthesisPath??e.t("report.footer.pendingSynthesis"),s=[`## ${r}: ${o}`,`## ${n}: ${t.debatePath}`];return t.status==="ready-for-approval"&&(s.push(""),s.push(e.t("approval.pending"))),s}function hM(t,e){let r=t.acceptedItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.acceptedItems")}`];for(let o of r)n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),n.push(`**${e.t("report.table.proposer")}:** ${o.proposerIds.join(", ")}`),n.push(`**${e.t("report.table.agreement")}:** ${o.agreeCount}/${o.totalVoters}`),o.finalStatement.length>0&&(n.push(""),n.push(o.finalStatement));return n}function gM(t,e){let r=t.rejectedItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.rejectedItems")}`];for(let o of r){n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),o.rejectionReason.length>0&&(n.push(""),n.push(o.rejectionReason));for(let s of o.dissentVotes)n.push(Tp(s))}return n}function yM(t,e){let r=t.openItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.openItems")}`];for(let o of r){n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),n.push(`**${e.t("report.table.agreement")}:** ${o.agreeCount}/${o.totalVoters}`);for(let s of o.perParticipant)n.push(Tp(s))}return n}var co=class{deps;sessions=new Map;formatter=px();constructor(e){this.deps=e}async startDebate(e){let r=(this.deps.generateSessionId??vM)(),n=this.nowIso(),o=Hw({topic:e.topic,...e.goal!==void 0?{goal:e.goal}:{},participants:e.participants,excludeParticipants:e.excludeParticipants??[],autoInjectSpecialists:e.autoInjectSpecialists??!0}),s=o.participants,i={topic:e.topic,scope:e.scope??e.topic,participants:s,excludeParticipants:e.excludeParticipants??[],leader:e.leader,maxRounds:e.maxRounds??Cc,locale:e.locale??this.deps.i18n.locale,autoInjectSpecialists:e.autoInjectSpecialists??!0},a=await this.deps.documentManager.createDebateDocument({topic:e.topic,providers:s.slice(),...e.goal!==void 0?{goal:e.goal}:{}}),c={sessionId:r,config:i,goal:e.goal,individualReviewPrompt:e.individualReviewPrompt,files:e.files??[],debateDocId:a.id,debateDocPath:a.path,individualPaths:{},createdAt:n,ledger:new io,rounds:0,maxRounds:i.maxRounds,consecutiveFailures:new Map,unavailableParticipants:new Set,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:1};this.sessions.set(r,c);try{let u=await this.runIndividualPhase(c,o),{ledger:l}=nx(u);c.ledger=l,c.nextProposalIndex=kM(u),l.aliasCandidates.length>0&&await this.runAliasClarificationPhase(c),await this.runRoundLoop(c);let d=this.buildSnapshot(c,gx(c));return await this.deps.registry.persist(d),this.emitTrace(c,"debate_rfa",{status:d.status}),{sessionId:r,status:d.status,snapshot:d,terminalReport:this.renderTerminal(c,d)}}catch(u){let l=this.buildSnapshot(c,"error",vc(u));try{await this.deps.registry.persist(l)}catch{}return this.emitTrace(c,"debate_error",{error:vc(u)}),{sessionId:r,status:"error",snapshot:l,terminalReport:this.renderTerminal(c,l),errorMessage:vc(u)}}}async approve(e){let r=await this.loadSnapshotOrThrow(e.sessionId);if(r.status==="approved"){if(!r.documentPaths.synthesis)throw new Error(`approve: session "${e.sessionId}" is marked approved but has no synthesis path recorded. Snapshot is inconsistent.`);let u=this.sessions.get(e.sessionId);return{snapshot:r,synthesisPath:r.documentPaths.synthesis,terminalReport:this.renderTerminal(u??null,r),idempotentReplay:!0}}Ep(r,["ready-for-approval","escalated"],"approve");let n=this.sessions.get(e.sessionId),o=n?this.buildReportData(n,r,e.leaderNote):vx(r,e.leaderNote),s=this.formatter.renderSynthesis(o,this.deps.i18n),i=(r.status==="escalated"||r.status==="ready-for-approval")&&r.status==="escalated"?"escalated":"consensus",a=await this.deps.documentManager.createSynthesis({sessionId:r.sessionId,topic:r.config.topic,status:i,rounds:r.rounds,maxRounds:r.config.maxRounds,participantIds:r.config.participants,individualPaths:Object.values(r.documentPaths.individual),debatePath:r.documentPaths.debate,body:s,...e.leaderNote!==void 0?{metadata:{"Leader Note":e.leaderNote}}:{}});await this.deps.documentManager.addComment(n?.debateDocId??_c(r),{author:"moderator",content:this.formatApprovalFooter(e.leaderNote)});let c={...r,status:"approved",documentPaths:{...r.documentPaths,synthesis:a.path}};return await this.deps.registry.persist(c),this.emitTrace(n??null,"debate_approved",{sessionId:r.sessionId,synthesisPath:a.path}),{snapshot:c,synthesisPath:a.path,terminalReport:this.renderTerminal(n??null,c)}}async continueDebate(e){if(!Number.isInteger(e.additionalRounds)||e.additionalRounds<=0)throw new Error(`continueDebate: additionalRounds must be a positive integer (got ${e.additionalRounds})`);let r=await this.loadSnapshotOrThrow(e.sessionId);Ep(r,["ready-for-approval","escalated"],"continue");let n=this.sessions.get(e.sessionId);if(!n){if(!r.ledgerState)throw new Error(`continueDebate: snapshot for session "${e.sessionId}" is too old to resume after restart \u2014 missing ledgerState. Use approve or reject instead, or rerun the debate.`);n=this.rehydrateSessionContext(r),this.sessions.set(e.sessionId,n)}n.maxRounds=r.config.maxRounds+e.additionalRounds;for(let i of n.ledger.proposals.values())i.status;await this.runRoundLoop(n);let o=gx(n),s=this.buildSnapshot(n,o);return await this.deps.registry.persist(s),this.emitTrace(n,"debate_continued",{additionalRounds:e.additionalRounds,status:s.status}),{snapshot:s,terminalReport:this.renderTerminal(n,s)}}async reject(e){let r=await this.loadSnapshotOrThrow(e.sessionId);if(r.status==="rejected")return{snapshot:r,idempotentReplay:!0,...r.documentPaths.issue!==void 0?{issuePath:r.documentPaths.issue}:{}};Ep(r,["ready-for-approval","escalated","leader-timeout"],"reject");let n=this.sessions.get(e.sessionId),o=n?.debateDocId??_c(r);await this.deps.documentManager.addComment(o,{author:"moderator",content:this.formatRejectionFooter(e.reason)});let s;e.spawnIssue===!0&&(s=(await this.deps.documentManager.createIssueDocument({sessionId:r.sessionId,topic:r.config.topic,...e.reason!==void 0?{reason:e.reason}:{},items:$M(r)})).path);let i={...r,status:"rejected",terminalNote:e.reason??r.terminalNote,documentPaths:{...r.documentPaths,...s!==void 0?{issue:s}:{}}};return await this.deps.registry.persist(i),this.emitTrace(n??null,"debate_rejected",{sessionId:r.sessionId,...s!==void 0?{issuePath:s}:{}}),{snapshot:i,...s!==void 0?{issuePath:s}:{}}}async handleTimedOutSnapshots(e){for(let r of e){if(r.status!=="leader-timeout")continue;let n=_c(r);try{await this.deps.documentManager.addComment(n,{author:"moderator",content:this.formatLeaderTimeoutFooter(r)})}catch{}this.emitTrace(this.sessions.get(r.sessionId)??null,"debate_leader_timeout",{sessionId:r.sessionId})}}async runIndividualPhase(e,r){let n=CM(),o=DM(e),s=await Promise.allSettled(e.config.participants.map(async a=>{let c=await this.deps.bridge.requestTurn(a,{prompt:o,system:e.individualReviewPrompt??n,round:0,...e.files.length>0?{files:e.files}:{}});return{participantId:a,resp:c}})),i=[];for(let a of s){if(a.status==="rejected")continue;let{participantId:c,resp:u}=a.value,l=u.failed?`(no response: ${u.failureReason??"unknown"})`:u.text,d=await this.deps.documentManager.createIndividualReview({participantId:c,topic:e.config.topic,content:l,...e.files.length>0?{files:e.files}:{}});if(e.individualPaths[c]=d.path,u.failed)continue;let p=AM(u.text);for(let f of p){let m=yx(e,f.id);i.push({id:m,proposerId:c,title:f.title,severity:f.severity,...f.location!==void 0?{location:f.location}:{},...f.description!==void 0?{description:f.description}:{},roundOpened:1})}}return i}async runAliasClarificationPhase(e){let r=await lx({ledger:e.ledger,participantIds:e.config.participants,askParticipant:async(o,s)=>{let i=await this.deps.bridge.requestTurn(o,{prompt:s,round:0,...e.files.length>0?{files:e.files}:{}});return i.failed?{text:"",failed:!0}:{text:i.text}}}),n=jM(r,this.deps.i18n);n.length>0&&await this.deps.documentManager.addComment(e.debateDocId,{author:"moderator",content:n})}async runRoundLoop(e){for(;e.rounds<e.maxRounds;){if(e.ledger.getOpenProposals().map(p=>p.id).length===0)return;e.rounds+=1;let n=e.rounds,o=e.config.participants.filter(p=>!e.unavailableParticipants.has(p)),s=e.ledger.getOpenProposals(),i=e.pendingVoteWarnings,a=new Map,c=await Promise.allSettled(o.map(async p=>{let f={prompt:zM({round:n,maxRounds:e.maxRounds,topic:e.config.topic,scope:e.config.scope,openProposals:s,previousVoteIssues:i.get(p)}),round:n,...e.files.length>0?{files:e.files}:{}},m=await this.deps.bridge.requestTurn(p,f);return{participantId:p,request:f,resp:m}})),u=[],l=new Set;for(let p=0;p<c.length;p+=1){let f=c[p],m=o[p];if(f.status==="rejected"||f.value.resp.failed){this.registerFailure(e,m);let y=f.status==="rejected"?vc(f.reason):f.value.resp.failureReason??"unknown";u.push({participantId:m,text:`(no response: ${y})`,failed:!0});continue}l.add(m);let g=await this.parseVotesWithRetry(m,f.value.request,f.value.resp.text,s,n);if(u.push({participantId:m,text:g.displayText,failed:!g.ok}),!g.ok){this.registerFailure(e,m),a.set(m,g.warnings);continue}this.clearFailure(e,m);for(let y of g.parsed.entries)e.ledger.recordVote(y.proposalId,m,{vote:y.vote,roundRecorded:n,...y.reason!==void 0?{reason:y.reason}:{}});g.parsed.entryErrors.length>0&&a.set(m,MM(g.parsed.entryErrors))}e.pendingVoteWarnings=a;let d=e.ledger.aggregateRound(n,e.config.participants,Array.from(e.unavailableParticipants));for(let p of d){let f=e.ledger.proposals.get(p.proposalId);if(!f)continue;let m=e.config.participants.filter(g=>!f.proposerIds.includes(g)).length;if(bM(p.tally,m)){e.ledger.setStatus(p.proposalId,"consensus"),e.allAbstainCount.delete(p.proposalId);continue}if(wM(p.tally,m)){e.ledger.setStatus(p.proposalId,"rejected"),e.allAbstainCount.delete(p.proposalId);continue}if(xM(p.tally)){let g=(e.allAbstainCount.get(p.proposalId)??0)+1;e.allAbstainCount.set(p.proposalId,g),g>=zc&&(e.ledger.setStatus(p.proposalId,"unresolved"),e.allAbstainCount.delete(p.proposalId));continue}e.allAbstainCount.delete(p.proposalId)}for(let p of d){if(p.tally.revise===0)continue;let f=e.ledger.proposals.get(p.proposalId);if(!f||f.status!=="open"||e.ledger.countRevisesThisRound(p.proposalId,n)===0)continue;let g=this.synthesizeReviseSuccessor(e,f,n);e.reviseSuccessors.set(f.id,g)}if(await this.deps.documentManager.addComment(e.debateDocId,{author:"moderator",content:NM({round:n,maxRounds:e.maxRounds,openProposals:s,turns:u,aggregation:d,ledger:e.ledger})}),l.size===0)return}}async parseVotesWithRetry(e,r,n,o,s){let i=o.map(p=>p.id),a=xp(n,i);if(a.ok)return{ok:!0,parsed:a,displayText:n};let c={prompt:OM({openProposals:o,errorKind:a.error.kind,errorDetails:a.error.details}),round:s,...r.files!==void 0?{files:r.files}:{}},u=await this.deps.bridge.requestTurn(e,c);if(u.failed)return{ok:!1,displayText:`${n}
|
|
307
|
+
`,r+4);return n<0?"":t.slice(n+1)}function YO(t,e){return GO.has(t)?e==="claude-code"?{transport:"task-subagent",agentName:Dp[t]}:{transport:"cli-bridge",providerId:Cp,agentName:Dp[t]}:t===Ap?e==="claude-code"?{transport:"read-only-chat",providerId:Ap}:{transport:"cli-bridge",providerId:Cp}:{transport:"read-only-chat",providerId:t}}function lx(t){if(!(!t||t.length===0))return t.map(e=>({path:e}))}var dx=18e4;function Ip(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Participant "${e}" stalled (no response after ${dx/1e3}s)`)),dx))])}function px(t,e,r,n,o){if(e.system!==void 0)return e.system;let s=Dp[t];if(s===void 0)return;if(o.has(s))return o.get(s)??void 0;let i=fx(r,`${s}.md`);try{let a=JO(n(i)).trim(),c=a.length>0?a:null;return o.set(s,c),c??void 0}catch{o.set(s,null);return}}var zp=class{registry;readOnlyAdapter;hostKind;agentsDir;readFile;subagentSpawner;sysPromptCache=new Map;constructor(e){this.registry=e.registry,this.readOnlyAdapter=e.readOnlyAdapter,this.hostKind=e.hostKind,this.agentsDir=e.agentsDir??fx(process.cwd(),"agents"),this.readFile=e.agentsFileReader??(r=>KO(r,"utf-8")),this.subagentSpawner=e.subagentSpawner}describe(e){return this.resolveDescriptor(e)}async requestTurn(e,r){let n=this.resolveDescriptor(e),o=performance.now();try{switch(n.transport){case"task-subagent":{if(!this.subagentSpawner)return this.buildFailure(e,o,"subagent spawner not wired (integration pending \u2014 T10/T12)");let s=await Ip(this.subagentSpawner({agentName:n.agentName??e,prompt:r.prompt,system:r.system}),e);return this.buildSuccess(e,o,s.text)}case"cli-bridge":{let s=n.providerId??Cp,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`CLI provider "${s}" not registered`);let a=px(e,r,this.agentsDir,this.readFile,this.sysPromptCache),c=await Ip(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:lx(r.files)}:{}}),e);return this.buildSuccess(e,o,c.text)}case"read-only-chat":{let s=n.providerId??e,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`provider "${s}" not registered`);let a=n.agentName!==void 0?px(e,r,this.agentsDir,this.readFile,this.sysPromptCache):r.system,c=await Ip(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:lx(r.files)}:{}}),e);return this.buildSuccess(e,o,c.text)}default:{let s=n.transport;return this.buildFailure(e,o,`unknown transport: ${String(s)}`)}}}catch(s){return this.buildFailure(e,o,M(s))}}lookupProviderOrNull(e){try{return this.registry.get(e)}catch{return null}}resolveDescriptor(e){let r=YO(e,this.hostKind);return r.transport==="task-subagent"&&!this.subagentSpawner&&this.hostKind==="claude-code"?{transport:"read-only-chat",providerId:Ap,agentName:r.agentName}:r}buildSuccess(e,r,n){return{participantId:e,text:n,latencyMs:Math.round(performance.now()-r),failed:!1}}buildFailure(e,r,n){return{participantId:e,text:"",latencyMs:Math.round(performance.now()-r),failed:!0,failureReason:n}}};function mx(t){return new zp(t)}function hx(t,e){return e(t)}var XO=/[.,!?;:]/g,QO=/\s+/g;function gx(t){return t.toLowerCase().replace(XO," ").replace(QO," ").trim()}function yx(t){return typeof t.location=="string"&&t.location.length>0}function vx(t,e){if(e.length===0)return t;let r=new Set(t),n=t.slice();for(let o of e)r.has(o)||(r.add(o),n.push(o));return n}function eM(t){let e={id:t.id,proposerIds:t.proposerIds.slice(),title:t.title,severity:t.severity,roundOpened:t.roundOpened,status:t.status,votes:new Map};t.location!==void 0&&(e.location=t.location),t.description!==void 0&&(e.description=t.description),t.supersededBy!==void 0&&(e.supersededBy=t.supersededBy),t.mergedInto!==void 0&&(e.mergedInto=t.mergedInto);for(let[r,n]of t.votes)e.votes.set(r,{...n});return e}function tM(t,e){let r=t.proposerIds[0],n=e.proposerIds[0];if(r===n)return{kind:"unrelated"};let o=gx(t.title)===gx(e.title),s=t.severity===e.severity,a=yx(t)&&yx(e)&&t.location===e.location,c=[];if(o&&c.push("title"),s&&c.push("severity"),a&&c.push("location"),c.length===0)return{kind:"unrelated"};if(o&&s&&a)return{kind:"hard-merge"};let l;return o?s?l="location":l="severity":l="title",{kind:"alias",pair:{proposalA:t.id,proposalB:e.id,matchedFields:c,missingField:l}}}var po=class t{_proposals=new Map;_aliasCandidates=[];get proposals(){return this._proposals}get aliasCandidates(){return this._aliasCandidates.slice()}addProposal(e){if(this._proposals.has(e.id))throw new Error(`ProposalLedger.addProposal: duplicate id "${e.id}"`);let r={id:e.id,proposerIds:e.proposerIds.slice(),title:e.title,severity:e.severity,roundOpened:e.roundOpened,status:e.status??"open",votes:new Map};e.location!==void 0&&(r.location=e.location),e.description!==void 0&&(r.description=e.description),this._proposals.set(r.id,r)}recordVote(e,r,n){let o=this._proposals.get(e);if(!o)throw new Error(`ProposalLedger.recordVote: unknown proposal id "${e}"`);o.votes.set(r,{...n}),o.proposerIds.includes(r)&&n.vote==="revise"&&o.status==="open"&&(o.status="withdrawn-by-author")}countRevisesThisRound(e,r){let n=this._proposals.get(e);if(!n)return 0;let o=0;for(let[s,i]of n.votes)i.vote==="revise"&&i.roundRecorded===r&&(n.proposerIds.includes(s)||(o+=1));return o}markSuperseded(e,r,n){let o=this._proposals.get(e);if(!o)throw new Error(`ProposalLedger.markSuperseded: unknown old id "${e}"`);if(!this._proposals.has(r))throw new Error(`ProposalLedger.markSuperseded: successor id "${r}" not registered`);o.status="superseded",o.supersededBy=r;for(let s of o.votes.values())s.supersededAt===void 0&&(s.supersededAt=n)}applyAliasMerge(e,r){if(e===r)throw new Error(`ProposalLedger.applyAliasMerge: cannot merge id "${e}" into itself`);let n=this._proposals.get(e),o=this._proposals.get(r);if(!n)throw new Error(`ProposalLedger.applyAliasMerge: unknown primary id "${e}"`);if(!o)throw new Error(`ProposalLedger.applyAliasMerge: unknown alias id "${r}"`);n.proposerIds=vx(n.proposerIds,o.proposerIds);for(let[s,i]of o.votes){let a=n.votes.get(s);if(!a){n.votes.set(s,{...i});continue}i.roundRecorded>a.roundRecorded&&n.votes.set(s,{...i})}o.status="merged",o.mergedInto=e;for(let s=this._aliasCandidates.length-1;s>=0;s-=1){let i=this._aliasCandidates[s];(i.proposalA===r||i.proposalB===r||i.proposalA===e||i.proposalB===e)&&this._aliasCandidates.splice(s,1)}}setStatus(e,r){let n=this._proposals.get(e);if(!n)throw new Error(`ProposalLedger.setStatus: unknown proposal id "${e}"`);n.status=r}aggregateRound(e,r,n=[]){let o=new Set(n),s=[];for(let i of this._proposals.values()){if(i.status!=="open")continue;let a={agree:0,disagree:0,abstain:0,revise:0,missing:0};for(let u of r){if(i.proposerIds.includes(u))continue;let l=i.votes.get(u);if(l===void 0||l.roundRecorded!==e){o.has(u)?a.abstain+=1:a.missing+=1;continue}switch(l.vote){case"agree":a.agree+=1;break;case"disagree":a.disagree+=1;break;case"abstain":a.abstain+=1;break;case"revise":a.revise+=1;break;default:{let d=l.vote}}}let c=rM(a);s.push({proposalId:i.id,tally:a,verdict:c})}return s}getOpenProposals(){return this.selectByStatus("open")}getConsensusProposals(){return this.selectByStatus("consensus")}getUnresolved(){return this.selectByStatus("unresolved")}selectByStatus(e){let r=[];for(let n of this._proposals.values())n.status===e&&r.push(eM(n));return r}toJSON(){let e=Array.from(this._proposals.values()).map(n=>{let o=[];for(let[i,a]of n.votes){let c={voter:i,vote:a.vote,roundRecorded:a.roundRecorded};a.reason!==void 0&&(c.reason=a.reason),a.supersededAt!==void 0&&(c.supersededAt=a.supersededAt),o.push(c)}let s={id:n.id,proposerIds:n.proposerIds.slice(),title:n.title,severity:n.severity,roundOpened:n.roundOpened,status:n.status,votes:o};return n.location!==void 0&&(s.location=n.location),n.description!==void 0&&(s.description=n.description),n.supersededBy!==void 0&&(s.supersededBy=n.supersededBy),n.mergedInto!==void 0&&(s.mergedInto=n.mergedInto),s}),r=this._aliasCandidates.map(n=>({proposalA:n.proposalA,proposalB:n.proposalB,matchedFields:n.matchedFields.slice(),missingField:n.missingField}));return{proposals:e,aliasCandidates:r}}static fromJSON(e){let r=new t,n=new Set;for(let o of e.proposals){if(n.has(o.id))throw new Error(`ProposalLedger.fromJSON: duplicate proposal id "${o.id}"`);n.add(o.id);let s={id:o.id,proposerIds:o.proposerIds.slice(),title:o.title,severity:o.severity,roundOpened:o.roundOpened,status:o.status,votes:new Map};o.location!==void 0&&(s.location=o.location),o.description!==void 0&&(s.description=o.description),o.supersededBy!==void 0&&(s.supersededBy=o.supersededBy),o.mergedInto!==void 0&&(s.mergedInto=o.mergedInto);for(let i of o.votes){let a={vote:i.vote,roundRecorded:i.roundRecorded};i.reason!==void 0&&(a.reason=i.reason),i.supersededAt!==void 0&&(a.supersededAt=i.supersededAt),s.votes.set(i.voter,a)}r._proposals.set(s.id,s)}for(let o of e.aliasCandidates)r._aliasCandidates.push({proposalA:o.proposalA,proposalB:o.proposalB,matchedFields:o.matchedFields.slice(),missingField:o.missingField});return r}_rawProposal(e){return this._proposals.get(e)}_pushAliasCandidate(e){this._aliasCandidates.push(e)}_extendProposers(e,r){let n=this._proposals.get(e);n&&(n.proposerIds=vx(n.proposerIds,r))}_maybeReplaceDescription(e,r){let n=this._proposals.get(e);if(!n||r===void 0)return;let o=n.description??"";r.length>o.length&&(n.description=r)}};function rM(t){return t.disagree>0||t.revise>0?"dissent":t.missing>0?"pending":t.agree>0?"consensus":"pending"}function _x(t){let e=new po,r=new Set;for(let s of t){if(r.has(s.id))throw new Error(`buildInitialLedger: duplicate proposal id "${s.id}"`);r.add(s.id),e.addProposal({id:s.id,proposerIds:[s.proposerId],title:s.title,severity:s.severity,...s.location!==void 0?{location:s.location}:{},...s.description!==void 0?{description:s.description}:{},roundOpened:s.roundOpened??1,status:"open"})}let n=new Set,o=t.map(s=>s.id);for(let s=0;s<o.length;s+=1){let i=o[s];if(n.has(i))continue;let a=e._rawProposal(i);if(a)for(let c=s+1;c<o.length;c+=1){let u=o[c];if(n.has(u))continue;let l=e._rawProposal(u);if(!l)continue;let d=tM(a,l);if(d.kind==="hard-merge"){e._extendProposers(i,l.proposerIds),e._maybeReplaceDescription(i,l.description),e._proposals.delete(u),n.add(u);continue}d.kind==="alias"&&e._pushAliasCandidate(d.pair)}}return{ledger:e,aliasCandidates:e.aliasCandidates}}var nM=new Set(kf);function oM(t){return nM.has(t)}var sM=new Set(["disagree","revise"]);function iM(t){let e=`<${gn}>`,r=`</${gn}>`,n=t.lastIndexOf(r);if(n<0)return null;let o=t.lastIndexOf(e,n);return o<0?null:{inner:t.slice(o+e.length,n)}}function aM(t){let e=`<${gn}>`;return t.includes(e)}var cM=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function uM(t){return t.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g,(e,r)=>{if(r.startsWith("#x")||r.startsWith("#X")){let o=parseInt(r.slice(2),16);return Number.isFinite(o)?String.fromCodePoint(o):e}if(r.startsWith("#")){let o=parseInt(r.slice(1),10);return Number.isFinite(o)?String.fromCodePoint(o):e}return cM[r]??e})}function lM(t){let e={},r=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,n=0,o;for(;(o=r.exec(t))!==null;){if(t.slice(n,o.index).trim().length>0)return null;let i=o[1],a=o[2],c=o[3],u=a!==void 0?a:c??"";if(Object.prototype.hasOwnProperty.call(e,i))return null;e[i]=uM(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function Op(t,e){let r=iM(t);if(!r)return aM(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${gn}> without matching </${gn}>`}}:{ok:!1,error:{kind:"missing-block"}};let n=new Set(e),o=/<item\b([^>]*?)\/>/g,s=[],i;for(;(i=o.exec(r.inner))!==null;)s.push({raw:i[0],attrString:i[1],index:i.index,length:i[0].length});let a=0;for(let p of s){let f=r.inner.slice(a,p.index);if(!bx(f))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected content between <item> elements: ${JSON.stringify(f.slice(0,40))}`}};a=p.index+p.length}let c=r.inner.slice(a);if(!bx(c))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected trailing content: ${JSON.stringify(c.slice(0,40))}`}};let u=[],l=[],d=new Set;for(let p of s){let f=lM(p.attrString);if(f===null){l.push({reason:"malformed-entry",raw:p.raw});continue}let m=f.id,g=f.vote;if(typeof m!="string"||m.length===0||typeof g!="string"){l.push({proposalId:typeof m=="string"&&m.length>0?m:void 0,reason:"malformed-entry",raw:p.raw});continue}if(!oM(g)){l.push({proposalId:m,reason:"unknown-vote",raw:p.raw});continue}if(!n.has(m)){l.push({proposalId:m,reason:"unknown-id",raw:p.raw});continue}if(d.has(m)){l.push({proposalId:m,reason:"duplicate-id",raw:p.raw});continue}let y=f.reason,v=typeof y=="string"&&y.length>0?y:void 0;if(sM.has(g)&&v===void 0){d.add(m),l.push({proposalId:m,reason:"missing-reason",raw:p.raw});continue}d.add(m);let S={proposalId:m,vote:g};v!==void 0&&(S.reason=v),u.push(S)}return{ok:!0,entries:u,entryErrors:l}}function bx(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}var dM=Object.freeze(["same","different","unsure"]),Us="alias-votes",pM=new Set(dM);function fM(t){return pM.has(t)}function mM(t){let e=`<${Us}>`,r=`</${Us}>`,n=t.lastIndexOf(r);if(n<0)return null;let o=t.lastIndexOf(e,n);return o<0?null:{inner:t.slice(o+e.length,n)}}function hM(t){let e=`<${Us}>`;return t.includes(e)}var gM=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function yM(t){return t.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g,(e,r)=>{if(r.startsWith("#x")||r.startsWith("#X")){let o=parseInt(r.slice(2),16);return Number.isFinite(o)?String.fromCodePoint(o):e}if(r.startsWith("#")){let o=parseInt(r.slice(1),10);return Number.isFinite(o)?String.fromCodePoint(o):e}return gM[r]??e})}function vM(t){let e={},r=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,n=0,o;for(;(o=r.exec(t))!==null;){if(t.slice(n,o.index).trim().length>0)return null;let i=o[1],a=o[2],c=o[3],u=a!==void 0?a:c??"";if(Object.prototype.hasOwnProperty.call(e,i))return null;e[i]=yM(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function wx(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}function Mp(t,e){let r=mM(t);if(!r)return hM(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${Us}> without matching </${Us}>`}}:{ok:!1,error:{kind:"missing-block"}};let n=new Set(e),o=/<item\b([^>]*?)\/>/g,s=[],i;for(;(i=o.exec(r.inner))!==null;)s.push({raw:i[0],attrString:i[1],index:i.index,length:i[0].length});let a=0;for(let p of s){let f=r.inner.slice(a,p.index);if(!wx(f))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected content between <item> elements: ${JSON.stringify(f.slice(0,40))}`}};a=p.index+p.length}let c=r.inner.slice(a);if(!wx(c))return{ok:!1,error:{kind:"malformed-xml",details:`unexpected trailing content: ${JSON.stringify(c.slice(0,40))}`}};let u=[],l=[],d=new Set;for(let p of s){let f=vM(p.attrString);if(f===null){l.push({reason:"malformed-entry",raw:p.raw});continue}let m=f.pair,g=f.vote;if(typeof m!="string"||m.length===0||typeof g!="string"){l.push({pair:typeof m=="string"&&m.length>0?m:void 0,reason:"malformed-entry",raw:p.raw});continue}if(!fM(g)){l.push({pair:m,reason:"unknown-vote",raw:p.raw});continue}if(!n.has(m)){l.push({pair:m,reason:"unknown-pair",raw:p.raw});continue}if(d.has(m)){l.push({pair:m,reason:"duplicate-pair",raw:p.raw});continue}let y=f.reason,v=typeof y=="string"&&y.length>0?y:void 0;d.add(m);let S={pair:m,vote:g};v!==void 0&&(S.reason=v),u.push(S)}return{ok:!0,entries:u,entryErrors:l}}var _M="__";function bM(t){return`${t.proposalA}${_M}${t.proposalB}`}var wM=["You are participating in the alias clarification phase of a structured debate.","The moderator has detected the following proposal pairs that partially match","on title / severity / location but did not satisfy the automatic hard-merge","rule. For each pair, decide whether the two proposals describe the SAME","underlying issue or DIFFERENT issues. If you cannot tell from the material","given, answer `unsure` \u2014 there is no penalty for uncertainty here, this","phase is not the main debate."].join(" "),xM=["For every pair below, emit exactly one `<item>` element inside the","`<alias-votes>` block. The `pair` attribute must match the identifier","printed with each pair. The `vote` attribute must be one of:","`same`, `different`, `unsure`. A `reason` attribute is optional but","encouraged when you answer `different` or `unsure`."].join(" "),SM=["Response format \u2014 append the following block at the end of your reply","(moderator parses only this block; preamble is ignored):","","<alias-votes>",' <item pair="P1__P2" vote="same"/>',' <item pair="P3__P4" vote="different" reason="P3 concerns cache invalidation; P4 concerns read-through."/>',' <item pair="P5__P6" vote="unsure" reason="Insufficient detail on location."/>',"</alias-votes>"].join(`
|
|
308
|
+
`),$M="Candidate pairs:";function kM(t,e){return["Your previous response did not include a valid `<alias-votes>` block.",`Problem: ${e}`,"Reply with ONLY the `<alias-votes>` block. Do not include prose.","<alias-votes>",...t.map(r=>` <item pair="${r}" vote="same|different|unsure" reason="optional"/>`),"</alias-votes>"].join(`
|
|
309
|
+
`)}async function Px(t){let{ledger:e,participantIds:r,askParticipant:n}=t,o=e.aliasCandidates;if(o.length===0)return{mergesApplied:[],undecided:[],parseFailures:[]};let s=o.map(bM),i=new Map;for(let f=0;f<o.length;f+=1)i.set(s[f],o[f]);let a=PM(e,o,s),c=await Promise.allSettled(r.map(async f=>{let m=await n(f,a);return{participantId:f,response:m}})),u=[],l=new Map;for(let f of s)l.set(f,{same:0,different:0,unsure:0,missing:0});for(let f=0;f<c.length;f+=1){let m=c[f],g=r[f];if(m.status==="rejected"){u.push({participantId:g,reason:kx(m.reason)}),bc(l,s);continue}let{response:y}=m.value;if(y.failed===!0){u.push({participantId:g,reason:"askParticipant reported failed=true"}),bc(l,s);continue}let v=Mp(y.text,s),S=new Set;if(!v.ok){let w=await n(g,kM(s,v.error.details!==void 0?`${v.error.kind}: ${v.error.details}`:v.error.kind)).catch(P=>({text:"",failed:!0,reason:kx(P)}));if(w.failed===!0){u.push({participantId:g,reason:"reason"in w&&typeof w.reason=="string"?w.reason:"retry failed"}),bc(l,s);continue}let _=Mp(w.text,s);if(!_.ok){u.push({participantId:g,reason:_.error.details!==void 0?`${_.error.kind}: ${_.error.details}`:_.error.kind}),bc(l,s);continue}for(let P of _.entries)$x(l,P),S.add(P.pair);for(let P of s)if(!S.has(P)){let A=l.get(P);A!==void 0&&(A.missing+=1)}continue}for(let w of v.entries)$x(l,w),S.add(w.pair);for(let w of s)if(!S.has(w)){let _=l.get(w);_!==void 0&&(_.missing+=1)}}let d=[],p=[];for(let f of s){let m=i.get(f),g=l.get(f);if(m===void 0||g===void 0)continue;let y=EM(g);if(y.kind==="merge"){let v=m.proposalA,S=m.proposalB;if(e.proposals.get(v)===void 0||e.proposals.get(S)===void 0)continue;e.applyAliasMerge(v,S),d.push({primary:v,alias:S,voteBreakdown:{...g}});continue}p.push({pair:m,voteBreakdown:{...g},reason:y.reason})}return{mergesApplied:d,undecided:p,parseFailures:u}}function PM(t,e,r){let n=[];n.push(wM),n.push(""),n.push(xM),n.push(""),n.push($M),n.push("");for(let o=0;o<e.length;o+=1){let s=e[o],i=r[o],a=t.proposals.get(s.proposalA),c=t.proposals.get(s.proposalB);n.push(`Pair ${o+1} \u2014 pair="${i}"`),n.push(` matched fields: ${s.matchedFields.join(", ")||"(none)"}`),n.push(` blocking field: ${s.missingField}`),n.push(" Proposal A:"),xx(n,a),n.push(" Proposal B:"),xx(n,c),n.push("")}return n.push(SM),n.join(`
|
|
310
|
+
`)}function xx(t,e){if(e===void 0){t.push(" (proposal unavailable \u2014 already removed from ledger)");return}if(t.push(` id: ${e.id}`),t.push(` title: ${e.title}`),t.push(` severity: ${e.severity}`),t.push(` location: ${e.location!==void 0&&e.location.length>0?e.location:"(empty)"}`),e.description!==void 0&&e.description.length>0){let r=TM(e.description);t.push(` description: ${r}`)}}var Sx=400;function TM(t){return t.length<=Sx?t:`${t.slice(0,Sx)}\u2026`}function $x(t,e){let r=t.get(e.pair);if(r!==void 0)switch(e.vote){case"same":r.same+=1;break;case"different":r.different+=1;break;case"unsure":r.unsure+=1;break;default:{let n=e.vote}}}function bc(t,e){for(let r of e){let n=t.get(r);n!==void 0&&(n.missing+=1)}}function EM(t){return t.same===0&&t.different===0?{kind:"undecided",reason:"no-votes"}:t.same>t.different?{kind:"merge"}:t.same===t.different?{kind:"undecided",reason:"tie"}:{kind:"undecided",reason:"different-majority"}}function kx(t){if(t instanceof Error)return`askParticipant threw: ${t.message}`;try{return`askParticipant threw: ${String(t)}`}catch{return"askParticipant threw: <unstringifiable>"}}import{readdir as RM}from"fs/promises";import{readFileSync as IM,existsSync as Np,unlinkSync as AM,mkdirSync as CM}from"fs";import{join as qs}from"path";var Lp=".approval.json";function jp(t){return`${t}${Lp}`}function DM(t){return t.endsWith(Lp)?t.slice(0,t.length-Lp.length):null}function Tx(t){let e=Date.parse(t);if(Number.isNaN(e))throw new Error(`computeApprovalDeadline: invalid readyAt ISO string: ${t}`);return new Date(e+Pf).toISOString()}var fo=class{debatesDir;cache=new Map;hydrated=!1;constructor(e){if(!e||typeof e!="string")throw new Error("StructuredSessionRegistry: baseDir is required");this.debatesDir=qs(e,Hs)}getDebatesDir(){return this.debatesDir}async persist(e){if(!e||!e.sessionId)throw new Error("StructuredSessionRegistry.persist: snapshot.sessionId is required");if(e.schemaVersion!==1)throw new Error(`StructuredSessionRegistry.persist: unsupported schemaVersion=${e.schemaVersion}`);CM(this.debatesDir,{recursive:!0});let r=qs(this.debatesDir,jp(e.sessionId));je(r,e),this.cache.set(e.sessionId,e)}async load(e){let r=this.cache.get(e);if(r)return r;let n=qs(this.debatesDir,jp(e));if(!Np(n))return null;let o=this.readSnapshotFile(n);return o&&this.cache.set(e,o),o}async remove(e){this.cache.delete(e);let r=qs(this.debatesDir,jp(e));if(Np(r))try{AM(r)}catch(n){if(n.code!=="ENOENT")throw n}}async hydrateFromDisk(){if(this.cache.clear(),!Np(this.debatesDir)){this.hydrated=!0;return}let e;try{e=await RM(this.debatesDir)}catch(r){if(r.code==="ENOENT"){this.hydrated=!0;return}throw r}for(let r of e){let n=DM(r);if(!n)continue;let o=this.readSnapshotFile(qs(this.debatesDir,r));o&&o.sessionId===n&&this.cache.set(n,o)}this.hydrated=!0}get(e){return this.cache.get(e)}getAll(){return Array.from(this.cache.values())}async sweepTimeouts(e=new Date){let r=e.getTime(),n=[],o=[];for(let s of this.cache.values()){if(s.status!=="ready-for-approval")continue;let i=Date.parse(s.deadline);if(Number.isNaN(i)||r<=i)continue;let a={...s,status:"leader-timeout",terminalNote:s.terminalNote??"leader-timeout after approval window"};try{await this.persist(a),n.push(a)}catch(c){o.push({sessionId:s.sessionId,error:c})}}return o.length>0&&console.warn(`[session-registry] sweepTimeouts: ${o.length} snapshot(s) failed to transition; will retry on next sweep`,o.map(s=>({sessionId:s.sessionId,message:s.error instanceof Error?s.error.message:String(s.error)}))),n}isHydrated(){return this.hydrated}readSnapshotFile(e){let r;try{r=IM(e,"utf-8")}catch(o){if(o.code==="ENOENT")return null;throw o}let n;try{n=JSON.parse(r)}catch{return console.warn(`[session-registry] skipping unparseable snapshot file: ${e}`),null}return zM(n)?n:(console.warn(`[session-registry] skipping snapshot with unexpected shape: ${e}`),null)}};function zM(t){if(!t||typeof t!="object")return!1;let e=t;return e.schemaVersion===1&&typeof e.sessionId=="string"&&typeof e.status=="string"&&typeof e.createdAt=="string"&&typeof e.readyAt=="string"&&typeof e.deadline=="string"&&typeof e.config=="object"&&e.config!==null&&typeof e.rounds=="number"&&Array.isArray(e.aggregatedVotes)&&typeof e.documentPaths=="object"&&e.documentPaths!==null}function OM(t,e){let r=[];r.push(...jM(t,e)),r.push(""),r.push(...Rx(t,e));let n=Ix(t,e);return n.length>0&&(r.push(""),r.push(...n)),r.push(""),r.push(...Ax(t,e)),r.push(""),r.push(...FM(t,e)),r.join(`
|
|
311
|
+
`)}function MM(t,e){let r=[];r.push(...Rx(t,e));let n=ZM(t,e);n.length>0&&(r.push(""),r.push(...n));let o=UM(t,e);o.length>0&&(r.push(""),r.push(...o));let s=qM(t,e);s.length>0&&(r.push(""),r.push(...s));let i=Ix(t,e);return i.length>0&&(r.push(""),r.push(...i)),r.push(""),r.push(...Ax(t,e)),r.join(`
|
|
312
|
+
`)}function Ex(){return{renderTerminal:OM,renderSynthesis:MM}}var NM=Object.freeze({running:"report.status.running","ready-for-approval":"report.status.readyForApproval",consensus:"report.status.consensus",escalated:"report.status.escalated",approved:"report.status.approved",rejected:"report.status.rejected","leader-timeout":"report.status.leaderTimeout",error:"report.status.error"});function jM(t,e){let r=e.t(NM[t.status]),n=e.t("report.header.topic"),o=e.t("report.header.participants"),s=e.t("report.header.individualDocs"),i=[`## ${n}: ${t.topic} (${t.rounds}/${t.maxRounds} \u2014 ${r})`,`## ${o}: ${t.participantIds.join(", ")}`,`## ${s}:`],a=Math.min(t.participantIds.length,t.individualPaths.length);for(let c=0;c<a;c+=1)i.push(` - ${t.participantIds[c]}: ${t.individualPaths[c]}`);return i}function Rx(t,e){let r=[`## ${e.t("report.section.mainTable")}`,"",`| ${e.t("report.table.proposer")} | ${e.t("report.table.opinion")} | ${e.t("report.table.severity")} | ${e.t("report.table.agreement")} |`,"|---|---|---|---|"];for(let n of t.proposals){let o=n.proposerIds.join(", "),s=LM(n);r.push(`| ${o} | ${n.title} | ${n.severity} | ${s} |`)}return r}function LM(t){let e=`${t.agreeCount}/${t.totalVoters}`;return t.accepted||t.dissentSummary===void 0||t.dissentSummary.length===0?e:`${e} (${t.dissentSummary})`}function Ix(t,e){if(t.dissentDetails.length===0)return[];let r=[`## ${e.t("report.section.dissentDetail")}`];for(let n of t.dissentDetails){r.push(""),r.push(`### ${n.proposalTitle} (${n.severity})`);for(let o of n.perParticipant)r.push(Fp(o))}return r}function Fp(t){let e=`- **${t.participantId}:** ${t.vote}`;return t.reason===void 0||t.reason.length===0?e:`${e} \u2014 ${t.reason}`}function Ax(t,e){let r=`| ${e.t("report.contribution.ai")} | ${e.t("report.contribution.proposed")} | ${e.t("report.contribution.accepted")} | ${e.t("report.contribution.revises")} | ${e.t("report.contribution.abstains")} |`,n=[`## ${e.t("report.section.contributionSummary")}`,"",r,"|---|---|---|---|---|"];for(let o of t.contributionSummary){let s=o.proposed===0?"\u2014":String(o.consensusReceived);n.push(`| ${o.participantId} | ${o.proposed} | ${s} | ${o.revisesProposed} | ${o.abstains} |`)}return n}function FM(t,e){let r=e.t("report.footer.synthesisPath"),n=e.t("report.footer.debatePath"),o=t.synthesisPath??e.t("report.footer.pendingSynthesis"),s=[`## ${r}: ${o}`,`## ${n}: ${t.debatePath}`];return t.status==="ready-for-approval"&&(s.push(""),s.push(e.t("approval.pending"))),s}function ZM(t,e){let r=t.acceptedItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.acceptedItems")}`];for(let o of r)n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),n.push(`**${e.t("report.table.proposer")}:** ${o.proposerIds.join(", ")}`),n.push(`**${e.t("report.table.agreement")}:** ${o.agreeCount}/${o.totalVoters}`),o.finalStatement.length>0&&(n.push(""),n.push(o.finalStatement));return n}function UM(t,e){let r=t.rejectedItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.rejectedItems")}`];for(let o of r){n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),o.rejectionReason.length>0&&(n.push(""),n.push(o.rejectionReason));for(let s of o.dissentVotes)n.push(Fp(s))}return n}function qM(t,e){let r=t.openItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.openItems")}`];for(let o of r){n.push(""),n.push(`### ${o.id} \u2014 ${o.title}`),n.push(`**${e.t("report.table.severity")}:** ${o.severity}`),n.push(`**${e.t("report.table.agreement")}:** ${o.agreeCount}/${o.totalVoters}`);for(let s of o.perParticipant)n.push(Fp(s))}return n}var mo=class{deps;sessions=new Map;formatter=Ex();constructor(e){this.deps=e}async startDebate(e){let r=(this.deps.generateSessionId??VM)(),n=this.nowIso(),o=ux({topic:e.topic,...e.goal!==void 0?{goal:e.goal}:{},participants:e.participants,excludeParticipants:e.excludeParticipants??[],autoInjectSpecialists:e.autoInjectSpecialists??!0}),s=o.participants,i={topic:e.topic,scope:e.scope??e.topic,participants:s,excludeParticipants:e.excludeParticipants??[],leader:e.leader,maxRounds:e.maxRounds??jc,locale:e.locale??this.deps.i18n.locale,autoInjectSpecialists:e.autoInjectSpecialists??!0},a=await this.deps.documentManager.createDebateDocument({topic:e.topic,providers:s.slice(),...e.goal!==void 0?{goal:e.goal}:{}}),c={sessionId:r,config:i,goal:e.goal,individualReviewPrompt:e.individualReviewPrompt,files:e.files??[],debateDocId:a.id,debateDocPath:a.path,individualPaths:{},createdAt:n,ledger:new po,rounds:0,maxRounds:i.maxRounds,consecutiveFailures:new Map,unavailableParticipants:new Set,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:1};this.sessions.set(r,c);try{let u=await this.runIndividualPhase(c,o),{ledger:l}=_x(u);c.ledger=l,c.nextProposalIndex=YM(u),l.aliasCandidates.length>0&&await this.runAliasClarificationPhase(c),await this.runRoundLoop(c);let d=this.buildSnapshot(c,Cx(c));return await this.deps.registry.persist(d),this.emitTrace(c,"debate_rfa",{status:d.status}),{sessionId:r,status:d.status,snapshot:d,terminalReport:this.renderTerminal(c,d)}}catch(u){let l=this.buildSnapshot(c,"error",wc(u));try{await this.deps.registry.persist(l)}catch{}return this.emitTrace(c,"debate_error",{error:wc(u)}),{sessionId:r,status:"error",snapshot:l,terminalReport:this.renderTerminal(c,l),errorMessage:wc(u)}}}async approve(e){let r=await this.loadSnapshotOrThrow(e.sessionId);if(r.status==="approved"){if(!r.documentPaths.synthesis)throw new Error(`approve: session "${e.sessionId}" is marked approved but has no synthesis path recorded. Snapshot is inconsistent.`);let u=this.sessions.get(e.sessionId);return{snapshot:r,synthesisPath:r.documentPaths.synthesis,terminalReport:this.renderTerminal(u??null,r),idempotentReplay:!0}}Zp(r,["ready-for-approval","escalated"],"approve");let n=this.sessions.get(e.sessionId),o=n?this.buildReportData(n,r,e.leaderNote):zx(r,e.leaderNote),s=this.formatter.renderSynthesis(o,this.deps.i18n),i=(r.status==="escalated"||r.status==="ready-for-approval")&&r.status==="escalated"?"escalated":"consensus",a=await this.deps.documentManager.createSynthesis({sessionId:r.sessionId,topic:r.config.topic,status:i,rounds:r.rounds,maxRounds:r.config.maxRounds,participantIds:r.config.participants,individualPaths:Object.values(r.documentPaths.individual),debatePath:r.documentPaths.debate,body:s,...e.leaderNote!==void 0?{metadata:{"Leader Note":e.leaderNote}}:{}});await this.deps.documentManager.addComment(n?.debateDocId??xc(r),{author:"moderator",content:this.formatApprovalFooter(e.leaderNote)});let c={...r,status:"approved",documentPaths:{...r.documentPaths,synthesis:a.path}};return await this.deps.registry.persist(c),this.emitTrace(n??null,"debate_approved",{sessionId:r.sessionId,synthesisPath:a.path}),{snapshot:c,synthesisPath:a.path,terminalReport:this.renderTerminal(n??null,c)}}async continueDebate(e){if(!Number.isInteger(e.additionalRounds)||e.additionalRounds<=0)throw new Error(`continueDebate: additionalRounds must be a positive integer (got ${e.additionalRounds})`);let r=await this.loadSnapshotOrThrow(e.sessionId);Zp(r,["ready-for-approval","escalated"],"continue");let n=this.sessions.get(e.sessionId);if(!n){if(!r.ledgerState)throw new Error(`continueDebate: snapshot for session "${e.sessionId}" is too old to resume after restart \u2014 missing ledgerState. Use approve or reject instead, or rerun the debate.`);n=this.rehydrateSessionContext(r),this.sessions.set(e.sessionId,n)}n.maxRounds=r.config.maxRounds+e.additionalRounds;for(let i of n.ledger.proposals.values())i.status;await this.runRoundLoop(n);let o=Cx(n),s=this.buildSnapshot(n,o);return await this.deps.registry.persist(s),this.emitTrace(n,"debate_continued",{additionalRounds:e.additionalRounds,status:s.status}),{snapshot:s,terminalReport:this.renderTerminal(n,s)}}async reject(e){let r=await this.loadSnapshotOrThrow(e.sessionId);if(r.status==="rejected")return{snapshot:r,idempotentReplay:!0,...r.documentPaths.issue!==void 0?{issuePath:r.documentPaths.issue}:{}};Zp(r,["ready-for-approval","escalated","leader-timeout"],"reject");let n=this.sessions.get(e.sessionId),o=n?.debateDocId??xc(r);await this.deps.documentManager.addComment(o,{author:"moderator",content:this.formatRejectionFooter(e.reason)});let s;e.spawnIssue===!0&&(s=(await this.deps.documentManager.createIssueDocument({sessionId:r.sessionId,topic:r.config.topic,...e.reason!==void 0?{reason:e.reason}:{},items:JM(r)})).path);let i={...r,status:"rejected",terminalNote:e.reason??r.terminalNote,documentPaths:{...r.documentPaths,...s!==void 0?{issue:s}:{}}};return await this.deps.registry.persist(i),this.emitTrace(n??null,"debate_rejected",{sessionId:r.sessionId,...s!==void 0?{issuePath:s}:{}}),{snapshot:i,...s!==void 0?{issuePath:s}:{}}}async handleTimedOutSnapshots(e){for(let r of e){if(r.status!=="leader-timeout")continue;let n=xc(r);try{await this.deps.documentManager.addComment(n,{author:"moderator",content:this.formatLeaderTimeoutFooter(r)})}catch{}this.emitTrace(this.sessions.get(r.sessionId)??null,"debate_leader_timeout",{sessionId:r.sessionId})}}async runIndividualPhase(e,r){let n=oN(),o=sN(e),s=await Promise.allSettled(e.config.participants.map(async a=>{let c=await this.deps.bridge.requestTurn(a,{prompt:o,system:e.individualReviewPrompt??n,round:0,...e.files.length>0?{files:e.files}:{}});return{participantId:a,resp:c}})),i=[];for(let a of s){if(a.status==="rejected")continue;let{participantId:c,resp:u}=a.value,l=u.failed?`(no response: ${u.failureReason??"unknown"})`:u.text,d=await this.deps.documentManager.createIndividualReview({participantId:c,topic:e.config.topic,content:l,...e.files.length>0?{files:e.files}:{}});if(e.individualPaths[c]=d.path,u.failed)continue;let p=nN(u.text);for(let f of p){let m=Dx(e,f.id);i.push({id:m,proposerId:c,title:f.title,severity:f.severity,...f.location!==void 0?{location:f.location}:{},...f.description!==void 0?{description:f.description}:{},roundOpened:1})}}return i}async runAliasClarificationPhase(e){let r=await Px({ledger:e.ledger,participantIds:e.config.participants,askParticipant:async(o,s)=>{let i=await this.deps.bridge.requestTurn(o,{prompt:s,round:0,...e.files.length>0?{files:e.files}:{}});return i.failed?{text:"",failed:!0}:{text:i.text}}}),n=lN(r,this.deps.i18n);n.length>0&&await this.deps.documentManager.addComment(e.debateDocId,{author:"moderator",content:n})}async runRoundLoop(e){for(;e.rounds<e.maxRounds;){if(e.ledger.getOpenProposals().map(p=>p.id).length===0)return;e.rounds+=1;let n=e.rounds,o=e.config.participants.filter(p=>!e.unavailableParticipants.has(p)),s=e.ledger.getOpenProposals(),i=e.pendingVoteWarnings,a=new Map,c=await Promise.allSettled(o.map(async p=>{let f={prompt:iN({round:n,maxRounds:e.maxRounds,topic:e.config.topic,scope:e.config.scope,openProposals:s,previousVoteIssues:i.get(p)}),round:n,...e.files.length>0?{files:e.files}:{}},m=await this.deps.bridge.requestTurn(p,f);return{participantId:p,request:f,resp:m}})),u=[],l=new Set;for(let p=0;p<c.length;p+=1){let f=c[p],m=o[p];if(f.status==="rejected"||f.value.resp.failed){this.registerFailure(e,m);let y=f.status==="rejected"?wc(f.reason):f.value.resp.failureReason??"unknown";u.push({participantId:m,text:`(no response: ${y})`,failed:!0});continue}l.add(m);let g=await this.parseVotesWithRetry(m,f.value.request,f.value.resp.text,s,n);if(u.push({participantId:m,text:g.displayText,failed:!g.ok}),!g.ok){this.registerFailure(e,m),a.set(m,g.warnings);continue}this.clearFailure(e,m);for(let y of g.parsed.entries)e.ledger.recordVote(y.proposalId,m,{vote:y.vote,roundRecorded:n,...y.reason!==void 0?{reason:y.reason}:{}});g.parsed.entryErrors.length>0&&a.set(m,cN(g.parsed.entryErrors))}e.pendingVoteWarnings=a;let d=e.ledger.aggregateRound(n,e.config.participants,Array.from(e.unavailableParticipants));for(let p of d){let f=e.ledger.proposals.get(p.proposalId);if(!f)continue;let m=e.config.participants.filter(g=>!f.proposerIds.includes(g)).length;if(WM(p.tally,m)){e.ledger.setStatus(p.proposalId,"consensus"),e.allAbstainCount.delete(p.proposalId);continue}if(HM(p.tally,m)){e.ledger.setStatus(p.proposalId,"rejected"),e.allAbstainCount.delete(p.proposalId);continue}if(KM(p.tally)){let g=(e.allAbstainCount.get(p.proposalId)??0)+1;e.allAbstainCount.set(p.proposalId,g),g>=Fc&&(e.ledger.setStatus(p.proposalId,"unresolved"),e.allAbstainCount.delete(p.proposalId));continue}e.allAbstainCount.delete(p.proposalId)}for(let p of d){if(p.tally.revise===0)continue;let f=e.ledger.proposals.get(p.proposalId);if(!f||f.status!=="open"||e.ledger.countRevisesThisRound(p.proposalId,n)===0)continue;let g=this.synthesizeReviseSuccessor(e,f,n);e.reviseSuccessors.set(f.id,g)}if(await this.deps.documentManager.addComment(e.debateDocId,{author:"moderator",content:uN({round:n,maxRounds:e.maxRounds,openProposals:s,turns:u,aggregation:d,ledger:e.ledger})}),l.size===0)return}}async parseVotesWithRetry(e,r,n,o,s){let i=o.map(p=>p.id),a=Op(n,i);if(a.ok)return{ok:!0,parsed:a,displayText:n};let c={prompt:aN({openProposals:o,errorKind:a.error.kind,errorDetails:a.error.details}),round:s,...r.files!==void 0?{files:r.files}:{}},u=await this.deps.bridge.requestTurn(e,c);if(u.failed)return{ok:!1,displayText:`${n}
|
|
297
313
|
|
|
298
|
-
[retry failed: ${u.failureReason??"unknown"}]`,warnings:[`Missing or malformed <votes> block (${a.error.kind}). Retry failed: ${u.failureReason??"unknown"}.`]};let l=
|
|
314
|
+
[retry failed: ${u.failureReason??"unknown"}]`,warnings:[`Missing or malformed <votes> block (${a.error.kind}). Retry failed: ${u.failureReason??"unknown"}.`]};let l=Op(u.text,i),d=`${n}
|
|
299
315
|
|
|
300
316
|
[retry response]
|
|
301
|
-
${u.text}`;return l.ok?{ok:!0,parsed:l,displayText:d}:{ok:!1,displayText:d,warnings:[`Missing or malformed <votes> block (${l.error.kind}).${l.error.details?` ${l.error.details}`:""}`]}}registerFailure(e,r){let n=(e.consecutiveFailures.get(r)??0)+1;e.consecutiveFailures.set(r,n),n>=
|
|
317
|
+
${u.text}`;return l.ok?{ok:!0,parsed:l,displayText:d}:{ok:!1,displayText:d,warnings:[`Missing or malformed <votes> block (${l.error.kind}).${l.error.details?` ${l.error.details}`:""}`]}}registerFailure(e,r){let n=(e.consecutiveFailures.get(r)??0)+1;e.consecutiveFailures.set(r,n),n>=Lc&&e.unavailableParticipants.add(r)}clearFailure(e,r){e.consecutiveFailures.delete(r)}synthesizeReviseSuccessor(e,r,n){let o=Dx(e),s=[];for(let[,a]of r.votes)a.vote==="revise"&&a.roundRecorded===n&&a.reason&&s.push(a.reason);let i=s.length>0?`Revised from ${r.id}: ${s.join(" / ")}`:`Revised from ${r.id}`;return e.ledger.addProposal({id:o,proposerIds:r.proposerIds,title:`${r.title} (revised)`,severity:r.severity,...r.location!==void 0?{location:r.location}:{},description:i,roundOpened:n+1}),e.ledger.markSuperseded(r.id,o,n),o}rehydrateSessionContext(e){if(!e.ledgerState)throw new Error(`rehydrateSessionContext: snapshot "${e.sessionId}" has no ledgerState`);let r=po.fromJSON(e.ledgerState),n=new Map;if(e.consecutiveFailuresByParticipant)for(let[a,c]of Object.entries(e.consecutiveFailuresByParticipant))c>0&&n.set(a,c);let o=new Set(e.unavailableParticipants??[]),s=0;for(let a of e.ledgerState.proposals.map(c=>c.id)){let c=a.match(/^P(\d+)$/);if(c){let u=Number.parseInt(c[1],10);Number.isFinite(u)&&u>s&&(s=u)}}return{sessionId:e.sessionId,config:e.config,goal:void 0,individualReviewPrompt:void 0,files:[],debateDocId:xc(e),debateDocPath:e.documentPaths.debate,individualPaths:{...e.documentPaths.individual},createdAt:e.createdAt,ledger:r,rounds:e.rounds,maxRounds:e.config.maxRounds,consecutiveFailures:n,unavailableParticipants:o,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:s+1}}buildSnapshot(e,r,n){let o=this.nowIso(),s=BM(r)?hx(o,Tx):o,i=this.snapshotAggregatedVotes(e),a={};for(let[u,l]of e.consecutiveFailures)l>0&&(a[u]=l);return{schemaVersion:1,sessionId:e.sessionId,status:r,createdAt:e.createdAt,readyAt:o,deadline:s,config:{...e.config,maxRounds:e.maxRounds},rounds:e.rounds,aggregatedVotes:i,documentPaths:{individual:{...e.individualPaths},debate:e.debateDocPath},ledgerState:e.ledger.toJSON(),...Object.keys(a).length>0?{consecutiveFailuresByParticipant:a}:{},...e.unavailableParticipants.size>0?{unavailableParticipants:Array.from(e.unavailableParticipants)}:{},...n!==void 0?{terminalNote:n}:{}}}snapshotAggregatedVotes(e){let r=[];for(let n of e.ledger.proposals.values()){if(n.status==="merged")continue;let o={};for(let[s,i]of n.votes)o[s]={vote:i.vote,roundRecorded:i.roundRecorded,...i.reason!==void 0?{reason:i.reason}:{}};r.push({proposalId:n.id,title:n.title,severity:n.severity,...n.location!==void 0?{location:n.location}:{},proposers:n.proposerIds,status:GM(n.status),votes:o,...n.supersededBy!==void 0?{supersededBy:n.supersededBy}:{}})}return r}renderTerminal(e,r){let n=e?this.buildReportData(e,r):zx(r);return this.formatter.renderTerminal(n,this.deps.i18n)}buildReportData(e,r,n){let o=[],s=[],i=[],a=[],c=[];for(let l of e.ledger.proposals.values()){if(l.status==="merged"||l.status==="superseded")continue;let d=e.config.participants.filter(f=>!l.proposerIds.includes(f)),p=XM(l,d);o.push({proposerIds:l.proposerIds,title:l.title,severity:l.severity,agreeCount:p.agree,totalVoters:p.denominator,accepted:l.status==="consensus",...p.dissentSummary!==void 0?{dissentSummary:p.dissentSummary}:{}}),p.perParticipant.length>0&&l.status!=="consensus"&&s.push({proposalTitle:l.title,severity:l.severity,perParticipant:p.perParticipant}),l.status==="consensus"?i.push({id:l.id,proposerIds:l.proposerIds,title:l.title,severity:l.severity,agreeCount:p.agree,totalVoters:p.denominator,finalStatement:l.description??""}):l.status==="rejected"||l.status==="withdrawn-by-author"?a.push({id:l.id,title:l.title,severity:l.severity,rejectionReason:l.status==="withdrawn-by-author"?"Withdrawn by author":"Rejected by tally",dissentVotes:p.perParticipant}):(l.status==="open"||l.status==="unresolved")&&c.push({id:l.id,title:l.title,severity:l.severity,agreeCount:p.agree,totalVoters:p.denominator,perParticipant:p.perParticipant})}let u=QM(e);return{topic:e.config.topic,rounds:e.rounds,maxRounds:e.maxRounds,status:Ox(r.status),participantIds:e.config.participants,individualPaths:Object.values(e.individualPaths),debatePath:e.debateDocPath,...r.documentPaths.synthesis!==void 0?{synthesisPath:r.documentPaths.synthesis}:{},proposals:o,contributionSummary:u,dissentDetails:s,acceptedItems:i,rejectedItems:a,openItems:c,...n!==void 0?{leaderNote:n}:{}}}nowIso(){return(this.deps.now?this.deps.now():new Date).toISOString()}async loadSnapshotOrThrow(e){let r=await this.deps.registry.load(e);if(!r)throw new Error(`Structured debate session "${e}" not found`);return r}formatApprovalFooter(e){let r=this.deps.i18n.t("moderator.narration.approved");if(!e)return r;let n=this.deps.i18n.t("synthesis.narration.leaderNote");return`${r}
|
|
302
318
|
|
|
303
319
|
**${n}:** ${e}`}formatRejectionFooter(e){let r=this.deps.i18n.t("moderator.narration.rejected");return e?`${r}
|
|
304
320
|
|
|
305
321
|
Reason: ${e}`:r}formatLeaderTimeoutFooter(e){let r=this.deps.i18n.t("moderator.narration.leaderTimeoutFooter"),n=Date.parse(e.readyAt),o=Date.parse(e.deadline),s=Number.isFinite(n)&&Number.isFinite(o)&&o>n?Math.round((o-n)/(3600*1e3)):24,i=this.deps.i18n.t("approval.timeout",{hours:s});return`## ${r}
|
|
306
322
|
|
|
307
|
-
${i}`}emitTrace(e,r,n){if(this.deps.traceWriter)try{this.deps.traceWriter.write({traceId:e?.sessionId??"unknown",action:r,providerId:"moderator-engine",task:e?.config.topic??"",request:{promptSummary:JSON.stringify(n),fileCount:0},response:{success:!0,charLength:0},latencyMs:0})}catch{}}};function
|
|
308
|
-
`)}function
|
|
309
|
-
`)}function
|
|
310
|
-
`)}function
|
|
311
|
-
`)}function
|
|
312
|
-
`)}function
|
|
313
|
-
`)}var
|
|
323
|
+
${i}`}emitTrace(e,r,n){if(this.deps.traceWriter)try{this.deps.traceWriter.write({traceId:e?.sessionId??"unknown",action:r,providerId:"moderator-engine",task:e?.config.topic??"",request:{promptSummary:JSON.stringify(n),fileCount:0},response:{success:!0,charLength:0},latencyMs:0})}catch{}}};function VM(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return`s-${t}-${e}`}function Cx(t){for(let e of t.ledger.proposals.values())if(e.status==="open")return"escalated";return"ready-for-approval"}function BM(t){return t==="ready-for-approval"||t==="escalated"}function WM(t,e){return e===0?t.agree===0&&!1:t.disagree>0||t.revise>0||t.missing>0||t.agree<1?!1:t.agree+t.abstain===e}function HM(t,e){if(e===0||t.agree>0||t.revise>0)return!1;let r=Math.ceil(e/2);return t.disagree>=r}function KM(t){return t.abstain>0&&t.agree===0&&t.disagree===0&&t.revise===0&&t.missing===0}function Zp(t,e,r){if(!e.includes(t.status))throw new Error(`Operation \`${r}\` is not allowed in state \`${t.status}\`. Allowed states: ${e.join(", ")}`)}function GM(t){switch(t){case"consensus":return"accepted";case"rejected":return"rejected";case"withdrawn-by-author":return"withdrawn-by-author";case"superseded":return"superseded";case"unresolved":return"inconclusive";default:return"open"}}function Ox(t){switch(t){case"running":return"running";case"ready-for-approval":return"ready-for-approval";case"escalated":return"escalated";case"approved":return"approved";case"rejected":return"rejected";case"leader-timeout":return"leader-timeout";default:return"error"}}function wc(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"<unstringifiable error>"}}function xc(t){let e=t.documentPaths.debate;return(e.split(/[\\/]/).pop()??e).replace(/\.md$/,"")}function JM(t){let e=[];for(let r of t.aggregatedVotes){if(r.status==="accepted")continue;let n={agree:0,disagree:0,abstain:0,revise:0,total:0};for(let o of Object.values(r.votes))switch(n.total+=1,o.vote){case"agree":n.agree+=1;break;case"disagree":n.disagree+=1;break;case"abstain":n.abstain+=1;break;case"revise":n.revise+=1;break}e.push({title:r.title,severity:r.severity,status:r.status,proposerIds:r.proposers,...r.location!==void 0?{location:r.location}:{},votes:n})}return e}function YM(t){let e=0;for(let r of t){let n=r.id.match(/^P(\d+)$/);if(n){let o=Number.parseInt(n[1],10);Number.isFinite(o)&&o>e&&(e=o)}}return e+1}function Dx(t,e){let r=`P${t.nextProposalIndex}`;return t.nextProposalIndex+=1,r}function XM(t,e){let r=0,n=0,o=[];for(let a of e){let c=t.votes.get(a);if(!c){o.push({participantId:a,vote:"missing"});continue}o.push({participantId:a,vote:c.vote,...c.reason!==void 0?{reason:c.reason}:{}}),c.vote==="agree"?r+=1:c.vote==="abstain"&&(n+=1)}let s=e.length-n,i=[];for(let a of o)a.vote==="agree"||a.vote==="abstain"||i.push(`${a.participantId} ${a.vote}`);return{agree:r,denominator:s,perParticipant:o,...i.length>0?{dissentSummary:i.join(", ")}:{}}}function QM(t){let e=new Map;for(let r of t.config.participants)e.set(r,{proposed:0,consensusReceived:0,revisesProposed:0,abstains:0});for(let r of t.ledger.proposals.values())if(r.status!=="merged"){for(let n of r.proposerIds){let o=e.get(n);o&&(o.proposed+=1,r.status==="consensus"&&(o.consensusReceived+=1))}for(let[n,o]of r.votes){let s=e.get(n);s&&(o.vote==="revise"&&(s.revisesProposed+=1),o.vote==="abstain"&&(s.abstains+=1))}}return Array.from(e.entries()).map(([r,n])=>({participantId:r,proposed:n.proposed,consensusReceived:n.consensusReceived,revisesProposed:n.revisesProposed,abstains:n.abstains}))}function zx(t,e){let r=[],n=[],o=[],s=[],i=[];for(let a of t.aggregatedVotes){let c=t.config.participants.filter(m=>!a.proposers.includes(m)),u=c.map(m=>{let g=a.votes[m];return g?{participantId:m,vote:g.vote,...g.reason!==void 0?{reason:g.reason}:{}}:{participantId:m,vote:"missing"}}),l=0,d=0;for(let m of u)m.vote==="agree"?l+=1:m.vote==="abstain"&&(d+=1);let p=c.length-d;r.push({proposerIds:a.proposers,title:a.title,severity:a.severity,agreeCount:l,totalVoters:p,accepted:a.status==="accepted"}),a.status==="accepted"?n.push({id:a.proposalId,proposerIds:a.proposers,title:a.title,severity:a.severity,agreeCount:l,totalVoters:p,finalStatement:""}):a.status==="rejected"||a.status==="withdrawn-by-author"?o.push({id:a.proposalId,title:a.title,severity:a.severity,rejectionReason:a.status==="withdrawn-by-author"?"Withdrawn by author":"Rejected by tally",dissentVotes:u}):a.status==="open"&&s.push({id:a.proposalId,title:a.title,severity:a.severity,agreeCount:l,totalVoters:p,perParticipant:u}),u.some(m=>m.vote!=="agree"&&m.vote!=="abstain")&&a.status!=="accepted"&&i.push({proposalTitle:a.title,severity:a.severity,perParticipant:u})}return{topic:t.config.topic,rounds:t.rounds,maxRounds:t.config.maxRounds,status:Ox(t.status),participantIds:t.config.participants,individualPaths:Object.values(t.documentPaths.individual),debatePath:t.documentPaths.debate,...t.documentPaths.synthesis!==void 0?{synthesisPath:t.documentPaths.synthesis}:{},proposals:r,contributionSummary:[],dissentDetails:i,acceptedItems:n,rejectedItems:o,openItems:s}}var eN=/<proposals>([\s\S]*?)<\/proposals>/i,tN=/<item\b([^>]*)>([\s\S]*?)<\/item>/g,rN=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*"([^"]*)"/g;function nN(t){let e=eN.exec(t);if(!e)return[];let r=e[1],n=[],o,s=new RegExp(tN.source,"g");for(;(o=s.exec(r))!==null;){let i=o[1],a=o[2].trim(),c={},u=new RegExp(rN.source,"g"),l;for(;(l=u.exec(i))!==null;)c[l[1]]=l[2];let d=c.id,p=c.title,f=c.severity;if(!d||!p||!f)continue;let m={id:d,title:p,severity:f,...c.location?{location:c.location}:{},...a.length>0?{description:a}:{}};n.push(m)}return n}function oN(){return["You are a participant in the individual-review phase of a structured multi-AI debate.","Produce a concise review of the stated topic and propose concrete findings.","Findings must be emitted inside a `<proposals>` XML block using the exact shape:","<proposals>",' <item id="P1" title="Short title" severity="CRITICAL|HIGH|MEDIUM|LOW" location="file:line or component">'," Multi-line description / evidence."," </item>","</proposals>","Rules:","- Do NOT emit `<votes>` in this phase.","- Use stable, unique `id` attributes (e.g. P1, P2).","- Severity labels are free-form but stick to the four levels above.","- Description text is AI-native; the moderator preserves it verbatim."].join(`
|
|
324
|
+
`)}function sN(t){let e=[];if(e.push(`Topic: ${t.config.topic}`),t.goal&&e.push(`Goal: ${t.goal}`),e.push(`Scope: ${t.config.scope}`),t.files.length>0){e.push("Files examined:");for(let r of t.files)e.push(` - ${r}`)}return t.individualReviewPrompt&&(e.push(""),e.push(t.individualReviewPrompt)),e.push(""),e.push("Return your review followed by the required `<proposals>` block."),e.join(`
|
|
325
|
+
`)}function iN(t){let e=[];if(e.push(`Structured debate \u2014 round ${t.round} of ${t.maxRounds}.`),e.push(`Topic: ${t.topic}`),e.push(`Scope: ${t.scope}`),t.previousVoteIssues&&t.previousVoteIssues.length>0){e.push(""),e.push("Previous round vote issues in your response:");for(let r of t.previousVoteIssues)e.push(`- ${r}`);e.push("Correct these issues in this round. Every open proposal still needs an explicit vote.")}e.push(""),e.push("Open proposals:");for(let r of t.openProposals)e.push(`- ${r.id} (${r.severity}, proposer(s): ${r.proposerIds.join(", ")}): ${r.title}`),r.description&&e.push(` ${r.description}`);e.push(""),e.push("Respond with your analysis followed by a `<votes>` block:"),e.push("<votes>");for(let r of t.openProposals)e.push(` <item id="${r.id}" vote="agree|disagree|abstain|revise" reason="\u2026"/>`);return e.push("</votes>"),e.push("`reason` is required for `disagree` and `revise`. Vote on every open proposal."),e.join(`
|
|
326
|
+
`)}function aN(t){let e=[];e.push("Your previous response did not include a valid `<votes>` block."),e.push(`Problem: ${t.errorKind}.`),t.errorDetails&&e.push(`Details: ${t.errorDetails}`),e.push("Reply with ONLY the `<votes>` block. Do not include prose."),e.push("<votes>");for(let r of t.openProposals)e.push(` <item id="${r.id}" vote="agree|disagree|abstain|revise" reason="\u2026"/>`);return e.push("</votes>"),e.push("`reason` is required for `disagree` and `revise`."),e.join(`
|
|
327
|
+
`)}function cN(t){return t.map(e=>`${e.proposalId??"unparsed entry"}: ${e.reason}`)}function uN(t){let e=[];e.push(`## Round ${t.round} / ${t.maxRounds}`),e.push(""),e.push("### Proposal Ledger (open at round start)");for(let r of t.openProposals)e.push(`- ${r.id} (${r.severity}, proposer(s): ${r.proposerIds.join(", ")}): ${r.title}`);e.push(""),e.push("### Turns");for(let r of t.turns)e.push(""),e.push(`#### [${r.participantId}]${r.failed?" (failed)":""}`),e.push(r.text);e.push(""),e.push("### Aggregation");for(let r of t.aggregation){let o=t.ledger.proposals.get(r.proposalId)?.status??"open";e.push(`- ${r.proposalId} \u2192 ${o} (${r.verdict}; agree=${r.tally.agree}, disagree=${r.tally.disagree}, abstain=${r.tally.abstain}, revise=${r.tally.revise}, missing=${r.tally.missing})`)}return e.join(`
|
|
328
|
+
`)}function lN(t,e){let n=[`## ${e.t("moderator.narration.aliasClarification")}`];if(t.mergesApplied.length>0){n.push(""),n.push("Applied merges:");for(let o of t.mergesApplied)n.push(`- ${o.alias} \u2192 ${o.primary} (same=${o.voteBreakdown.same}, different=${o.voteBreakdown.different}, unsure=${o.voteBreakdown.unsure}, missing=${o.voteBreakdown.missing})`)}if(t.undecided.length>0){n.push(""),n.push("Undecided pairs (kept separate):");for(let o of t.undecided)n.push(`- ${o.pair.proposalA} \u2194 ${o.pair.proposalB} (${o.reason})`)}return n.join(`
|
|
329
|
+
`)}var Mx=18e4;function Vs(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Provider "${e}" stalled (no response after ${Mx/1e3}s)`)),Mx))])}function Lx(t){return new On({tools:Ti(),baseDir:t})}var Up,Nx;function Fx(t){return(!Up||Nx!==t)&&(Up=new zo,Nx=t),Up}var ho;function Sc(t,e,r){if(ho&&ho.registry===t&&ho.hostKind===e&&ho.baseDir===r)return ho.bridge;let n=new On({tools:Ti(),baseDir:r}),o=mx({registry:t,readOnlyAdapter:n,hostKind:e,agentsDir:dN(r,"agents")});return ho={bridge:o,registry:t,hostKind:e,baseDir:r},o}var jx=new Map;function Zx(t){let e=jx.get(t.workspaceBaseDir);if(e&&e.registry===t.structuredSessionRegistry&&e.documentManager===t.documentManager&&e.bridge===t.bridge)return e.engine;let r=new mo({bridge:t.bridge,documentManager:t.documentManager,registry:t.structuredSessionRegistry,i18n:t.i18n,...t.traceWriter!==void 0?{traceWriter:t.traceWriter}:{}});return jx.set(t.workspaceBaseDir,{engine:r,registry:t.structuredSessionRegistry,documentManager:t.documentManager,bridge:t.bridge}),r}function Ux(t,e,r){let n=.7;if(r&&e){for(let o of r)e.updateQuality(t.id,o.provider,{score:o.score,evaluator:"claude",feedback:o.feedback});n=r.reduce((o,s)=>o+s.score,0)/r.length}else if(e){let o=new Map;for(let a of t.turns){if(a.speaker==="claude")continue;let c=t.turns.filter(d=>d.turnNumber<a.turnNumber).map(d=>({speaker:d.speaker,content:d.content})),u=Lo(a.content,c,t.topic),l=o.get(a.speaker)??[];l.push(u.score),o.set(a.speaker,l)}let s=0,i=0;for(let[a,c]of o){let u=c.reduce((l,d)=>l+d,0)/c.length;e.updateQuality(t.id,a,{score:u,evaluator:"auto_rule_based",feedback:`Auto-aggregated from ${c.length} turns`}),s+=u,i++}i>0&&(n=s/i)}return{avgQuality:n}}function $c(t,e,r){r.alreadyConcluded||t.debateEngine.conclude(e);let n=t.debateEngine.buildTurnTranscript(e);return t.debateEngine.delete(e),n}async function qx(t,e){let r=rc.parse(t),n=new Map(r.providers.map(l=>[l,e.registry.get(l)])),o=e.sessionManager.createSession("debate",{topic:r.topic,providers:r.providers,maxRounds:r.max_rounds});e.sessionManager.updateSessionStatus(o.id,"in_progress");let s=e.debateEngine,i=s.create({topic:r.topic,providerIds:r.providers,goal:r.goal}),a=!!(r.goal&&r.validator),c=a?e.registry.get(r.validator):void 0,u=a?r.min_rounds??2:r.max_rounds;return(async()=>{try{let l="";for(let p=0;p<r.max_rounds;p++){for(let[f,m]of n){let g=s.buildPromptForProvider(i.id,f);l&&(g+=`
|
|
314
330
|
|
|
315
331
|
Validator feedback from previous round:
|
|
316
|
-
${l}`);let y=await
|
|
332
|
+
${l}`);let y=await Vs(e.readOnlyAdapter.chat(m,{prompt:g}),f);s.addTurn(i.id,f,y.text)}if(a&&c&&p+1>=u){let f=s.buildTurnTranscript(i.id),m=`Evaluate this debate against the goal: "${r.goal}"
|
|
317
333
|
|
|
318
334
|
Current discussion:
|
|
319
335
|
${f}
|
|
@@ -325,12 +341,12 @@ Respond in JSON:
|
|
|
325
341
|
"accuracy": true/false,
|
|
326
342
|
"consistency": true/false,
|
|
327
343
|
"feedback": "..."
|
|
328
|
-
}`,g=await
|
|
344
|
+
}`,g=await Vs(e.readOnlyAdapter.chat(c,{prompt:m}),c.id);try{let y=JSON.parse(g.text);if(y.goalAchievement&&y.completeness&&y.accuracy&&y.consistency)break;l=String(y.feedback??"")}catch{l=g.text}}}let d=$c(e,i.id,{topic:r.topic,providerIds:r.providers});e.sessionManager.completeSession(o.id,d)}catch(l){let d=M(l);try{s.delete(i.id)}catch{}e.sessionManager.updateSessionStatus(o.id,"failed")}})(),{content:[{type:"text",text:`**Debate started**
|
|
329
345
|
**Session ID:** ${o.id}
|
|
330
346
|
**Topic:** ${r.topic}
|
|
331
347
|
**Participants:** ${r.providers.join(", ")}
|
|
332
348
|
|
|
333
|
-
Use \`agent_debate_status\` to check progress.`}]}}async function
|
|
349
|
+
Use \`agent_debate_status\` to check progress.`}]}}async function Vx(t,e){let r=oc.parse(t),n=e.sessionManager.getSession(r.session_id);if(!n)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=`**Session ID:** ${n.id}
|
|
334
350
|
**Type:** ${n.type}
|
|
335
351
|
**Status:** ${n.status}
|
|
336
352
|
**Created:** ${n.createdAt}
|
|
@@ -340,7 +356,7 @@ Use \`agent_debate_status\` to check progress.`}]}}async function Ex(t,e){let r=
|
|
|
340
356
|
|
|
341
357
|
---
|
|
342
358
|
|
|
343
|
-
${n.result}`),{content:[{type:"text",text:o}]}}async function
|
|
359
|
+
${n.result}`),{content:[{type:"text",text:o}]}}async function Bx(t,e){let r=nc.parse(t),n=new Mo(e.registry,e.readOnlyAdapter);try{let o=await n.validate({items:r.items.map(i=>({providerId:i.provider,content:i.content,task:i.task})),validators:r.validators?.map(i=>e.registry.get(i)),criteria:r.criteria}),s=`**Cross-Validation ${o.overallPass?"PASSED":"FAILED"}**
|
|
344
360
|
|
|
345
361
|
`;for(let i of o.reviews)s+=`### ${i.targetProvider} reviewed by ${i.reviewerProvider}
|
|
346
362
|
`,s+=`**Result:** ${i.passed?"PASS":"FAIL"}
|
|
@@ -350,13 +366,13 @@ ${n.result}`),{content:[{type:"text",text:o}]}}async function Rx(t,e){let r=ec.p
|
|
|
350
366
|
`;return o.conflicts.length>0&&(s+=`## Conflicts
|
|
351
367
|
${o.conflicts.map(i=>`- ${i}`).join(`
|
|
352
368
|
`)}
|
|
353
|
-
`),{content:[{type:"text",text:s}]}}catch(o){return{content:[{type:"text",text:`**Cross-validation failed:** ${
|
|
369
|
+
`),{content:[{type:"text",text:s}]}}catch(o){return{content:[{type:"text",text:`**Cross-validation failed:** ${M(o)}`}],isError:!0}}}async function Wx(t,e){let r=sc.parse(t);for(let s of r.providers)s!=="claude"&&e.registry.get(s);let n;return r.save_document&&(n=(await e.documentManager.createDebateDocument({topic:r.topic,providers:r.providers,goal:r.goal})).id),{content:[{type:"text",text:`**Debate created**
|
|
354
370
|
**Debate ID:** ${e.debateEngine.create({topic:r.topic,providerIds:r.providers,goal:r.goal,documentId:n}).id}
|
|
355
371
|
**Topic:** ${r.topic}
|
|
356
372
|
**Participants:** ${r.providers.join(", ")}${n?`
|
|
357
|
-
**Document ID:** ${n}`:""}`}]}}async function
|
|
373
|
+
**Document ID:** ${n}`:""}`}]}}async function Hx(t,e){let r=ic.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};if(n.status==="concluded")return{content:[{type:"text",text:`Debate already concluded: ${r.debate_id}`}],isError:!0};if(r.provider==="claude")return r.claude_comment?(e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment}),{content:[{type:"text",text:`**[claude]:** ${r.claude_comment}`}]}):{content:[{type:"text",text:'provider: "claude" requires claude_comment to be set.'}],isError:!0};let o=e.registry.get(r.provider);r.claude_comment&&(e.debateEngine.addTurn(r.debate_id,"claude",r.claude_comment),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude",content:r.claude_comment}));let s=e.debateEngine.buildPromptForProvider(r.debate_id,r.provider),i=e.traceWriter?{candidateProviders:n.providerIds,selectedProvider:r.provider,selectionReason:`Debate turn: ${r.provider}'s turn to respond`,memoryHit:!1}:void 0,a=performance.now(),c;try{c=await e.readOnlyAdapter.chat(o,{prompt:s})}catch(p){let f=Math.round(performance.now()-a),m=M(p);return e.traceWriter&&e.traceWriter.write({traceId:n.id,action:"debate_turn",providerId:r.provider,task:n.topic,request:{promptSummary:s.slice(0,100),fileCount:0},response:{success:!1,charLength:0,error:m},latencyMs:f,reasoning:i}),{content:[{type:"text",text:`**Debate turn failed (${r.provider}):** ${m}`}],isError:!0}}let u=Math.round(performance.now()-a);e.traceWriter&&e.traceWriter.write({traceId:n.id,action:"debate_turn",providerId:r.provider,task:n.topic,request:{promptSummary:s.slice(0,100),fileCount:0},response:{success:!0,charLength:c.text.length},latencyMs:u,reasoning:i});let l=n.turns.map(p=>({speaker:p.speaker,content:p.content})),d=Lo(c.text,l,n.topic);return e.traceWriter&&e.traceWriter.updateQuality(n.id,r.provider,{score:d.score,evaluator:"auto_rule_based",feedback:JSON.stringify(d.breakdown)}),e.debateEngine.addTurn(r.debate_id,r.provider,c.text),n.documentId&&await e.documentManager.addComment(n.documentId,{author:r.provider,content:c.text}),{content:[{type:"text",text:`**[${r.provider}]:** ${c.text}
|
|
358
374
|
|
|
359
|
-
_Quality: ${d.score.toFixed(2)}_`}]}}async function
|
|
375
|
+
_Quality: ${d.score.toFixed(2)}_`}]}}async function Kx(t,e){let r=ac.parse(t),n=e.debateEngine.getState(r.debate_id);if(!n)return{content:[{type:"text",text:`Debate not found: ${r.debate_id}`}],isError:!0};r.summary&&(e.debateEngine.addTurn(r.debate_id,"claude",r.summary),n.documentId&&await e.documentManager.addComment(n.documentId,{author:"Claude (Summary)",content:r.summary})),e.debateEngine.conclude(r.debate_id);let{avgQuality:o}=Ux(n,e.traceWriter,r.quality_scores),s=$c(e,r.debate_id,{topic:n.topic,providerIds:n.providerIds,importance:.5+o*.5,confidence:o,alreadyConcluded:!0}),i=`**Debate concluded**
|
|
360
376
|
**Debate ID:** ${r.debate_id}
|
|
361
377
|
**Topic:** ${n.topic}
|
|
362
378
|
**Turns:** ${n.turns.length}`;return n.documentId&&(i+=`
|
|
@@ -364,13 +380,13 @@ _Quality: ${d.score.toFixed(2)}_`}]}}async function Cx(t,e){let r=oc.parse(t),n=
|
|
|
364
380
|
|
|
365
381
|
---
|
|
366
382
|
|
|
367
|
-
${s}`,{content:[{type:"text",text:i}]}}async function
|
|
383
|
+
${s}`,{content:[{type:"text",text:i}]}}async function Gx(t,e,r,n){e&&await t.documentManager.addComment(e,{author:r,content:n})}function kc(t){switch(t.kind){case"agree":return"AGREES";case"disagree":return"DISAGREES";case"parseError":return"PARSE_ERROR";case"unavailable":return"UNAVAILABLE"}}function Pc(t){switch(t.kind){case"agree":case"disagree":{let e=t.suggestions?`
|
|
368
384
|
|
|
369
385
|
**Suggestions:** ${t.suggestions}`:"";return`${t.feedback}${e}`}case"parseError":return`[Parse error: ${t.reason}]
|
|
370
386
|
|
|
371
387
|
**Raw response:**
|
|
372
388
|
|
|
373
|
-
${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function
|
|
389
|
+
${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function Jx(t,e,r,n,o){if(!e)return;let s=await t.documentManager.createReview({files:[],rules:[`Independent review from ${o.provider}`,`Parent document: ${e}`,...r?[`Debate ID: ${r}`]:[]],provider:o.provider,topic:`review-${e.slice(0,12)}`});await t.documentManager.addComment(s.id,{author:"Moderator",content:`## Review Target
|
|
374
390
|
|
|
375
391
|
Parent document: ${e}${r?`
|
|
376
392
|
Debate ID: ${r}`:""}
|
|
@@ -381,27 +397,27 @@ ${n}`});let i=o.rawResponse?`
|
|
|
381
397
|
|
|
382
398
|
**Raw response:**
|
|
383
399
|
|
|
384
|
-
${o.rawResponse}`:"";return await t.documentManager.addComment(s.id,{author:`${o.provider} (independent review)`,content:`**${
|
|
400
|
+
${o.rawResponse}`:"";return await t.documentManager.addComment(s.id,{author:`${o.provider} (independent review)`,content:`**${kc(o.outcome)}**
|
|
385
401
|
|
|
386
|
-
${
|
|
387
|
-
${
|
|
388
|
-
**Excluded Providers:** ${o.map(
|
|
402
|
+
${Pc(o.outcome)}${i}`}),s.id}function pN(t){return`${t?.trim()??"Review the following document carefully and state whether you agree with its content."}
|
|
403
|
+
${Rf}`}function fN(t){let e=zn(t);if(e===null||typeof e!="object")return{kind:"parseError",rawResponse:t,reason:"Response did not contain a parseable JSON object."};let r=ex.safeParse(e);if(!r.success)return{kind:"parseError",rawResponse:t,reason:`Response JSON did not match review contract: ${r.error.message}`};let{agrees:n,feedback:o,suggestions:s}=r.data;return n?{kind:"agree",feedback:o,suggestions:s}:{kind:"disagree",feedback:o,suggestions:s}}async function Yx(t,e){let r=cc.parse(t),n=[...r.providers],o=[],s=r.debate_id?e.debateEngine.getState(r.debate_id):void 0,i=s?.documentId;if(r.debate_id&&s){let v=new Set(e.debateEngine.getActiveProviders(r.debate_id)),S=[];for(let w of n)if(w==="claude"||v.has(w))S.push(w);else{let _=(s.unavailableProviders??[]).find(P=>P.providerId===w);o.push({id:w,reason:_?`Marked unavailable for this debate: ${_.reason}`:"Not currently active in this debate."})}n=S}let a=o.length===0?"":`
|
|
404
|
+
**Excluded Providers:** ${o.map(v=>`${v.id} (${v.reason})`).join(", ")}`;if(n.length===0)return{content:[{type:"text",text:`No review-capable providers remain after exclusions.${a}`}],isError:!0};let c=pN(r.review_prompt),u=[],l=n.map(async v=>{if(v==="claude")return null;let S=e.registry.get(v),w=`${c}
|
|
389
405
|
|
|
390
406
|
---
|
|
391
407
|
|
|
392
|
-
${r.document}`,P
|
|
408
|
+
${r.document}`,_,P;try{let D=await Vs(e.readOnlyAdapter.chat(S,{prompt:w}),v);_=D.text,P=fN(D.text)}catch(D){let U=M(D);if(P={kind:"unavailable",reason:U},r.debate_id&&s){let $e=D instanceof de?`Provider reported unavailable: ${U}`:`Chat failed: ${U}`;e.debateEngine.markProviderUnavailable(r.debate_id,v,$e),s=e.debateEngine.getState(r.debate_id)}}let A={provider:v,outcome:P,rawResponse:_};if(A.linkedDocumentId=await Jx(e,i,r.debate_id,r.document,A),i){let D=Pc(A.outcome),U=A.linkedDocumentId?`
|
|
393
409
|
|
|
394
|
-
**Independent review document:** ${
|
|
410
|
+
**Independent review document:** ${A.linkedDocumentId}`:"";await e.documentManager.addComment(i,{author:`${v} (review)`,content:`**${kc(A.outcome)}**
|
|
395
411
|
|
|
396
|
-
${
|
|
412
|
+
${D}${U}`})}return A}),d=await Promise.all(l);for(let v of d)v&&u.push(v);let p=u.filter(v=>v.outcome.kind==="agree"||v.outcome.kind==="disagree"),f=u.length>0&&p.length===u.length&&p.every(v=>v.outcome.kind==="agree"),m=u.filter(v=>v.outcome.kind==="parseError"||v.outcome.kind==="unavailable"),y=`**Document Review** \u2014 ${f?"ALL AGREE \u2713":m.length>0&&p.length===0?"NO RESPONSES":"DISAGREEMENTS FOUND"}${a}
|
|
397
413
|
|
|
398
|
-
`;for(let
|
|
399
|
-
`,y+=`${
|
|
400
|
-
`,
|
|
414
|
+
`;for(let v of u)y+=`### ${v.provider}: ${kc(v.outcome)}
|
|
415
|
+
`,y+=`${Pc(v.outcome)}
|
|
416
|
+
`,v.linkedDocumentId&&(y+=`**Independent review document:** ${v.linkedDocumentId}
|
|
401
417
|
`),y+=`
|
|
402
|
-
`;if(!f){let
|
|
418
|
+
`;if(!f){let v=m.length>0?`Revise the document addressing the feedback above. Note: ${m.length} provider(s) did not return a definite agree/disagree (parseError or unavailable) \u2014 they are NOT counted as agreement. Call \`agent_debate_review\` again with an updated document or a narrower providers list.`:"Revise the document addressing the feedback above, then call `agent_debate_review` again to check for consensus.";y+=`---
|
|
403
419
|
|
|
404
|
-
**Next step:** ${
|
|
420
|
+
**Next step:** ${v}`}return await Gx(e,i,"Moderator (Review Aggregation)",y),{content:[{type:"text",text:y}]}}async function Xx(t,e){let r=uc.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};let n;try{n=e.cliWorkerManager.reviewChanges(r.task_id)}catch(s){return{content:[{type:"text",text:M(s)}],isError:!0}}let o=`**File Change Review**
|
|
405
421
|
**Task ID:** ${r.task_id}
|
|
406
422
|
**Worktree:** ${n.worktreePath}
|
|
407
423
|
**Branch:** ${n.branch}
|
|
@@ -415,25 +431,25 @@ ${n.diffStat}
|
|
|
415
431
|
### Changes
|
|
416
432
|
\`\`\`diff
|
|
417
433
|
${n.fullDiff}
|
|
418
|
-
\`\`\``,{content:[{type:"text",text:o}]}}async function
|
|
434
|
+
\`\`\``,{content:[{type:"text",text:o}]}}async function Qx(t,e){let r=lc.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{let n=e.cliWorkerManager.acceptChanges(r.task_id,r.message);return{content:[{type:"text",text:`**Changes accepted**
|
|
419
435
|
**Task ID:** ${r.task_id}
|
|
420
436
|
**Merged files:** ${n.merged.length}
|
|
421
437
|
|
|
422
438
|
${n.merged.map(o=>`- ${o}`).join(`
|
|
423
|
-
`)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${
|
|
439
|
+
`)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${M(n)}`}],isError:!0}}}async function eS(t,e){let r=dc.parse(t);if(!e.cliWorkerManager)return{content:[{type:"text",text:"CLI worker manager is not available."}],isError:!0};try{e.cliWorkerManager.rejectChanges(r.task_id)}catch(o){return{content:[{type:"text",text:M(o)}],isError:!0}}let n=`**Changes rejected**
|
|
424
440
|
**Task ID:** ${r.task_id}`;return r.reason&&(n+=`
|
|
425
|
-
**Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}import{join as
|
|
441
|
+
**Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}import{join as mN}from"path";var hN="unknown";async function tS(t,e,r){let n=r.workspaceBaseDir??process.cwd(),o=r.structuredSessionRegistry??new fo(mN(n,bo)),s=Sc(r.registry,r.sessionContext?.hostKind??hN,n),i=r.moderatorEngine??Zx({workspaceBaseDir:n,bridge:s,documentManager:r.documentManager,structuredSessionRegistry:o,i18n:r.i18n,...r.traceWriter!==void 0?{traceWriter:r.traceWriter}:{}}),a={...r,debateEngine:Fx(n),readOnlyAdapter:Lx(n),structuredSessionRegistry:o,moderatorEngine:i};switch(t){case"agent_debate_start":return qx(e,a);case"agent_debate_status":return Vx(e,a);case"agent_cross_validate":return Bx(e,a);case"agent_debate_create":return Wx(e,a);case"agent_debate_turn":return Hx(e,a);case"agent_debate_conclude":return Kx(e,a);case"agent_debate_review":return Yx(e,a);case"agent_changes_review":return Xx(e,a);case"agent_changes_accept":return Qx(e,a);case"agent_changes_reject":return eS(e,a);case gc:return tx(e,a);case co:return rx(e,a);case uo:return nx(e,a);case lo:return ox(e,a);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Vp={};Be(Vp,{getTools:()=>gN,handleTool:()=>$N});var rS=h.object({files:h.array(h.string()).min(1).describe("File paths to include in the review"),rules:h.array(h.string()).describe("Review rules/guidelines to apply")}),nS=h.object({doc_id:h.string().describe("Document ID to request review for"),provider:h.union([h.string(),h.array(h.string()).min(1)]).describe("Provider ID(s) to perform the review")}),oS=h.object({session_id:h.string().describe("Session ID returned by workspace_request_review")}),sS=h.object({doc_id:h.string().describe("Document ID to comment on"),author:h.string().describe("Comment author name"),content:h.string().describe("Comment content")}),iS=h.object({doc_id:h.string().describe("Document ID to read")}),aS=h.object({title:h.string().describe("Document title"),content:h.string().describe("Document content (markdown)"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata (e.g. Provider, Task, Mode)"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' (per-provider independent work) \u2192 individual/, 'debate' (round-by-round working docs) \u2192 debates/, 'synthesis' (final consensus) \u2192 synthesis/, 'general' (default, legacy) \u2192 reviews/. Always pass an explicit kind for idea/review workflows so the workspace tree stays sorted.")}),cS=h.object({});function gN(){return[{name:"workspace_create_review",title:"Create Code Review",description:"Create a code review document for the specified files with given review rules.",inputSchema:V(rS)},{name:"workspace_request_review",title:"Request Code Review",description:"Request AI provider(s) to perform a code review on an existing review document. Returns immediately with a session ID. Use workspace_review_status to check progress.",inputSchema:V(nS)},{name:"workspace_review_status",title:"Check Review Status",description:"Check the status of an async review session started by workspace_request_review.",inputSchema:V(oS)},{name:"workspace_add_comment",title:"Add Review Comment",description:"Add a comment to an existing review document.",inputSchema:V(sS)},{name:"workspace_create_document",title:"Create Document",description:"Create a general-purpose workspace document with a title, content, and optional metadata. Use for independent analysis documents, aggregated reports, or any structured output.",inputSchema:V(aS)},{name:"workspace_read",title:"Read Document",description:"Read the contents of a workspace document.",inputSchema:V(iS)},{name:"workspace_list",title:"List Documents",description:"List all workspace documents.",inputSchema:V(cS)}]}async function yN(t,e){let r=rS.parse(t),n=await e.documentManager.createReview({files:r.files,rules:r.rules});return{content:[{type:"text",text:`**Review created**
|
|
426
442
|
**Document ID:** ${n.id}
|
|
427
443
|
**Path:** ${n.path}
|
|
428
444
|
**Files:** ${r.files.join(", ")}
|
|
429
|
-
**Rules:** ${r.rules.length}`}]}}async function
|
|
445
|
+
**Rules:** ${r.rules.length}`}]}}async function vN(t,e){let r=nS.parse(t),n=Array.isArray(r.provider)?r.provider:[r.provider],o=[];for(let c of n){let u=e.registry.get(c);o.push({id:c,provider:u})}let s=await e.documentManager.read(r.doc_id),i=e.sessionManager.createSession("review",{doc_id:r.doc_id,providers:n,completed:[],failed:[]});e.sessionManager.updateSessionStatus(i.id,"in_progress");let a=o.map(async({id:c,provider:u})=>{try{let l=await u.chat({prompt:`Please review the following document and provide feedback:
|
|
430
446
|
|
|
431
|
-
${s.content}`,system:"You are a code reviewer. Provide detailed, actionable feedback."});await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:l.text});let d=e.sessionManager.getSession(i.id);if(d){let p=d.config.completed||[];p.push(c),d.config.completed=p}}catch(l){let d=
|
|
447
|
+
${s.content}`,system:"You are a code reviewer. Provide detailed, actionable feedback."});await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:l.text});let d=e.sessionManager.getSession(i.id);if(d){let p=d.config.completed||[];p.push(c),d.config.completed=p}}catch(l){let d=M(l);try{await e.documentManager.addComment(r.doc_id,{author:`AI (${c})`,content:`**Review failed:** ${d}`})}catch{}let p=e.sessionManager.getSession(i.id);if(p){let f=p.config.failed||[];f.push(c),p.config.failed=f}}});return Promise.all(a).then(()=>{try{let c=e.sessionManager.getSession(i.id),u=c?.config.completed||[],l=c?.config.failed||[],d=`Completed: ${u.join(", ")||"none"}. Failed: ${l.join(", ")||"none"}.`,p=vu({providers:n.length,failed:l.length});e.sessionManager.transitionSession(i.id,p,d)}catch{}}),{content:[{type:"text",text:`**Review started (async)**
|
|
432
448
|
**Session ID:** ${i.id}
|
|
433
449
|
**Document ID:** ${r.doc_id}
|
|
434
450
|
**Providers:** ${n.join(", ")}
|
|
435
451
|
|
|
436
|
-
Use \`workspace_review_status\` with session_id to check progress.`}]}}async function
|
|
452
|
+
Use \`workspace_review_status\` with session_id to check progress.`}]}}async function _N(t,e){let r=oS.parse(t),n=e.sessionManager.getSession(r.session_id);if(!n)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=n.config.providers||[],s=n.config.completed||[],i=n.config.failed||[],a=o.filter(u=>!s.includes(u)&&!i.includes(u)),c=`**Review Session Status**
|
|
437
453
|
`;return c+=`**Session ID:** ${n.id}
|
|
438
454
|
`,c+=`**Status:** ${n.status}
|
|
439
455
|
`,c+=`**Document:** ${n.config.doc_id}
|
|
@@ -443,30 +459,30 @@ Use \`workspace_review_status\` with session_id to check progress.`}]}}async fun
|
|
|
443
459
|
`,c+=`- Failed: ${i.join(", ")||"none"}
|
|
444
460
|
`,c+=`- Pending: ${a.join(", ")||"none"}
|
|
445
461
|
`,n.result&&(c+=`
|
|
446
|
-
**Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function
|
|
462
|
+
**Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function bN(t,e){let r=sS.parse(t);return await e.documentManager.addComment(r.doc_id,{author:r.author,content:r.content}),{content:[{type:"text",text:`**Comment added**
|
|
447
463
|
**Document ID:** ${r.doc_id}
|
|
448
464
|
**Author:** ${r.author}
|
|
449
465
|
|
|
450
|
-
${r.content}`}]}}async function
|
|
466
|
+
${r.content}`}]}}async function wN(t,e){let r=aS.parse(t),n=await e.documentManager.createDocument({title:r.title,content:r.content,metadata:r.metadata,kind:r.kind});return{content:[{type:"text",text:`**Document created**
|
|
451
467
|
**Document ID:** ${n.id}
|
|
452
468
|
**Path:** ${n.path}
|
|
453
|
-
**Title:** ${r.title}`}]}}async function
|
|
469
|
+
**Title:** ${r.title}`}]}}async function xN(t,e){let r=iS.parse(t),n=await e.documentManager.read(r.doc_id);return{content:[{type:"text",text:`**Document ID:** ${n.id}
|
|
454
470
|
**Path:** ${n.path}
|
|
455
471
|
|
|
456
|
-
${n.content}`}]}}async function
|
|
472
|
+
${n.content}`}]}}async function SN(t,e){cS.parse(t);let r=await e.documentManager.list();if(r.length===0)return{content:[{type:"text",text:"No workspace documents found."}]};let n=`# Workspace Documents
|
|
457
473
|
|
|
458
474
|
**Total:** ${r.length}
|
|
459
475
|
|
|
460
476
|
`;for(let o of r){let s=o.content.slice(0,100).replace(/\n/g," ");n+=`- **${o.id}** \u2014 ${s}...
|
|
461
|
-
`}return{content:[{type:"text",text:n}]}}async function
|
|
477
|
+
`}return{content:[{type:"text",text:n}]}}async function $N(t,e,r){switch(t){case"workspace_create_review":return yN(e,r);case"workspace_request_review":return vN(e,r);case"workspace_review_status":return _N(e,r);case"workspace_add_comment":return bN(e,r);case"workspace_create_document":return wN(e,r);case"workspace_read":return xN(e,r);case"workspace_list":return SN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Bp={};Be(Bp,{getTools:()=>PN,handleTool:()=>RN});function Tc(t,e){return t==="claude-only"&&e!=="claude-code"?"leader-only":t}var kN=h.object({provider:h.string().optional().describe("Provider ID to check (omit to check all)")});function PN(){return[{name:"provider_list",title:"List AI Providers",description:"List all registered AI providers with their availability status and capabilities.",inputSchema:{type:"object",properties:{},required:[]}},{name:"provider_health",title:"Check Provider Health",description:"Run health checks on AI providers. Optionally specify a provider ID, or omit to check all.",inputSchema:{type:"object",properties:{provider:{type:"string",description:"Provider ID to check (omit to check all)"}},required:[]}}]}async function TN(t){let e=t.registry.getAll();if(e.length===0)return{content:[{type:"text",text:"No providers registered."}]};let r=`# Registered Providers (${e.length})
|
|
462
478
|
|
|
463
479
|
`;t.sessionContext&&(r+=`## Host Session
|
|
464
480
|
`,r+=`- **Host:** ${t.sessionContext.hostId} (${t.sessionContext.hostKind})
|
|
465
481
|
`,r+=`- **Leader Provider:** ${t.sessionContext.leaderProviderId}
|
|
466
|
-
`,r+=`- **Execution Mode:** ${
|
|
482
|
+
`,r+=`- **Execution Mode:** ${Tc(t.sessionContext.executionMode,t.sessionContext.hostKind)}
|
|
467
483
|
`,r+=`- **Participants:** ${t.sessionContext.participantProviderIds.join(", ")}
|
|
468
484
|
|
|
469
|
-
`);for(let n of e){let o=n.isAvailable(),s=n.getCapabilities(),i=typeof t.registry.getDescriptor=="function"?t.registry.getDescriptor(n.id):
|
|
485
|
+
`);for(let n of e){let o=n.isAvailable(),s=n.getCapabilities(),i=typeof t.registry.getDescriptor=="function"?t.registry.getDescriptor(n.id):ir(n,s),a=o?"Available":"Unavailable";r+=`## ${n.id} (${n.type})
|
|
470
486
|
`,r+=`- **Status:** ${a}
|
|
471
487
|
`,r+=`- **Invocation:** ${i.invocation}
|
|
472
488
|
`,r+=`- **Roles:** ${i.roles.join(", ")}
|
|
@@ -481,34 +497,37 @@ ${n.content}`}]}}async function JM(t,e){Wx.parse(t);let r=await e.documentManage
|
|
|
481
497
|
`,s.strengths.length>0&&(r+=`- **Strengths:** ${s.strengths.join(", ")}
|
|
482
498
|
`),s.models.length>0&&(r+=`- **Models:** ${s.models.map(c=>c.name).join(", ")}
|
|
483
499
|
`),r+=`
|
|
484
|
-
`}return{content:[{type:"text",text:r}]}}async function
|
|
500
|
+
`}return{content:[{type:"text",text:r}]}}async function EN(t,e){let r=kN.parse(t),n=r.provider?[e.registry.get(r.provider)]:e.registry.getAll();if(n.length===0)return{content:[{type:"text",text:"No providers to check."}]};let o=await Promise.all(n.map(async i=>{try{let a=await i.healthCheck();return{id:i.id,type:i.type,status:a.status,message:a.message,details:a.details,error:null}}catch(a){return{id:i.id,type:i.type,status:"error",message:M(a),details:void 0,error:M(a)}}})),s=`# Health Check Results
|
|
485
501
|
|
|
486
502
|
`;for(let i of o){let a=i.status==="ok"?"OK":i.status==="degraded"?"DEGRADED":"ERROR";s+=`## ${i.id} (${i.type})
|
|
487
503
|
`,s+=`- **Status:** ${a}
|
|
488
504
|
`,i.message&&(s+=`- **Message:** ${i.message}
|
|
489
505
|
`),i.error&&(s+=`- **Error:** ${i.error}
|
|
490
506
|
`),s+=`
|
|
491
|
-
`}return{content:[{type:"text",text:s}]}}async function
|
|
492
|
-
`)}]}}async function
|
|
493
|
-
`)}]}}async function
|
|
507
|
+
`}return{content:[{type:"text",text:s}]}}async function RN(t,e,r){switch(t){case"provider_list":return TN(r);case"provider_health":return EN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Hp={};Be(Hp,{getTools:()=>ZN,handleTool:()=>VN});import{existsSync as ON,readFileSync as MN}from"fs";import{readFileSync as IN,existsSync as AN}from"fs";var CN={ollama:{executionPolicy:"workspace-write",config:{host:_o,defaultModel:"auto"}},"gemini-cli":{executionPolicy:Jt("gemini-cli"),config:{timeout:12e4}},"codex-cli":{executionPolicy:Jt("codex-cli"),config:{timeout:12e4}},"claude-cli":{executionPolicy:Jt("claude-cli"),config:{timeout:12e4}}};async function go(t){let e=t?.workspaceBaseDir,r=[{id:"ollama",type:"ollama",provider:new Gr({id:"ollama",host:_o})},{id:"gemini",type:"gemini-cli",provider:new Jr({id:"gemini"})},{id:"codex",type:"codex-cli",provider:new Yr({id:"codex",workspaceBaseDir:e})},{id:"claude-cli",type:"claude-cli",provider:new Xr({id:"claude-cli"})}],n=[],o=[];await Promise.all(r.map(async i=>{try{await i.provider.initialize()}catch{}let a=i.provider.isAvailable();n.push({id:i.id,type:i.type,available:a}),a&&o.push(i.provider)}));let s=["ollama","gemini","codex","claude-cli"];return n.sort((i,a)=>s.indexOf(i.id)-s.indexOf(a.id)),o.sort((i,a)=>s.indexOf(i.id)-s.indexOf(a.id)),{results:n,providers:o}}function DN(t){if(!AN(t))return null;try{return JSON.parse(IN(t,"utf-8"))}catch{return null}}function zN(t){return t==="auto"?"auto":"default-only"}function uS(t,e,r){let n=DN(t),o=new Set(r.enabledIds??[]),s=new Map((n?.providers??[]).map(d=>[d.id,d])),i=e.map(d=>{let p=CN[d.type]||{executionPolicy:Jt(d.type),config:{}},f=s.get(d.id);return s.delete(d.id),{id:d.id,type:d.type,enabled:d.available&&o.has(d.id),executionPolicy:f?.executionPolicy??p.executionPolicy,config:{...f?.config??p.config}}});for(let d of s.values())i.push({...d,enabled:o.has(d.id)?d.enabled:!1});if(i.length===0)throw new Error("No providers available to write into providers.config.json");let a={selectionPolicy:zN(r.selectionPolicy??n?.selectionPolicy),...r.locale!==void 0?{locale:r.locale}:n?.locale!==void 0?{locale:n.locale}:{},providers:i},c=n?JSON.stringify(n):null,u=JSON.stringify(a),l=c===null?"created":c===u?"unchanged":"updated";return!r.dryRun&&l!=="unchanged"&&(Wf(t),je(t,a)),{action:l,path:t,config:a}}function lS(t,e){Wp(t,e)}function Wp(t,e,r){let n=[];for(let o of t)e.has(o.id)||r?.excludeIds?.has(o.id)||r?.excludeTypes?.has(o.type)||(e.register(o),n.push(o));return n}var NN=h.object({}),jN=h.object({enabled_providers:h.array(h.string()).describe("Provider IDs to enable for Agestra workflows."),locale:h.enum(["ko","en","ja","zh"]).describe("UI language for moderator/setup-facing text."),selection_policy:h.enum(["default-only","auto"]).optional().default("default-only").describe("Provider selection policy stored in providers.config.json."),dry_run:h.boolean().optional().default(!1).describe("When true, compute the resulting config without writing it to disk.")});function LN(t){if(!ON(t))return null;try{return JSON.parse(MN(t,"utf-8"))}catch{return null}}function FN(t,e){if(!t)return["Current config: not found",`Expected location: ${e}`];let r=t.providers.filter(n=>n.enabled);return[`Current config: ${r.length>0?"present":"present (no providers enabled)"}`,`Config path: ${e}`,`Enabled providers: ${r.length>0?r.map(n=>n.id).join(", "):"(none)"}`,`Locale: ${t.locale??"(default)"}`,`Selection policy: ${t.selectionPolicy}`]}function ZN(){return[{name:"setup_status",title:"Read Agestra Setup Status",description:"Detect available AI providers and show the current Agestra setup state from providers.config.json.",inputSchema:{type:"object",properties:{},required:[]}},{name:"setup_apply",title:"Apply Agestra Setup",description:"Write the selected AI providers and locale into providers.config.json for Agestra workflows.",inputSchema:{type:"object",properties:{enabled_providers:{type:"array",items:{type:"string"},description:"Provider IDs to enable"},locale:{type:"string",enum:["ko","en","ja","zh"],description:"UI locale"},selection_policy:{type:"string",enum:["default-only","auto"],description:"Stored provider selection policy"},dry_run:{type:"boolean",description:"Preview without writing providers.config.json"}},required:["enabled_providers","locale"]}}]}async function UN(t){let e=ko(),r=LN(e),{results:n}=await go(),o=["# Agestra Setup"];if(o.push(""),o.push(...FN(r,e)),o.push(""),o.push("Detected providers:"),n.length===0)o.push("- (none detected)");else for(let s of n)o.push(`- ${s.id} (${s.type}) \u2014 ${s.available?"available":"unavailable"}`);return{content:[{type:"text",text:o.join(`
|
|
508
|
+
`)}]}}async function qN(t,e){let r=jN.parse(t),n=ko(),{results:o}=await go();if(o.length===0)return{content:[{type:"text",text:"No AI providers were detected, so setup could not be applied."}],isError:!0};let s=new Set(o.filter(l=>l.available).map(l=>l.id)),i=r.enabled_providers.filter(l=>!s.has(l));if(i.length>0)return{content:[{type:"text",text:`These providers are not currently available and cannot be enabled: ${i.join(", ")}`}],isError:!0};let a=uS(n,o,{enabledIds:r.enabled_providers,locale:r.locale,selectionPolicy:r.selection_policy,dryRun:r.dry_run}),c=a.config.providers.filter(l=>l.enabled);return{content:[{type:"text",text:[r.dry_run?"# Agestra Setup Preview":"# Agestra Setup Applied","",`Config path: ${a.path}`,`Action: ${a.action}`,`Enabled providers: ${c.length>0?c.map(l=>l.id).join(", "):"(none)"}`,`Locale: ${a.config.locale??"(default)"}`,`Selection policy: ${a.config.selectionPolicy}`].join(`
|
|
509
|
+
`)}]}}async function VN(t,e,r){switch(t){case"setup_status":return NN.parse(e),UN(r);case"setup_apply":return qN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Kp={};Be(Kp,{getTools:()=>WN,handleTool:()=>GN});var BN=h.object({model:h.string().describe("Model name to download (e.g. 'llama3', 'codellama')")});function WN(){return[{name:"ollama_models",title:"List Ollama Models",description:"List installed Ollama models with their sizes and capabilities.",inputSchema:{type:"object",properties:{},required:[]}},{name:"ollama_pull",title:"Pull Ollama Model",description:"Download (pull) a model from the Ollama registry.",inputSchema:{type:"object",properties:{model:{type:"string",description:"Model name to download (e.g. 'llama3', 'codellama')"}},required:["model"]}}]}function dS(t){let e=t.ollamaProviderId||"ollama",r=t.registry.get(e);if(r.type!=="ollama")throw new Error(`Provider '${e}' is not an Ollama provider (type: ${r.type})`);return r}async function HN(t){let r=dS(t).getModels();if(r.length===0)return{content:[{type:"text",text:"No models installed. Use `ollama_pull` to download a model."}]};let n=`# Installed Ollama Models (${r.length})
|
|
494
510
|
|
|
495
511
|
`;for(let o of r){let s=(o.size/1e9).toFixed(1);n+=`## ${o.name}
|
|
496
512
|
`,n+=`- **Size:** ${s} GB
|
|
497
513
|
`,o.strengths.length>0&&(n+=`- **Strengths:** ${o.strengths.join(", ")}
|
|
498
514
|
`),n+=`
|
|
499
|
-
`}return{content:[{type:"text",text:n}]}}async function
|
|
515
|
+
`}return{content:[{type:"text",text:n}]}}async function KN(t,e){let r=BN.parse(t),n=dS(e);try{let o=n.getConnectionInfo().host,s=await fetch(`${o}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:r.model,stream:!1})});if(!s.ok){let a=await s.text();return{content:[{type:"text",text:`**Pull failed**
|
|
500
516
|
**Model:** ${r.model}
|
|
501
517
|
**Error:** HTTP ${s.status}: ${a}`}],isError:!0}}let i=await s.json();return{content:[{type:"text",text:`**Model pulled successfully**
|
|
502
518
|
**Model:** ${r.model}
|
|
503
|
-
**Status:** ${i.status||"success"}`}]}}catch(o){let s=
|
|
519
|
+
**Status:** ${i.status||"success"}`}]}}catch(o){let s=M(o);return{content:[{type:"text",text:`**Pull failed**
|
|
504
520
|
**Model:** ${r.model}
|
|
505
|
-
**Error:** ${s}`}],isError:!0}}}async function
|
|
506
|
-
**
|
|
507
|
-
**
|
|
521
|
+
**Error:** ${s}`}],isError:!0}}}async function GN(t,e,r){switch(t){case"ollama_models":return HN(r);case"ollama_pull":return KN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Gp={};Be(Gp,{getTools:()=>YN,handleTool:()=>ej});var JN=h.object({title:h.string().describe("Document title"),metadata:h.record(h.string()).optional().describe("Optional key-value metadata"),kind:h.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' / 'debate' / 'synthesis' / 'general' (default).")}).optional(),pS=h.object({provider:h.string().describe("Provider ID (e.g. 'gemini', 'codex')"),prompt:h.string().describe("Prompt to send to the provider CLI"),timeout:h.number().int().positive().optional().describe("Timeout in ms (default: 300000)"),save_as_document:JN.describe("If set, the job output will be saved as a workspace document on completion. Returned via cli_job_status once finalized.")}).strict(),fS=h.object({job_id:h.string().describe("Job ID returned by cli_job_submit")});function YN(){return[{name:"cli_job_submit",title:"Submit CLI Job",description:"Submit a long-running CLI job to a provider. Returns a job ID immediately. Use cli_job_status to check progress.",inputSchema:V(pS)},{name:"cli_job_status",title:"Check CLI Job Status",description:"Check the status of a CLI job. Returns state, output (on completion), and stderr.",inputSchema:V(fS)}]}async function XN(t,e){let r=pS.parse(t),n=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:r.timeout,saveAsDocument:r.save_as_document}),o=r.save_as_document?`
|
|
522
|
+
**Save on complete:** ${r.save_as_document.title}`:"";return{content:[{type:"text",text:`**Job submitted**
|
|
523
|
+
**Job ID:** ${n}
|
|
524
|
+
**Provider:** ${r.provider}${o}
|
|
508
525
|
|
|
509
|
-
Use \`cli_job_status\` with this job_id to check progress.`}]}}async function
|
|
526
|
+
Use \`cli_job_status\` with this job_id to check progress.`}]}}async function QN(t,e){let r=fS.parse(t),n=typeof e.jobManager.getResultAwaited=="function"?await e.jobManager.getResultAwaited(r.job_id):e.jobManager.getResult(r.job_id);if(!n)return{content:[{type:"text",text:`Job not found: ${r.job_id}`}],isError:!0};let o=`**Job ID:** ${n.id}
|
|
510
527
|
**State:** ${n.state}`;return n.exitCode!==void 0&&(o+=`
|
|
511
|
-
**Exit Code:** ${n.exitCode}`),n.
|
|
528
|
+
**Exit Code:** ${n.exitCode}`),n.savedDocumentId?o+=`
|
|
529
|
+
**Document ID:** ${n.savedDocumentId}`:n.saveError&&(o+=`
|
|
530
|
+
**Save error:** ${n.saveError}`),n.output&&(o+=`
|
|
512
531
|
|
|
513
532
|
---
|
|
514
533
|
|
|
@@ -516,10 +535,10 @@ Use \`cli_job_status\` with this job_id to check progress.`}]}}async function kN
|
|
|
516
535
|
${n.output}`),n.error&&(o+=`
|
|
517
536
|
|
|
518
537
|
**Stderr:**
|
|
519
|
-
${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state==="missing_cli"}}async function
|
|
538
|
+
${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state==="missing_cli"}}async function ej(t,e,r){switch(t){case"cli_job_submit":return XN(e,r);case"cli_job_status":return QN(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Jp={};Be(Jp,{getTools:()=>tj,handleTool:()=>rj});var mS=h.object({provider_id:h.string().optional(),task:h.string().optional(),trace_id:h.string().optional(),days_back:h.number().optional().default(7),limit:h.number().optional().default(50)}),hS=h.object({days_back:h.number().optional().default(30)}),gS=h.object({trace_id:h.string()});function tj(){return[{name:"trace_query",title:"Query Trace Records",description:"Query trace records with filtering. Returns recent provider interactions with latency, quality scores, and reasoning.",inputSchema:V(mS)},{name:"trace_summary",title:"Summarize Trace Stats",description:"Get quality and performance stats per provider and task type. Shows average quality scores, latency, and success rates.",inputSchema:V(hS)},{name:"trace_visualize",title:"Visualize Trace Flow",description:"Generate a Mermaid diagram showing the flow of a traced operation. Shows provider selection, execution, and quality assessment.",inputSchema:V(gS)}]}async function rj(t,e,r){if(!r.traceWriter)return{content:[{type:"text",text:"Trace tools require traceWriter to be configured."}],isError:!0};let n={traceWriter:r.traceWriter};switch(t){case"trace_query":return nj(e,n);case"trace_summary":return oj(e,n);case"trace_visualize":return sj(e,n);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}function nj(t,e){let r=mS.parse(t),n=e.traceWriter.query({providerId:r.provider_id,task:r.task,traceId:r.trace_id,daysBack:r.days_back,limit:r.limit});if(n.length===0)return{content:[{type:"text",text:"No trace records found."}]};let o=`**Trace Records** (${n.length} results)
|
|
520
539
|
|
|
521
540
|
`;for(let s of n)o+=`| ${s.timestamp?.slice(0,19)} | ${s.providerId} | ${s.task} | ${s.latencyMs}ms | ${s.response.success?"OK":"FAIL"} |`,s.quality&&(o+=` quality: ${s.quality.score}`),o+=`
|
|
522
|
-
`;return{content:[{type:"text",text:o}]}}function
|
|
541
|
+
`;return{content:[{type:"text",text:o}]}}function oj(t,e){let r=hS.parse(t),n=e.traceWriter.getQualityStats(r.days_back);if(n.size===0)return{content:[{type:"text",text:"No quality data available yet."}]};let o=`**Provider Quality Summary** (last ${r.days_back} days)
|
|
523
542
|
|
|
524
543
|
`;o+=`| Provider:Task | Avg Quality | Count | Avg Latency |
|
|
525
544
|
`,o+=`|---|---|---|---|
|
|
@@ -527,23 +546,23 @@ ${n.error}`),{content:[{type:"text",text:o}],isError:n.state==="error"||n.state=
|
|
|
527
546
|
`;let s=new Map;for(let[a,c]of n){let u=a.split(":")[0],l=s.get(u)??{totalScore:0,count:0};l.totalScore+=c.avgScore*c.count,l.count+=c.count,s.set(u,l)}let i=["low","medium","high"];o+=`
|
|
528
547
|
**Provider Difficulty Qualification**
|
|
529
548
|
|
|
530
|
-
`,o+=`| Provider | Overall Avg | Samples | Low | Medium (>=${
|
|
549
|
+
`,o+=`| Provider | Overall Avg | Samples | Low | Medium (>=${Ys.medium}) | High (>=${Ys.high}) |
|
|
531
550
|
`,o+=`|---|---|---|---|---|---|
|
|
532
|
-
`;for(let[a,c]of s){let u=c.totalScore/c.count,l=i.map(d=>
|
|
533
|
-
`}return{content:[{type:"text",text:o}]}}function
|
|
551
|
+
`;for(let[a,c]of s){let u=c.totalScore/c.count,l=i.map(d=>Xs(u,d)?"YES":"no");o+=`| ${a} | ${u.toFixed(2)} | ${c.count} | ${l[0]} | ${l[1]} | ${l[2]} |
|
|
552
|
+
`}return{content:[{type:"text",text:o}]}}function sj(t,e){let r=gS.parse(t),n=e.traceWriter.query({traceId:r.trace_id});if(n.length===0)return{content:[{type:"text",text:`No records found for trace: ${r.trace_id}`}],isError:!0};let o="```mermaid\ngraph LR\n";o+=` A[User Request] --> B{Provider Selection}
|
|
534
553
|
`;for(let i=0;i<n.length;i++){let a=n[i],c=String.fromCharCode(67+i),u=a.reasoning?.selectionReason?a.reasoning.selectionReason.slice(0,40):`${a.latencyMs}ms`;o+=` B -->|${u}| ${c}[${a.providerId}]
|
|
535
554
|
`;let l=a.response.success?`${a.response.charLength} chars, ${a.latencyMs}ms`:`FAIL: ${a.response.error?.slice(0,30)??"error"}`;o+=` ${c} --> ${c}R[${l}]
|
|
536
555
|
`,a.quality&&(o+=` ${c}R --> ${c}Q[Quality: ${a.quality.score}]
|
|
537
556
|
`)}return o+="```",{content:[{type:"text",text:`**Trace Visualization: ${r.trace_id}**
|
|
538
557
|
|
|
539
|
-
${o}`}]}}var
|
|
558
|
+
${o}`}]}}var Xp={};Be(Xp,{getTools:()=>uj,handleTool:()=>pj,resetCache:()=>lj});import{execFile as ij}from"child_process";import{promisify as aj}from"util";var vS=aj(ij),_S=5e3;async function Bs(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:r}=await vS(e,[t],{timeout:_S,encoding:"utf-8"});return r.split(/\r?\n/).map(o=>o.trim()).find(Boolean)||null}catch{return null}}async function cj(){try{return await vS("git",["worktree","list"],{timeout:_S,encoding:"utf-8"}),!0}catch{return!1}}function uj(){return[{name:"environment_check",title:"Check Environment",description:"Check installed AI CLI tools (codex, gemini), infrastructure (tmux, git worktree), and Ollama models. Returns a capability map showing available v3 orchestration modes. Results are cached per session \u2014 call with force_refresh to re-check.",inputSchema:{type:"object",properties:{force_refresh:{type:"boolean",description:"Force re-check even if cached (default: false)"}},required:[]}}]}var Ec=null,Yp=null;function lj(){Ec=null,Yp=null}async function dj(t,e){let r=JSON.stringify(e.sessionContext??null);if(Ec&&Yp===r&&!t.force_refresh)return{content:[{type:"text",text:yS(Ec)}]};let n=typeof e.registry.getAvailable=="function"?e.registry.getAvailable():e.registry.getAll().filter(G=>G.isAvailable()),o=n.find(G=>G.type==="claude-cli"),s=n.find(G=>G.type==="claude-host"),i=n.find(G=>G.type==="codex-cli"),a=n.find(G=>G.type==="codex-host"),c=n.find(G=>G.type==="gemini-cli"),u=n.find(G=>G.type==="gemini-host"),[l,d,p,f,m,g]=await Promise.all([Bs("claude"),Bs("codex"),Bs("gemini"),Bs("tmux"),Bs("git"),cj()]),y=[],v=e.registry.getAll(),S=v.find(G=>G.id==="ollama");if(S?.isAvailable()){let G=S.getCapabilities();for(let _t of G.models){let Te=_t.sizeGb??0;y.push({name:_t.name,size_gb:Te,tier:Uc(Te)})}}let w=i!==void 0||c!==void 0,_=f!==null,P=m!==null&&g,A=a!==void 0||u!==void 0||e.sessionContext?.hostKind==="codex-cli"||e.sessionContext?.hostKind==="gemini-cli",D=v.some(G=>G.isAvailable()&&!G.type.endsWith("-host")&&G.id!=="ollama"),U=[A?"leader_only":"claude_only"];(D||y.length>0)&&U.push("independent","debate"),w&&P&&U.push("team");let $e={host:e.sessionContext?{id:e.sessionContext.hostId,kind:e.sessionContext.hostKind,leader_provider:e.sessionContext.leaderProviderId,execution_mode:e.sessionContext.executionMode,participant_providers:e.sessionContext.participantProviderIds}:void 0,providers:{ollama:{available:S?.isAvailable()??!1,models:y},claude:{available:o!==void 0||s!==void 0,cli_path:l,host_backed:s!==void 0},gemini:{available:c!==void 0||u!==void 0,cli_path:p,autonomous_capable:c!==void 0,host_backed:u!==void 0},codex:{available:i!==void 0||a!==void 0,cli_path:d,autonomous_capable:i!==void 0,host_backed:a!==void 0}},infrastructure:{tmux:{available:_,path:f},git:{available:m!==null,worktree_support:P}},capabilities:{can_autonomous_work:w&&P,can_tmux_visible:_,can_parallel_workers:w&&P,max_parallel_workers:w?3:0,available_modes:U}};return Ec=$e,Yp=r,{content:[{type:"text",text:yS($e)}]}}function yS(t){let e=`# Environment Check
|
|
540
559
|
|
|
541
560
|
`;t.host&&(e+=`## Host Session
|
|
542
561
|
|
|
543
562
|
`,e+=`- **Host:** ${t.host.id}
|
|
544
563
|
`,e+=`- **Kind:** ${t.host.kind}
|
|
545
564
|
`,e+=`- **Leader Provider:** ${t.host.leader_provider}
|
|
546
|
-
`,e+=`- **Execution Mode:** ${
|
|
565
|
+
`,e+=`- **Execution Mode:** ${Tc(t.host.execution_mode,t.host.kind)}
|
|
547
566
|
`,e+=`- **Participants:** ${t.host.participant_providers.join(", ")}
|
|
548
567
|
|
|
549
568
|
`),e+=`## Providers
|
|
@@ -567,14 +586,14 @@ ${o}`}]}}var Lp={};Ze(Lp,{getTools:()=>ON,handleTool:()=>jN,resetCache:()=>MN});
|
|
|
567
586
|
`,e+=`- **tmux visible:** ${t.capabilities.can_tmux_visible?"Yes":"No"}
|
|
568
587
|
`,e+=`- **Parallel workers:** ${t.capabilities.can_parallel_workers?`Yes (max ${t.capabilities.max_parallel_workers})`:"No"}
|
|
569
588
|
`,e+=`- **Available modes:** ${t.capabilities.available_modes.join(", ")}
|
|
570
|
-
`,e}async function
|
|
589
|
+
`,e}async function pj(t,e,r){return t==="environment_check"?dj(e??{},r):{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var Qp={};Be(Qp,{getTools:()=>fj,handleTool:()=>xj});var bS=h.object({provider:h.string().trim().min(1),task_description:h.string().trim().min(1),working_dir:h.string().trim().min(1),files_to_read:h.array(h.string().trim().min(1)).optional(),files_to_modify:h.array(h.string().trim().min(1)).optional(),constraints:h.string().optional(),success_criteria:h.array(h.string().trim().min(1)).optional(),timeout_minutes:h.number().positive().optional(),use_worktree:h.boolean().optional(),use_tmux:h.boolean().optional()}).strict(),wS=h.object({worker_id:h.string().trim().min(1).optional()}).strict(),xS=h.object({worker_id:h.string().trim().min(1)}).strict(),SS=h.object({worker_id:h.string().trim().min(1)}).strict();function fj(){return[{name:"cli_worker_spawn",title:"Spawn CLI Worker",description:"Spawn a CLI AI worker (any registered provider; use `provider_list` to discover available) in autonomous mode. The worker runs in the background and can be monitored with cli_worker_status.",inputSchema:V(bS)},{name:"cli_worker_status",title:"Check CLI Worker Status",description:"Get the status of a CLI worker by ID, or list all tracked workers if no ID is given.",inputSchema:V(wS)},{name:"cli_worker_collect",title:"Collect CLI Worker Results",description:"Collect results from a successful COLLECTING worker, a completed worker, or a failed CLI worker. Returns full output, git diff, and changed files.",inputSchema:V(xS)},{name:"cli_worker_stop",title:"Stop CLI Worker",description:"Stop a running CLI worker. Sends SIGTERM, then SIGKILL after 5 seconds.",inputSchema:V(SS)}]}function Rc(t){if(!t.cliWorkerManager)throw new Error("CliWorkerManager not initialized \u2014 cli_worker tools are unavailable");return t.cliWorkerManager}function Rt(t,e){return{content:[{type:"text",text:t}],...e?{isError:e}:{}}}function mj(t){let e=`# Worker Spawned
|
|
571
590
|
|
|
572
591
|
`;return e+=`- **Worker ID:** ${t.workerId}
|
|
573
592
|
`,e+=`- **Provider:** ${t.provider}
|
|
574
593
|
`,e+=`- **State:** ${t.state}
|
|
575
594
|
`,e+=`- **PID:** ${t.pid??"N/A"}
|
|
576
595
|
`,t.worktreeBranch&&(e+=`- **Worktree Branch:** ${t.worktreeBranch}
|
|
577
|
-
`),e}function
|
|
596
|
+
`),e}function hj(t){let e=`# Worker Status
|
|
578
597
|
|
|
579
598
|
`;return e+=`- **Worker ID:** ${t.workerId}
|
|
580
599
|
`,e+=`- **Provider:** ${t.provider}
|
|
@@ -583,18 +602,18 @@ ${o}`}]}}var Lp={};Ze(Lp,{getTools:()=>ON,handleTool:()=>jN,resetCache:()=>MN});
|
|
|
583
602
|
`,e+=`- **PID:** ${t.pid??"N/A"}
|
|
584
603
|
`,e+=`- **Retry Count:** ${t.retryCount}
|
|
585
604
|
`,t.worktreeBranch&&(e+=`- **Worktree Branch:** ${t.worktreeBranch}
|
|
586
|
-
`),t.state
|
|
605
|
+
`),t.state===ke.COLLECTING&&(e+="- **Next Step:** Worker exited successfully and is ready for `cli_worker_collect`\n"),t.outputTail&&(e+=`
|
|
587
606
|
## Recent Output
|
|
588
607
|
|
|
589
608
|
\`\`\`
|
|
590
609
|
${t.outputTail}
|
|
591
610
|
\`\`\`
|
|
592
|
-
`),e}function
|
|
611
|
+
`),e}function gj(t){if(t.length===0)return`# Workers
|
|
593
612
|
|
|
594
613
|
No tracked workers.`;let e=`# Workers (${t.length})
|
|
595
614
|
|
|
596
615
|
`;for(let r of t)e+=`- **${r.workerId}** \u2014 ${r.provider} \u2014 ${r.state}`,r.pid&&(e+=` (PID ${r.pid})`),e+=`
|
|
597
|
-
`;return e}function
|
|
616
|
+
`;return e}function yj(t){let e=`# Worker Results
|
|
598
617
|
|
|
599
618
|
`;if(e+=`- **Worker ID:** ${t.workerId}
|
|
600
619
|
`,e+=`- **State:** ${t.state}
|
|
@@ -616,7 +635,7 @@ ${t.gitDiff}
|
|
|
616
635
|
\`\`\`
|
|
617
636
|
${t.outputFull}
|
|
618
637
|
\`\`\`
|
|
619
|
-
`),e}async function
|
|
638
|
+
`),e}async function vj(t,e){let r=Rc(e),n=bS.parse(t),o=r.knownProviders();if(!o.includes(n.provider))return Rt(`Unknown provider: "${n.provider}". Known: [${o.join(", ")}]`,!0);let s={provider:n.provider,taskDescription:n.task_description,workingDir:n.working_dir,filesToRead:n.files_to_read,filesToModify:n.files_to_modify,constraints:n.constraints,successCriteria:n.success_criteria,timeoutMinutes:n.timeout_minutes,useWorktree:n.use_worktree,useTmux:n.use_tmux};try{let i=r.spawn(s);return Rt(mj(i))}catch(i){let a=M(i);return Rt(`Error spawning worker: ${a}`,!0)}}async function _j(t,e){let r=Rc(e),n=wS.parse(t);if(!n.worker_id){let s=r.listAll();return Rt(gj(s))}let o=r.getStatus(n.worker_id);return o?Rt(hj(o)):Rt(`Worker not found: ${n.worker_id}`,!0)}async function bj(t,e){let r=Rc(e),n=xS.parse(t),o=r.collect(n.worker_id);return o?Rt(yj(o)):Rt(`Worker not found: ${n.worker_id}`,!0)}async function wj(t,e){let r=Rc(e),n=SS.parse(t);return r.stop(n.worker_id),Rt(`Stop signal sent to worker: ${n.worker_id}`)}async function xj(t,e,r){try{switch(t){case"cli_worker_spawn":return await vj(e??{},r);case"cli_worker_status":return await _j(e??{},r);case"cli_worker_collect":return await bj(e??{},r);case"cli_worker_stop":return await wj(e??{},r);default:return Rt(`Unknown tool: ${t}`,!0)}}catch(n){let o=M(n);return Rt(`Error: ${o}`,!0)}}var ef={};Be(ef,{getTools:()=>Sj,handleTool:()=>kj});var $S=h.object({design_doc:h.string().optional().describe("Optional design document path to verify against"),build_profile:h.enum(["auto","tsc","vitest","npm-build","npm-test"]).optional().describe("QA build profile to execute. Defaults to 'auto' which detects from project structure."),timeout_ms:h.number().int().positive().optional().describe("Timeout per command in milliseconds")}).strict();function Sj(){return[{name:"qa_run",title:"Run Auto QA",description:"Run automatic QA for the current project. Detects build/test commands, optionally includes a design document reference, and returns a PASS/FAIL summary with captured output.",inputSchema:V($S)}]}function $j(t){let e=`# Auto QA
|
|
620
639
|
|
|
621
640
|
${t.summary}
|
|
622
641
|
`;return t.designDoc&&(e+=`
|
|
@@ -633,12 +652,12 @@ ${t.buildOutput||"(no output)"}
|
|
|
633
652
|
\`\`\`
|
|
634
653
|
${t.testOutput||"(no output)"}
|
|
635
654
|
\`\`\`
|
|
636
|
-
`,e}async function
|
|
655
|
+
`,e}async function kj(t,e,r){if(t==="qa_run"){let n=$S.parse(e??{}),s=await new jo(r?.workspaceBaseDir??process.cwd()).run({designDoc:n.design_doc,buildProfile:n.build_profile??"auto",timeoutMs:n.timeout_ms});return{content:[{type:"text",text:$j(s)}],isError:!(s.buildPassed&&s.testsPassed)}}else return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var TS=[Ep,qp,Vp,Bp,Hp,Kp,Gp,Jp,Xp,Qp,ef];function ES(){let t=[];for(let e of TS)t.push(...e.getTools());return t}var PS=new Map;function Tj(t){return t.sessionId??"__default__"}function Ej(t){for(let e of t)if(!(typeof e.uri!="string"||!e.uri.startsWith("file://")))try{return Pj(e.uri)}catch{}}async function Rj(t,e,r){let n=Tj(r);try{let o=await t.listRoots(void 0,{timeout:1500}),s=Ej(o.roots);if(s)return PS.set(n,s),s}catch{}return PS.get(n)??e.workspaceBaseDir??process.cwd()}function Ij(t,e){return t.filter(r=>RS(r.name,e))}function Aj(t,e){let r=ir(t);if(r.invocation!=="cli"||!r.roles.includes("worker"))return!1;let n=e?.get(t.id)??"workspace-write";return si(n)}function RS(t,e){let r=e.registry.getAvailable(),n=r.length>0,o=r.some(i=>i.type==="ollama"),s=r.some(i=>Aj(i,e.providerPolicies));return t.startsWith("ollama_")?o:t.startsWith("cli_worker_")||t.startsWith("agent_changes_")?s&&e.cliWorkerManager!==void 0:t.startsWith("ai_")||t.startsWith("agent_debate_")||t==="agent_cross_validate"?n:!0}function Cj(t,e){let r=[],n=0;for(let o of t){let s=Buffer.byteLength(o,"utf-8");if(n+s>e)break;r.push(o),n+=s}return r.join("")}var tf=null;function Dj(){if(tf)return tf;let t=new Map;for(let e of TS)for(let r of e.getTools())t.set(r.name,e);return tf=t,t}function IS(t){let e=t.content.map(r=>r.type==="text"&&Buffer.byteLength(r.text,"utf-8")>51200?{type:"text",text:Cj(r.text,51200)+`
|
|
637
656
|
|
|
638
|
-
... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function
|
|
657
|
+
... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function AS(t,e,r){let o=Dj().get(t);if(!o)return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0};if(!RS(t,r))return{content:[{type:"text",text:`Tool unavailable in current environment: ${t}`}],isError:!0};let s={registry:r.registry,sessionManager:r.sessionManager,documentManager:r.documentManager,jobManager:r.jobManager,traceWriter:r.traceWriter,qualityStatsProvider:r.qualityStatsProvider,cliWorkerManager:r.cliWorkerManager,sessionContext:r.resolveSessionContext?.()??r.sessionContext,workspaceBaseDir:r.workspaceBaseDir,i18n:r.i18n,structuredSessionRegistry:r.structuredSessionRegistry,moderatorEngine:r.moderatorEngine},i=await o.handleTool(t,e,s);return IS(i)}function rf(t){let e=new Qa({name:"agestra",version:pf},{capabilities:{tools:{}}});return e.setRequestHandler(kl,async()=>({tools:Ij(ES(),t)})),e.setRequestHandler(ls,async(r,n)=>{let{name:o,arguments:s}=r.params;try{let i=await Rj(e,t,n),a=await t.resolveWorkspaceServices?.(i)??{},c=await AS(o,s??{},{...t,...a,workspaceBaseDir:i});return{content:c.content,isError:c.isError}}catch(i){return{content:[{type:"text",text:`Error: ${M(i)}`}],isError:!0}}}),e}async function nf(t){let e=new tc;await t.connect(e)}function CS(t){return typeof t=="object"&&t!==null&&t.type==="text"&&typeof t.text=="string"}function zj(t){return Array.isArray(t)?t.filter(CS).map(e=>e.text).join(`
|
|
639
658
|
|
|
640
|
-
`).trim():
|
|
641
|
-
`),e
|
|
642
|
-
`),process.exit(1)}),t(`Starting MCP server with ${o.getAll().length} provider(s)...`),await
|
|
643
|
-
`),process.exit(1)});export{
|
|
659
|
+
`).trim():CS(t)?t.text:""}function DS(t,e){let r=t?.[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function zS(t,e){let r=t?.[e];return typeof r=="string"&&r.length>0?r:void 0}function yo(t){let e=t?.toLowerCase()??"";return e.includes("claude")?"claude-code":e.includes("codex")?"codex-cli":e.includes("gemini")?"gemini-cli":"unknown"}function of(t,e,r){let n=()=>yo(t.getClientVersion()?.name);return{providerId:e,isAvailable(){return!!t.getClientCapabilities()?.sampling&&n()===r.expectedHostKind},async healthCheck(){if(!t.getClientCapabilities()?.sampling)return{status:"error",message:"Client does not support MCP sampling"};let o=n();return o!==r.expectedHostKind?{status:"error",message:`${r.displayName} host bridge requires a ${r.displayName} host, got ${o}`}:{status:"ok",message:`${r.displayName} host bridge available via ${t.getClientVersion()?.name??"unknown client"}`}},async runTurn(o){if(!this.isAvailable())throw new Error(r.unavailableMessage);let s=await t.createMessage({messages:[{role:"user",content:{type:"text",text:o.prompt}}],systemPrompt:o.system,includeContext:"none",maxTokens:DS(o.metadata,"maxTokens")??4096,temperature:DS(o.metadata,"temperature"),modelPreferences:zS(o.metadata,"model")?{hints:[{name:zS(o.metadata,"model")}]}:void 0,metadata:o.metadata}),i=zj(s.content);if(!i)throw new Error("Claude host bridge returned no text content");return{text:i,metadata:{model:s.model,stopReason:s.stopReason,hostKind:n()}}}}}function Ic(t,e="claude"){return of(t,e,{expectedHostKind:"claude-code",displayName:"Claude",unavailableMessage:"Claude host bridge unavailable or client does not support sampling"})}function Ac(t,e="codex-host"){return of(t,e,{expectedHostKind:"codex-cli",displayName:"Codex",unavailableMessage:"Codex host bridge unavailable or client does not support sampling"})}function Cc(t,e="gemini-host"){return of(t,e,{expectedHostKind:"gemini-cli",displayName:"Gemini",unavailableMessage:"Gemini host bridge unavailable or client does not support sampling"})}var Oj=[{type:"claude-host",defaultId:"claude",supportedHosts:["claude-code"],createProvider:(t,e)=>new _i({id:e,bridge:Ic(t,e)})},{type:"codex-host",defaultId:"codex-host",supportedHosts:["codex-cli"],createProvider:(t,e)=>new bi({id:e,bridge:Ac(t,e)})},{type:"gemini-host",defaultId:"gemini-host",supportedHosts:["gemini-cli"],createProvider:(t,e)=>new wi({id:e,bridge:Cc(t,e)})}];function vo(t,e,r){return t?.providers.find(o=>o.type===e||o.id===r)?.id??r}function Mj(t){switch(t){case"claude-code":return"claude-host";case"codex-cli":return"codex-host";case"gemini-cli":return"gemini-host";default:return}}function Nj(t,e){switch(t){case"claude-code":return vo(e,"claude-host","claude");case"codex-cli":return vo(e,"codex-host","codex-host");case"gemini-cli":return vo(e,"gemini-host","gemini-host");default:return}}function jj(t,e){return t.some(o=>o.roles.includes("worker")&&o.supportsAutonomousExecution)?"team":t.some(o=>o.id!==e&&o.supportsReadOnlyChat)&&t.length>1?"debate":"claude-only"}function sf(t,e){let r=()=>yo(t.getClientVersion()?.name),n=()=>Mj(r()),o=()=>Nj(r(),e);return{get id(){return r()},get kind(){return r()},get leaderProviderId(){return o()},get leaderProviderType(){return n()},get supportsHooks(){return r()==="claude-code"},get supportsInteractiveChoices(){return r()!=="unknown"},get supportsSampling(){return!!t.getClientCapabilities()?.sampling},createLeaderBridge(){switch(r()){case"claude-code":{let s=vo(e,"claude-host","claude");return Ic(t,s)}case"codex-cli":{let s=vo(e,"codex-host","codex-host");return Ac(t,s)}case"gemini-cli":{let s=vo(e,"gemini-host","gemini-host");return Cc(t,s)}default:return null}},createHostProviders(){let s=r();return Oj.flatMap(i=>{if(s==="unknown"||!i.supportedHosts.includes(s))return[];let a=e?.providers.find(u=>u.type===i.type||u.id===i.defaultId);if(a?.enabled===!1)return[];let c=a?.id??i.defaultId;return[{id:c,type:i.type,executionPolicy:a?.executionPolicy??Jt(i.type),provider:i.createProvider(t,c)}]})},createSessionContext(s){let i=s.filter(u=>u.supportsReadOnlyChat);if(i.length===0)return;let a=o(),c=(a?i.find(u=>u.id===a):void 0)??(n()?i.find(u=>u.type===n()):void 0)??i.find(u=>u.roles.includes("leader"))??i[0];return{hostId:r(),hostKind:r(),leaderProviderId:c.id,participantProviderIds:i.map(u=>u.id),executionMode:jj(i,c.id)}}}}async function af(t,e,r,n){let o=t.createHostProviders();for(let s of o)e.has(s.id)||(await s.provider.initialize(),e.register(s.provider),r.set(s.id,s.executionPolicy),n(`Registered provider: ${s.id} (${s.type})`))}function cf(t,e){let r=typeof e.getAvailableDescriptors=="function"?e.getAvailableDescriptors():e.getAvailable().map(n=>typeof e.getDescriptor=="function"?e.getDescriptor(n.id):{id:n.id,type:n.type,invocation:"unknown",roles:["participant"],supportsAutonomousExecution:!1,supportsReadOnlyChat:!0,supportsToolUse:n.getCapabilities().supportsToolUse});return t.createSessionContext?.(r)}import{existsSync as OS}from"fs";import{dirname as NS,join as Dc,resolve as jS,sep as Lj}from"path";import{fileURLToPath as Fj}from"url";var Zj=[Dc(".claude","plugins","cache"),Dc(".claude","plugins","local")];function Uj(t){let e=t.split(/[\\/]/).join(Lj);return Zj.some(r=>e.includes(r))}function qj(t){return!(!OS(Dc(t,"package.json"))||!OS(Dc(t,"AGENTS.md"))||Uj(t))}function MS(t){let e=jS(t);for(;;){if(qj(e))return e;let r=NS(e);if(r===e)return null;e=r}}function LS(){let t=process.env.AGESTRA_BASE_DIR?.trim();if(t)return jS(t);let e=NS(Fj(import.meta.url));return MS(process.cwd())??MS(e)??process.cwd()}function Wj(t){return{ollama:e=>new Gr({id:e.id,host:e.config?.host||_o}),"gemini-cli":e=>new Jr({id:e.id,timeout:e.config?.timeout}),"codex-cli":e=>new Yr({id:e.id,timeout:e.config?.timeout,workspaceBaseDir:t}),"claude-cli":e=>new Xr({id:e.id,timeout:e.config?.timeout})}}async function Hj(t,e,r){if(t.getAll().length>0)return r("Providers already registered, skipping auto-detect."),{detected:0};r("No providers found \u2014 running auto-detect...");try{let{results:n,providers:o}=await go({workspaceBaseDir:e}),s=n.filter(i=>i.available);return s.length===0?(r("Auto-detect found no available providers."),{detected:0}):(lS(o,t),r(`Auto-detected ${s.length} provider(s): ${s.map(i=>i.id).join(", ")}`),{detected:s.length})}catch(n){return r(`Auto-detect failed (non-fatal): ${M(n)}`),{detected:0}}}async function Kj(){let t=_=>process.stderr.write(`[mcp-server] ${_}
|
|
660
|
+
`),e=LS(),r=ko(),n;try{let _=Vj(r,"utf-8");n=JSON.parse(_)}catch(_){t(`Warning: Could not load ${r}: ${M(_)}`),t("Starting with empty provider registry."),n=null}let o=new Qs,s=null;if(n)try{s=qf(n)}catch(_){t(`Warning: Invalid provider config in ${r}: ${M(_)}`),t("Ignoring config and continuing with auto-detect defaults."),n=null}let i=Wj(e);if(s){let _=s.enabledProviders.map(A=>{let D=i[A.type];if(!D)return t(`Unknown provider type: ${A.type} (id: ${A.id}), skipping`),null;let U=D(A);return{pc:A,provider:U}}).filter(A=>A!==null),P=await Promise.allSettled(_.map(async({pc:A,provider:D})=>(await D.initialize(),{pc:A,provider:D})));for(let A of P)if(A.status==="fulfilled"){let{pc:D,provider:U}=A.value;o.register(U),t(`Registered provider: ${D.id} (${D.type})`)}else t(`Failed to initialize provider: ${M(A.reason)}`)}if(await Hj(o,e,t),s){let _=new Set(s.providers.filter(A=>!A.enabled).map(A=>A.id)),P=new Set(s.providers.filter(A=>!A.enabled).map(A=>A.type));try{let{providers:A}=await go({workspaceBaseDir:e}),D=Wp(A,o,{excludeIds:_,excludeTypes:P});for(let U of D)t(`Registered newly detected provider: ${U.id} (${U.type})`)}catch(A){t(`Supplemental provider detection failed (non-fatal): ${M(A)}`)}}let a=new Map(s?.providers.map(_=>[_.id,_.executionPolicy])??[]),c=new Map(o.getAll().map(_=>[_.id,a.get(_.id)??Jt(_.type)])),u;try{u=du(s?.locale)}catch(_){let P=_ instanceof Error?_.message:String(_);t(`[i18n] failed to load requested locale (${s?.locale??"default"}): ${P}. Retrying with default bundle.`),u=du(void 0)}t(`Localization active: ${u.locale}`);let l=new Map,d=()=>"unknown",p=async _=>{let P=l.get(_);if(P)return P;let A=new Oo(uf(_,yf)),D=new Uo(uf(_,bo)),U=new li(_,{completionHandler:async({descriptor:It,result:zc,saveAsDocument:Oc})=>!zc.output||zc.output.trim().length===0?null:{documentId:(await D.createDocument({title:Oc.title,content:zc.output,metadata:{...Oc.metadata,Provider:It.provider,Model:It.provider,JobId:It.id},kind:Oc.kind})).id}});try{let It=U.reconcileOrphans();It>0&&t(`Reconciled ${It} orphaned job(s) in ${_}`)}catch(It){t(`Job orphan reconcile failed for ${_}: ${M(It)}`)}let $e=new di(_);$e.cleanup(30);let G=new gi($e,{ttlMs:6e4}),_t=new Co(_,{providerPolicies:c}),Te=new fo(uf(_,bo));try{await Te.hydrateFromDisk()}catch(It){t(`Structured session registry hydrate failed for ${_}: ${M(It)}`)}let Pr=Sc(o,d(),_),fn=new mo({bridge:Pr,documentManager:D,registry:Te,i18n:u,traceWriter:$e}),lf={sessionManager:A,documentManager:D,jobManager:U,traceWriter:$e,qualityStatsProvider:G,cliWorkerManager:_t,structuredSessionRegistry:Te,moderatorEngine:fn};return l.set(_,lf),lf},f=await p(e),m={registry:o,...f,providerPolicies:c,workspaceBaseDir:e,resolveWorkspaceServices:async _=>p(_),i18n:u},g=rf(m),y=sf(g,s);d=()=>yo(g.getClientVersion()?.name),await af(y,o,c,t),m.resolveSessionContext=()=>cf(y,o);let v=setInterval(()=>{(async()=>{for(let _ of l.values())try{let P=await _.structuredSessionRegistry.sweepTimeouts();P.length>0&&await _.moderatorEngine.handleTimedOutSnapshots(P)}catch(P){t(`Session sweep failed: ${M(P)}`)}})()},Tf);v.unref?.();let S=!1,w=async()=>{if(!S){S=!0,t("Shutting down..."),clearInterval(v);for(let _ of l.values())_.traceWriter.shutdown();for(let _ of o.getAll())if(_.shutdown)try{await _.shutdown()}catch{}}};process.on("SIGTERM",()=>{w().finally(()=>process.exit(0))}),process.on("SIGINT",()=>{w().finally(()=>process.exit(0))}),process.on("uncaughtException",_=>{for(let P of l.values())P.traceWriter.panicFlush();process.stderr.write(`[mcp-server] Uncaught: ${_}
|
|
661
|
+
`),process.exit(1)}),t(`Starting MCP server with ${o.getAll().length} provider(s)...`),await nf(g),t("MCP server connected via stdio.")}var Gj=(()=>{if(typeof process>"u"||!process.argv[1])return!1;try{let t=Bj(import.meta.url),e=process.argv[1];return e===t||e.endsWith("/dist/bundle.js")}catch{return!1}})();Gj&&Kj().catch(t=>{process.stderr.write(`[mcp-server] Fatal: ${t}
|
|
662
|
+
`),process.exit(1)});export{Hj as autoDetectIfNeeded,ES as collectTools,nf as connectStdio,Ic as createClaudeLeaderBridge,Ac as createCodexLeaderBridge,Cc as createGeminiLeaderBridge,sf as createRuntimeHostAdapter,rf as createServer,AS as dispatch,yo as inferHostKindFromClientName,af as registerHostBackedProviders,cf as resolveSessionContext,IS as truncateResponse};
|
|
644
663
|
//# sourceMappingURL=bundle.js.map
|