agestra 4.12.2 → 4.12.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/AGENTS.md +1 -1
- package/GEMINI.md +1 -1
- package/README.md +4 -4
- package/agents/agestra-moderator.md +15 -15
- package/agents/agestra-team-lead.md +14 -12
- package/commands/design.md +7 -5
- package/commands/idea.md +9 -7
- package/commands/implement.md +2 -2
- package/commands/review.md +16 -10
- package/dist/bundle.js +290 -284
- package/package.json +3 -2
- package/skills/design.md +1 -0
- package/skills/idea.md +19 -30
- package/skills/review.md +10 -6
package/dist/bundle.js
CHANGED
|
@@ -1,93 +1,93 @@
|
|
|
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
|
-
`),
|
|
5
|
-
`)}catch{}return e()}finally{try{BA(a)}catch{}try{vv(t)}catch{}}}var JA,GA,YA,Dd,dc=Er(()=>{"use strict";JA=3e4,GA=5e3,YA=10,Dd=class extends Error{constructor(e,r){super(`withFileLock: timed out after ${r}ms waiting for ${e}`),this.name="FileLockTimeoutError"}}});import{existsSync as _v,realpathSync as XA}from"fs";import{basename as eC,dirname as tC,isAbsolute as zd,join as rC,normalize as wv,resolve as Nd,relative as nC}from"path";function oC(t){return t===""||!t.startsWith("..")&&!zd(t)}function Od(t){let e=[],r=Nd(t);for(;!_v(r);){let o=tC(r);if(o===r)break;e.unshift(eC(r)),r=o}let n=_v(r)?XA(r):r;return e.reduce((o,s)=>rC(o,s),n)}function $v(t,e){let r=Od(e),n=Od(t),o=nC(r,n);return oC(o)}function jd(t,e){let r=Nd(e,t);return $v(r,e)}function Mt(t,e){let r=Nd(e,t);if(!$v(r,e))throw new Error(`Path traversal blocked: ${t} escapes ${e}`);return r}function rt(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 Mt(t,e)}function Or(t,e){if(zd(t)){let r=wv(t);if(!jd(r,e))throw new Error(`Read path outside base directory: ${t} is not within ${e}`);return r}return Mt(t,e)}function Md(t,e){return zd(t)?Od(wv(t)):Mt(t,e)}function zr(t){return sC.test(t)}function pc(t,e){if(!t||typeof t!="string")throw new At(String(t),"command must be a non-empty string");if(t.includes("\0"))throw new At(t,"command contains null byte");if(t.includes("/")||t.includes("\\"))throw new At(t,"command must not contain path separators");if(!bv.has(t))throw new At(t,`command is not in the allowlist (${[...bv].join(", ")})`);for(let r of e){if(typeof r!="string")throw new At(t,`args contain a non-string entry: ${JSON.stringify(r)}`);if(r.includes("\0"))throw new At(t,`arg contains null byte: ${JSON.stringify(r)}`);if(iC.has(r))throw new At(t,`arg ${JSON.stringify(r)} is a code-execution flag and is not permitted`)}}var sC,bv,iC,At,No=Er(()=>{"use strict";sC=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;bv=new Set(["gemini","codex","claude","npx","node","npm","tsc"]),iC=new Set(["-e","--eval","-c","--command","-E","--execute","--exec"]),At=class extends Error{command;reason;constructor(e,r){super(`CLI command rejected: ${e} \u2014 ${r}`),this.command=e,this.reason=r,this.name="CliCommandRejectedError"}}});import{readFileSync as aC}from"fs";import{join as cC}from"path";function We(t,e){let r=cC(t,"status.json"),n=`${r}.lock`;Zn(n,()=>{let o=JSON.parse(aC(r,"utf-8"));Ve(r,{...o,...e})})}var ni=Er(()=>{"use strict";tn();dc()});import{spawn as uC}from"child_process";import{join as Ld}from"path";function fc(t){return new Promise(e=>{let r=Pn(t.command,t.args),n=uC(r.command,r.args,{cwd:t.cwd,stdio:["ignore","pipe","pipe"],windowsHide:!0});if(t.recordPid&&typeof n.pid=="number"&&n.pid>0)try{We(t.jobDir,{pid:n.pid})}catch{}if(!n.stdout||!n.stderr){try{n.kill()}catch{}try{ye(Ld(t.jobDir,"error.txt"),"Worker stdout/stderr streams unavailable (pipe allocation failed)"),We(t.jobDir,{state:"error",completedAt:new Date().toISOString()})}catch{}e();return}let o="",s="",i=0,a=0,c=!1,u=!1;n.stdout.on("data",p=>{i+=p.length,i<=10485760?o+=p.toString():c||(c=!0,Jr(n))}),n.stderr.on("data",p=>{a+=p.length,a<=10485760&&(s+=p.toString())});let l=(p,f)=>{if(!u){u=!0,clearTimeout(d);try{ye(Ld(t.jobDir,"output.txt"),o),ye(Ld(t.jobDir,"error.txt"),f!==void 0?f:s),We(t.jobDir,p)}catch{}e()}},d=setTimeout(()=>{Jr(n),l({state:"timed_out",completedAt:new Date().toISOString()})},t.timeoutMs);n.on("close",p=>{let f=o.trim().length>0;l({state:p===0||f?"completed":"error",exitCode:p??1,completedAt:new Date().toISOString()})}),n.on("error",p=>{let f=p.code==="ENOENT"?"missing_cli":"error";l({state:f,completedAt:new Date().toISOString()},p.message)})})}var qd=Er(()=>{"use strict";tn();Gs();Js();ni()});var Pv={};lt(Pv,{CLI_PROVIDERS:()=>xv,resolveCliConfig:()=>kv});import{readFileSync as Sv}from"fs";import{join as Vn}from"path";function kv(t){let e=lC[t.provider]??t.provider;return xv[e]??null}async function dC(){let t=process.argv[2];t||process.exit(1);let e;try{e=JSON.parse(Sv(Vn(t,"job.json"),"utf-8"))}catch{try{Ve(Vn(t,"status.json"),{id:"unknown",state:"error",provider:"unknown",completedAt:new Date().toISOString()}),ye(Vn(t,"error.txt"),"Failed to read job.json")}catch{}process.exit(1)}let r=kv(e);r||(We(t,{state:"missing_cli",completedAt:new Date().toISOString()}),ye(Vn(t,"error.txt"),`No CLI mapping for provider: ${e.provider}`),process.exit(1));let{command:n,buildArgs:o}=r;We(t,{state:"running",startedAt:new Date().toISOString()});let s=Sv(Vn(t,"prompt.txt"),"utf-8"),i=o(s);try{pc(n,i)}catch(c){let u=c instanceof At?c.message:`Argv rejected: ${c.message}`;We(t,{state:"error",completedAt:new Date().toISOString()}),ye(Vn(t,"error.txt"),u);return}let a;if(e.cwd)try{a=Mt(e.cwd,process.cwd())}catch(c){We(t,{state:"error",completedAt:new Date().toISOString()}),ye(Vn(t,"error.txt"),`Rejected descriptor.cwd: ${c.message}`);return}await fc({jobDir:t,command:n,args:i,cwd:a,timeoutMs:e.timeout,recordPid:!1})}var lC,xv,pC,Ev=Er(()=>{"use strict";tn();No();qd();ni();lC={"gemini-cli":"gemini","codex-cli":"codex","claude-cli":"claude"},xv={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]}};pC=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");pC&&dC().catch(()=>process.exit(1))});var Vi=$(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.regexpCode=me.getEsmExportName=me.getProperty=me.safeStringify=me.stringify=me.strConcat=me.addCodeArg=me.str=me._=me.nil=me._Code=me.Name=me.IDENTIFIER=me._CodeOrName=void 0;var Ui=class{};me._CodeOrName=Ui;me.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Xn=class extends Ui{constructor(e){if(super(),!me.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}}};me.Name=Xn;var Ut=class extends Ui{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 Xn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};me._Code=Ut;me.nil=new Ut("");function DS(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Sf(r,e[n]),r.push(t[++n]);return new Ut(r)}me._=DS;var $f=new Ut("+");function OS(t,...e){let r=[Zi(t[0])],n=0;for(;n<e.length;)r.push($f),Sf(r,e[n]),r.push($f,Zi(t[++n]));return gj(r),new Ut(r)}me.str=OS;function Sf(t,e){e instanceof Ut?t.push(...e._items):e instanceof Xn?t.push(e):t.push(_j(e))}me.addCodeArg=Sf;function gj(t){let e=1;for(;e<t.length-1;){if(t[e]===$f){let r=yj(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function yj(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Xn||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 Xn))return`"${t}${e.slice(1)}`}function vj(t,e){return e.emptyStr()?t:t.emptyStr()?e:OS`${t}${e}`}me.strConcat=vj;function _j(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Zi(Array.isArray(t)?t.join(","):t)}function bj(t){return new Ut(Zi(t))}me.stringify=bj;function Zi(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}me.safeStringify=Zi;function wj(t){return typeof t=="string"&&me.IDENTIFIER.test(t)?new Ut(`.${t}`):DS`[${t}]`}me.getProperty=wj;function $j(t){if(typeof t=="string"&&me.IDENTIFIER.test(t))return new Ut(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}me.getEsmExportName=$j;function Sj(t){return new Ut(t.toString())}me.regexpCode=Sj});var Pf=$(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.ValueScope=St.ValueScopeName=St.Scope=St.varKinds=St.UsedValueState=void 0;var $t=Vi(),xf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},wu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(wu||(St.UsedValueState=wu={}));St.varKinds={const:new $t.Name("const"),let:new $t.Name("let"),var:new $t.Name("var")};var $u=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof $t.Name?e:this.name(e)}name(e){return new $t.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}}};St.Scope=$u;var Su=class extends $t.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,$t._)`.${new $t.Name(r)}[${n}]`}};St.ValueScopeName=Su;var xj=(0,$t._)`\n`,kf=class extends $u{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?xj:$t.nil}}get(){return this._scope}name(e){return new Su(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,$t._)`${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=$t.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,wu.Started);let l=r(u);if(l){let d=this.opts.es5?St.varKinds.var:St.varKinds.const;s=(0,$t._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,$t._)`${s}${l}${this.opts._n}`;else throw new xf(u);c.set(u,wu.Completed)})}return s}};St.ValueScope=kf});var te=$(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.or=X.and=X.not=X.CodeGen=X.operators=X.varKinds=X.ValueScopeName=X.ValueScope=X.Scope=X.Name=X.regexpCode=X.stringify=X.getProperty=X.nil=X.strConcat=X.str=X._=void 0;var ce=Vi(),er=Pf(),cn=Vi();Object.defineProperty(X,"_",{enumerable:!0,get:function(){return cn._}});Object.defineProperty(X,"str",{enumerable:!0,get:function(){return cn.str}});Object.defineProperty(X,"strConcat",{enumerable:!0,get:function(){return cn.strConcat}});Object.defineProperty(X,"nil",{enumerable:!0,get:function(){return cn.nil}});Object.defineProperty(X,"getProperty",{enumerable:!0,get:function(){return cn.getProperty}});Object.defineProperty(X,"stringify",{enumerable:!0,get:function(){return cn.stringify}});Object.defineProperty(X,"regexpCode",{enumerable:!0,get:function(){return cn.regexpCode}});Object.defineProperty(X,"Name",{enumerable:!0,get:function(){return cn.Name}});var Eu=Pf();Object.defineProperty(X,"Scope",{enumerable:!0,get:function(){return Eu.Scope}});Object.defineProperty(X,"ValueScope",{enumerable:!0,get:function(){return Eu.ValueScope}});Object.defineProperty(X,"ValueScopeName",{enumerable:!0,get:function(){return Eu.ValueScopeName}});Object.defineProperty(X,"varKinds",{enumerable:!0,get:function(){return Eu.varKinds}});X.operators={GT:new ce._Code(">"),GTE:new ce._Code(">="),LT:new ce._Code("<"),LTE:new ce._Code("<="),EQ:new ce._Code("==="),NEQ:new ce._Code("!=="),NOT:new ce._Code("!"),OR:new ce._Code("||"),AND:new ce._Code("&&"),ADD:new ce._Code("+")};var Mr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Ef=class extends Mr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?er.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=ss(this.rhs,e,r)),this}get names(){return this.rhs instanceof ce._CodeOrName?this.rhs.names:{}}},xu=class extends Mr{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 ce.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ss(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ce.Name?{}:{...this.lhs.names};return Pu(e,this.rhs)}},Tf=class extends xu{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Rf=class extends Mr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},If=class extends Mr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Af=class extends Mr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Cf=class extends Mr{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=ss(this.code,e,r),this}get names(){return this.code instanceof ce._CodeOrName?this.code.names:{}}},Bi=class extends Mr{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)||(kj(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>ro(e,r.names),{})}},Lr=class extends Bi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Df=class extends Bi{},os=class extends Lr{};os.kind="else";var eo=class t extends Lr{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 os(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(zS(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=ss(this.condition,e,r),this}get names(){let e=super.names;return Pu(e,this.condition),this.else&&ro(e,this.else.names),e}};eo.kind="if";var to=class extends Lr{};to.kind="for";var Of=class extends to{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=ss(this.iteration,e,r),this}get names(){return ro(super.names,this.iteration.names)}},zf=class extends to{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?er.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=Pu(super.names,this.from);return Pu(e,this.to)}},ku=class extends to{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=ss(this.iterable,e,r),this}get names(){return ro(super.names,this.iterable.names)}},Wi=class extends Lr{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)}};Wi.kind="func";var Hi=class extends Bi{render(e){return"return "+super.render(e)}};Hi.kind="return";var Nf=class extends Lr{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&&ro(e,this.catch.names),this.finally&&ro(e,this.finally.names),e}},Ki=class extends Lr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ki.kind="catch";var Ji=class extends Lr{render(e){return"finally"+super.render(e)}};Ji.kind="finally";var jf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
6
|
-
`:""},this._extScope=e,this._scope=new er.Scope({parent:e}),this._nodes=[new Df]}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 Ef(e,s,n)),s}const(e,r,n){return this._def(er.varKinds.const,e,r,n)}let(e,r,n){return this._def(er.varKinds.let,e,r,n)}var(e,r,n){return this._def(er.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new xu(e,r,n))}add(e,r){return this._leafNode(new Tf(e,X.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ce.nil&&this._leafNode(new Cf(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,ce.addCodeArg)(r,o));return r.push("}"),new ce._Code(r)}if(e,r,n){if(this._blockNode(new eo(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 eo(e))}else(){return this._elseNode(new os)}endIf(){return this._endBlockNode(eo,os)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Of(e),r)}forRange(e,r,n,o,s=this.opts.es5?er.varKinds.var:er.varKinds.let){let i=this._scope.toName(e);return this._for(new zf(s,i,r,n),()=>o(i))}forOf(e,r,n,o=er.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ce.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ce._)`${i}.length`,a=>{this.var(s,(0,ce._)`${i}[${a}]`),n(s)})}return this._for(new ku("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?er.varKinds.var:er.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ce._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new ku("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(to)}label(e){return this._leafNode(new Rf(e))}break(e){return this._leafNode(new If(e))}return(e){let r=new Hi;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Hi)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Nf;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Ki(s),r(s)}return n&&(this._currNode=o.finally=new Ji,this.code(n)),this._endBlockNode(Ki,Ji)}throw(e){return this._leafNode(new Af(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=ce.nil,n,o){return this._blockNode(new Wi(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Wi)}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 eo))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}};X.CodeGen=jf;function ro(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Pu(t,e){return e instanceof ce._CodeOrName?ro(t,e.names):t}function ss(t,e,r){if(t instanceof ce.Name)return n(t);if(!o(t))return t;return new ce._Code(t._items.reduce((s,i)=>(i instanceof ce.Name&&(i=n(i)),i instanceof ce._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 ce._Code&&s._items.some(i=>i instanceof ce.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function kj(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function zS(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ce._)`!${Mf(t)}`}X.not=zS;var Pj=NS(X.operators.AND);function Ej(...t){return t.reduce(Pj)}X.and=Ej;var Tj=NS(X.operators.OR);function Rj(...t){return t.reduce(Tj)}X.or=Rj;function NS(t){return(e,r)=>e===ce.nil?r:r===ce.nil?e:(0,ce._)`${Mf(e)} ${t} ${Mf(r)}`}function Mf(t){return t instanceof ce.Name?t:(0,ce._)`(${t})`}});var le=$(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.checkStrictMode=re.getErrorPath=re.Type=re.useFunc=re.setEvaluated=re.evaluatedPropsToName=re.mergeEvaluated=re.eachItem=re.unescapeJsonPointer=re.escapeJsonPointer=re.escapeFragment=re.unescapeFragment=re.schemaRefOrVal=re.schemaHasRulesButRef=re.schemaHasRules=re.checkUnknownRules=re.alwaysValidSchema=re.toHash=void 0;var we=te(),Ij=Vi();function Aj(t){let e={};for(let r of t)e[r]=!0;return e}re.toHash=Aj;function Cj(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(LS(t,e),!qS(e,t.self.RULES.all))}re.alwaysValidSchema=Cj;function LS(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]||ZS(t,`unknown keyword: "${s}"`)}re.checkUnknownRules=LS;function qS(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}re.schemaHasRules=qS;function Dj(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}re.schemaHasRulesButRef=Dj;function Oj({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,we._)`${r}`}return(0,we._)`${t}${e}${(0,we.getProperty)(n)}`}re.schemaRefOrVal=Oj;function zj(t){return FS(decodeURIComponent(t))}re.unescapeFragment=zj;function Nj(t){return encodeURIComponent(qf(t))}re.escapeFragment=Nj;function qf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=qf;function FS(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=FS;function jj(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}re.eachItem=jj;function jS({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof we.Name?(s instanceof we.Name?t(o,s,i):e(o,s,i),i):s instanceof we.Name?(e(o,i,s),s):r(s,i);return a===we.Name&&!(c instanceof we.Name)?n(o,c):c}}re.mergeEvaluated={props:jS({mergeNames:(t,e,r)=>t.if((0,we._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,we._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,we._)`${r} || {}`).code((0,we._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,we._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,we._)`${r} || {}`),Ff(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:US}),items:jS({mergeNames:(t,e,r)=>t.if((0,we._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,we._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,we._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,we._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function US(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,we._)`{}`);return e!==void 0&&Ff(t,r,e),r}re.evaluatedPropsToName=US;function Ff(t,e,r){Object.keys(r).forEach(n=>t.assign((0,we._)`${e}${(0,we.getProperty)(n)}`,!0))}re.setEvaluated=Ff;var MS={};function Mj(t,e){return t.scopeValue("func",{ref:e,code:MS[e.code]||(MS[e.code]=new Ij._Code(e.code))})}re.useFunc=Mj;var Lf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Lf||(re.Type=Lf={}));function Lj(t,e,r){if(t instanceof we.Name){let n=e===Lf.Num;return r?n?(0,we._)`"[" + ${t} + "]"`:(0,we._)`"['" + ${t} + "']"`:n?(0,we._)`"/" + ${t}`:(0,we._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,we.getProperty)(t).toString():"/"+qf(t)}re.getErrorPath=Lj;function ZS(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}re.checkStrictMode=ZS});var qr=$(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var ot=te(),qj={data:new ot.Name("data"),valCxt:new ot.Name("valCxt"),instancePath:new ot.Name("instancePath"),parentData:new ot.Name("parentData"),parentDataProperty:new ot.Name("parentDataProperty"),rootData:new ot.Name("rootData"),dynamicAnchors:new ot.Name("dynamicAnchors"),vErrors:new ot.Name("vErrors"),errors:new ot.Name("errors"),this:new ot.Name("this"),self:new ot.Name("self"),scope:new ot.Name("scope"),json:new ot.Name("json"),jsonPos:new ot.Name("jsonPos"),jsonLen:new ot.Name("jsonLen"),jsonPart:new ot.Name("jsonPart")};Uf.default=qj});var Gi=$(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.extendErrors=st.resetErrorsCount=st.reportExtraError=st.reportError=st.keyword$DataError=st.keywordError=void 0;var de=te(),Tu=le(),mt=qr();st.keywordError={message:({keyword:t})=>(0,de.str)`must pass "${t}" keyword validation`};st.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,de.str)`"${t}" keyword must be ${e} ($data)`:(0,de.str)`"${t}" keyword is invalid ($data)`};function Fj(t,e=st.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=WS(t,e,r);n??(i||a)?VS(s,c):BS(o,(0,de._)`[${c}]`)}st.reportError=Fj;function Uj(t,e=st.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=WS(t,e,r);VS(o,a),s||i||BS(n,mt.default.vErrors)}st.reportExtraError=Uj;function Zj(t,e){t.assign(mt.default.errors,e),t.if((0,de._)`${mt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,de._)`${mt.default.vErrors}.length`,e),()=>t.assign(mt.default.vErrors,null)))}st.resetErrorsCount=Zj;function Vj({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,mt.default.errors,a=>{t.const(i,(0,de._)`${mt.default.vErrors}[${a}]`),t.if((0,de._)`${i}.instancePath === undefined`,()=>t.assign((0,de._)`${i}.instancePath`,(0,de.strConcat)(mt.default.instancePath,s.errorPath))),t.assign((0,de._)`${i}.schemaPath`,(0,de.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,de._)`${i}.schema`,r),t.assign((0,de._)`${i}.data`,n))})}st.extendErrors=Vj;function VS(t,e){let r=t.const("err",e);t.if((0,de._)`${mt.default.vErrors} === null`,()=>t.assign(mt.default.vErrors,(0,de._)`[${r}]`),(0,de._)`${mt.default.vErrors}.push(${r})`),t.code((0,de._)`${mt.default.errors}++`)}function BS(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,de._)`new ${t.ValidationError}(${e})`):(r.assign((0,de._)`${n}.errors`,e),r.return(!1))}var no={keyword:new de.Name("keyword"),schemaPath:new de.Name("schemaPath"),params:new de.Name("params"),propertyName:new de.Name("propertyName"),message:new de.Name("message"),schema:new de.Name("schema"),parentSchema:new de.Name("parentSchema")};function WS(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,de._)`{}`:Bj(t,e,r)}function Bj(t,e,r={}){let{gen:n,it:o}=t,s=[Wj(o,r),Hj(t,r)];return Kj(t,e,s),n.object(...s)}function Wj({errorPath:t},{instancePath:e}){let r=e?(0,de.str)`${t}${(0,Tu.getErrorPath)(e,Tu.Type.Str)}`:t;return[mt.default.instancePath,(0,de.strConcat)(mt.default.instancePath,r)]}function Hj({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,de.str)`${e}/${t}`;return r&&(o=(0,de.str)`${o}${(0,Tu.getErrorPath)(r,Tu.Type.Str)}`),[no.schemaPath,o]}function Kj(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([no.keyword,o],[no.params,typeof e=="function"?e(t):e||(0,de._)`{}`]),c.messages&&n.push([no.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([no.schema,i],[no.parentSchema,(0,de._)`${l}${d}`],[mt.default.data,s]),u&&n.push([no.propertyName,u])}});var KS=$(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.boolOrEmptySchema=is.topBoolOrEmptySchema=void 0;var Jj=Gi(),Gj=te(),Yj=qr(),Qj={message:"boolean schema is false"};function Xj(t){let{gen:e,schema:r,validateName:n}=t;r===!1?HS(t,!1):typeof r=="object"&&r.$async===!0?e.return(Yj.default.data):(e.assign((0,Gj._)`${n}.errors`,null),e.return(!0))}is.topBoolOrEmptySchema=Xj;function eM(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),HS(t)):r.var(e,!0)}is.boolOrEmptySchema=eM;function HS(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,Jj.reportError)(o,Qj,void 0,e)}});var Zf=$(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.getRules=as.isJSONType=void 0;var tM=["string","number","integer","boolean","null","object","array"],rM=new Set(tM);function nM(t){return typeof t=="string"&&rM.has(t)}as.isJSONType=nM;function oM(){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:{}}}as.getRules=oM});var Vf=$(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.shouldUseRule=un.shouldUseGroup=un.schemaHasRulesForType=void 0;function sM({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&JS(t,n)}un.schemaHasRulesForType=sM;function JS(t,e){return e.rules.some(r=>GS(t,r))}un.shouldUseGroup=JS;function GS(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))}un.shouldUseRule=GS});var Yi=$(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.reportTypeError=it.checkDataTypes=it.checkDataType=it.coerceAndCheckDataType=it.getJSONTypes=it.getSchemaTypes=it.DataType=void 0;var iM=Zf(),aM=Vf(),cM=Gi(),K=te(),YS=le(),cs;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(cs||(it.DataType=cs={}));function uM(t){let e=QS(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}it.getSchemaTypes=uM;function QS(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(iM.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}it.getJSONTypes=QS;function lM(t,e){let{gen:r,data:n,opts:o}=t,s=dM(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,aM.schemaHasRulesForType)(t,e[0]));if(i){let a=Wf(e,n,o.strictNumbers,cs.Wrong);r.if(a,()=>{s.length?pM(t,e,s):Hf(t)})}return i}it.coerceAndCheckDataType=lM;var XS=new Set(["string","number","integer","boolean","null"]);function dM(t,e){return e?t.filter(r=>XS.has(r)||e==="array"&&r==="array"):[]}function pM(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,K._)`typeof ${o}`),a=n.let("coerced",(0,K._)`undefined`);s.coerceTypes==="array"&&n.if((0,K._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,K._)`${o}[0]`).assign(i,(0,K._)`typeof ${o}`).if(Wf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,K._)`${a} !== undefined`);for(let u of r)(XS.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Hf(t),n.endIf(),n.if((0,K._)`${a} !== undefined`,()=>{n.assign(o,a),fM(t,a)});function c(u){switch(u){case"string":n.elseIf((0,K._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,K._)`"" + ${o}`).elseIf((0,K._)`${o} === null`).assign(a,(0,K._)`""`);return;case"number":n.elseIf((0,K._)`${i} == "boolean" || ${o} === null
|
|
7
|
-
|| (${i} == "string" && ${
|
|
8
|
-
|| (${i} === "string" && ${
|
|
9
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,K._)`[${o}]`)}}}function fM({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,K._)`${e} !== undefined`,()=>t.assign((0,K._)`${e}[${r}]`,n))}function Bf(t,e,r,n=cs.Correct){let o=n===cs.Correct?K.operators.EQ:K.operators.NEQ,s;switch(t){case"null":return(0,K._)`${e} ${o} null`;case"array":s=(0,K._)`Array.isArray(${e})`;break;case"object":s=(0,K._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,K._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,K._)`typeof ${e} ${o} ${t}`}return n===cs.Correct?s:(0,K.not)(s);function i(a=K.nil){return(0,K.and)((0,K._)`typeof ${e} == "number"`,a,r?(0,K._)`isFinite(${e})`:K.nil)}}it.checkDataType=Bf;function Wf(t,e,r,n){if(t.length===1)return Bf(t[0],e,r,n);let o,s=(0,YS.toHash)(t);if(s.array&&s.object){let i=(0,K._)`typeof ${e} != "object"`;o=s.null?i:(0,K._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=K.nil;s.number&&delete s.integer;for(let i in s)o=(0,K.and)(o,Bf(i,e,r,n));return o}it.checkDataTypes=Wf;var mM={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,K._)`{type: ${t}}`:(0,K._)`{type: ${e}}`};function Hf(t){let e=hM(t);(0,cM.reportError)(e,mM)}it.reportTypeError=Hf;function hM(t){let{gen:e,data:r,schema:n}=t,o=(0,YS.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var tx=$(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});Ru.assignDefaults=void 0;var us=te(),gM=le();function yM(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)ex(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>ex(t,s,o.default))}Ru.assignDefaults=yM;function ex(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,us._)`${s}${(0,us.getProperty)(e)}`;if(o){(0,gM.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,us._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,us._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,us._)`${a} = ${(0,us.stringify)(r)}`)}});var Zt=$(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.validateUnion=_e.validateArray=_e.usePattern=_e.callValidateCode=_e.schemaProperties=_e.allSchemaProperties=_e.noPropertyInData=_e.propertyInData=_e.isOwnProperty=_e.hasPropFunc=_e.reportMissingProp=_e.checkMissingProp=_e.checkReportMissingProp=void 0;var Re=te(),Kf=le(),ln=qr(),vM=le();function _M(t,e){let{gen:r,data:n,it:o}=t;r.if(Gf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Re._)`${e}`},!0),t.error()})}_e.checkReportMissingProp=_M;function bM({gen:t,data:e,it:{opts:r}},n,o){return(0,Re.or)(...n.map(s=>(0,Re.and)(Gf(t,e,s,r.ownProperties),(0,Re._)`${o} = ${s}`)))}_e.checkMissingProp=bM;function wM(t,e){t.setParams({missingProperty:e},!0),t.error()}_e.reportMissingProp=wM;function rx(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Re._)`Object.prototype.hasOwnProperty`})}_e.hasPropFunc=rx;function Jf(t,e,r){return(0,Re._)`${rx(t)}.call(${e}, ${r})`}_e.isOwnProperty=Jf;function $M(t,e,r,n){let o=(0,Re._)`${e}${(0,Re.getProperty)(r)} !== undefined`;return n?(0,Re._)`${o} && ${Jf(t,e,r)}`:o}_e.propertyInData=$M;function Gf(t,e,r,n){let o=(0,Re._)`${e}${(0,Re.getProperty)(r)} === undefined`;return n?(0,Re.or)(o,(0,Re.not)(Jf(t,e,r))):o}_e.noPropertyInData=Gf;function nx(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}_e.allSchemaProperties=nx;function SM(t,e){return nx(e).filter(r=>!(0,Kf.alwaysValidSchema)(t,e[r]))}_e.schemaProperties=SM;function xM({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Re._)`${t}, ${e}, ${n}${o}`:e,d=[[ln.default.instancePath,(0,Re.strConcat)(ln.default.instancePath,s)],[ln.default.parentData,i.parentData],[ln.default.parentDataProperty,i.parentDataProperty],[ln.default.rootData,ln.default.rootData]];i.opts.dynamicRef&&d.push([ln.default.dynamicAnchors,ln.default.dynamicAnchors]);let p=(0,Re._)`${l}, ${r.object(...d)}`;return c!==Re.nil?(0,Re._)`${a}.call(${c}, ${p})`:(0,Re._)`${a}(${p})`}_e.callValidateCode=xM;var kM=(0,Re._)`new RegExp`;function PM({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,Re._)`${o.code==="new RegExp"?kM:(0,vM.useFunc)(t,o)}(${r}, ${n})`})}_e.usePattern=PM;function EM(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,Re._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Kf.Type.Num},s),e.if((0,Re.not)(s),a)})}}_e.validateArray=EM;function TM(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,Kf.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,Re._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Re.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}_e.validateUnion=TM});var ix=$(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.validateKeywordUsage=vr.validSchemaType=vr.funcKeywordCode=vr.macroKeywordCode=void 0;var ht=te(),oo=qr(),RM=Zt(),IM=Gi();function AM(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=sx(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:ht.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}vr.macroKeywordCode=AM;function CM(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;OM(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=sx(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)h(),e.modifying&&ox(t),y(()=>t.error());else{let v=e.async?f():m();e.modifying&&ox(t),y(()=>DM(t,v))}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>h((0,ht._)`await `),b=>n.assign(d,!1).if((0,ht._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,ht._)`${b}.errors`),()=>n.throw(b))),v}function m(){let v=(0,ht._)`${l}.errors`;return n.assign(v,null),h(ht.nil),v}function h(v=e.async?(0,ht._)`await `:ht.nil){let b=c.opts.passContext?oo.default.this:oo.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ht._)`${v}${(0,RM.callValidateCode)(t,l,b,_)}`,e.modifying)}function y(v){var b;n.if((0,ht.not)((b=e.valid)!==null&&b!==void 0?b:d),v)}}vr.funcKeywordCode=CM;function ox(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ht._)`${n.parentData}[${n.parentDataProperty}]`))}function DM(t,e){let{gen:r}=t;r.if((0,ht._)`Array.isArray(${e})`,()=>{r.assign(oo.default.vErrors,(0,ht._)`${oo.default.vErrors} === null ? ${e} : ${oo.default.vErrors}.concat(${e})`).assign(oo.default.errors,(0,ht._)`${oo.default.vErrors}.length`),(0,IM.extendErrors)(t)},()=>t.error())}function OM({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function sx(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,ht.stringify)(r)})}function zM(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")}vr.validSchemaType=zM;function NM({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)}}vr.validateKeywordUsage=NM});var cx=$(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.extendSubschemaMode=dn.extendSubschemaData=dn.getSubschema=void 0;var _r=te(),ax=le();function jM(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,_r._)`${t.schemaPath}${(0,_r.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,_r._)`${t.schemaPath}${(0,_r.getProperty)(e)}${(0,_r.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,ax.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')}dn.getSubschema=jM;function MM(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,_r._)`${e.data}${(0,_r.getProperty)(r)}`,!0);c(p),t.errorPath=(0,_r.str)`${u}${(0,ax.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,_r._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof _r.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]}}dn.extendSubschemaData=MM;function LM(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}dn.extendSubschemaMode=LM});var Qi=$((bX,ux)=>{"use strict";ux.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 dx=$((wX,lx)=>{"use strict";var pn=lx.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(){};Iu(e,n,o,t,"",t)};pn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};pn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};pn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};pn.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 Iu(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 pn.arrayKeywords)for(var p=0;p<d.length;p++)Iu(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in pn.propsKeywords){if(d&&typeof d=="object")for(var f in d)Iu(t,e,r,d[f],o+"/"+l+"/"+qM(f),s,o,l,n,f)}else(l in pn.keywords||t.allKeys&&!(l in pn.skipKeywords))&&Iu(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function qM(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Xi=$(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.getSchemaRefs=xt.resolveUrl=xt.normalizeId=xt._getFullPath=xt.getFullPath=xt.inlineRef=void 0;var FM=le(),UM=Qi(),ZM=dx(),VM=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function BM(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Yf(t):e?px(t)<=e:!1}xt.inlineRef=BM;var WM=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Yf(t){for(let e in t){if(WM.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Yf)||typeof r=="object"&&Yf(r))return!0}return!1}function px(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!VM.has(r)&&(typeof t[r]=="object"&&(0,FM.eachItem)(t[r],n=>e+=px(n)),e===1/0))return 1/0}return e}function fx(t,e="",r){r!==!1&&(e=ls(e));let n=t.parse(e);return mx(t,n)}xt.getFullPath=fx;function mx(t,e){return t.serialize(e).split("#")[0]+"#"}xt._getFullPath=mx;var HM=/#\/?$/;function ls(t){return t?t.replace(HM,""):""}xt.normalizeId=ls;function KM(t,e,r){return r=ls(r),t.resolve(e,r)}xt.resolveUrl=KM;var JM=/^[a-z_][-a-z0-9._]*$/i;function GM(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=ls(t[r]||e),s={"":o},i=fx(n,o,!1),a={},c=new Set;return ZM(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=i+p,y=s[m];typeof d[r]=="string"&&(y=v.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),s[p]=y;function v(_){let k=this.opts.uriResolver.resolve;if(_=ls(y?k(y,_):_),c.has(_))throw l(_);c.add(_);let x=this.refs[_];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?u(d,x.schema,_):_!==ls(h)&&(_[0]==="#"?(u(d,a[_],_),a[_]=d):this.refs[_]=h),_}function b(_){if(typeof _=="string"){if(!JM.test(_))throw new Error(`invalid anchor "${_}"`);v.call(this,`#${_}`)}}}),a;function u(d,p,f){if(p!==void 0&&!UM(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}xt.getSchemaRefs=GM});var ra=$(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.getData=fn.KeywordCxt=fn.validateFunctionCode=void 0;var _x=KS(),hx=Yi(),Xf=Vf(),Au=Yi(),YM=tx(),ta=ix(),Qf=cx(),O=te(),V=qr(),QM=Xi(),Fr=le(),ea=Gi();function XM(t){if($x(t)&&(Sx(t),wx(t))){r1(t);return}bx(t,()=>(0,_x.topBoolOrEmptySchema)(t))}fn.validateFunctionCode=XM;function bx({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,O._)`${V.default.data}, ${V.default.valCxt}`,n.$async,()=>{t.code((0,O._)`"use strict"; ${gx(r,o)}`),t1(t,o),t.code(s)}):t.func(e,(0,O._)`${V.default.data}, ${e1(o)}`,n.$async,()=>t.code(gx(r,o)).code(s))}function e1(t){return(0,O._)`{${V.default.instancePath}="", ${V.default.parentData}, ${V.default.parentDataProperty}, ${V.default.rootData}=${V.default.data}${t.dynamicRef?(0,O._)`, ${V.default.dynamicAnchors}={}`:O.nil}}={}`}function t1(t,e){t.if(V.default.valCxt,()=>{t.var(V.default.instancePath,(0,O._)`${V.default.valCxt}.${V.default.instancePath}`),t.var(V.default.parentData,(0,O._)`${V.default.valCxt}.${V.default.parentData}`),t.var(V.default.parentDataProperty,(0,O._)`${V.default.valCxt}.${V.default.parentDataProperty}`),t.var(V.default.rootData,(0,O._)`${V.default.valCxt}.${V.default.rootData}`),e.dynamicRef&&t.var(V.default.dynamicAnchors,(0,O._)`${V.default.valCxt}.${V.default.dynamicAnchors}`)},()=>{t.var(V.default.instancePath,(0,O._)`""`),t.var(V.default.parentData,(0,O._)`undefined`),t.var(V.default.parentDataProperty,(0,O._)`undefined`),t.var(V.default.rootData,V.default.data),e.dynamicRef&&t.var(V.default.dynamicAnchors,(0,O._)`{}`)})}function r1(t){let{schema:e,opts:r,gen:n}=t;bx(t,()=>{r.$comment&&e.$comment&&kx(t),a1(t),n.let(V.default.vErrors,null),n.let(V.default.errors,0),r.unevaluated&&n1(t),xx(t),l1(t)})}function n1(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 gx(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 o1(t,e){if($x(t)&&(Sx(t),wx(t))){s1(t,e);return}(0,_x.boolOrEmptySchema)(t,e)}function wx({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 $x(t){return typeof t.schema!="boolean"}function s1(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&kx(t),c1(t),u1(t);let s=n.const("_errs",V.default.errors);xx(t,s),n.var(e,(0,O._)`${s} === ${V.default.errors}`)}function Sx(t){(0,Fr.checkUnknownRules)(t),i1(t)}function xx(t,e){if(t.opts.jtd)return yx(t,[],!1,e);let r=(0,hx.getSchemaTypes)(t.schema),n=(0,hx.coerceAndCheckDataType)(t,r);yx(t,r,!n,e)}function i1(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Fr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function a1(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Fr.checkStrictMode)(t,"default is ignored in the schema root")}function c1(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,QM.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function u1(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function kx({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,O._)`${V.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._)`${V.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function l1(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,O._)`${V.default.errors} === 0`,()=>e.return(V.default.data),()=>e.throw((0,O._)`new ${o}(${V.default.vErrors})`)):(e.assign((0,O._)`${n}.errors`,V.default.vErrors),s.unevaluated&&d1(t),e.return((0,O._)`${V.default.errors} === 0`))}function d1({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 yx(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,Fr.schemaHasRulesButRef)(s,l))){o.block(()=>Ex(t,"$ref",l.all.$ref.definition));return}c.jtd||p1(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Xf.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Au.checkDataType)(p.type,i,c.strictNumbers)),vx(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Au.reportTypeError)(t)),o.endIf()):vx(t,p),a||o.if((0,O._)`${V.default.errors} === ${n||0}`))}}function vx(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,YM.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Xf.shouldUseRule)(n,s)&&Ex(t,s.keyword,s.definition,e.type)})}function p1(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(f1(t,e),t.opts.allowUnionTypes||m1(t,e),h1(t,t.dataTypes))}function f1(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Px(t.dataTypes,r)||em(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),y1(t,e)}}function m1(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&em(t,"use allowUnionTypes to allow union type keyword")}function h1(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Xf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>g1(e,i))&&em(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function g1(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Px(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function y1(t,e){let r=[];for(let n of t.dataTypes)Px(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function em(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Fr.checkStrictMode)(t,e,t.opts.strictTypes)}var Cu=class{constructor(e,r,n){if((0,ta.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,Fr.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",Tx(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ta.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",V.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?ea.reportExtraError:ea.reportError)(this,this.def.error,r)}$dataError(){(0,ea.reportError)(this,this.def.$dataError||ea.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ea.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,Au.checkDataTypes)(c,r,s.opts.strictNumbers,Au.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,Qf.getSubschema)(this.it,e);(0,Qf.extendSubschemaData)(n,this.it,e),(0,Qf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return o1(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Fr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Fr.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}};fn.KeywordCxt=Cu;function Ex(t,e,r,n){let o=new Cu(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ta.funcKeywordCode)(o,r):"macro"in r?(0,ta.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ta.funcKeywordCode)(o,r)}var v1=/^\/(?:[^~]|~0|~1)*$/,_1=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Tx(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return V.default.rootData;if(t[0]==="/"){if(!v1.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=V.default.rootData}else{let u=_1.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,Fr.unescapeJsonPointer)(u))}`,i=(0,O._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}fn.getData=Tx});var Du=$(rm=>{"use strict";Object.defineProperty(rm,"__esModule",{value:!0});var tm=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};rm.default=tm});var na=$(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});var nm=Xi(),om=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,nm.resolveUrl)(e,r,n),this.missingSchema=(0,nm.normalizeId)((0,nm.getFullPath)(e,this.missingRef))}};sm.default=om});var zu=$(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.resolveSchema=Vt.getCompilingSchema=Vt.resolveRef=Vt.compileSchema=Vt.SchemaEnv=void 0;var tr=te(),b1=Du(),so=qr(),rr=Xi(),Rx=le(),w1=ra(),ds=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,rr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Vt.SchemaEnv=ds;function am(t){let e=Ix.call(this,t);if(e)return e;let r=(0,rr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new tr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:b1.default,code:(0,tr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:so.default.data,parentData:so.default.parentData,parentDataProperty:so.default.parentDataProperty,dataNames:[so.default.data],dataPathArr:[tr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,tr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:tr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,tr._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,w1.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(so.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${so.default.self}`,`${so.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:h}=u;f.evaluated={props:m instanceof tr.Name?void 0:m,items:h instanceof tr.Name?void 0:h,dynamicProps:m instanceof tr.Name,dynamicItems:h instanceof tr.Name},f.source&&(f.source.evaluated=(0,tr.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)}}Vt.compileSchema=am;function $1(t,e,r){var n;r=(0,rr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=k1.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 ds({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=S1.call(this,s)}Vt.resolveRef=$1;function S1(t){return(0,rr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:am.call(this,t)}function Ix(t){for(let e of this._compilations)if(x1(e,t))return e}Vt.getCompilingSchema=Ix;function x1(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function k1(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ou.call(this,t,e)}function Ou(t,e){let r=this.opts.uriResolver.parse(e),n=(0,rr._getFullPath)(this.opts.uriResolver,r),o=(0,rr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return im.call(this,r,t);let s=(0,rr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ou.call(this,t,i);return typeof a?.schema!="object"?void 0:im.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||am.call(this,i),s===(0,rr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,rr.resolveUrl)(this.opts.uriResolver,o,u)),new ds({schema:a,schemaId:c,root:t,baseId:o})}return im.call(this,r,i)}}Vt.resolveSchema=Ou;var P1=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function im(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,Rx.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!P1.has(a)&&u&&(e=(0,rr.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Rx.schemaHasRulesButRef)(r,this.RULES)){let a=(0,rr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ou.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new ds({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Ax=$((EX,E1)=>{E1.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 um=$((TX,zx)=>{"use strict";var T1=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Dx=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 cm(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 R1=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Cx(t){return t.length=0,!0}function I1(t,e,r){if(t.length){let n=cm(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function A1(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=I1;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=Cx}else{o.push(u);continue}}return o.length&&(a===Cx?r.zone=o.join(""):i?n.push(o.join("")):n.push(cm(o))),r.address=n.join(""),r}function Ox(t){if(C1(t,":")<2)return{host:t,isIPV6:!1};let e=A1(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 C1(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function D1(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 O1(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 z1(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Dx(r)){let n=Ox(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}zx.exports={nonSimpleDomain:R1,recomposeAuthority:z1,normalizeComponentEncoding:O1,removeDotSegments:D1,isIPv4:Dx,isUUID:T1,normalizeIPv6:Ox,stringArrayToHexStripped:cm}});var qx=$((RX,Lx)=>{"use strict";var{isUUID:N1}=um(),j1=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,M1=["http","https","ws","wss","urn","urn:uuid"];function L1(t){return M1.indexOf(t)!==-1}function lm(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 Nx(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function jx(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 q1(t){return t.secure=lm(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function F1(t){if((t.port===(lm(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 U1(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(j1);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=dm(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Z1(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=dm(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 V1(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!N1(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function B1(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Mx={scheme:"http",domainHost:!0,parse:Nx,serialize:jx},W1={scheme:"https",domainHost:Mx.domainHost,parse:Nx,serialize:jx},Nu={scheme:"ws",domainHost:!0,parse:q1,serialize:F1},H1={scheme:"wss",domainHost:Nu.domainHost,parse:Nu.parse,serialize:Nu.serialize},K1={scheme:"urn",parse:U1,serialize:Z1,skipNormalize:!0},J1={scheme:"urn:uuid",parse:V1,serialize:B1,skipNormalize:!0},ju={http:Mx,https:W1,ws:Nu,wss:H1,urn:K1,"urn:uuid":J1};Object.setPrototypeOf(ju,null);function dm(t){return t&&(ju[t]||ju[t.toLowerCase()])||void 0}Lx.exports={wsIsSecure:lm,SCHEMES:ju,isValidSchemeName:L1,getSchemeHandler:dm}});var fm=$((IX,Lu)=>{"use strict";var{normalizeIPv6:G1,removeDotSegments:oa,recomposeAuthority:Y1,normalizeComponentEncoding:Mu,isIPv4:Q1,nonSimpleDomain:X1}=um(),{SCHEMES:eL,getSchemeHandler:Fx}=qx();function tL(t,e){return typeof t=="string"?t=br(Ur(t,e),e):typeof t=="object"&&(t=Ur(br(t,e),e)),t}function rL(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Ux(Ur(t,n),Ur(e,n),n,!0);return n.skipEscape=!0,br(o,n)}function Ux(t,e,r,n){let o={};return n||(t=Ur(br(t,r),r),e=Ur(br(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=oa(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=oa(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=oa(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=oa(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 nL(t,e,r){return typeof t=="string"?(t=unescape(t),t=br(Mu(Ur(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=br(Mu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=br(Mu(Ur(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=br(Mu(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function br(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=Fx(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=Y1(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=oa(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 oL=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Ur(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(oL);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(Q1(n.host)===!1){let c=G1(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=Fx(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&X1(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 pm={SCHEMES:eL,normalize:tL,resolve:rL,resolveComponent:Ux,equal:nL,serialize:br,parse:Ur};Lu.exports=pm;Lu.exports.default=pm;Lu.exports.fastUri=pm});var Vx=$(mm=>{"use strict";Object.defineProperty(mm,"__esModule",{value:!0});var Zx=fm();Zx.code='require("ajv/dist/runtime/uri").default';mm.default=Zx});var Qx=$(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.CodeGen=Ye.Name=Ye.nil=Ye.stringify=Ye.str=Ye._=Ye.KeywordCxt=void 0;var sL=ra();Object.defineProperty(Ye,"KeywordCxt",{enumerable:!0,get:function(){return sL.KeywordCxt}});var ps=te();Object.defineProperty(Ye,"_",{enumerable:!0,get:function(){return ps._}});Object.defineProperty(Ye,"str",{enumerable:!0,get:function(){return ps.str}});Object.defineProperty(Ye,"stringify",{enumerable:!0,get:function(){return ps.stringify}});Object.defineProperty(Ye,"nil",{enumerable:!0,get:function(){return ps.nil}});Object.defineProperty(Ye,"Name",{enumerable:!0,get:function(){return ps.Name}});Object.defineProperty(Ye,"CodeGen",{enumerable:!0,get:function(){return ps.CodeGen}});var iL=Du(),Jx=na(),aL=Zf(),sa=zu(),cL=te(),ia=Xi(),qu=Yi(),gm=le(),Bx=Ax(),uL=Vx(),Gx=(t,e)=>new RegExp(t,e);Gx.code="new RegExp";var lL=["removeAdditional","useDefaults","coerceTypes"],dL=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),pL={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."},fL={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Wx=200;function mL(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,h,y,v,b,_,k,x,L,P,M,q;let j=t.strict,De=(e=t.code)===null||e===void 0?void 0:e.optimize,Le=De===!0||De===void 0?1:De||0,It=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Gx,Kr=(o=t.uriResolver)!==null&&o!==void 0?o:uL.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:j)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:j)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:j)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:j)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:j)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Le,regExp:It}:{optimize:Le,regExp:It},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Wx,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Wx,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(x=t.addUsedSchema)!==null&&x!==void 0?x:!0,validateSchema:(L=t.validateSchema)!==null&&L!==void 0?L:!0,validateFormats:(P=t.validateFormats)!==null&&P!==void 0?P:!0,unicodeRegExp:(M=t.unicodeRegExp)!==null&&M!==void 0?M:!0,int32range:(q=t.int32range)!==null&&q!==void 0?q:!0,uriResolver:Kr}}var aa=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...mL(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new cL.ValueScope({scope:{},prefixes:dL,es5:r,lines:n}),this.logger=bL(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,aL.getRules)(),Hx.call(this,pL,e,"NOT SUPPORTED"),Hx.call(this,fL,e,"DEPRECATED","warn"),this._metaOpts=vL.call(this),e.formats&&gL.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&yL.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),hL.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Bx;n==="id"&&(o={...Bx},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 Jx.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,ia.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=Kx.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new sa.SchemaEnv({schema:{},schemaId:n});if(r=sa.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=Kx.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,ia.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($L.call(this,n,r),!r)return(0,gm.eachItem)(n,s=>hm.call(this,s)),this;xL.call(this,r);let o={...r,type:(0,qu.getJSONTypes)(r.type),schemaType:(0,qu.getJSONTypes)(r.schemaType)};return(0,gm.eachItem)(n,o.type.length===0?s=>hm.call(this,s,o):s=>o.type.forEach(i=>hm.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]=Yx(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,ia.normalizeId)(i||n);let u=ia.getSchemaRefs.call(this,e,n);return c=new sa.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):sa.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{sa.compileSchema.call(this,e)}finally{this.opts=r}}};aa.ValidationError=iL.default;aa.MissingRefError=Jx.default;Ye.default=aa;function Hx(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 Kx(t){return t=(0,ia.normalizeId)(t),this.schemas[t]||this.refs[t]}function hL(){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 gL(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function yL(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 vL(){let t={...this.opts};for(let e of lL)delete t[e];return t}var _L={log(){},warn(){},error(){}};function bL(t){if(t===!1)return _L;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 wL=/^[a-z_$][a-z0-9_$:-]*$/i;function $L(t,e){let{RULES:r}=this;if((0,gm.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!wL.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 hm(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,qu.getJSONTypes)(e.type),schemaType:(0,qu.getJSONTypes)(e.schemaType)}};e.before?SL.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 SL(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 xL(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Yx(e)),t.validateSchema=this.compile(e,!0))}var kL={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Yx(t){return{anyOf:[t,kL]}}});var Xx=$(ym=>{"use strict";Object.defineProperty(ym,"__esModule",{value:!0});var PL={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ym.default=PL});var n0=$(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.callRef=io.getValidate=void 0;var EL=na(),e0=Zt(),kt=te(),fs=qr(),t0=zu(),Fu=le(),TL={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=t0.resolveRef.call(c,u,o,r);if(l===void 0)throw new EL.default(n.opts.uriResolver,o,r);if(l instanceof t0.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Uu(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Uu(t,(0,kt._)`${m}.validate`,u,u.$async)}function p(m){let h=r0(t,m);Uu(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,kt.stringify)(m)}:{ref:m}),y=e.name("valid"),v=t.subschema({schema:m,dataTypes:[],schemaPath:kt.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(v),t.ok(y)}}};function r0(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,kt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}io.getValidate=r0;function Uu(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?fs.default.this:kt.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,kt._)`await ${(0,e0.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},h=>{o.if((0,kt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),p(h),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,e0.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,kt._)`${m}.errors`;o.assign(fs.default.vErrors,(0,kt._)`${fs.default.vErrors} === null ? ${h} : ${fs.default.vErrors}.concat(${h})`),o.assign(fs.default.errors,(0,kt._)`${fs.default.vErrors}.length`)}function f(m){var h;if(!s.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Fu.mergeEvaluated.props(o,y.props,s.props));else{let v=o.var("props",(0,kt._)`${m}.evaluated.props`);s.props=Fu.mergeEvaluated.props(o,v,s.props,kt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Fu.mergeEvaluated.items(o,y.items,s.items));else{let v=o.var("items",(0,kt._)`${m}.evaluated.items`);s.items=Fu.mergeEvaluated.items(o,v,s.items,kt.Name)}}}io.callRef=Uu;io.default=TL});var o0=$(vm=>{"use strict";Object.defineProperty(vm,"__esModule",{value:!0});var RL=Xx(),IL=n0(),AL=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",RL.default,IL.default];vm.default=AL});var s0=$(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});var Zu=te(),mn=Zu.operators,Vu={maximum:{okStr:"<=",ok:mn.LTE,fail:mn.GT},minimum:{okStr:">=",ok:mn.GTE,fail:mn.LT},exclusiveMaximum:{okStr:"<",ok:mn.LT,fail:mn.GTE},exclusiveMinimum:{okStr:">",ok:mn.GT,fail:mn.LTE}},CL={message:({keyword:t,schemaCode:e})=>(0,Zu.str)`must be ${Vu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Zu._)`{comparison: ${Vu[t].okStr}, limit: ${e}}`},DL={keyword:Object.keys(Vu),type:"number",schemaType:"number",$data:!0,error:CL,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Zu._)`${r} ${Vu[e].fail} ${n} || isNaN(${r})`)}};_m.default=DL});var i0=$(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0});var ca=te(),OL={message:({schemaCode:t})=>(0,ca.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ca._)`{multipleOf: ${t}}`},zL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:OL,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ca._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ca._)`${i} !== parseInt(${i})`;t.fail$data((0,ca._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};bm.default=zL});var c0=$(wm=>{"use strict";Object.defineProperty(wm,"__esModule",{value:!0});function a0(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}wm.default=a0;a0.code='require("ajv/dist/runtime/ucs2length").default'});var u0=$($m=>{"use strict";Object.defineProperty($m,"__esModule",{value:!0});var ao=te(),NL=le(),jL=c0(),ML={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,ao.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,ao._)`{limit: ${t}}`},LL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ML,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?ao.operators.GT:ao.operators.LT,i=o.opts.unicode===!1?(0,ao._)`${r}.length`:(0,ao._)`${(0,NL.useFunc)(t.gen,jL.default)}(${r})`;t.fail$data((0,ao._)`${i} ${s} ${n}`)}};$m.default=LL});var l0=$(Sm=>{"use strict";Object.defineProperty(Sm,"__esModule",{value:!0});var qL=Zt(),FL=le(),ms=te(),UL={message:({schemaCode:t})=>(0,ms.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ms._)`{pattern: ${t}}`},ZL={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:UL,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,ms._)`new RegExp`:(0,FL.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,ms._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,ms._)`!${l}`)}else{let c=(0,qL.usePattern)(t,o);t.fail$data((0,ms._)`!${c}.test(${r})`)}}};Sm.default=ZL});var d0=$(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});var ua=te(),VL={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ua.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ua._)`{limit: ${t}}`},BL={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:VL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ua.operators.GT:ua.operators.LT;t.fail$data((0,ua._)`Object.keys(${r}).length ${o} ${n}`)}};xm.default=BL});var p0=$(km=>{"use strict";Object.defineProperty(km,"__esModule",{value:!0});var la=Zt(),da=te(),WL=le(),HL={message:({params:{missingProperty:t}})=>(0,da.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,da._)`{missingProperty: ${t}}`},KL={keyword:"required",type:"object",schemaType:"array",$data:!0,error:HL,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 h of r)if(f?.[h]===void 0&&!m.has(h)){let y=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,WL.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(da.nil,d);else for(let f of r)(0,la.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,la.checkMissingProp)(t,r,f)),(0,la.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,la.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,la.propertyInData)(e,o,f,a.ownProperties)),e.if((0,da.not)(m),()=>{t.error(),e.break()})},da.nil)}}};km.default=KL});var f0=$(Pm=>{"use strict";Object.defineProperty(Pm,"__esModule",{value:!0});var pa=te(),JL={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,pa.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,pa._)`{limit: ${t}}`},GL={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:JL,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?pa.operators.GT:pa.operators.LT;t.fail$data((0,pa._)`${r}.length ${o} ${n}`)}};Pm.default=GL});var Bu=$(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});var m0=Qi();m0.code='require("ajv/dist/runtime/equal").default';Em.default=m0});var h0=$(Rm=>{"use strict";Object.defineProperty(Rm,"__esModule",{value:!0});var Tm=Yi(),Qe=te(),YL=le(),QL=Bu(),XL={message:({params:{i:t,j:e}})=>(0,Qe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Qe._)`{i: ${t}, j: ${e}}`},eq={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:XL,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,Tm.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Qe._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,Qe._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,Qe._)`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,h){let y=e.name("item"),v=(0,Tm.checkDataTypes)(u,y,a.opts.strictNumbers,Tm.DataType.Wrong),b=e.const("indices",(0,Qe._)`{}`);e.for((0,Qe._)`;${m}--;`,()=>{e.let(y,(0,Qe._)`${r}[${m}]`),e.if(v,(0,Qe._)`continue`),u.length>1&&e.if((0,Qe._)`typeof ${y} == "string"`,(0,Qe._)`${y} += "_"`),e.if((0,Qe._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(h,(0,Qe._)`${b}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Qe._)`${b}[${y}] = ${m}`)})}function f(m,h){let y=(0,YL.useFunc)(e,QL.default),v=e.name("outer");e.label(v).for((0,Qe._)`;${m}--;`,()=>e.for((0,Qe._)`${h} = ${m}; ${h}--;`,()=>e.if((0,Qe._)`${y}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};Rm.default=eq});var g0=$(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});var Im=te(),tq=le(),rq=Bu(),nq={message:"must be equal to constant",params:({schemaCode:t})=>(0,Im._)`{allowedValue: ${t}}`},oq={keyword:"const",$data:!0,error:nq,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Im._)`!${(0,tq.useFunc)(e,rq.default)}(${r}, ${o})`):t.fail((0,Im._)`${s} !== ${r}`)}};Am.default=oq});var y0=$(Cm=>{"use strict";Object.defineProperty(Cm,"__esModule",{value:!0});var fa=te(),sq=le(),iq=Bu(),aq={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,fa._)`{allowedValues: ${t}}`},cq={keyword:"enum",schemaType:"array",$data:!0,error:aq,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,sq.useFunc)(e,iq.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,fa.or)(...o.map((m,h)=>p(f,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,fa._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let h=o[m];return typeof h=="object"&&h!==null?(0,fa._)`${u()}(${r}, ${f}[${m}])`:(0,fa._)`${r} === ${h}`}}};Cm.default=cq});var v0=$(Dm=>{"use strict";Object.defineProperty(Dm,"__esModule",{value:!0});var uq=s0(),lq=i0(),dq=u0(),pq=l0(),fq=d0(),mq=p0(),hq=f0(),gq=h0(),yq=g0(),vq=y0(),_q=[uq.default,lq.default,dq.default,pq.default,fq.default,mq.default,hq.default,gq.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},yq.default,vq.default];Dm.default=_q});var zm=$(ma=>{"use strict";Object.defineProperty(ma,"__esModule",{value:!0});ma.validateAdditionalItems=void 0;var co=te(),Om=le(),bq={message:({params:{len:t}})=>(0,co.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,co._)`{limit: ${t}}`},wq={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:bq,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Om.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}_0(t,n)}};function _0(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,co._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,co._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Om.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,co._)`${a} <= ${e.length}`);r.if((0,co.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Om.Type.Num},u),i.allErrors||r.if((0,co.not)(u),()=>r.break())})}}ma.validateAdditionalItems=_0;ma.default=wq});var Nm=$(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.validateTuple=void 0;var b0=te(),Wu=le(),$q=Zt(),Sq={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return w0(t,"additionalItems",e);r.items=!0,!(0,Wu.alwaysValidSchema)(r,e)&&t.ok((0,$q.validateArray)(t))}};function w0(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=Wu.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,b0._)`${s}.length`);r.forEach((d,p)=>{(0,Wu.alwaysValidSchema)(a,d)||(n.if((0,b0._)`${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,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let y=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Wu.checkStrictMode)(a,y,p.strictTuples)}}}ha.validateTuple=w0;ha.default=Sq});var $0=$(jm=>{"use strict";Object.defineProperty(jm,"__esModule",{value:!0});var xq=Nm(),kq={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,xq.validateTuple)(t,"items")};jm.default=kq});var x0=$(Mm=>{"use strict";Object.defineProperty(Mm,"__esModule",{value:!0});var S0=te(),Pq=le(),Eq=Zt(),Tq=zm(),Rq={message:({params:{len:t}})=>(0,S0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,S0._)`{limit: ${t}}`},Iq={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Rq,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,Pq.alwaysValidSchema)(n,e)&&(o?(0,Tq.validateAdditionalItems)(t,o):t.ok((0,Eq.validateArray)(t)))}};Mm.default=Iq});var k0=$(Lm=>{"use strict";Object.defineProperty(Lm,"__esModule",{value:!0});var Bt=te(),Hu=le(),Aq={message:({params:{min:t,max:e}})=>e===void 0?(0,Bt.str)`must contain at least ${t} valid item(s)`:(0,Bt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Bt._)`{minContains: ${t}}`:(0,Bt._)`{minContains: ${t}, maxContains: ${e}}`},Cq={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Aq,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,Bt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Hu.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Hu.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Hu.alwaysValidSchema)(s,r)){let h=(0,Bt._)`${l} >= ${i}`;a!==void 0&&(h=(0,Bt._)`${h} && ${l} <= ${a}`),t.pass(h);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,Bt._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),y=e.let("count",0);f(h,()=>e.if(h,()=>m(y)))}function f(h,y){e.forRange("i",0,l,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:Hu.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,Bt._)`${h}++`),a===void 0?e.if((0,Bt._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Bt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Bt._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};Lm.default=Cq});var T0=$(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.validateSchemaDeps=wr.validatePropertyDeps=wr.error=void 0;var qm=te(),Dq=le(),ga=Zt();wr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,qm.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,qm._)`{property: ${t},
|
|
3
|
+
var cR=Object.create;var kd=Object.defineProperty;var uR=Object.getOwnPropertyDescriptor;var lR=Object.getOwnPropertyNames;var dR=Object.getPrototypeOf,pR=Object.prototype.hasOwnProperty;var Rr=(t,e)=>()=>(t&&(e=t(t=0)),e);var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),lt=(t,e)=>{for(var r in e)kd(t,r,{get:e[r],enumerable:!0})},fR=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of lR(e))!pR.call(t,s)&&s!==r&&kd(t,s,{get:()=>e[s],enumerable:!(n=uR(e,s))||n.enumerable});return t};var jy=(t,e,r)=>(r=t!=null?cR(dR(t)):{},fR(e||!t||!t.__esModule?kd(r,"default",{value:t,enumerable:!0}):r,t));var Ly,ri,qy,Fy,Uy,Zy,Vy,ni,By,Is,Wy,Hy,Ky,Jy,Gy,Yy,En,Ed,Td,FH,UH,Id,Xy,Qy,sc,Tn,Rd,ev,tv,Rs,Ar=Rr(()=>{"use strict";Ly="4.12.4",ri="http://localhost:11434",qy="llama3",Fy=".agestra/.jobs",Uy=".agestra/traces",Zy=".agestra/worktrees",Vy=".agestra/sessions",ni=".agestra/workspace",By="individual",Is="debates",Wy="synthesis",Hy="issue",Ky=".agestra/workers",Jy=Object.freeze(["PATH","HOME","USER","USERPROFILE","APPDATA","LOCALAPPDATA","TEMP","TMP","TMPDIR","SHELL","LANG","LC_ALL","NODE_PATH","SystemRoot","SystemDrive","COMSPEC","ComSpec","windir"]),Gy=2,Yy=6e4,En=20,Ed=5e4,Td=10,FH=Object.freeze([3,5,10]),UH=Object.freeze(["agree","disagree","abstain","revise"]),Id=2,Xy=1440*60*1e3,Qy=3600*1e3,sc=Object.freeze(["ko","zh","ja","en"]),Tn="ko",Rd="en",ev="[REDACTED]",tv=["","--- 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
|
+
`),Rs=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 mR}from"child_process";function As(t){if(!Number.isFinite(t)||t<=0)return{delivered:!1};if(process.platform==="win32")try{return mR("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 Qt(t,e=3e3){let r=t.pid;if(r)As(r);else try{t.kill("SIGTERM")}catch{}setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},e).unref?.()}var Cs=Rr(()=>{"use strict"});import{execFileSync as hR,spawn as gR}from"child_process";import{existsSync as yR}from"fs";function rv(t){let e=t.replace(/\s+/g," ").trim();return e.length>200?`${e.slice(0,200)}...`:e}function Gr(t,e){if(t)try{t({...e,at:new Date().toISOString()})}catch{}}function _R(t){return process.platform!=="win32"||t.includes("/")||t.includes("\\")?!1:vR.has(t.toLowerCase())}function bR(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 wR(t){let e=t.toLowerCase();if(Ds.has(e))return Ds.get(e)??null;try{let n=hR("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 Ds.set(e,null),null;let s=n.find(a=>/\.(cmd|bat)$/i.test(a));if(s){let a={type:"cmd",path:s};return Ds.set(e,a),a}let i=`${n[0]}.ps1`;if(yR(i)){let a={type:"powershell",path:i};return Ds.set(e,a),a}}catch{}return Ds.set(e,null),null}function In(t,e){if(!_R(t))return{command:t,args:e};let r=wR(t);return r?r.type==="cmd"?{command:"cmd.exe",args:["/d","/s","/c",r.path,...e.map(n=>bR(n))]}:{command:"powershell.exe",args:["-NoProfile","-ExecutionPolicy","RemoteSigned","-File",r.path,...e]}:{command:t,args:e}}function vt(t){let{command:e,args:r,timeout:n=12e4,overallTimeoutMs:s,cwd:o,env:i,stdin:a,maxBuffer:c=10485760,onStderrChunk:u,onActivity:l,signal:d}=t;return new Promise((p,f)=>{if(d?.aborted){Gr(l,{type:"abort",command:e,args:r,reason:String(d.reason??"aborted before spawn")}),f(new Nt(d.reason));return}let m=In(e,r);Gr(l,{type:"start",command:m.command,args:m.args,timeoutMs:n});let h=gR(m.command,m.args,{cwd:o,env:i?{...process.env,...i}:void 0,stdio:[a?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),v="",g="",b=0,_=0,P=!1,x=null,j=!1,k=null,O=()=>{k&&d&&d.removeEventListener("abort",k)},L=!1,q=()=>{!L&&b+_>c&&(P=!0,L=!0,Qt(h))},$e=null,He=()=>{$e&&(clearTimeout($e),$e=null)},Rt=()=>{j||(Qt(h),j=!0,He(),O(),Gr(l,{type:"timeout",command:e,args:r,timeoutMs:n}),f(new Error(`CLI timeout after ${n}ms of inactivity: ${e} ${r.join(" ")}`)))},Mt=setTimeout(Rt,n);$e=s!==void 0?setTimeout(()=>{j||(Qt(h),j=!0,clearTimeout(Mt),He(),O(),Gr(l,{type:"timeout",command:e,args:r,timeoutMs:s}),f(new Error(`CLI overall timeout after ${s}ms: ${e} ${r.join(" ")}`)))},s):null,d&&(k=()=>{j||(j=!0,clearTimeout(Mt),He(),Qt(h),O(),Gr(l,{type:"abort",command:e,args:r,reason:String(d.reason??"aborted")}),f(new Nt(d.reason)))},d.addEventListener("abort",k));let ks=()=>{L||(clearTimeout(Mt),Mt=setTimeout(Rt,n))};if(h.stdout.on("data",At=>{b+=At.length,Gr(l,{type:"stdout",command:e,args:r,preview:rv(At.toString())}),b<=c&&(v+=At.toString()),q(),ks()}),h.stderr.on("data",At=>{_+=At.length;let kn=At.toString();if(Gr(l,{type:"stderr",command:e,args:r,preview:rv(kn)}),_<=c&&(g+=kn),q(),!L&&u){let ti=u(kn);ti&&(x=ti,L=!0,Qt(h))}ks()}),a&&h.stdin){h.stdin.on("error",()=>{});try{h.stdin.write(a),h.stdin.end()}catch{}}h.on("close",(At,kn)=>{if(clearTimeout(Mt),He(),!j){if(Gr(l,{type:"close",command:e,args:r,exitCode:At,signalCode:kn}),x){j=!0,O(),f(x);return}j=!0,O(),p({stdout:v,stderr:g,exitCode:At??1,truncated:P})}}),h.on("error",At=>{clearTimeout(Mt),He(),!j&&(j=!0,O(),f(new Error(`CLI spawn error: ${At.message}`)))})})}var Nt,vR,Ds,si=Rr(()=>{"use strict";Cs();Nt=class extends Error{constructor(e){let r=e instanceof Error?`: ${e.message}`:typeof e=="string"&&e?`: ${e}`:"";super(`CLI aborted${r}`),this.name="CliAbortedError"}};vR=new Set(["codex","gemini","npm","npx"]),Ds=new Map});import{writeFileSync as VA,mkdirSync as ui,openSync as zd,writeSync as Md,fsyncSync as Sv,closeSync as Nd,renameSync as BA,unlinkSync as wv,appendFileSync as WA,copyFileSync as HA}from"fs";import{dirname as li,join as KA}from"path";import{randomUUID as JA}from"crypto";function ge(t,e){let r=li(t);ui(r,{recursive:!0});let n=KA(r,`.tmp-${JA().slice(0,8)}`);try{VA(n,e,"utf-8");try{BA(n,t)}catch(s){if(s.code!=="EXDEV")throw s;HA(n,t),wv(n)}}catch(s){try{wv(n)}catch{}throw s}}function Ze(t,e){ge(t,JSON.stringify(e,null,2))}function yc(t,e){let r=li(t);ui(r,{recursive:!0});let n=zd(t,"a");try{Md(n,e),Sv(n)}finally{Nd(n)}}var gc,rn=Rr(()=>{"use strict";gc=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)yc(e,r);else{let o=li(e);ui(o,{recursive:!0}),WA(e,r)}return}let s=this.buffer.get(e);s||(s=[],this.buffer.set(e,s)),s.push(r),s.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=li(e);ui(n,{recursive:!0});let s=zd(e,"a");try{Md(s,r.join("")),Sv(s)}finally{Nd(s)}}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=li(e);ui(n,{recursive:!0});let s=zd(e,"a");try{Md(s,r.join(""))}finally{Nd(s)}this.buffer.delete(e)}}});import{openSync as GA,writeSync as YA,closeSync as XA,unlinkSync as $v,statSync as QA,mkdirSync as eC,existsSync as tC}from"fs";import{dirname as rC}from"path";function iC(t){if(t<=0)return;let e=new SharedArrayBuffer(4),r=new Int32Array(e);Atomics.wait(r,0,0,t)}function Wn(t,e,r={}){let n=r.staleMs??nC,s=r.acquireTimeoutMs??sC,o=r.pollMs??oC;eC(rC(t),{recursive:!0});let i=Date.now(),a=null;for(;a===null;)try{a=GA(t,"wx")}catch(c){let u=c.code;if(!(u==="EEXIST"||process.platform==="win32"&&u==="EPERM"&&tC(t)))throw c;let d=!1;try{let f=QA(t);d=Date.now()-f.mtimeMs>n}catch{continue}if(d){try{$v(t)}catch{}continue}let p=Date.now()-i;if(p>=s)throw new jd(t,p);iC(o)}try{try{YA(a,`${process.pid}@${Date.now()}
|
|
5
|
+
`)}catch{}return e()}finally{try{XA(a)}catch{}try{$v(t)}catch{}}}var nC,sC,oC,jd,vc=Rr(()=>{"use strict";nC=3e4,sC=5e3,oC=10,jd=class extends Error{constructor(e,r){super(`withFileLock: timed out after ${r}ms waiting for ${e}`),this.name="FileLockTimeoutError"}}});import{existsSync as xv,realpathSync as aC}from"fs";import{basename as cC,dirname as uC,isAbsolute as qd,join as lC,normalize as kv,resolve as Fd,relative as dC}from"path";function pC(t){return t===""||!t.startsWith("..")&&!qd(t)}function Ld(t){let e=[],r=Fd(t);for(;!xv(r);){let s=uC(r);if(s===r)break;e.unshift(cC(r)),r=s}let n=xv(r)?aC(r):r;return e.reduce((s,o)=>lC(s,o),n)}function Ev(t,e){let r=Ld(e),n=Ld(t),s=dC(r,n);return pC(s)}function Ud(t,e){let r=Fd(e,t);return Ev(r,e)}function Ft(t,e){let r=Fd(e,t);if(!Ev(r,e))throw new Error(`Path traversal blocked: ${t} escapes ${e}`);return r}function Je(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 Ft(t,e)}function nn(t,e){if(qd(t)){let r=kv(t);if(!Ud(r,e))throw new Error(`Read path outside base directory: ${t} is not within ${e}`);return r}return Ft(t,e)}function Tv(t,e){return qd(t)?Ld(kv(t)):Ft(t,e)}function Nr(t){return fC.test(t)}function _c(t,e){if(!t||typeof t!="string")throw new Ct(String(t),"command must be a non-empty string");if(t.includes("\0"))throw new Ct(t,"command contains null byte");if(t.includes("/")||t.includes("\\"))throw new Ct(t,"command must not contain path separators");if(!Pv.has(t))throw new Ct(t,`command is not in the allowlist (${[...Pv].join(", ")})`);for(let r of e){if(typeof r!="string")throw new Ct(t,`args contain a non-string entry: ${JSON.stringify(r)}`);if(r.includes("\0"))throw new Ct(t,`arg contains null byte: ${JSON.stringify(r)}`);if(mC.has(r))throw new Ct(t,`arg ${JSON.stringify(r)} is a code-execution flag and is not permitted`)}}var fC,Pv,mC,Ct,Us=Rr(()=>{"use strict";fC=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;Pv=new Set(["gemini","codex","claude","npx","node","npm","tsc"]),mC=new Set(["-e","--eval","-c","--command","-E","--execute","--exec"]),Ct=class extends Error{command;reason;constructor(e,r){super(`CLI command rejected: ${e} \u2014 ${r}`),this.command=e,this.reason=r,this.name="CliCommandRejectedError"}}});import{readFileSync as hC}from"fs";import{join as gC}from"path";function Be(t,e){let r=gC(t,"status.json"),n=`${r}.lock`;Wn(n,()=>{let s=JSON.parse(hC(r,"utf-8"));Ze(r,{...s,...e})})}var di=Rr(()=>{"use strict";rn();vc()});import{spawn as yC}from"child_process";import{join as Zd}from"path";function bc(t){return new Promise(e=>{let r=In(t.command,t.args),n=yC(r.command,r.args,{cwd:t.cwd,stdio:["ignore","pipe","pipe"],windowsHide:!0});if(t.recordPid&&typeof n.pid=="number"&&n.pid>0)try{Be(t.jobDir,{pid:n.pid})}catch{}if(!n.stdout||!n.stderr){try{n.kill()}catch{}try{ge(Zd(t.jobDir,"error.txt"),"Worker stdout/stderr streams unavailable (pipe allocation failed)"),Be(t.jobDir,{state:"error",completedAt:new Date().toISOString()})}catch{}e();return}let s="",o="",i=0,a=0,c=!1,u=!1;n.stdout.on("data",p=>{i+=p.length,i<=10485760?s+=p.toString():c||(c=!0,Qt(n))}),n.stderr.on("data",p=>{a+=p.length,a<=10485760&&(o+=p.toString())});let l=(p,f)=>{if(!u){u=!0,clearTimeout(d);try{ge(Zd(t.jobDir,"output.txt"),s),ge(Zd(t.jobDir,"error.txt"),f!==void 0?f:o),Be(t.jobDir,p)}catch{}e()}},d=setTimeout(()=>{Qt(n),l({state:"timed_out",completedAt:new Date().toISOString()})},t.timeoutMs);n.on("close",p=>{let f=s.trim().length>0;l({state:p===0||f?"completed":"error",exitCode:p??1,completedAt:new Date().toISOString()})}),n.on("error",p=>{let f=p.code==="ENOENT"?"missing_cli":"error";l({state:f,completedAt:new Date().toISOString()},p.message)})})}var Vd=Rr(()=>{"use strict";rn();si();Cs();di()});var Cv={};lt(Cv,{CLI_PROVIDERS:()=>Rv,resolveCliConfig:()=>Av});import{readFileSync as Iv}from"fs";import{join as Hn}from"path";function Av(t){let e=vC[t.provider]??t.provider;return Rv[e]??null}async function _C(){let t=process.argv[2];t||process.exit(1);let e;try{e=JSON.parse(Iv(Hn(t,"job.json"),"utf-8"))}catch{try{Ze(Hn(t,"status.json"),{id:"unknown",state:"error",provider:"unknown",completedAt:new Date().toISOString()}),ge(Hn(t,"error.txt"),"Failed to read job.json")}catch{}process.exit(1)}let r=Av(e);r||(Be(t,{state:"missing_cli",completedAt:new Date().toISOString()}),ge(Hn(t,"error.txt"),`No CLI mapping for provider: ${e.provider}`),process.exit(1));let{command:n,buildArgs:s}=r;Be(t,{state:"running",startedAt:new Date().toISOString()});let o=Iv(Hn(t,"prompt.txt"),"utf-8"),i=s(o);try{_c(n,i)}catch(c){let u=c instanceof Ct?c.message:`Argv rejected: ${c.message}`;Be(t,{state:"error",completedAt:new Date().toISOString()}),ge(Hn(t,"error.txt"),u);return}let a;if(e.cwd)try{a=Ft(e.cwd,process.cwd())}catch(c){Be(t,{state:"error",completedAt:new Date().toISOString()}),ge(Hn(t,"error.txt"),`Rejected descriptor.cwd: ${c.message}`);return}await bc({jobDir:t,command:n,args:i,cwd:a,timeoutMs:e.timeout,recordPid:!1})}var vC,Rv,bC,Dv=Rr(()=>{"use strict";rn();Us();Vd();di();vC={"gemini-cli":"gemini","codex-cli":"codex","claude-cli":"claude"},Rv={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]}};bC=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");bC&&_C().catch(()=>process.exit(1))});var Yi=S(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.regexpCode=me.getEsmExportName=me.getProperty=me.safeStringify=me.stringify=me.strConcat=me.addCodeArg=me.str=me._=me.nil=me._Code=me.Name=me.IDENTIFIER=me._CodeOrName=void 0;var Ji=class{};me._CodeOrName=Ji;me.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var rs=class extends Ji{constructor(e){if(super(),!me.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}}};me.Name=rs;var Bt=class extends Ji{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 rs&&(r[n.str]=(r[n.str]||0)+1),r),{})}};me._Code=Bt;me.nil=new Bt("");function q$(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Ef(r,e[n]),r.push(t[++n]);return new Bt(r)}me._=q$;var kf=new Bt("+");function F$(t,...e){let r=[Gi(t[0])],n=0;for(;n<e.length;)r.push(kf),Ef(r,e[n]),r.push(kf,Gi(t[++n]));return $N(r),new Bt(r)}me.str=F$;function Ef(t,e){e instanceof Bt?t.push(...e._items):e instanceof rs?t.push(e):t.push(kN(e))}me.addCodeArg=Ef;function $N(t){let e=1;for(;e<t.length-1;){if(t[e]===kf){let r=xN(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function xN(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof rs||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 rs))return`"${t}${e.slice(1)}`}function PN(t,e){return e.emptyStr()?t:t.emptyStr()?e:F$`${t}${e}`}me.strConcat=PN;function kN(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Gi(Array.isArray(t)?t.join(","):t)}function EN(t){return new Bt(Gi(t))}me.stringify=EN;function Gi(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}me.safeStringify=Gi;function TN(t){return typeof t=="string"&&me.IDENTIFIER.test(t)?new Bt(`.${t}`):q$`[${t}]`}me.getProperty=TN;function IN(t){if(typeof t=="string"&&me.IDENTIFIER.test(t))return new Bt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}me.getEsmExportName=IN;function RN(t){return new Bt(t.toString())}me.regexpCode=RN});var Rf=S($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.ValueScope=$t.ValueScopeName=$t.Scope=$t.varKinds=$t.UsedValueState=void 0;var St=Yi(),Tf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Eu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Eu||($t.UsedValueState=Eu={}));$t.varKinds={const:new St.Name("const"),let:new St.Name("let"),var:new St.Name("var")};var Tu=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof St.Name?e:this.name(e)}name(e){return new St.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}}};$t.Scope=Tu;var Iu=class extends St.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,St._)`.${new St.Name(r)}[${n}]`}};$t.ValueScopeName=Iu;var AN=(0,St._)`\n`,If=class extends Tu{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?AN:St.nil}}get(){return this._scope}name(e){return new Iu(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 s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let l=a.get(i);if(l)return l}else a=this._values[o]=new Map;a.set(i,s);let c=this._scope[o]||(this._scope[o]=[]),u=c.length;return c[u]=r.ref,s.setValue(r,{property:o,itemIndex:u}),s}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,St._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=St.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,Eu.Started);let l=r(u);if(l){let d=this.opts.es5?$t.varKinds.var:$t.varKinds.const;o=(0,St._)`${o}${d} ${u} = ${l};${this.opts._n}`}else if(l=s?.(u))o=(0,St._)`${o}${l}${this.opts._n}`;else throw new Tf(u);c.set(u,Eu.Completed)})}return o}};$t.ValueScope=If});var te=S(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.or=Q.and=Q.not=Q.CodeGen=Q.operators=Q.varKinds=Q.ValueScopeName=Q.ValueScope=Q.Scope=Q.Name=Q.regexpCode=Q.stringify=Q.getProperty=Q.nil=Q.strConcat=Q.str=Q._=void 0;var ce=Yi(),sr=Rf(),ln=Yi();Object.defineProperty(Q,"_",{enumerable:!0,get:function(){return ln._}});Object.defineProperty(Q,"str",{enumerable:!0,get:function(){return ln.str}});Object.defineProperty(Q,"strConcat",{enumerable:!0,get:function(){return ln.strConcat}});Object.defineProperty(Q,"nil",{enumerable:!0,get:function(){return ln.nil}});Object.defineProperty(Q,"getProperty",{enumerable:!0,get:function(){return ln.getProperty}});Object.defineProperty(Q,"stringify",{enumerable:!0,get:function(){return ln.stringify}});Object.defineProperty(Q,"regexpCode",{enumerable:!0,get:function(){return ln.regexpCode}});Object.defineProperty(Q,"Name",{enumerable:!0,get:function(){return ln.Name}});var Du=Rf();Object.defineProperty(Q,"Scope",{enumerable:!0,get:function(){return Du.Scope}});Object.defineProperty(Q,"ValueScope",{enumerable:!0,get:function(){return Du.ValueScope}});Object.defineProperty(Q,"ValueScopeName",{enumerable:!0,get:function(){return Du.ValueScopeName}});Object.defineProperty(Q,"varKinds",{enumerable:!0,get:function(){return Du.varKinds}});Q.operators={GT:new ce._Code(">"),GTE:new ce._Code(">="),LT:new ce._Code("<"),LTE:new ce._Code("<="),EQ:new ce._Code("==="),NEQ:new ce._Code("!=="),NOT:new ce._Code("!"),OR:new ce._Code("||"),AND:new ce._Code("&&"),ADD:new ce._Code("+")};var qr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Af=class extends qr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?sr.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=mo(this.rhs,e,r)),this}get names(){return this.rhs instanceof ce._CodeOrName?this.rhs.names:{}}},Ru=class extends qr{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 ce.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=mo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ce.Name?{}:{...this.lhs.names};return Cu(e,this.rhs)}},Cf=class extends Ru{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Df=class extends qr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Of=class extends qr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},zf=class extends qr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Mf=class extends qr{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=mo(this.code,e,r),this}get names(){return this.code instanceof ce._CodeOrName?this.code.names:{}}},Xi=class extends qr{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,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(CN(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>os(e,r.names),{})}},Fr=class extends Xi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Nf=class extends Xi{},fo=class extends Fr{};fo.kind="else";var ns=class t extends Fr{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 fo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(U$(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=mo(this.condition,e,r),this}get names(){let e=super.names;return Cu(e,this.condition),this.else&&os(e,this.else.names),e}};ns.kind="if";var ss=class extends Fr{};ss.kind="for";var jf=class extends ss{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=mo(this.iteration,e,r),this}get names(){return os(super.names,this.iteration.names)}},Lf=class extends ss{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?sr.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=Cu(super.names,this.from);return Cu(e,this.to)}},Au=class extends ss{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}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=mo(this.iterable,e,r),this}get names(){return os(super.names,this.iterable.names)}},Qi=class extends Fr{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)}};Qi.kind="func";var ea=class extends Xi{render(e){return"return "+super.render(e)}};ea.kind="return";var qf=class extends Fr{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,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&os(e,this.catch.names),this.finally&&os(e,this.finally.names),e}},ta=class extends Fr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ta.kind="catch";var ra=class extends Fr{render(e){return"finally"+super.render(e)}};ra.kind="finally";var Ff=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
6
|
+
`:""},this._extScope=e,this._scope=new sr.Scope({parent:e}),this._nodes=[new Nf]}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,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new Af(e,o,n)),o}const(e,r,n){return this._def(sr.varKinds.const,e,r,n)}let(e,r,n){return this._def(sr.varKinds.let,e,r,n)}var(e,r,n){return this._def(sr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Ru(e,r,n))}add(e,r){return this._leafNode(new Cf(e,Q.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ce.nil&&this._leafNode(new Mf(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,ce.addCodeArg)(r,s));return r.push("}"),new ce._Code(r)}if(e,r,n){if(this._blockNode(new ns(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 ns(e))}else(){return this._elseNode(new fo)}endIf(){return this._endBlockNode(ns,fo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new jf(e),r)}forRange(e,r,n,s,o=this.opts.es5?sr.varKinds.var:sr.varKinds.let){let i=this._scope.toName(e);return this._for(new Lf(o,i,r,n),()=>s(i))}forOf(e,r,n,s=sr.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ce.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ce._)`${i}.length`,a=>{this.var(o,(0,ce._)`${i}[${a}]`),n(o)})}return this._for(new Au("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?sr.varKinds.var:sr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ce._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new Au("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(ss)}label(e){return this._leafNode(new Df(e))}break(e){return this._leafNode(new Of(e))}return(e){let r=new ea;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ea)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new qf;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new ta(o),r(o)}return n&&(this._currNode=s.finally=new ra,this.code(n)),this._endBlockNode(ta,ra)}throw(e){return this._leafNode(new zf(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=ce.nil,n,s){return this._blockNode(new Qi(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Qi)}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 ns))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}};Q.CodeGen=Ff;function os(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Cu(t,e){return e instanceof ce._CodeOrName?os(t,e.names):t}function mo(t,e,r){if(t instanceof ce.Name)return n(t);if(!s(t))return t;return new ce._Code(t._items.reduce((o,i)=>(i instanceof ce.Name&&(i=n(i)),i instanceof ce._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof ce._Code&&o._items.some(i=>i instanceof ce.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function CN(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function U$(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ce._)`!${Uf(t)}`}Q.not=U$;var DN=Z$(Q.operators.AND);function ON(...t){return t.reduce(DN)}Q.and=ON;var zN=Z$(Q.operators.OR);function MN(...t){return t.reduce(zN)}Q.or=MN;function Z$(t){return(e,r)=>e===ce.nil?r:r===ce.nil?e:(0,ce._)`${Uf(e)} ${t} ${Uf(r)}`}function Uf(t){return t instanceof ce.Name?t:(0,ce._)`(${t})`}});var le=S(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.checkStrictMode=re.getErrorPath=re.Type=re.useFunc=re.setEvaluated=re.evaluatedPropsToName=re.mergeEvaluated=re.eachItem=re.unescapeJsonPointer=re.escapeJsonPointer=re.escapeFragment=re.unescapeFragment=re.schemaRefOrVal=re.schemaHasRulesButRef=re.schemaHasRules=re.checkUnknownRules=re.alwaysValidSchema=re.toHash=void 0;var we=te(),NN=Yi();function jN(t){let e={};for(let r of t)e[r]=!0;return e}re.toHash=jN;function LN(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(W$(t,e),!H$(e,t.self.RULES.all))}re.alwaysValidSchema=LN;function W$(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||G$(t,`unknown keyword: "${o}"`)}re.checkUnknownRules=W$;function H$(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}re.schemaHasRules=H$;function qN(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}re.schemaHasRulesButRef=qN;function FN({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,we._)`${r}`}return(0,we._)`${t}${e}${(0,we.getProperty)(n)}`}re.schemaRefOrVal=FN;function UN(t){return K$(decodeURIComponent(t))}re.unescapeFragment=UN;function ZN(t){return encodeURIComponent(Vf(t))}re.escapeFragment=ZN;function Vf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=Vf;function K$(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=K$;function VN(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}re.eachItem=VN;function V$({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof we.Name?(o instanceof we.Name?t(s,o,i):e(s,o,i),i):o instanceof we.Name?(e(s,i,o),o):r(o,i);return a===we.Name&&!(c instanceof we.Name)?n(s,c):c}}re.mergeEvaluated={props:V$({mergeNames:(t,e,r)=>t.if((0,we._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,we._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,we._)`${r} || {}`).code((0,we._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,we._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,we._)`${r} || {}`),Bf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:J$}),items:V$({mergeNames:(t,e,r)=>t.if((0,we._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,we._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,we._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,we._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function J$(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,we._)`{}`);return e!==void 0&&Bf(t,r,e),r}re.evaluatedPropsToName=J$;function Bf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,we._)`${e}${(0,we.getProperty)(n)}`,!0))}re.setEvaluated=Bf;var B$={};function BN(t,e){return t.scopeValue("func",{ref:e,code:B$[e.code]||(B$[e.code]=new NN._Code(e.code))})}re.useFunc=BN;var Zf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Zf||(re.Type=Zf={}));function WN(t,e,r){if(t instanceof we.Name){let n=e===Zf.Num;return r?n?(0,we._)`"[" + ${t} + "]"`:(0,we._)`"['" + ${t} + "']"`:n?(0,we._)`"/" + ${t}`:(0,we._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,we.getProperty)(t).toString():"/"+Vf(t)}re.getErrorPath=WN;function G$(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}re.checkStrictMode=G$});var Ur=S(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var st=te(),HN={data:new st.Name("data"),valCxt:new st.Name("valCxt"),instancePath:new st.Name("instancePath"),parentData:new st.Name("parentData"),parentDataProperty:new st.Name("parentDataProperty"),rootData:new st.Name("rootData"),dynamicAnchors:new st.Name("dynamicAnchors"),vErrors:new st.Name("vErrors"),errors:new st.Name("errors"),this:new st.Name("this"),self:new st.Name("self"),scope:new st.Name("scope"),json:new st.Name("json"),jsonPos:new st.Name("jsonPos"),jsonLen:new st.Name("jsonLen"),jsonPart:new st.Name("jsonPart")};Wf.default=HN});var na=S(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.extendErrors=ot.resetErrorsCount=ot.reportExtraError=ot.reportError=ot.keyword$DataError=ot.keywordError=void 0;var de=te(),Ou=le(),mt=Ur();ot.keywordError={message:({keyword:t})=>(0,de.str)`must pass "${t}" keyword validation`};ot.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,de.str)`"${t}" keyword must be ${e} ($data)`:(0,de.str)`"${t}" keyword is invalid ($data)`};function KN(t,e=ot.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=Q$(t,e,r);n??(i||a)?Y$(o,c):X$(s,(0,de._)`[${c}]`)}ot.reportError=KN;function JN(t,e=ot.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=Q$(t,e,r);Y$(s,a),o||i||X$(n,mt.default.vErrors)}ot.reportExtraError=JN;function GN(t,e){t.assign(mt.default.errors,e),t.if((0,de._)`${mt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,de._)`${mt.default.vErrors}.length`,e),()=>t.assign(mt.default.vErrors,null)))}ot.resetErrorsCount=GN;function YN({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,mt.default.errors,a=>{t.const(i,(0,de._)`${mt.default.vErrors}[${a}]`),t.if((0,de._)`${i}.instancePath === undefined`,()=>t.assign((0,de._)`${i}.instancePath`,(0,de.strConcat)(mt.default.instancePath,o.errorPath))),t.assign((0,de._)`${i}.schemaPath`,(0,de.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,de._)`${i}.schema`,r),t.assign((0,de._)`${i}.data`,n))})}ot.extendErrors=YN;function Y$(t,e){let r=t.const("err",e);t.if((0,de._)`${mt.default.vErrors} === null`,()=>t.assign(mt.default.vErrors,(0,de._)`[${r}]`),(0,de._)`${mt.default.vErrors}.push(${r})`),t.code((0,de._)`${mt.default.errors}++`)}function X$(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,de._)`new ${t.ValidationError}(${e})`):(r.assign((0,de._)`${n}.errors`,e),r.return(!1))}var is={keyword:new de.Name("keyword"),schemaPath:new de.Name("schemaPath"),params:new de.Name("params"),propertyName:new de.Name("propertyName"),message:new de.Name("message"),schema:new de.Name("schema"),parentSchema:new de.Name("parentSchema")};function Q$(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,de._)`{}`:XN(t,e,r)}function XN(t,e,r={}){let{gen:n,it:s}=t,o=[QN(s,r),ej(t,r)];return tj(t,e,o),n.object(...o)}function QN({errorPath:t},{instancePath:e}){let r=e?(0,de.str)`${t}${(0,Ou.getErrorPath)(e,Ou.Type.Str)}`:t;return[mt.default.instancePath,(0,de.strConcat)(mt.default.instancePath,r)]}function ej({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,de.str)`${e}/${t}`;return r&&(s=(0,de.str)`${s}${(0,Ou.getErrorPath)(r,Ou.Type.Str)}`),[is.schemaPath,s]}function tj(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([is.keyword,s],[is.params,typeof e=="function"?e(t):e||(0,de._)`{}`]),c.messages&&n.push([is.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([is.schema,i],[is.parentSchema,(0,de._)`${l}${d}`],[mt.default.data,o]),u&&n.push([is.propertyName,u])}});var tx=S(ho=>{"use strict";Object.defineProperty(ho,"__esModule",{value:!0});ho.boolOrEmptySchema=ho.topBoolOrEmptySchema=void 0;var rj=na(),nj=te(),sj=Ur(),oj={message:"boolean schema is false"};function ij(t){let{gen:e,schema:r,validateName:n}=t;r===!1?ex(t,!1):typeof r=="object"&&r.$async===!0?e.return(sj.default.data):(e.assign((0,nj._)`${n}.errors`,null),e.return(!0))}ho.topBoolOrEmptySchema=ij;function aj(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),ex(t)):r.var(e,!0)}ho.boolOrEmptySchema=aj;function ex(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,rj.reportError)(s,oj,void 0,e)}});var Hf=S(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.getRules=go.isJSONType=void 0;var cj=["string","number","integer","boolean","null","object","array"],uj=new Set(cj);function lj(t){return typeof t=="string"&&uj.has(t)}go.isJSONType=lj;function dj(){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:{}}}go.getRules=dj});var Kf=S(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.shouldUseRule=dn.shouldUseGroup=dn.schemaHasRulesForType=void 0;function pj({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&rx(t,n)}dn.schemaHasRulesForType=pj;function rx(t,e){return e.rules.some(r=>nx(t,r))}dn.shouldUseGroup=rx;function nx(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))}dn.shouldUseRule=nx});var sa=S(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.reportTypeError=it.checkDataTypes=it.checkDataType=it.coerceAndCheckDataType=it.getJSONTypes=it.getSchemaTypes=it.DataType=void 0;var fj=Hf(),mj=Kf(),hj=na(),K=te(),sx=le(),yo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(yo||(it.DataType=yo={}));function gj(t){let e=ox(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}it.getSchemaTypes=gj;function ox(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(fj.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}it.getJSONTypes=ox;function yj(t,e){let{gen:r,data:n,opts:s}=t,o=vj(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,mj.schemaHasRulesForType)(t,e[0]));if(i){let a=Gf(e,n,s.strictNumbers,yo.Wrong);r.if(a,()=>{o.length?_j(t,e,o):Yf(t)})}return i}it.coerceAndCheckDataType=yj;var ix=new Set(["string","number","integer","boolean","null"]);function vj(t,e){return e?t.filter(r=>ix.has(r)||e==="array"&&r==="array"):[]}function _j(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,K._)`typeof ${s}`),a=n.let("coerced",(0,K._)`undefined`);o.coerceTypes==="array"&&n.if((0,K._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,K._)`${s}[0]`).assign(i,(0,K._)`typeof ${s}`).if(Gf(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,K._)`${a} !== undefined`);for(let u of r)(ix.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),Yf(t),n.endIf(),n.if((0,K._)`${a} !== undefined`,()=>{n.assign(s,a),bj(t,a)});function c(u){switch(u){case"string":n.elseIf((0,K._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,K._)`"" + ${s}`).elseIf((0,K._)`${s} === null`).assign(a,(0,K._)`""`);return;case"number":n.elseIf((0,K._)`${i} == "boolean" || ${s} === null
|
|
7
|
+
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,K._)`+${s}`);return;case"integer":n.elseIf((0,K._)`${i} === "boolean" || ${s} === null
|
|
8
|
+
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,K._)`+${s}`);return;case"boolean":n.elseIf((0,K._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,K._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,K._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,K._)`${i} === "string" || ${i} === "number"
|
|
9
|
+
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,K._)`[${s}]`)}}}function bj({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,K._)`${e} !== undefined`,()=>t.assign((0,K._)`${e}[${r}]`,n))}function Jf(t,e,r,n=yo.Correct){let s=n===yo.Correct?K.operators.EQ:K.operators.NEQ,o;switch(t){case"null":return(0,K._)`${e} ${s} null`;case"array":o=(0,K._)`Array.isArray(${e})`;break;case"object":o=(0,K._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,K._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,K._)`typeof ${e} ${s} ${t}`}return n===yo.Correct?o:(0,K.not)(o);function i(a=K.nil){return(0,K.and)((0,K._)`typeof ${e} == "number"`,a,r?(0,K._)`isFinite(${e})`:K.nil)}}it.checkDataType=Jf;function Gf(t,e,r,n){if(t.length===1)return Jf(t[0],e,r,n);let s,o=(0,sx.toHash)(t);if(o.array&&o.object){let i=(0,K._)`typeof ${e} != "object"`;s=o.null?i:(0,K._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=K.nil;o.number&&delete o.integer;for(let i in o)s=(0,K.and)(s,Jf(i,e,r,n));return s}it.checkDataTypes=Gf;var wj={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,K._)`{type: ${t}}`:(0,K._)`{type: ${e}}`};function Yf(t){let e=Sj(t);(0,hj.reportError)(e,wj)}it.reportTypeError=Yf;function Sj(t){let{gen:e,data:r,schema:n}=t,s=(0,sx.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var cx=S(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});zu.assignDefaults=void 0;var vo=te(),$j=le();function xj(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)ax(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>ax(t,o,s.default))}zu.assignDefaults=xj;function ax(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,vo._)`${o}${(0,vo.getProperty)(e)}`;if(s){(0,$j.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,vo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,vo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,vo._)`${a} = ${(0,vo.stringify)(r)}`)}});var Wt=S(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.validateUnion=_e.validateArray=_e.usePattern=_e.callValidateCode=_e.schemaProperties=_e.allSchemaProperties=_e.noPropertyInData=_e.propertyInData=_e.isOwnProperty=_e.hasPropFunc=_e.reportMissingProp=_e.checkMissingProp=_e.checkReportMissingProp=void 0;var Re=te(),Xf=le(),pn=Ur(),Pj=le();function kj(t,e){let{gen:r,data:n,it:s}=t;r.if(em(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Re._)`${e}`},!0),t.error()})}_e.checkReportMissingProp=kj;function Ej({gen:t,data:e,it:{opts:r}},n,s){return(0,Re.or)(...n.map(o=>(0,Re.and)(em(t,e,o,r.ownProperties),(0,Re._)`${s} = ${o}`)))}_e.checkMissingProp=Ej;function Tj(t,e){t.setParams({missingProperty:e},!0),t.error()}_e.reportMissingProp=Tj;function ux(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Re._)`Object.prototype.hasOwnProperty`})}_e.hasPropFunc=ux;function Qf(t,e,r){return(0,Re._)`${ux(t)}.call(${e}, ${r})`}_e.isOwnProperty=Qf;function Ij(t,e,r,n){let s=(0,Re._)`${e}${(0,Re.getProperty)(r)} !== undefined`;return n?(0,Re._)`${s} && ${Qf(t,e,r)}`:s}_e.propertyInData=Ij;function em(t,e,r,n){let s=(0,Re._)`${e}${(0,Re.getProperty)(r)} === undefined`;return n?(0,Re.or)(s,(0,Re.not)(Qf(t,e,r))):s}_e.noPropertyInData=em;function lx(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}_e.allSchemaProperties=lx;function Rj(t,e){return lx(e).filter(r=>!(0,Xf.alwaysValidSchema)(t,e[r]))}_e.schemaProperties=Rj;function Aj({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,u){let l=u?(0,Re._)`${t}, ${e}, ${n}${s}`:e,d=[[pn.default.instancePath,(0,Re.strConcat)(pn.default.instancePath,o)],[pn.default.parentData,i.parentData],[pn.default.parentDataProperty,i.parentDataProperty],[pn.default.rootData,pn.default.rootData]];i.opts.dynamicRef&&d.push([pn.default.dynamicAnchors,pn.default.dynamicAnchors]);let p=(0,Re._)`${l}, ${r.object(...d)}`;return c!==Re.nil?(0,Re._)`${a}.call(${c}, ${p})`:(0,Re._)`${a}(${p})`}_e.callValidateCode=Aj;var Cj=(0,Re._)`new RegExp`;function Dj({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,Re._)`${s.code==="new RegExp"?Cj:(0,Pj.useFunc)(t,s)}(${r}, ${n})`})}_e.usePattern=Dj;function Oj(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let c=e.const("len",(0,Re._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Xf.Type.Num},o),e.if((0,Re.not)(o),a)})}}_e.validateArray=Oj;function zj(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Xf.alwaysValidSchema)(s,c))&&!s.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,Re._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Re.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}_e.validateUnion=zj});var fx=S(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.validateKeywordUsage=wr.validSchemaType=wr.funcKeywordCode=wr.macroKeywordCode=void 0;var ht=te(),as=Ur(),Mj=Wt(),Nj=na();function jj(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=px(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:ht.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}wr.macroKeywordCode=jj;function Lj(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;Fj(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,l=px(n,s,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)h(),e.modifying&&dx(t),v(()=>t.error());else{let g=e.async?f():m();e.modifying&&dx(t),v(()=>qj(t,g))}}function f(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,ht._)`await `),b=>n.assign(d,!1).if((0,ht._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,ht._)`${b}.errors`),()=>n.throw(b))),g}function m(){let g=(0,ht._)`${l}.errors`;return n.assign(g,null),h(ht.nil),g}function h(g=e.async?(0,ht._)`await `:ht.nil){let b=c.opts.passContext?as.default.this:as.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ht._)`${g}${(0,Mj.callValidateCode)(t,l,b,_)}`,e.modifying)}function v(g){var b;n.if((0,ht.not)((b=e.valid)!==null&&b!==void 0?b:d),g)}}wr.funcKeywordCode=Lj;function dx(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ht._)`${n.parentData}[${n.parentDataProperty}]`))}function qj(t,e){let{gen:r}=t;r.if((0,ht._)`Array.isArray(${e})`,()=>{r.assign(as.default.vErrors,(0,ht._)`${as.default.vErrors} === null ? ${e} : ${as.default.vErrors}.concat(${e})`).assign(as.default.errors,(0,ht._)`${as.default.vErrors}.length`),(0,Nj.extendErrors)(t)},()=>t.error())}function Fj({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function px(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,ht.stringify)(r)})}function Uj(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")}wr.validSchemaType=Uj;function Zj({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}wr.validateKeywordUsage=Zj});var hx=S(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.extendSubschemaMode=fn.extendSubschemaData=fn.getSubschema=void 0;var Sr=te(),mx=le();function Vj(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,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,Sr._)`${t.schemaPath}${(0,Sr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Sr._)`${t.schemaPath}${(0,Sr.getProperty)(e)}${(0,Sr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,mx.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}fn.getSubschema=Vj;function Bj(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==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,Sr._)`${e.data}${(0,Sr.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Sr.str)`${u}${(0,mx.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Sr._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Sr.Name?s:a.let("data",s,!0);c(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);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]}}fn.extendSubschemaData=Bj;function Wj(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}fn.extendSubschemaMode=Wj});var oa=S((OQ,gx)=>{"use strict";gx.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,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))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(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var vx=S((zQ,yx)=>{"use strict";var mn=yx.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};Mu(e,n,s,t,"",t)};mn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};mn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};mn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};mn.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 Mu(t,e,r,n,s,o,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in mn.arrayKeywords)for(var p=0;p<d.length;p++)Mu(t,e,r,d[p],s+"/"+l+"/"+p,o,s,l,n,p)}else if(l in mn.propsKeywords){if(d&&typeof d=="object")for(var f in d)Mu(t,e,r,d[f],s+"/"+l+"/"+Hj(f),o,s,l,n,f)}else(l in mn.keywords||t.allKeys&&!(l in mn.skipKeywords))&&Mu(t,e,r,d,s+"/"+l,o,s,l,n)}r(n,s,o,i,a,c,u)}}function Hj(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ia=S(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.getSchemaRefs=xt.resolveUrl=xt.normalizeId=xt._getFullPath=xt.getFullPath=xt.inlineRef=void 0;var Kj=le(),Jj=oa(),Gj=vx(),Yj=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Xj(t,e=!0){return typeof t=="boolean"?!0:e===!0?!tm(t):e?_x(t)<=e:!1}xt.inlineRef=Xj;var Qj=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function tm(t){for(let e in t){if(Qj.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(tm)||typeof r=="object"&&tm(r))return!0}return!1}function _x(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!Yj.has(r)&&(typeof t[r]=="object"&&(0,Kj.eachItem)(t[r],n=>e+=_x(n)),e===1/0))return 1/0}return e}function bx(t,e="",r){r!==!1&&(e=_o(e));let n=t.parse(e);return wx(t,n)}xt.getFullPath=bx;function wx(t,e){return t.serialize(e).split("#")[0]+"#"}xt._getFullPath=wx;var e1=/#\/?$/;function _o(t){return t?t.replace(e1,""):""}xt.normalizeId=_o;function t1(t,e,r){return r=_o(r),t.resolve(e,r)}xt.resolveUrl=t1;var r1=/^[a-z_][-a-z0-9._]*$/i;function n1(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=_o(t[r]||e),o={"":s},i=bx(n,s,!1),a={},c=new Set;return Gj(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=i+p,v=o[m];typeof d[r]=="string"&&(v=g.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),o[p]=v;function g(_){let P=this.opts.uriResolver.resolve;if(_=_o(v?P(v,_):_),c.has(_))throw l(_);c.add(_);let x=this.refs[_];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?u(d,x.schema,_):_!==_o(h)&&(_[0]==="#"?(u(d,a[_],_),a[_]=d):this.refs[_]=h),_}function b(_){if(typeof _=="string"){if(!r1.test(_))throw new Error(`invalid anchor "${_}"`);g.call(this,`#${_}`)}}}),a;function u(d,p,f){if(p!==void 0&&!Jj(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}xt.getSchemaRefs=n1});var ua=S(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.getData=hn.KeywordCxt=hn.validateFunctionCode=void 0;var kx=tx(),Sx=sa(),nm=Kf(),Nu=sa(),s1=cx(),ca=fx(),rm=hx(),M=te(),V=Ur(),o1=ia(),Zr=le(),aa=na();function i1(t){if(Ix(t)&&(Rx(t),Tx(t))){u1(t);return}Ex(t,()=>(0,kx.topBoolOrEmptySchema)(t))}hn.validateFunctionCode=i1;function Ex({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,M._)`${V.default.data}, ${V.default.valCxt}`,n.$async,()=>{t.code((0,M._)`"use strict"; ${$x(r,s)}`),c1(t,s),t.code(o)}):t.func(e,(0,M._)`${V.default.data}, ${a1(s)}`,n.$async,()=>t.code($x(r,s)).code(o))}function a1(t){return(0,M._)`{${V.default.instancePath}="", ${V.default.parentData}, ${V.default.parentDataProperty}, ${V.default.rootData}=${V.default.data}${t.dynamicRef?(0,M._)`, ${V.default.dynamicAnchors}={}`:M.nil}}={}`}function c1(t,e){t.if(V.default.valCxt,()=>{t.var(V.default.instancePath,(0,M._)`${V.default.valCxt}.${V.default.instancePath}`),t.var(V.default.parentData,(0,M._)`${V.default.valCxt}.${V.default.parentData}`),t.var(V.default.parentDataProperty,(0,M._)`${V.default.valCxt}.${V.default.parentDataProperty}`),t.var(V.default.rootData,(0,M._)`${V.default.valCxt}.${V.default.rootData}`),e.dynamicRef&&t.var(V.default.dynamicAnchors,(0,M._)`${V.default.valCxt}.${V.default.dynamicAnchors}`)},()=>{t.var(V.default.instancePath,(0,M._)`""`),t.var(V.default.parentData,(0,M._)`undefined`),t.var(V.default.parentDataProperty,(0,M._)`undefined`),t.var(V.default.rootData,V.default.data),e.dynamicRef&&t.var(V.default.dynamicAnchors,(0,M._)`{}`)})}function u1(t){let{schema:e,opts:r,gen:n}=t;Ex(t,()=>{r.$comment&&e.$comment&&Cx(t),m1(t),n.let(V.default.vErrors,null),n.let(V.default.errors,0),r.unevaluated&&l1(t),Ax(t),y1(t)})}function l1(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,M._)`${r}.evaluated`),e.if((0,M._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,M._)`${t.evaluated}.props`,(0,M._)`undefined`)),e.if((0,M._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,M._)`${t.evaluated}.items`,(0,M._)`undefined`))}function $x(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,M._)`/*# sourceURL=${r} */`:M.nil}function d1(t,e){if(Ix(t)&&(Rx(t),Tx(t))){p1(t,e);return}(0,kx.boolOrEmptySchema)(t,e)}function Tx({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 Ix(t){return typeof t.schema!="boolean"}function p1(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&Cx(t),h1(t),g1(t);let o=n.const("_errs",V.default.errors);Ax(t,o),n.var(e,(0,M._)`${o} === ${V.default.errors}`)}function Rx(t){(0,Zr.checkUnknownRules)(t),f1(t)}function Ax(t,e){if(t.opts.jtd)return xx(t,[],!1,e);let r=(0,Sx.getSchemaTypes)(t.schema),n=(0,Sx.coerceAndCheckDataType)(t,r);xx(t,r,!n,e)}function f1(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Zr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function m1(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Zr.checkStrictMode)(t,"default is ignored in the schema root")}function h1(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,o1.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function g1(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Cx({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,M._)`${V.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,M.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,M._)`${V.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function y1(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,M._)`${V.default.errors} === 0`,()=>e.return(V.default.data),()=>e.throw((0,M._)`new ${s}(${V.default.vErrors})`)):(e.assign((0,M._)`${n}.errors`,V.default.vErrors),o.unevaluated&&v1(t),e.return((0,M._)`${V.default.errors} === 0`))}function v1({gen:t,evaluated:e,props:r,items:n}){r instanceof M.Name&&t.assign((0,M._)`${e}.props`,r),n instanceof M.Name&&t.assign((0,M._)`${e}.items`,n)}function xx(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,Zr.schemaHasRulesButRef)(o,l))){s.block(()=>Ox(t,"$ref",l.all.$ref.definition));return}c.jtd||_1(t,e),s.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,nm.shouldUseGroup)(o,p)&&(p.type?(s.if((0,Nu.checkDataType)(p.type,i,c.strictNumbers)),Px(t,p),e.length===1&&e[0]===p.type&&r&&(s.else(),(0,Nu.reportTypeError)(t)),s.endIf()):Px(t,p),a||s.if((0,M._)`${V.default.errors} === ${n||0}`))}}function Px(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,s1.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,nm.shouldUseRule)(n,o)&&Ox(t,o.keyword,o.definition,e.type)})}function _1(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(b1(t,e),t.opts.allowUnionTypes||w1(t,e),S1(t,t.dataTypes))}function b1(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Dx(t.dataTypes,r)||sm(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),x1(t,e)}}function w1(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&sm(t,"use allowUnionTypes to allow union type keyword")}function S1(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,nm.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>$1(e,i))&&sm(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function $1(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Dx(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function x1(t,e){let r=[];for(let n of t.dataTypes)Dx(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function sm(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Zr.checkStrictMode)(t,e,t.opts.strictTypes)}var ju=class{constructor(e,r,n){if((0,ca.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,Zr.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",zx(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ca.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",V.default.errors))}result(e,r,n){this.failResult((0,M.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,M.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,M._)`${r} !== undefined && (${(0,M.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?aa.reportExtraError:aa.reportError)(this,this.def.error,r)}$dataError(){(0,aa.reportError)(this,this.def.$dataError||aa.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,aa.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=M.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=M.nil,r=M.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,M.or)((0,M._)`${s} === undefined`,r)),e!==M.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==M.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,M.or)(i(),a());function i(){if(n.length){if(!(r instanceof M.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,M._)`${(0,Nu.checkDataTypes)(c,r,o.opts.strictNumbers,Nu.DataType.Wrong)}`}return M.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,M._)`!${c}(${r})`}return M.nil}}subschema(e,r){let n=(0,rm.getSubschema)(this.it,e);(0,rm.extendSubschemaData)(n,this.it,e),(0,rm.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return d1(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Zr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Zr.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,M.Name)),!0}};hn.KeywordCxt=ju;function Ox(t,e,r,n){let s=new ju(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,ca.funcKeywordCode)(s,r):"macro"in r?(0,ca.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,ca.funcKeywordCode)(s,r)}var P1=/^\/(?:[^~]|~0|~1)*$/,k1=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function zx(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return V.default.rootData;if(t[0]==="/"){if(!P1.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=V.default.rootData}else{let u=k1.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(s=u[2],s==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(o=r[e-l],!s)return o}let i=o,a=s.split("/");for(let u of a)u&&(o=(0,M._)`${o}${(0,M.getProperty)((0,Zr.unescapeJsonPointer)(u))}`,i=(0,M._)`${i} && ${o}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}hn.getData=zx});var Lu=S(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});var om=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};im.default=om});var la=S(um=>{"use strict";Object.defineProperty(um,"__esModule",{value:!0});var am=ia(),cm=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,am.resolveUrl)(e,r,n),this.missingSchema=(0,am.normalizeId)((0,am.getFullPath)(e,this.missingRef))}};um.default=cm});var Fu=S(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.resolveSchema=Ht.getCompilingSchema=Ht.resolveRef=Ht.compileSchema=Ht.SchemaEnv=void 0;var or=te(),E1=Lu(),cs=Ur(),ir=ia(),Mx=le(),T1=ua(),bo=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,ir.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Ht.SchemaEnv=bo;function dm(t){let e=Nx.call(this,t);if(e)return e;let r=(0,ir.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new or.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:E1.default,code:(0,or._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:cs.default.data,parentData:cs.default.parentData,parentDataProperty:cs.default.parentDataProperty,dataNames:[cs.default.data],dataPathArr:[or.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,or.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:or.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,or._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,T1.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(cs.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${cs.default.self}`,`${cs.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:h}=u;f.evaluated={props:m instanceof or.Name?void 0:m,items:h instanceof or.Name?void 0:h,dynamicProps:m instanceof or.Name,dynamicItems:h instanceof or.Name},f.source&&(f.source.evaluated=(0,or.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)}}Ht.compileSchema=dm;function I1(t,e,r){var n;r=(0,ir.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=C1.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(o=new bo({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=R1.call(this,o)}Ht.resolveRef=I1;function R1(t){return(0,ir.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:dm.call(this,t)}function Nx(t){for(let e of this._compilations)if(A1(e,t))return e}Ht.getCompilingSchema=Nx;function A1(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function C1(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||qu.call(this,t,e)}function qu(t,e){let r=this.opts.uriResolver.parse(e),n=(0,ir._getFullPath)(this.opts.uriResolver,r),s=(0,ir.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return lm.call(this,r,t);let o=(0,ir.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=qu.call(this,t,i);return typeof a?.schema!="object"?void 0:lm.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||dm.call(this,i),o===(0,ir.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,ir.resolveUrl)(this.opts.uriResolver,s,u)),new bo({schema:a,schemaId:c,root:t,baseId:s})}return lm.call(this,r,i)}}Ht.resolveSchema=qu;var D1=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function lm(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Mx.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!D1.has(a)&&u&&(e=(0,ir.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,Mx.schemaHasRulesButRef)(r,this.RULES)){let a=(0,ir.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=qu.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new bo({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var jx=S((FQ,O1)=>{O1.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 fm=S((UQ,Ux)=>{"use strict";var z1=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),qx=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 pm(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 M1=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Lx(t){return t.length=0,!0}function N1(t,e,r){if(t.length){let n=pm(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function j1(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=N1;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!a(s,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(o=!0),n.push(":");continue}else if(u==="%"){if(!a(s,n,r))break;a=Lx}else{s.push(u);continue}}return s.length&&(a===Lx?r.zone=s.join(""):i?n.push(s.join("")):n.push(pm(s))),r.address=n.join(""),r}function Fx(t){if(L1(t,":")<2)return{host:t,isIPV6:!1};let e=j1(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 L1(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function q1(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(s===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(s===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 F1(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 U1(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!qx(r)){let n=Fx(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}Ux.exports={nonSimpleDomain:M1,recomposeAuthority:U1,normalizeComponentEncoding:F1,removeDotSegments:q1,isIPv4:qx,isUUID:z1,normalizeIPv6:Fx,stringArrayToHexStripped:pm}});var Hx=S((ZQ,Wx)=>{"use strict";var{isUUID:Z1}=fm(),V1=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,B1=["http","https","ws","wss","urn","urn:uuid"];function W1(t){return B1.indexOf(t)!==-1}function mm(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 Zx(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Vx(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 H1(t){return t.secure=mm(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function K1(t){if((t.port===(mm(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 J1(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(V1);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=hm(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function G1(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(),s=`${r}:${e.nid||n}`,o=hm(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function Y1(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Z1(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function X1(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Bx={scheme:"http",domainHost:!0,parse:Zx,serialize:Vx},Q1={scheme:"https",domainHost:Bx.domainHost,parse:Zx,serialize:Vx},Uu={scheme:"ws",domainHost:!0,parse:H1,serialize:K1},eL={scheme:"wss",domainHost:Uu.domainHost,parse:Uu.parse,serialize:Uu.serialize},tL={scheme:"urn",parse:J1,serialize:G1,skipNormalize:!0},rL={scheme:"urn:uuid",parse:Y1,serialize:X1,skipNormalize:!0},Zu={http:Bx,https:Q1,ws:Uu,wss:eL,urn:tL,"urn:uuid":rL};Object.setPrototypeOf(Zu,null);function hm(t){return t&&(Zu[t]||Zu[t.toLowerCase()])||void 0}Wx.exports={wsIsSecure:mm,SCHEMES:Zu,isValidSchemeName:W1,getSchemeHandler:hm}});var ym=S((VQ,Bu)=>{"use strict";var{normalizeIPv6:nL,removeDotSegments:da,recomposeAuthority:sL,normalizeComponentEncoding:Vu,isIPv4:oL,nonSimpleDomain:iL}=fm(),{SCHEMES:aL,getSchemeHandler:Kx}=Hx();function cL(t,e){return typeof t=="string"?t=$r(Vr(t,e),e):typeof t=="object"&&(t=Vr($r(t,e),e)),t}function uL(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=Jx(Vr(t,n),Vr(e,n),n,!0);return n.skipEscape=!0,$r(s,n)}function Jx(t,e,r,n){let s={};return n||(t=Vr($r(t,r),r),e=Vr($r(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=da(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=da(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=da(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=da(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function lL(t,e,r){return typeof t=="string"?(t=unescape(t),t=$r(Vu(Vr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=$r(Vu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=$r(Vu(Vr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=$r(Vu(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function $r(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),s=[],o=Kx(n.scheme||r.scheme);o&&o.serialize&&o.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&&s.push(r.scheme,":");let i=sL(r);if(i!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(i),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=da(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var dL=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Vr(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},s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let o=t.match(dL);if(o){if(n.scheme=o[1],n.userinfo=o[3],n.host=o[4],n.port=parseInt(o[5],10),n.path=o[6]||"",n.query=o[7],n.fragment=o[8],isNaN(n.port)&&(n.port=o[5]),n.host)if(oL(n.host)===!1){let c=nL(n.host);n.host=c.host.toLowerCase(),s=c.isIPV6}else s=!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=Kx(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&iL(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 gm={SCHEMES:aL,normalize:cL,resolve:uL,resolveComponent:Jx,equal:lL,serialize:$r,parse:Vr};Bu.exports=gm;Bu.exports.default=gm;Bu.exports.fastUri=gm});var Yx=S(vm=>{"use strict";Object.defineProperty(vm,"__esModule",{value:!0});var Gx=ym();Gx.code='require("ajv/dist/runtime/uri").default';vm.default=Gx});var o0=S(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.CodeGen=Xe.Name=Xe.nil=Xe.stringify=Xe.str=Xe._=Xe.KeywordCxt=void 0;var pL=ua();Object.defineProperty(Xe,"KeywordCxt",{enumerable:!0,get:function(){return pL.KeywordCxt}});var wo=te();Object.defineProperty(Xe,"_",{enumerable:!0,get:function(){return wo._}});Object.defineProperty(Xe,"str",{enumerable:!0,get:function(){return wo.str}});Object.defineProperty(Xe,"stringify",{enumerable:!0,get:function(){return wo.stringify}});Object.defineProperty(Xe,"nil",{enumerable:!0,get:function(){return wo.nil}});Object.defineProperty(Xe,"Name",{enumerable:!0,get:function(){return wo.Name}});Object.defineProperty(Xe,"CodeGen",{enumerable:!0,get:function(){return wo.CodeGen}});var fL=Lu(),r0=la(),mL=Hf(),pa=Fu(),hL=te(),fa=ia(),Wu=sa(),bm=le(),Xx=jx(),gL=Yx(),n0=(t,e)=>new RegExp(t,e);n0.code="new RegExp";var yL=["removeAdditional","useDefaults","coerceTypes"],vL=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),_L={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."},bL={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Qx=200;function wL(t){var e,r,n,s,o,i,a,c,u,l,d,p,f,m,h,v,g,b,_,P,x,j,k,O,L;let q=t.strict,$e=(e=t.code)===null||e===void 0?void 0:e.optimize,He=$e===!0||$e===void 0?1:$e||0,Rt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:n0,Mt=(s=t.uriResolver)!==null&&s!==void 0?s:gL.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:q)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:q)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:q)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:q)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:q)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:He,regExp:Rt}:{optimize:He,regExp:Rt},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Qx,loopEnum:(v=t.loopEnum)!==null&&v!==void 0?v:Qx,meta:(g=t.meta)!==null&&g!==void 0?g:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(P=t.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(x=t.addUsedSchema)!==null&&x!==void 0?x:!0,validateSchema:(j=t.validateSchema)!==null&&j!==void 0?j:!0,validateFormats:(k=t.validateFormats)!==null&&k!==void 0?k:!0,unicodeRegExp:(O=t.unicodeRegExp)!==null&&O!==void 0?O:!0,int32range:(L=t.int32range)!==null&&L!==void 0?L:!0,uriResolver:Mt}}var ma=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...wL(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new hL.ValueScope({scope:{},prefixes:vL,es5:r,lines:n}),this.logger=EL(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,mL.getRules)(),e0.call(this,_L,e,"NOT SUPPORTED"),e0.call(this,bL,e,"DEPRECATED","warn"),this._metaOpts=PL.call(this),e.formats&&$L.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&xL.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),SL.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Xx;n==="id"&&(s={...Xx},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[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 s=n(r);return"$async"in n||(this.errors=n.errors),s}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 s.call(this,e,r);async function s(l,d){await o.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function o(l){l&&!this.getSchema(l)&&await s.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof r0.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 o.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,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,fa.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!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 s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=t0.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new pa.SchemaEnv({schema:{},schemaId:n});if(r=pa.resolveSchema.call(this,s,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=t0.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,fa.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(IL.call(this,n,r),!r)return(0,bm.eachItem)(n,o=>_m.call(this,o)),this;AL.call(this,r);let s={...r,type:(0,Wu.getJSONTypes)(r.type),schemaType:(0,Wu.getJSONTypes)(r.schemaType)};return(0,bm.eachItem)(n,s.type.length===0?o=>_m.call(this,o,s):o=>s.type.forEach(i=>_m.call(this,o,s,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 s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,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(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let a of o)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]=s0(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=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,fa.normalizeId)(i||n);let u=fa.getSchemaRefs.call(this,e,n);return c=new pa.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&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):pa.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{pa.compileSchema.call(this,e)}finally{this.opts=r}}};ma.ValidationError=fL.default;ma.MissingRefError=r0.default;Xe.default=ma;function e0(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function t0(t){return t=(0,fa.normalizeId)(t),this.schemas[t]||this.refs[t]}function SL(){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 $L(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function xL(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 PL(){let t={...this.opts};for(let e of yL)delete t[e];return t}var kL={log(){},warn(){},error(){}};function EL(t){if(t===!1)return kL;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 TL=/^[a-z_$][a-z0-9_$:-]*$/i;function IL(t,e){let{RULES:r}=this;if((0,bm.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!TL.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 _m(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Wu.getJSONTypes)(e.type),schemaType:(0,Wu.getJSONTypes)(e.schemaType)}};e.before?RL.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function RL(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function AL(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=s0(e)),t.validateSchema=this.compile(e,!0))}var CL={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function s0(t){return{anyOf:[t,CL]}}});var i0=S(wm=>{"use strict";Object.defineProperty(wm,"__esModule",{value:!0});var DL={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};wm.default=DL});var l0=S(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.callRef=us.getValidate=void 0;var OL=la(),a0=Wt(),Pt=te(),So=Ur(),c0=Fu(),Hu=le(),zL={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:c}=n,{root:u}=o;if((r==="#"||r==="#/")&&s===u.baseId)return d();let l=c0.resolveRef.call(c,u,s,r);if(l===void 0)throw new OL.default(n.opts.uriResolver,s,r);if(l instanceof c0.SchemaEnv)return p(l);return f(l);function d(){if(o===u)return Ku(t,i,o,o.$async);let m=e.scopeValue("root",{ref:u});return Ku(t,(0,Pt._)`${m}.validate`,u,u.$async)}function p(m){let h=u0(t,m);Ku(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Pt.stringify)(m)}:{ref:m}),v=e.name("valid"),g=t.subschema({schema:m,dataTypes:[],schemaPath:Pt.nil,topSchemaRef:h,errSchemaPath:r},v);t.mergeEvaluated(g),t.ok(v)}}};function u0(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Pt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}us.getValidate=u0;function Ku(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?So.default.this:Pt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=s.let("valid");s.try(()=>{s.code((0,Pt._)`await ${(0,a0.callValidateCode)(t,e,u)}`),f(e),i||s.assign(m,!0)},h=>{s.if((0,Pt._)`!(${h} instanceof ${o.ValidationError})`,()=>s.throw(h)),p(h),i||s.assign(m,!1)}),t.ok(m)}function d(){t.result((0,a0.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,Pt._)`${m}.errors`;s.assign(So.default.vErrors,(0,Pt._)`${So.default.vErrors} === null ? ${h} : ${So.default.vErrors}.concat(${h})`),s.assign(So.default.errors,(0,Pt._)`${So.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let v=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(v&&!v.dynamicProps)v.props!==void 0&&(o.props=Hu.mergeEvaluated.props(s,v.props,o.props));else{let g=s.var("props",(0,Pt._)`${m}.evaluated.props`);o.props=Hu.mergeEvaluated.props(s,g,o.props,Pt.Name)}if(o.items!==!0)if(v&&!v.dynamicItems)v.items!==void 0&&(o.items=Hu.mergeEvaluated.items(s,v.items,o.items));else{let g=s.var("items",(0,Pt._)`${m}.evaluated.items`);o.items=Hu.mergeEvaluated.items(s,g,o.items,Pt.Name)}}}us.callRef=Ku;us.default=zL});var d0=S(Sm=>{"use strict";Object.defineProperty(Sm,"__esModule",{value:!0});var ML=i0(),NL=l0(),jL=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",ML.default,NL.default];Sm.default=jL});var p0=S($m=>{"use strict";Object.defineProperty($m,"__esModule",{value:!0});var Ju=te(),gn=Ju.operators,Gu={maximum:{okStr:"<=",ok:gn.LTE,fail:gn.GT},minimum:{okStr:">=",ok:gn.GTE,fail:gn.LT},exclusiveMaximum:{okStr:"<",ok:gn.LT,fail:gn.GTE},exclusiveMinimum:{okStr:">",ok:gn.GT,fail:gn.LTE}},LL={message:({keyword:t,schemaCode:e})=>(0,Ju.str)`must be ${Gu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ju._)`{comparison: ${Gu[t].okStr}, limit: ${e}}`},qL={keyword:Object.keys(Gu),type:"number",schemaType:"number",$data:!0,error:LL,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Ju._)`${r} ${Gu[e].fail} ${n} || isNaN(${r})`)}};$m.default=qL});var f0=S(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});var ha=te(),FL={message:({schemaCode:t})=>(0,ha.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ha._)`{multipleOf: ${t}}`},UL={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:FL,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,ha._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,ha._)`${i} !== parseInt(${i})`;t.fail$data((0,ha._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};xm.default=UL});var h0=S(Pm=>{"use strict";Object.defineProperty(Pm,"__esModule",{value:!0});function m0(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}Pm.default=m0;m0.code='require("ajv/dist/runtime/ucs2length").default'});var g0=S(km=>{"use strict";Object.defineProperty(km,"__esModule",{value:!0});var ls=te(),ZL=le(),VL=h0(),BL={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,ls.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,ls._)`{limit: ${t}}`},WL={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:BL,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?ls.operators.GT:ls.operators.LT,i=s.opts.unicode===!1?(0,ls._)`${r}.length`:(0,ls._)`${(0,ZL.useFunc)(t.gen,VL.default)}(${r})`;t.fail$data((0,ls._)`${i} ${o} ${n}`)}};km.default=WL});var y0=S(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});var HL=Wt(),KL=le(),$o=te(),JL={message:({schemaCode:t})=>(0,$o.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,$o._)`{pattern: ${t}}`},GL={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:JL,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,$o._)`new RegExp`:(0,KL.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,$o._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,$o._)`!${l}`)}else{let c=(0,HL.usePattern)(t,s);t.fail$data((0,$o._)`!${c}.test(${r})`)}}};Em.default=GL});var v0=S(Tm=>{"use strict";Object.defineProperty(Tm,"__esModule",{value:!0});var ga=te(),YL={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ga.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ga._)`{limit: ${t}}`},XL={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:YL,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?ga.operators.GT:ga.operators.LT;t.fail$data((0,ga._)`Object.keys(${r}).length ${s} ${n}`)}};Tm.default=XL});var _0=S(Im=>{"use strict";Object.defineProperty(Im,"__esModule",{value:!0});var ya=Wt(),va=te(),QL=le(),eq={message:({params:{missingProperty:t}})=>(0,va.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,va._)`{missingProperty: ${t}}`},tq={keyword:"required",type:"object",schemaType:"array",$data:!0,error:eq,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&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 h of r)if(f?.[h]===void 0&&!m.has(h)){let v=i.schemaEnv.baseId+i.errSchemaPath,g=`required property "${h}" is not defined at "${v}" (strictRequired)`;(0,QL.checkStrictMode)(i,g,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(va.nil,d);else for(let f of r)(0,ya.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||o){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,ya.checkMissingProp)(t,r,f)),(0,ya.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,ya.noPropertyInData)(e,s,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,ya.propertyInData)(e,s,f,a.ownProperties)),e.if((0,va.not)(m),()=>{t.error(),e.break()})},va.nil)}}};Im.default=tq});var b0=S(Rm=>{"use strict";Object.defineProperty(Rm,"__esModule",{value:!0});var _a=te(),rq={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,_a.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,_a._)`{limit: ${t}}`},nq={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:rq,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?_a.operators.GT:_a.operators.LT;t.fail$data((0,_a._)`${r}.length ${s} ${n}`)}};Rm.default=nq});var Yu=S(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});var w0=oa();w0.code='require("ajv/dist/runtime/equal").default';Am.default=w0});var S0=S(Dm=>{"use strict";Object.defineProperty(Dm,"__esModule",{value:!0});var Cm=sa(),Qe=te(),sq=le(),oq=Yu(),iq={message:({params:{i:t,j:e}})=>(0,Qe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Qe._)`{i: ${t}, j: ${e}}`},aq={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:iq,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let c=e.let("valid"),u=o.items?(0,Cm.getSchemaTypes)(o.items):[];t.block$data(c,l,(0,Qe._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,Qe._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,Qe._)`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,h){let v=e.name("item"),g=(0,Cm.checkDataTypes)(u,v,a.opts.strictNumbers,Cm.DataType.Wrong),b=e.const("indices",(0,Qe._)`{}`);e.for((0,Qe._)`;${m}--;`,()=>{e.let(v,(0,Qe._)`${r}[${m}]`),e.if(g,(0,Qe._)`continue`),u.length>1&&e.if((0,Qe._)`typeof ${v} == "string"`,(0,Qe._)`${v} += "_"`),e.if((0,Qe._)`typeof ${b}[${v}] == "number"`,()=>{e.assign(h,(0,Qe._)`${b}[${v}]`),t.error(),e.assign(c,!1).break()}).code((0,Qe._)`${b}[${v}] = ${m}`)})}function f(m,h){let v=(0,sq.useFunc)(e,oq.default),g=e.name("outer");e.label(g).for((0,Qe._)`;${m}--;`,()=>e.for((0,Qe._)`${h} = ${m}; ${h}--;`,()=>e.if((0,Qe._)`${v}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(g)})))}}};Dm.default=aq});var $0=S(zm=>{"use strict";Object.defineProperty(zm,"__esModule",{value:!0});var Om=te(),cq=le(),uq=Yu(),lq={message:"must be equal to constant",params:({schemaCode:t})=>(0,Om._)`{allowedValue: ${t}}`},dq={keyword:"const",$data:!0,error:lq,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,Om._)`!${(0,cq.useFunc)(e,uq.default)}(${r}, ${s})`):t.fail((0,Om._)`${o} !== ${r}`)}};zm.default=dq});var x0=S(Mm=>{"use strict";Object.defineProperty(Mm,"__esModule",{value:!0});var ba=te(),pq=le(),fq=Yu(),mq={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ba._)`{allowedValues: ${t}}`},hq={keyword:"enum",schemaType:"array",$data:!0,error:mq,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,pq.useFunc)(e,fq.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let f=e.const("vSchema",o);l=(0,ba.or)(...s.map((m,h)=>p(f,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",o,f=>e.if((0,ba._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let h=s[m];return typeof h=="object"&&h!==null?(0,ba._)`${u()}(${r}, ${f}[${m}])`:(0,ba._)`${r} === ${h}`}}};Mm.default=hq});var P0=S(Nm=>{"use strict";Object.defineProperty(Nm,"__esModule",{value:!0});var gq=p0(),yq=f0(),vq=g0(),_q=y0(),bq=v0(),wq=_0(),Sq=b0(),$q=S0(),xq=$0(),Pq=x0(),kq=[gq.default,yq.default,vq.default,_q.default,bq.default,wq.default,Sq.default,$q.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},xq.default,Pq.default];Nm.default=kq});var Lm=S(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.validateAdditionalItems=void 0;var ds=te(),jm=le(),Eq={message:({params:{len:t}})=>(0,ds.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ds._)`{limit: ${t}}`},Tq={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Eq,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,jm.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}k0(t,n)}};function k0(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,ds._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,ds._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,jm.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,ds._)`${a} <= ${e.length}`);r.if((0,ds.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:o,dataProp:l,dataPropType:jm.Type.Num},u),i.allErrors||r.if((0,ds.not)(u),()=>r.break())})}}wa.validateAdditionalItems=k0;wa.default=Tq});var qm=S(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.validateTuple=void 0;var E0=te(),Xu=le(),Iq=Wt(),Rq={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return T0(t,"additionalItems",e);r.items=!0,!(0,Xu.alwaysValidSchema)(r,e)&&t.ok((0,Iq.validateArray)(t))}};function T0(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=t;l(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Xu.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,E0._)`${o}.length`);r.forEach((d,p)=>{(0,Xu.alwaysValidSchema)(a,d)||(n.if((0,E0._)`${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,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let v=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Xu.checkStrictMode)(a,v,p.strictTuples)}}}Sa.validateTuple=T0;Sa.default=Rq});var I0=S(Fm=>{"use strict";Object.defineProperty(Fm,"__esModule",{value:!0});var Aq=qm(),Cq={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Aq.validateTuple)(t,"items")};Fm.default=Cq});var A0=S(Um=>{"use strict";Object.defineProperty(Um,"__esModule",{value:!0});var R0=te(),Dq=le(),Oq=Wt(),zq=Lm(),Mq={message:({params:{len:t}})=>(0,R0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,R0._)`{limit: ${t}}`},Nq={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Mq,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,Dq.alwaysValidSchema)(n,e)&&(s?(0,zq.validateAdditionalItems)(t,s):t.ok((0,Oq.validateArray)(t)))}};Um.default=Nq});var C0=S(Zm=>{"use strict";Object.defineProperty(Zm,"__esModule",{value:!0});var Kt=te(),Qu=le(),jq={message:({params:{min:t,max:e}})=>e===void 0?(0,Kt.str)`must contain at least ${t} valid item(s)`:(0,Kt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Kt._)`{minContains: ${t}}`:(0,Kt._)`{minContains: ${t}, maxContains: ${e}}`},Lq={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:jq,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:c,maxContains:u}=n;o.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,Kt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Qu.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Qu.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Qu.alwaysValidSchema)(o,r)){let h=(0,Kt._)`${l} >= ${i}`;a!==void 0&&(h=(0,Kt._)`${h} && ${l} <= ${a}`),t.pass(h);return}o.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,Kt._)`${s}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),v=e.let("count",0);f(h,()=>e.if(h,()=>m(v)))}function f(h,v){e.forRange("i",0,l,g=>{t.subschema({keyword:"contains",dataProp:g,dataPropType:Qu.Type.Num,compositeRule:!0},h),v()})}function m(h){e.code((0,Kt._)`${h}++`),a===void 0?e.if((0,Kt._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Kt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Kt._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};Zm.default=Lq});var z0=S(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.validateSchemaDeps=xr.validatePropertyDeps=xr.error=void 0;var Vm=te(),qq=le(),$a=Wt();xr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Vm.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Vm._)`{property: ${t},
|
|
10
10
|
missingProperty: ${n},
|
|
11
11
|
depsCount: ${e},
|
|
12
|
-
deps: ${r}}`};var Oq={keyword:"dependencies",type:"object",schemaType:"object",error:wr.error,code(t){let[e,r]=zq(t);P0(t,e),E0(t,r)}};function zq({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 P0(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,ga.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,ga.checkReportMissingProp)(t,u)}):(r.if((0,qm._)`${c} && (${(0,ga.checkMissingProp)(t,a,s)})`),(0,ga.reportMissingProp)(t,s),r.else())}}wr.validatePropertyDeps=P0;function E0(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,Dq.alwaysValidSchema)(s,e[a])||(r.if((0,ga.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))}wr.validateSchemaDeps=E0;wr.default=Oq});var I0=$(Fm=>{"use strict";Object.defineProperty(Fm,"__esModule",{value:!0});var R0=te(),Nq=le(),jq={message:"property name must be valid",params:({params:t})=>(0,R0._)`{propertyName: ${t.propertyName}}`},Mq={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:jq,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,Nq.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,R0.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Fm.default=Mq});var Zm=$(Um=>{"use strict";Object.defineProperty(Um,"__esModule",{value:!0});var Ku=Zt(),nr=te(),Lq=qr(),Ju=le(),qq={message:"must NOT have additional properties",params:({params:t})=>(0,nr._)`{additionalProperty: ${t.additionalProperty}}`},Fq={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:qq,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,Ju.alwaysValidSchema)(i,r))return;let u=(0,Ku.allSchemaProperties)(n.properties),l=(0,Ku.allSchemaProperties)(n.patternProperties);d(),t.ok((0,nr._)`${s} === ${Lq.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 b=(0,Ju.schemaRefOrVal)(i,n.properties,"properties");v=(0,Ku.isOwnProperty)(e,b,y)}else u.length?v=(0,nr.or)(...u.map(b=>(0,nr._)`${y} === ${b}`)):v=nr.nil;return l.length&&(v=(0,nr.or)(v,...l.map(b=>(0,nr._)`${(0,Ku.usePattern)(t,b)}.test(${y})`))),(0,nr.not)(v)}function f(y){e.code((0,nr._)`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,Ju.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(h(y,v,!1),e.if((0,nr.not)(v),()=>{t.reset(),f(y)})):(h(y,v),a||e.if((0,nr.not)(v),()=>e.break()))}}function h(y,v,b){let _={keyword:"additionalProperties",dataProp:y,dataPropType:Ju.Type.Str};b===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,v)}}};Um.default=Fq});var D0=$(Bm=>{"use strict";Object.defineProperty(Bm,"__esModule",{value:!0});var Uq=ra(),A0=Zt(),Vm=le(),C0=Zm(),Zq={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&&C0.default.code(new Uq.KeywordCxt(s,C0.default,"additionalProperties"));let i=(0,A0.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Vm.mergeEvaluated.props(e,(0,Vm.toHash)(i),s.props));let a=i.filter(d=>!(0,Vm.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,A0.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)}}};Bm.default=Zq});var j0=$(Wm=>{"use strict";Object.defineProperty(Wm,"__esModule",{value:!0});var O0=Zt(),Gu=te(),z0=le(),N0=le(),Vq={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,O0.allSchemaProperties)(r),c=a.filter(h=>(0,z0.alwaysValidSchema)(s,r[h]));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 Gu.Name)&&(s.props=(0,N0.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let h of a)u&&f(h),s.allErrors?m(h):(e.var(l,!0),m(h),e.if(l))}function f(h){for(let y in u)new RegExp(h).test(y)&&(0,z0.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,Gu._)`${(0,O0.usePattern)(t,h)}.test(${y})`,()=>{let v=c.includes(h);v||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:N0.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Gu._)`${d}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,Gu.not)(l),()=>e.break())})})}}};Wm.default=Vq});var M0=$(Hm=>{"use strict";Object.defineProperty(Hm,"__esModule",{value:!0});var Bq=le(),Wq={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Bq.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"}};Hm.default=Wq});var L0=$(Km=>{"use strict";Object.defineProperty(Km,"__esModule",{value:!0});var Hq=Zt(),Kq={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Hq.validateUnion,error:{message:"must match a schema in anyOf"}};Km.default=Kq});var q0=$(Jm=>{"use strict";Object.defineProperty(Jm,"__esModule",{value:!0});var Yu=te(),Jq=le(),Gq={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Yu._)`{passingSchemas: ${t.passing}}`},Yq={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Gq,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,Jq.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Yu._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Yu._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Yu.Name)})})}}};Jm.default=Yq});var F0=$(Gm=>{"use strict";Object.defineProperty(Gm,"__esModule",{value:!0});var Qq=le(),Xq={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,Qq.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Gm.default=Xq});var V0=$(Ym=>{"use strict";Object.defineProperty(Ym,"__esModule",{value:!0});var Qu=te(),Z0=le(),eF={message:({params:t})=>(0,Qu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Qu._)`{failingKeyword: ${t.ifClause}}`},tF={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:eF,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Z0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=U0(n,"then"),s=U0(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,Qu.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,Qu._)`${l}`):t.setParams({ifClause:l})}}}};function U0(t,e){let r=t.schema[e];return r!==void 0&&!(0,Z0.alwaysValidSchema)(t,r)}Ym.default=tF});var B0=$(Qm=>{"use strict";Object.defineProperty(Qm,"__esModule",{value:!0});var rF=le(),nF={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,rF.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Qm.default=nF});var W0=$(Xm=>{"use strict";Object.defineProperty(Xm,"__esModule",{value:!0});var oF=zm(),sF=$0(),iF=Nm(),aF=x0(),cF=k0(),uF=T0(),lF=I0(),dF=Zm(),pF=D0(),fF=j0(),mF=M0(),hF=L0(),gF=q0(),yF=F0(),vF=V0(),_F=B0();function bF(t=!1){let e=[mF.default,hF.default,gF.default,yF.default,vF.default,_F.default,lF.default,dF.default,uF.default,pF.default,fF.default];return t?e.push(sF.default,aF.default):e.push(oF.default,iF.default),e.push(cF.default),e}Xm.default=bF});var H0=$(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});var Ue=te(),wF={message:({schemaCode:t})=>(0,Ue.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ue._)`{format: ${t}}`},$F={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:wF,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}),h=r.const("fDef",(0,Ue._)`${m}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,Ue._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,Ue._)`${h}.type || "string"`).assign(v,(0,Ue._)`${h}.validate`),()=>r.assign(y,(0,Ue._)`"string"`).assign(v,h)),t.fail$data((0,Ue.or)(b(),_()));function b(){return c.strictSchema===!1?Ue.nil:(0,Ue._)`${i} && !${v}`}function _(){let k=l.$async?(0,Ue._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Ue._)`${v}(${n})`,x=(0,Ue._)`(typeof ${v} == "function" ? ${k} : ${v}.test(${n}))`;return(0,Ue._)`${v} && ${v} !== true && ${y} === ${e} && !${x}`}}function f(){let m=d.formats[s];if(!m){b();return}if(m===!0)return;let[h,y,v]=_(m);h===e&&t.pass(k());function b(){if(c.strictSchema===!1){d.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function _(x){let L=x instanceof RegExp?(0,Ue.regexpCode)(x):c.code.formats?(0,Ue._)`${c.code.formats}${(0,Ue.getProperty)(s)}`:void 0,P=r.scopeValue("formats",{key:s,ref:x,code:L});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,Ue._)`${P}.validate`]:["string",x,P]}function k(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ue._)`await ${v}(${n})`}return typeof y=="function"?(0,Ue._)`${v}(${n})`:(0,Ue._)`${v}.test(${n})`}}}};eh.default=$F});var K0=$(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var SF=H0(),xF=[SF.default];th.default=xF});var J0=$(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.contentVocabulary=hs.metadataVocabulary=void 0;hs.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];hs.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Y0=$(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});var kF=o0(),PF=v0(),EF=W0(),TF=K0(),G0=J0(),RF=[kF.default,PF.default,(0,EF.default)(),TF.default,G0.metadataVocabulary,G0.contentVocabulary];rh.default=RF});var X0=$(Xu=>{"use strict";Object.defineProperty(Xu,"__esModule",{value:!0});Xu.DiscrError=void 0;var Q0;(function(t){t.Tag="tag",t.Mapping="mapping"})(Q0||(Xu.DiscrError=Q0={}))});var tk=$(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});var gs=te(),nh=X0(),ek=zu(),IF=na(),AF=le(),CF={message:({params:{discrError:t,tagName:e}})=>t===nh.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,gs._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},DF={keyword:"discriminator",type:"object",schemaType:"object",error:CF,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,gs._)`${r}${(0,gs.getProperty)(a)}`);e.if((0,gs._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:nh.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,gs._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:nh.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,gs.Name),m}function p(){var f;let m={},h=v(o),y=!0;for(let k=0;k<i.length;k++){let x=i[k];if(x?.$ref&&!(0,AF.schemaHasRulesButRef)(x,s.self.RULES)){let P=x.$ref;if(x=ek.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,P),x instanceof ek.SchemaEnv&&(x=x.schema),x===void 0)throw new IF.default(s.opts.uriResolver,s.baseId,P)}let L=(f=x?.properties)===null||f===void 0?void 0:f[a];if(typeof L!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||v(x)),b(L,k)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function v({required:k}){return Array.isArray(k)&&k.includes(a)}function b(k,x){if(k.const)_(k.const,x);else if(k.enum)for(let L of k.enum)_(L,x);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(k,x){if(typeof k!="string"||k in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[k]=x}}}};oh.default=DF});var rk=$((v7,OF)=>{OF.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 ok=$((Ie,sh)=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.MissingRefError=Ie.ValidationError=Ie.CodeGen=Ie.Name=Ie.nil=Ie.stringify=Ie.str=Ie._=Ie.KeywordCxt=Ie.Ajv=void 0;var zF=Qx(),NF=Y0(),jF=tk(),nk=rk(),MF=["/properties"],el="http://json-schema.org/draft-07/schema",ys=class extends zF.default{_addVocabularies(){super._addVocabularies(),NF.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(jF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(nk,MF):nk;this.addMetaSchema(e,el,!1),this.refs["http://json-schema.org/schema"]=el}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(el)?el:void 0)}};Ie.Ajv=ys;sh.exports=Ie=ys;sh.exports.Ajv=ys;Object.defineProperty(Ie,"__esModule",{value:!0});Ie.default=ys;var LF=ra();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return LF.KeywordCxt}});var vs=te();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return vs._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return vs.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return vs.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return vs.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return vs.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return vs.CodeGen}});var qF=Du();Object.defineProperty(Ie,"ValidationError",{enumerable:!0,get:function(){return qF.default}});var FF=na();Object.defineProperty(Ie,"MissingRefError",{enumerable:!0,get:function(){return FF.default}})});var pk=$(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.formatNames=Sr.fastFormats=Sr.fullFormats=void 0;function $r(t,e){return{validate:t,compare:e}}Sr.fullFormats={date:$r(ck,uh),time:$r(ah(!0),lh),"date-time":$r(sk(!0),lk),"iso-time":$r(ah(),uk),"iso-date-time":$r(sk(),dk),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:HF,"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:eU,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:KF,int32:{type:"number",validate:YF},int64:{type:"number",validate:QF},float:{type:"number",validate:ak},double:{type:"number",validate:ak},password:!0,binary:!0};Sr.fastFormats={...Sr.fullFormats,date:$r(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,uh),time:$r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,lh),"date-time":$r(/^\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,lk),"iso-time":$r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,uk),"iso-date-time":$r(/^\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,dk),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};Sr.formatNames=Object.keys(Sr.fullFormats);function UF(t){return t%4===0&&(t%100!==0||t%400===0)}var ZF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,VF=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ck(t){let e=ZF.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&&UF(r)?29:VF[n])}function uh(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ih=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ah(t){return function(r){let n=ih.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 lh(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 uk(t,e){if(!(t&&e))return;let r=ih.exec(t),n=ih.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 ch=/t|\s/i;function sk(t){let e=ah(t);return function(n){let o=n.split(ch);return o.length===2&&ck(o[0])&&e(o[1])}}function lk(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function dk(t,e){if(!(t&&e))return;let[r,n]=t.split(ch),[o,s]=e.split(ch),i=uh(r,o);if(i!==void 0)return i||lh(n,s)}var BF=/\/|:/,WF=/^(?:[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 HF(t){return BF.test(t)&&WF.test(t)}var ik=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function KF(t){return ik.lastIndex=0,ik.test(t)}var JF=-(2**31),GF=2**31-1;function YF(t){return Number.isInteger(t)&&t<=GF&&t>=JF}function QF(t){return Number.isInteger(t)}function ak(){return!0}var XF=/[^\\]\\Z/;function eU(t){if(XF.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var _a=$(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var ya=class{};he._CodeOrName=ya;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var uo=class extends ya{constructor(e){if(super(),!he.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}}};he.Name=uo;var Wt=class extends ya{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 uo&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=Wt;he.nil=new Wt("");function fk(t,...e){let r=[t[0]],n=0;for(;n<e.length;)ph(r,e[n]),r.push(t[++n]);return new Wt(r)}he._=fk;var dh=new Wt("+");function mk(t,...e){let r=[va(t[0])],n=0;for(;n<e.length;)r.push(dh),ph(r,e[n]),r.push(dh,va(t[++n]));return tU(r),new Wt(r)}he.str=mk;function ph(t,e){e instanceof Wt?t.push(...e._items):e instanceof uo?t.push(e):t.push(oU(e))}he.addCodeArg=ph;function tU(t){let e=1;for(;e<t.length-1;){if(t[e]===dh){let r=rU(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function rU(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof uo||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 uo))return`"${t}${e.slice(1)}`}function nU(t,e){return e.emptyStr()?t:t.emptyStr()?e:mk`${t}${e}`}he.strConcat=nU;function oU(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:va(Array.isArray(t)?t.join(","):t)}function sU(t){return new Wt(va(t))}he.stringify=sU;function va(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=va;function iU(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new Wt(`.${t}`):fk`[${t}]`}he.getProperty=iU;function aU(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new Wt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=aU;function cU(t){return new Wt(t.toString())}he.regexpCode=cU});var hh=$(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.ValueScope=Et.ValueScopeName=Et.Scope=Et.varKinds=Et.UsedValueState=void 0;var Pt=_a(),fh=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},tl;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(tl||(Et.UsedValueState=tl={}));Et.varKinds={const:new Pt.Name("const"),let:new Pt.Name("let"),var:new Pt.Name("var")};var rl=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Pt.Name?e:this.name(e)}name(e){return new Pt.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}}};Et.Scope=rl;var nl=class extends Pt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Pt._)`.${new Pt.Name(r)}[${n}]`}};Et.ValueScopeName=nl;var uU=(0,Pt._)`\n`,mh=class extends rl{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?uU:Pt.nil}}get(){return this._scope}name(e){return new nl(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,Pt._)`${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=Pt.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,tl.Started);let l=r(u);if(l){let d=this.opts.es5?Et.varKinds.var:Et.varKinds.const;s=(0,Pt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,Pt._)`${s}${l}${this.opts._n}`;else throw new fh(u);c.set(u,tl.Completed)})}return s}};Et.ValueScope=mh});var Q=$(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.or=ee.and=ee.not=ee.CodeGen=ee.operators=ee.varKinds=ee.ValueScopeName=ee.ValueScope=ee.Scope=ee.Name=ee.regexpCode=ee.stringify=ee.getProperty=ee.nil=ee.strConcat=ee.str=ee._=void 0;var ue=_a(),or=hh(),hn=_a();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return hn._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return hn.str}});Object.defineProperty(ee,"strConcat",{enumerable:!0,get:function(){return hn.strConcat}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return hn.nil}});Object.defineProperty(ee,"getProperty",{enumerable:!0,get:function(){return hn.getProperty}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return hn.stringify}});Object.defineProperty(ee,"regexpCode",{enumerable:!0,get:function(){return hn.regexpCode}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return hn.Name}});var al=hh();Object.defineProperty(ee,"Scope",{enumerable:!0,get:function(){return al.Scope}});Object.defineProperty(ee,"ValueScope",{enumerable:!0,get:function(){return al.ValueScope}});Object.defineProperty(ee,"ValueScopeName",{enumerable:!0,get:function(){return al.ValueScopeName}});Object.defineProperty(ee,"varKinds",{enumerable:!0,get:function(){return al.varKinds}});ee.operators={GT:new ue._Code(">"),GTE:new ue._Code(">="),LT:new ue._Code("<"),LTE:new ue._Code("<="),EQ:new ue._Code("==="),NEQ:new ue._Code("!=="),NOT:new ue._Code("!"),OR:new ue._Code("||"),AND:new ue._Code("&&"),ADD:new ue._Code("+")};var Zr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},gh=class extends Zr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?or.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=bs(this.rhs,e,r)),this}get names(){return this.rhs instanceof ue._CodeOrName?this.rhs.names:{}}},ol=class extends Zr{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 ue.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=bs(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ue.Name?{}:{...this.lhs.names};return il(e,this.rhs)}},yh=class extends ol{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},vh=class extends Zr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},_h=class extends Zr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},bh=class extends Zr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},wh=class extends Zr{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=bs(this.code,e,r),this}get names(){return this.code instanceof ue._CodeOrName?this.code.names:{}}},ba=class extends Zr{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)||(lU(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>fo(e,r.names),{})}},Vr=class extends ba{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},$h=class extends ba{},_s=class extends Vr{};_s.kind="else";var lo=class t extends Vr{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 _s(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(hk(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=bs(this.condition,e,r),this}get names(){let e=super.names;return il(e,this.condition),this.else&&fo(e,this.else.names),e}};lo.kind="if";var po=class extends Vr{};po.kind="for";var Sh=class extends po{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=bs(this.iteration,e,r),this}get names(){return fo(super.names,this.iteration.names)}},xh=class extends po{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?or.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=il(super.names,this.from);return il(e,this.to)}},sl=class extends po{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=bs(this.iterable,e,r),this}get names(){return fo(super.names,this.iterable.names)}},wa=class extends Vr{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)}};wa.kind="func";var $a=class extends ba{render(e){return"return "+super.render(e)}};$a.kind="return";var kh=class extends Vr{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&&fo(e,this.catch.names),this.finally&&fo(e,this.finally.names),e}},Sa=class extends Vr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Sa.kind="catch";var xa=class extends Vr{render(e){return"finally"+super.render(e)}};xa.kind="finally";var Ph=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
13
|
-
`:""},this._extScope=e,this._scope=new or.Scope({parent:e}),this._nodes=[new $h]}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 gh(e,s,n)),s}const(e,r,n){return this._def(or.varKinds.const,e,r,n)}let(e,r,n){return this._def(or.varKinds.let,e,r,n)}var(e,r,n){return this._def(or.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new ol(e,r,n))}add(e,r){return this._leafNode(new yh(e,ee.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ue.nil&&this._leafNode(new wh(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,ue.addCodeArg)(r,o));return r.push("}"),new ue._Code(r)}if(e,r,n){if(this._blockNode(new lo(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 lo(e))}else(){return this._elseNode(new _s)}endIf(){return this._endBlockNode(lo,_s)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Sh(e),r)}forRange(e,r,n,o,s=this.opts.es5?or.varKinds.var:or.varKinds.let){let i=this._scope.toName(e);return this._for(new xh(s,i,r,n),()=>o(i))}forOf(e,r,n,o=or.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ue.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ue._)`${i}.length`,a=>{this.var(s,(0,ue._)`${i}[${a}]`),n(s)})}return this._for(new sl("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?or.varKinds.var:or.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ue._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new sl("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(po)}label(e){return this._leafNode(new vh(e))}break(e){return this._leafNode(new _h(e))}return(e){let r=new $a;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode($a)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new kh;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Sa(s),r(s)}return n&&(this._currNode=o.finally=new xa,this.code(n)),this._endBlockNode(Sa,xa)}throw(e){return this._leafNode(new bh(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=ue.nil,n,o){return this._blockNode(new wa(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(wa)}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 lo))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}};ee.CodeGen=Ph;function fo(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function il(t,e){return e instanceof ue._CodeOrName?fo(t,e.names):t}function bs(t,e,r){if(t instanceof ue.Name)return n(t);if(!o(t))return t;return new ue._Code(t._items.reduce((s,i)=>(i instanceof ue.Name&&(i=n(i)),i instanceof ue._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 ue._Code&&s._items.some(i=>i instanceof ue.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function lU(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function hk(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ue._)`!${Eh(t)}`}ee.not=hk;var dU=gk(ee.operators.AND);function pU(...t){return t.reduce(dU)}ee.and=pU;var fU=gk(ee.operators.OR);function mU(...t){return t.reduce(fU)}ee.or=mU;function gk(t){return(e,r)=>e===ue.nil?r:r===ue.nil?e:(0,ue._)`${Eh(e)} ${t} ${Eh(r)}`}function Eh(t){return t instanceof ue.Name?t:(0,ue._)`(${t})`}});var pe=$(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.checkStrictMode=ne.getErrorPath=ne.Type=ne.useFunc=ne.setEvaluated=ne.evaluatedPropsToName=ne.mergeEvaluated=ne.eachItem=ne.unescapeJsonPointer=ne.escapeJsonPointer=ne.escapeFragment=ne.unescapeFragment=ne.schemaRefOrVal=ne.schemaHasRulesButRef=ne.schemaHasRules=ne.checkUnknownRules=ne.alwaysValidSchema=ne.toHash=void 0;var $e=Q(),hU=_a();function gU(t){let e={};for(let r of t)e[r]=!0;return e}ne.toHash=gU;function yU(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(_k(t,e),!bk(e,t.self.RULES.all))}ne.alwaysValidSchema=yU;function _k(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]||Sk(t,`unknown keyword: "${s}"`)}ne.checkUnknownRules=_k;function bk(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ne.schemaHasRules=bk;function vU(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ne.schemaHasRulesButRef=vU;function _U({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,$e._)`${r}`}return(0,$e._)`${t}${e}${(0,$e.getProperty)(n)}`}ne.schemaRefOrVal=_U;function bU(t){return wk(decodeURIComponent(t))}ne.unescapeFragment=bU;function wU(t){return encodeURIComponent(Rh(t))}ne.escapeFragment=wU;function Rh(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ne.escapeJsonPointer=Rh;function wk(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ne.unescapeJsonPointer=wk;function $U(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ne.eachItem=$U;function yk({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof $e.Name?(s instanceof $e.Name?t(o,s,i):e(o,s,i),i):s instanceof $e.Name?(e(o,i,s),s):r(s,i);return a===$e.Name&&!(c instanceof $e.Name)?n(o,c):c}}ne.mergeEvaluated={props:yk({mergeNames:(t,e,r)=>t.if((0,$e._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,$e._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,$e._)`${r} || {}`).code((0,$e._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,$e._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,$e._)`${r} || {}`),Ih(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:$k}),items:yk({mergeNames:(t,e,r)=>t.if((0,$e._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,$e._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,$e._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,$e._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function $k(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,$e._)`{}`);return e!==void 0&&Ih(t,r,e),r}ne.evaluatedPropsToName=$k;function Ih(t,e,r){Object.keys(r).forEach(n=>t.assign((0,$e._)`${e}${(0,$e.getProperty)(n)}`,!0))}ne.setEvaluated=Ih;var vk={};function SU(t,e){return t.scopeValue("func",{ref:e,code:vk[e.code]||(vk[e.code]=new hU._Code(e.code))})}ne.useFunc=SU;var Th;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Th||(ne.Type=Th={}));function xU(t,e,r){if(t instanceof $e.Name){let n=e===Th.Num;return r?n?(0,$e._)`"[" + ${t} + "]"`:(0,$e._)`"['" + ${t} + "']"`:n?(0,$e._)`"/" + ${t}`:(0,$e._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,$e.getProperty)(t).toString():"/"+Rh(t)}ne.getErrorPath=xU;function Sk(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ne.checkStrictMode=Sk});var Br=$(Ah=>{"use strict";Object.defineProperty(Ah,"__esModule",{value:!0});var at=Q(),kU={data:new at.Name("data"),valCxt:new at.Name("valCxt"),instancePath:new at.Name("instancePath"),parentData:new at.Name("parentData"),parentDataProperty:new at.Name("parentDataProperty"),rootData:new at.Name("rootData"),dynamicAnchors:new at.Name("dynamicAnchors"),vErrors:new at.Name("vErrors"),errors:new at.Name("errors"),this:new at.Name("this"),self:new at.Name("self"),scope:new at.Name("scope"),json:new at.Name("json"),jsonPos:new at.Name("jsonPos"),jsonLen:new at.Name("jsonLen"),jsonPart:new at.Name("jsonPart")};Ah.default=kU});var ka=$(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.extendErrors=ct.resetErrorsCount=ct.reportExtraError=ct.reportError=ct.keyword$DataError=ct.keywordError=void 0;var fe=Q(),cl=pe(),gt=Br();ct.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};ct.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,fe.str)`"${t}" keyword must be ${e} ($data)`:(0,fe.str)`"${t}" keyword is invalid ($data)`};function PU(t,e=ct.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Pk(t,e,r);n??(i||a)?xk(s,c):kk(o,(0,fe._)`[${c}]`)}ct.reportError=PU;function EU(t,e=ct.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Pk(t,e,r);xk(o,a),s||i||kk(n,gt.default.vErrors)}ct.reportExtraError=EU;function TU(t,e){t.assign(gt.default.errors,e),t.if((0,fe._)`${gt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${gt.default.vErrors}.length`,e),()=>t.assign(gt.default.vErrors,null)))}ct.resetErrorsCount=TU;function RU({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,gt.default.errors,a=>{t.const(i,(0,fe._)`${gt.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)(gt.default.instancePath,s.errorPath))),t.assign((0,fe._)`${i}.schemaPath`,(0,fe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,fe._)`${i}.schema`,r),t.assign((0,fe._)`${i}.data`,n))})}ct.extendErrors=RU;function xk(t,e){let r=t.const("err",e);t.if((0,fe._)`${gt.default.vErrors} === null`,()=>t.assign(gt.default.vErrors,(0,fe._)`[${r}]`),(0,fe._)`${gt.default.vErrors}.push(${r})`),t.code((0,fe._)`${gt.default.errors}++`)}function kk(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,fe._)`new ${t.ValidationError}(${e})`):(r.assign((0,fe._)`${n}.errors`,e),r.return(!1))}var mo={keyword:new fe.Name("keyword"),schemaPath:new fe.Name("schemaPath"),params:new fe.Name("params"),propertyName:new fe.Name("propertyName"),message:new fe.Name("message"),schema:new fe.Name("schema"),parentSchema:new fe.Name("parentSchema")};function Pk(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,fe._)`{}`:IU(t,e,r)}function IU(t,e,r={}){let{gen:n,it:o}=t,s=[AU(o,r),CU(t,r)];return DU(t,e,s),n.object(...s)}function AU({errorPath:t},{instancePath:e}){let r=e?(0,fe.str)`${t}${(0,cl.getErrorPath)(e,cl.Type.Str)}`:t;return[gt.default.instancePath,(0,fe.strConcat)(gt.default.instancePath,r)]}function CU({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,fe.str)`${e}/${t}`;return r&&(o=(0,fe.str)`${o}${(0,cl.getErrorPath)(r,cl.Type.Str)}`),[mo.schemaPath,o]}function DU(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([mo.keyword,o],[mo.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&n.push([mo.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([mo.schema,i],[mo.parentSchema,(0,fe._)`${l}${d}`],[gt.default.data,s]),u&&n.push([mo.propertyName,u])}});var Tk=$(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});ws.boolOrEmptySchema=ws.topBoolOrEmptySchema=void 0;var OU=ka(),zU=Q(),NU=Br(),jU={message:"boolean schema is false"};function MU(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Ek(t,!1):typeof r=="object"&&r.$async===!0?e.return(NU.default.data):(e.assign((0,zU._)`${n}.errors`,null),e.return(!0))}ws.topBoolOrEmptySchema=MU;function LU(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Ek(t)):r.var(e,!0)}ws.boolOrEmptySchema=LU;function Ek(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,OU.reportError)(o,jU,void 0,e)}});var Ch=$($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.getRules=$s.isJSONType=void 0;var qU=["string","number","integer","boolean","null","object","array"],FU=new Set(qU);function UU(t){return typeof t=="string"&&FU.has(t)}$s.isJSONType=UU;function ZU(){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:{}}}$s.getRules=ZU});var Dh=$(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.shouldUseRule=gn.shouldUseGroup=gn.schemaHasRulesForType=void 0;function VU({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Rk(t,n)}gn.schemaHasRulesForType=VU;function Rk(t,e){return e.rules.some(r=>Ik(t,r))}gn.shouldUseGroup=Rk;function Ik(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))}gn.shouldUseRule=Ik});var Pa=$(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.reportTypeError=ut.checkDataTypes=ut.checkDataType=ut.coerceAndCheckDataType=ut.getJSONTypes=ut.getSchemaTypes=ut.DataType=void 0;var BU=Ch(),WU=Dh(),HU=ka(),J=Q(),Ak=pe(),Ss;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Ss||(ut.DataType=Ss={}));function KU(t){let e=Ck(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}ut.getSchemaTypes=KU;function Ck(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(BU.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ut.getJSONTypes=Ck;function JU(t,e){let{gen:r,data:n,opts:o}=t,s=GU(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,WU.schemaHasRulesForType)(t,e[0]));if(i){let a=zh(e,n,o.strictNumbers,Ss.Wrong);r.if(a,()=>{s.length?YU(t,e,s):Nh(t)})}return i}ut.coerceAndCheckDataType=JU;var Dk=new Set(["string","number","integer","boolean","null"]);function GU(t,e){return e?t.filter(r=>Dk.has(r)||e==="array"&&r==="array"):[]}function YU(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,J._)`typeof ${o}`),a=n.let("coerced",(0,J._)`undefined`);s.coerceTypes==="array"&&n.if((0,J._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,J._)`${o}[0]`).assign(i,(0,J._)`typeof ${o}`).if(zh(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,J._)`${a} !== undefined`);for(let u of r)(Dk.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Nh(t),n.endIf(),n.if((0,J._)`${a} !== undefined`,()=>{n.assign(o,a),QU(t,a)});function c(u){switch(u){case"string":n.elseIf((0,J._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,J._)`"" + ${o}`).elseIf((0,J._)`${o} === null`).assign(a,(0,J._)`""`);return;case"number":n.elseIf((0,J._)`${i} == "boolean" || ${o} === null
|
|
14
|
-
|| (${i} == "string" && ${
|
|
15
|
-
|| (${i} === "string" && ${
|
|
16
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,J._)`[${o}]`)}}}function QU({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,J._)`${e} !== undefined`,()=>t.assign((0,J._)`${e}[${r}]`,n))}function Oh(t,e,r,n=Ss.Correct){let o=n===Ss.Correct?J.operators.EQ:J.operators.NEQ,s;switch(t){case"null":return(0,J._)`${e} ${o} null`;case"array":s=(0,J._)`Array.isArray(${e})`;break;case"object":s=(0,J._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,J._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,J._)`typeof ${e} ${o} ${t}`}return n===Ss.Correct?s:(0,J.not)(s);function i(a=J.nil){return(0,J.and)((0,J._)`typeof ${e} == "number"`,a,r?(0,J._)`isFinite(${e})`:J.nil)}}ut.checkDataType=Oh;function zh(t,e,r,n){if(t.length===1)return Oh(t[0],e,r,n);let o,s=(0,Ak.toHash)(t);if(s.array&&s.object){let i=(0,J._)`typeof ${e} != "object"`;o=s.null?i:(0,J._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=J.nil;s.number&&delete s.integer;for(let i in s)o=(0,J.and)(o,Oh(i,e,r,n));return o}ut.checkDataTypes=zh;var XU={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,J._)`{type: ${t}}`:(0,J._)`{type: ${e}}`};function Nh(t){let e=eZ(t);(0,HU.reportError)(e,XU)}ut.reportTypeError=Nh;function eZ(t){let{gen:e,data:r,schema:n}=t,o=(0,Ak.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var zk=$(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.assignDefaults=void 0;var xs=Q(),tZ=pe();function rZ(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Ok(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Ok(t,s,o.default))}ul.assignDefaults=rZ;function Ok(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,xs._)`${s}${(0,xs.getProperty)(e)}`;if(o){(0,tZ.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,xs._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,xs._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,xs._)`${a} = ${(0,xs.stringify)(r)}`)}});var Ht=$(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.validateUnion=be.validateArray=be.usePattern=be.callValidateCode=be.schemaProperties=be.allSchemaProperties=be.noPropertyInData=be.propertyInData=be.isOwnProperty=be.hasPropFunc=be.reportMissingProp=be.checkMissingProp=be.checkReportMissingProp=void 0;var Ae=Q(),jh=pe(),yn=Br(),nZ=pe();function oZ(t,e){let{gen:r,data:n,it:o}=t;r.if(Lh(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ae._)`${e}`},!0),t.error()})}be.checkReportMissingProp=oZ;function sZ({gen:t,data:e,it:{opts:r}},n,o){return(0,Ae.or)(...n.map(s=>(0,Ae.and)(Lh(t,e,s,r.ownProperties),(0,Ae._)`${o} = ${s}`)))}be.checkMissingProp=sZ;function iZ(t,e){t.setParams({missingProperty:e},!0),t.error()}be.reportMissingProp=iZ;function Nk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ae._)`Object.prototype.hasOwnProperty`})}be.hasPropFunc=Nk;function Mh(t,e,r){return(0,Ae._)`${Nk(t)}.call(${e}, ${r})`}be.isOwnProperty=Mh;function aZ(t,e,r,n){let o=(0,Ae._)`${e}${(0,Ae.getProperty)(r)} !== undefined`;return n?(0,Ae._)`${o} && ${Mh(t,e,r)}`:o}be.propertyInData=aZ;function Lh(t,e,r,n){let o=(0,Ae._)`${e}${(0,Ae.getProperty)(r)} === undefined`;return n?(0,Ae.or)(o,(0,Ae.not)(Mh(t,e,r))):o}be.noPropertyInData=Lh;function jk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}be.allSchemaProperties=jk;function cZ(t,e){return jk(e).filter(r=>!(0,jh.alwaysValidSchema)(t,e[r]))}be.schemaProperties=cZ;function uZ({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Ae._)`${t}, ${e}, ${n}${o}`:e,d=[[yn.default.instancePath,(0,Ae.strConcat)(yn.default.instancePath,s)],[yn.default.parentData,i.parentData],[yn.default.parentDataProperty,i.parentDataProperty],[yn.default.rootData,yn.default.rootData]];i.opts.dynamicRef&&d.push([yn.default.dynamicAnchors,yn.default.dynamicAnchors]);let p=(0,Ae._)`${l}, ${r.object(...d)}`;return c!==Ae.nil?(0,Ae._)`${a}.call(${c}, ${p})`:(0,Ae._)`${a}(${p})`}be.callValidateCode=uZ;var lZ=(0,Ae._)`new RegExp`;function dZ({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,Ae._)`${o.code==="new RegExp"?lZ:(0,nZ.useFunc)(t,o)}(${r}, ${n})`})}be.usePattern=dZ;function pZ(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,Ae._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:jh.Type.Num},s),e.if((0,Ae.not)(s),a)})}}be.validateArray=pZ;function fZ(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,jh.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,Ae._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ae.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}be.validateUnion=fZ});var qk=$(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.validateKeywordUsage=xr.validSchemaType=xr.funcKeywordCode=xr.macroKeywordCode=void 0;var yt=Q(),ho=Br(),mZ=Ht(),hZ=ka();function gZ(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Lk(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:yt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}xr.macroKeywordCode=gZ;function yZ(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;_Z(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Lk(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)h(),e.modifying&&Mk(t),y(()=>t.error());else{let v=e.async?f():m();e.modifying&&Mk(t),y(()=>vZ(t,v))}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>h((0,yt._)`await `),b=>n.assign(d,!1).if((0,yt._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,yt._)`${b}.errors`),()=>n.throw(b))),v}function m(){let v=(0,yt._)`${l}.errors`;return n.assign(v,null),h(yt.nil),v}function h(v=e.async?(0,yt._)`await `:yt.nil){let b=c.opts.passContext?ho.default.this:ho.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,yt._)`${v}${(0,mZ.callValidateCode)(t,l,b,_)}`,e.modifying)}function y(v){var b;n.if((0,yt.not)((b=e.valid)!==null&&b!==void 0?b:d),v)}}xr.funcKeywordCode=yZ;function Mk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,yt._)`${n.parentData}[${n.parentDataProperty}]`))}function vZ(t,e){let{gen:r}=t;r.if((0,yt._)`Array.isArray(${e})`,()=>{r.assign(ho.default.vErrors,(0,yt._)`${ho.default.vErrors} === null ? ${e} : ${ho.default.vErrors}.concat(${e})`).assign(ho.default.errors,(0,yt._)`${ho.default.vErrors}.length`),(0,hZ.extendErrors)(t)},()=>t.error())}function _Z({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Lk(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,yt.stringify)(r)})}function bZ(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")}xr.validSchemaType=bZ;function wZ({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)}}xr.validateKeywordUsage=wZ});var Uk=$(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.extendSubschemaMode=vn.extendSubschemaData=vn.getSubschema=void 0;var kr=Q(),Fk=pe();function $Z(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,kr._)`${t.schemaPath}${(0,kr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,kr._)`${t.schemaPath}${(0,kr.getProperty)(e)}${(0,kr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Fk.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')}vn.getSubschema=$Z;function SZ(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,kr._)`${e.data}${(0,kr.getProperty)(r)}`,!0);c(p),t.errorPath=(0,kr.str)`${u}${(0,Fk.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,kr._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof kr.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]}}vn.extendSubschemaData=SZ;function xZ(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}vn.extendSubschemaMode=xZ});var Vk=$((O7,Zk)=>{"use strict";var _n=Zk.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(){};ll(e,n,o,t,"",t)};_n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};_n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};_n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};_n.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 ll(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 _n.arrayKeywords)for(var p=0;p<d.length;p++)ll(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in _n.propsKeywords){if(d&&typeof d=="object")for(var f in d)ll(t,e,r,d[f],o+"/"+l+"/"+kZ(f),s,o,l,n,f)}else(l in _n.keywords||t.allKeys&&!(l in _n.skipKeywords))&&ll(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function kZ(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ea=$(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getSchemaRefs=Tt.resolveUrl=Tt.normalizeId=Tt._getFullPath=Tt.getFullPath=Tt.inlineRef=void 0;var PZ=pe(),EZ=Qi(),TZ=Vk(),RZ=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function IZ(t,e=!0){return typeof t=="boolean"?!0:e===!0?!qh(t):e?Bk(t)<=e:!1}Tt.inlineRef=IZ;var AZ=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function qh(t){for(let e in t){if(AZ.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(qh)||typeof r=="object"&&qh(r))return!0}return!1}function Bk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!RZ.has(r)&&(typeof t[r]=="object"&&(0,PZ.eachItem)(t[r],n=>e+=Bk(n)),e===1/0))return 1/0}return e}function Wk(t,e="",r){r!==!1&&(e=ks(e));let n=t.parse(e);return Hk(t,n)}Tt.getFullPath=Wk;function Hk(t,e){return t.serialize(e).split("#")[0]+"#"}Tt._getFullPath=Hk;var CZ=/#\/?$/;function ks(t){return t?t.replace(CZ,""):""}Tt.normalizeId=ks;function DZ(t,e,r){return r=ks(r),t.resolve(e,r)}Tt.resolveUrl=DZ;var OZ=/^[a-z_][-a-z0-9._]*$/i;function zZ(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=ks(t[r]||e),s={"":o},i=Wk(n,o,!1),a={},c=new Set;return TZ(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=i+p,y=s[m];typeof d[r]=="string"&&(y=v.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),s[p]=y;function v(_){let k=this.opts.uriResolver.resolve;if(_=ks(y?k(y,_):_),c.has(_))throw l(_);c.add(_);let x=this.refs[_];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?u(d,x.schema,_):_!==ks(h)&&(_[0]==="#"?(u(d,a[_],_),a[_]=d):this.refs[_]=h),_}function b(_){if(typeof _=="string"){if(!OZ.test(_))throw new Error(`invalid anchor "${_}"`);v.call(this,`#${_}`)}}}),a;function u(d,p,f){if(p!==void 0&&!EZ(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Tt.getSchemaRefs=zZ});var Ia=$(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.getData=bn.KeywordCxt=bn.validateFunctionCode=void 0;var Qk=Tk(),Kk=Pa(),Uh=Dh(),dl=Pa(),NZ=zk(),Ra=qk(),Fh=Uk(),z=Q(),B=Br(),jZ=Ea(),Wr=pe(),Ta=ka();function MZ(t){if(tP(t)&&(rP(t),eP(t))){FZ(t);return}Xk(t,()=>(0,Qk.topBoolOrEmptySchema)(t))}bn.validateFunctionCode=MZ;function Xk({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,z._)`${B.default.data}, ${B.default.valCxt}`,n.$async,()=>{t.code((0,z._)`"use strict"; ${Jk(r,o)}`),qZ(t,o),t.code(s)}):t.func(e,(0,z._)`${B.default.data}, ${LZ(o)}`,n.$async,()=>t.code(Jk(r,o)).code(s))}function LZ(t){return(0,z._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${t.dynamicRef?(0,z._)`, ${B.default.dynamicAnchors}={}`:z.nil}}={}`}function qZ(t,e){t.if(B.default.valCxt,()=>{t.var(B.default.instancePath,(0,z._)`${B.default.valCxt}.${B.default.instancePath}`),t.var(B.default.parentData,(0,z._)`${B.default.valCxt}.${B.default.parentData}`),t.var(B.default.parentDataProperty,(0,z._)`${B.default.valCxt}.${B.default.parentDataProperty}`),t.var(B.default.rootData,(0,z._)`${B.default.valCxt}.${B.default.rootData}`),e.dynamicRef&&t.var(B.default.dynamicAnchors,(0,z._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{t.var(B.default.instancePath,(0,z._)`""`),t.var(B.default.parentData,(0,z._)`undefined`),t.var(B.default.parentDataProperty,(0,z._)`undefined`),t.var(B.default.rootData,B.default.data),e.dynamicRef&&t.var(B.default.dynamicAnchors,(0,z._)`{}`)})}function FZ(t){let{schema:e,opts:r,gen:n}=t;Xk(t,()=>{r.$comment&&e.$comment&&oP(t),WZ(t),n.let(B.default.vErrors,null),n.let(B.default.errors,0),r.unevaluated&&UZ(t),nP(t),JZ(t)})}function UZ(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,z._)`${r}.evaluated`),e.if((0,z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,z._)`${t.evaluated}.props`,(0,z._)`undefined`)),e.if((0,z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,z._)`${t.evaluated}.items`,(0,z._)`undefined`))}function Jk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,z._)`/*# sourceURL=${r} */`:z.nil}function ZZ(t,e){if(tP(t)&&(rP(t),eP(t))){VZ(t,e);return}(0,Qk.boolOrEmptySchema)(t,e)}function eP({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 tP(t){return typeof t.schema!="boolean"}function VZ(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&oP(t),HZ(t),KZ(t);let s=n.const("_errs",B.default.errors);nP(t,s),n.var(e,(0,z._)`${s} === ${B.default.errors}`)}function rP(t){(0,Wr.checkUnknownRules)(t),BZ(t)}function nP(t,e){if(t.opts.jtd)return Gk(t,[],!1,e);let r=(0,Kk.getSchemaTypes)(t.schema),n=(0,Kk.coerceAndCheckDataType)(t,r);Gk(t,r,!n,e)}function BZ(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Wr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function WZ(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Wr.checkStrictMode)(t,"default is ignored in the schema root")}function HZ(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,jZ.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function KZ(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function oP({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,z._)`${B.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,z.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,z._)`${B.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function JZ(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,z._)`${B.default.errors} === 0`,()=>e.return(B.default.data),()=>e.throw((0,z._)`new ${o}(${B.default.vErrors})`)):(e.assign((0,z._)`${n}.errors`,B.default.vErrors),s.unevaluated&&GZ(t),e.return((0,z._)`${B.default.errors} === 0`))}function GZ({gen:t,evaluated:e,props:r,items:n}){r instanceof z.Name&&t.assign((0,z._)`${e}.props`,r),n instanceof z.Name&&t.assign((0,z._)`${e}.items`,n)}function Gk(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,Wr.schemaHasRulesButRef)(s,l))){o.block(()=>iP(t,"$ref",l.all.$ref.definition));return}c.jtd||YZ(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Uh.shouldUseGroup)(s,p)&&(p.type?(o.if((0,dl.checkDataType)(p.type,i,c.strictNumbers)),Yk(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,dl.reportTypeError)(t)),o.endIf()):Yk(t,p),a||o.if((0,z._)`${B.default.errors} === ${n||0}`))}}function Yk(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,NZ.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Uh.shouldUseRule)(n,s)&&iP(t,s.keyword,s.definition,e.type)})}function YZ(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(QZ(t,e),t.opts.allowUnionTypes||XZ(t,e),eV(t,t.dataTypes))}function QZ(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{sP(t.dataTypes,r)||Zh(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),rV(t,e)}}function XZ(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Zh(t,"use allowUnionTypes to allow union type keyword")}function eV(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Uh.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>tV(e,i))&&Zh(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function tV(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function sP(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function rV(t,e){let r=[];for(let n of t.dataTypes)sP(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Zh(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Wr.checkStrictMode)(t,e,t.opts.strictTypes)}var pl=class{constructor(e,r,n){if((0,Ra.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,Wr.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",aP(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ra.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",B.default.errors))}result(e,r,n){this.failResult((0,z.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,z.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,z._)`${r} !== undefined && (${(0,z.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?Ta.reportExtraError:Ta.reportError)(this,this.def.error,r)}$dataError(){(0,Ta.reportError)(this,this.def.$dataError||Ta.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ta.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=z.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=z.nil,r=z.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,z.or)((0,z._)`${o} === undefined`,r)),e!==z.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==z.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,z.or)(i(),a());function i(){if(n.length){if(!(r instanceof z.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,z._)`${(0,dl.checkDataTypes)(c,r,s.opts.strictNumbers,dl.DataType.Wrong)}`}return z.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,z._)`!${c}(${r})`}return z.nil}}subschema(e,r){let n=(0,Fh.getSubschema)(this.it,e);(0,Fh.extendSubschemaData)(n,this.it,e),(0,Fh.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return ZZ(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Wr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Wr.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,z.Name)),!0}};bn.KeywordCxt=pl;function iP(t,e,r,n){let o=new pl(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ra.funcKeywordCode)(o,r):"macro"in r?(0,Ra.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ra.funcKeywordCode)(o,r)}var nV=/^\/(?:[^~]|~0|~1)*$/,oV=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function aP(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return B.default.rootData;if(t[0]==="/"){if(!nV.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=B.default.rootData}else{let u=oV.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,z._)`${s}${(0,z.getProperty)((0,Wr.unescapeJsonPointer)(u))}`,i=(0,z._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}bn.getData=aP});var fl=$(Bh=>{"use strict";Object.defineProperty(Bh,"__esModule",{value:!0});var Vh=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Bh.default=Vh});var Aa=$(Kh=>{"use strict";Object.defineProperty(Kh,"__esModule",{value:!0});var Wh=Ea(),Hh=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Wh.resolveUrl)(e,r,n),this.missingSchema=(0,Wh.normalizeId)((0,Wh.getFullPath)(e,this.missingRef))}};Kh.default=Hh});var hl=$(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.resolveSchema=Kt.getCompilingSchema=Kt.resolveRef=Kt.compileSchema=Kt.SchemaEnv=void 0;var sr=Q(),sV=fl(),go=Br(),ir=Ea(),cP=pe(),iV=Ia(),Ps=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,ir.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Kt.SchemaEnv=Ps;function Gh(t){let e=uP.call(this,t);if(e)return e;let r=(0,ir.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new sr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:sV.default,code:(0,sr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:go.default.data,parentData:go.default.parentData,parentDataProperty:go.default.parentDataProperty,dataNames:[go.default.data],dataPathArr:[sr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,sr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:sr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,sr._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,iV.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(go.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${go.default.self}`,`${go.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:h}=u;f.evaluated={props:m instanceof sr.Name?void 0:m,items:h instanceof sr.Name?void 0:h,dynamicProps:m instanceof sr.Name,dynamicItems:h instanceof sr.Name},f.source&&(f.source.evaluated=(0,sr.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)}}Kt.compileSchema=Gh;function aV(t,e,r){var n;r=(0,ir.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=lV.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 Ps({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=cV.call(this,s)}Kt.resolveRef=aV;function cV(t){return(0,ir.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Gh.call(this,t)}function uP(t){for(let e of this._compilations)if(uV(e,t))return e}Kt.getCompilingSchema=uP;function uV(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function lV(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ml.call(this,t,e)}function ml(t,e){let r=this.opts.uriResolver.parse(e),n=(0,ir._getFullPath)(this.opts.uriResolver,r),o=(0,ir.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Jh.call(this,r,t);let s=(0,ir.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ml.call(this,t,i);return typeof a?.schema!="object"?void 0:Jh.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Gh.call(this,i),s===(0,ir.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,ir.resolveUrl)(this.opts.uriResolver,o,u)),new Ps({schema:a,schemaId:c,root:t,baseId:o})}return Jh.call(this,r,i)}}Kt.resolveSchema=ml;var dV=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Jh(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,cP.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!dV.has(a)&&u&&(e=(0,ir.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,cP.schemaHasRulesButRef)(r,this.RULES)){let a=(0,ir.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ml.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Ps({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var lP=$((q7,pV)=>{pV.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 pP=$(Yh=>{"use strict";Object.defineProperty(Yh,"__esModule",{value:!0});var dP=fm();dP.code='require("ajv/dist/runtime/uri").default';Yh.default=dP});var bP=$(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.CodeGen=Xe.Name=Xe.nil=Xe.stringify=Xe.str=Xe._=Xe.KeywordCxt=void 0;var fV=Ia();Object.defineProperty(Xe,"KeywordCxt",{enumerable:!0,get:function(){return fV.KeywordCxt}});var Es=Q();Object.defineProperty(Xe,"_",{enumerable:!0,get:function(){return Es._}});Object.defineProperty(Xe,"str",{enumerable:!0,get:function(){return Es.str}});Object.defineProperty(Xe,"stringify",{enumerable:!0,get:function(){return Es.stringify}});Object.defineProperty(Xe,"nil",{enumerable:!0,get:function(){return Es.nil}});Object.defineProperty(Xe,"Name",{enumerable:!0,get:function(){return Es.Name}});Object.defineProperty(Xe,"CodeGen",{enumerable:!0,get:function(){return Es.CodeGen}});var mV=fl(),yP=Aa(),hV=Ch(),Ca=hl(),gV=Q(),Da=Ea(),gl=Pa(),Xh=pe(),fP=lP(),yV=pP(),vP=(t,e)=>new RegExp(t,e);vP.code="new RegExp";var vV=["removeAdditional","useDefaults","coerceTypes"],_V=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),bV={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."},wV={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},mP=200;function $V(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,h,y,v,b,_,k,x,L,P,M,q;let j=t.strict,De=(e=t.code)===null||e===void 0?void 0:e.optimize,Le=De===!0||De===void 0?1:De||0,It=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:vP,Kr=(o=t.uriResolver)!==null&&o!==void 0?o:yV.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:j)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:j)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:j)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:j)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:j)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:Le,regExp:It}:{optimize:Le,regExp:It},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:mP,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:mP,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(x=t.addUsedSchema)!==null&&x!==void 0?x:!0,validateSchema:(L=t.validateSchema)!==null&&L!==void 0?L:!0,validateFormats:(P=t.validateFormats)!==null&&P!==void 0?P:!0,unicodeRegExp:(M=t.unicodeRegExp)!==null&&M!==void 0?M:!0,int32range:(q=t.int32range)!==null&&q!==void 0?q:!0,uriResolver:Kr}}var Oa=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...$V(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new gV.ValueScope({scope:{},prefixes:_V,es5:r,lines:n}),this.logger=TV(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,hV.getRules)(),hP.call(this,bV,e,"NOT SUPPORTED"),hP.call(this,wV,e,"DEPRECATED","warn"),this._metaOpts=PV.call(this),e.formats&&xV.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&kV.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),SV.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=fP;n==="id"&&(o={...fP},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 yP.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,Da.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=gP.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Ca.SchemaEnv({schema:{},schemaId:n});if(r=Ca.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=gP.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,Da.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(IV.call(this,n,r),!r)return(0,Xh.eachItem)(n,s=>Qh.call(this,s)),this;CV.call(this,r);let o={...r,type:(0,gl.getJSONTypes)(r.type),schemaType:(0,gl.getJSONTypes)(r.schemaType)};return(0,Xh.eachItem)(n,o.type.length===0?s=>Qh.call(this,s,o):s=>o.type.forEach(i=>Qh.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]=_P(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,Da.normalizeId)(i||n);let u=Da.getSchemaRefs.call(this,e,n);return c=new Ca.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):Ca.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{Ca.compileSchema.call(this,e)}finally{this.opts=r}}};Oa.ValidationError=mV.default;Oa.MissingRefError=yP.default;Xe.default=Oa;function hP(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 gP(t){return t=(0,Da.normalizeId)(t),this.schemas[t]||this.refs[t]}function SV(){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 xV(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function kV(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 PV(){let t={...this.opts};for(let e of vV)delete t[e];return t}var EV={log(){},warn(){},error(){}};function TV(t){if(t===!1)return EV;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 RV=/^[a-z_$][a-z0-9_$:-]*$/i;function IV(t,e){let{RULES:r}=this;if((0,Xh.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!RV.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 Qh(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,gl.getJSONTypes)(e.type),schemaType:(0,gl.getJSONTypes)(e.schemaType)}};e.before?AV.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 AV(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 CV(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=_P(e)),t.validateSchema=this.compile(e,!0))}var DV={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function _P(t){return{anyOf:[t,DV]}}});var wP=$(eg=>{"use strict";Object.defineProperty(eg,"__esModule",{value:!0});var OV={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};eg.default=OV});var kP=$(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.callRef=yo.getValidate=void 0;var zV=Aa(),$P=Ht(),Rt=Q(),Ts=Br(),SP=hl(),yl=pe(),NV={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=SP.resolveRef.call(c,u,o,r);if(l===void 0)throw new zV.default(n.opts.uriResolver,o,r);if(l instanceof SP.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return vl(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return vl(t,(0,Rt._)`${m}.validate`,u,u.$async)}function p(m){let h=xP(t,m);vl(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Rt.stringify)(m)}:{ref:m}),y=e.name("valid"),v=t.subschema({schema:m,dataTypes:[],schemaPath:Rt.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(v),t.ok(y)}}};function xP(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Rt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}yo.getValidate=xP;function vl(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Ts.default.this:Rt.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,Rt._)`await ${(0,$P.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},h=>{o.if((0,Rt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),p(h),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,$P.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,Rt._)`${m}.errors`;o.assign(Ts.default.vErrors,(0,Rt._)`${Ts.default.vErrors} === null ? ${h} : ${Ts.default.vErrors}.concat(${h})`),o.assign(Ts.default.errors,(0,Rt._)`${Ts.default.vErrors}.length`)}function f(m){var h;if(!s.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=yl.mergeEvaluated.props(o,y.props,s.props));else{let v=o.var("props",(0,Rt._)`${m}.evaluated.props`);s.props=yl.mergeEvaluated.props(o,v,s.props,Rt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=yl.mergeEvaluated.items(o,y.items,s.items));else{let v=o.var("items",(0,Rt._)`${m}.evaluated.items`);s.items=yl.mergeEvaluated.items(o,v,s.items,Rt.Name)}}}yo.callRef=vl;yo.default=NV});var PP=$(tg=>{"use strict";Object.defineProperty(tg,"__esModule",{value:!0});var jV=wP(),MV=kP(),LV=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",jV.default,MV.default];tg.default=LV});var EP=$(rg=>{"use strict";Object.defineProperty(rg,"__esModule",{value:!0});var _l=Q(),wn=_l.operators,bl={maximum:{okStr:"<=",ok:wn.LTE,fail:wn.GT},minimum:{okStr:">=",ok:wn.GTE,fail:wn.LT},exclusiveMaximum:{okStr:"<",ok:wn.LT,fail:wn.GTE},exclusiveMinimum:{okStr:">",ok:wn.GT,fail:wn.LTE}},qV={message:({keyword:t,schemaCode:e})=>(0,_l.str)`must be ${bl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,_l._)`{comparison: ${bl[t].okStr}, limit: ${e}}`},FV={keyword:Object.keys(bl),type:"number",schemaType:"number",$data:!0,error:qV,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,_l._)`${r} ${bl[e].fail} ${n} || isNaN(${r})`)}};rg.default=FV});var TP=$(ng=>{"use strict";Object.defineProperty(ng,"__esModule",{value:!0});var za=Q(),UV={message:({schemaCode:t})=>(0,za.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,za._)`{multipleOf: ${t}}`},ZV={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:UV,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,za._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,za._)`${i} !== parseInt(${i})`;t.fail$data((0,za._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};ng.default=ZV});var IP=$(og=>{"use strict";Object.defineProperty(og,"__esModule",{value:!0});function RP(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}og.default=RP;RP.code='require("ajv/dist/runtime/ucs2length").default'});var AP=$(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});var vo=Q(),VV=pe(),BV=IP(),WV={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,vo.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,vo._)`{limit: ${t}}`},HV={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:WV,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?vo.operators.GT:vo.operators.LT,i=o.opts.unicode===!1?(0,vo._)`${r}.length`:(0,vo._)`${(0,VV.useFunc)(t.gen,BV.default)}(${r})`;t.fail$data((0,vo._)`${i} ${s} ${n}`)}};sg.default=HV});var CP=$(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});var KV=Ht(),JV=pe(),Rs=Q(),GV={message:({schemaCode:t})=>(0,Rs.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Rs._)`{pattern: ${t}}`},YV={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:GV,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Rs._)`new RegExp`:(0,JV.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Rs._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Rs._)`!${l}`)}else{let c=(0,KV.usePattern)(t,o);t.fail$data((0,Rs._)`!${c}.test(${r})`)}}};ig.default=YV});var DP=$(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});var Na=Q(),QV={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Na.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Na._)`{limit: ${t}}`},XV={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:QV,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Na.operators.GT:Na.operators.LT;t.fail$data((0,Na._)`Object.keys(${r}).length ${o} ${n}`)}};ag.default=XV});var OP=$(cg=>{"use strict";Object.defineProperty(cg,"__esModule",{value:!0});var ja=Ht(),Ma=Q(),e9=pe(),t9={message:({params:{missingProperty:t}})=>(0,Ma.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ma._)`{missingProperty: ${t}}`},r9={keyword:"required",type:"object",schemaType:"array",$data:!0,error:t9,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 h of r)if(f?.[h]===void 0&&!m.has(h)){let y=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,e9.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Ma.nil,d);else for(let f of r)(0,ja.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,ja.checkMissingProp)(t,r,f)),(0,ja.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,ja.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,ja.propertyInData)(e,o,f,a.ownProperties)),e.if((0,Ma.not)(m),()=>{t.error(),e.break()})},Ma.nil)}}};cg.default=r9});var zP=$(ug=>{"use strict";Object.defineProperty(ug,"__esModule",{value:!0});var La=Q(),n9={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,La.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,La._)`{limit: ${t}}`},o9={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:n9,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?La.operators.GT:La.operators.LT;t.fail$data((0,La._)`${r}.length ${o} ${n}`)}};ug.default=o9});var wl=$(lg=>{"use strict";Object.defineProperty(lg,"__esModule",{value:!0});var NP=Qi();NP.code='require("ajv/dist/runtime/equal").default';lg.default=NP});var jP=$(pg=>{"use strict";Object.defineProperty(pg,"__esModule",{value:!0});var dg=Pa(),et=Q(),s9=pe(),i9=wl(),a9={message:({params:{i:t,j:e}})=>(0,et.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,et._)`{i: ${t}, j: ${e}}`},c9={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:a9,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,dg.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,et._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,et._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,et._)`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,h){let y=e.name("item"),v=(0,dg.checkDataTypes)(u,y,a.opts.strictNumbers,dg.DataType.Wrong),b=e.const("indices",(0,et._)`{}`);e.for((0,et._)`;${m}--;`,()=>{e.let(y,(0,et._)`${r}[${m}]`),e.if(v,(0,et._)`continue`),u.length>1&&e.if((0,et._)`typeof ${y} == "string"`,(0,et._)`${y} += "_"`),e.if((0,et._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(h,(0,et._)`${b}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,et._)`${b}[${y}] = ${m}`)})}function f(m,h){let y=(0,s9.useFunc)(e,i9.default),v=e.name("outer");e.label(v).for((0,et._)`;${m}--;`,()=>e.for((0,et._)`${h} = ${m}; ${h}--;`,()=>e.if((0,et._)`${y}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};pg.default=c9});var MP=$(mg=>{"use strict";Object.defineProperty(mg,"__esModule",{value:!0});var fg=Q(),u9=pe(),l9=wl(),d9={message:"must be equal to constant",params:({schemaCode:t})=>(0,fg._)`{allowedValue: ${t}}`},p9={keyword:"const",$data:!0,error:d9,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,fg._)`!${(0,u9.useFunc)(e,l9.default)}(${r}, ${o})`):t.fail((0,fg._)`${s} !== ${r}`)}};mg.default=p9});var LP=$(hg=>{"use strict";Object.defineProperty(hg,"__esModule",{value:!0});var qa=Q(),f9=pe(),m9=wl(),h9={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,qa._)`{allowedValues: ${t}}`},g9={keyword:"enum",schemaType:"array",$data:!0,error:h9,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,f9.useFunc)(e,m9.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,qa.or)(...o.map((m,h)=>p(f,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,qa._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let h=o[m];return typeof h=="object"&&h!==null?(0,qa._)`${u()}(${r}, ${f}[${m}])`:(0,qa._)`${r} === ${h}`}}};hg.default=g9});var qP=$(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var y9=EP(),v9=TP(),_9=AP(),b9=CP(),w9=DP(),$9=OP(),S9=zP(),x9=jP(),k9=MP(),P9=LP(),E9=[y9.default,v9.default,_9.default,b9.default,w9.default,$9.default,S9.default,x9.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},k9.default,P9.default];gg.default=E9});var vg=$(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.validateAdditionalItems=void 0;var _o=Q(),yg=pe(),T9={message:({params:{len:t}})=>(0,_o.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,_o._)`{limit: ${t}}`},R9={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:T9,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,yg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}FP(t,n)}};function FP(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,_o._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,_o._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,yg.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,_o._)`${a} <= ${e.length}`);r.if((0,_o.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:yg.Type.Num},u),i.allErrors||r.if((0,_o.not)(u),()=>r.break())})}}Fa.validateAdditionalItems=FP;Fa.default=R9});var _g=$(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.validateTuple=void 0;var UP=Q(),$l=pe(),I9=Ht(),A9={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return ZP(t,"additionalItems",e);r.items=!0,!(0,$l.alwaysValidSchema)(r,e)&&t.ok((0,I9.validateArray)(t))}};function ZP(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=$l.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,UP._)`${s}.length`);r.forEach((d,p)=>{(0,$l.alwaysValidSchema)(a,d)||(n.if((0,UP._)`${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,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let y=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,$l.checkStrictMode)(a,y,p.strictTuples)}}}Ua.validateTuple=ZP;Ua.default=A9});var VP=$(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});var C9=_g(),D9={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,C9.validateTuple)(t,"items")};bg.default=D9});var WP=$(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});var BP=Q(),O9=pe(),z9=Ht(),N9=vg(),j9={message:({params:{len:t}})=>(0,BP.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,BP._)`{limit: ${t}}`},M9={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:j9,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,O9.alwaysValidSchema)(n,e)&&(o?(0,N9.validateAdditionalItems)(t,o):t.ok((0,z9.validateArray)(t)))}};wg.default=M9});var HP=$($g=>{"use strict";Object.defineProperty($g,"__esModule",{value:!0});var Jt=Q(),Sl=pe(),L9={message:({params:{min:t,max:e}})=>e===void 0?(0,Jt.str)`must contain at least ${t} valid item(s)`:(0,Jt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Jt._)`{minContains: ${t}}`:(0,Jt._)`{minContains: ${t}, maxContains: ${e}}`},q9={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:L9,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,Jt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Sl.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Sl.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Sl.alwaysValidSchema)(s,r)){let h=(0,Jt._)`${l} >= ${i}`;a!==void 0&&(h=(0,Jt._)`${h} && ${l} <= ${a}`),t.pass(h);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,Jt._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),y=e.let("count",0);f(h,()=>e.if(h,()=>m(y)))}function f(h,y){e.forRange("i",0,l,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:Sl.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,Jt._)`${h}++`),a===void 0?e.if((0,Jt._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Jt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Jt._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};$g.default=q9});var GP=$(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.validateSchemaDeps=Pr.validatePropertyDeps=Pr.error=void 0;var Sg=Q(),F9=pe(),Za=Ht();Pr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Sg.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Sg._)`{property: ${t},
|
|
12
|
+
deps: ${r}}`};var Fq={keyword:"dependencies",type:"object",schemaType:"object",error:xr.error,code(t){let[e,r]=Uq(t);D0(t,e),O0(t,r)}};function Uq({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function D0(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,$a.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(c,()=>{for(let u of a)(0,$a.checkReportMissingProp)(t,u)}):(r.if((0,Vm._)`${c} && (${(0,$a.checkMissingProp)(t,a,o)})`),(0,$a.reportMissingProp)(t,o),r.else())}}xr.validatePropertyDeps=D0;function O0(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,qq.alwaysValidSchema)(o,e[a])||(r.if((0,$a.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}xr.validateSchemaDeps=O0;xr.default=Fq});var N0=S(Bm=>{"use strict";Object.defineProperty(Bm,"__esModule",{value:!0});var M0=te(),Zq=le(),Vq={message:"property name must be valid",params:({params:t})=>(0,M0._)`{propertyName: ${t.propertyName}}`},Bq={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Vq,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,Zq.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,M0.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Bm.default=Bq});var Hm=S(Wm=>{"use strict";Object.defineProperty(Wm,"__esModule",{value:!0});var el=Wt(),ar=te(),Wq=Ur(),tl=le(),Hq={message:"must NOT have additional properties",params:({params:t})=>(0,ar._)`{additionalProperty: ${t.additionalProperty}}`},Kq={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Hq,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,tl.alwaysValidSchema)(i,r))return;let u=(0,el.allSchemaProperties)(n.properties),l=(0,el.allSchemaProperties)(n.patternProperties);d(),t.ok((0,ar._)`${o} === ${Wq.default.errors}`);function d(){e.forIn("key",s,v=>{!u.length&&!l.length?m(v):e.if(p(v),()=>m(v))})}function p(v){let g;if(u.length>8){let b=(0,tl.schemaRefOrVal)(i,n.properties,"properties");g=(0,el.isOwnProperty)(e,b,v)}else u.length?g=(0,ar.or)(...u.map(b=>(0,ar._)`${v} === ${b}`)):g=ar.nil;return l.length&&(g=(0,ar.or)(g,...l.map(b=>(0,ar._)`${(0,el.usePattern)(t,b)}.test(${v})`))),(0,ar.not)(g)}function f(v){e.code((0,ar._)`delete ${s}[${v}]`)}function m(v){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(v);return}if(r===!1){t.setParams({additionalProperty:v}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,tl.alwaysValidSchema)(i,r)){let g=e.name("valid");c.removeAdditional==="failing"?(h(v,g,!1),e.if((0,ar.not)(g),()=>{t.reset(),f(v)})):(h(v,g),a||e.if((0,ar.not)(g),()=>e.break()))}}function h(v,g,b){let _={keyword:"additionalProperties",dataProp:v,dataPropType:tl.Type.Str};b===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,g)}}};Wm.default=Kq});var q0=S(Jm=>{"use strict";Object.defineProperty(Jm,"__esModule",{value:!0});var Jq=ua(),j0=Wt(),Km=le(),L0=Hm(),Gq={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&L0.default.code(new Jq.KeywordCxt(o,L0.default,"additionalProperties"));let i=(0,j0.allSchemaProperties)(r);for(let d of i)o.definedProperties.add(d);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Km.mergeEvaluated.props(e,(0,Km.toHash)(i),o.props));let a=i.filter(d=>!(0,Km.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,j0.propertyInData)(e,s,d,o.opts.ownProperties)),l(d),o.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Jm.default=Gq});var V0=S(Gm=>{"use strict";Object.defineProperty(Gm,"__esModule",{value:!0});var F0=Wt(),rl=te(),U0=le(),Z0=le(),Yq={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,F0.allSchemaProperties)(r),c=a.filter(h=>(0,U0.alwaysValidSchema)(o,r[h]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,l=e.name("valid");o.props!==!0&&!(o.props instanceof rl.Name)&&(o.props=(0,Z0.evaluatedPropsToName)(e,o.props));let{props:d}=o;p();function p(){for(let h of a)u&&f(h),o.allErrors?m(h):(e.var(l,!0),m(h),e.if(l))}function f(h){for(let v in u)new RegExp(h).test(v)&&(0,U0.checkStrictMode)(o,`property ${v} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,v=>{e.if((0,rl._)`${(0,F0.usePattern)(t,h)}.test(${v})`,()=>{let g=c.includes(h);g||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:v,dataPropType:Z0.Type.Str},l),o.opts.unevaluated&&d!==!0?e.assign((0,rl._)`${d}[${v}]`,!0):!g&&!o.allErrors&&e.if((0,rl.not)(l),()=>e.break())})})}}};Gm.default=Yq});var B0=S(Ym=>{"use strict";Object.defineProperty(Ym,"__esModule",{value:!0});var Xq=le(),Qq={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Xq.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Ym.default=Qq});var W0=S(Xm=>{"use strict";Object.defineProperty(Xm,"__esModule",{value:!0});var eF=Wt(),tF={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:eF.validateUnion,error:{message:"must match a schema in anyOf"}};Xm.default=tF});var H0=S(Qm=>{"use strict";Object.defineProperty(Qm,"__esModule",{value:!0});var nl=te(),rF=le(),nF={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,nl._)`{passingSchemas: ${t.passing}}`},sF={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:nF,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=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(){o.forEach((l,d)=>{let p;(0,rF.alwaysValidSchema)(s,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,nl._)`${c} && ${i}`).assign(i,!1).assign(a,(0,nl._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,nl.Name)})})}}};Qm.default=sF});var K0=S(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});var oF=le(),iF={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 s=e.name("valid");r.forEach((o,i)=>{if((0,oF.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};eh.default=iF});var Y0=S(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var sl=te(),G0=le(),aF={message:({params:t})=>(0,sl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,sl._)`{failingKeyword: ${t.ifClause}}`},cF={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:aF,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,G0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=J0(n,"then"),o=J0(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),s&&o){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else s?e.if(a,u("then")):e.if((0,sl.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,sl._)`${l}`):t.setParams({ifClause:l})}}}};function J0(t,e){let r=t.schema[e];return r!==void 0&&!(0,G0.alwaysValidSchema)(t,r)}th.default=cF});var X0=S(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});var uF=le(),lF={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,uF.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};rh.default=lF});var Q0=S(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});var dF=Lm(),pF=I0(),fF=qm(),mF=A0(),hF=C0(),gF=z0(),yF=N0(),vF=Hm(),_F=q0(),bF=V0(),wF=B0(),SF=W0(),$F=H0(),xF=K0(),PF=Y0(),kF=X0();function EF(t=!1){let e=[wF.default,SF.default,$F.default,xF.default,PF.default,kF.default,yF.default,vF.default,gF.default,_F.default,bF.default];return t?e.push(pF.default,mF.default):e.push(dF.default,fF.default),e.push(hF.default),e}nh.default=EF});var eP=S(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var Fe=te(),TF={message:({schemaCode:t})=>(0,Fe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Fe._)`{format: ${t}}`},IF={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:TF,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;s?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,Fe._)`${m}[${i}]`),v=r.let("fType"),g=r.let("format");r.if((0,Fe._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(v,(0,Fe._)`${h}.type || "string"`).assign(g,(0,Fe._)`${h}.validate`),()=>r.assign(v,(0,Fe._)`"string"`).assign(g,h)),t.fail$data((0,Fe.or)(b(),_()));function b(){return c.strictSchema===!1?Fe.nil:(0,Fe._)`${i} && !${g}`}function _(){let P=l.$async?(0,Fe._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,Fe._)`${g}(${n})`,x=(0,Fe._)`(typeof ${g} == "function" ? ${P} : ${g}.test(${n}))`;return(0,Fe._)`${g} && ${g} !== true && ${v} === ${e} && !${x}`}}function f(){let m=d.formats[o];if(!m){b();return}if(m===!0)return;let[h,v,g]=_(m);h===e&&t.pass(P());function b(){if(c.strictSchema===!1){d.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function _(x){let j=x instanceof RegExp?(0,Fe.regexpCode)(x):c.code.formats?(0,Fe._)`${c.code.formats}${(0,Fe.getProperty)(o)}`:void 0,k=r.scopeValue("formats",{key:o,ref:x,code:j});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,Fe._)`${k}.validate`]:["string",x,k]}function P(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Fe._)`await ${g}(${n})`}return typeof v=="function"?(0,Fe._)`${g}(${n})`:(0,Fe._)`${g}.test(${n})`}}}};sh.default=IF});var tP=S(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});var RF=eP(),AF=[RF.default];oh.default=AF});var rP=S(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.contentVocabulary=xo.metadataVocabulary=void 0;xo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];xo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var sP=S(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});var CF=d0(),DF=P0(),OF=Q0(),zF=tP(),nP=rP(),MF=[CF.default,DF.default,(0,OF.default)(),zF.default,nP.metadataVocabulary,nP.contentVocabulary];ih.default=MF});var iP=S(ol=>{"use strict";Object.defineProperty(ol,"__esModule",{value:!0});ol.DiscrError=void 0;var oP;(function(t){t.Tag="tag",t.Mapping="mapping"})(oP||(ol.DiscrError=oP={}))});var cP=S(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var Po=te(),ah=iP(),aP=Fu(),NF=la(),jF=le(),LF={message:({params:{discrError:t,tagName:e}})=>t===ah.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Po._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},qF={keyword:"discriminator",type:"object",schemaType:"object",error:LF,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.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,Po._)`${r}${(0,Po.getProperty)(a)}`);e.if((0,Po._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:ah.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,Po._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:ah.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,Po.Name),m}function p(){var f;let m={},h=g(s),v=!0;for(let P=0;P<i.length;P++){let x=i[P];if(x?.$ref&&!(0,jF.schemaHasRulesButRef)(x,o.self.RULES)){let k=x.$ref;if(x=aP.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,k),x instanceof aP.SchemaEnv&&(x=x.schema),x===void 0)throw new NF.default(o.opts.uriResolver,o.baseId,k)}let j=(f=x?.properties)===null||f===void 0?void 0:f[a];if(typeof j!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);v=v&&(h||g(x)),b(j,P)}if(!v)throw new Error(`discriminator: "${a}" must be required`);return m;function g({required:P}){return Array.isArray(P)&&P.includes(a)}function b(P,x){if(P.const)_(P.const,x);else if(P.enum)for(let j of P.enum)_(j,x);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(P,x){if(typeof P!="string"||P in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[P]=x}}}};ch.default=qF});var uP=S((C7,FF)=>{FF.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 dP=S((Ae,uh)=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.MissingRefError=Ae.ValidationError=Ae.CodeGen=Ae.Name=Ae.nil=Ae.stringify=Ae.str=Ae._=Ae.KeywordCxt=Ae.Ajv=void 0;var UF=o0(),ZF=sP(),VF=cP(),lP=uP(),BF=["/properties"],il="http://json-schema.org/draft-07/schema",ko=class extends UF.default{_addVocabularies(){super._addVocabularies(),ZF.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(VF.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(lP,BF):lP;this.addMetaSchema(e,il,!1),this.refs["http://json-schema.org/schema"]=il}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(il)?il:void 0)}};Ae.Ajv=ko;uh.exports=Ae=ko;uh.exports.Ajv=ko;Object.defineProperty(Ae,"__esModule",{value:!0});Ae.default=ko;var WF=ua();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return WF.KeywordCxt}});var Eo=te();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return Eo._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return Eo.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return Eo.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return Eo.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return Eo.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return Eo.CodeGen}});var HF=Lu();Object.defineProperty(Ae,"ValidationError",{enumerable:!0,get:function(){return HF.default}});var KF=la();Object.defineProperty(Ae,"MissingRefError",{enumerable:!0,get:function(){return KF.default}})});var _P=S(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.formatNames=kr.fastFormats=kr.fullFormats=void 0;function Pr(t,e){return{validate:t,compare:e}}kr.fullFormats={date:Pr(hP,fh),time:Pr(dh(!0),mh),"date-time":Pr(pP(!0),yP),"iso-time":Pr(dh(),gP),"iso-date-time":Pr(pP(),vP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:eU,"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:aU,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:tU,int32:{type:"number",validate:sU},int64:{type:"number",validate:oU},float:{type:"number",validate:mP},double:{type:"number",validate:mP},password:!0,binary:!0};kr.fastFormats={...kr.fullFormats,date:Pr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,fh),time:Pr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,mh),"date-time":Pr(/^\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,yP),"iso-time":Pr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,gP),"iso-date-time":Pr(/^\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,vP),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};kr.formatNames=Object.keys(kr.fullFormats);function JF(t){return t%4===0&&(t%100!==0||t%400===0)}var GF=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,YF=[0,31,28,31,30,31,30,31,31,30,31,30,31];function hP(t){let e=GF.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&JF(r)?29:YF[n])}function fh(t,e){if(t&&e)return t>e?1:t<e?-1:0}var lh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function dh(t){return function(r){let n=lh.exec(r);if(!n)return!1;let s=+n[1],o=+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(s<=23&&o<=59&&i<60)return!0;let d=o-l*c,p=s-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function mh(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 gP(t,e){if(!(t&&e))return;let r=lh.exec(t),n=lh.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 ph=/t|\s/i;function pP(t){let e=dh(t);return function(n){let s=n.split(ph);return s.length===2&&hP(s[0])&&e(s[1])}}function yP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function vP(t,e){if(!(t&&e))return;let[r,n]=t.split(ph),[s,o]=e.split(ph),i=fh(r,s);if(i!==void 0)return i||mh(n,o)}var XF=/\/|:/,QF=/^(?:[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 eU(t){return XF.test(t)&&QF.test(t)}var fP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function tU(t){return fP.lastIndex=0,fP.test(t)}var rU=-(2**31),nU=2**31-1;function sU(t){return Number.isInteger(t)&&t<=nU&&t>=rU}function oU(t){return Number.isInteger(t)}function mP(){return!0}var iU=/[^\\]\\Z/;function aU(t){if(iU.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var ka=S(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var xa=class{};he._CodeOrName=xa;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ps=class extends xa{constructor(e){if(super(),!he.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}}};he.Name=ps;var Jt=class extends xa{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 ps&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=Jt;he.nil=new Jt("");function bP(t,...e){let r=[t[0]],n=0;for(;n<e.length;)gh(r,e[n]),r.push(t[++n]);return new Jt(r)}he._=bP;var hh=new Jt("+");function wP(t,...e){let r=[Pa(t[0])],n=0;for(;n<e.length;)r.push(hh),gh(r,e[n]),r.push(hh,Pa(t[++n]));return cU(r),new Jt(r)}he.str=wP;function gh(t,e){e instanceof Jt?t.push(...e._items):e instanceof ps?t.push(e):t.push(dU(e))}he.addCodeArg=gh;function cU(t){let e=1;for(;e<t.length-1;){if(t[e]===hh){let r=uU(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function uU(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof ps||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 ps))return`"${t}${e.slice(1)}`}function lU(t,e){return e.emptyStr()?t:t.emptyStr()?e:wP`${t}${e}`}he.strConcat=lU;function dU(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Pa(Array.isArray(t)?t.join(","):t)}function pU(t){return new Jt(Pa(t))}he.stringify=pU;function Pa(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Pa;function fU(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new Jt(`.${t}`):bP`[${t}]`}he.getProperty=fU;function mU(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new Jt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=mU;function hU(t){return new Jt(t.toString())}he.regexpCode=hU});var _h=S(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.ValueScope=Et.ValueScopeName=Et.Scope=Et.varKinds=Et.UsedValueState=void 0;var kt=ka(),yh=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},al;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(al||(Et.UsedValueState=al={}));Et.varKinds={const:new kt.Name("const"),let:new kt.Name("let"),var:new kt.Name("var")};var cl=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof kt.Name?e:this.name(e)}name(e){return new kt.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}}};Et.Scope=cl;var ul=class extends kt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,kt._)`.${new kt.Name(r)}[${n}]`}};Et.ValueScopeName=ul;var gU=(0,kt._)`\n`,vh=class extends cl{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?gU:kt.nil}}get(){return this._scope}name(e){return new ul(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 s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let l=a.get(i);if(l)return l}else a=this._values[o]=new Map;a.set(i,s);let c=this._scope[o]||(this._scope[o]=[]),u=c.length;return c[u]=r.ref,s.setValue(r,{property:o,itemIndex:u}),s}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,kt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=kt.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,al.Started);let l=r(u);if(l){let d=this.opts.es5?Et.varKinds.var:Et.varKinds.const;o=(0,kt._)`${o}${d} ${u} = ${l};${this.opts._n}`}else if(l=s?.(u))o=(0,kt._)`${o}${l}${this.opts._n}`;else throw new yh(u);c.set(u,al.Completed)})}return o}};Et.ValueScope=vh});var X=S(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.or=ee.and=ee.not=ee.CodeGen=ee.operators=ee.varKinds=ee.ValueScopeName=ee.ValueScope=ee.Scope=ee.Name=ee.regexpCode=ee.stringify=ee.getProperty=ee.nil=ee.strConcat=ee.str=ee._=void 0;var ue=ka(),cr=_h(),yn=ka();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return yn._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return yn.str}});Object.defineProperty(ee,"strConcat",{enumerable:!0,get:function(){return yn.strConcat}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return yn.nil}});Object.defineProperty(ee,"getProperty",{enumerable:!0,get:function(){return yn.getProperty}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return yn.stringify}});Object.defineProperty(ee,"regexpCode",{enumerable:!0,get:function(){return yn.regexpCode}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return yn.Name}});var fl=_h();Object.defineProperty(ee,"Scope",{enumerable:!0,get:function(){return fl.Scope}});Object.defineProperty(ee,"ValueScope",{enumerable:!0,get:function(){return fl.ValueScope}});Object.defineProperty(ee,"ValueScopeName",{enumerable:!0,get:function(){return fl.ValueScopeName}});Object.defineProperty(ee,"varKinds",{enumerable:!0,get:function(){return fl.varKinds}});ee.operators={GT:new ue._Code(">"),GTE:new ue._Code(">="),LT:new ue._Code("<"),LTE:new ue._Code("<="),EQ:new ue._Code("==="),NEQ:new ue._Code("!=="),NOT:new ue._Code("!"),OR:new ue._Code("||"),AND:new ue._Code("&&"),ADD:new ue._Code("+")};var Br=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},bh=class extends Br{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?cr.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Io(this.rhs,e,r)),this}get names(){return this.rhs instanceof ue._CodeOrName?this.rhs.names:{}}},ll=class extends Br{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 ue.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Io(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ue.Name?{}:{...this.lhs.names};return pl(e,this.rhs)}},wh=class extends ll{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Sh=class extends Br{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},$h=class extends Br{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},xh=class extends Br{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ph=class extends Br{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=Io(this.code,e,r),this}get names(){return this.code instanceof ue._CodeOrName?this.code.names:{}}},Ea=class extends Br{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,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(yU(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>hs(e,r.names),{})}},Wr=class extends Ea{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},kh=class extends Ea{},To=class extends Wr{};To.kind="else";var fs=class t extends Wr{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 To(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(SP(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=Io(this.condition,e,r),this}get names(){let e=super.names;return pl(e,this.condition),this.else&&hs(e,this.else.names),e}};fs.kind="if";var ms=class extends Wr{};ms.kind="for";var Eh=class extends ms{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=Io(this.iteration,e,r),this}get names(){return hs(super.names,this.iteration.names)}},Th=class extends ms{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?cr.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=pl(super.names,this.from);return pl(e,this.to)}},dl=class extends ms{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}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=Io(this.iterable,e,r),this}get names(){return hs(super.names,this.iterable.names)}},Ta=class extends Wr{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)}};Ta.kind="func";var Ia=class extends Ea{render(e){return"return "+super.render(e)}};Ia.kind="return";var Ih=class extends Wr{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,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&hs(e,this.catch.names),this.finally&&hs(e,this.finally.names),e}},Ra=class extends Wr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ra.kind="catch";var Aa=class extends Wr{render(e){return"finally"+super.render(e)}};Aa.kind="finally";var Rh=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
13
|
+
`:""},this._extScope=e,this._scope=new cr.Scope({parent:e}),this._nodes=[new kh]}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,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new bh(e,o,n)),o}const(e,r,n){return this._def(cr.varKinds.const,e,r,n)}let(e,r,n){return this._def(cr.varKinds.let,e,r,n)}var(e,r,n){return this._def(cr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new ll(e,r,n))}add(e,r){return this._leafNode(new wh(e,ee.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ue.nil&&this._leafNode(new Ph(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,ue.addCodeArg)(r,s));return r.push("}"),new ue._Code(r)}if(e,r,n){if(this._blockNode(new fs(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 fs(e))}else(){return this._elseNode(new To)}endIf(){return this._endBlockNode(fs,To)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Eh(e),r)}forRange(e,r,n,s,o=this.opts.es5?cr.varKinds.var:cr.varKinds.let){let i=this._scope.toName(e);return this._for(new Th(o,i,r,n),()=>s(i))}forOf(e,r,n,s=cr.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ue.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ue._)`${i}.length`,a=>{this.var(o,(0,ue._)`${i}[${a}]`),n(o)})}return this._for(new dl("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?cr.varKinds.var:cr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ue._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new dl("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(ms)}label(e){return this._leafNode(new Sh(e))}break(e){return this._leafNode(new $h(e))}return(e){let r=new Ia;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Ia)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Ih;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new Ra(o),r(o)}return n&&(this._currNode=s.finally=new Aa,this.code(n)),this._endBlockNode(Ra,Aa)}throw(e){return this._leafNode(new xh(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=ue.nil,n,s){return this._blockNode(new Ta(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Ta)}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 fs))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}};ee.CodeGen=Rh;function hs(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function pl(t,e){return e instanceof ue._CodeOrName?hs(t,e.names):t}function Io(t,e,r){if(t instanceof ue.Name)return n(t);if(!s(t))return t;return new ue._Code(t._items.reduce((o,i)=>(i instanceof ue.Name&&(i=n(i)),i instanceof ue._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof ue._Code&&o._items.some(i=>i instanceof ue.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function yU(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function SP(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ue._)`!${Ah(t)}`}ee.not=SP;var vU=$P(ee.operators.AND);function _U(...t){return t.reduce(vU)}ee.and=_U;var bU=$P(ee.operators.OR);function wU(...t){return t.reduce(bU)}ee.or=wU;function $P(t){return(e,r)=>e===ue.nil?r:r===ue.nil?e:(0,ue._)`${Ah(e)} ${t} ${Ah(r)}`}function Ah(t){return t instanceof ue.Name?t:(0,ue._)`(${t})`}});var pe=S(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.checkStrictMode=ne.getErrorPath=ne.Type=ne.useFunc=ne.setEvaluated=ne.evaluatedPropsToName=ne.mergeEvaluated=ne.eachItem=ne.unescapeJsonPointer=ne.escapeJsonPointer=ne.escapeFragment=ne.unescapeFragment=ne.schemaRefOrVal=ne.schemaHasRulesButRef=ne.schemaHasRules=ne.checkUnknownRules=ne.alwaysValidSchema=ne.toHash=void 0;var Se=X(),SU=ka();function $U(t){let e={};for(let r of t)e[r]=!0;return e}ne.toHash=$U;function xU(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(kP(t,e),!EP(e,t.self.RULES.all))}ne.alwaysValidSchema=xU;function kP(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||RP(t,`unknown keyword: "${o}"`)}ne.checkUnknownRules=kP;function EP(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ne.schemaHasRules=EP;function PU(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ne.schemaHasRulesButRef=PU;function kU({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Se._)`${r}`}return(0,Se._)`${t}${e}${(0,Se.getProperty)(n)}`}ne.schemaRefOrVal=kU;function EU(t){return TP(decodeURIComponent(t))}ne.unescapeFragment=EU;function TU(t){return encodeURIComponent(Dh(t))}ne.escapeFragment=TU;function Dh(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ne.escapeJsonPointer=Dh;function TP(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ne.unescapeJsonPointer=TP;function IU(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ne.eachItem=IU;function xP({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof Se.Name?(o instanceof Se.Name?t(s,o,i):e(s,o,i),i):o instanceof Se.Name?(e(s,i,o),o):r(o,i);return a===Se.Name&&!(c instanceof Se.Name)?n(s,c):c}}ne.mergeEvaluated={props:xP({mergeNames:(t,e,r)=>t.if((0,Se._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Se._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Se._)`${r} || {}`).code((0,Se._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Se._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Se._)`${r} || {}`),Oh(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:IP}),items:xP({mergeNames:(t,e,r)=>t.if((0,Se._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Se._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Se._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Se._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function IP(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Se._)`{}`);return e!==void 0&&Oh(t,r,e),r}ne.evaluatedPropsToName=IP;function Oh(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Se._)`${e}${(0,Se.getProperty)(n)}`,!0))}ne.setEvaluated=Oh;var PP={};function RU(t,e){return t.scopeValue("func",{ref:e,code:PP[e.code]||(PP[e.code]=new SU._Code(e.code))})}ne.useFunc=RU;var Ch;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ch||(ne.Type=Ch={}));function AU(t,e,r){if(t instanceof Se.Name){let n=e===Ch.Num;return r?n?(0,Se._)`"[" + ${t} + "]"`:(0,Se._)`"['" + ${t} + "']"`:n?(0,Se._)`"/" + ${t}`:(0,Se._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Se.getProperty)(t).toString():"/"+Dh(t)}ne.getErrorPath=AU;function RP(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ne.checkStrictMode=RP});var Hr=S(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});var at=X(),CU={data:new at.Name("data"),valCxt:new at.Name("valCxt"),instancePath:new at.Name("instancePath"),parentData:new at.Name("parentData"),parentDataProperty:new at.Name("parentDataProperty"),rootData:new at.Name("rootData"),dynamicAnchors:new at.Name("dynamicAnchors"),vErrors:new at.Name("vErrors"),errors:new at.Name("errors"),this:new at.Name("this"),self:new at.Name("self"),scope:new at.Name("scope"),json:new at.Name("json"),jsonPos:new at.Name("jsonPos"),jsonLen:new at.Name("jsonLen"),jsonPart:new at.Name("jsonPart")};zh.default=CU});var Ca=S(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.extendErrors=ct.resetErrorsCount=ct.reportExtraError=ct.reportError=ct.keyword$DataError=ct.keywordError=void 0;var fe=X(),ml=pe(),gt=Hr();ct.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};ct.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,fe.str)`"${t}" keyword must be ${e} ($data)`:(0,fe.str)`"${t}" keyword is invalid ($data)`};function DU(t,e=ct.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=DP(t,e,r);n??(i||a)?AP(o,c):CP(s,(0,fe._)`[${c}]`)}ct.reportError=DU;function OU(t,e=ct.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=DP(t,e,r);AP(s,a),o||i||CP(n,gt.default.vErrors)}ct.reportExtraError=OU;function zU(t,e){t.assign(gt.default.errors,e),t.if((0,fe._)`${gt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,fe._)`${gt.default.vErrors}.length`,e),()=>t.assign(gt.default.vErrors,null)))}ct.resetErrorsCount=zU;function MU({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,gt.default.errors,a=>{t.const(i,(0,fe._)`${gt.default.vErrors}[${a}]`),t.if((0,fe._)`${i}.instancePath === undefined`,()=>t.assign((0,fe._)`${i}.instancePath`,(0,fe.strConcat)(gt.default.instancePath,o.errorPath))),t.assign((0,fe._)`${i}.schemaPath`,(0,fe.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,fe._)`${i}.schema`,r),t.assign((0,fe._)`${i}.data`,n))})}ct.extendErrors=MU;function AP(t,e){let r=t.const("err",e);t.if((0,fe._)`${gt.default.vErrors} === null`,()=>t.assign(gt.default.vErrors,(0,fe._)`[${r}]`),(0,fe._)`${gt.default.vErrors}.push(${r})`),t.code((0,fe._)`${gt.default.errors}++`)}function CP(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,fe._)`new ${t.ValidationError}(${e})`):(r.assign((0,fe._)`${n}.errors`,e),r.return(!1))}var gs={keyword:new fe.Name("keyword"),schemaPath:new fe.Name("schemaPath"),params:new fe.Name("params"),propertyName:new fe.Name("propertyName"),message:new fe.Name("message"),schema:new fe.Name("schema"),parentSchema:new fe.Name("parentSchema")};function DP(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,fe._)`{}`:NU(t,e,r)}function NU(t,e,r={}){let{gen:n,it:s}=t,o=[jU(s,r),LU(t,r)];return qU(t,e,o),n.object(...o)}function jU({errorPath:t},{instancePath:e}){let r=e?(0,fe.str)`${t}${(0,ml.getErrorPath)(e,ml.Type.Str)}`:t;return[gt.default.instancePath,(0,fe.strConcat)(gt.default.instancePath,r)]}function LU({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,fe.str)`${e}/${t}`;return r&&(s=(0,fe.str)`${s}${(0,ml.getErrorPath)(r,ml.Type.Str)}`),[gs.schemaPath,s]}function qU(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([gs.keyword,s],[gs.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&n.push([gs.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([gs.schema,i],[gs.parentSchema,(0,fe._)`${l}${d}`],[gt.default.data,o]),u&&n.push([gs.propertyName,u])}});var zP=S(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});Ro.boolOrEmptySchema=Ro.topBoolOrEmptySchema=void 0;var FU=Ca(),UU=X(),ZU=Hr(),VU={message:"boolean schema is false"};function BU(t){let{gen:e,schema:r,validateName:n}=t;r===!1?OP(t,!1):typeof r=="object"&&r.$async===!0?e.return(ZU.default.data):(e.assign((0,UU._)`${n}.errors`,null),e.return(!0))}Ro.topBoolOrEmptySchema=BU;function WU(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),OP(t)):r.var(e,!0)}Ro.boolOrEmptySchema=WU;function OP(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,FU.reportError)(s,VU,void 0,e)}});var Mh=S(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.getRules=Ao.isJSONType=void 0;var HU=["string","number","integer","boolean","null","object","array"],KU=new Set(HU);function JU(t){return typeof t=="string"&&KU.has(t)}Ao.isJSONType=JU;function GU(){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:{}}}Ao.getRules=GU});var Nh=S(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.shouldUseRule=vn.shouldUseGroup=vn.schemaHasRulesForType=void 0;function YU({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&MP(t,n)}vn.schemaHasRulesForType=YU;function MP(t,e){return e.rules.some(r=>NP(t,r))}vn.shouldUseGroup=MP;function NP(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))}vn.shouldUseRule=NP});var Da=S(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.reportTypeError=ut.checkDataTypes=ut.checkDataType=ut.coerceAndCheckDataType=ut.getJSONTypes=ut.getSchemaTypes=ut.DataType=void 0;var XU=Mh(),QU=Nh(),eZ=Ca(),J=X(),jP=pe(),Co;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Co||(ut.DataType=Co={}));function tZ(t){let e=LP(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}ut.getSchemaTypes=tZ;function LP(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(XU.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ut.getJSONTypes=LP;function rZ(t,e){let{gen:r,data:n,opts:s}=t,o=nZ(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,QU.schemaHasRulesForType)(t,e[0]));if(i){let a=Lh(e,n,s.strictNumbers,Co.Wrong);r.if(a,()=>{o.length?sZ(t,e,o):qh(t)})}return i}ut.coerceAndCheckDataType=rZ;var qP=new Set(["string","number","integer","boolean","null"]);function nZ(t,e){return e?t.filter(r=>qP.has(r)||e==="array"&&r==="array"):[]}function sZ(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,J._)`typeof ${s}`),a=n.let("coerced",(0,J._)`undefined`);o.coerceTypes==="array"&&n.if((0,J._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,J._)`${s}[0]`).assign(i,(0,J._)`typeof ${s}`).if(Lh(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,J._)`${a} !== undefined`);for(let u of r)(qP.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),qh(t),n.endIf(),n.if((0,J._)`${a} !== undefined`,()=>{n.assign(s,a),oZ(t,a)});function c(u){switch(u){case"string":n.elseIf((0,J._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,J._)`"" + ${s}`).elseIf((0,J._)`${s} === null`).assign(a,(0,J._)`""`);return;case"number":n.elseIf((0,J._)`${i} == "boolean" || ${s} === null
|
|
14
|
+
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,J._)`+${s}`);return;case"integer":n.elseIf((0,J._)`${i} === "boolean" || ${s} === null
|
|
15
|
+
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,J._)`+${s}`);return;case"boolean":n.elseIf((0,J._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,J._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,J._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,J._)`${i} === "string" || ${i} === "number"
|
|
16
|
+
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,J._)`[${s}]`)}}}function oZ({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,J._)`${e} !== undefined`,()=>t.assign((0,J._)`${e}[${r}]`,n))}function jh(t,e,r,n=Co.Correct){let s=n===Co.Correct?J.operators.EQ:J.operators.NEQ,o;switch(t){case"null":return(0,J._)`${e} ${s} null`;case"array":o=(0,J._)`Array.isArray(${e})`;break;case"object":o=(0,J._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,J._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,J._)`typeof ${e} ${s} ${t}`}return n===Co.Correct?o:(0,J.not)(o);function i(a=J.nil){return(0,J.and)((0,J._)`typeof ${e} == "number"`,a,r?(0,J._)`isFinite(${e})`:J.nil)}}ut.checkDataType=jh;function Lh(t,e,r,n){if(t.length===1)return jh(t[0],e,r,n);let s,o=(0,jP.toHash)(t);if(o.array&&o.object){let i=(0,J._)`typeof ${e} != "object"`;s=o.null?i:(0,J._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=J.nil;o.number&&delete o.integer;for(let i in o)s=(0,J.and)(s,jh(i,e,r,n));return s}ut.checkDataTypes=Lh;var iZ={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,J._)`{type: ${t}}`:(0,J._)`{type: ${e}}`};function qh(t){let e=aZ(t);(0,eZ.reportError)(e,iZ)}ut.reportTypeError=qh;function aZ(t){let{gen:e,data:r,schema:n}=t,s=(0,jP.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var UP=S(hl=>{"use strict";Object.defineProperty(hl,"__esModule",{value:!0});hl.assignDefaults=void 0;var Do=X(),cZ=pe();function uZ(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)FP(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>FP(t,o,s.default))}hl.assignDefaults=uZ;function FP(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,Do._)`${o}${(0,Do.getProperty)(e)}`;if(s){(0,cZ.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Do._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Do._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Do._)`${a} = ${(0,Do.stringify)(r)}`)}});var Gt=S(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.validateUnion=be.validateArray=be.usePattern=be.callValidateCode=be.schemaProperties=be.allSchemaProperties=be.noPropertyInData=be.propertyInData=be.isOwnProperty=be.hasPropFunc=be.reportMissingProp=be.checkMissingProp=be.checkReportMissingProp=void 0;var Ce=X(),Fh=pe(),_n=Hr(),lZ=pe();function dZ(t,e){let{gen:r,data:n,it:s}=t;r.if(Zh(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ce._)`${e}`},!0),t.error()})}be.checkReportMissingProp=dZ;function pZ({gen:t,data:e,it:{opts:r}},n,s){return(0,Ce.or)(...n.map(o=>(0,Ce.and)(Zh(t,e,o,r.ownProperties),(0,Ce._)`${s} = ${o}`)))}be.checkMissingProp=pZ;function fZ(t,e){t.setParams({missingProperty:e},!0),t.error()}be.reportMissingProp=fZ;function ZP(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ce._)`Object.prototype.hasOwnProperty`})}be.hasPropFunc=ZP;function Uh(t,e,r){return(0,Ce._)`${ZP(t)}.call(${e}, ${r})`}be.isOwnProperty=Uh;function mZ(t,e,r,n){let s=(0,Ce._)`${e}${(0,Ce.getProperty)(r)} !== undefined`;return n?(0,Ce._)`${s} && ${Uh(t,e,r)}`:s}be.propertyInData=mZ;function Zh(t,e,r,n){let s=(0,Ce._)`${e}${(0,Ce.getProperty)(r)} === undefined`;return n?(0,Ce.or)(s,(0,Ce.not)(Uh(t,e,r))):s}be.noPropertyInData=Zh;function VP(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}be.allSchemaProperties=VP;function hZ(t,e){return VP(e).filter(r=>!(0,Fh.alwaysValidSchema)(t,e[r]))}be.schemaProperties=hZ;function gZ({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,u){let l=u?(0,Ce._)`${t}, ${e}, ${n}${s}`:e,d=[[_n.default.instancePath,(0,Ce.strConcat)(_n.default.instancePath,o)],[_n.default.parentData,i.parentData],[_n.default.parentDataProperty,i.parentDataProperty],[_n.default.rootData,_n.default.rootData]];i.opts.dynamicRef&&d.push([_n.default.dynamicAnchors,_n.default.dynamicAnchors]);let p=(0,Ce._)`${l}, ${r.object(...d)}`;return c!==Ce.nil?(0,Ce._)`${a}.call(${c}, ${p})`:(0,Ce._)`${a}(${p})`}be.callValidateCode=gZ;var yZ=(0,Ce._)`new RegExp`;function vZ({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,Ce._)`${s.code==="new RegExp"?yZ:(0,lZ.useFunc)(t,s)}(${r}, ${n})`})}be.usePattern=vZ;function _Z(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let c=e.const("len",(0,Ce._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Fh.Type.Num},o),e.if((0,Ce.not)(o),a)})}}be.validateArray=_Z;function bZ(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Fh.alwaysValidSchema)(s,c))&&!s.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,Ce._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ce.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}be.validateUnion=bZ});var HP=S(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.validateKeywordUsage=Er.validSchemaType=Er.funcKeywordCode=Er.macroKeywordCode=void 0;var yt=X(),ys=Hr(),wZ=Gt(),SZ=Ca();function $Z(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=WP(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:yt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Er.macroKeywordCode=$Z;function xZ(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;kZ(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,l=WP(n,s,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)h(),e.modifying&&BP(t),v(()=>t.error());else{let g=e.async?f():m();e.modifying&&BP(t),v(()=>PZ(t,g))}}function f(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,yt._)`await `),b=>n.assign(d,!1).if((0,yt._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,yt._)`${b}.errors`),()=>n.throw(b))),g}function m(){let g=(0,yt._)`${l}.errors`;return n.assign(g,null),h(yt.nil),g}function h(g=e.async?(0,yt._)`await `:yt.nil){let b=c.opts.passContext?ys.default.this:ys.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,yt._)`${g}${(0,wZ.callValidateCode)(t,l,b,_)}`,e.modifying)}function v(g){var b;n.if((0,yt.not)((b=e.valid)!==null&&b!==void 0?b:d),g)}}Er.funcKeywordCode=xZ;function BP(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,yt._)`${n.parentData}[${n.parentDataProperty}]`))}function PZ(t,e){let{gen:r}=t;r.if((0,yt._)`Array.isArray(${e})`,()=>{r.assign(ys.default.vErrors,(0,yt._)`${ys.default.vErrors} === null ? ${e} : ${ys.default.vErrors}.concat(${e})`).assign(ys.default.errors,(0,yt._)`${ys.default.vErrors}.length`),(0,SZ.extendErrors)(t)},()=>t.error())}function kZ({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function WP(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,yt.stringify)(r)})}function EZ(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")}Er.validSchemaType=EZ;function TZ({schema:t,opts:e,self:r,errSchemaPath:n},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let c=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Er.validateKeywordUsage=TZ});var JP=S(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.extendSubschemaMode=bn.extendSubschemaData=bn.getSubschema=void 0;var Tr=X(),KP=pe();function IZ(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,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,Tr._)`${t.schemaPath}${(0,Tr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Tr._)`${t.schemaPath}${(0,Tr.getProperty)(e)}${(0,Tr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,KP.escapeFragment)(r)}`}}if(n!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}bn.getSubschema=IZ;function RZ(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==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,Tr._)`${e.data}${(0,Tr.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Tr.str)`${u}${(0,KP.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Tr._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Tr.Name?s:a.let("data",s,!0);c(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);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]}}bn.extendSubschemaData=RZ;function AZ(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}bn.extendSubschemaMode=AZ});var YP=S((K7,GP)=>{"use strict";var wn=GP.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};gl(e,n,s,t,"",t)};wn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};wn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};wn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};wn.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 gl(t,e,r,n,s,o,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in wn.arrayKeywords)for(var p=0;p<d.length;p++)gl(t,e,r,d[p],s+"/"+l+"/"+p,o,s,l,n,p)}else if(l in wn.propsKeywords){if(d&&typeof d=="object")for(var f in d)gl(t,e,r,d[f],s+"/"+l+"/"+CZ(f),o,s,l,n,f)}else(l in wn.keywords||t.allKeys&&!(l in wn.skipKeywords))&&gl(t,e,r,d,s+"/"+l,o,s,l,n)}r(n,s,o,i,a,c,u)}}function CZ(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Oa=S(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getSchemaRefs=Tt.resolveUrl=Tt.normalizeId=Tt._getFullPath=Tt.getFullPath=Tt.inlineRef=void 0;var DZ=pe(),OZ=oa(),zZ=YP(),MZ=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function NZ(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Vh(t):e?XP(t)<=e:!1}Tt.inlineRef=NZ;var jZ=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Vh(t){for(let e in t){if(jZ.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Vh)||typeof r=="object"&&Vh(r))return!0}return!1}function XP(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!MZ.has(r)&&(typeof t[r]=="object"&&(0,DZ.eachItem)(t[r],n=>e+=XP(n)),e===1/0))return 1/0}return e}function QP(t,e="",r){r!==!1&&(e=Oo(e));let n=t.parse(e);return ek(t,n)}Tt.getFullPath=QP;function ek(t,e){return t.serialize(e).split("#")[0]+"#"}Tt._getFullPath=ek;var LZ=/#\/?$/;function Oo(t){return t?t.replace(LZ,""):""}Tt.normalizeId=Oo;function qZ(t,e,r){return r=Oo(r),t.resolve(e,r)}Tt.resolveUrl=qZ;var FZ=/^[a-z_][-a-z0-9._]*$/i;function UZ(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=Oo(t[r]||e),o={"":s},i=QP(n,s,!1),a={},c=new Set;return zZ(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=i+p,v=o[m];typeof d[r]=="string"&&(v=g.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),o[p]=v;function g(_){let P=this.opts.uriResolver.resolve;if(_=Oo(v?P(v,_):_),c.has(_))throw l(_);c.add(_);let x=this.refs[_];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?u(d,x.schema,_):_!==Oo(h)&&(_[0]==="#"?(u(d,a[_],_),a[_]=d):this.refs[_]=h),_}function b(_){if(typeof _=="string"){if(!FZ.test(_))throw new Error(`invalid anchor "${_}"`);g.call(this,`#${_}`)}}}),a;function u(d,p,f){if(p!==void 0&&!OZ(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Tt.getSchemaRefs=UZ});var Na=S(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.getData=Sn.KeywordCxt=Sn.validateFunctionCode=void 0;var ok=zP(),tk=Da(),Wh=Nh(),yl=Da(),ZZ=UP(),Ma=HP(),Bh=JP(),N=X(),B=Hr(),VZ=Oa(),Kr=pe(),za=Ca();function BZ(t){if(ck(t)&&(uk(t),ak(t))){KZ(t);return}ik(t,()=>(0,ok.topBoolOrEmptySchema)(t))}Sn.validateFunctionCode=BZ;function ik({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,N._)`${B.default.data}, ${B.default.valCxt}`,n.$async,()=>{t.code((0,N._)`"use strict"; ${rk(r,s)}`),HZ(t,s),t.code(o)}):t.func(e,(0,N._)`${B.default.data}, ${WZ(s)}`,n.$async,()=>t.code(rk(r,s)).code(o))}function WZ(t){return(0,N._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${t.dynamicRef?(0,N._)`, ${B.default.dynamicAnchors}={}`:N.nil}}={}`}function HZ(t,e){t.if(B.default.valCxt,()=>{t.var(B.default.instancePath,(0,N._)`${B.default.valCxt}.${B.default.instancePath}`),t.var(B.default.parentData,(0,N._)`${B.default.valCxt}.${B.default.parentData}`),t.var(B.default.parentDataProperty,(0,N._)`${B.default.valCxt}.${B.default.parentDataProperty}`),t.var(B.default.rootData,(0,N._)`${B.default.valCxt}.${B.default.rootData}`),e.dynamicRef&&t.var(B.default.dynamicAnchors,(0,N._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{t.var(B.default.instancePath,(0,N._)`""`),t.var(B.default.parentData,(0,N._)`undefined`),t.var(B.default.parentDataProperty,(0,N._)`undefined`),t.var(B.default.rootData,B.default.data),e.dynamicRef&&t.var(B.default.dynamicAnchors,(0,N._)`{}`)})}function KZ(t){let{schema:e,opts:r,gen:n}=t;ik(t,()=>{r.$comment&&e.$comment&&dk(t),QZ(t),n.let(B.default.vErrors,null),n.let(B.default.errors,0),r.unevaluated&&JZ(t),lk(t),rV(t)})}function JZ(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,N._)`${r}.evaluated`),e.if((0,N._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,N._)`${t.evaluated}.props`,(0,N._)`undefined`)),e.if((0,N._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,N._)`${t.evaluated}.items`,(0,N._)`undefined`))}function rk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,N._)`/*# sourceURL=${r} */`:N.nil}function GZ(t,e){if(ck(t)&&(uk(t),ak(t))){YZ(t,e);return}(0,ok.boolOrEmptySchema)(t,e)}function ak({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 ck(t){return typeof t.schema!="boolean"}function YZ(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&dk(t),eV(t),tV(t);let o=n.const("_errs",B.default.errors);lk(t,o),n.var(e,(0,N._)`${o} === ${B.default.errors}`)}function uk(t){(0,Kr.checkUnknownRules)(t),XZ(t)}function lk(t,e){if(t.opts.jtd)return nk(t,[],!1,e);let r=(0,tk.getSchemaTypes)(t.schema),n=(0,tk.coerceAndCheckDataType)(t,r);nk(t,r,!n,e)}function XZ(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Kr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function QZ(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Kr.checkStrictMode)(t,"default is ignored in the schema root")}function eV(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,VZ.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function tV(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function dk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,N._)`${B.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,N.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,N._)`${B.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function rV(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,N._)`${B.default.errors} === 0`,()=>e.return(B.default.data),()=>e.throw((0,N._)`new ${s}(${B.default.vErrors})`)):(e.assign((0,N._)`${n}.errors`,B.default.vErrors),o.unevaluated&&nV(t),e.return((0,N._)`${B.default.errors} === 0`))}function nV({gen:t,evaluated:e,props:r,items:n}){r instanceof N.Name&&t.assign((0,N._)`${e}.props`,r),n instanceof N.Name&&t.assign((0,N._)`${e}.items`,n)}function nk(t,e,r,n){let{gen:s,schema:o,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(o.$ref&&(c.ignoreKeywordsWithRef||!(0,Kr.schemaHasRulesButRef)(o,l))){s.block(()=>fk(t,"$ref",l.all.$ref.definition));return}c.jtd||sV(t,e),s.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Wh.shouldUseGroup)(o,p)&&(p.type?(s.if((0,yl.checkDataType)(p.type,i,c.strictNumbers)),sk(t,p),e.length===1&&e[0]===p.type&&r&&(s.else(),(0,yl.reportTypeError)(t)),s.endIf()):sk(t,p),a||s.if((0,N._)`${B.default.errors} === ${n||0}`))}}function sk(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,ZZ.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,Wh.shouldUseRule)(n,o)&&fk(t,o.keyword,o.definition,e.type)})}function sV(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(oV(t,e),t.opts.allowUnionTypes||iV(t,e),aV(t,t.dataTypes))}function oV(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{pk(t.dataTypes,r)||Hh(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),uV(t,e)}}function iV(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Hh(t,"use allowUnionTypes to allow union type keyword")}function aV(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,Wh.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>cV(e,i))&&Hh(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function cV(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function pk(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function uV(t,e){let r=[];for(let n of t.dataTypes)pk(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Hh(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Kr.checkStrictMode)(t,e,t.opts.strictTypes)}var vl=class{constructor(e,r,n){if((0,Ma.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,Kr.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",mk(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ma.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",B.default.errors))}result(e,r,n){this.failResult((0,N.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,N.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,N._)`${r} !== undefined && (${(0,N.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?za.reportExtraError:za.reportError)(this,this.def.error,r)}$dataError(){(0,za.reportError)(this,this.def.$dataError||za.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,za.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=N.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=N.nil,r=N.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,N.or)((0,N._)`${s} === undefined`,r)),e!==N.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==N.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,N.or)(i(),a());function i(){if(n.length){if(!(r instanceof N.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,N._)`${(0,yl.checkDataTypes)(c,r,o.opts.strictNumbers,yl.DataType.Wrong)}`}return N.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,N._)`!${c}(${r})`}return N.nil}}subschema(e,r){let n=(0,Bh.getSubschema)(this.it,e);(0,Bh.extendSubschemaData)(n,this.it,e),(0,Bh.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return GZ(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Kr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Kr.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,N.Name)),!0}};Sn.KeywordCxt=vl;function fk(t,e,r,n){let s=new vl(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Ma.funcKeywordCode)(s,r):"macro"in r?(0,Ma.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Ma.funcKeywordCode)(s,r)}var lV=/^\/(?:[^~]|~0|~1)*$/,dV=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function mk(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return B.default.rootData;if(t[0]==="/"){if(!lV.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=B.default.rootData}else{let u=dV.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(s=u[2],s==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(o=r[e-l],!s)return o}let i=o,a=s.split("/");for(let u of a)u&&(o=(0,N._)`${o}${(0,N.getProperty)((0,Kr.unescapeJsonPointer)(u))}`,i=(0,N._)`${i} && ${o}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Sn.getData=mk});var _l=S(Jh=>{"use strict";Object.defineProperty(Jh,"__esModule",{value:!0});var Kh=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Jh.default=Kh});var ja=S(Xh=>{"use strict";Object.defineProperty(Xh,"__esModule",{value:!0});var Gh=Oa(),Yh=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Gh.resolveUrl)(e,r,n),this.missingSchema=(0,Gh.normalizeId)((0,Gh.getFullPath)(e,this.missingRef))}};Xh.default=Yh});var wl=S(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.resolveSchema=Yt.getCompilingSchema=Yt.resolveRef=Yt.compileSchema=Yt.SchemaEnv=void 0;var ur=X(),pV=_l(),vs=Hr(),lr=Oa(),hk=pe(),fV=Na(),zo=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,lr.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=zo;function eg(t){let e=gk.call(this,t);if(e)return e;let r=(0,lr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new ur.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:pV.default,code:(0,ur._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:vs.default.data,parentData:vs.default.parentData,parentDataProperty:vs.default.parentDataProperty,dataNames:[vs.default.data],dataPathArr:[ur.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ur.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ur.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ur._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,fV.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(vs.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${vs.default.self}`,`${vs.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:h}=u;f.evaluated={props:m instanceof ur.Name?void 0:m,items:h instanceof ur.Name?void 0:h,dynamicProps:m instanceof ur.Name,dynamicItems:h instanceof ur.Name},f.source&&(f.source.evaluated=(0,ur.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=eg;function mV(t,e,r){var n;r=(0,lr.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=yV.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(o=new zo({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=hV.call(this,o)}Yt.resolveRef=mV;function hV(t){return(0,lr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:eg.call(this,t)}function gk(t){for(let e of this._compilations)if(gV(e,t))return e}Yt.getCompilingSchema=gk;function gV(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function yV(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||bl.call(this,t,e)}function bl(t,e){let r=this.opts.uriResolver.parse(e),n=(0,lr._getFullPath)(this.opts.uriResolver,r),s=(0,lr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return Qh.call(this,r,t);let o=(0,lr.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=bl.call(this,t,i);return typeof a?.schema!="object"?void 0:Qh.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||eg.call(this,i),o===(0,lr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,lr.resolveUrl)(this.opts.uriResolver,s,u)),new zo({schema:a,schemaId:c,root:t,baseId:s})}return Qh.call(this,r,i)}}Yt.resolveSchema=bl;var vV=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Qh(t,{baseId:e,schema:r,root:n}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,hk.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!vV.has(a)&&u&&(e=(0,lr.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,hk.schemaHasRulesButRef)(r,this.RULES)){let a=(0,lr.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=bl.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new zo({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var yk=S((eee,_V)=>{_V.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 _k=S(tg=>{"use strict";Object.defineProperty(tg,"__esModule",{value:!0});var vk=ym();vk.code='require("ajv/dist/runtime/uri").default';tg.default=vk});var Ek=S(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.CodeGen=et.Name=et.nil=et.stringify=et.str=et._=et.KeywordCxt=void 0;var bV=Na();Object.defineProperty(et,"KeywordCxt",{enumerable:!0,get:function(){return bV.KeywordCxt}});var Mo=X();Object.defineProperty(et,"_",{enumerable:!0,get:function(){return Mo._}});Object.defineProperty(et,"str",{enumerable:!0,get:function(){return Mo.str}});Object.defineProperty(et,"stringify",{enumerable:!0,get:function(){return Mo.stringify}});Object.defineProperty(et,"nil",{enumerable:!0,get:function(){return Mo.nil}});Object.defineProperty(et,"Name",{enumerable:!0,get:function(){return Mo.Name}});Object.defineProperty(et,"CodeGen",{enumerable:!0,get:function(){return Mo.CodeGen}});var wV=_l(),xk=ja(),SV=Mh(),La=wl(),$V=X(),qa=Oa(),Sl=Da(),ng=pe(),bk=yk(),xV=_k(),Pk=(t,e)=>new RegExp(t,e);Pk.code="new RegExp";var PV=["removeAdditional","useDefaults","coerceTypes"],kV=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),EV={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."},TV={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},wk=200;function IV(t){var e,r,n,s,o,i,a,c,u,l,d,p,f,m,h,v,g,b,_,P,x,j,k,O,L;let q=t.strict,$e=(e=t.code)===null||e===void 0?void 0:e.optimize,He=$e===!0||$e===void 0?1:$e||0,Rt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Pk,Mt=(s=t.uriResolver)!==null&&s!==void 0?s:xV.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:q)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:q)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:q)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:q)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:q)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:He,regExp:Rt}:{optimize:He,regExp:Rt},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:wk,loopEnum:(v=t.loopEnum)!==null&&v!==void 0?v:wk,meta:(g=t.meta)!==null&&g!==void 0?g:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(P=t.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(x=t.addUsedSchema)!==null&&x!==void 0?x:!0,validateSchema:(j=t.validateSchema)!==null&&j!==void 0?j:!0,validateFormats:(k=t.validateFormats)!==null&&k!==void 0?k:!0,unicodeRegExp:(O=t.unicodeRegExp)!==null&&O!==void 0?O:!0,int32range:(L=t.int32range)!==null&&L!==void 0?L:!0,uriResolver:Mt}}var Fa=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...IV(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new $V.ValueScope({scope:{},prefixes:kV,es5:r,lines:n}),this.logger=zV(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,SV.getRules)(),Sk.call(this,EV,e,"NOT SUPPORTED"),Sk.call(this,TV,e,"DEPRECATED","warn"),this._metaOpts=DV.call(this),e.formats&&AV.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&CV.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),RV.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=bk;n==="id"&&(s={...bk},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[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 s=n(r);return"$async"in n||(this.errors=n.errors),s}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 s.call(this,e,r);async function s(l,d){await o.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function o(l){l&&!this.getSchema(l)&&await s.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof xk.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 o.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,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0,qa.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!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 s=this.validate(n,e);if(!s&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let r;for(;typeof(r=$k.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new La.SchemaEnv({schema:{},schemaId:n});if(r=La.resolveSchema.call(this,s,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=$k.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,qa.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(NV.call(this,n,r),!r)return(0,ng.eachItem)(n,o=>rg.call(this,o)),this;LV.call(this,r);let s={...r,type:(0,Sl.getJSONTypes)(r.type),schemaType:(0,Sl.getJSONTypes)(r.schemaType)};return(0,ng.eachItem)(n,s.type.length===0?o=>rg.call(this,o,s):o=>s.type.forEach(i=>rg.call(this,o,s,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 s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,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(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let a of o)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]=kk(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,s=this.opts.validateSchema,o=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,qa.normalizeId)(i||n);let u=qa.getSchemaRefs.call(this,e,n);return c=new La.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&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):La.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{La.compileSchema.call(this,e)}finally{this.opts=r}}};Fa.ValidationError=wV.default;Fa.MissingRefError=xk.default;et.default=Fa;function Sk(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function $k(t){return t=(0,qa.normalizeId)(t),this.schemas[t]||this.refs[t]}function RV(){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 AV(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function CV(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 DV(){let t={...this.opts};for(let e of PV)delete t[e];return t}var OV={log(){},warn(){},error(){}};function zV(t){if(t===!1)return OV;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 MV=/^[a-z_$][a-z0-9_$:-]*$/i;function NV(t,e){let{RULES:r}=this;if((0,ng.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!MV.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 rg(t,e,r){var n;let s=e?.post;if(r&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Sl.getJSONTypes)(e.type),schemaType:(0,Sl.getJSONTypes)(e.schemaType)}};e.before?jV.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function jV(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function LV(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=kk(e)),t.validateSchema=this.compile(e,!0))}var qV={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function kk(t){return{anyOf:[t,qV]}}});var Tk=S(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});var FV={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};sg.default=FV});var Ck=S(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});_s.callRef=_s.getValidate=void 0;var UV=ja(),Ik=Gt(),It=X(),No=Hr(),Rk=wl(),$l=pe(),ZV={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:c}=n,{root:u}=o;if((r==="#"||r==="#/")&&s===u.baseId)return d();let l=Rk.resolveRef.call(c,u,s,r);if(l===void 0)throw new UV.default(n.opts.uriResolver,s,r);if(l instanceof Rk.SchemaEnv)return p(l);return f(l);function d(){if(o===u)return xl(t,i,o,o.$async);let m=e.scopeValue("root",{ref:u});return xl(t,(0,It._)`${m}.validate`,u,u.$async)}function p(m){let h=Ak(t,m);xl(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,It.stringify)(m)}:{ref:m}),v=e.name("valid"),g=t.subschema({schema:m,dataTypes:[],schemaPath:It.nil,topSchemaRef:h,errSchemaPath:r},v);t.mergeEvaluated(g),t.ok(v)}}};function Ak(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,It._)`${r.scopeValue("wrapper",{ref:e})}.validate`}_s.getValidate=Ak;function xl(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?No.default.this:It.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=s.let("valid");s.try(()=>{s.code((0,It._)`await ${(0,Ik.callValidateCode)(t,e,u)}`),f(e),i||s.assign(m,!0)},h=>{s.if((0,It._)`!(${h} instanceof ${o.ValidationError})`,()=>s.throw(h)),p(h),i||s.assign(m,!1)}),t.ok(m)}function d(){t.result((0,Ik.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,It._)`${m}.errors`;s.assign(No.default.vErrors,(0,It._)`${No.default.vErrors} === null ? ${h} : ${No.default.vErrors}.concat(${h})`),s.assign(No.default.errors,(0,It._)`${No.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let v=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(v&&!v.dynamicProps)v.props!==void 0&&(o.props=$l.mergeEvaluated.props(s,v.props,o.props));else{let g=s.var("props",(0,It._)`${m}.evaluated.props`);o.props=$l.mergeEvaluated.props(s,g,o.props,It.Name)}if(o.items!==!0)if(v&&!v.dynamicItems)v.items!==void 0&&(o.items=$l.mergeEvaluated.items(s,v.items,o.items));else{let g=s.var("items",(0,It._)`${m}.evaluated.items`);o.items=$l.mergeEvaluated.items(s,g,o.items,It.Name)}}}_s.callRef=xl;_s.default=ZV});var Dk=S(og=>{"use strict";Object.defineProperty(og,"__esModule",{value:!0});var VV=Tk(),BV=Ck(),WV=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",VV.default,BV.default];og.default=WV});var Ok=S(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});var Pl=X(),$n=Pl.operators,kl={maximum:{okStr:"<=",ok:$n.LTE,fail:$n.GT},minimum:{okStr:">=",ok:$n.GTE,fail:$n.LT},exclusiveMaximum:{okStr:"<",ok:$n.LT,fail:$n.GTE},exclusiveMinimum:{okStr:">",ok:$n.GT,fail:$n.LTE}},HV={message:({keyword:t,schemaCode:e})=>(0,Pl.str)`must be ${kl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Pl._)`{comparison: ${kl[t].okStr}, limit: ${e}}`},KV={keyword:Object.keys(kl),type:"number",schemaType:"number",$data:!0,error:HV,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Pl._)`${r} ${kl[e].fail} ${n} || isNaN(${r})`)}};ig.default=KV});var zk=S(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});var Ua=X(),JV={message:({schemaCode:t})=>(0,Ua.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ua._)`{multipleOf: ${t}}`},GV={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:JV,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Ua._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Ua._)`${i} !== parseInt(${i})`;t.fail$data((0,Ua._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};ag.default=GV});var Nk=S(cg=>{"use strict";Object.defineProperty(cg,"__esModule",{value:!0});function Mk(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}cg.default=Mk;Mk.code='require("ajv/dist/runtime/ucs2length").default'});var jk=S(ug=>{"use strict";Object.defineProperty(ug,"__esModule",{value:!0});var bs=X(),YV=pe(),XV=Nk(),QV={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,bs.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,bs._)`{limit: ${t}}`},eB={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:QV,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?bs.operators.GT:bs.operators.LT,i=s.opts.unicode===!1?(0,bs._)`${r}.length`:(0,bs._)`${(0,YV.useFunc)(t.gen,XV.default)}(${r})`;t.fail$data((0,bs._)`${i} ${o} ${n}`)}};ug.default=eB});var Lk=S(lg=>{"use strict";Object.defineProperty(lg,"__esModule",{value:!0});var tB=Gt(),rB=pe(),jo=X(),nB={message:({schemaCode:t})=>(0,jo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,jo._)`{pattern: ${t}}`},sB={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:nB,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,jo._)`new RegExp`:(0,rB.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,jo._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,jo._)`!${l}`)}else{let c=(0,tB.usePattern)(t,s);t.fail$data((0,jo._)`!${c}.test(${r})`)}}};lg.default=sB});var qk=S(dg=>{"use strict";Object.defineProperty(dg,"__esModule",{value:!0});var Za=X(),oB={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Za.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Za._)`{limit: ${t}}`},iB={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:oB,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Za.operators.GT:Za.operators.LT;t.fail$data((0,Za._)`Object.keys(${r}).length ${s} ${n}`)}};dg.default=iB});var Fk=S(pg=>{"use strict";Object.defineProperty(pg,"__esModule",{value:!0});var Va=Gt(),Ba=X(),aB=pe(),cB={message:({params:{missingProperty:t}})=>(0,Ba.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ba._)`{missingProperty: ${t}}`},uB={keyword:"required",type:"object",schemaType:"array",$data:!0,error:cB,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&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 h of r)if(f?.[h]===void 0&&!m.has(h)){let v=i.schemaEnv.baseId+i.errSchemaPath,g=`required property "${h}" is not defined at "${v}" (strictRequired)`;(0,aB.checkStrictMode)(i,g,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(Ba.nil,d);else for(let f of r)(0,Va.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||o){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,Va.checkMissingProp)(t,r,f)),(0,Va.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Va.noPropertyInData)(e,s,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Va.propertyInData)(e,s,f,a.ownProperties)),e.if((0,Ba.not)(m),()=>{t.error(),e.break()})},Ba.nil)}}};pg.default=uB});var Uk=S(fg=>{"use strict";Object.defineProperty(fg,"__esModule",{value:!0});var Wa=X(),lB={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Wa.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Wa._)`{limit: ${t}}`},dB={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:lB,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Wa.operators.GT:Wa.operators.LT;t.fail$data((0,Wa._)`${r}.length ${s} ${n}`)}};fg.default=dB});var El=S(mg=>{"use strict";Object.defineProperty(mg,"__esModule",{value:!0});var Zk=oa();Zk.code='require("ajv/dist/runtime/equal").default';mg.default=Zk});var Vk=S(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var hg=Da(),tt=X(),pB=pe(),fB=El(),mB={message:({params:{i:t,j:e}})=>(0,tt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,tt._)`{i: ${t}, j: ${e}}`},hB={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:mB,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let c=e.let("valid"),u=o.items?(0,hg.getSchemaTypes)(o.items):[];t.block$data(c,l,(0,tt._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,tt._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,tt._)`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,h){let v=e.name("item"),g=(0,hg.checkDataTypes)(u,v,a.opts.strictNumbers,hg.DataType.Wrong),b=e.const("indices",(0,tt._)`{}`);e.for((0,tt._)`;${m}--;`,()=>{e.let(v,(0,tt._)`${r}[${m}]`),e.if(g,(0,tt._)`continue`),u.length>1&&e.if((0,tt._)`typeof ${v} == "string"`,(0,tt._)`${v} += "_"`),e.if((0,tt._)`typeof ${b}[${v}] == "number"`,()=>{e.assign(h,(0,tt._)`${b}[${v}]`),t.error(),e.assign(c,!1).break()}).code((0,tt._)`${b}[${v}] = ${m}`)})}function f(m,h){let v=(0,pB.useFunc)(e,fB.default),g=e.name("outer");e.label(g).for((0,tt._)`;${m}--;`,()=>e.for((0,tt._)`${h} = ${m}; ${h}--;`,()=>e.if((0,tt._)`${v}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(g)})))}}};gg.default=hB});var Bk=S(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});var yg=X(),gB=pe(),yB=El(),vB={message:"must be equal to constant",params:({schemaCode:t})=>(0,yg._)`{allowedValue: ${t}}`},_B={keyword:"const",$data:!0,error:vB,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,yg._)`!${(0,gB.useFunc)(e,yB.default)}(${r}, ${s})`):t.fail((0,yg._)`${o} !== ${r}`)}};vg.default=_B});var Wk=S(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});var Ha=X(),bB=pe(),wB=El(),SB={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ha._)`{allowedValues: ${t}}`},$B={keyword:"enum",schemaType:"array",$data:!0,error:SB,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,bB.useFunc)(e,wB.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let f=e.const("vSchema",o);l=(0,Ha.or)(...s.map((m,h)=>p(f,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",o,f=>e.if((0,Ha._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let h=s[m];return typeof h=="object"&&h!==null?(0,Ha._)`${u()}(${r}, ${f}[${m}])`:(0,Ha._)`${r} === ${h}`}}};_g.default=$B});var Hk=S(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});var xB=Ok(),PB=zk(),kB=jk(),EB=Lk(),TB=qk(),IB=Fk(),RB=Uk(),AB=Vk(),CB=Bk(),DB=Wk(),OB=[xB.default,PB.default,kB.default,EB.default,TB.default,IB.default,RB.default,AB.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},CB.default,DB.default];bg.default=OB});var Sg=S(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.validateAdditionalItems=void 0;var ws=X(),wg=pe(),zB={message:({params:{len:t}})=>(0,ws.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ws._)`{limit: ${t}}`},MB={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:zB,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,wg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Kk(t,n)}};function Kk(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,ws._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,ws._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,wg.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,ws._)`${a} <= ${e.length}`);r.if((0,ws.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:o,dataProp:l,dataPropType:wg.Type.Num},u),i.allErrors||r.if((0,ws.not)(u),()=>r.break())})}}Ka.validateAdditionalItems=Kk;Ka.default=MB});var $g=S(Ja=>{"use strict";Object.defineProperty(Ja,"__esModule",{value:!0});Ja.validateTuple=void 0;var Jk=X(),Tl=pe(),NB=Gt(),jB={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Gk(t,"additionalItems",e);r.items=!0,!(0,Tl.alwaysValidSchema)(r,e)&&t.ok((0,NB.validateArray)(t))}};function Gk(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=t;l(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Tl.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Jk._)`${o}.length`);r.forEach((d,p)=>{(0,Tl.alwaysValidSchema)(a,d)||(n.if((0,Jk._)`${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,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let v=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Tl.checkStrictMode)(a,v,p.strictTuples)}}}Ja.validateTuple=Gk;Ja.default=jB});var Yk=S(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var LB=$g(),qB={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,LB.validateTuple)(t,"items")};xg.default=qB});var Qk=S(Pg=>{"use strict";Object.defineProperty(Pg,"__esModule",{value:!0});var Xk=X(),FB=pe(),UB=Gt(),ZB=Sg(),VB={message:({params:{len:t}})=>(0,Xk.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Xk._)`{limit: ${t}}`},BB={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:VB,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,FB.alwaysValidSchema)(n,e)&&(s?(0,ZB.validateAdditionalItems)(t,s):t.ok((0,UB.validateArray)(t)))}};Pg.default=BB});var eE=S(kg=>{"use strict";Object.defineProperty(kg,"__esModule",{value:!0});var Xt=X(),Il=pe(),WB={message:({params:{min:t,max:e}})=>e===void 0?(0,Xt.str)`must contain at least ${t} valid item(s)`:(0,Xt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Xt._)`{minContains: ${t}}`:(0,Xt._)`{minContains: ${t}, maxContains: ${e}}`},HB={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:WB,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:c,maxContains:u}=n;o.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,Xt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Il.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Il.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Il.alwaysValidSchema)(o,r)){let h=(0,Xt._)`${l} >= ${i}`;a!==void 0&&(h=(0,Xt._)`${h} && ${l} <= ${a}`),t.pass(h);return}o.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,Xt._)`${s}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),v=e.let("count",0);f(h,()=>e.if(h,()=>m(v)))}function f(h,v){e.forRange("i",0,l,g=>{t.subschema({keyword:"contains",dataProp:g,dataPropType:Il.Type.Num,compositeRule:!0},h),v()})}function m(h){e.code((0,Xt._)`${h}++`),a===void 0?e.if((0,Xt._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Xt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Xt._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};kg.default=HB});var nE=S(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateSchemaDeps=Ir.validatePropertyDeps=Ir.error=void 0;var Eg=X(),KB=pe(),Ga=Gt();Ir.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Eg.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Eg._)`{property: ${t},
|
|
17
17
|
missingProperty: ${n},
|
|
18
18
|
depsCount: ${e},
|
|
19
|
-
deps: ${r}}`};var U9={keyword:"dependencies",type:"object",schemaType:"object",error:Pr.error,code(t){let[e,r]=Z9(t);KP(t,e),JP(t,r)}};function Z9({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 KP(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,Za.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,Za.checkReportMissingProp)(t,u)}):(r.if((0,Sg._)`${c} && (${(0,Za.checkMissingProp)(t,a,s)})`),(0,Za.reportMissingProp)(t,s),r.else())}}Pr.validatePropertyDeps=KP;function JP(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,F9.alwaysValidSchema)(s,e[a])||(r.if((0,Za.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))}Pr.validateSchemaDeps=JP;Pr.default=U9});var QP=$(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var YP=Q(),V9=pe(),B9={message:"property name must be valid",params:({params:t})=>(0,YP._)`{propertyName: ${t.propertyName}}`},W9={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:B9,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,V9.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,YP.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};xg.default=W9});var Pg=$(kg=>{"use strict";Object.defineProperty(kg,"__esModule",{value:!0});var xl=Ht(),ar=Q(),H9=Br(),kl=pe(),K9={message:"must NOT have additional properties",params:({params:t})=>(0,ar._)`{additionalProperty: ${t.additionalProperty}}`},J9={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:K9,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,kl.alwaysValidSchema)(i,r))return;let u=(0,xl.allSchemaProperties)(n.properties),l=(0,xl.allSchemaProperties)(n.patternProperties);d(),t.ok((0,ar._)`${s} === ${H9.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 b=(0,kl.schemaRefOrVal)(i,n.properties,"properties");v=(0,xl.isOwnProperty)(e,b,y)}else u.length?v=(0,ar.or)(...u.map(b=>(0,ar._)`${y} === ${b}`)):v=ar.nil;return l.length&&(v=(0,ar.or)(v,...l.map(b=>(0,ar._)`${(0,xl.usePattern)(t,b)}.test(${y})`))),(0,ar.not)(v)}function f(y){e.code((0,ar._)`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,kl.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(h(y,v,!1),e.if((0,ar.not)(v),()=>{t.reset(),f(y)})):(h(y,v),a||e.if((0,ar.not)(v),()=>e.break()))}}function h(y,v,b){let _={keyword:"additionalProperties",dataProp:y,dataPropType:kl.Type.Str};b===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,v)}}};kg.default=J9});var tE=$(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});var G9=Ia(),XP=Ht(),Eg=pe(),eE=Pg(),Y9={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&&eE.default.code(new G9.KeywordCxt(s,eE.default,"additionalProperties"));let i=(0,XP.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Eg.mergeEvaluated.props(e,(0,Eg.toHash)(i),s.props));let a=i.filter(d=>!(0,Eg.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,XP.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)}}};Tg.default=Y9});var sE=$(Rg=>{"use strict";Object.defineProperty(Rg,"__esModule",{value:!0});var rE=Ht(),Pl=Q(),nE=pe(),oE=pe(),Q9={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,rE.allSchemaProperties)(r),c=a.filter(h=>(0,nE.alwaysValidSchema)(s,r[h]));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 Pl.Name)&&(s.props=(0,oE.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let h of a)u&&f(h),s.allErrors?m(h):(e.var(l,!0),m(h),e.if(l))}function f(h){for(let y in u)new RegExp(h).test(y)&&(0,nE.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,Pl._)`${(0,rE.usePattern)(t,h)}.test(${y})`,()=>{let v=c.includes(h);v||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:oE.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Pl._)`${d}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,Pl.not)(l),()=>e.break())})})}}};Rg.default=Q9});var iE=$(Ig=>{"use strict";Object.defineProperty(Ig,"__esModule",{value:!0});var X9=pe(),eB={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,X9.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"}};Ig.default=eB});var aE=$(Ag=>{"use strict";Object.defineProperty(Ag,"__esModule",{value:!0});var tB=Ht(),rB={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:tB.validateUnion,error:{message:"must match a schema in anyOf"}};Ag.default=rB});var cE=$(Cg=>{"use strict";Object.defineProperty(Cg,"__esModule",{value:!0});var El=Q(),nB=pe(),oB={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,El._)`{passingSchemas: ${t.passing}}`},sB={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:oB,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,nB.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,El._)`${c} && ${i}`).assign(i,!1).assign(a,(0,El._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,El.Name)})})}}};Cg.default=sB});var uE=$(Dg=>{"use strict";Object.defineProperty(Dg,"__esModule",{value:!0});var iB=pe(),aB={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,iB.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Dg.default=aB});var pE=$(Og=>{"use strict";Object.defineProperty(Og,"__esModule",{value:!0});var Tl=Q(),dE=pe(),cB={message:({params:t})=>(0,Tl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Tl._)`{failingKeyword: ${t.ifClause}}`},uB={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:cB,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,dE.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=lE(n,"then"),s=lE(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,Tl.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,Tl._)`${l}`):t.setParams({ifClause:l})}}}};function lE(t,e){let r=t.schema[e];return r!==void 0&&!(0,dE.alwaysValidSchema)(t,r)}Og.default=uB});var fE=$(zg=>{"use strict";Object.defineProperty(zg,"__esModule",{value:!0});var lB=pe(),dB={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,lB.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};zg.default=dB});var mE=$(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});var pB=vg(),fB=VP(),mB=_g(),hB=WP(),gB=HP(),yB=GP(),vB=QP(),_B=Pg(),bB=tE(),wB=sE(),$B=iE(),SB=aE(),xB=cE(),kB=uE(),PB=pE(),EB=fE();function TB(t=!1){let e=[$B.default,SB.default,xB.default,kB.default,PB.default,EB.default,vB.default,_B.default,yB.default,bB.default,wB.default];return t?e.push(fB.default,hB.default):e.push(pB.default,mB.default),e.push(gB.default),e}Ng.default=TB});var hE=$(jg=>{"use strict";Object.defineProperty(jg,"__esModule",{value:!0});var Ze=Q(),RB={message:({schemaCode:t})=>(0,Ze.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ze._)`{format: ${t}}`},IB={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:RB,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}),h=r.const("fDef",(0,Ze._)`${m}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,Ze._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,Ze._)`${h}.type || "string"`).assign(v,(0,Ze._)`${h}.validate`),()=>r.assign(y,(0,Ze._)`"string"`).assign(v,h)),t.fail$data((0,Ze.or)(b(),_()));function b(){return c.strictSchema===!1?Ze.nil:(0,Ze._)`${i} && !${v}`}function _(){let k=l.$async?(0,Ze._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Ze._)`${v}(${n})`,x=(0,Ze._)`(typeof ${v} == "function" ? ${k} : ${v}.test(${n}))`;return(0,Ze._)`${v} && ${v} !== true && ${y} === ${e} && !${x}`}}function f(){let m=d.formats[s];if(!m){b();return}if(m===!0)return;let[h,y,v]=_(m);h===e&&t.pass(k());function b(){if(c.strictSchema===!1){d.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function _(x){let L=x instanceof RegExp?(0,Ze.regexpCode)(x):c.code.formats?(0,Ze._)`${c.code.formats}${(0,Ze.getProperty)(s)}`:void 0,P=r.scopeValue("formats",{key:s,ref:x,code:L});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,Ze._)`${P}.validate`]:["string",x,P]}function k(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ze._)`await ${v}(${n})`}return typeof y=="function"?(0,Ze._)`${v}(${n})`:(0,Ze._)`${v}.test(${n})`}}}};jg.default=IB});var gE=$(Mg=>{"use strict";Object.defineProperty(Mg,"__esModule",{value:!0});var AB=hE(),CB=[AB.default];Mg.default=CB});var yE=$(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.contentVocabulary=Is.metadataVocabulary=void 0;Is.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Is.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var _E=$(Lg=>{"use strict";Object.defineProperty(Lg,"__esModule",{value:!0});var DB=PP(),OB=qP(),zB=mE(),NB=gE(),vE=yE(),jB=[DB.default,OB.default,(0,zB.default)(),NB.default,vE.metadataVocabulary,vE.contentVocabulary];Lg.default=jB});var wE=$(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.DiscrError=void 0;var bE;(function(t){t.Tag="tag",t.Mapping="mapping"})(bE||(Rl.DiscrError=bE={}))});var SE=$(Fg=>{"use strict";Object.defineProperty(Fg,"__esModule",{value:!0});var As=Q(),qg=wE(),$E=hl(),MB=Aa(),LB=pe(),qB={message:({params:{discrError:t,tagName:e}})=>t===qg.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,As._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},FB={keyword:"discriminator",type:"object",schemaType:"object",error:qB,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,As._)`${r}${(0,As.getProperty)(a)}`);e.if((0,As._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:qg.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,As._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:qg.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,As.Name),m}function p(){var f;let m={},h=v(o),y=!0;for(let k=0;k<i.length;k++){let x=i[k];if(x?.$ref&&!(0,LB.schemaHasRulesButRef)(x,s.self.RULES)){let P=x.$ref;if(x=$E.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,P),x instanceof $E.SchemaEnv&&(x=x.schema),x===void 0)throw new MB.default(s.opts.uriResolver,s.baseId,P)}let L=(f=x?.properties)===null||f===void 0?void 0:f[a];if(typeof L!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||v(x)),b(L,k)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function v({required:k}){return Array.isArray(k)&&k.includes(a)}function b(k,x){if(k.const)_(k.const,x);else if(k.enum)for(let L of k.enum)_(L,x);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(k,x){if(typeof k!="string"||k in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[k]=x}}}};Fg.default=FB});var xE=$((Tee,UB)=>{UB.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 PE=$((Ce,Ug)=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.MissingRefError=Ce.ValidationError=Ce.CodeGen=Ce.Name=Ce.nil=Ce.stringify=Ce.str=Ce._=Ce.KeywordCxt=Ce.Ajv=void 0;var ZB=bP(),VB=_E(),BB=SE(),kE=xE(),WB=["/properties"],Il="http://json-schema.org/draft-07/schema",Cs=class extends ZB.default{_addVocabularies(){super._addVocabularies(),VB.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(BB.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(kE,WB):kE;this.addMetaSchema(e,Il,!1),this.refs["http://json-schema.org/schema"]=Il}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Il)?Il:void 0)}};Ce.Ajv=Cs;Ug.exports=Ce=Cs;Ug.exports.Ajv=Cs;Object.defineProperty(Ce,"__esModule",{value:!0});Ce.default=Cs;var HB=Ia();Object.defineProperty(Ce,"KeywordCxt",{enumerable:!0,get:function(){return HB.KeywordCxt}});var Ds=Q();Object.defineProperty(Ce,"_",{enumerable:!0,get:function(){return Ds._}});Object.defineProperty(Ce,"str",{enumerable:!0,get:function(){return Ds.str}});Object.defineProperty(Ce,"stringify",{enumerable:!0,get:function(){return Ds.stringify}});Object.defineProperty(Ce,"nil",{enumerable:!0,get:function(){return Ds.nil}});Object.defineProperty(Ce,"Name",{enumerable:!0,get:function(){return Ds.Name}});Object.defineProperty(Ce,"CodeGen",{enumerable:!0,get:function(){return Ds.CodeGen}});var KB=fl();Object.defineProperty(Ce,"ValidationError",{enumerable:!0,get:function(){return KB.default}});var JB=Aa();Object.defineProperty(Ce,"MissingRefError",{enumerable:!0,get:function(){return JB.default}})});var EE=$(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.formatLimitDefinition=void 0;var GB=PE(),cr=Q(),$n=cr.operators,Al={formatMaximum:{okStr:"<=",ok:$n.LTE,fail:$n.GT},formatMinimum:{okStr:">=",ok:$n.GTE,fail:$n.LT},formatExclusiveMaximum:{okStr:"<",ok:$n.LT,fail:$n.GTE},formatExclusiveMinimum:{okStr:">",ok:$n.GT,fail:$n.LTE}},YB={message:({keyword:t,schemaCode:e})=>(0,cr.str)`should be ${Al[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,cr._)`{comparison: ${Al[t].okStr}, limit: ${e}}`};Os.formatLimitDefinition={keyword:Object.keys(Al),type:"string",schemaType:"string",$data:!0,error:YB,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 GB.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,cr._)`${p}[${c.schemaCode}]`);t.fail$data((0,cr.or)((0,cr._)`typeof ${f} != "object"`,(0,cr._)`${f} instanceof RegExp`,(0,cr._)`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,cr._)`${i.code.formats}${(0,cr.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,cr._)`${p}.compare(${r}, ${n}) ${Al[o].fail} 0`}},dependencies:["format"]};var QB=t=>(t.addKeyword(Os.formatLimitDefinition),t);Os.default=QB});var AE=$((Va,IE)=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});var zs=pk(),XB=EE(),Zg=Q(),TE=new Zg.Name("fullFormats"),e2=new Zg.Name("fastFormats"),Vg=(t,e={keywords:!0})=>{if(Array.isArray(e))return RE(t,e,zs.fullFormats,TE),t;let[r,n]=e.mode==="fast"?[zs.fastFormats,e2]:[zs.fullFormats,TE],o=e.formats||zs.formatNames;return RE(t,o,r,n),e.keywords&&(0,XB.default)(t),t};Vg.get=(t,e="full")=>{let n=(e==="fast"?zs.fastFormats:zs.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function RE(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Zg._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}IE.exports=Va=Vg;Object.defineProperty(Va,"__esModule",{value:!0});Va.default=Vg});import{readFileSync as _H}from"fs";import{join as Ay}from"path";import{fileURLToPath as bH}from"url";var wo=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},Ga=class extends wo{code="PROVIDER_NOT_FOUND";retryable=!1;constructor(e){super(e,`Provider not found: ${e}`)}},Se=class extends wo{code="PROVIDER_UNAVAILABLE";retryable=!1;constructor(e,r){super(e,`Provider unavailable: ${r||"not installed or not running"}`)}};var $o=class extends wo{timeoutMs;code="PROVIDER_TIMEOUT";retryable=!0;constructor(e,r){super(e,`Timeout after ${r}ms`),this.timeoutMs=r}},dt=class extends wo{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(e,r){super(e,`Execution error: ${r}`)}};var Qy={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"}},hI={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 Pd(t){return t<3?"simple":t<8?"moderate":t<=20?"complex":"advanced"}function Xa(t,e,r,n=t){let o=Qy[n]??Qy[t]??{},s=o.maxComplexity??"simple";return n==="ollama"&&r!==void 0&&(s=Pd(r)),{providerId:t,tier:o.tier??"tool",strengths:o.strengths??e.strengths,maxComplexity:s}}function Gr(t,e){let r=hI[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 ec={low:0,medium:.5,high:.7},gI={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 Xy(t,e){return e?.[t]??gI[t]??"low"}function tc(t,e,r=ec){return t>=r[e]}var rc=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 Ga(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 Xa(r.id,r.getCapabilities(),void 0,r.type)}getDescriptor(e){let r=this.get(e);return r.getDescriptor?.()??Gr(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??Xy(e),a=r.getQualityStats(30),c=new Map;for(let[p,f]of a){let m=p.split(":")[0],h=c.get(m)??{totalScore:0,count:0};h.totalScore+=f.avgScore*f.count,h.count+=f.count,c.set(m,h)}let u=s.filter(p=>{let f=c.get(p.id);if(!f)return i==="low";let m=f.totalScore/f.count;return tc(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 g={};lt(g,{BRAND:()=>UI,DIRTY:()=>En,EMPTY_PATH:()=>bI,INVALID:()=>F,NEVER:()=>PA,OK:()=>tt,ParseStatus:()=>Ke,Schema:()=>Y,ZodAny:()=>Xr,ZodArray:()=>Cr,ZodBigInt:()=>Rn,ZodBoolean:()=>In,ZodBranded:()=>Qs,ZodCatch:()=>Fn,ZodDate:()=>An,ZodDefault:()=>qn,ZodDiscriminatedUnion:()=>sc,ZodEffects:()=>jt,ZodEnum:()=>Mn,ZodError:()=>_t,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>ac,ZodIntersection:()=>zn,ZodIssueCode:()=>E,ZodLazy:()=>Nn,ZodLiteral:()=>jn,ZodMap:()=>Do,ZodNaN:()=>zo,ZodNativeEnum:()=>Ln,ZodNever:()=>Gt,ZodNull:()=>Dn,ZodNullable:()=>mr,ZodNumber:()=>Tn,ZodObject:()=>bt,ZodOptional:()=>zt,ZodParsedType:()=>I,ZodPipeline:()=>Xs,ZodPromise:()=>en,ZodReadonly:()=>Un,ZodRecord:()=>ic,ZodSchema:()=>Y,ZodSet:()=>Oo,ZodString:()=>Qr,ZodSymbol:()=>Ao,ZodTransformer:()=>jt,ZodTuple:()=>fr,ZodType:()=>Y,ZodUndefined:()=>Cn,ZodUnion:()=>On,ZodUnknown:()=>Ar,ZodVoid:()=>Co,addIssueToContext:()=>R,any:()=>YI,array:()=>tA,bigint:()=>WI,boolean:()=>lv,coerce:()=>kA,custom:()=>av,date:()=>HI,datetimeRegex:()=>sv,defaultErrorMap:()=>Rr,discriminatedUnion:()=>sA,effect:()=>yA,enum:()=>mA,function:()=>dA,getErrorMap:()=>To,getParsedType:()=>pr,instanceof:()=>VI,intersection:()=>iA,isAborted:()=>nc,isAsync:()=>Ro,isDirty:()=>oc,isValid:()=>Yr,late:()=>ZI,lazy:()=>pA,literal:()=>fA,makeIssue:()=>Ys,map:()=>uA,nan:()=>BI,nativeEnum:()=>hA,never:()=>XI,null:()=>GI,nullable:()=>_A,number:()=>uv,object:()=>rA,objectUtil:()=>Ed,oboolean:()=>xA,onumber:()=>SA,optional:()=>vA,ostring:()=>$A,pipeline:()=>wA,preprocess:()=>bA,promise:()=>gA,quotelessJson:()=>yI,record:()=>cA,set:()=>lA,setErrorMap:()=>_I,strictObject:()=>nA,string:()=>cv,symbol:()=>KI,transformer:()=>yA,tuple:()=>aA,undefined:()=>JI,union:()=>oA,unknown:()=>QI,util:()=>oe,void:()=>eA});var oe;(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})(oe||(oe={}));var Ed;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ed||(Ed={}));var I=oe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),pr=t=>{switch(typeof t){case"undefined":return I.undefined;case"string":return I.string;case"number":return Number.isNaN(t)?I.nan:I.number;case"boolean":return I.boolean;case"function":return I.function;case"bigint":return I.bigint;case"symbol":return I.symbol;case"object":return Array.isArray(t)?I.array:t===null?I.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?I.promise:typeof Map<"u"&&t instanceof Map?I.map:typeof Set<"u"&&t instanceof Set?I.set:typeof Date<"u"&&t instanceof Date?I.date:I.object;default:return I.unknown}};var E=oe.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"]),yI=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),_t=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,oe.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()}};_t.create=t=>new _t(t);var vI=(t,e)=>{let r;switch(t.code){case E.invalid_type:t.received===I.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,oe.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:r=`Unrecognized key(s) in object: ${oe.joinValues(t.keys,", ")}`;break;case E.invalid_union:r="Invalid input";break;case E.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${oe.joinValues(t.options)}`;break;case E.invalid_enum_value:r=`Invalid enum value. Expected ${oe.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:r="Invalid function arguments";break;case E.invalid_return_type:r="Invalid function return type";break;case E.invalid_date:r="Invalid date";break;case E.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}"`:oe.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case E.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 E.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 E.custom:r="Invalid input";break;case E.invalid_intersection_types:r="Intersection results could not be merged";break;case E.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:r="Number must be finite";break;default:r=e.defaultError,oe.assertNever(t)}return{message:r}},Rr=vI;var ev=Rr;function _I(t){ev=t}function To(){return ev}var Ys=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}},bI=[];function R(t,e){let r=To(),n=Ys({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Rr?void 0:Rr].filter(o=>!!o)});t.common.issues.push(n)}var Ke=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 F;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 F;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}}},F=Object.freeze({status:"aborted"}),En=t=>({status:"dirty",value:t}),tt=t=>({status:"valid",value:t}),nc=t=>t.status==="aborted",oc=t=>t.status==="dirty",Yr=t=>t.status==="valid",Ro=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 Nt=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}},tv=(t,e)=>{if(Yr(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 _t(t.common.issues);return this._error=r,this._error}}};function W(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 Y=class{get description(){return this._def.description}_getType(e){return pr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:pr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ke,ctx:{common:e.parent.common,data:e.data,parsedType:pr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ro(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:pr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return tv(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Yr(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=>Yr(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:pr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Ro(o)?o:Promise.resolve(o));return tv(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:E.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 jt({schema:this,typeName:T.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 zt.create(this,this._def)}nullable(){return mr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Cr.create(this)}promise(){return en.create(this,this._def)}or(e){return On.create([this,e],this._def)}and(e){return zn.create(this,e,this._def)}transform(e){return new jt({...W(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new qn({...W(this._def),innerType:this,defaultValue:r,typeName:T.ZodDefault})}brand(){return new Qs({typeName:T.ZodBranded,type:this,...W(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Fn({...W(this._def),innerType:this,catchValue:r,typeName:T.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Xs.create(this,e)}readonly(){return Un.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},wI=/^c[^\s-]{8,}$/i,$I=/^[0-9a-z]+$/,SI=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xI=/^[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,kI=/^[a-z0-9_-]{21}$/i,PI=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,EI=/^[-+]?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)?)??$/,TI=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,RI="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Td,II=/^(?:(?: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])$/,AI=/^(?:(?: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])$/,CI=/^(([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]))$/,DI=/^(([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])$/,OI=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,zI=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nv="((\\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])))",NI=new RegExp(`^${nv}$`);function ov(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 jI(t){return new RegExp(`^${ov(t)}$`)}function sv(t){let e=`${nv}T${ov(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 MI(t,e){return!!((e==="v4"||!e)&&II.test(t)||(e==="v6"||!e)&&CI.test(t))}function LI(t,e){if(!PI.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 qI(t,e){return!!((e==="v4"||!e)&&AI.test(t)||(e==="v6"||!e)&&DI.test(t))}var Qr=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==I.string){let s=this._getOrReturnCtx(e);return R(s,{code:E.invalid_type,expected:I.string,received:s.parsedType}),F}let n=new Ke,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),R(o,{code:E.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),R(o,{code:E.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?R(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&R(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")TI.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"email",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Td||(Td=new RegExp(RI,"u")),Td.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"emoji",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")xI.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"uuid",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")kI.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"nanoid",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")wI.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"cuid",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")$I.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"cuid2",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")SI.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"ulid",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),R(o,{validation:"url",code:E.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),R(o,{validation:"regex",code:E.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),R(o,{code:E.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),R(o,{code:E.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),R(o,{code:E.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?sv(s).test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{code:E.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?NI.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{code:E.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?jI(s).test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{code:E.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?EI.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"duration",code:E.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?MI(e.data,s.version)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"ip",code:E.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?LI(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"jwt",code:E.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?qI(e.data,s.version)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"cidr",code:E.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?OI.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"base64",code:E.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?zI.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"base64url",code:E.invalid_string,message:s.message}),n.dirty()):oe.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:E.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}};Qr.create=t=>new Qr({checks:[],typeName:T.ZodString,coerce:t?.coerce??!1,...W(t)});function FI(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 Tn=class t extends Y{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)!==I.number){let s=this._getOrReturnCtx(e);return R(s,{code:E.invalid_type,expected:I.number,received:s.parsedType}),F}let n,o=new Ke;for(let s of this._def.checks)s.kind==="int"?oe.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{code:E.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),R(n,{code:E.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),R(n,{code:E.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?FI(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),R(n,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{code:E.not_finite,message:s.message}),o.dirty()):oe.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"&&oe.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)}};Tn.create=t=>new Tn({checks:[],typeName:T.ZodNumber,coerce:t?.coerce||!1,...W(t)});var Rn=class t extends Y{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)!==I.bigint)return this._getInvalidInput(e);let n,o=new Ke;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),R(n,{code:E.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),R(n,{code:E.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),R(n,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):oe.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return R(r,{code:E.invalid_type,expected:I.bigint,received:r.parsedType}),F}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}};Rn.create=t=>new Rn({checks:[],typeName:T.ZodBigInt,coerce:t?.coerce??!1,...W(t)});var In=class extends Y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==I.boolean){let n=this._getOrReturnCtx(e);return R(n,{code:E.invalid_type,expected:I.boolean,received:n.parsedType}),F}return tt(e.data)}};In.create=t=>new In({typeName:T.ZodBoolean,coerce:t?.coerce||!1,...W(t)});var An=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==I.date){let s=this._getOrReturnCtx(e);return R(s,{code:E.invalid_type,expected:I.date,received:s.parsedType}),F}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return R(s,{code:E.invalid_date}),F}let n=new Ke,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),R(o,{code:E.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),R(o,{code:E.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):oe.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}};An.create=t=>new An({checks:[],coerce:t?.coerce||!1,typeName:T.ZodDate,...W(t)});var Ao=class extends Y{_parse(e){if(this._getType(e)!==I.symbol){let n=this._getOrReturnCtx(e);return R(n,{code:E.invalid_type,expected:I.symbol,received:n.parsedType}),F}return tt(e.data)}};Ao.create=t=>new Ao({typeName:T.ZodSymbol,...W(t)});var Cn=class extends Y{_parse(e){if(this._getType(e)!==I.undefined){let n=this._getOrReturnCtx(e);return R(n,{code:E.invalid_type,expected:I.undefined,received:n.parsedType}),F}return tt(e.data)}};Cn.create=t=>new Cn({typeName:T.ZodUndefined,...W(t)});var Dn=class extends Y{_parse(e){if(this._getType(e)!==I.null){let n=this._getOrReturnCtx(e);return R(n,{code:E.invalid_type,expected:I.null,received:n.parsedType}),F}return tt(e.data)}};Dn.create=t=>new Dn({typeName:T.ZodNull,...W(t)});var Xr=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return tt(e.data)}};Xr.create=t=>new Xr({typeName:T.ZodAny,...W(t)});var Ar=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return tt(e.data)}};Ar.create=t=>new Ar({typeName:T.ZodUnknown,...W(t)});var Gt=class extends Y{_parse(e){let r=this._getOrReturnCtx(e);return R(r,{code:E.invalid_type,expected:I.never,received:r.parsedType}),F}};Gt.create=t=>new Gt({typeName:T.ZodNever,...W(t)});var Co=class extends Y{_parse(e){if(this._getType(e)!==I.undefined){let n=this._getOrReturnCtx(e);return R(n,{code:E.invalid_type,expected:I.void,received:n.parsedType}),F}return tt(e.data)}};Co.create=t=>new Co({typeName:T.ZodVoid,...W(t)});var Cr=class t extends Y{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==I.array)return R(r,{code:E.invalid_type,expected:I.array,received:r.parsedType}),F;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(R(r,{code:i?E.too_big:E.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&&(R(r,{code:E.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&&(R(r,{code:E.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 Nt(r,i,r.path,a)))).then(i=>Ke.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Nt(r,i,r.path,a)));return Ke.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)}};Cr.create=(t,e)=>new Cr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...W(e)});function Io(t){if(t instanceof bt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=zt.create(Io(n))}return new bt({...t._def,shape:()=>e})}else return t instanceof Cr?new Cr({...t._def,type:Io(t.element)}):t instanceof zt?zt.create(Io(t.unwrap())):t instanceof mr?mr.create(Io(t.unwrap())):t instanceof fr?fr.create(t.items.map(e=>Io(e))):t}var bt=class t extends Y{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=oe.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==I.object){let u=this._getOrReturnCtx(e);return R(u,{code:E.invalid_type,expected:I.object,received:u.parsedType}),F}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Gt&&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 Nt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Gt){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&&(R(o,{code:E.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 Nt(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=>Ke.mergeObjectSync(n,u)):Ke.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:T.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 oe.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 oe.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Io(this)}partial(e){let r={};for(let n of oe.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 oe.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof zt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return iv(oe.objectKeys(this.shape))}};bt.create=(t,e)=>new bt({shape:()=>t,unknownKeys:"strip",catchall:Gt.create(),typeName:T.ZodObject,...W(e)});bt.strictCreate=(t,e)=>new bt({shape:()=>t,unknownKeys:"strict",catchall:Gt.create(),typeName:T.ZodObject,...W(e)});bt.lazycreate=(t,e)=>new bt({shape:t,unknownKeys:"strip",catchall:Gt.create(),typeName:T.ZodObject,...W(e)});var On=class extends Y{_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 _t(a.ctx.common.issues));return R(r,{code:E.invalid_union,unionErrors:i}),F}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 _t(c));return R(r,{code:E.invalid_union,unionErrors:a}),F}}get options(){return this._def.options}};On.create=(t,e)=>new On({options:t,typeName:T.ZodUnion,...W(e)});var Ir=t=>t instanceof Nn?Ir(t.schema):t instanceof jt?Ir(t.innerType()):t instanceof jn?[t.value]:t instanceof Mn?t.options:t instanceof Ln?oe.objectValues(t.enum):t instanceof qn?Ir(t._def.innerType):t instanceof Cn?[void 0]:t instanceof Dn?[null]:t instanceof zt?[void 0,...Ir(t.unwrap())]:t instanceof mr?[null,...Ir(t.unwrap())]:t instanceof Qs||t instanceof Un?Ir(t.unwrap()):t instanceof Fn?Ir(t._def.innerType):[],sc=class t extends Y{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==I.object)return R(r,{code:E.invalid_type,expected:I.object,received:r.parsedType}),F;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}):(R(r,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),F)}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=Ir(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:T.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...W(n)})}};function Rd(t,e){let r=pr(t),n=pr(e);if(t===e)return{valid:!0,data:t};if(r===I.object&&n===I.object){let o=oe.objectKeys(e),s=oe.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Rd(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===I.array&&n===I.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=Rd(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===I.date&&n===I.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var zn=class extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(nc(s)||nc(i))return F;let a=Rd(s.value,i.value);return a.valid?((oc(s)||oc(i))&&r.dirty(),{status:r.value,value:a.data}):(R(n,{code:E.invalid_intersection_types}),F)};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}))}};zn.create=(t,e,r)=>new zn({left:t,right:e,typeName:T.ZodIntersection,...W(r)});var fr=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.array)return R(n,{code:E.invalid_type,expected:I.array,received:n.parsedType}),F;if(n.data.length<this._def.items.length)return R(n,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),F;!this._def.rest&&n.data.length>this._def.items.length&&(R(n,{code:E.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 Nt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Ke.mergeArray(r,i)):Ke.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};fr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new fr({items:t,typeName:T.ZodTuple,rest:null,...W(e)})};var ic=class t extends Y{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!==I.object)return R(n,{code:E.invalid_type,expected:I.object,received:n.parsedType}),F;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Nt(n,a,n.path,a)),value:i._parse(new Nt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ke.mergeObjectAsync(r,o):Ke.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Y?new t({keyType:e,valueType:r,typeName:T.ZodRecord,...W(n)}):new t({keyType:Qr.create(),valueType:e,typeName:T.ZodRecord,...W(r)})}},Do=class extends Y{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!==I.map)return R(n,{code:E.invalid_type,expected:I.map,received:n.parsedType}),F;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new Nt(n,a,n.path,[u,"key"])),value:s._parse(new Nt(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 F;(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 F;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Do.create=(t,e,r)=>new Do({valueType:e,keyType:t,typeName:T.ZodMap,...W(r)});var Oo=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.set)return R(n,{code:E.invalid_type,expected:I.set,received:n.parsedType}),F;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(R(n,{code:E.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&&(R(n,{code:E.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 F;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 Nt(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)}};Oo.create=(t,e)=>new Oo({valueType:t,minSize:null,maxSize:null,typeName:T.ZodSet,...W(e)});var ac=class t extends Y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==I.function)return R(r,{code:E.invalid_type,expected:I.function,received:r.parsedType}),F;function n(a,c){return Ys({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,To(),Rr].filter(u=>!!u),issueData:{code:E.invalid_arguments,argumentsError:c}})}function o(a,c){return Ys({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,To(),Rr].filter(u=>!!u),issueData:{code:E.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof en){let a=this;return tt(async function(...c){let u=new _t([]),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 tt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new _t([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new _t([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:fr.create(e).rest(Ar.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||fr.create([]).rest(Ar.create()),returns:r||Ar.create(),typeName:T.ZodFunction,...W(n)})}},Nn=class extends Y{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})}};Nn.create=(t,e)=>new Nn({getter:t,typeName:T.ZodLazy,...W(e)});var jn=class extends Y{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return R(r,{received:r.data,code:E.invalid_literal,expected:this._def.value}),F}return{status:"valid",value:e.data}}get value(){return this._def.value}};jn.create=(t,e)=>new jn({value:t,typeName:T.ZodLiteral,...W(e)});function iv(t,e){return new Mn({values:t,typeName:T.ZodEnum,...W(e)})}var Mn=class t extends Y{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return R(r,{expected:oe.joinValues(n),received:r.parsedType,code:E.invalid_type}),F}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 R(r,{received:r.data,code:E.invalid_enum_value,options:n}),F}return tt(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})}};Mn.create=iv;var Ln=class extends Y{_parse(e){let r=oe.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==I.string&&n.parsedType!==I.number){let o=oe.objectValues(r);return R(n,{expected:oe.joinValues(o),received:n.parsedType,code:E.invalid_type}),F}if(this._cache||(this._cache=new Set(oe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=oe.objectValues(r);return R(n,{received:n.data,code:E.invalid_enum_value,options:o}),F}return tt(e.data)}get enum(){return this._def.values}};Ln.create=(t,e)=>new Ln({values:t,typeName:T.ZodNativeEnum,...W(e)});var en=class extends Y{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==I.promise&&r.common.async===!1)return R(r,{code:E.invalid_type,expected:I.promise,received:r.parsedType}),F;let n=r.parsedType===I.promise?r.data:Promise.resolve(r.data);return tt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};en.create=(t,e)=>new en({type:t,typeName:T.ZodPromise,...W(e)});var jt=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===T.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=>{R(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 F;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?F:c.status==="dirty"?En(c.value):r.value==="dirty"?En(c.value):c});{if(r.value==="aborted")return F;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?F:a.status==="dirty"?En(a.value):r.value==="dirty"?En(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"?F:(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"?F:(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(!Yr(i))return F;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=>Yr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):F);oe.assertNever(o)}};jt.create=(t,e,r)=>new jt({schema:t,typeName:T.ZodEffects,effect:e,...W(r)});jt.createWithPreprocess=(t,e,r)=>new jt({schema:e,effect:{type:"preprocess",transform:t},typeName:T.ZodEffects,...W(r)});var zt=class extends Y{_parse(e){return this._getType(e)===I.undefined?tt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};zt.create=(t,e)=>new zt({innerType:t,typeName:T.ZodOptional,...W(e)});var mr=class extends Y{_parse(e){return this._getType(e)===I.null?tt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};mr.create=(t,e)=>new mr({innerType:t,typeName:T.ZodNullable,...W(e)});var qn=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===I.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};qn.create=(t,e)=>new qn({innerType:t,typeName:T.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...W(e)});var Fn=class extends Y{_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 Ro(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Fn.create=(t,e)=>new Fn({innerType:t,typeName:T.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...W(e)});var zo=class extends Y{_parse(e){if(this._getType(e)!==I.nan){let n=this._getOrReturnCtx(e);return R(n,{code:E.invalid_type,expected:I.nan,received:n.parsedType}),F}return{status:"valid",value:e.data}}};zo.create=t=>new zo({typeName:T.ZodNaN,...W(t)});var UI=Symbol("zod_brand"),Qs=class extends Y{_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}},Xs=class t extends Y{_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"?F:s.status==="dirty"?(r.dirty(),En(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"?F: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:T.ZodPipeline})}},Un=class extends Y{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Yr(o)&&(o.value=Object.freeze(o.value)),o);return Ro(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Un.create=(t,e)=>new Un({innerType:t,typeName:T.ZodReadonly,...W(e)});function rv(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function av(t,e={},r){return t?Xr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=rv(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=rv(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Xr.create()}var ZI={object:bt.lazycreate},T;(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"})(T||(T={}));var VI=(t,e={message:`Input not instance of ${t.name}`})=>av(r=>r instanceof t,e),cv=Qr.create,uv=Tn.create,BI=zo.create,WI=Rn.create,lv=In.create,HI=An.create,KI=Ao.create,JI=Cn.create,GI=Dn.create,YI=Xr.create,QI=Ar.create,XI=Gt.create,eA=Co.create,tA=Cr.create,rA=bt.create,nA=bt.strictCreate,oA=On.create,sA=sc.create,iA=zn.create,aA=fr.create,cA=ic.create,uA=Do.create,lA=Oo.create,dA=ac.create,pA=Nn.create,fA=jn.create,mA=Mn.create,hA=Ln.create,gA=en.create,yA=jt.create,vA=zt.create,_A=mr.create,bA=jt.createWithPreprocess,wA=Xs.create,$A=()=>cv().optional(),SA=()=>uv().optional(),xA=()=>lv().optional(),kA={string:(t=>Qr.create({...t,coerce:!0})),number:(t=>Tn.create({...t,coerce:!0})),boolean:(t=>In.create({...t,coerce:!0})),bigint:(t=>Rn.create({...t,coerce:!0})),date:(t=>An.create({...t,coerce:!0}))};var PA=F;Tr();var EA=g.enum(["read-only","workspace-write","full-auto"]),TA=EA.default("read-only"),RA=g.object({id:g.string(),type:g.string(),enabled:g.boolean().default(!0),executionPolicy:TA,config:g.record(g.unknown()).default({})}),IA=g.enum(["default-only","auto"]).default("default-only"),AA=g.object({selectionPolicy:IA,locale:g.string().optional(),providers:g.array(RA).min(1,"At least one provider required")});function Dr(t){switch(t){case"ollama":case"gemini-cli":case"codex-cli":case"claude-cli":return"workspace-write";default:return"read-only"}}function cc(t){return t==="workspace-write"||t==="full-auto"}function CA(t){return Ya.includes(t)}function DA(t){if(t!==void 0)return CA(t)?t:(console.warn(`[config] unknown locale '${t}', falling back to ${kn}`),kn)}function dv(t){let e=AA.parse(t);return{selectionPolicy:e.selectionPolicy,locale:DA(e.locale),providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}import{existsSync as pv,mkdirSync as OA}from"fs";import{homedir as zA}from"os";import{dirname as NA,join as fv}from"path";var mv="providers.config.json";function ei(){let t=process.env.AGESTRA_CONFIG_PATH;if(t&&t.length>0)return t;let e=fv(zA(),".agestra",mv);if(pv(e))return e;let r=process.env.CLAUDE_PLUGIN_ROOT,n=r&&r.length>0?fv(r,mv):void 0;return n&&pv(n)?n:e}function hv(t){OA(NA(t),{recursive:!0})}tn();dc();No();Js();import{mkdirSync as Nv,readFileSync as hr,readdirSync as jv,existsSync as Ct}from"fs";import{join as qe}from"path";import{spawn as wC}from"child_process";import{randomUUID as $C}from"crypto";tn();qd();ni();import{readFileSync as Tv}from"fs";import{join as mc}from"path";function hc(t){Promise.resolve().then(()=>(Ev(),Pv)).then(async({resolveCliConfig:e})=>{let r;try{r=JSON.parse(Tv(mc(t,"job.json"),"utf-8"))}catch{return}let n=e(r);if(!n){We(t,{state:"missing_cli",completedAt:new Date().toISOString()}),ye(mc(t,"error.txt"),`No CLI mapping for provider: ${r.provider}`);return}let{command:o,buildArgs:s}=n,i=Tv(mc(t,"prompt.txt"),"utf-8"),a=s(i);We(t,{state:"running",startedAt:new Date().toISOString()}),await fc({jobDir:t,command:o,args:a,cwd:r.cwd||void 0,timeoutMs:r.timeout,recordPid:!0})}).catch(()=>{try{We(t,{state:"error",completedAt:new Date().toISOString()}),ye(mc(t,"error.txt"),"Failed to load job worker module")}catch{}})}import{existsSync as Rv,readFileSync as Iv,readdirSync as Av,unlinkSync as fC,rmdirSync as mC}from"fs";import{join as gc}from"path";var hC=["completed","error","timed_out","cancelled","missing_cli"];function Cv(t){let{jobsDir:e,maxJobs:r,maxAgeDays:n,statusCache:o,clearDeferredSaveTimer:s}=t;if(!Rv(e))return 0;let i;try{i=Av(e,{withFileTypes:!0}).filter(f=>f.isDirectory())}catch{return 0}let a=[];for(let f of i)try{let m=gc(e,f.name,"status.json"),h=gc(e,f.name,"job.json");if(!Rv(m))continue;let y=JSON.parse(Iv(m,"utf-8")),v=null;try{v=JSON.parse(Iv(h,"utf-8"))}catch{}a.push({name:f.name,status:y,descriptor:v})}catch{}let c=a.filter(f=>hC.includes(f.status.state)).sort((f,m)=>{let h=f.descriptor?.createdAt??"",y=m.descriptor?.createdAt??"";return h.localeCompare(y)}),u=0,l=Date.now(),d=n*24*60*60*1e3,p=a.length;for(let f of c){let h=(f.descriptor?.createdAt?l-new Date(f.descriptor.createdAt).getTime():1/0)>d,y=p-u>r;if(!h&&!y)continue;let v=gc(e,f.name);try{let b=Av(v);for(let _ of b)fC(gc(v,_));mC(v),o.delete(f.name),s(f.name),u++}catch{}}return u}tn();dc();No();import{existsSync as gC,readFileSync as Fd,readdirSync as yC}from"fs";import{join as Ud}from"path";function Dv(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Ov(t,e){let r=Ud(t,e,"job.json");try{let o=JSON.parse(Fd(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}function zv(t){let{jobsDir:e,statusCache:r}=t,n=0,o;try{o=yC(e)}catch{return 0}for(let s of o){if(!zr(s))continue;let i=Ud(e,s,"status.json");if(!gC(i))continue;let a;try{a=JSON.parse(Fd(i,"utf-8"))}catch{continue}if(a.state!=="running"||a.pid!==void 0&&Dv(a.pid))continue;let c=`${i}.lock`;try{let u=Zn(c,()=>{let l=JSON.parse(Fd(i,"utf-8"));if(l.state!=="running"||l.pid!==void 0&&Dv(l.pid))return null;let d={...l,state:"error",completedAt:new Date().toISOString()};return Ve(i,d),d});if(!u)continue;ye(Ud(e,s,"error.txt"),"orphaned (worker process died before completion)"),r.set(s,u),n++}catch{}}return n}ni();Tr();var SC=5e3,Zd=["completed","error","timed_out","cancelled","missing_cli"],yc=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=qe(e,Ny),Nv(this.jobsDir,{recursive:!0}),this.maxJobs=r?.maxJobs??100,this.maxAgeDays=r?.maxAgeDays??7,this.completionHandler=r?.completionHandler,this.submitCount=this.countExistingJobs()}countExistingJobs(){if(!Ct(this.jobsDir))return 0;try{return jv(this.jobsDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).length}catch{return 0}}reconcileOrphans(){return zv({jobsDir:this.jobsDir,statusCache:this.statusCache})}submit(e){let r=`${e.provider}-${Date.now()}-${$C().slice(0,6)}`,n=qe(this.jobsDir,r);Nv(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(Ve(qe(n,"job.json"),s),Ve(qe(n,"status.json"),i),ye(qe(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+SC);a.unref?.(),this.deferredSaveTimers.set(r,a)}return this.submitCount++,this.submitCount%10===0&&this.cleanup(),r}getStatus(e){if(!zr(e))return null;let r=this.statusCache.get(e);if(r&&Zd.includes(r.state)&&((r.savedDocumentId?!0:r.saveError!==void 0)||!this.completionHandler))return r;let n=qe(this.jobsDir,e,"status.json");if(!Ct(n))return null;let o=JSON.parse(hr(n,"utf-8"));if(o.state==="queued"){let s=Ov(this.jobsDir,e);if(s!==null&&Date.now()-s>6e4){let a=`${n}.lock`;try{let c=Zn(a,()=>{let u=JSON.parse(hr(n,"utf-8"));if(u.state!=="queued")return null;let l={...u,state:"error",completedAt:new Date().toISOString()};return Ve(n,l),l});if(c)return ye(qe(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),Zd.includes(o.state)&&!o.savedDocumentId&&!o.saveError&&this.completionHandler&&this.maybeTriggerCompletionSave(e).catch(()=>{}),o}getResult(e){if(!zr(e))return null;let r=this.getStatus(e);if(!r)return null;let n=qe(this.jobsDir,e),o={id:e,state:r.state,exitCode:r.exitCode,savedDocumentId:r.savedDocumentId,saveError:r.saveError},s=qe(n,"output.txt");Ct(s)&&(o.output=hr(s,"utf-8"));let i=qe(n,"error.txt");return Ct(i)&&(o.error=hr(i,"utf-8")),o}async getResultAwaited(e){return zr(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(!Ct(qe(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||!zr(e))return;let r=qe(this.jobsDir,e);if(!Ct(qe(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||!zr(e))return;let r=qe(this.jobsDir,e),n=qe(r,"status.json"),o=qe(r,"job.json");if(!Ct(n)||!Ct(o))return;let s=JSON.parse(hr(n,"utf-8"));if(!Zd.includes(s.state)||s.savedDocumentId||s.saveError)return;let i=JSON.parse(hr(o,"utf-8"));if(!i.saveAsDocument)return;let a={id:e,state:s.state,exitCode:s.exitCode},c=qe(r,"output.txt");Ct(c)&&(a.output=hr(c,"utf-8"));let u=qe(r,"error.txt");Ct(u)&&(a.error=hr(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};We(r,d),this.statusCache.set(e,{...s,...d})}else{let d={saveError:`skipped (state=${s.state})`};We(r,d),this.statusCache.set(e,{...s,...d})}}catch(l){let p={saveError:l instanceof Error?l.message:String(l)};try{We(r,p),this.statusCache.set(e,{...s,...p})}catch{}}}listJobs(){if(!Ct(this.jobsDir))return[];let e;try{e=jv(this.jobsDir,{withFileTypes:!0}).filter(n=>n.isDirectory())}catch{return[]}let r=[];for(let n of e)try{let o=qe(this.jobsDir,n.name,"status.json");Ct(o)&&r.push(JSON.parse(hr(o,"utf-8")))}catch{}return r}cancel(e){if(!zr(e))return!1;let r=this.getStatus(e);if(!r||r.state!=="queued"&&r.state!=="running")return!1;r.pid&&Po(r.pid);let n=qe(this.jobsDir,e),o=qe(n,"status.json"),s=`${o}.lock`;try{let i=Zn(s,()=>{let a=JSON.parse(hr(o,"utf-8"));if(a.state!=="queued"&&a.state!=="running")return null;let c={...a,state:"cancelled",completedAt:new Date().toISOString()};return Ve(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(){return Cv({jobsDir:this.jobsDir,maxJobs:this.maxJobs,maxAgeDays:this.maxAgeDays,statusCache:this.statusCache,clearDeferredSaveTimer:e=>this.clearDeferredSaveTimer(e)})}spawnWorker(e){let r=new URL("./job-worker.js",import.meta.url).pathname;if(Ct(r)){let n=wC(process.execPath,[r,e],{detached:!0,stdio:"ignore",cwd:this.workspaceDir}),o=typeof n.pid=="number"&&n.pid>0;if(o)try{We(e,{pid:n.pid})}catch{}n.on("error",s=>{if(o)return;s.code==="ENOENT"?hc(e):hc(e)}),n.unref()}else hc(e)}};tn();Tr();import{mkdirSync as xC,readdirSync as Mv,readFileSync as kC,unlinkSync as PC}from"fs";import{join as oi}from"path";function Lv(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 EC(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function TC(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var vc=class{tracesDir;writer;constructor(e,r){this.tracesDir=oi(e,jy),xC(this.tracesDir,{recursive:!0}),this.writer=new uc(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=Lv(new Date(r.timestamp)),o=oi(this.tracesDir,`${n}.jsonl`);this.writer.append(o,JSON.stringify(r)+`
|
|
20
|
-
`,"trace")}query(e={}){let r=this.listFiles(e.daysBack),n=[],
|
|
21
|
-
`).filter(Boolean);for(let c of a)try{let u=JSON.parse(c);
|
|
22
|
-
`,"audit")}shutdown(){this.writer.destroy()}panicFlush(){this.writer.panicFlush()}getQualityStats(e){let r=this.query({daysBack:e}),n=new Map;for(let
|
|
23
|
-
`),r=[];for(let n=0;n<e.length;n++){let
|
|
24
|
-
`);for(let r=0;r<e.length;r++){let n=e[r];for(let
|
|
25
|
-
`)}
|
|
26
|
-
`))i.startsWith("worktree ")?n=i.slice(9):i.startsWith("branch refs/heads/")?
|
|
27
|
-
`)}function
|
|
28
|
-
...[truncated]`:
|
|
29
|
-
`)}var
|
|
19
|
+
deps: ${r}}`};var JB={keyword:"dependencies",type:"object",schemaType:"object",error:Ir.error,code(t){let[e,r]=GB(t);tE(t,e),rE(t,r)}};function GB({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function tE(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Ga.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(c,()=>{for(let u of a)(0,Ga.checkReportMissingProp)(t,u)}):(r.if((0,Eg._)`${c} && (${(0,Ga.checkMissingProp)(t,a,o)})`),(0,Ga.reportMissingProp)(t,o),r.else())}}Ir.validatePropertyDeps=tE;function rE(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,KB.alwaysValidSchema)(o,e[a])||(r.if((0,Ga.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let c=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Ir.validateSchemaDeps=rE;Ir.default=JB});var oE=S(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});var sE=X(),YB=pe(),XB={message:"property name must be valid",params:({params:t})=>(0,sE._)`{propertyName: ${t.propertyName}}`},QB={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:XB,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,YB.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,sE.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Tg.default=QB});var Rg=S(Ig=>{"use strict";Object.defineProperty(Ig,"__esModule",{value:!0});var Rl=Gt(),dr=X(),e9=Hr(),Al=pe(),t9={message:"must NOT have additional properties",params:({params:t})=>(0,dr._)`{additionalProperty: ${t.additionalProperty}}`},r9={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:t9,code(t){let{gen:e,schema:r,parentSchema:n,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Al.alwaysValidSchema)(i,r))return;let u=(0,Rl.allSchemaProperties)(n.properties),l=(0,Rl.allSchemaProperties)(n.patternProperties);d(),t.ok((0,dr._)`${o} === ${e9.default.errors}`);function d(){e.forIn("key",s,v=>{!u.length&&!l.length?m(v):e.if(p(v),()=>m(v))})}function p(v){let g;if(u.length>8){let b=(0,Al.schemaRefOrVal)(i,n.properties,"properties");g=(0,Rl.isOwnProperty)(e,b,v)}else u.length?g=(0,dr.or)(...u.map(b=>(0,dr._)`${v} === ${b}`)):g=dr.nil;return l.length&&(g=(0,dr.or)(g,...l.map(b=>(0,dr._)`${(0,Rl.usePattern)(t,b)}.test(${v})`))),(0,dr.not)(g)}function f(v){e.code((0,dr._)`delete ${s}[${v}]`)}function m(v){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(v);return}if(r===!1){t.setParams({additionalProperty:v}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Al.alwaysValidSchema)(i,r)){let g=e.name("valid");c.removeAdditional==="failing"?(h(v,g,!1),e.if((0,dr.not)(g),()=>{t.reset(),f(v)})):(h(v,g),a||e.if((0,dr.not)(g),()=>e.break()))}}function h(v,g,b){let _={keyword:"additionalProperties",dataProp:v,dataPropType:Al.Type.Str};b===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,g)}}};Ig.default=r9});var cE=S(Cg=>{"use strict";Object.defineProperty(Cg,"__esModule",{value:!0});var n9=Na(),iE=Gt(),Ag=pe(),aE=Rg(),s9={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&aE.default.code(new n9.KeywordCxt(o,aE.default,"additionalProperties"));let i=(0,iE.allSchemaProperties)(r);for(let d of i)o.definedProperties.add(d);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Ag.mergeEvaluated.props(e,(0,Ag.toHash)(i),o.props));let a=i.filter(d=>!(0,Ag.alwaysValidSchema)(o,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,iE.propertyInData)(e,s,d,o.opts.ownProperties)),l(d),o.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Cg.default=s9});var pE=S(Dg=>{"use strict";Object.defineProperty(Dg,"__esModule",{value:!0});var uE=Gt(),Cl=X(),lE=pe(),dE=pe(),o9={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,uE.allSchemaProperties)(r),c=a.filter(h=>(0,lE.alwaysValidSchema)(o,r[h]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,l=e.name("valid");o.props!==!0&&!(o.props instanceof Cl.Name)&&(o.props=(0,dE.evaluatedPropsToName)(e,o.props));let{props:d}=o;p();function p(){for(let h of a)u&&f(h),o.allErrors?m(h):(e.var(l,!0),m(h),e.if(l))}function f(h){for(let v in u)new RegExp(h).test(v)&&(0,lE.checkStrictMode)(o,`property ${v} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,v=>{e.if((0,Cl._)`${(0,uE.usePattern)(t,h)}.test(${v})`,()=>{let g=c.includes(h);g||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:v,dataPropType:dE.Type.Str},l),o.opts.unevaluated&&d!==!0?e.assign((0,Cl._)`${d}[${v}]`,!0):!g&&!o.allErrors&&e.if((0,Cl.not)(l),()=>e.break())})})}}};Dg.default=o9});var fE=S(Og=>{"use strict";Object.defineProperty(Og,"__esModule",{value:!0});var i9=pe(),a9={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,i9.alwaysValidSchema)(n,r)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Og.default=a9});var mE=S(zg=>{"use strict";Object.defineProperty(zg,"__esModule",{value:!0});var c9=Gt(),u9={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:c9.validateUnion,error:{message:"must match a schema in anyOf"}};zg.default=u9});var hE=S(Mg=>{"use strict";Object.defineProperty(Mg,"__esModule",{value:!0});var Dl=X(),l9=pe(),d9={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Dl._)`{passingSchemas: ${t.passing}}`},p9={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:d9,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=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(){o.forEach((l,d)=>{let p;(0,l9.alwaysValidSchema)(s,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Dl._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Dl._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Dl.Name)})})}}};Mg.default=p9});var gE=S(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});var f9=pe(),m9={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 s=e.name("valid");r.forEach((o,i)=>{if((0,f9.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Ng.default=m9});var _E=S(jg=>{"use strict";Object.defineProperty(jg,"__esModule",{value:!0});var Ol=X(),vE=pe(),h9={message:({params:t})=>(0,Ol.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ol._)`{failingKeyword: ${t.ifClause}}`},g9={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:h9,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,vE.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=yE(n,"then"),o=yE(n,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),s&&o){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else s?e.if(a,u("then")):e.if((0,Ol.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,Ol._)`${l}`):t.setParams({ifClause:l})}}}};function yE(t,e){let r=t.schema[e];return r!==void 0&&!(0,vE.alwaysValidSchema)(t,r)}jg.default=g9});var bE=S(Lg=>{"use strict";Object.defineProperty(Lg,"__esModule",{value:!0});var y9=pe(),v9={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,y9.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Lg.default=v9});var wE=S(qg=>{"use strict";Object.defineProperty(qg,"__esModule",{value:!0});var _9=Sg(),b9=Yk(),w9=$g(),S9=Qk(),$9=eE(),x9=nE(),P9=oE(),k9=Rg(),E9=cE(),T9=pE(),I9=fE(),R9=mE(),A9=hE(),C9=gE(),D9=_E(),O9=bE();function z9(t=!1){let e=[I9.default,R9.default,A9.default,C9.default,D9.default,O9.default,P9.default,k9.default,x9.default,E9.default,T9.default];return t?e.push(b9.default,S9.default):e.push(_9.default,w9.default),e.push($9.default),e}qg.default=z9});var SE=S(Fg=>{"use strict";Object.defineProperty(Fg,"__esModule",{value:!0});var Ue=X(),M9={message:({schemaCode:t})=>(0,Ue.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ue._)`{format: ${t}}`},N9={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:M9,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;s?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,Ue._)`${m}[${i}]`),v=r.let("fType"),g=r.let("format");r.if((0,Ue._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(v,(0,Ue._)`${h}.type || "string"`).assign(g,(0,Ue._)`${h}.validate`),()=>r.assign(v,(0,Ue._)`"string"`).assign(g,h)),t.fail$data((0,Ue.or)(b(),_()));function b(){return c.strictSchema===!1?Ue.nil:(0,Ue._)`${i} && !${g}`}function _(){let P=l.$async?(0,Ue._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,Ue._)`${g}(${n})`,x=(0,Ue._)`(typeof ${g} == "function" ? ${P} : ${g}.test(${n}))`;return(0,Ue._)`${g} && ${g} !== true && ${v} === ${e} && !${x}`}}function f(){let m=d.formats[o];if(!m){b();return}if(m===!0)return;let[h,v,g]=_(m);h===e&&t.pass(P());function b(){if(c.strictSchema===!1){d.logger.warn(x());return}throw new Error(x());function x(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function _(x){let j=x instanceof RegExp?(0,Ue.regexpCode)(x):c.code.formats?(0,Ue._)`${c.code.formats}${(0,Ue.getProperty)(o)}`:void 0,k=r.scopeValue("formats",{key:o,ref:x,code:j});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,Ue._)`${k}.validate`]:["string",x,k]}function P(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Ue._)`await ${g}(${n})`}return typeof v=="function"?(0,Ue._)`${g}(${n})`:(0,Ue._)`${g}.test(${n})`}}}};Fg.default=N9});var $E=S(Ug=>{"use strict";Object.defineProperty(Ug,"__esModule",{value:!0});var j9=SE(),L9=[j9.default];Ug.default=L9});var xE=S(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.contentVocabulary=Lo.metadataVocabulary=void 0;Lo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Lo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var kE=S(Zg=>{"use strict";Object.defineProperty(Zg,"__esModule",{value:!0});var q9=Dk(),F9=Hk(),U9=wE(),Z9=$E(),PE=xE(),V9=[q9.default,F9.default,(0,U9.default)(),Z9.default,PE.metadataVocabulary,PE.contentVocabulary];Zg.default=V9});var TE=S(zl=>{"use strict";Object.defineProperty(zl,"__esModule",{value:!0});zl.DiscrError=void 0;var EE;(function(t){t.Tag="tag",t.Mapping="mapping"})(EE||(zl.DiscrError=EE={}))});var RE=S(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});var qo=X(),Vg=TE(),IE=wl(),B9=ja(),W9=pe(),H9={message:({params:{discrError:t,tagName:e}})=>t===Vg.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,qo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},K9={keyword:"discriminator",type:"object",schemaType:"object",error:H9,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.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,qo._)`${r}${(0,qo.getProperty)(a)}`);e.if((0,qo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Vg.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,qo._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:Vg.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,qo.Name),m}function p(){var f;let m={},h=g(s),v=!0;for(let P=0;P<i.length;P++){let x=i[P];if(x?.$ref&&!(0,W9.schemaHasRulesButRef)(x,o.self.RULES)){let k=x.$ref;if(x=IE.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,k),x instanceof IE.SchemaEnv&&(x=x.schema),x===void 0)throw new B9.default(o.opts.uriResolver,o.baseId,k)}let j=(f=x?.properties)===null||f===void 0?void 0:f[a];if(typeof j!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);v=v&&(h||g(x)),b(j,P)}if(!v)throw new Error(`discriminator: "${a}" must be required`);return m;function g({required:P}){return Array.isArray(P)&&P.includes(a)}function b(P,x){if(P.const)_(P.const,x);else if(P.enum)for(let j of P.enum)_(j,x);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(P,x){if(typeof P!="string"||P in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[P]=x}}}};Bg.default=K9});var AE=S((Uee,J9)=>{J9.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 DE=S((De,Wg)=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.MissingRefError=De.ValidationError=De.CodeGen=De.Name=De.nil=De.stringify=De.str=De._=De.KeywordCxt=De.Ajv=void 0;var G9=Ek(),Y9=kE(),X9=RE(),CE=AE(),Q9=["/properties"],Ml="http://json-schema.org/draft-07/schema",Fo=class extends G9.default{_addVocabularies(){super._addVocabularies(),Y9.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(X9.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(CE,Q9):CE;this.addMetaSchema(e,Ml,!1),this.refs["http://json-schema.org/schema"]=Ml}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ml)?Ml:void 0)}};De.Ajv=Fo;Wg.exports=De=Fo;Wg.exports.Ajv=Fo;Object.defineProperty(De,"__esModule",{value:!0});De.default=Fo;var e2=Na();Object.defineProperty(De,"KeywordCxt",{enumerable:!0,get:function(){return e2.KeywordCxt}});var Uo=X();Object.defineProperty(De,"_",{enumerable:!0,get:function(){return Uo._}});Object.defineProperty(De,"str",{enumerable:!0,get:function(){return Uo.str}});Object.defineProperty(De,"stringify",{enumerable:!0,get:function(){return Uo.stringify}});Object.defineProperty(De,"nil",{enumerable:!0,get:function(){return Uo.nil}});Object.defineProperty(De,"Name",{enumerable:!0,get:function(){return Uo.Name}});Object.defineProperty(De,"CodeGen",{enumerable:!0,get:function(){return Uo.CodeGen}});var t2=_l();Object.defineProperty(De,"ValidationError",{enumerable:!0,get:function(){return t2.default}});var r2=ja();Object.defineProperty(De,"MissingRefError",{enumerable:!0,get:function(){return r2.default}})});var OE=S(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.formatLimitDefinition=void 0;var n2=DE(),pr=X(),xn=pr.operators,Nl={formatMaximum:{okStr:"<=",ok:xn.LTE,fail:xn.GT},formatMinimum:{okStr:">=",ok:xn.GTE,fail:xn.LT},formatExclusiveMaximum:{okStr:"<",ok:xn.LT,fail:xn.GTE},formatExclusiveMinimum:{okStr:">",ok:xn.GT,fail:xn.LTE}},s2={message:({keyword:t,schemaCode:e})=>(0,pr.str)`should be ${Nl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,pr._)`{comparison: ${Nl[t].okStr}, limit: ${e}}`};Zo.formatLimitDefinition={keyword:Object.keys(Nl),type:"string",schemaType:"string",$data:!0,error:s2,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let c=new n2.KeywordCxt(o,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,pr._)`${p}[${c.schemaCode}]`);t.fail$data((0,pr.or)((0,pr._)`typeof ${f} != "object"`,(0,pr._)`${f} instanceof RegExp`,(0,pr._)`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(`"${s}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,pr._)`${i.code.formats}${(0,pr.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,pr._)`${p}.compare(${r}, ${n}) ${Nl[s].fail} 0`}},dependencies:["format"]};var o2=t=>(t.addKeyword(Zo.formatLimitDefinition),t);Zo.default=o2});var jE=S((Ya,NE)=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});var Vo=_P(),i2=OE(),Hg=X(),zE=new Hg.Name("fullFormats"),a2=new Hg.Name("fastFormats"),Kg=(t,e={keywords:!0})=>{if(Array.isArray(e))return ME(t,e,Vo.fullFormats,zE),t;let[r,n]=e.mode==="fast"?[Vo.fastFormats,a2]:[Vo.fullFormats,zE],s=e.formats||Vo.formatNames;return ME(t,s,r,n),e.keywords&&(0,i2.default)(t),t};Kg.get=(t,e="full")=>{let n=(e==="fast"?Vo.fastFormats:Vo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function ME(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Hg._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}NE.exports=Ya=Kg;Object.defineProperty(Ya,"__esModule",{value:!0});Ya.default=Kg});import{readFileSync as AH}from"fs";import{join as My}from"path";import{fileURLToPath as CH}from"url";var Es=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},nc=class extends Es{code="PROVIDER_NOT_FOUND";retryable=!1;constructor(e){super(e,`Provider not found: ${e}`)}},xe=class extends Es{code="PROVIDER_UNAVAILABLE";retryable=!1;constructor(e,r){super(e,`Provider unavailable: ${r||"not installed or not running"}`)}};var Ts=class extends Es{timeoutMs;code="PROVIDER_TIMEOUT";retryable=!0;constructor(e,r){super(e,`Timeout after ${r}ms`),this.timeoutMs=r}},dt=class extends Es{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(e,r){super(e,`Execution error: ${r}`)}};var nv={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"}},SR={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 Ad(t){return t<3?"simple":t<8?"moderate":t<=20?"complex":"advanced"}function ic(t,e,r,n=t){let s=nv[n]??nv[t]??{},o=s.maxComplexity??"simple";return n==="ollama"&&r!==void 0&&(o=Ad(r)),{providerId:t,tier:s.tier??"tool",strengths:s.strengths??e.strengths,maxComplexity:o}}function Yr(t,e){let r=SR[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 ac={low:0,medium:.5,high:.7},$R={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 sv(t,e){return e?.[t]??$R[t]??"low"}function cc(t,e,r=ac){return t>=r[e]}var uc=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 nc(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 ic(r.id,r.getCapabilities(),void 0,r.type)}getDescriptor(e){let r=this.get(e);return r.getDescriptor?.()??Yr(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,s){let o=this.getAvailable();if(o.length===0)return;if(!r)return o[0];let i=n??sv(e),a=r.getQualityStats(30),c=new Map;for(let[p,f]of a){let m=p.split(":")[0],h=c.get(m)??{totalScore:0,count:0};h.totalScore+=f.avgScore*f.count,h.count+=f.count,c.set(m,h)}let u=o.filter(p=>{let f=c.get(p.id);if(!f)return i==="low";let m=f.totalScore/f.count;return cc(m,i,s)});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 y={};lt(y,{BRAND:()=>JR,DIRTY:()=>Rn,EMPTY_PATH:()=>ER,INVALID:()=>F,NEVER:()=>DA,OK:()=>rt,ParseStatus:()=>Ke,Schema:()=>Y,ZodAny:()=>en,ZodArray:()=>zr,ZodBigInt:()=>Cn,ZodBoolean:()=>Dn,ZodBranded:()=>ii,ZodCatch:()=>Vn,ZodDate:()=>On,ZodDefault:()=>Zn,ZodDiscriminatedUnion:()=>pc,ZodEffects:()=>qt,ZodEnum:()=>Fn,ZodError:()=>_t,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>mc,ZodIntersection:()=>jn,ZodIssueCode:()=>E,ZodLazy:()=>Ln,ZodLiteral:()=>qn,ZodMap:()=>Ls,ZodNaN:()=>Fs,ZodNativeEnum:()=>Un,ZodNever:()=>er,ZodNull:()=>Mn,ZodNullable:()=>yr,ZodNumber:()=>An,ZodObject:()=>bt,ZodOptional:()=>jt,ZodParsedType:()=>R,ZodPipeline:()=>ai,ZodPromise:()=>tn,ZodReadonly:()=>Bn,ZodRecord:()=>fc,ZodSchema:()=>Y,ZodSet:()=>qs,ZodString:()=>Qr,ZodSymbol:()=>Ns,ZodTransformer:()=>qt,ZodTuple:()=>gr,ZodType:()=>Y,ZodUndefined:()=>zn,ZodUnion:()=>Nn,ZodUnknown:()=>Or,ZodVoid:()=>js,addIssueToContext:()=>I,any:()=>sA,array:()=>cA,bigint:()=>QR,boolean:()=>hv,coerce:()=>CA,custom:()=>pv,date:()=>eA,datetimeRegex:()=>lv,defaultErrorMap:()=>Cr,discriminatedUnion:()=>pA,effect:()=>xA,enum:()=>wA,function:()=>vA,getErrorMap:()=>Os,getParsedType:()=>hr,instanceof:()=>YR,intersection:()=>fA,isAborted:()=>lc,isAsync:()=>zs,isDirty:()=>dc,isValid:()=>Xr,late:()=>GR,lazy:()=>_A,literal:()=>bA,makeIssue:()=>oi,map:()=>gA,nan:()=>XR,nativeEnum:()=>SA,never:()=>iA,null:()=>nA,nullable:()=>kA,number:()=>mv,object:()=>uA,objectUtil:()=>Cd,oboolean:()=>AA,onumber:()=>RA,optional:()=>PA,ostring:()=>IA,pipeline:()=>TA,preprocess:()=>EA,promise:()=>$A,quotelessJson:()=>xR,record:()=>hA,set:()=>yA,setErrorMap:()=>kR,strictObject:()=>lA,string:()=>fv,symbol:()=>tA,transformer:()=>xA,tuple:()=>mA,undefined:()=>rA,union:()=>dA,unknown:()=>oA,util:()=>se,void:()=>aA});var se;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let o={};for(let i of s)o[i]=i;return o},t.getValidEnumValues=s=>{let o=t.objectKeys(s).filter(a=>typeof s[s[a]]!="number"),i={};for(let a of o)i[a]=s[a];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(o){return s[o]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let o=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&o.push(i);return o},t.find=(s,o)=>{for(let i of s)if(o(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(se||(se={}));var Cd;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Cd||(Cd={}));var R=se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),hr=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 E=se.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"]),xR=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),_t=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(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(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 s(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,se.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];r[o]=r[o]||[],r[o].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};_t.create=t=>new _t(t);var PR=(t,e)=>{let r;switch(t.code){case E.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,se.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:r=`Unrecognized key(s) in object: ${se.joinValues(t.keys,", ")}`;break;case E.invalid_union:r="Invalid input";break;case E.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${se.joinValues(t.options)}`;break;case E.invalid_enum_value:r=`Invalid enum value. Expected ${se.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:r="Invalid function arguments";break;case E.invalid_return_type:r="Invalid function return type";break;case E.invalid_date:r="Invalid date";break;case E.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}"`:se.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case E.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 E.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 E.custom:r="Invalid input";break;case E.invalid_intersection_types:r="Intersection results could not be merged";break;case E.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:r="Number must be finite";break;default:r=e.defaultError,se.assertNever(t)}return{message:r}},Cr=PR;var ov=Cr;function kR(t){ov=t}function Os(){return ov}var oi=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,o=[...r,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}},ER=[];function I(t,e){let r=Os(),n=oi({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Cr?void 0:Cr].filter(s=>!!s)});t.common.issues.push(n)}var Ke=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 s of r){if(s.status==="aborted")return F;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return F;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},F=Object.freeze({status:"aborted"}),Rn=t=>({status:"dirty",value:t}),rt=t=>({status:"valid",value:t}),lc=t=>t.status==="aborted",dc=t=>t.status==="dirty",Xr=t=>t.status==="valid",zs=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 Lt=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}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}},iv=(t,e)=>{if(Xr(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 _t(t.common.issues);return this._error=r,this._error}}};function W(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=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:s}:{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:s}}var Y=class{get description(){return this._def.description}_getType(e){return hr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:hr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ke,ctx:{common:e.parent.common,data:e.data,parsedType:hr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(zs(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:hr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return iv(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Xr(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=>Xr(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:hr(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(zs(s)?s:Promise.resolve(s));return iv(n,o)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:E.custom,...n(s)});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,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new qt({schema:this,typeName:T.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 jt.create(this,this._def)}nullable(){return yr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zr.create(this)}promise(){return tn.create(this,this._def)}or(e){return Nn.create([this,e],this._def)}and(e){return jn.create(this,e,this._def)}transform(e){return new qt({...W(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Zn({...W(this._def),innerType:this,defaultValue:r,typeName:T.ZodDefault})}brand(){return new ii({typeName:T.ZodBranded,type:this,...W(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Vn({...W(this._def),innerType:this,catchValue:r,typeName:T.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ai.create(this,e)}readonly(){return Bn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},TR=/^c[^\s-]{8,}$/i,IR=/^[0-9a-z]+$/,RR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,AR=/^[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,CR=/^[a-z0-9_-]{21}$/i,DR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,OR=/^[-+]?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)?)??$/,zR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,MR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Dd,NR=/^(?:(?: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])$/,jR=/^(?:(?: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])$/,LR=/^(([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]))$/,qR=/^(([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])$/,FR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,UR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,cv="((\\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])))",ZR=new RegExp(`^${cv}$`);function uv(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 VR(t){return new RegExp(`^${uv(t)}$`)}function lv(t){let e=`${cv}T${uv(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 BR(t,e){return!!((e==="v4"||!e)&&NR.test(t)||(e==="v6"||!e)&&LR.test(t))}function WR(t,e){if(!DR.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,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function HR(t,e){return!!((e==="v4"||!e)&&jR.test(t)||(e==="v6"||!e)&&qR.test(t))}var Qr=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==R.string){let o=this._getOrReturnCtx(e);return I(o,{code:E.invalid_type,expected:R.string,received:o.parsedType}),F}let n=new Ke,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),I(s,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),I(s,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let i=e.data.length>o.value,a=e.data.length<o.value;(i||a)&&(s=this._getOrReturnCtx(e,s),i?I(s,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&I(s,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")zR.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"email",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Dd||(Dd=new RegExp(MR,"u")),Dd.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"emoji",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")AR.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"uuid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")CR.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"nanoid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")TR.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"cuid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")IR.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"cuid2",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")RR.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"ulid",code:E.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),I(s,{validation:"url",code:E.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"regex",code:E.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),I(s,{code:E.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(s=this._getOrReturnCtx(e,s),I(s,{code:E.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),I(s,{code:E.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?lv(o).test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{code:E.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?ZR.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{code:E.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?VR(o).test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{code:E.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?OR.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"duration",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?BR(e.data,o.version)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"ip",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?WR(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"jwt",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?HR(e.data,o.version)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"cidr",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?FR.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"base64",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?UR.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"base64url",code:E.invalid_string,message:o.message}),n.dirty()):se.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:E.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}};Qr.create=t=>new Qr({checks:[],typeName:T.ZodString,coerce:t?.coerce??!1,...W(t)});function KR(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}var An=class t extends Y{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 o=this._getOrReturnCtx(e);return I(o,{code:E.invalid_type,expected:R.number,received:o.parsedType}),F}let n,s=new Ke;for(let o of this._def.checks)o.kind==="int"?se.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:E.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:E.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:E.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?KR(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),I(n,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:E.not_finite,message:o.message}),s.dirty()):se.assertNever(o);return{status:s.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,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:C.toString(s)}]})}_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"&&se.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)}};An.create=t=>new An({checks:[],typeName:T.ZodNumber,coerce:t?.coerce||!1,...W(t)});var Cn=class t extends Y{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,s=new Ke;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:E.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),I(n,{code:E.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),I(n,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):se.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return I(r,{code:E.invalid_type,expected:R.bigint,received:r.parsedType}),F}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,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:C.toString(s)}]})}_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}};Cn.create=t=>new Cn({checks:[],typeName:T.ZodBigInt,coerce:t?.coerce??!1,...W(t)});var Dn=class extends Y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==R.boolean){let n=this._getOrReturnCtx(e);return I(n,{code:E.invalid_type,expected:R.boolean,received:n.parsedType}),F}return rt(e.data)}};Dn.create=t=>new Dn({typeName:T.ZodBoolean,coerce:t?.coerce||!1,...W(t)});var On=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==R.date){let o=this._getOrReturnCtx(e);return I(o,{code:E.invalid_type,expected:R.date,received:o.parsedType}),F}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return I(o,{code:E.invalid_date}),F}let n=new Ke,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),I(s,{code:E.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),I(s,{code:E.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):se.assertNever(o);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}};On.create=t=>new On({checks:[],coerce:t?.coerce||!1,typeName:T.ZodDate,...W(t)});var Ns=class extends Y{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return I(n,{code:E.invalid_type,expected:R.symbol,received:n.parsedType}),F}return rt(e.data)}};Ns.create=t=>new Ns({typeName:T.ZodSymbol,...W(t)});var zn=class extends Y{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return I(n,{code:E.invalid_type,expected:R.undefined,received:n.parsedType}),F}return rt(e.data)}};zn.create=t=>new zn({typeName:T.ZodUndefined,...W(t)});var Mn=class extends Y{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return I(n,{code:E.invalid_type,expected:R.null,received:n.parsedType}),F}return rt(e.data)}};Mn.create=t=>new Mn({typeName:T.ZodNull,...W(t)});var en=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return rt(e.data)}};en.create=t=>new en({typeName:T.ZodAny,...W(t)});var Or=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return rt(e.data)}};Or.create=t=>new Or({typeName:T.ZodUnknown,...W(t)});var er=class extends Y{_parse(e){let r=this._getOrReturnCtx(e);return I(r,{code:E.invalid_type,expected:R.never,received:r.parsedType}),F}};er.create=t=>new er({typeName:T.ZodNever,...W(t)});var js=class extends Y{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return I(n,{code:E.invalid_type,expected:R.void,received:n.parsedType}),F}return rt(e.data)}};js.create=t=>new js({typeName:T.ZodVoid,...W(t)});var zr=class t extends Y{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==R.array)return I(r,{code:E.invalid_type,expected:R.array,received:r.parsedType}),F;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(I(r,{code:i?E.too_big:E.too_small,minimum:a?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(I(r,{code:E.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(I(r,{code:E.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>s.type._parseAsync(new Lt(r,i,r.path,a)))).then(i=>Ke.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new Lt(r,i,r.path,a)));return Ke.mergeArray(n,o)}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)}};zr.create=(t,e)=>new zr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...W(e)});function Ms(t){if(t instanceof bt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=jt.create(Ms(n))}return new bt({...t._def,shape:()=>e})}else return t instanceof zr?new zr({...t._def,type:Ms(t.element)}):t instanceof jt?jt.create(Ms(t.unwrap())):t instanceof yr?yr.create(Ms(t.unwrap())):t instanceof gr?gr.create(t.items.map(e=>Ms(e))):t}var bt=class t extends Y{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=se.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 I(u,{code:E.invalid_type,expected:R.object,received:u.parsedType}),F}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof er&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=o[u],d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Lt(s,d,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof er){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(u==="strict")a.length>0&&(I(s,{code:E.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=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Lt(s,d,s.path,l)),alwaysSet:l in s.data})}}return s.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=>Ke.mergeObjectSync(n,u)):Ke.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 s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:C.errToObj(e).message??s}:{message:s}}}:{}})}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:T.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 se.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 se.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Ms(this)}partial(e){let r={};for(let n of se.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of se.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof jt;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return dv(se.objectKeys(this.shape))}};bt.create=(t,e)=>new bt({shape:()=>t,unknownKeys:"strip",catchall:er.create(),typeName:T.ZodObject,...W(e)});bt.strictCreate=(t,e)=>new bt({shape:()=>t,unknownKeys:"strict",catchall:er.create(),typeName:T.ZodObject,...W(e)});bt.lazycreate=(t,e)=>new bt({shape:t,unknownKeys:"strip",catchall:er.create(),typeName:T.ZodObject,...W(e)});var Nn=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new _t(a.ctx.common.issues));return I(r,{code:E.invalid_union,unionErrors:i}),F}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,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"&&!o&&(o={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new _t(c));return I(r,{code:E.invalid_union,unionErrors:a}),F}}get options(){return this._def.options}};Nn.create=(t,e)=>new Nn({options:t,typeName:T.ZodUnion,...W(e)});var Dr=t=>t instanceof Ln?Dr(t.schema):t instanceof qt?Dr(t.innerType()):t instanceof qn?[t.value]:t instanceof Fn?t.options:t instanceof Un?se.objectValues(t.enum):t instanceof Zn?Dr(t._def.innerType):t instanceof zn?[void 0]:t instanceof Mn?[null]:t instanceof jt?[void 0,...Dr(t.unwrap())]:t instanceof yr?[null,...Dr(t.unwrap())]:t instanceof ii||t instanceof Bn?Dr(t.unwrap()):t instanceof Vn?Dr(t._def.innerType):[],pc=class t extends Y{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.object)return I(r,{code:E.invalid_type,expected:R.object,received:r.parsedType}),F;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(I(r,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),F)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let o of r){let i=Dr(o.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(s.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);s.set(a,o)}}return new t({typeName:T.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...W(n)})}};function Od(t,e){let r=hr(t),n=hr(e);if(t===e)return{valid:!0,data:t};if(r===R.object&&n===R.object){let s=se.objectKeys(e),o=se.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=Od(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 s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=Od(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===R.date&&n===R.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var jn=class extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(lc(o)||lc(i))return F;let a=Od(o.value,i.value);return a.valid?((dc(o)||dc(i))&&r.dirty(),{status:r.value,value:a.data}):(I(n,{code:E.invalid_intersection_types}),F)};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(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};jn.create=(t,e,r)=>new jn({left:t,right:e,typeName:T.ZodIntersection,...W(r)});var gr=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return I(n,{code:E.invalid_type,expected:R.array,received:n.parsedType}),F;if(n.data.length<this._def.items.length)return I(n,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),F;!this._def.rest&&n.data.length>this._def.items.length&&(I(n,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Lt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>Ke.mergeArray(r,i)):Ke.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};gr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new gr({items:t,typeName:T.ZodTuple,rest:null,...W(e)})};var fc=class t extends Y{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 I(n,{code:E.invalid_type,expected:R.object,received:n.parsedType}),F;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new Lt(n,a,n.path,a)),value:i._parse(new Lt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ke.mergeObjectAsync(r,s):Ke.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Y?new t({keyType:e,valueType:r,typeName:T.ZodRecord,...W(n)}):new t({keyType:Qr.create(),valueType:e,typeName:T.ZodRecord,...W(r)})}},Ls=class extends Y{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 I(n,{code:E.invalid_type,expected:R.map,received:n.parsedType}),F;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new Lt(n,a,n.path,[u,"key"])),value:o._parse(new Lt(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 F;(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 F;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Ls.create=(t,e,r)=>new Ls({valueType:e,keyType:t,typeName:T.ZodMap,...W(r)});var qs=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return I(n,{code:E.invalid_type,expected:R.set,received:n.parsedType}),F;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(I(n,{code:E.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(I(n,{code:E.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return F;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new Lt(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)}};qs.create=(t,e)=>new qs({valueType:t,minSize:null,maxSize:null,typeName:T.ZodSet,...W(e)});var mc=class t extends Y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.function)return I(r,{code:E.invalid_type,expected:R.function,received:r.parsedType}),F;function n(a,c){return oi({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Os(),Cr].filter(u=>!!u),issueData:{code:E.invalid_arguments,argumentsError:c}})}function s(a,c){return oi({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Os(),Cr].filter(u=>!!u),issueData:{code:E.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof tn){let a=this;return rt(async function(...c){let u=new _t([]),l=await a._def.args.parseAsync(c,o).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,o).catch(f=>{throw u.addIssue(s(d,f)),u})})}else{let a=this;return rt(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new _t([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,o);if(!d.success)throw new _t([s(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:gr.create(e).rest(Or.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||gr.create([]).rest(Or.create()),returns:r||Or.create(),typeName:T.ZodFunction,...W(n)})}},Ln=class extends Y{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})}};Ln.create=(t,e)=>new Ln({getter:t,typeName:T.ZodLazy,...W(e)});var qn=class extends Y{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return I(r,{received:r.data,code:E.invalid_literal,expected:this._def.value}),F}return{status:"valid",value:e.data}}get value(){return this._def.value}};qn.create=(t,e)=>new qn({value:t,typeName:T.ZodLiteral,...W(e)});function dv(t,e){return new Fn({values:t,typeName:T.ZodEnum,...W(e)})}var Fn=class t extends Y{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return I(r,{expected:se.joinValues(n),received:r.parsedType,code:E.invalid_type}),F}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 I(r,{received:r.data,code:E.invalid_enum_value,options:n}),F}return rt(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})}};Fn.create=dv;var Un=class extends Y{_parse(e){let r=se.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==R.string&&n.parsedType!==R.number){let s=se.objectValues(r);return I(n,{expected:se.joinValues(s),received:n.parsedType,code:E.invalid_type}),F}if(this._cache||(this._cache=new Set(se.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=se.objectValues(r);return I(n,{received:n.data,code:E.invalid_enum_value,options:s}),F}return rt(e.data)}get enum(){return this._def.values}};Un.create=(t,e)=>new Un({values:t,typeName:T.ZodNativeEnum,...W(e)});var tn=class extends Y{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.promise&&r.common.async===!1)return I(r,{code:E.invalid_type,expected:R.promise,received:r.parsedType}),F;let n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return rt(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};tn.create=(t,e)=>new tn({type:t,typeName:T.ZodPromise,...W(e)});var qt=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===T.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{I(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return F;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?F:c.status==="dirty"?Rn(c.value):r.value==="dirty"?Rn(c.value):c});{if(r.value==="aborted")return F;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?F:a.status==="dirty"?Rn(a.value):r.value==="dirty"?Rn(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);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"?F:(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"?F:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Xr(i))return F;let a=s.transform(i.value,o);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=>Xr(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):F);se.assertNever(s)}};qt.create=(t,e,r)=>new qt({schema:t,typeName:T.ZodEffects,effect:e,...W(r)});qt.createWithPreprocess=(t,e,r)=>new qt({schema:e,effect:{type:"preprocess",transform:t},typeName:T.ZodEffects,...W(r)});var jt=class extends Y{_parse(e){return this._getType(e)===R.undefined?rt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};jt.create=(t,e)=>new jt({innerType:t,typeName:T.ZodOptional,...W(e)});var yr=class extends Y{_parse(e){return this._getType(e)===R.null?rt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};yr.create=(t,e)=>new yr({innerType:t,typeName:T.ZodNullable,...W(e)});var Zn=class extends Y{_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}};Zn.create=(t,e)=>new Zn({innerType:t,typeName:T.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...W(e)});var Vn=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return zs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Vn.create=(t,e)=>new Vn({innerType:t,typeName:T.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...W(e)});var Fs=class extends Y{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return I(n,{code:E.invalid_type,expected:R.nan,received:n.parsedType}),F}return{status:"valid",value:e.data}}};Fs.create=t=>new Fs({typeName:T.ZodNaN,...W(t)});var JR=Symbol("zod_brand"),ii=class extends Y{_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}},ai=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?F:o.status==="dirty"?(r.dirty(),Rn(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?F:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:T.ZodPipeline})}},Bn=class extends Y{_parse(e){let r=this._def.innerType._parse(e),n=s=>(Xr(s)&&(s.value=Object.freeze(s.value)),s);return zs(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Bn.create=(t,e)=>new Bn({innerType:t,typeName:T.ZodReadonly,...W(e)});function av(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function pv(t,e={},r){return t?en.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=av(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=av(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):en.create()}var GR={object:bt.lazycreate},T;(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"})(T||(T={}));var YR=(t,e={message:`Input not instance of ${t.name}`})=>pv(r=>r instanceof t,e),fv=Qr.create,mv=An.create,XR=Fs.create,QR=Cn.create,hv=Dn.create,eA=On.create,tA=Ns.create,rA=zn.create,nA=Mn.create,sA=en.create,oA=Or.create,iA=er.create,aA=js.create,cA=zr.create,uA=bt.create,lA=bt.strictCreate,dA=Nn.create,pA=pc.create,fA=jn.create,mA=gr.create,hA=fc.create,gA=Ls.create,yA=qs.create,vA=mc.create,_A=Ln.create,bA=qn.create,wA=Fn.create,SA=Un.create,$A=tn.create,xA=qt.create,PA=jt.create,kA=yr.create,EA=qt.createWithPreprocess,TA=ai.create,IA=()=>fv().optional(),RA=()=>mv().optional(),AA=()=>hv().optional(),CA={string:(t=>Qr.create({...t,coerce:!0})),number:(t=>An.create({...t,coerce:!0})),boolean:(t=>Dn.create({...t,coerce:!0})),bigint:(t=>Cn.create({...t,coerce:!0})),date:(t=>On.create({...t,coerce:!0}))};var DA=F;Ar();var OA=y.enum(["read-only","workspace-write","full-auto"]),zA=OA.default("read-only"),MA=y.object({id:y.string(),type:y.string(),enabled:y.boolean().default(!0),executionPolicy:zA,config:y.record(y.unknown()).default({})}),NA=y.enum(["default-only","auto"]).default("default-only"),jA=y.object({selectionPolicy:NA,locale:y.string().optional(),providers:y.array(MA).min(1,"At least one provider required")});function Mr(t){switch(t){case"ollama":case"gemini-cli":case"codex-cli":case"claude-cli":return"workspace-write";default:return"read-only"}}function hc(t){return t==="workspace-write"||t==="full-auto"}function LA(t){return sc.includes(t)}function qA(t){if(t!==void 0)return LA(t)?t:(console.warn(`[config] unknown locale '${t}', falling back to ${Tn}`),Tn)}function gv(t){let e=jA.parse(t);return{selectionPolicy:e.selectionPolicy,locale:qA(e.locale),providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}import{existsSync as yv,mkdirSync as FA}from"fs";import{homedir as UA}from"os";import{dirname as ZA,join as vv}from"path";var _v="providers.config.json";function ci(){let t=process.env.AGESTRA_CONFIG_PATH;if(t&&t.length>0)return t;let e=vv(UA(),".agestra",_v);if(yv(e))return e;let r=process.env.CLAUDE_PLUGIN_ROOT,n=r&&r.length>0?vv(r,_v):void 0;return n&&yv(n)?n:e}function bv(t){FA(ZA(t),{recursive:!0})}rn();vc();Us();Cs();import{mkdirSync as Uv,readFileSync as vr,readdirSync as Zv,existsSync as Dt}from"fs";import{join as Le}from"path";import{spawn as IC}from"child_process";import{randomUUID as RC}from"crypto";rn();Vd();di();import{readFileSync as Ov}from"fs";import{join as wc}from"path";function Sc(t){Promise.resolve().then(()=>(Dv(),Cv)).then(async({resolveCliConfig:e})=>{let r;try{r=JSON.parse(Ov(wc(t,"job.json"),"utf-8"))}catch{return}let n=e(r);if(!n){Be(t,{state:"missing_cli",completedAt:new Date().toISOString()}),ge(wc(t,"error.txt"),`No CLI mapping for provider: ${r.provider}`);return}let{command:s,buildArgs:o}=n,i=Ov(wc(t,"prompt.txt"),"utf-8"),a=o(i);Be(t,{state:"running",startedAt:new Date().toISOString()}),await bc({jobDir:t,command:s,args:a,cwd:r.cwd||void 0,timeoutMs:r.timeout,recordPid:!0})}).catch(()=>{try{Be(t,{state:"error",completedAt:new Date().toISOString()}),ge(wc(t,"error.txt"),"Failed to load job worker module")}catch{}})}import{existsSync as zv,readFileSync as Mv,readdirSync as Nv,unlinkSync as wC,rmdirSync as SC}from"fs";import{join as $c}from"path";var $C=["completed","error","timed_out","cancelled","missing_cli"];function jv(t){let{jobsDir:e,maxJobs:r,maxAgeDays:n,statusCache:s,clearDeferredSaveTimer:o}=t;if(!zv(e))return 0;let i;try{i=Nv(e,{withFileTypes:!0}).filter(f=>f.isDirectory())}catch{return 0}let a=[];for(let f of i)try{let m=$c(e,f.name,"status.json"),h=$c(e,f.name,"job.json");if(!zv(m))continue;let v=JSON.parse(Mv(m,"utf-8")),g=null;try{g=JSON.parse(Mv(h,"utf-8"))}catch{}a.push({name:f.name,status:v,descriptor:g})}catch{}let c=a.filter(f=>$C.includes(f.status.state)).sort((f,m)=>{let h=f.descriptor?.createdAt??"",v=m.descriptor?.createdAt??"";return h.localeCompare(v)}),u=0,l=Date.now(),d=n*24*60*60*1e3,p=a.length;for(let f of c){let h=(f.descriptor?.createdAt?l-new Date(f.descriptor.createdAt).getTime():1/0)>d,v=p-u>r;if(!h&&!v)continue;let g=$c(e,f.name);try{let b=Nv(g);for(let _ of b)wC($c(g,_));SC(g),s.delete(f.name),o(f.name),u++}catch{}}return u}rn();vc();Us();import{existsSync as xC,readFileSync as Bd,readdirSync as PC}from"fs";import{join as Wd}from"path";function Lv(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function qv(t,e){let r=Wd(t,e,"job.json");try{let s=JSON.parse(Bd(r,"utf-8")),o=new Date(s.createdAt).getTime();if(Number.isFinite(o))return o}catch{}let n=e.split("-");for(let s=n.length-2;s>=0;s--)if(/^\d+$/.test(n[s])){let o=Number(n[s]);if(Number.isFinite(o)&&o>0)return o}return null}function Fv(t){let{jobsDir:e,statusCache:r}=t,n=0,s;try{s=PC(e)}catch{return 0}for(let o of s){if(!Nr(o))continue;let i=Wd(e,o,"status.json");if(!xC(i))continue;let a;try{a=JSON.parse(Bd(i,"utf-8"))}catch{continue}if(a.state!=="running"||a.pid!==void 0&&Lv(a.pid))continue;let c=`${i}.lock`;try{let u=Wn(c,()=>{let l=JSON.parse(Bd(i,"utf-8"));if(l.state!=="running"||l.pid!==void 0&&Lv(l.pid))return null;let d={...l,state:"error",completedAt:new Date().toISOString()};return Ze(i,d),d});if(!u)continue;ge(Wd(e,o,"error.txt"),"orphaned (worker process died before completion)"),r.set(o,u),n++}catch{}}return n}di();Ar();var AC=5e3,Hd=["completed","error","timed_out","cancelled","missing_cli"],xc=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=Le(e,Fy),Uv(this.jobsDir,{recursive:!0}),this.maxJobs=r?.maxJobs??100,this.maxAgeDays=r?.maxAgeDays??7,this.completionHandler=r?.completionHandler,this.submitCount=this.countExistingJobs()}countExistingJobs(){if(!Dt(this.jobsDir))return 0;try{return Zv(this.jobsDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).length}catch{return 0}}reconcileOrphans(){return Fv({jobsDir:this.jobsDir,statusCache:this.statusCache})}submit(e){let r=`${e.provider}-${Date.now()}-${RC().slice(0,6)}`,n=Le(this.jobsDir,r);Uv(n,{recursive:!0});let s=e.timeout??3e5,o={id:r,provider:e.provider,prompt:e.prompt,timeout:s,createdAt:new Date().toISOString(),cwd:this.workspaceDir,saveAsDocument:e.saveAsDocument},i={id:r,state:"queued",provider:e.provider};if(Ze(Le(n,"job.json"),o),Ze(Le(n,"status.json"),i),ge(Le(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(()=>{})},s+AC);a.unref?.(),this.deferredSaveTimers.set(r,a)}return this.submitCount++,this.submitCount%10===0&&this.cleanup(),r}getStatus(e){if(!Nr(e))return null;let r=this.statusCache.get(e);if(r&&Hd.includes(r.state)&&((r.savedDocumentId?!0:r.saveError!==void 0)||!this.completionHandler))return r;let n=Le(this.jobsDir,e,"status.json");if(!Dt(n))return null;let s=JSON.parse(vr(n,"utf-8"));if(s.state==="queued"){let o=qv(this.jobsDir,e);if(o!==null&&Date.now()-o>6e4){let a=`${n}.lock`;try{let c=Wn(a,()=>{let u=JSON.parse(vr(n,"utf-8"));if(u.state!=="queued")return null;let l={...u,state:"error",completedAt:new Date().toISOString()};return Ze(n,l),l});if(c)return ge(Le(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,s),Hd.includes(s.state)&&!s.savedDocumentId&&!s.saveError&&this.completionHandler&&this.maybeTriggerCompletionSave(e).catch(()=>{}),s}getResult(e){if(!Nr(e))return null;let r=this.getStatus(e);if(!r)return null;let n=Le(this.jobsDir,e),s={id:e,state:r.state,exitCode:r.exitCode,savedDocumentId:r.savedDocumentId,saveError:r.saveError},o=Le(n,"output.txt");Dt(o)&&(s.output=vr(o,"utf-8"));let i=Le(n,"error.txt");return Dt(i)&&(s.error=vr(i,"utf-8")),s}async getResultAwaited(e){return Nr(e)?(await this.maybeTriggerCompletionSave(e),this.getResult(e)):null}async invokeHandlerWithRetry(e,r){let n=[200,600],s;for(let o=0;o<n.length+1;o++){if(!Dt(Le(r,"status.json")))throw s||new Error("job directory removed during completion save");try{return await e()}catch(i){if(s=i,o>=n.length)break;await new Promise(a=>setTimeout(a,n[o]))}}throw s}async maybeTriggerCompletionSave(e){if(!this.completionHandler||!Nr(e))return;let r=Le(this.jobsDir,e);if(!Dt(Le(r,"status.json")))return;let n=this.saveInFlight.get(e);if(n)return n;let s=this.runCompletionSave(e).finally(()=>{this.saveInFlight.delete(e)});return this.saveInFlight.set(e,s),s}async runCompletionSave(e){if(!this.completionHandler||!Nr(e))return;let r=Le(this.jobsDir,e),n=Le(r,"status.json"),s=Le(r,"job.json");if(!Dt(n)||!Dt(s))return;let o=JSON.parse(vr(n,"utf-8"));if(!Hd.includes(o.state)||o.savedDocumentId||o.saveError)return;let i=JSON.parse(vr(s,"utf-8"));if(!i.saveAsDocument)return;let a={id:e,state:o.state,exitCode:o.exitCode},c=Le(r,"output.txt");Dt(c)&&(a.output=vr(c,"utf-8"));let u=Le(r,"error.txt");Dt(u)&&(a.error=vr(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};Be(r,d),this.statusCache.set(e,{...o,...d})}else{let d={saveError:`skipped (state=${o.state})`};Be(r,d),this.statusCache.set(e,{...o,...d})}}catch(l){let p={saveError:l instanceof Error?l.message:String(l)};try{Be(r,p),this.statusCache.set(e,{...o,...p})}catch{}}}listJobs(){if(!Dt(this.jobsDir))return[];let e;try{e=Zv(this.jobsDir,{withFileTypes:!0}).filter(n=>n.isDirectory())}catch{return[]}let r=[];for(let n of e)try{let s=Le(this.jobsDir,n.name,"status.json");Dt(s)&&r.push(JSON.parse(vr(s,"utf-8")))}catch{}return r}cancel(e){if(!Nr(e))return!1;let r=this.getStatus(e);if(!r||r.state!=="queued"&&r.state!=="running")return!1;r.pid&&As(r.pid);let n=Le(this.jobsDir,e),s=Le(n,"status.json"),o=`${s}.lock`;try{let i=Wn(o,()=>{let a=JSON.parse(vr(s,"utf-8"));if(a.state!=="queued"&&a.state!=="running")return null;let c={...a,state:"cancelled",completedAt:new Date().toISOString()};return Ze(s,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(){return jv({jobsDir:this.jobsDir,maxJobs:this.maxJobs,maxAgeDays:this.maxAgeDays,statusCache:this.statusCache,clearDeferredSaveTimer:e=>this.clearDeferredSaveTimer(e)})}spawnWorker(e){let r=new URL("./job-worker.js",import.meta.url).pathname;if(Dt(r)){let n=IC(process.execPath,[r,e],{detached:!0,stdio:"ignore",cwd:this.workspaceDir}),s=typeof n.pid=="number"&&n.pid>0;if(s)try{Be(e,{pid:n.pid})}catch{}n.on("error",o=>{if(s)return;o.code==="ENOENT"?Sc(e):Sc(e)}),n.unref()}else Sc(e)}};rn();Ar();import{mkdirSync as CC,readdirSync as Vv,readFileSync as DC,unlinkSync as OC}from"fs";import{join as pi}from"path";function Bv(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 zC(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function MC(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var Pc=class{tracesDir;writer;constructor(e,r){this.tracesDir=pi(e,Uy),CC(this.tracesDir,{recursive:!0}),this.writer=new gc(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=Bv(new Date(r.timestamp)),s=pi(this.tracesDir,`${n}.jsonl`);this.writer.append(s,JSON.stringify(r)+`
|
|
20
|
+
`,"trace")}query(e={}){let r=this.listFiles(e.daysBack),n=[],s=[];for(let i of r){let a=DC(i,"utf-8").split(`
|
|
21
|
+
`).filter(Boolean);for(let c of a)try{let u=JSON.parse(c);MC(u)?s.push(u):zC(u)&&n.push(u)}catch{}}for(let i of s){let a=n.find(c=>c.traceId===i.traceId&&c.providerId===i.providerId);a&&(a.quality=i.quality)}let o=n;return e.providerId&&(o=o.filter(i=>i.providerId===e.providerId)),e.task&&(o=o.filter(i=>i.task===e.task)),e.traceId&&(o=o.filter(i=>i.traceId===e.traceId)),e.successOnly&&(o=o.filter(i=>i.response.success)),e.failedOnly&&(o=o.filter(i=>!i.response.success)),e.limit!==void 0&&(o=o.slice(0,e.limit)),o}updateQuality(e,r,n){let s=new Date,o={type:"quality_update",traceId:e,providerId:r,timestamp:s.toISOString(),quality:n},i=Bv(s),a=pi(this.tracesDir,`${i}.jsonl`);this.writer.append(a,JSON.stringify(o)+`
|
|
22
|
+
`,"audit")}shutdown(){this.writer.destroy()}panicFlush(){this.writer.panicFlush()}getQualityStats(e){let r=this.query({daysBack:e}),n=new Map;for(let o of r){if(!o.quality)continue;let i=`${o.providerId}:${o.task}`,a=n.get(i)??{totalScore:0,count:0,totalLatency:0};a.totalScore+=o.quality.score,a.count+=1,a.totalLatency+=o.latencyMs,n.set(i,a)}let s=new Map;for(let[o,i]of n)s.set(o,{avgScore:i.totalScore/i.count,count:i.count,avgLatencyMs:i.totalLatency/i.count});return s}cleanup(e){let r=new Date;r.setDate(r.getDate()-e);let n=0,s;try{s=Vv(this.tracesDir)}catch{return 0}for(let o of s){if(!o.endsWith(".jsonl"))continue;let i=o.replace(".jsonl",""),a=new Date(i+"T00:00:00.000Z");isNaN(a.getTime())||a<r&&(OC(pi(this.tracesDir,o)),n++)}return n}listFiles(e){let r;try{r=Vv(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(s=>{let o=s.replace(".jsonl",""),i=new Date(o+"T00:00:00.000Z");return!isNaN(i.getTime())&&i>=n})}return r.map(n=>pi(this.tracesDir,n))}};var NC=/[;|&`$(){}!><\n\r\\]/,kc=new Set(["ls","cat","head","tail","wc","diff","find","grep","sort","uniq"]),jC=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 Wv(t){if(NC.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(!kc.has(r))return{valid:!1,error:`Command '${r}' is not allowed. Allowed: ${[...kc].join(", ")}`};for(let n of e){let s=n.replace(/^.*\//,"");if(jC.has(s))return{valid:!1,error:`Command contains blocked token '${s}'`}}return{valid:!0}}Ar();var Hv=[{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"}],Kv=[/\$[A-Z_]+/,/\$\{[A-Z_]+\}/,/process\.env\.\w+/,/<YOUR_[A-Z_]+>/];function Jv(t){let e=Array.isArray(t)?t:t.split(`
|
|
23
|
+
`),r=[];for(let n=0;n<e.length;n++){let s=e[n];for(let o of Hv){let i=o.regex.exec(s);if(!i)continue;let a=i[0];if(!Kv.some(u=>u.test(a))){r.push({type:o.type,pattern:o.description,line:n+1,excerpt:s.length>80?s.slice(0,80)+"...":s});break}}}return{clean:r.length===0,findings:r}}function Zs(t){if(t.length===0)return t;let e=t.split(`
|
|
24
|
+
`);for(let r=0;r<e.length;r++){let n=e[r];for(let s of Hv){let o=new RegExp(s.regex.source,s.regex.flags.includes("g")?s.regex.flags:s.regex.flags+"g");n=n.replace(o,i=>Kv.some(a=>a.test(i))?i:ev)}e[r]=n}return e.join(`
|
|
25
|
+
`)}Ar();import{execFileSync as LC}from"child_process";import{existsSync as Gv,rmSync as qC,mkdirSync as FC}from"fs";import{join as Yv}from"path";var Ec=class{baseDir;worktrees=new Map;worktreeBaseDir;constructor(e){this.baseDir=e,this.worktreeBaseDir=Yv(e,Zy)}create(e){let r=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,60),n=`agestra-worker/${r}`,s=Yv(this.worktreeBaseDir,r);FC(this.worktreeBaseDir,{recursive:!0}),Gv(s)&&this.forceRemoveWorktree(s),this.gitSafe(["branch","-D",n]),this.git(["worktree","add","-b",n,s,"HEAD"]);let o={id:e,path:s,branch:n};return this.worktrees.set(e,o),o}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="",s="",o=()=>{n.includes(".agestra/worktrees")&&s.startsWith("agestra-worker/")&&([...this.worktrees.values()].some(a=>a.path===n)||r.push({path:n,branch:s})),n="",s=""};for(let i of e.split(`
|
|
26
|
+
`))i.startsWith("worktree ")?n=i.slice(9):i.startsWith("branch refs/heads/")?s=i.slice(18):i===""&&o();return n&&o(),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&&(Gv(e)&&qC(e,{recursive:!0,force:!0}),this.gitSafe(["worktree","prune"]))}git(e){return LC("git",e,{cwd:this.baseDir,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}gitSafe(e){try{return this.git(e)}catch{return null}}};var UC=["npm","node","git","tsc"];function Xv(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:[...UC]},timeout_minutes:t.timeoutMinutes??10}}function Qv(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 qe;(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"})(qe||(qe={}));var Tc=10,Gd=2e4;import{spawn as KC}from"child_process";import{writeFileSync as Xd,mkdirSync as JC,readFileSync as n_,existsSync as s_}from"fs";import{isAbsolute as o_,join as fi,resolve as i_}from"path";import{randomBytes as GC}from"crypto";import{execFileSync as YC}from"child_process";Ar();si();Cs();Us();Us();import{readFileSync as e_}from"fs";var Yd=class{builders=new Map;register(e,r){this.builders.set(e,r)}has(e){return this.builders.has(e)}build(e,r,n,s){let o=this.builders.get(e);if(!o){let i=[...this.builders.keys()];throw new Error(`No CLI launch builder registered for provider "${e}". Known: [${i.join(", ")}]`)}return o(r,n,s)}knownProviders(){return[...this.builders.keys()]}};function ZC(t,e,r){let n=t_(t,e,r);return{command:"codex",args:["exec","--skip-git-repo-check","--full-auto","--ephemeral","-C",e,"-"],stdin:n}}function VC(t,e,r){return{command:"gemini",args:["--approval-mode","yolo","-p",t_(t,e,r)]}}function t_(t,e,r){let n=e_(t,"utf-8"),s=BC(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,s].join(`
|
|
27
|
+
`)}function r_(){let t=new Yd;return t.register("codex",ZC),t.register("gemini",VC),t}function BC(t,e){if(!t||t.length===0)return"";let r=t.filter(s=>!Ud(s,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 s of r.slice(0,Tc))try{let o=e_(s,"utf-8"),i=o.length>Gd?`${o.slice(0,Gd)}
|
|
28
|
+
...[truncated]`:o;n.push(`### File: ${s}`),n.push("```"),n.push(i),n.push("```"),n.push("")}catch(o){let i=o instanceof Error?o.message:String(o);n.push(`### File: ${s}`),n.push(`[unavailable: ${i}]`),n.push("")}return r.length>Tc&&(n.push(`...[${r.length-Tc} additional read-only files omitted]`),n.push("")),n.join(`
|
|
29
|
+
`)}var mi=class t{baseDir;workers=new Map;workersBaseDir;worktreeManager;providerPolicies;cliBuilderRegistry;constructor(e,r={}){this.baseDir=e,this.workersBaseDir=fi(e,Ky),this.worktreeManager=new Ec(e),this.providerPolicies=r.providerPolicies??new Map,this.cliBuilderRegistry=r.cliBuilderRegistry??r_()}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===qe.RUNNING||n===qe.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),s=this.normalizeWritablePaths(e.filesToModify,r);this.assertAutonomousExecutionAllowed(e.provider);let o=[e.taskDescription,e.constraints??""],i=Jv(o);if(!i.clean){let O=i.findings.map(L=>L.pattern).join(", ");throw new Error(`Secret detected in task input \u2014 spawn blocked. Found: ${O}`)}let a=GC(3).toString("hex"),c=`${e.provider}-${Date.now()}-${a}`,u=fi(this.workersBaseDir,c);JC(u,{recursive:!0});let l=Xv({taskDescription:e.taskDescription,workingDir:r,filesToRead:n,filesToModify:s,constraints:e.constraints,successCriteria:e.successCriteria,timeoutMinutes:e.timeoutMinutes}),d=Qv(l);if(!d.valid)throw new Error(`Invalid task manifest: ${d.errors.join(", ")}`);let p=fi(u,"task-manifest.json");Xd(p,JSON.stringify(l,null,2),"utf-8");let f=e.useWorktree!==!1?this.tryCreateWorktree(c):null,m=fi(u,"stdout.log"),h=fi(u,"stderr.log"),v=f?.path??r,g=this.cliBuilderRegistry.build(e.provider,p,v,n),b=In(g.command,g.args),_=KC(b.command,b.args,{cwd:v,env:t.buildWorkerEnv(),detached:!0,stdio:[g.stdin?"pipe":"ignore","pipe","pipe"]}),P=[],x=[];_.stdout?.on("data",O=>P.push(O)),_.stderr?.on("data",O=>x.push(O)),g.stdin!==void 0&&_.stdin?.end(g.stdin),_.unref();let j={workerId:c,provider:e.provider,state:qe.RUNNING,pid:_.pid??null,worktreePath:f?.path??null,worktreeBranch:f?.branch??null,startedAt:Date.now(),retryCount:0,exitCode:null,error:null},k={info:j,process:_,workerDir:u,manifestPath:p,outputPath:m,errorPath:h};if(this.workers.set(c,k),e.timeoutMinutes){let O=e.timeoutMinutes*6e4,L=setTimeout(()=>{if(k.info.state===qe.RUNNING&&k.process===_){k.info.state=qe.TIMEOUT,k.info.error=`Worker timed out after ${e.timeoutMinutes} minutes`;let q=_.pid;q&&As(q)}},O);L.unref(),k.timeoutTimer=L}return _.on("close",O=>{k.timeoutTimer&&(clearTimeout(k.timeoutTimer),k.timeoutTimer=void 0),k.info.exitCode=O;try{Xd(m,Buffer.concat(P).toString("utf-8")),Xd(h,Buffer.concat(x).toString("utf-8"))}catch{}k.info.state===qe.CANCELLING?k.info.state=qe.CANCELLED:O===0?k.info.state=qe.COLLECTING:(k.info.state=qe.FAILED,k.info.error=`Process exited with code ${O}`)}),j}getStatus(e){let r=this.workers.get(e);if(!r)return;let n=Math.floor((Date.now()-r.info.startedAt)/1e3),s="";try{s_(r.outputPath)&&(s=n_(r.outputPath,"utf-8").split(`
|
|
30
30
|
`).slice(-20).join(`
|
|
31
|
-
`))}catch{}return{workerId:r.info.workerId,provider:r.info.provider,state:r.info.state,elapsedSeconds:n,pid:r.info.pid,outputTail:
|
|
32
|
-
`).map(c=>c.trim().slice(3)):[];return a.length>0&&(this.execGit(["commit","-m",
|
|
33
|
-
`).map(n=>n.trim().slice(3)).filter(Boolean):[]}static buildWorkerEnv(){let e={};for(let r of
|
|
34
|
-
`),this.stdoutBuffer="",this.state!=="shutdown"){this.state="error",this.consecutiveFailures++,this.lastFailureTime=Date.now();for(let[,
|
|
35
|
-
`))!==-1;){let
|
|
36
|
-
`)}catch(f){clearTimeout(u),this.pendingRequests.delete(e.id),a(),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",
|
|
37
|
-
`);for(let n=r.length-1;n>=0;n--){let
|
|
31
|
+
`))}catch{}return{workerId:r.info.workerId,provider:r.info.provider,state:r.info.state,elapsedSeconds:n,pid:r.info.pid,outputTail:Zs(s),worktreeBranch:r.info.worktreeBranch,retryCount:r.info.retryCount}}collect(e){let r=this.workers.get(e);if(!r)return;let n="";try{s_(r.outputPath)&&(n=n_(r.outputPath,"utf-8"))}catch{}n=Zs(n);let s=null;try{r.info.worktreePath&&(s=this.reviewChanges(r.info.workerId))}catch{s=null}return r.info.state===qe.COLLECTING&&(r.info.state=qe.COMPLETED),{workerId:r.info.workerId,state:r.info.state,exitCode:r.info.exitCode,outputFull:n,gitDiff:s?.fullDiff??"",filesChanged:s?.filesChanged??[],worktreeBranch:r.info.worktreeBranch}}stop(e){let r=this.workers.get(e);if(!r||!r.process||r.info.state!==qe.RUNNING)return;r.info.state=qe.CANCELLING;let n=r.process.pid;if(n)As(n);else try{r.process.kill("SIGTERM")}catch{}setTimeout(()=>{if(r.info.state===qe.CANCELLING){try{r.process?.kill("SIGKILL")}catch{}r.info.state=qe.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 s=n.info.worktreePath,o=r??`agestra: worker ${e}`;this.execGit(["add","-A"],s);let i=this.execGit(["status","--porcelain"],s),a=i.trim()?i.trim().split(`
|
|
32
|
+
`).map(c=>c.trim().slice(3)):[];return a.length>0&&(this.execGit(["commit","-m",o],s),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 YC("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(`
|
|
33
|
+
`).map(n=>n.trim().slice(3)).filter(Boolean):[]}static buildWorkerEnv(){let e={};for(let r of Jy){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(!hc(r))throw new Error(`Execution policy blocks autonomous worker for provider "${e}" (policy: ${r})`)}validateWorkingDirectory(e){return Ft(e,this.baseDir)}normalizeReadablePaths(e,r){return e?.map(n=>{let s=o_(n)?n:i_(r,n);return nn(s,this.baseDir)})}normalizeWritablePaths(e,r){return e?.map(n=>{let s=o_(n)?n:i_(r,n);return Ft(s,this.baseDir)})}};var Rc=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 Vs=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()}}};si();Ar();Cs();import{spawn as XC}from"child_process";var QC=3e5,eD=3,tD=15e3,a_=10*1024*1024,rD=6e5,Ac=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??QC,this.maxConsecutiveFailures=e.maxConsecutiveFailures??eD,this.startupTimeoutMs=e.startupTimeoutMs??tD}async request(e,r,n){if(this.state==="shutdown")throw new Error("CodexAppServer is shutting down");if(n?.aborted)throw new Nt(n.reason);if((this.state==="idle"||this.state==="error")&&await this.start(),this.state==="starting"&&await this.waitForReady(),n?.aborted)throw new Nt(n.reason);if(this.state!=="ready"&&this.state!=="busy")throw new Error(`CodexAppServer in unexpected state: ${this.state}`);return this.sendRequest(e,r??rD,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>Yy?(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[,r]of this.pendingRequests)clearTimeout(r.timer),r.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,Qt(e),await new Promise(r=>{e.on("close",()=>{r()}),(e.exitCode!==null||e.signalCode!==null)&&r()}),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=In(this.command,e),n=XC(r.command,r.args,{stdio:["pipe","pipe","pipe"],detached:!1,windowsHide:!0});this.process=n;let s=c=>this.handleStdout(c.toString()),o=c=>{process.stderr.write(`[codex-app-server] ${c.toString()}`)},i=(c,u)=>{n.stdout?.off("data",s),n.stderr?.off("data",o),n.off("error",a),this.handleProcessClose(c,u)},a=c=>{n.stdout?.off("data",s),n.stderr?.off("data",o),n.off("close",i),this.handleProcessError(c)};return n.stdout.on("data",s),n.stderr.on("data",o),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=s=>{clearTimeout(n),r(s)}})}handleStdout(e){if(this.stdoutBuffer+=e,this.stdoutBuffer.length>a_){if(process.stderr.write(`[codex-app-server] stdoutBuffer exceeded ${a_} bytes \u2014 dropping and restarting
|
|
34
|
+
`),this.stdoutBuffer="",this.state!=="shutdown"){this.state="error",this.consecutiveFailures++,this.lastFailureTime=Date.now();for(let[,s]of this.pendingRequests)clearTimeout(s.timer),s.reject(new Error("App server stdout buffer overflow"));this.pendingRequests.clear();try{this.process?.kill("SIGTERM")}catch{}}return}for(let s of this.pendingRequests.values())s.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(`
|
|
35
|
+
`))!==-1;){let s=this.stdoutBuffer.slice(0,n).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(n+1),!!s){if(this.state==="starting"&&(s.includes("ready")||s.includes("initialized"))){r();continue}try{let o=JSON.parse(s);if(this.state==="starting"&&r(),o.id&&this.pendingRequests.has(o.id)){let i=this.pendingRequests.get(o.id);this.pendingRequests.delete(o.id),clearTimeout(i.timer),this.consecutiveFailures=0,this.pendingRequests.size===0&&(this.state="ready",this.resetIdleTimer()),i.resolve(o)}}catch{this.state==="starting"&&r()}}}}sendRequest(e,r,n){return new Promise((s,o)=>{if(!this.process||!this.process.stdin){o(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"),o(new Error(`App server request timeout (${r}ms of inactivity)`))},u=setTimeout(c,r),l=()=>{clearTimeout(u),u=setTimeout(c,r)},d=f=>{a(),s(f)},p=f=>{a(),o(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(),o(new Nt(n.reason)))},n.addEventListener("abort",i));try{this.process.stdin.write(JSON.stringify(e)+`
|
|
36
|
+
`)}catch(f){clearTimeout(u),this.pendingRequests.delete(e.id),a(),this.consecutiveFailures++,this.lastFailureTime=Date.now(),this.state="error",o(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 D(t){return t instanceof Error?t.message:String(t)}function Bs(t,e,r="... [truncated]"){return t.length<=e?t:t.slice(0,e)+r}si();async function Ws(t,e){try{if((await vt({command:t,args:["--version"],timeout:1e4})).exitCode===0)return{available:!0,cliPath:t}}catch{}try{if((await vt({command:"npx",args:[e,"--version"],timeout:3e4})).exitCode===0)return{available:!0,cliPath:"npx"}}catch{}return{available:!1,cliPath:null}}async function Hs(t,e,r,n){if(!t)return{status:"error",message:`${n} CLI not installed`};try{let i=await vt({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(s){return{status:"error",message:s.message}}}function hi(t){let e=t.trim();try{return JSON.parse(e)}catch{}let r=t.split(`
|
|
37
|
+
`);for(let n=r.length-1;n>=0;n--){let s=r[n].trim();if(s.startsWith("{"))try{return JSON.parse(s)}catch{}}return null}function Ks(t,e,r){let n=e.trim()||`Exit code ${t}`,s=n.toLowerCase();if(s.includes("429")||s.includes("rate limit")||s.includes("quota")){let o=new xe(r,`Rate limited: ${n}`);throw o.markUnavailable=!0,o}throw s.includes("auth")||s.includes("credential")||s.includes("login")||s.includes("api key")?new xe(r,`Authentication issue: ${n}`):new dt(r,n)}function c_(t){let e="",r=!1;return{feed(n){if(r)return null;e+=n;let s=n.toLowerCase();if(s.includes("429")||s.includes("rate limit")||s.includes("rate-limit")||s.includes("resource_exhausted")||s.includes("quota")){r=!0;let o=new xe(t,`Rate limited (detected in stream): ${n.trim().slice(0,200)}`);return o.markUnavailable=!0,o}return s.includes("authentication")||s.includes("credential")||s.includes("api key")?(r=!0,new xe(t,`Authentication issue (detected in stream): ${n.trim().slice(0,200)}`)):null},drain(){return e}}}function Kn(t){let e=t.prompt;if(t.system&&(e=`${t.system}
|
|
38
38
|
|
|
39
39
|
${e}`),t.files?.length)for(let r of t.files)r.content&&(e+=`
|
|
40
40
|
|
|
41
41
|
### File: ${r.path}
|
|
42
42
|
\`\`\`
|
|
43
43
|
${r.content}
|
|
44
|
-
\`\`\``);return e}function
|
|
44
|
+
\`\`\``);return e}function Js(t,e){return!!t.files?.length||e.length>4e3}function Qd(t){let e=0;return t.replace(/^### File: .+$/gm,()=>(e+=1,`### File ${e}`))}function Gs(t,e,r,n){return t==="npx"?{command:"npx",cliArgs:[r,...n]}:{command:e,cliArgs:n}}function Ys(t,e,r){if(t instanceof xe||t instanceof dt||t instanceof Nt)throw t;let n=t?.message??"";throw n.startsWith("CLI timeout after ")?new Ts(e,r):new dt(e,n)}function sD(t){let e=t.prompt;if(t.system&&(e=`${t.system}
|
|
45
45
|
|
|
46
46
|
${e}`),t.files?.length)for(let r of t.files)r.content&&(e+=`
|
|
47
47
|
|
|
48
48
|
### File: ${r.path}
|
|
49
49
|
\`\`\`
|
|
50
50
|
${r.content}
|
|
51
|
-
\`\`\``);return e}function QC(t,e){let r=e?.model;return typeof r=="string"&&r.length>0?r:t}var rn=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 Gr(this,this.getCapabilities())}isAvailable(){return this.bridge.isAvailable()}async chat(e){if(!this.isAvailable())throw new Se(this.id,`${this.displayName} host bridge is not available`);try{let r=YC(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:QC(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 Se(this.id,n):new dt(this.id,n)}}};var XC={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"]}]},Pc=class extends rn{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:XC,modelName:e.modelName??"claude-host"})}};var eD={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"]}]},Ec=class extends rn{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:eD,modelName:e.modelName??"codex-host"})}};var tD={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"]}]},Tc=class extends rn{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:tD,modelName:e.modelName??"gemini-host"})}};Tr();var n_={"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 o_={"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 s_={"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 i_={"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 a_=Object.freeze({en:n_,ko:o_,ja:s_,zh:i_});function iD(t){return typeof t=="string"&&Ya.includes(t)}function Gd(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 Qd(t){return t===void 0?Yd(kn):iD(t)?Yd(t):(console.warn(`[i18n] unknown locale '${t}', falling back to ${kn}`),Yd(kn))}function aD(t,e,r){let n=new Set;return{locale:t,t(o,s){let i=e[o];if(i!==void 0)return Gd(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 ${kd}`)),Gd(a,s)):(n.has(o)||(n.add(o),console.warn(`[i18n] missing key '${o}' in all bundles; returning raw key`)),Gd(o,s))}}}function Yd(t){return aD(t,a_[t],a_[kd])}async function c_(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:cD(n.name||"")}))}function cD(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 lD=new Set(["http:","https:"]);function dD(t){let e;try{e=new URL(t)}catch{throw new Error(`Invalid Ollama host: not a valid URL (${t})`)}if(!lD.has(e.protocol))throw new Error(`Invalid Ollama host: scheme "${e.protocol}" not allowed (use http:// or https://)`);if(e.username||e.password)throw new Error("Invalid Ollama host: embedded credentials are not allowed");return t.replace(/\/+$/,"")}var Wn=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=dD(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 c_(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 Se(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 Se(this.id,`Rate limited (429) \u2014 temporarily deactivated for ${t.RATE_LIMIT_BACKOFF_MS/1e3}s`);if(!a.ok)throw new dt(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 $o(this.id,this.timeouts.generate):a instanceof dt||a instanceof Se?a:new dt(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 Se(this.id,`No models detected. Install a model first (ollama pull ${zy})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var pD=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function u_(t){return t.split(`
|
|
52
|
-
`).filter(n=>{let
|
|
53
|
-
`).trim()}function
|
|
54
|
-
`),r=[];for(let n of e)try{let
|
|
55
|
-
`)||t.trim()}var
|
|
56
|
-
`).trim();try{
|
|
57
|
-
`;if(n.goal&&(
|
|
58
|
-
`),n.turns.length>0){
|
|
51
|
+
\`\`\``);return e}function oD(t,e){let r=e?.model;return typeof r=="string"&&r.length>0?r:t}var sn=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 Yr(this,this.getCapabilities())}isAvailable(){return this.bridge.isAvailable()}async chat(e){if(!this.isAvailable())throw new xe(this.id,`${this.displayName} host bridge is not available`);try{let r=sD(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 s=await this.bridge.runTurn({prompt:r,system:e.system,metadata:n});return{text:s.text,model:oD(this.modelName,s.metadata),provider:this.id,metadata:s.metadata}}catch(r){let n=r instanceof Error?r.message:String(r);throw/sampling|host bridge unavailable|does not support/i.test(n)?new xe(this.id,n):new dt(this.id,n)}}};var iD={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"]}]},Cc=class extends sn{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:iD,modelName:e.modelName??"claude-host"})}};var aD={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"]}]},Dc=class extends sn{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:aD,modelName:e.modelName??"codex-host"})}};var cD={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"]}]},Oc=class extends sn{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:cD,modelName:e.modelName??"gemini-host"})}};Ar();var u_={"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 l_={"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 d_={"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 p_={"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 f_=Object.freeze({en:u_,ko:l_,ja:d_,zh:p_});function fD(t){return typeof t=="string"&&sc.includes(t)}function ep(t,e){return e===void 0?t:t.replace(/\{(\w+)\}/g,(r,n)=>{if(Object.prototype.hasOwnProperty.call(e,n)){let s=e[n];return typeof s=="number"?String(s):s}return r})}function rp(t){return t===void 0?tp(Tn):fD(t)?tp(t):(console.warn(`[i18n] unknown locale '${t}', falling back to ${Tn}`),tp(Tn))}function mD(t,e,r){let n=new Set;return{locale:t,t(s,o){let i=e[s];if(i!==void 0)return ep(i,o);let a=r[s];return a!==void 0?(n.has(s)||(n.add(s),console.warn(`[i18n] missing key '${s}' in locale '${t}', falling back to ${Rd}`)),ep(a,o)):(n.has(s)||(n.add(s),console.warn(`[i18n] missing key '${s}' in all bundles; returning raw key`)),ep(s,o))}}}function tp(t){return mD(t,f_[t],f_[Rd])}async function m_(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:hD(n.name||"")}))}function hD(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 yD=new Set(["http:","https:"]);function vD(t){let e;try{e=new URL(t)}catch{throw new Error(`Invalid Ollama host: not a valid URL (${t})`)}if(!yD.has(e.protocol))throw new Error(`Invalid Ollama host: scheme "${e.protocol}" not allowed (use http:// or https://)`);if(e.username||e.password)throw new Error("Invalid Ollama host: embedded credentials are not allowed");return t.replace(/\/+$/,"")}var Jn=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=vD(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 m_(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(s=>s.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 xe(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||{}},s=new AbortController,o=setTimeout(()=>s.abort(),this.timeouts.generate),i=()=>s.abort(e.signal.reason);e.signal&&(e.signal.aborted?s.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:s.signal});if(a.status===429)throw this.unavailableUntil=Date.now()+t.RATE_LIMIT_BACKOFF_MS,new xe(this.id,`Rate limited (429) \u2014 temporarily deactivated for ${t.RATE_LIMIT_BACKOFF_MS/1e3}s`);if(!a.ok)throw new dt(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 Ts(this.id,this.timeouts.generate):a instanceof dt||a instanceof xe?a:new dt(this.id,a.message)}finally{clearTimeout(o),e.signal&&e.signal.removeEventListener("abort",i)}}selectModel(){if(this.defaultModel!=="auto")return this.defaultModel;if(this.models.length===0)throw new xe(this.id,`No models detected. Install a model first (ollama pull ${qy})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var _D=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function h_(t){return t.split(`
|
|
52
|
+
`).filter(n=>{let s=n.trim();return s?!_D.some(o=>o.test(s)):!1}).join(`
|
|
53
|
+
`).trim()}function g_(t){let e=hi(t);return e&&typeof e.response=="string"?e.response:null}var np="gemini",sp="@google/gemini-cli",Gn=class{id;type="gemini-cli";timeout;available=!1;cliPath=null;defaultCwd;limiter=new Vs(Gy);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4,this.defaultCwd=e.workspaceBaseDir??process.cwd()}async initialize(){let e=await Ws(np,sp);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){return Hs(this.cliPath,np,sp,"Gemini")}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 xe(this.id,"Gemini CLI not installed");let r=Kn(e),n=Js(e,r),o=["-p",n?"Use the full instructions and file contents provided on stdin.":r,"-o","json"],{command:i,cliArgs:a}=Gs(this.cliPath,np,sp,o),c=c_(this.id),u=e.timeoutMs??this.timeout;try{let l=await vt({command:i,args:a,cwd:e.workspaceBaseDir??this.defaultCwd,stdin:n?r:void 0,timeout:u,onStderrChunk:f=>c.feed(f),onActivity:e.activity,signal:e.signal});if(l.exitCode!==0)try{Ks(l.exitCode,l.stderr,this.id)}catch(f){throw f.markUnavailable&&(this.available=!1),f}let d=g_(l.stdout);if(d!==null){let f=bD(l.stdout);return{text:d,model:f,provider:this.id}}return{text:h_(l.stdout),model:"gemini",provider:this.id}}catch(l){if(l instanceof xe)throw l.markUnavailable&&(this.available=!1),l;Ys(l,this.id,u)}}};function bD(t){try{let e=JSON.parse(t.trim());if(e?.stats?.models){for(let[n,s]of Object.entries(e.stats.models))if(s?.roles?.main)return n;let r=Object.keys(e.stats.models);if(r.length>0)return r[0]}}catch{}return"gemini"}import{randomUUID as wD}from"crypto";function op(t){let e=t.trim().split(`
|
|
54
|
+
`),r=[];for(let n of e)try{let s=JSON.parse(n);s.type==="item.completed"&&s.item?.type==="agent_message"&&s.item.text&&r.push(s.item.text)}catch{n.trim()&&r.push(n.trim())}return r.join(`
|
|
55
|
+
`)||t.trim()}var zc="codex",Mc="@openai/codex";function SD(t){return["-C",t]}function $D(t,e,r){return["exec","--skip-git-repo-check","-C",r,"--full-auto","--ephemeral","--json","--",e?"-":t]}function y_(t,e){try{t.activity?.(e)}catch{}}var Yn=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 Ws(zc,Mc);this.available=e.available,this.cliPath=e.cliPath,this.available&&this.cliPath&&(this.appServer=new Ac({command:this.cliPath==="npx"?"npx":zc,commandPrefix:this.cliPath==="npx"?[Mc]:void 0,commandArgs:SD(this.defaultCwd)}))}async healthCheck(){return Hs(this.cliPath,zc,Mc,"Codex")}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 xe(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(s){if(!this.shouldFallbackFrom(s))throw s}return this.chatViaCli(e)}shouldFallbackFrom(e){return!(e instanceof Nt||e instanceof xe||e instanceof dt)}async shutdown(){this.appServer&&await this.appServer.shutdown()}async chatViaAppServer(e){let r=e.timeoutMs??this.timeout,n={method:"exec",params:{prompt:Qd(Kn(e)),fullAuto:!0,ephemeral:!0},id:wD()};y_(e,{type:"start",at:new Date().toISOString(),command:"codex-app-server",timeoutMs:r});let s=await(async()=>{try{return await this.appServer.request(n,r,e.signal)}finally{y_(e,{type:"close",at:new Date().toISOString(),command:"codex-app-server"})}})();if(s.error)throw new dt(this.id,s.error.message);return{text:op(JSON.stringify(s.result)),model:"codex",provider:this.id}}async chatViaCli(e){let r=Qd(Kn(e)),n=process.platform==="win32"||Js(e,r),s=e.workspaceBaseDir??this.defaultCwd,o=$D(r,n,s),{command:i,cliArgs:a}=Gs(this.cliPath,zc,Mc,o),c=e.timeoutMs??this.timeout;try{let u=await vt({command:i,args:a,stdin:n?r:void 0,timeout:c,onActivity:e.activity,signal:e.signal});if(u.exitCode!==0)try{Ks(u.exitCode,u.stderr,this.id)}catch(d){throw d.markUnavailable&&(this.available=!1),d}return{text:op(u.stdout),model:"codex",provider:this.id}}catch(u){Ys(u,this.id,c)}}};function v_(t){let e=hi(t);return e?typeof e.result=="string"?e.result:typeof e.response=="string"?e.response:null:null}function __(t){let e=hi(t);return typeof e?.model=="string"?e.model:"claude"}var xD=1,ip="claude",ap="@anthropic-ai/claude-code",Xn=class{id;type="claude-cli";timeout;available=!1;cliPath=null;defaultCwd;limiter=new Vs(xD);constructor(e){this.id=e.id,this.timeout=e.timeout??12e4,this.defaultCwd=e.workspaceBaseDir??process.cwd()}async initialize(){let e=await Ws(ip,ap);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){return Hs(this.cliPath,ip,ap,"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 xe(this.id,"Claude CLI not installed");let r=Kn(e),n=process.platform==="win32"||Js(e,r),o=["-p",n?"Use the complete instructions and file contents provided on stdin.":r,"--output-format","json"];e.model&&o.push("--model",e.model);let{command:i,cliArgs:a}=Gs(this.cliPath,ip,ap,o),c=e.timeoutMs??this.timeout;try{let u=await vt({command:i,args:a,cwd:e.workspaceBaseDir??this.defaultCwd,stdin:n?r:void 0,timeout:c,onActivity:e.activity,signal:e.signal});if(u.exitCode!==0){let d=[u.stderr,u.stdout].filter(Boolean).join(`
|
|
56
|
+
`).trim();try{Ks(u.exitCode,d,this.id)}catch(p){throw(p.markUnavailable||/auth|credential|login|api key|oauth|token|401/i.test(d))&&(this.available=!1),p}}return{text:v_(u.stdout)??u.stdout.trim(),model:__(u.stdout),provider:this.id}}catch(u){Ys(u,this.id,c)}}};import{randomUUID as PD}from"crypto";var kD=7200*1e3,gi=class{debates=new Map;create(e){this.purgeStaleDebates();let r=PD(),n=new Date().toISOString(),s={id:r,topic:e.topic,goal:e.goal,providerIds:e.providerIds,turns:[],status:"active",documentId:e.documentId,createdAt:n};return this.debates.set(r,s),s}addTurn(e,r,n){let s=this.getState(e);if(!s)throw new Error(`Debate not found: ${e}`);if(s.status==="concluded")throw new Error(`Debate already concluded: ${e}`);let o={turnNumber:s.turns.length+1,speaker:r,content:n,timestamp:new Date().toISOString()};return s.turns.push(o),s}buildPromptForProvider(e,r){let n=this.getState(e);if(!n)throw new Error(`Debate not found: ${e}`);let s=`Topic: ${n.topic}
|
|
57
|
+
`;if(n.goal&&(s+=`Goal: ${n.goal}
|
|
58
|
+
`),n.turns.length>0){s+=`
|
|
59
59
|
=== Conversation History ===
|
|
60
60
|
|
|
61
|
-
`;let i=n.turns.length;if(i>
|
|
61
|
+
`;let i=n.turns.length;if(i>En){let u=i-En,l=[...new Set(n.turns.slice(0,u).map(d=>d.speaker))];s+=`[${u} earlier turn(s) omitted \u2014 participants: ${l.join(", ")}]
|
|
62
62
|
|
|
63
|
-
`}let a=n.turns.slice(-
|
|
63
|
+
`}let a=n.turns.slice(-En),c="";for(let u of a){let l=`[Turn ${u.turnNumber}] ${u.speaker}:
|
|
64
64
|
${u.content}
|
|
65
65
|
|
|
66
|
-
`;if(c.length+l.length
|
|
67
|
-
|
|
68
|
-
`;break}c+=l}
|
|
69
|
-
|
|
70
|
-
`}return n.turns.length===0?(
|
|
71
|
-
|
|
72
|
-
`,
|
|
73
|
-
`,
|
|
74
|
-
`,
|
|
75
|
-
`,
|
|
76
|
-
`,
|
|
77
|
-
`,
|
|
78
|
-
`):(
|
|
79
|
-
|
|
80
|
-
`,
|
|
81
|
-
`,
|
|
82
|
-
`,
|
|
83
|
-
`,
|
|
84
|
-
`,
|
|
85
|
-
`,
|
|
86
|
-
`,
|
|
87
|
-
`,
|
|
88
|
-
`),n.goal&&(
|
|
66
|
+
`;if(c.length+l.length>Ed){c+=`[... history truncated at ${Ed} characters]
|
|
67
|
+
|
|
68
|
+
`;break}c+=l}s+=c,s+=`===
|
|
69
|
+
|
|
70
|
+
`}return n.turns.length===0?(s+=`You are ${r}, acting as an independent analyst.
|
|
71
|
+
|
|
72
|
+
`,s+=`Instructions:
|
|
73
|
+
`,s+=`- Provide a thorough, detailed analysis of the topic
|
|
74
|
+
`,s+=`- Include specific reasoning, evidence, and concrete examples
|
|
75
|
+
`,s+=`- Present pros and cons where applicable
|
|
76
|
+
`,s+=`- Give actionable recommendations with clear justification
|
|
77
|
+
`,s+=`- Be comprehensive \u2014 longer, well-structured responses are preferred over brief ones
|
|
78
|
+
`):(s+=`You are ${r}, acting as an independent reviewer.
|
|
79
|
+
|
|
80
|
+
`,s+=`Instructions:
|
|
81
|
+
`,s+=`- Read the previous analysis carefully
|
|
82
|
+
`,s+=`- If you genuinely agree, say so clearly and explain why
|
|
83
|
+
`,s+=`- If you see actual problems or risks, point them out with specific reasoning
|
|
84
|
+
`,s+=`- Do NOT force criticism \u2014 only raise issues you believe are real
|
|
85
|
+
`,s+=`- Add any perspectives, considerations, or alternatives that were missed
|
|
86
|
+
`,s+=`- If you have a completely new idea or approach not yet discussed, present it fully
|
|
87
|
+
`,s+=`- Be thorough and detailed in your response
|
|
88
|
+
`),n.goal&&(s+=`
|
|
89
89
|
Evaluation goal: ${n.goal}
|
|
90
|
-
`),
|
|
90
|
+
`),s}conclude(e){let r=this.getState(e);if(!r)throw new Error(`Debate not found: ${e}`);return r.status="concluded",r}getState(e){return this.debates.get(e)}delete(e){return this.debates.delete(e)}markProviderUnavailable(e,r,n){let s=this.getState(e);if(!s)throw new Error(`Debate not found: ${e}`);s.providerIds.includes(r)&&(s.unavailableProviders||(s.unavailableProviders=[]),!s.unavailableProviders.some(o=>o.providerId===r)&&s.unavailableProviders.push({providerId:r,reason:n,recordedAt:new Date().toISOString()}))}getActiveProviders(e){let r=this.getState(e);if(!r)throw new Error(`Debate not found: ${e}`);let n=new Set((r.unavailableProviders??[]).map(s=>s.providerId));return r.providerIds.filter(s=>!n.has(s))}isProviderUnavailable(e,r){let n=this.getState(e);return n?(n.unavailableProviders??[]).some(s=>s.providerId===r):!1}buildTurnTranscript(e){let r=this.getState(e);if(!r)throw new Error(`Debate not found: ${e}`);let n=`# Debate: ${r.topic}
|
|
91
91
|
|
|
92
92
|
`;r.goal&&(n+=`**Goal:** ${r.goal}
|
|
93
93
|
|
|
@@ -95,36 +95,36 @@ Evaluation goal: ${n.goal}
|
|
|
95
95
|
|
|
96
96
|
`,n+=`---
|
|
97
97
|
|
|
98
|
-
`;for(let
|
|
98
|
+
`;for(let s of r.turns)n+=`### [Turn ${s.turnNumber}] ${s.speaker}
|
|
99
99
|
|
|
100
|
-
${
|
|
100
|
+
${s.content}
|
|
101
101
|
|
|
102
|
-
`;return n}purgeStaleDebates(){let e=Date.now();for(let[r,n]of this.debates){if(n.status!=="active")continue;let
|
|
103
|
-
Additional criteria: ${n}`:"",
|
|
104
|
-
${e.content}`,
|
|
105
|
-
`),i=await this.chatWith(r,{prompt:
|
|
106
|
-
`),
|
|
107
|
-
`)}return Buffer.byteLength(n,"utf-8")>
|
|
108
|
-
... [truncated]`)),n}},
|
|
109
|
-
... [truncated at ${
|
|
110
|
-
`)+i}},
|
|
102
|
+
`;return n}purgeStaleDebates(){let e=Date.now();for(let[r,n]of this.debates){if(n.status!=="active")continue;let s=new Date(n.createdAt).getTime();e-s>kD&&this.debates.delete(r)}}};import{mkdirSync as ED,readFileSync as b_,readdirSync as cp,existsSync as Nc,renameSync as TD,rmdirSync as ID}from"fs";import{join as RD}from"path";import{randomUUID as AD}from"crypto";function up(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 w_=new Set(["completed","completed_with_errors","failed"]);function S_(t,e){return w_.has(t)?!1:!!(t==="pending"&&e==="in_progress"||t==="in_progress"&&w_.has(e)||t==="in_progress"&&e==="in_progress")}function $_(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 yi=class{sessionDir;sessions;fullyLoaded=!1;constructor(e){this.sessionDir=e,ED(this.sessionDir,{recursive:!0}),this.migrateLegacyNestedSessions(),this.sessions=new Map}migrateLegacyNestedSessions(){let e=RD(this.sessionDir,"sessions");if(!Nc(e))return;let r;try{r=cp(e)}catch(s){console.warn(`[SessionManager] failed to read legacy nested dir ${e}: ${String(s)}`);return}let n=r.filter(s=>s.endsWith(".json"));for(let s of n){let o,i;try{o=Je(s,e),i=Je(s,this.sessionDir)}catch(a){console.warn(`[SessionManager] skipped legacy file ${JSON.stringify(s)}: ${String(a)}`);continue}if(Nc(i)){console.warn(`[SessionManager] migration skipped ${s}: destination already exists at ${i}`);continue}try{TD(o,i)}catch(a){console.warn(`[SessionManager] migration failed for ${s}: ${String(a)}`)}}try{cp(e).length===0&&ID(e)}catch(s){console.warn(`[SessionManager] could not remove legacy nested dir ${e}: ${String(s)}`)}}createSession(e,r){let n=new Date().toISOString(),s={id:AD(),type:e,status:"pending",config:r,createdAt:n,updatedAt:n};return this.sessions.set(s.id,s),this.persist(s),s}getSession(e){let r=this.sessions.get(e);if(r)return r;if(!this.fullyLoaded){let n;try{n=Je(`${e}.json`,this.sessionDir)}catch{return}if(Nc(n))try{let s=b_(n,"utf-8"),o=JSON.parse(s);return $_(o)?(this.sessions.set(o.id,o),o):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(!S_(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 s=this.getSession(e);if(!s)throw new Error(`Session not found: ${e}`);if(!S_(s.status,r))throw new Error(`Illegal session transition: ${s.id} ${s.status} -> ${r}`);s.status=r,n!==void 0&&(s.result=n),s.updatedAt=new Date().toISOString(),this.persist(s)}completeSession(e,r){this.transitionSession(e,"completed",r)}persist(e){let r=Je(`${e.id}.json`,this.sessionDir);Ze(r,e)}ensureFullyLoaded(){if(this.fullyLoaded)return;if(!Nc(this.sessionDir)){this.fullyLoaded=!0;return}let e=cp(this.sessionDir).filter(r=>r.endsWith(".json"));for(let r of e){let n=r.replace(/\.json$/,"");if(!this.sessions.has(n))try{let s=Je(r,this.sessionDir),o=b_(s,"utf-8"),i=JSON.parse(o);if(!$_(i))continue;this.sessions.set(i.id,i)}catch{}}this.fullyLoaded=!0}};function Xs(t){if(!t||!t.trim())return null;try{return JSON.parse(t.trim())}catch{}let e=[],r=0,n=-1;for(let s=0;s<t.length;s++){let o=t[s];o==="{"?(r===0&&(n=s),r++):o==="}"&&(r--,r===0&&n>=0&&(e.push(t.slice(n,s+1)),n=-1),r<0&&(r=0))}if(e.length===0)return null;for(let s=e.length-1;s>=0;s--)try{return JSON.parse(e[s])}catch{continue}return null}function x_(t,e,r){try{let n=Xs(t);if(n&&typeof n=="object")return e(n)}catch{}return r(t)}var vi=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,s=this.resolveValidators(e),o=[];for(let l of r)for(let d of s)d.id!==l.providerId&&o.push(this.reviewItem(l,d,n));let i=await Promise.all(o),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(s=>this.canValidate(s.id));let r=new Set,n=[];for(let s of e.items)r.has(s.providerId)||(r.add(s.providerId),this.canValidate(s.providerId)&&n.push(this.registry.get(s.providerId)));return n}isAgentTier(e){return this.registry.getCapability(e).tier==="agent"}async reviewItem(e,r,n){let s=n?`
|
|
103
|
+
Additional criteria: ${n}`:"",o=[`You are a cross-validator reviewing work from provider "${e.providerId}".`,`Task: ${e.task}`,`Content to review:
|
|
104
|
+
${e.content}`,s,"",'Respond with JSON only: { "passed": boolean, "feedback": "string", "suggestedFixes": "string or omit" }'].join(`
|
|
105
|
+
`),i=await this.chatWith(r,{prompt:o});return this.parseReview(e.providerId,r.id,i.text)}parseReview(e,r,n){return x_(n,s=>({targetProvider:e,reviewerProvider:r,passed:!!s.passed,feedback:String(s.feedback??""),suggestedFixes:s.suggestedFixes?String(s.suggestedFixes):void 0}),s=>({targetProvider:e,reviewerProvider:r,passed:!1,feedback:s}))}detectConflicts(e){let r=[],n=new Map;for(let s of e){let o=s.targetProvider;n.has(o)||n.set(o,[]),n.get(o).push(s)}for(let[s,o]of n){if(o.length<2)continue;let i=o.filter(c=>c.passed),a=o.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 "${s}": passed by [${c}], failed by [${u}]`)}}return r}};import{readFileSync as E_,readdirSync as T_,statSync as Lc}from"fs";import{join as I_,relative as OD}from"path";var P_=50*1024,jc=500,k_=100;function zD(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}function MD(t,e){let r=[],n=s=>{let o=Lc(s);if(o.isFile()){r.push(s);return}if(o.isDirectory())for(let i of T_(s)){let a=I_(s,i),c=Lc(a);c.isFile()?r.push(a):e&&c.isDirectory()&&n(a)}};return n(t),r}function ND(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]):".",s=e.slice(1).map(r);return{command:"powershell.exe",args:["-NoProfile","-NonInteractive","-Command",`Get-ChildItem -Name -LiteralPath ${n}${s.length?" "+s.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 R_={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=nn(String(t.path??""),e),n=E_(r,"utf-8");if(t.offset!==void 0||t.limit!==void 0){let s=n.split(`
|
|
106
|
+
`),o=Number(t.offset??0),i=Number(t.limit??s.length);n=s.slice(o,o+i).join(`
|
|
107
|
+
`)}return Buffer.byteLength(n,"utf-8")>P_&&(n=Bs(n,P_,`
|
|
108
|
+
... [truncated]`)),n}},jD={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=Ft(String(t.path??""),e),n=String(t.content??"");return ge(r,n),`File written: ${t.path} (${Buffer.byteLength(n,"utf-8")} bytes)`}},A_={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=nn(String(t.path??"."),e),n=!!t.recursive,s=[];function o(a,c){if(s.length>=jc)return;let u=T_(a);for(let l of u){if(s.length>=jc)break;let d=I_(a,l),p=c?`${c}/${l}`:l;try{let f=Lc(d);s.push(f.isDirectory()?`${p}/`:p),n&&f.isDirectory()&&o(d,p)}catch{}}}o(r,"");let i=s.length>=jc?`
|
|
109
|
+
... [truncated at ${jc} entries]`:"";return s.join(`
|
|
110
|
+
`)+i}},C_={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=nn(String(t.path??"."),e),s=t.glob?zD(String(t.glob)):null,o=Lc(n).isDirectory(),i=MD(n,o);try{let a=new RegExp(r),c=[];for(let u of i){let l=OD(e,u).replace(/\\/g,"/");if(s&&!s.test(l.split("/").pop()??l))continue;let d;try{d=E_(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>=k_))return c.join(`
|
|
111
111
|
`)+`
|
|
112
|
-
... [truncated at ${
|
|
113
|
-
`)||"No matches found."}catch{return"No matches found."}}},
|
|
112
|
+
... [truncated at ${k_} matches]`}return c.join(`
|
|
113
|
+
`)||"No matches found."}catch{return"No matches found."}}},LD={name:"shell_exec",description:`Execute a shell command. Only safe, read-oriented commands are allowed (${[...kc].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=Wv(r);if(!n.valid)return`Error: ${n.error}`;let s=r.split(/\s+/).filter(Boolean),o=s[0],i=s.slice(1),a=ND(o,i);try{let c=await vt({command:a.command,args:a.args,timeout:3e4,cwd:e,maxBuffer:102400}),u=c.stdout;return c.stderr&&(u+=(u?`
|
|
114
114
|
`:"")+`[stderr] ${c.stderr}`),c.exitCode!==0&&(u+=`
|
|
115
115
|
[exit code: ${c.exitCode}]`),c.truncated&&(u+=`
|
|
116
|
-
... [output truncated]`),u||"(no output)"}catch(c){return`Error: ${
|
|
116
|
+
... [output truncated]`),u||"(no output)"}catch(c){return`Error: ${D(c)}`}}};function lp(){return[R_,jD,A_,C_,LD]}function qc(){return[R_,A_,C_]}function dp(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 qD=15,FD=30,UD=3e5,ZD=2e3,VD=`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.
|
|
117
117
|
|
|
118
118
|
Guidelines:
|
|
119
119
|
- Read files before modifying them to understand the existing code.
|
|
120
120
|
- Use grep_search to find relevant code across the workspace.
|
|
121
121
|
- Write complete file contents when using file_write (not just diffs).
|
|
122
|
-
- Provide a clear summary of what you did when finished.`,
|
|
123
|
-
${c.content}`:c.content),!c.tool_calls||c.tool_calls.length===0)return{success:!0,output:
|
|
122
|
+
- Provide a clear summary of what you did when finished.`,Fc=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??qD,FD),this.timeoutMs=e.timeoutMs??UD,this.systemPrompt=e.systemPrompt??VD,this.tools=e.tools??lp(),this.toolDefs=dp(this.tools),this.toolMap=new Map(this.tools.map(r=>[r.name,r]))}async run(e){let r=Date.now(),n=[],s="",o=[{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:s||"Agent loop timed out before completion.",iterations:i,toolCalls:n,error:`Timed out after ${this.timeoutMs}ms`};this.pruneHistory(o);let a;try{a=await this.callOllama(o)}catch(u){let l=D(u);return{success:!1,output:s||"",iterations:i,toolCalls:n,error:`Ollama API error: ${l}`}}let c=a.message;if(c.content&&(s=s?`${s}
|
|
123
|
+
${c.content}`:c.content),!c.tool_calls||c.tool_calls.length===0)return{success:!0,output:s,iterations:i+1,toolCalls:n};o.push(c);for(let u of c.tool_calls){let l=u.function.name,d=u.function.arguments,p;if(typeof d=="string"){let v=Xs(d);p=v&&typeof v=="object"&&!Array.isArray(v)?v:{}}else p=d??{};let f=this.toolMap.get(l),m=Date.now(),h;if(!f)h=`Error: unknown tool '${l}'. Available tools: ${[...this.toolMap.keys()].join(", ")}`;else try{h=await f.execute(p,this.baseDir)}catch(v){h=`Error: ${D(v)}`}n.push({iteration:i,toolName:l,arguments:p,result:Bs(h,ZD,"... [truncated in log]"),durationMs:Date.now()-m}),o.push({role:"tool",content:h})}}return{success:!1,output:s||"Agent loop reached max iterations without completing.",iterations:this.maxIterations,toolCalls:n,error:`Max iterations (${this.maxIterations}) reached`}}pruneHistory(e){let r=[];for(let n=2;n<e.length;n++)e[n].role==="assistant"&&r.push(n);if(r.length>En){let n=r[r.length-En];e.splice(2,n-2)}}async callOllama(e){let r=`${this.host}/api/chat`,n={model:this.model,messages:e,tools:this.toolDefs,stream:!1},s=new AbortController,o=setTimeout(()=>s.abort(),this.timeoutMs);try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:s.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(o)}}};function D_(t){if(t.type!=="ollama")return null;let e=t;return typeof e.getConnectionInfo=="function"?e.getConnectionInfo():null}var Qs=class{tools;baseDir;constructor(e){this.tools=e.tools,this.baseDir=e.baseDir}async chat(e,r){if(ic(e.id,e.getCapabilities(),void 0,e.type).tier!=="tool")return e.chat(r);let s=D_(e);return s?{text:(await new Fc({providerHost:s.host,model:s.model,baseDir:this.baseDir,tools:this.tools}).run(r.prompt)).output,model:s.model,provider:e.id}:e.chat(r)}};import{existsSync as _i,readFileSync as HD,readdirSync as KD}from"fs";import{join as eo}from"path";var bi=class{baseDir;constructor(e){this.baseDir=e}async run(e={}){let r=e.timeoutMs??12e4,n=e.buildProfile??"auto",s=this.resolveProfile(n),o=e.designDoc??this.detectDesignDoc(),i=s?await this.runProfile(s,r):{exitCode:0,output:"(no build profile resolved)"},a=i.exitCode===0,c=i.output,u=[];s?u.push(`${s.name}: ${a?"PASS":"FAIL"}`):u.push("No profile resolved"),o&&u.push(`Design doc: ${o}`);let d=`**AutoQA: ${a?"PASS":"FAIL"}**
|
|
124
124
|
${u.join(`
|
|
125
|
-
`)}`;return{buildPassed:a,buildOutput:c,testsPassed:a,testOutput:c,designDoc:
|
|
126
|
-
${n.stderr}`.trim(),
|
|
127
|
-
... [truncated]`);return{exitCode:n.exitCode,output:
|
|
125
|
+
`)}`;return{buildPassed:a,buildOutput:c,testsPassed:a,testOutput:c,designDoc:o??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=Rs[e];return r?{name:r.name,command:r.command,args:r.args}:null}detectBuildProfile(){if(_i(eo(this.baseDir,"tsconfig.json")))return Rs.tsc;if(_i(eo(this.baseDir,"vitest.config.ts"))||_i(eo(this.baseDir,"vitest.config.js")))return Rs.vitest;let e=this.getPackageScripts();return e?.build?Rs["npm-build"]:e?.test&&e.test!=='echo "Error: no test specified" && exit 1'?Rs["npm-test"]:null}detectDesignDoc(){let e=eo(this.baseDir,"docs","plans");if(!_i(e))return null;try{let r=KD(e).filter(n=>n.endsWith(".md")).sort().reverse();if(r.length>0)return eo("docs","plans",r[0])}catch{}return null}getPackageScripts(){let e=eo(this.baseDir,"package.json");if(!_i(e))return null;try{return JSON.parse(HD(e,"utf-8")).scripts??null}catch{return null}}async runProfile(e,r){try{_c(e.command,e.args)}catch(n){return{exitCode:1,output:n instanceof Ct?n.message:`Profile ${e.name} rejected: ${n.message}`}}try{let n=await vt({command:e.command,args:[...e.args],cwd:this.baseDir,timeout:r,maxBuffer:10485760}),s=n.exitCode===0?n.stdout:`${n.stdout}
|
|
126
|
+
${n.stderr}`.trim(),o=Bs(s,1e4,`
|
|
127
|
+
... [truncated]`);return{exitCode:n.exitCode,output:o}}catch(n){return{exitCode:1,output:n.message??"AutoQA run failed"}}}};var JD=new Set(["","hello","hi","thanks","thank you","sure","okay","i agree","great question"]),GD=/[\w./\\]+\.[a-z]{1,4}/gi,YD=/\b\d+\.?\d*\b/g,XD=/`[^`\n]+`/g,QD=/https?:\/\/\S+/g,eO=/\b[a-z][a-zA-Z]*[A-Z][a-zA-Z]*\b|\b[a-z]+(?:_[a-z]+)+\b/g;function Uc(t){return Math.max(0,Math.min(1,t))}function jr(t,e){return t.match(e)?.length??0}function tO(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 rO(t){let e=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim();return JD.has(e)?!0:e.replace(/\s+/g,"").length<5}function nO(t){let e=tO(t);if(e.length===0)return .1;let r=e.filter(rO).length,n=(e.length-r)/e.length;return Math.max(.1,Uc(n))}function sO(t){let e=jr(t,/^\s*#\s+/gm),r=jr(t,/^\s*(?:[-*]|\d+\.)\s+/gm),n=Math.ceil(jr(t,/^\s*```/gm)/2),s=jr(t,/^\s*.*\|.*\s*$/gm),o=e+r+n+s;return Uc(o/3)}function oO(t){let e=jr(t,GD)+jr(t,YD)+jr(t,XD)+jr(t,QD)+jr(t,eO);return Uc(e/3)}function O_(t){let e=t.toLowerCase().match(/\b[\w-]+\b/g)??[];return new Set(e.filter(r=>r.length>=4))}function iO(t,e){if(e.length===0)return .5;let r=new Set;for(let i of e)for(let a of O_(i.content))r.add(a);if(r.size===0)return 0;let n=O_(t),s=0;for(let i of r)n.has(i)&&(s+=1);let o=Math.max(1,r.size*.3);return Uc(s/o)}function wi(t,e,r){let n={substanceRatio:nO(t),structureScore:sO(t),specificityScore:oO(t),engagementScore:iO(t,e)};return{score:(n.substanceRatio+n.structureScore+n.specificityScore+n.engagementScore)/4,breakdown:n}}import{mkdirSync as Zc,readFileSync as cO,readdirSync as pp,existsSync as to,statSync as z_,unlinkSync as uO}from"fs";import{basename as M_,join as Si,relative as N_,sep as j_}from"path";import{randomUUID as lO}from"crypto";var dO="reviews";function ro(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"untitled"}function pO(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"anonymous"}function no(){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 L_(t){return j_==="/"?t:t.split(j_).join("/")}var $i=class{reviewDir;individualDir;debateDir;synthesisDir;constructor(e){this.reviewDir=Si(e,dO),this.individualDir=Si(e,By),this.debateDir=Si(e,Is),this.synthesisDir=Si(e,Wy),Zc(this.reviewDir,{recursive:!0}),Zc(this.individualDir,{recursive:!0}),Zc(this.debateDir,{recursive:!0}),Zc(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 s of this.allDirs){if(!to(s))continue;let o;try{o=pp(s)}catch{continue}for(let i of o){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 s=Je(`${e}.md`,n);if(to(s))return s}catch(s){r===void 0&&(r=s)}throw r!==void 0?r:new Error(`Document not found: ${e}`)}async createReview(e){let r=no(),n=e.topic?ro(e.topic):lO().slice(0,8),s=this.nextSequenceGlobal(r),o=e.provider?`${e.provider}_${n}_${r}_${s}`:`${n}_${r}_${s}`,i=Je(`${o}.md`,this.reviewDir),a=`# Review: ${e.topic??o}
|
|
128
128
|
|
|
129
129
|
`;a+=`**Date:** ${new Date().toISOString().slice(0,10)}
|
|
130
130
|
`,e.provider&&(a+=`**Provider:** ${e.provider}
|
|
@@ -139,7 +139,7 @@ ${n.stderr}`.trim(),s=Lo(o,1e4,`
|
|
|
139
139
|
`}return a+=`
|
|
140
140
|
---
|
|
141
141
|
|
|
142
|
-
`,
|
|
142
|
+
`,ge(i,a),{id:o,content:a,path:i}}async createDebateDocument(e){let r=no(),n=ro(e.topic),s=this.nextSequenceGlobal(r),o=`${n}_${r}_${s}`,i=Je(`${o}.md`,this.debateDir),a=`# Debate: ${e.topic}
|
|
143
143
|
|
|
144
144
|
`;return a+=`**Date:** ${new Date().toISOString().slice(0,10)}
|
|
145
145
|
`,a+=`**Participants:** ${e.providers.join(", ")}
|
|
@@ -147,7 +147,7 @@ ${n.stderr}`.trim(),s=Lo(o,1e4,`
|
|
|
147
147
|
`),a+=`
|
|
148
148
|
---
|
|
149
149
|
|
|
150
|
-
`,
|
|
150
|
+
`,ge(i,a),{id:o,content:a,path:i}}async createIndividualReview(e){let r=no(),n=pO(e.participantId),s=ro(e.topic),o=this.nextSequenceGlobal(r),i=`${n}_${s}_${r}_${o}`,a=Je(`${i}.md`,this.individualDir),c=`# ${e.topic} \u2014 ${e.participantId}
|
|
151
151
|
|
|
152
152
|
`;if(c+=`**Date:** ${new Date().toISOString().slice(0,10)}
|
|
153
153
|
`,c+=`**Participant:** ${e.participantId}
|
|
@@ -162,7 +162,7 @@ ${n.stderr}`.trim(),s=Lo(o,1e4,`
|
|
|
162
162
|
`,c+=e.content,c+=`
|
|
163
163
|
|
|
164
164
|
---
|
|
165
|
-
`,
|
|
165
|
+
`,ge(a,c),{id:i,content:c,path:a}}async createIssueDocument(e){let r=no(),n=e.sessionId.slice(0,8),s=this.nextSequenceGlobal(r),o=`${Hy}_${n}_${r}_${s}`,i=Je(`${o}.md`,this.individualDir),a=`# Rejection Issue Report \u2014 ${e.topic}
|
|
166
166
|
|
|
167
167
|
`;if(a+=`**Session:** ${e.sessionId}
|
|
168
168
|
`,a+=`**Rejected at:** ${new Date().toISOString()}
|
|
@@ -181,160 +181,165 @@ ${n.stderr}`.trim(),s=Lo(o,1e4,`
|
|
|
181
181
|
`}a+=`
|
|
182
182
|
`}return a+=`
|
|
183
183
|
---
|
|
184
|
-
`,
|
|
185
|
-
|
|
186
|
-
`;if(
|
|
187
|
-
`,
|
|
188
|
-
`,
|
|
189
|
-
`,
|
|
190
|
-
`,
|
|
191
|
-
`,e.metadata)for(let[
|
|
192
|
-
`;if(
|
|
184
|
+
`,ge(i,a),{id:o,content:a,path:i}}buildSynthesisContent(e,r){let n=L_(N_(r,e.debatePath)),s=e.individualPaths.map(i=>L_(N_(r,i))),o=`# Synthesis: ${e.topic}
|
|
185
|
+
|
|
186
|
+
`;if(o+=`**Date:** ${new Date().toISOString().slice(0,10)}
|
|
187
|
+
`,o+=`**Status:** ${e.status}
|
|
188
|
+
`,o+=`**Rounds:** ${e.rounds}/${e.maxRounds}
|
|
189
|
+
`,o+=`**Participants:** ${e.participantIds.join(", ")}
|
|
190
|
+
`,o+=`**Session:** ${e.sessionId}
|
|
191
|
+
`,e.metadata)for(let[i,a]of Object.entries(e.metadata))o+=`**${i}:** ${a}
|
|
192
|
+
`;if(o+=`
|
|
193
193
|
## Sources
|
|
194
194
|
|
|
195
|
-
`,
|
|
196
|
-
`,e.individualPaths.length>0){
|
|
197
|
-
`;for(let
|
|
198
|
-
`}}return
|
|
195
|
+
`,o+=`- Debate transcript: [${M_(e.debatePath)}](${n})
|
|
196
|
+
`,e.individualPaths.length>0){o+=`- Individual reviews:
|
|
197
|
+
`;for(let i=0;i<e.individualPaths.length;i++){let a=e.individualPaths[i];o+=` - [${M_(a)}](${s[i]})
|
|
198
|
+
`}}return o+=`
|
|
199
199
|
---
|
|
200
200
|
|
|
201
|
-
`,
|
|
201
|
+
`,o+=e.body,o+=`
|
|
202
202
|
|
|
203
203
|
---
|
|
204
|
-
`,
|
|
204
|
+
`,o}async createSynthesis(e){let r=no(),n=ro(e.topic),s=this.nextSequenceGlobal(r),o=`${n}_${r}_${s}`,i=Je(`${o}.md`,this.synthesisDir),a=this.buildSynthesisContent(e,this.synthesisDir);return ge(i,a),{id:o,content:a,path:i}}async replaceSynthesis(e){let r=Je(`${e.synthesisId}.md`,this.synthesisDir);if(!to(r))throw new Error(`Synthesis document not found: ${e.synthesisId}`);let n=this.buildSynthesisContent(e,this.synthesisDir);return ge(r,n),{id:e.synthesisId,content:n,path:r}}async appendToSynthesis(e,r){let n=Je(`${e}.md`,this.synthesisDir);if(!to(n))throw new Error(`Synthesis document not found: ${e}`);yc(n,`
|
|
205
205
|
${r}
|
|
206
|
-
`)}async addComment(e,r){let n=this.resolveDocPath(e),
|
|
206
|
+
`)}async addComment(e,r){let n=this.resolveDocPath(e),s=`
|
|
207
207
|
## Comment by ${r.author}
|
|
208
208
|
|
|
209
209
|
${r.content}
|
|
210
210
|
|
|
211
211
|
---
|
|
212
|
-
`;
|
|
212
|
+
`;yc(n,s)}async replaceDocumentContent(e,r){let n=this.resolveDocPath(e);ge(n,r)}async read(e){let r=this.resolveDocPath(e),n=cO(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}}kindForDir(e){return e===this.individualDir?"individual":e===this.debateDir?"debate":e===this.synthesisDir?"synthesis":"general"}async createDocument(e){let r=e.kind??"general",n=this.resolveKindDir(r),s=no(),o=e.topic?ro(e.topic):ro(e.title),i=this.nextSequenceGlobal(s),a=`${o}_${s}_${i}`,c=Je(`${a}.md`,n),u=`# ${e.title}
|
|
213
213
|
|
|
214
214
|
`;if(e.metadata){for(let[l,d]of Object.entries(e.metadata))u+=`**${l}:** ${d}
|
|
215
215
|
`;u+=`
|
|
216
216
|
`}return u+=e.content,u+=`
|
|
217
217
|
|
|
218
218
|
---
|
|
219
|
-
`,ye(c,u),{id:a,content:u,path:c}}async list(){let e=[];for(let r of this.allDirs){if(!mi(r))continue;let n=cp(r).filter(o=>o.endsWith(".md"));for(let o of n){let s=o.replace(".md",""),i=rt(o,r),a=T_(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(!mi(a))continue;let c=cp(a).filter(u=>u.endsWith(".md")).map(u=>{let l=hi(a,u),d=tO(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{rO(c[u].path),i++}catch{}}}return{removed:i}}};var c3=Object.freeze({status:"aborted"});function S(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 jr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Mc={};function Lt(t){return t&&Object.assign(Mc,t),Mc}var ge={};lt(ge,{BIGINT_FORMAT_RANGES:()=>O_,Class:()=>lp,NUMBER_FORMAT_RANGES:()=>vp,aborted:()=>Yn,allowsEval:()=>hp,assert:()=>lO,assertEqual:()=>iO,assertIs:()=>cO,assertNever:()=>uO,assertNotEqual:()=>aO,assignProp:()=>mp,cached:()=>vi,captureStackTrace:()=>qc,cleanEnum:()=>SO,cleanRegex:()=>bi,clone:()=>gr,createTransparentProxy:()=>gO,defineLazy:()=>xe,esc:()=>Gn,escapeRegex:()=>nn,extend:()=>_O,finalizeIssue:()=>Yt,floatSafeRemainder:()=>fp,getElementAtPath:()=>dO,getEnumValues:()=>dp,getLengthableOrigin:()=>wi,getParsedType:()=>hO,getSizableOrigin:()=>z_,isObject:()=>Go,isPlainObject:()=>Yo,issue:()=>_p,joinValues:()=>Lc,jsonStringifyReplacer:()=>pp,merge:()=>bO,normalizeParams:()=>U,nullish:()=>_i,numKeys:()=>mO,omit:()=>vO,optionalKeys:()=>yp,partial:()=>wO,pick:()=>yO,prefixIssues:()=>yr,primitiveTypes:()=>D_,promiseAllObject:()=>pO,propertyKeyTypes:()=>gp,randomString:()=>fO,required:()=>$O,stringifyPrimitive:()=>Fc,unwrapMessage:()=>yi});function iO(t){return t}function aO(t){return t}function cO(t){}function uO(t){throw new Error}function lO(t){}function dp(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 Lc(t,e="|"){return t.map(r=>Fc(r)).join(e)}function pp(t,e){return typeof e=="bigint"?e.toString():e}function vi(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function _i(t){return t==null}function bi(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function fp(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 xe(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 mp(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function dO(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function pO(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 fO(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Gn(t){return JSON.stringify(t)}var qc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Go(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var hp=vi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Yo(t){if(Go(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Go(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function mO(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var hO=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}`)}},gp=new Set(["string","number","symbol"]),D_=new Set(["string","number","bigint","boolean","symbol","undefined"]);function nn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gr(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function U(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 gO(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 Fc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function yp(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var vp={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]},O_={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function yO(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 gr(t,{...t._zod.def,shape:r,checks:[]})}function vO(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 gr(t,{...t._zod.def,shape:r,checks:[]})}function _O(t,e){if(!Yo(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 mp(this,"shape",n),n},checks:[]};return gr(t,r)}function bO(t,e){return gr(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return mp(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function wO(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 gr(e,{...e._zod.def,shape:o,checks:[]})}function $O(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 gr(e,{...e._zod.def,shape:o,checks:[]})}function Yn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function yr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function yi(t){return typeof t=="string"?t:t?.message}function Yt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=yi(t.inst?._zod.def?.error?.(t))??yi(e?.error?.(t))??yi(r.customError?.(t))??yi(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function z_(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function wi(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function _p(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function SO(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var lp=class{constructor(...e){}};var N_=(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,pp,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Uc=S("$ZodError",N_),bp=S("$ZodError",N_,{Parent:Error});function j_(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 M_(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 L_=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 jr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Yt(c,s,Lt())));throw qc(a,o?.callee),a}return i.value};var q_=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=>Yt(c,s,Lt())));throw qc(a,o?.callee),a}return i.value};var wp=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 jr;return s.issues.length?{success:!1,error:new(t??Uc)(s.issues.map(i=>Yt(i,o,Lt())))}:{success:!0,data:s.value}},$i=wp(bp),$p=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=>Yt(i,o,Lt())))}:{success:!0,data:s.value}},Zc=$p(bp);var F_=/^[cC][^\s-]{8,}$/,U_=/^[0-9a-z]+$/,Z_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,V_=/^[0-9a-vA-V]{20}$/,B_=/^[A-Za-z0-9]{27}$/,W_=/^[a-zA-Z0-9_-]{21}$/,H_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var K_=/^([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})$/,Sp=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 J_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var kO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function G_(){return new RegExp(kO,"u")}var Y_=/^(?:(?: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])$/,Q_=/^(([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})$/,X_=/^((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])$/,eb=/^(([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])$/,tb=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,xp=/^[A-Za-z0-9_-]*$/,rb=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var nb=/^\+(?:[0-9]){6,14}[0-9]$/,ob="(?:(?:\\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])))",sb=new RegExp(`^${ob}$`);function ib(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 ab(t){return new RegExp(`^${ib(t)}$`)}function cb(t){let e=ib({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(`^${ob}T(?:${n})$`)}var ub=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var lb=/^\d+$/,db=/^-?\d+(?:\.\d+)?/i,pb=/true|false/i,fb=/null/i;var mb=/^[^A-Z]*$/,hb=/^[^a-z]*$/;var nt=S("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),gb={number:"number",bigint:"bigint",object:"date"},Pp=S("$ZodCheckLessThan",(t,e)=>{nt.init(t,e);let r=gb[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})}}),Ep=S("$ZodCheckGreaterThan",(t,e)=>{nt.init(t,e);let r=gb[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})}}),yb=S("$ZodCheckMultipleOf",(t,e)=>{nt.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):fp(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})}}),vb=S("$ZodCheckNumberFormat",(t,e)=>{nt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=vp[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=lb)}),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 _b=S("$ZodCheckMaxLength",(t,e)=>{var r;nt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!_i(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=wi(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),bb=S("$ZodCheckMinLength",(t,e)=>{var r;nt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!_i(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=wi(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),wb=S("$ZodCheckLengthEquals",(t,e)=>{var r;nt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!_i(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=wi(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})}}),Si=S("$ZodCheckStringFormat",(t,e)=>{var r,n;nt.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=()=>{})}),$b=S("$ZodCheckRegex",(t,e)=>{Si.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})}}),Sb=S("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=mb),Si.init(t,e)}),xb=S("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=hb),Si.init(t,e)}),kb=S("$ZodCheckIncludes",(t,e)=>{nt.init(t,e);let r=nn(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})}}),Pb=S("$ZodCheckStartsWith",(t,e)=>{nt.init(t,e);let r=new RegExp(`^${nn(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})}}),Eb=S("$ZodCheckEndsWith",(t,e)=>{nt.init(t,e);let r=new RegExp(`.*${nn(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 Tb=S("$ZodCheckOverwrite",(t,e)=>{nt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Vc=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(`
|
|
220
|
-
`).filter(i=>i),
|
|
221
|
-
`))}};var
|
|
219
|
+
`,ge(c,u),{id:a,content:u,path:c}}async list(){let e=[];for(let r of this.allDirs){if(!to(r))continue;let n=pp(r).filter(s=>s.endsWith(".md"));for(let s of n){let o=s.replace(".md",""),i=Je(s,r),a=z_(i);e.push({id:o,path:i,kind:this.kindForDir(r),sizeBytes:a.size,modifiedAt:a.mtime.toISOString()})}}return e}cleanup(e={}){let r=e.maxAgeDays??30,n=e.maxFilesPerDir??e.maxFiles??100,s=Date.now(),o=r*24*60*60*1e3,i=0;for(let a of this.allDirs){if(!to(a))continue;let c=pp(a).filter(u=>u.endsWith(".md")).map(u=>{let l=Si(a,u),d=z_(l);return{path:l,mtime:d.mtimeMs}}).sort((u,l)=>l.mtime-u.mtime);for(let u=0;u<c.length;u++){let l=s-c[u].mtime;if(u>=n||l>o)try{uO(c[u].path),i++}catch{}}}return{removed:i}}};var S3=Object.freeze({status:"aborted"});function $(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 s=r?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function i(a){var c;let u=r?.Parent?new o: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 Lr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Vc={};function Ut(t){return t&&Object.assign(Vc,t),Vc}var ye={};lt(ye,{BIGINT_FORMAT_RANGES:()=>F_,Class:()=>mp,NUMBER_FORMAT_RANGES:()=>Sp,aborted:()=>es,allowsEval:()=>_p,assert:()=>yO,assertEqual:()=>fO,assertIs:()=>hO,assertNever:()=>gO,assertNotEqual:()=>mO,assignProp:()=>vp,cached:()=>Pi,captureStackTrace:()=>Wc,cleanEnum:()=>RO,cleanRegex:()=>Ei,clone:()=>_r,createTransparentProxy:()=>$O,defineLazy:()=>Pe,esc:()=>Qn,escapeRegex:()=>on,extend:()=>kO,finalizeIssue:()=>tr,floatSafeRemainder:()=>yp,getElementAtPath:()=>vO,getEnumValues:()=>hp,getLengthableOrigin:()=>Ti,getParsedType:()=>SO,getSizableOrigin:()=>U_,isObject:()=>so,isPlainObject:()=>oo,issue:()=>$p,joinValues:()=>Bc,jsonStringifyReplacer:()=>gp,merge:()=>EO,normalizeParams:()=>U,nullish:()=>ki,numKeys:()=>wO,omit:()=>PO,optionalKeys:()=>wp,partial:()=>TO,pick:()=>xO,prefixIssues:()=>br,primitiveTypes:()=>q_,promiseAllObject:()=>_O,propertyKeyTypes:()=>bp,randomString:()=>bO,required:()=>IO,stringifyPrimitive:()=>Hc,unwrapMessage:()=>xi});function fO(t){return t}function mO(t){return t}function hO(t){}function gO(t){throw new Error}function yO(t){}function hp(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,s])=>e.indexOf(+n)===-1).map(([n,s])=>s)}function Bc(t,e="|"){return t.map(r=>Hc(r)).join(e)}function gp(t,e){return typeof e=="bigint"?e.toString():e}function Pi(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ki(t){return t==null}function Ei(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function yp(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function Pe(t,e,r){Object.defineProperty(t,e,{get(){{let s=r();return t[e]=s,s}throw new Error("cached value already set")},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function vp(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function vO(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function _O(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let s={};for(let o=0;o<e.length;o++)s[e[o]]=n[o];return s})}function bO(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Qn(t){return JSON.stringify(t)}var Wc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function so(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var _p=Pi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function oo(t){if(so(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(so(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function wO(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var SO=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}`)}},bp=new Set(["string","number","symbol"]),q_=new Set(["string","number","bigint","boolean","symbol","undefined"]);function on(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _r(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function U(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 $O(t){let e;return new Proxy({},{get(r,n,s){return e??(e=t()),Reflect.get(e,n,s)},set(r,n,s,o){return e??(e=t()),Reflect.set(e,n,s,o)},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,s){return e??(e=t()),Reflect.defineProperty(e,n,s)}})}function Hc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function wp(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Sp={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]},F_={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function xO(t,e){let r={},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(r[s]=n.shape[s])}return _r(t,{...t._zod.def,shape:r,checks:[]})}function PO(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let s in e){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete r[s]}return _r(t,{...t._zod.def,shape:r,checks:[]})}function kO(t,e){if(!oo(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 vp(this,"shape",n),n},checks:[]};return _r(t,r)}function EO(t,e){return _r(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return vp(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function TO(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in n))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=t?new t({type:"optional",innerType:n[o]}):n[o])}else for(let o in n)s[o]=t?new t({type:"optional",innerType:n[o]}):n[o];return _r(e,{...e._zod.def,shape:s,checks:[]})}function IO(t,e,r){let n=e._zod.def.shape,s={...n};if(r)for(let o in r){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);r[o]&&(s[o]=new t({type:"nonoptional",innerType:n[o]}))}else for(let o in n)s[o]=new t({type:"nonoptional",innerType:n[o]});return _r(e,{...e._zod.def,shape:s,checks:[]})}function es(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function br(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function xi(t){return typeof t=="string"?t:t?.message}function tr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let s=xi(t.inst?._zod.def?.error?.(t))??xi(e?.error?.(t))??xi(r.customError?.(t))??xi(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function U_(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ti(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function $p(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function RO(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var mp=class{constructor(...e){}};var Z_=(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,gp,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Kc=$("$ZodError",Z_),xp=$("$ZodError",Z_,{Parent:Error});function V_(t,e=r=>r.message){let r={},n=[];for(let s of t.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}function B_(t,e){let r=e||function(o){return o.message},n={_errors:[]},s=o=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>s({issues:a}));else if(i.code==="invalid_key")s({issues:i.issues});else if(i.code==="invalid_element")s({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 s(t),n}var W_=t=>(e,r,n,s)=>{let o=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Lr;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>tr(c,o,Ut())));throw Wc(a,s?.callee),a}return i.value};var H_=t=>async(e,r,n,s)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>tr(c,o,Ut())));throw Wc(a,s?.callee),a}return i.value};var Pp=t=>(e,r,n)=>{let s=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new Lr;return o.issues.length?{success:!1,error:new(t??Kc)(o.issues.map(i=>tr(i,s,Ut())))}:{success:!0,data:o.value}},Ii=Pp(xp),kp=t=>async(e,r,n)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=e._zod.run({value:r,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(i=>tr(i,s,Ut())))}:{success:!0,data:o.value}},Jc=kp(xp);var K_=/^[cC][^\s-]{8,}$/,J_=/^[0-9a-z]+$/,G_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Y_=/^[0-9a-vA-V]{20}$/,X_=/^[A-Za-z0-9]{27}$/,Q_=/^[a-zA-Z0-9_-]{21}$/,eb=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var tb=/^([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})$/,Ep=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 rb=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var CO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function nb(){return new RegExp(CO,"u")}var sb=/^(?:(?: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])$/,ob=/^(([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})$/,ib=/^((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])$/,ab=/^(([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])$/,cb=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Tp=/^[A-Za-z0-9_-]*$/,ub=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var lb=/^\+(?:[0-9]){6,14}[0-9]$/,db="(?:(?:\\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])))",pb=new RegExp(`^${db}$`);function fb(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 mb(t){return new RegExp(`^${fb(t)}$`)}function hb(t){let e=fb({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(`^${db}T(?:${n})$`)}var gb=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var yb=/^\d+$/,vb=/^-?\d+(?:\.\d+)?/i,_b=/true|false/i,bb=/null/i;var wb=/^[^A-Z]*$/,Sb=/^[^a-z]*$/;var nt=$("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),$b={number:"number",bigint:"bigint",object:"date"},Rp=$("$ZodCheckLessThan",(t,e)=>{nt.init(t,e);let r=$b[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.maximum:s.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?s.maximum=e.value:s.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})}}),Ap=$("$ZodCheckGreaterThan",(t,e)=>{nt.init(t,e);let r=$b[typeof e.value];t._zod.onattach.push(n=>{let s=n._zod.bag,o=(e.inclusive?s.minimum:s.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?s.minimum=e.value:s.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})}}),xb=$("$ZodCheckMultipleOf",(t,e)=>{nt.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):yp(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})}}),Pb=$("$ZodCheckNumberFormat",(t,e)=>{nt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[s,o]=Sp[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=s,a.maximum=o,r&&(a.pattern=yb)}),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<s&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),a>o&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:t})}});var kb=$("$ZodCheckMaxLength",(t,e)=>{var r;nt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!ki(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let s=n.value;if(s.length<=e.maximum)return;let i=Ti(s);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Eb=$("$ZodCheckMinLength",(t,e)=>{var r;nt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!ki(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let s=n.value;if(s.length>=e.minimum)return;let i=Ti(s);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Tb=$("$ZodCheckLengthEquals",(t,e)=>{var r;nt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!ki(s)&&s.length!==void 0}),t._zod.onattach.push(n=>{let s=n._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=n=>{let s=n.value,o=s.length;if(o===e.length)return;let i=Ti(s),a=o>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})}}),Ri=$("$ZodCheckStringFormat",(t,e)=>{var r,n;nt.init(t,e),t._zod.onattach.push(s=>{let o=s._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=s=>{e.pattern.lastIndex=0,!e.pattern.test(s.value)&&s.issues.push({origin:"string",code:"invalid_format",format:e.format,input:s.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Ib=$("$ZodCheckRegex",(t,e)=>{Ri.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})}}),Rb=$("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=wb),Ri.init(t,e)}),Ab=$("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Sb),Ri.init(t,e)}),Cb=$("$ZodCheckIncludes",(t,e)=>{nt.init(t,e);let r=on(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(s=>{let o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=s=>{s.value.includes(e.includes,e.position)||s.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:s.value,inst:t,continue:!e.abort})}}),Db=$("$ZodCheckStartsWith",(t,e)=>{nt.init(t,e);let r=new RegExp(`^${on(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.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})}}),Ob=$("$ZodCheckEndsWith",(t,e)=>{nt.init(t,e);let r=new RegExp(`.*${on(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let s=n._zod.bag;s.patterns??(s.patterns=new Set),s.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 zb=$("$ZodCheckOverwrite",(t,e)=>{nt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Gc=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(`
|
|
220
|
+
`).filter(i=>i),s=Math.min(...n.map(i=>i.length-i.trimStart().length)),o=n.map(i=>i.slice(s)).map(i=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let e=Function,r=this?.args,s=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...r,s.join(`
|
|
221
|
+
`))}};var Nb={major:4,minor:0,patch:0};var ke=$("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Nb;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let s of n)for(let o of s._zod.onattach)o(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let s=(o,i,a)=>{let c=es(o),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(o))continue}else if(c)continue;let d=o.issues.length,p=l._zod.check(o);if(p instanceof Promise&&a?.async===!1)throw new Lr;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,o.issues.length!==d&&(c||(c=es(o,d)))});else{if(o.issues.length===d)continue;c||(c=es(o,d))}}return u?u.then(()=>o):o};t._zod.run=(o,i)=>{let a=t._zod.parse(o,i);if(a instanceof Promise){if(i.async===!1)throw new Lr;return a.then(c=>s(c,n,i))}return s(a,n,i)}}t["~standard"]={validate:s=>{try{let o=Ii(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Jc(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Xc=$("$ZodString",(t,e)=>{ke.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??gb(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}}),Te=$("$ZodStringFormat",(t,e)=>{Ri.init(t,e),Xc.init(t,e)}),Hb=$("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=tb),Te.init(t,e)}),Kb=$("$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=Ep(n))}else e.pattern??(e.pattern=Ep());Te.init(t,e)}),Jb=$("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=rb),Te.init(t,e)}),Gb=$("$ZodURL",(t,e)=>{Te.init(t,e),t._zod.check=r=>{try{let n=r.value,s=new URL(n),o=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:ub.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.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("/")&&o.endsWith("/")?r.value=o.slice(0,-1):r.value=o;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Yb=$("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=nb()),Te.init(t,e)}),Xb=$("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Q_),Te.init(t,e)}),Qb=$("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=K_),Te.init(t,e)}),ew=$("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=J_),Te.init(t,e)}),tw=$("$ZodULID",(t,e)=>{e.pattern??(e.pattern=G_),Te.init(t,e)}),rw=$("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Y_),Te.init(t,e)}),nw=$("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=X_),Te.init(t,e)}),sw=$("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=hb(e)),Te.init(t,e)}),ow=$("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=pb),Te.init(t,e)}),iw=$("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=mb(e)),Te.init(t,e)}),aw=$("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=eb),Te.init(t,e)}),cw=$("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=sb),Te.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),uw=$("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=ob),Te.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})}}}),lw=$("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=ib),Te.init(t,e)}),dw=$("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=ab),Te.init(t,e),t._zod.check=r=>{let[n,s]=r.value.split("/");try{if(!s)throw new Error;let o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>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 pw(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var fw=$("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=cb),Te.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{pw(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function DO(t){if(!Tp.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return pw(r)}var mw=$("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Tp),Te.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{DO(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),hw=$("$ZodE164",(t,e)=>{e.pattern??(e.pattern=lb),Te.init(t,e)});function OO(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let s=JSON.parse(atob(n));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}var gw=$("$ZodJWT",(t,e)=>{Te.init(t,e),t._zod.check=r=>{OO(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Dp=$("$ZodNumber",(t,e)=>{ke.init(t,e),t._zod.pattern=t._zod.bag.pattern??vb,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let s=r.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return r;let o=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...o?{received:o}:{}}),r}}),yw=$("$ZodNumber",(t,e)=>{Pb.init(t,e),Dp.init(t,e)}),vw=$("$ZodBoolean",(t,e)=>{ke.init(t,e),t._zod.pattern=_b,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let s=r.value;return typeof s=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),r}});var _w=$("$ZodNull",(t,e)=>{ke.init(t,e),t._zod.pattern=bb,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let s=r.value;return s===null||r.issues.push({expected:"null",code:"invalid_type",input:s,inst:t}),r}});var bw=$("$ZodUnknown",(t,e)=>{ke.init(t,e),t._zod.parse=r=>r}),ww=$("$ZodNever",(t,e)=>{ke.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function jb(t,e,r){t.issues.length&&e.issues.push(...br(r,t.issues)),e.value[r]=t.value}var Sw=$("$ZodArray",(t,e)=>{ke.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!Array.isArray(s))return r.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),r;r.value=Array(s.length);let o=[];for(let i=0;i<s.length;i++){let a=s[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?o.push(c.then(u=>jb(u,r,i))):jb(c,r,i)}return o.length?Promise.all(o).then(()=>r):r}});function Yc(t,e,r){t.issues.length&&e.issues.push(...br(r,t.issues)),e.value[r]=t.value}function Lb(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(...br(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var $w=$("$ZodObject",(t,e)=>{ke.init(t,e);let r=Pi(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof ke))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=wp(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 h of m.values)p[f].add(h)}}return p});let n=d=>{let p=new Gc(["shape","payload","ctx"]),f=r.value,m=b=>{let _=Qn(b);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),v=0;for(let b of f.keys)h[b]=`key_${v++}`;p.write("const newResult = {}");for(let b of f.keys)if(f.optionalKeys.has(b)){let _=h[b];p.write(`const ${_} = ${m(b)};`);let P=Qn(b);p.write(`
|
|
222
222
|
if (${_}.issues.length) {
|
|
223
|
-
if (input[${
|
|
224
|
-
if (${
|
|
225
|
-
newResult[${
|
|
223
|
+
if (input[${P}] === undefined) {
|
|
224
|
+
if (${P} in input) {
|
|
225
|
+
newResult[${P}] = undefined;
|
|
226
226
|
}
|
|
227
227
|
} else {
|
|
228
228
|
payload.issues = payload.issues.concat(
|
|
229
229
|
${_}.issues.map((iss) => ({
|
|
230
230
|
...iss,
|
|
231
|
-
path: iss.path ? [${
|
|
231
|
+
path: iss.path ? [${P}, ...iss.path] : [${P}],
|
|
232
232
|
}))
|
|
233
233
|
);
|
|
234
234
|
}
|
|
235
235
|
} else if (${_}.value === undefined) {
|
|
236
|
-
if (${
|
|
236
|
+
if (${P} in input) newResult[${P}] = undefined;
|
|
237
237
|
} else {
|
|
238
|
-
newResult[${
|
|
238
|
+
newResult[${P}] = ${_}.value;
|
|
239
239
|
}
|
|
240
240
|
`)}else{let _=h[b];p.write(`const ${_} = ${m(b)};`),p.write(`
|
|
241
241
|
if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
|
|
242
242
|
...iss,
|
|
243
|
-
path: iss.path ? [${
|
|
244
|
-
})));`),p.write(`newResult[${Gn(b)}] = ${_}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let v=p.compile();return(b,_)=>v(d,b,_)},o,s=Go,i=!Mc.jitless,c=i&&hp.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 _=l.shape;for(let k of l.keys){let x=_[k],L=x._zod.run({value:f[k],issues:[]},p),P=x._zod.optin==="optional"&&x._zod.optout==="optional";L instanceof Promise?m.push(L.then(M=>P?Cb(M,d,k,f):Bc(M,d,k))):P?Cb(L,d,k,f):Bc(L,d,k)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let h=[],y=l.keySet,v=u._zod,b=v.def.type;for(let _ of Object.keys(f)){if(y.has(_))continue;if(b==="never"){h.push(_);continue}let k=v.run({value:f[_],issues:[]},p);k instanceof Promise?m.push(k.then(x=>Bc(x,d,_))):Bc(k,d,_)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function Db(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=>Yt(s,n,Lt())))}),e}var Ip=S("$ZodUnion",(t,e)=>{ke.init(t,e),xe(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),xe(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),xe(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),xe(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=>bi(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=>Db(i,r,t,n)):Db(s,r,t,n)}}),yw=S("$ZodDiscriminatedUnion",(t,e)=>{Ip.init(t,e);let r=t._zod.parse;xe(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=vi(()=>{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(!Go(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)}}),vw=S("$ZodIntersection",(t,e)=>{ke.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])=>Ob(r,c,u)):Ob(r,s,i)}});function Tp(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(Yo(t)&&Yo(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=Tp(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=Tp(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 Ob(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Yn(t))return t;let n=Tp(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 _w=S("$ZodRecord",(t,e)=>{ke.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Yo(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(...yr(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...yr(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=>Yt(u,n,Lt())),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(...yr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...yr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var bw=S("$ZodEnum",(t,e)=>{ke.init(t,e);let r=dp(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>gp.has(typeof n)).map(n=>typeof n=="string"?nn(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}}),ww=S("$ZodLiteral",(t,e)=>{ke.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?nn(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 $w=S("$ZodTransform",(t,e)=>{ke.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 jr;return r.value=o,r}}),Sw=S("$ZodOptional",(t,e)=>{ke.init(t,e),t._zod.optin="optional",t._zod.optout="optional",xe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),xe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${bi(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)}),xw=S("$ZodNullable",(t,e)=>{ke.init(t,e),xe(t._zod,"optin",()=>e.innerType._zod.optin),xe(t._zod,"optout",()=>e.innerType._zod.optout),xe(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${bi(r.source)}|null)$`):void 0}),xe(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)}),kw=S("$ZodDefault",(t,e)=>{ke.init(t,e),t._zod.optin="optional",xe(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=>zb(s,e)):zb(o,e)}});function zb(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Pw=S("$ZodPrefault",(t,e)=>{ke.init(t,e),t._zod.optin="optional",xe(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))}),Ew=S("$ZodNonOptional",(t,e)=>{ke.init(t,e),xe(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=>Nb(s,t)):Nb(o,t)}});function Nb(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 Tw=S("$ZodCatch",(t,e)=>{ke.init(t,e),t._zod.optin="optional",xe(t._zod,"optout",()=>e.innerType._zod.optout),xe(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=>Yt(i,n,Lt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Yt(s,n,Lt()))},input:r.value}),r.issues=[]),r)}});var Rw=S("$ZodPipe",(t,e)=>{ke.init(t,e),xe(t._zod,"values",()=>e.in._zod.values),xe(t._zod,"optin",()=>e.in._zod.optin),xe(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=>jb(s,e,n)):jb(o,e,n)}});function jb(t,e,r){return Yn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Iw=S("$ZodReadonly",(t,e)=>{ke.init(t,e),xe(t._zod,"propValues",()=>e.innerType._zod.propValues),xe(t._zod,"values",()=>e.innerType._zod.values),xe(t._zod,"optin",()=>e.innerType._zod.optin),xe(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(Mb):Mb(o)}});function Mb(t){return t.value=Object.freeze(t.value),t}var Aw=S("$ZodCustom",(t,e)=>{nt.init(t,e),ke.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=>Lb(s,r,n,t));Lb(o,r,n,t)}});function Lb(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(_p(o))}}var TO=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},RO=()=>{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 ${TO(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Fc(n.values[0])}`:`Invalid option: expected one of ${Lc(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":""}: ${Lc(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 Cw(){return{localeError:RO()}}var Ap=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 IO(){return new Ap}var xi=IO();function Dw(t,e){return new t({type:"string",...U(e)})}function Ow(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...U(e)})}function Cp(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...U(e)})}function zw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...U(e)})}function Nw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...U(e)})}function jw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...U(e)})}function Mw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...U(e)})}function Lw(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...U(e)})}function qw(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...U(e)})}function Fw(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...U(e)})}function Uw(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...U(e)})}function Zw(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...U(e)})}function Vw(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...U(e)})}function Bw(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...U(e)})}function Ww(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...U(e)})}function Hw(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...U(e)})}function Kw(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...U(e)})}function Jw(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...U(e)})}function Gw(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...U(e)})}function Yw(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...U(e)})}function Qw(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...U(e)})}function Xw(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...U(e)})}function e$(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...U(e)})}function t$(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...U(e)})}function r$(t,e){return new t({type:"string",format:"date",check:"string_format",...U(e)})}function n$(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...U(e)})}function o$(t,e){return new t({type:"string",format:"duration",check:"string_format",...U(e)})}function s$(t,e){return new t({type:"number",checks:[],...U(e)})}function i$(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...U(e)})}function a$(t,e){return new t({type:"boolean",...U(e)})}function c$(t,e){return new t({type:"null",...U(e)})}function u$(t){return new t({type:"unknown"})}function l$(t,e){return new t({type:"never",...U(e)})}function Hc(t,e){return new Pp({check:"less_than",...U(e),value:t,inclusive:!1})}function ki(t,e){return new Pp({check:"less_than",...U(e),value:t,inclusive:!0})}function Kc(t,e){return new Ep({check:"greater_than",...U(e),value:t,inclusive:!1})}function Pi(t,e){return new Ep({check:"greater_than",...U(e),value:t,inclusive:!0})}function Jc(t,e){return new yb({check:"multiple_of",...U(e),value:t})}function Gc(t,e){return new _b({check:"max_length",...U(e),maximum:t})}function Qo(t,e){return new bb({check:"min_length",...U(e),minimum:t})}function Yc(t,e){return new wb({check:"length_equals",...U(e),length:t})}function Dp(t,e){return new $b({check:"string_format",format:"regex",...U(e),pattern:t})}function Op(t){return new Sb({check:"string_format",format:"lowercase",...U(t)})}function zp(t){return new xb({check:"string_format",format:"uppercase",...U(t)})}function Np(t,e){return new kb({check:"string_format",format:"includes",...U(e),includes:t})}function jp(t,e){return new Pb({check:"string_format",format:"starts_with",...U(e),prefix:t})}function Mp(t,e){return new Eb({check:"string_format",format:"ends_with",...U(e),suffix:t})}function Qn(t){return new Tb({check:"overwrite",tx:t})}function Lp(t){return Qn(e=>e.normalize(t))}function qp(){return Qn(t=>t.trim())}function Fp(){return Qn(t=>t.toLowerCase())}function Up(){return Qn(t=>t.toUpperCase())}function d$(t,e,r){return new t({type:"array",element:e,...U(r)})}function p$(t,e,r){let n=U(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function f$(t,e,r){return new t({type:"custom",check:"custom",fn:e,...U(r)})}function Xo(t){return!!t._zod}function on(t,e){return Xo(t)?$i(t,e):t.safeParse(e)}function Qc(t){if(!t)return;let e;if(Xo(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function m$(t){if(Xo(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 Ti={};lt(Ti,{ZodISODate:()=>g$,ZodISODateTime:()=>h$,ZodISODuration:()=>v$,ZodISOTime:()=>y$,date:()=>Vp,datetime:()=>Zp,duration:()=>Wp,time:()=>Bp});var h$=S("ZodISODateTime",(t,e)=>{Yb.init(t,e),Oe.init(t,e)});function Zp(t){return t$(h$,t)}var g$=S("ZodISODate",(t,e)=>{Qb.init(t,e),Oe.init(t,e)});function Vp(t){return r$(g$,t)}var y$=S("ZodISOTime",(t,e)=>{Xb.init(t,e),Oe.init(t,e)});function Bp(t){return n$(y$,t)}var v$=S("ZodISODuration",(t,e)=>{ew.init(t,e),Oe.init(t,e)});function Wp(t){return o$(v$,t)}var _$=(t,e)=>{Uc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>M_(t,r)},flatten:{value:r=>j_(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},t5=S("ZodError",_$),Ri=S("ZodError",_$,{Parent:Error});var b$=L_(Ri),w$=q_(Ri),$$=wp(Ri),S$=$p(Ri);var Me=S("ZodType",(t,e)=>(ke.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)=>gr(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>b$(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>$$(t,r,n),t.parseAsync=async(r,n)=>w$(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>S$(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(Ez(r,n)),t.superRefine=r=>t.check(Tz(r)),t.overwrite=r=>t.check(Qn(r)),t.optional=()=>Ne(t),t.nullable=()=>P$(t),t.nullish=()=>Ne(P$(t)),t.nonoptional=r=>bz(t,r),t.array=()=>ie(t),t.or=r=>Te([t,r]),t.and=r=>eu(t,r),t.transform=r=>Kp(t,C$(r)),t.default=r=>yz(t,r),t.prefault=r=>_z(t,r),t.catch=r=>$z(t,r),t.pipe=r=>Kp(t,r),t.readonly=()=>kz(t),t.describe=r=>{let n=t.clone();return xi.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return xi.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return xi.get(t);let n=t.clone();return xi.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),E$=S("_ZodString",(t,e)=>{Wc.init(t,e),Me.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(Dp(...n)),t.includes=(...n)=>t.check(Np(...n)),t.startsWith=(...n)=>t.check(jp(...n)),t.endsWith=(...n)=>t.check(Mp(...n)),t.min=(...n)=>t.check(Qo(...n)),t.max=(...n)=>t.check(Gc(...n)),t.length=(...n)=>t.check(Yc(...n)),t.nonempty=(...n)=>t.check(Qo(1,...n)),t.lowercase=n=>t.check(Op(n)),t.uppercase=n=>t.check(zp(n)),t.trim=()=>t.check(qp()),t.normalize=(...n)=>t.check(Lp(...n)),t.toLowerCase=()=>t.check(Fp()),t.toUpperCase=()=>t.check(Up())}),LO=S("ZodString",(t,e)=>{Wc.init(t,e),E$.init(t,e),t.email=r=>t.check(Ow(qO,r)),t.url=r=>t.check(Lw(FO,r)),t.jwt=r=>t.check(e$(rz,r)),t.emoji=r=>t.check(qw(UO,r)),t.guid=r=>t.check(Cp(x$,r)),t.uuid=r=>t.check(zw(Xc,r)),t.uuidv4=r=>t.check(Nw(Xc,r)),t.uuidv6=r=>t.check(jw(Xc,r)),t.uuidv7=r=>t.check(Mw(Xc,r)),t.nanoid=r=>t.check(Fw(ZO,r)),t.guid=r=>t.check(Cp(x$,r)),t.cuid=r=>t.check(Uw(VO,r)),t.cuid2=r=>t.check(Zw(BO,r)),t.ulid=r=>t.check(Vw(WO,r)),t.base64=r=>t.check(Yw(XO,r)),t.base64url=r=>t.check(Qw(ez,r)),t.xid=r=>t.check(Bw(HO,r)),t.ksuid=r=>t.check(Ww(KO,r)),t.ipv4=r=>t.check(Hw(JO,r)),t.ipv6=r=>t.check(Kw(GO,r)),t.cidrv4=r=>t.check(Jw(YO,r)),t.cidrv6=r=>t.check(Gw(QO,r)),t.e164=r=>t.check(Xw(tz,r)),t.datetime=r=>t.check(Zp(r)),t.date=r=>t.check(Vp(r)),t.time=r=>t.check(Bp(r)),t.duration=r=>t.check(Wp(r))});function w(t){return Dw(LO,t)}var Oe=S("ZodStringFormat",(t,e)=>{Ee.init(t,e),E$.init(t,e)}),qO=S("ZodEmail",(t,e)=>{Ub.init(t,e),Oe.init(t,e)});var x$=S("ZodGUID",(t,e)=>{qb.init(t,e),Oe.init(t,e)});var Xc=S("ZodUUID",(t,e)=>{Fb.init(t,e),Oe.init(t,e)});var FO=S("ZodURL",(t,e)=>{Zb.init(t,e),Oe.init(t,e)});var UO=S("ZodEmoji",(t,e)=>{Vb.init(t,e),Oe.init(t,e)});var ZO=S("ZodNanoID",(t,e)=>{Bb.init(t,e),Oe.init(t,e)});var VO=S("ZodCUID",(t,e)=>{Wb.init(t,e),Oe.init(t,e)});var BO=S("ZodCUID2",(t,e)=>{Hb.init(t,e),Oe.init(t,e)});var WO=S("ZodULID",(t,e)=>{Kb.init(t,e),Oe.init(t,e)});var HO=S("ZodXID",(t,e)=>{Jb.init(t,e),Oe.init(t,e)});var KO=S("ZodKSUID",(t,e)=>{Gb.init(t,e),Oe.init(t,e)});var JO=S("ZodIPv4",(t,e)=>{tw.init(t,e),Oe.init(t,e)});var GO=S("ZodIPv6",(t,e)=>{rw.init(t,e),Oe.init(t,e)});var YO=S("ZodCIDRv4",(t,e)=>{nw.init(t,e),Oe.init(t,e)});var QO=S("ZodCIDRv6",(t,e)=>{ow.init(t,e),Oe.init(t,e)});var XO=S("ZodBase64",(t,e)=>{iw.init(t,e),Oe.init(t,e)});var ez=S("ZodBase64URL",(t,e)=>{aw.init(t,e),Oe.init(t,e)});var tz=S("ZodE164",(t,e)=>{cw.init(t,e),Oe.init(t,e)});var rz=S("ZodJWT",(t,e)=>{uw.init(t,e),Oe.init(t,e)});var T$=S("ZodNumber",(t,e)=>{Rp.init(t,e),Me.init(t,e),t.gt=(n,o)=>t.check(Kc(n,o)),t.gte=(n,o)=>t.check(Pi(n,o)),t.min=(n,o)=>t.check(Pi(n,o)),t.lt=(n,o)=>t.check(Hc(n,o)),t.lte=(n,o)=>t.check(ki(n,o)),t.max=(n,o)=>t.check(ki(n,o)),t.int=n=>t.check(k$(n)),t.safe=n=>t.check(k$(n)),t.positive=n=>t.check(Kc(0,n)),t.nonnegative=n=>t.check(Pi(0,n)),t.negative=n=>t.check(Hc(0,n)),t.nonpositive=n=>t.check(ki(0,n)),t.multipleOf=(n,o)=>t.check(Jc(n,o)),t.step=(n,o)=>t.check(Jc(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 ve(t){return s$(T$,t)}var nz=S("ZodNumberFormat",(t,e)=>{lw.init(t,e),T$.init(t,e)});function k$(t){return i$(nz,t)}var oz=S("ZodBoolean",(t,e)=>{dw.init(t,e),Me.init(t,e)});function He(t){return a$(oz,t)}var sz=S("ZodNull",(t,e)=>{pw.init(t,e),Me.init(t,e)});function R$(t){return c$(sz,t)}var iz=S("ZodUnknown",(t,e)=>{fw.init(t,e),Me.init(t,e)});function ze(){return u$(iz)}var az=S("ZodNever",(t,e)=>{mw.init(t,e),Me.init(t,e)});function cz(t){return l$(az,t)}var uz=S("ZodArray",(t,e)=>{hw.init(t,e),Me.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Qo(r,n)),t.nonempty=r=>t.check(Qo(1,r)),t.max=(r,n)=>t.check(Gc(r,n)),t.length=(r,n)=>t.check(Yc(r,n)),t.unwrap=()=>t.element});function ie(t,e){return d$(uz,t,e)}var I$=S("ZodObject",(t,e)=>{gw.init(t,e),Me.init(t,e),ge.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>wt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:ze()}),t.loose=()=>t.clone({...t._zod.def,catchall:ze()}),t.strict=()=>t.clone({...t._zod.def,catchall:cz()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ge.extend(t,r),t.merge=r=>ge.merge(t,r),t.pick=r=>ge.pick(t,r),t.omit=r=>ge.omit(t,r),t.partial=(...r)=>ge.partial(D$,t,r[0]),t.required=(...r)=>ge.required(O$,t,r[0])});function A(t,e){let r={type:"object",get shape(){return ge.assignProp(this,"shape",{...t}),this.shape},...ge.normalizeParams(e)};return new I$(r)}function pt(t,e){return new I$({type:"object",get shape(){return ge.assignProp(this,"shape",{...t}),this.shape},catchall:ze(),...ge.normalizeParams(e)})}var A$=S("ZodUnion",(t,e)=>{Ip.init(t,e),Me.init(t,e),t.options=e.options});function Te(t,e){return new A$({type:"union",options:t,...ge.normalizeParams(e)})}var lz=S("ZodDiscriminatedUnion",(t,e)=>{A$.init(t,e),yw.init(t,e)});function Jp(t,e,r){return new lz({type:"union",options:e,discriminator:t,...ge.normalizeParams(r)})}var dz=S("ZodIntersection",(t,e)=>{vw.init(t,e),Me.init(t,e)});function eu(t,e){return new dz({type:"intersection",left:t,right:e})}var pz=S("ZodRecord",(t,e)=>{_w.init(t,e),Me.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Pe(t,e,r){return new pz({type:"record",keyType:t,valueType:e,...ge.normalizeParams(r)})}var Hp=S("ZodEnum",(t,e)=>{bw.init(t,e),Me.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 Hp({...e,checks:[],...ge.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 Hp({...e,checks:[],...ge.normalizeParams(o),entries:s})}});function wt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Hp({type:"enum",entries:r,...ge.normalizeParams(e)})}var fz=S("ZodLiteral",(t,e)=>{ww.init(t,e),Me.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 D(t,e){return new fz({type:"literal",values:Array.isArray(t)?t:[t],...ge.normalizeParams(e)})}var mz=S("ZodTransform",(t,e)=>{$w.init(t,e),Me.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ge.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(ge.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 C$(t){return new mz({type:"transform",transform:t})}var D$=S("ZodOptional",(t,e)=>{Sw.init(t,e),Me.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ne(t){return new D$({type:"optional",innerType:t})}var hz=S("ZodNullable",(t,e)=>{xw.init(t,e),Me.init(t,e),t.unwrap=()=>t._zod.def.innerType});function P$(t){return new hz({type:"nullable",innerType:t})}var gz=S("ZodDefault",(t,e)=>{kw.init(t,e),Me.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function yz(t,e){return new gz({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var vz=S("ZodPrefault",(t,e)=>{Pw.init(t,e),Me.init(t,e),t.unwrap=()=>t._zod.def.innerType});function _z(t,e){return new vz({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var O$=S("ZodNonOptional",(t,e)=>{Ew.init(t,e),Me.init(t,e),t.unwrap=()=>t._zod.def.innerType});function bz(t,e){return new O$({type:"nonoptional",innerType:t,...ge.normalizeParams(e)})}var wz=S("ZodCatch",(t,e)=>{Tw.init(t,e),Me.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function $z(t,e){return new wz({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Sz=S("ZodPipe",(t,e)=>{Rw.init(t,e),Me.init(t,e),t.in=e.in,t.out=e.out});function Kp(t,e){return new Sz({type:"pipe",in:t,out:e})}var xz=S("ZodReadonly",(t,e)=>{Iw.init(t,e),Me.init(t,e)});function kz(t){return new xz({type:"readonly",innerType:t})}var z$=S("ZodCustom",(t,e)=>{Aw.init(t,e),Me.init(t,e)});function Pz(t){let e=new nt({check:"custom"});return e._zod.check=t,e}function N$(t,e){return p$(z$,t??(()=>!0),e)}function Ez(t,e={}){return f$(z$,t,e)}function Tz(t){let e=Pz(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ge.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(ge.issue(o))}},t(r.value,r)));return e}function Gp(t,e){return Kp(C$(t),e)}Lt(Cw());var Qp="2025-11-25";var j$=[Qp,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],sn="io.modelcontextprotocol/related-task",ru="2.0",Be=N$(t=>t!==null&&(typeof t=="object"||typeof t=="function")),M$=Te([w(),ve().int()]),L$=w(),K5=pt({ttl:ve().optional(),pollInterval:ve().optional()}),Rz=A({ttl:ve().optional()}),Iz=A({taskId:w()}),Xp=pt({progressToken:M$.optional(),[sn]:Iz.optional()}),Dt=A({_meta:Xp.optional()}),Ii=Dt.extend({task:Rz.optional()}),q$=t=>Ii.safeParse(t).success,Je=A({method:w(),params:Dt.loose().optional()}),qt=A({_meta:Xp.optional()}),Ft=A({method:w(),params:qt.loose().optional()}),Ge=pt({_meta:Xp.optional()}),nu=Te([w(),ve().int()]),F$=A({jsonrpc:D(ru),id:nu,...Je.shape}).strict(),ef=t=>F$.safeParse(t).success,U$=A({jsonrpc:D(ru),...Ft.shape}).strict(),Z$=t=>U$.safeParse(t).success,tf=A({jsonrpc:D(ru),id:nu,result:Ge}).strict(),Ai=t=>tf.safeParse(t).success;var se;(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"})(se||(se={}));var rf=A({jsonrpc:D(ru),id:nu.optional(),error:A({code:ve().int(),message:w(),data:ze().optional()})}).strict();var V$=t=>rf.safeParse(t).success;var B$=Te([F$,U$,tf,rf]),J5=Te([tf,rf]),ou=Ge.strict(),Az=qt.extend({requestId:nu.optional(),reason:w().optional()}),su=Ft.extend({method:D("notifications/cancelled"),params:Az}),Cz=A({src:w(),mimeType:w().optional(),sizes:ie(w()).optional(),theme:wt(["light","dark"]).optional()}),Ci=A({icons:ie(Cz).optional()}),es=A({name:w(),title:w().optional()}),W$=es.extend({...es.shape,...Ci.shape,version:w(),websiteUrl:w().optional(),description:w().optional()}),Dz=eu(A({applyDefaults:He().optional()}),Pe(w(),ze())),Oz=Gp(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,eu(A({form:Dz.optional(),url:Be.optional()}),Pe(w(),ze()).optional())),zz=pt({list:Be.optional(),cancel:Be.optional(),requests:pt({sampling:pt({createMessage:Be.optional()}).optional(),elicitation:pt({create:Be.optional()}).optional()}).optional()}),Nz=pt({list:Be.optional(),cancel:Be.optional(),requests:pt({tools:pt({call:Be.optional()}).optional()}).optional()}),jz=A({experimental:Pe(w(),Be).optional(),sampling:A({context:Be.optional(),tools:Be.optional()}).optional(),elicitation:Oz.optional(),roots:A({listChanged:He().optional()}).optional(),tasks:zz.optional(),extensions:Pe(w(),Be).optional()}),Mz=Dt.extend({protocolVersion:w(),capabilities:jz,clientInfo:W$}),nf=Je.extend({method:D("initialize"),params:Mz});var Lz=A({experimental:Pe(w(),Be).optional(),logging:Be.optional(),completions:Be.optional(),prompts:A({listChanged:He().optional()}).optional(),resources:A({subscribe:He().optional(),listChanged:He().optional()}).optional(),tools:A({listChanged:He().optional()}).optional(),tasks:Nz.optional(),extensions:Pe(w(),Be).optional()}),qz=Ge.extend({protocolVersion:w(),capabilities:Lz,serverInfo:W$,instructions:w().optional()}),of=Ft.extend({method:D("notifications/initialized"),params:qt.optional()});var iu=Je.extend({method:D("ping"),params:Dt.optional()}),Fz=A({progress:ve(),total:Ne(ve()),message:Ne(w())}),Uz=A({...qt.shape,...Fz.shape,progressToken:M$}),au=Ft.extend({method:D("notifications/progress"),params:Uz}),Zz=Dt.extend({cursor:L$.optional()}),Di=Je.extend({params:Zz.optional()}),Oi=Ge.extend({nextCursor:L$.optional()}),Vz=wt(["working","input_required","completed","failed","cancelled"]),zi=A({taskId:w(),status:Vz,ttl:Te([ve(),R$()]),createdAt:w(),lastUpdatedAt:w(),pollInterval:Ne(ve()),statusMessage:Ne(w())}),ts=Ge.extend({task:zi}),Bz=qt.merge(zi),Ni=Ft.extend({method:D("notifications/tasks/status"),params:Bz}),cu=Je.extend({method:D("tasks/get"),params:Dt.extend({taskId:w()})}),uu=Ge.merge(zi),lu=Je.extend({method:D("tasks/result"),params:Dt.extend({taskId:w()})}),G5=Ge.loose(),du=Di.extend({method:D("tasks/list")}),pu=Oi.extend({tasks:ie(zi)}),fu=Je.extend({method:D("tasks/cancel"),params:Dt.extend({taskId:w()})}),H$=Ge.merge(zi),K$=A({uri:w(),mimeType:Ne(w()),_meta:Pe(w(),ze()).optional()}),J$=K$.extend({text:w()}),sf=w().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),G$=K$.extend({blob:sf}),ji=wt(["user","assistant"]),rs=A({audience:ie(ji).optional(),priority:ve().min(0).max(1).optional(),lastModified:Ti.datetime({offset:!0}).optional()}),Y$=A({...es.shape,...Ci.shape,uri:w(),description:Ne(w()),mimeType:Ne(w()),size:Ne(ve()),annotations:rs.optional(),_meta:Ne(pt({}))}),Wz=A({...es.shape,...Ci.shape,uriTemplate:w(),description:Ne(w()),mimeType:Ne(w()),annotations:rs.optional(),_meta:Ne(pt({}))}),Hz=Di.extend({method:D("resources/list")}),Kz=Oi.extend({resources:ie(Y$)}),Jz=Di.extend({method:D("resources/templates/list")}),Gz=Oi.extend({resourceTemplates:ie(Wz)}),af=Dt.extend({uri:w()}),Yz=af,Qz=Je.extend({method:D("resources/read"),params:Yz}),Xz=Ge.extend({contents:ie(Te([J$,G$]))}),eN=Ft.extend({method:D("notifications/resources/list_changed"),params:qt.optional()}),tN=af,rN=Je.extend({method:D("resources/subscribe"),params:tN}),nN=af,oN=Je.extend({method:D("resources/unsubscribe"),params:nN}),sN=qt.extend({uri:w()}),iN=Ft.extend({method:D("notifications/resources/updated"),params:sN}),aN=A({name:w(),description:Ne(w()),required:Ne(He())}),cN=A({...es.shape,...Ci.shape,description:Ne(w()),arguments:Ne(ie(aN)),_meta:Ne(pt({}))}),uN=Di.extend({method:D("prompts/list")}),lN=Oi.extend({prompts:ie(cN)}),dN=Dt.extend({name:w(),arguments:Pe(w(),w()).optional()}),pN=Je.extend({method:D("prompts/get"),params:dN}),cf=A({type:D("text"),text:w(),annotations:rs.optional(),_meta:Pe(w(),ze()).optional()}),uf=A({type:D("image"),data:sf,mimeType:w(),annotations:rs.optional(),_meta:Pe(w(),ze()).optional()}),lf=A({type:D("audio"),data:sf,mimeType:w(),annotations:rs.optional(),_meta:Pe(w(),ze()).optional()}),fN=A({type:D("tool_use"),name:w(),id:w(),input:Pe(w(),ze()),_meta:Pe(w(),ze()).optional()}),mN=A({type:D("resource"),resource:Te([J$,G$]),annotations:rs.optional(),_meta:Pe(w(),ze()).optional()}),hN=Y$.extend({type:D("resource_link")}),df=Te([cf,uf,lf,hN,mN]),gN=A({role:ji,content:df}),yN=Ge.extend({description:w().optional(),messages:ie(gN)}),vN=Ft.extend({method:D("notifications/prompts/list_changed"),params:qt.optional()}),_N=A({title:w().optional(),readOnlyHint:He().optional(),destructiveHint:He().optional(),idempotentHint:He().optional(),openWorldHint:He().optional()}),bN=A({taskSupport:wt(["required","optional","forbidden"]).optional()}),Q$=A({...es.shape,...Ci.shape,description:w().optional(),inputSchema:A({type:D("object"),properties:Pe(w(),Be).optional(),required:ie(w()).optional()}).catchall(ze()),outputSchema:A({type:D("object"),properties:Pe(w(),Be).optional(),required:ie(w()).optional()}).catchall(ze()).optional(),annotations:_N.optional(),execution:bN.optional(),_meta:Pe(w(),ze()).optional()}),pf=Di.extend({method:D("tools/list")}),wN=Oi.extend({tools:ie(Q$)}),mu=Ge.extend({content:ie(df).default([]),structuredContent:Pe(w(),ze()).optional(),isError:He().optional()}),Y5=mu.or(Ge.extend({toolResult:ze()})),$N=Ii.extend({name:w(),arguments:Pe(w(),ze()).optional()}),Mi=Je.extend({method:D("tools/call"),params:$N}),SN=Ft.extend({method:D("notifications/tools/list_changed"),params:qt.optional()}),Q5=A({autoRefresh:He().default(!0),debounceMs:ve().int().nonnegative().default(300)}),Li=wt(["debug","info","notice","warning","error","critical","alert","emergency"]),xN=Dt.extend({level:Li}),ff=Je.extend({method:D("logging/setLevel"),params:xN}),kN=qt.extend({level:Li,logger:w().optional(),data:ze()}),PN=Ft.extend({method:D("notifications/message"),params:kN}),EN=A({name:w().optional()}),TN=A({hints:ie(EN).optional(),costPriority:ve().min(0).max(1).optional(),speedPriority:ve().min(0).max(1).optional(),intelligencePriority:ve().min(0).max(1).optional()}),RN=A({mode:wt(["auto","required","none"]).optional()}),IN=A({type:D("tool_result"),toolUseId:w().describe("The unique identifier for the corresponding tool call."),content:ie(df).default([]),structuredContent:A({}).loose().optional(),isError:He().optional(),_meta:Pe(w(),ze()).optional()}),AN=Jp("type",[cf,uf,lf]),tu=Jp("type",[cf,uf,lf,fN,IN]),CN=A({role:ji,content:Te([tu,ie(tu)]),_meta:Pe(w(),ze()).optional()}),DN=Ii.extend({messages:ie(CN),modelPreferences:TN.optional(),systemPrompt:w().optional(),includeContext:wt(["none","thisServer","allServers"]).optional(),temperature:ve().optional(),maxTokens:ve().int(),stopSequences:ie(w()).optional(),metadata:Be.optional(),tools:ie(Q$).optional(),toolChoice:RN.optional()}),ON=Je.extend({method:D("sampling/createMessage"),params:DN}),qi=Ge.extend({model:w(),stopReason:Ne(wt(["endTurn","stopSequence","maxTokens"]).or(w())),role:ji,content:AN}),mf=Ge.extend({model:w(),stopReason:Ne(wt(["endTurn","stopSequence","maxTokens","toolUse"]).or(w())),role:ji,content:Te([tu,ie(tu)])}),zN=A({type:D("boolean"),title:w().optional(),description:w().optional(),default:He().optional()}),NN=A({type:D("string"),title:w().optional(),description:w().optional(),minLength:ve().optional(),maxLength:ve().optional(),format:wt(["email","uri","date","date-time"]).optional(),default:w().optional()}),jN=A({type:wt(["number","integer"]),title:w().optional(),description:w().optional(),minimum:ve().optional(),maximum:ve().optional(),default:ve().optional()}),MN=A({type:D("string"),title:w().optional(),description:w().optional(),enum:ie(w()),default:w().optional()}),LN=A({type:D("string"),title:w().optional(),description:w().optional(),oneOf:ie(A({const:w(),title:w()})),default:w().optional()}),qN=A({type:D("string"),title:w().optional(),description:w().optional(),enum:ie(w()),enumNames:ie(w()).optional(),default:w().optional()}),FN=Te([MN,LN]),UN=A({type:D("array"),title:w().optional(),description:w().optional(),minItems:ve().optional(),maxItems:ve().optional(),items:A({type:D("string"),enum:ie(w())}),default:ie(w()).optional()}),ZN=A({type:D("array"),title:w().optional(),description:w().optional(),minItems:ve().optional(),maxItems:ve().optional(),items:A({anyOf:ie(A({const:w(),title:w()}))}),default:ie(w()).optional()}),VN=Te([UN,ZN]),BN=Te([qN,FN,VN]),WN=Te([BN,zN,NN,jN]),HN=Ii.extend({mode:D("form").optional(),message:w(),requestedSchema:A({type:D("object"),properties:Pe(w(),WN),required:ie(w()).optional()})}),KN=Ii.extend({mode:D("url"),message:w(),elicitationId:w(),url:w().url()}),JN=Te([HN,KN]),GN=Je.extend({method:D("elicitation/create"),params:JN}),YN=qt.extend({elicitationId:w()}),QN=Ft.extend({method:D("notifications/elicitation/complete"),params:YN}),ns=Ge.extend({action:wt(["accept","decline","cancel"]),content:Gp(t=>t===null?void 0:t,Pe(w(),Te([w(),ve(),He(),ie(w())])).optional())}),XN=A({type:D("ref/resource"),uri:w()});var ej=A({type:D("ref/prompt"),name:w()}),tj=Dt.extend({ref:Te([ej,XN]),argument:A({name:w(),value:w()}),context:A({arguments:Pe(w(),w()).optional()}).optional()}),rj=Je.extend({method:D("completion/complete"),params:tj});var nj=Ge.extend({completion:pt({values:ie(w()).max(100),total:Ne(ve().int()),hasMore:Ne(He())})}),oj=A({uri:w().startsWith("file://"),name:w().optional(),_meta:Pe(w(),ze()).optional()}),sj=Je.extend({method:D("roots/list"),params:Dt.optional()}),hf=Ge.extend({roots:ie(oj)}),ij=Ft.extend({method:D("notifications/roots/list_changed"),params:qt.optional()}),X5=Te([iu,nf,rj,ff,pN,uN,Hz,Jz,Qz,rN,oN,Mi,pf,cu,lu,du,fu]),e8=Te([su,au,of,ij,Ni]),t8=Te([ou,qi,mf,ns,hf,uu,pu,ts]),r8=Te([iu,ON,GN,sj,cu,lu,du,fu]),n8=Te([su,au,PN,iN,eN,SN,vN,Ni,QN]),o8=Te([ou,qz,nj,yN,lN,Kz,Gz,Xz,mu,wN,uu,pu,ts]),H=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===se.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Yp(o.elicitations,r)}return new t(e,r,n)}},Yp=class extends H{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(se.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function an(t){return t==="completed"||t==="failed"||t==="cancelled"}var eS=Symbol("Let zodToJsonSchema decide on which parser to use");var X$={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"},tS=t=>typeof t=="string"?{...X$,name:t}:{...X$,...t};var rS=t=>{let e=tS(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 gf(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ae(t,e,r,n,o){t[e]=r,gf(t,e,n,o)}var hu=(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 je(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?hu(e,t.currentPath):e.join("/")}}function nS(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==T.ZodAny&&(r.items=Z(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ae(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ae(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ae(r,"minItems",t.exactLength.value,t.exactLength.message,e),ae(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function oS(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?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function sS(){return{type:"boolean"}}function gu(t,e){return Z(t.type._def,e)}var iS=(t,e)=>Z(t.innerType._def,e);function yf(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>yf(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 aj(t,e)}}var aj=(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":ae(r,"minimum",n.value,n.message,e);break;case"max":ae(r,"maximum",n.value,n.message,e);break}return r};function aS(t,e){return{...Z(t.innerType._def,e),default:t.defaultValue()}}function cS(t,e){return e.effectStrategy==="input"?Z(t.schema._def,e):je(e)}function uS(t){return{type:"string",enum:Array.from(t.values)}}var cj=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function lS(t,e){let r=[Z(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Z(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(cj(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 dS(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 vf,Qt={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:()=>(vf===void 0&&(vf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),vf),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 yu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ae(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ae(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":Xt(r,"email",n.message,e);break;case"format:idn-email":Xt(r,"idn-email",n.message,e);break;case"pattern:zod":ft(r,Qt.email,n.message,e);break}break;case"url":Xt(r,"uri",n.message,e);break;case"uuid":Xt(r,"uuid",n.message,e);break;case"regex":ft(r,n.regex,n.message,e);break;case"cuid":ft(r,Qt.cuid,n.message,e);break;case"cuid2":ft(r,Qt.cuid2,n.message,e);break;case"startsWith":ft(r,RegExp(`^${_f(n.value,e)}`),n.message,e);break;case"endsWith":ft(r,RegExp(`${_f(n.value,e)}$`),n.message,e);break;case"datetime":Xt(r,"date-time",n.message,e);break;case"date":Xt(r,"date",n.message,e);break;case"time":Xt(r,"time",n.message,e);break;case"duration":Xt(r,"duration",n.message,e);break;case"length":ae(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ae(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{ft(r,RegExp(_f(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Xt(r,"ipv4",n.message,e),n.version!=="v4"&&Xt(r,"ipv6",n.message,e);break}case"base64url":ft(r,Qt.base64url,n.message,e);break;case"jwt":ft(r,Qt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&ft(r,Qt.ipv4Cidr,n.message,e),n.version!=="v4"&&ft(r,Qt.ipv6Cidr,n.message,e);break}case"emoji":ft(r,Qt.emoji(),n.message,e);break;case"ulid":{ft(r,Qt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Xt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ae(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{ft(r,Qt.base64,n.message,e);break}}break}case"nanoid":ft(r,Qt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function _f(t,e){return e.patternStrategy==="escape"?lj(t):t}var uj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function lj(t){let e="";for(let r=0;r<t.length;r++)uj.has(t[r])||(e+="\\"),e+=t[r];return e}function Xt(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}}})):ae(t,"format",e,r,n)}function ft(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:pS(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ae(t,"pattern",pS(e,n),r,n)}function pS(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
|
|
245
|
-
]))`;continue}else if(n[c]==="$"){
|
|
246
|
-
]))`;continue}}if(r.s&&n[c]==="."){
|
|
243
|
+
path: iss.path ? [${Qn(b)}, ...iss.path] : [${Qn(b)}]
|
|
244
|
+
})));`),p.write(`newResult[${Qn(b)}] = ${_}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let g=p.compile();return(b,_)=>g(d,b,_)},s,o=so,i=!Vc.jitless,c=i&&_p.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let f=d.value;if(!o(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)s||(s=n(e.shape)),d=s(d,p);else{d.value={};let _=l.shape;for(let P of l.keys){let x=_[P],j=x._zod.run({value:f[P],issues:[]},p),k=x._zod.optin==="optional"&&x._zod.optout==="optional";j instanceof Promise?m.push(j.then(O=>k?Lb(O,d,P,f):Yc(O,d,P))):k?Lb(j,d,P,f):Yc(j,d,P)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let h=[],v=l.keySet,g=u._zod,b=g.def.type;for(let _ of Object.keys(f)){if(v.has(_))continue;if(b==="never"){h.push(_);continue}let P=g.run({value:f[_],issues:[]},p);P instanceof Promise?m.push(P.then(x=>Yc(x,d,_))):Yc(P,d,_)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function qb(t,e,r,n){for(let s of t)if(s.issues.length===0)return e.value=s.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(s=>s.issues.map(o=>tr(o,n,Ut())))}),e}var Op=$("$ZodUnion",(t,e)=>{ke.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=>Ei(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let s=!1,o=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)o.push(a),s=!0;else{if(a.issues.length===0)return a;o.push(a)}}return s?Promise.all(o).then(i=>qb(i,r,t,n)):qb(o,r,t,n)}}),xw=$("$ZodDiscriminatedUnion",(t,e)=>{Op.init(t,e);let r=t._zod.parse;Pe(t._zod,"propValues",()=>{let s={};for(let o of e.options){let i=o._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[a,c]of Object.entries(i)){s[a]||(s[a]=new Set);for(let u of c)s[a].add(u)}}return s});let n=Pi(()=>{let s=e.options,o=new Map;for(let i of s){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(o.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);o.set(c,i)}}return o});t._zod.parse=(s,o)=>{let i=s.value;if(!so(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),s;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(s,o):e.unionFallback?r(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),s)}}),Pw=$("$ZodIntersection",(t,e)=>{ke.init(t,e),t._zod.parse=(r,n)=>{let s=r.value,o=e.left._zod.run({value:s,issues:[]},n),i=e.right._zod.run({value:s,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([c,u])=>Fb(r,c,u)):Fb(r,o,i)}});function Cp(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(oo(t)&&oo(e)){let r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),s={...t,...e};for(let o of n){let i=Cp(t[o],e[o]);if(!i.valid)return{valid:!1,mergeErrorPath:[o,...i.mergeErrorPath]};s[o]=i.data}return{valid:!0,data:s}}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 s=t[n],o=e[n],i=Cp(s,o);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Fb(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),es(t))return t;let n=Cp(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 kw=$("$ZodRecord",(t,e)=>{ke.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!oo(s))return r.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),r;let o=[];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:s[c],issues:[]},n);u instanceof Promise?o.push(u.then(l=>{l.issues.length&&r.issues.push(...br(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...br(c,u.issues)),r.value[c]=u.value)}let a;for(let c in s)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(s)){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=>tr(u,n,Ut())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:s[i],issues:[]},n);c instanceof Promise?o.push(c.then(u=>{u.issues.length&&r.issues.push(...br(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...br(i,c.issues)),r.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}});var Ew=$("$ZodEnum",(t,e)=>{ke.init(t,e);let r=hp(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>bp.has(typeof n)).map(n=>typeof n=="string"?on(n):n.toString()).join("|")})$`),t._zod.parse=(n,s)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:r,input:o,inst:t}),n}}),Tw=$("$ZodLiteral",(t,e)=>{ke.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?on(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}});var Iw=$("$ZodTransform",(t,e)=>{ke.init(t,e),t._zod.parse=(r,n)=>{let s=e.transform(r.value,r);if(n.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(r.value=i,r));if(s instanceof Promise)throw new Lr;return r.value=s,r}}),Rw=$("$ZodOptional",(t,e)=>{ke.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(`^(${Ei(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)}),Aw=$("$ZodNullable",(t,e)=>{ke.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(`^(${Ei(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)}),Cw=$("$ZodDefault",(t,e)=>{ke.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 s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Ub(o,e)):Ub(s,e)}});function Ub(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Dw=$("$ZodPrefault",(t,e)=>{ke.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))}),Ow=$("$ZodNonOptional",(t,e)=>{ke.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 s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Zb(o,t)):Zb(s,t)}});function Zb(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 zw=$("$ZodCatch",(t,e)=>{ke.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 s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(i=>tr(i,n,Ut()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>tr(o,n,Ut()))},input:r.value}),r.issues=[]),r)}});var Mw=$("$ZodPipe",(t,e)=>{ke.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 s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>Vb(o,e,n)):Vb(s,e,n)}});function Vb(t,e,r){return es(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Nw=$("$ZodReadonly",(t,e)=>{ke.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 s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(Bb):Bb(s)}});function Bb(t){return t.value=Object.freeze(t.value),t}var jw=$("$ZodCustom",(t,e)=>{nt.init(t,e),ke.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,s=e.fn(n);if(s instanceof Promise)return s.then(o=>Wb(o,r,n,t));Wb(s,r,n,t)}});function Wb(t,e,r,n){if(!t){let s={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(s.params=n._zod.def.params),e.issues.push($p(s))}}var zO=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},MO=()=>{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 ${zO(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Hc(n.values[0])}`:`Invalid option: expected one of ${Bc(n.values,"|")}`;case"too_big":{let s=n.inclusive?"<=":"<",o=e(n.origin);return o?`Too big: expected ${n.origin??"value"} to have ${s}${n.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${s}${n.maximum.toString()}`}case"too_small":{let s=n.inclusive?">=":">",o=e(n.origin);return o?`Too small: expected ${n.origin} to have ${s}${n.minimum.toString()} ${o.unit}`:`Too small: expected ${n.origin} to be ${s}${n.minimum.toString()}`}case"invalid_format":{let s=n;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.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":""}: ${Bc(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 Lw(){return{localeError:MO()}}var zp=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 NO(){return new zp}var Ai=NO();function qw(t,e){return new t({type:"string",...U(e)})}function Fw(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...U(e)})}function Mp(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...U(e)})}function Uw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...U(e)})}function Zw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...U(e)})}function Vw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...U(e)})}function Bw(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...U(e)})}function Ww(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...U(e)})}function Hw(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...U(e)})}function Kw(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...U(e)})}function Jw(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...U(e)})}function Gw(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...U(e)})}function Yw(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...U(e)})}function Xw(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...U(e)})}function Qw(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...U(e)})}function eS(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...U(e)})}function tS(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...U(e)})}function rS(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...U(e)})}function nS(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...U(e)})}function sS(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...U(e)})}function oS(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...U(e)})}function iS(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...U(e)})}function aS(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...U(e)})}function cS(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...U(e)})}function uS(t,e){return new t({type:"string",format:"date",check:"string_format",...U(e)})}function lS(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...U(e)})}function dS(t,e){return new t({type:"string",format:"duration",check:"string_format",...U(e)})}function pS(t,e){return new t({type:"number",checks:[],...U(e)})}function fS(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...U(e)})}function mS(t,e){return new t({type:"boolean",...U(e)})}function hS(t,e){return new t({type:"null",...U(e)})}function gS(t){return new t({type:"unknown"})}function yS(t,e){return new t({type:"never",...U(e)})}function Qc(t,e){return new Rp({check:"less_than",...U(e),value:t,inclusive:!1})}function Ci(t,e){return new Rp({check:"less_than",...U(e),value:t,inclusive:!0})}function eu(t,e){return new Ap({check:"greater_than",...U(e),value:t,inclusive:!1})}function Di(t,e){return new Ap({check:"greater_than",...U(e),value:t,inclusive:!0})}function tu(t,e){return new xb({check:"multiple_of",...U(e),value:t})}function ru(t,e){return new kb({check:"max_length",...U(e),maximum:t})}function io(t,e){return new Eb({check:"min_length",...U(e),minimum:t})}function nu(t,e){return new Tb({check:"length_equals",...U(e),length:t})}function Np(t,e){return new Ib({check:"string_format",format:"regex",...U(e),pattern:t})}function jp(t){return new Rb({check:"string_format",format:"lowercase",...U(t)})}function Lp(t){return new Ab({check:"string_format",format:"uppercase",...U(t)})}function qp(t,e){return new Cb({check:"string_format",format:"includes",...U(e),includes:t})}function Fp(t,e){return new Db({check:"string_format",format:"starts_with",...U(e),prefix:t})}function Up(t,e){return new Ob({check:"string_format",format:"ends_with",...U(e),suffix:t})}function ts(t){return new zb({check:"overwrite",tx:t})}function Zp(t){return ts(e=>e.normalize(t))}function Vp(){return ts(t=>t.trim())}function Bp(){return ts(t=>t.toLowerCase())}function Wp(){return ts(t=>t.toUpperCase())}function vS(t,e,r){return new t({type:"array",element:e,...U(r)})}function _S(t,e,r){let n=U(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function bS(t,e,r){return new t({type:"custom",check:"custom",fn:e,...U(r)})}function ao(t){return!!t._zod}function an(t,e){return ao(t)?Ii(t,e):t.safeParse(e)}function su(t){if(!t)return;let e;if(ao(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function wS(t){if(ao(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.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 zi={};lt(zi,{ZodISODate:()=>$S,ZodISODateTime:()=>SS,ZodISODuration:()=>PS,ZodISOTime:()=>xS,date:()=>Kp,datetime:()=>Hp,duration:()=>Gp,time:()=>Jp});var SS=$("ZodISODateTime",(t,e)=>{sw.init(t,e),Oe.init(t,e)});function Hp(t){return cS(SS,t)}var $S=$("ZodISODate",(t,e)=>{ow.init(t,e),Oe.init(t,e)});function Kp(t){return uS($S,t)}var xS=$("ZodISOTime",(t,e)=>{iw.init(t,e),Oe.init(t,e)});function Jp(t){return lS(xS,t)}var PS=$("ZodISODuration",(t,e)=>{aw.init(t,e),Oe.init(t,e)});function Gp(t){return dS(PS,t)}var kS=(t,e)=>{Kc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>B_(t,r)},flatten:{value:r=>V_(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},h5=$("ZodError",kS),Mi=$("ZodError",kS,{Parent:Error});var ES=W_(Mi),TS=H_(Mi),IS=Pp(Mi),RS=kp(Mi);var je=$("ZodType",(t,e)=>(ke.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)=>_r(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>ES(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>IS(t,r,n),t.parseAsync=async(r,n)=>TS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>RS(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(Oz(r,n)),t.superRefine=r=>t.check(zz(r)),t.overwrite=r=>t.check(ts(r)),t.optional=()=>Me(t),t.nullable=()=>DS(t),t.nullish=()=>Me(DS(t)),t.nonoptional=r=>Ez(t,r),t.array=()=>ie(t),t.or=r=>Ie([t,r]),t.and=r=>iu(t,r),t.transform=r=>Xp(t,LS(r)),t.default=r=>xz(t,r),t.prefault=r=>kz(t,r),t.catch=r=>Iz(t,r),t.pipe=r=>Xp(t,r),t.readonly=()=>Cz(t),t.describe=r=>{let n=t.clone();return Ai.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Ai.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Ai.get(t);let n=t.clone();return Ai.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),OS=$("_ZodString",(t,e)=>{Xc.init(t,e),je.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(Np(...n)),t.includes=(...n)=>t.check(qp(...n)),t.startsWith=(...n)=>t.check(Fp(...n)),t.endsWith=(...n)=>t.check(Up(...n)),t.min=(...n)=>t.check(io(...n)),t.max=(...n)=>t.check(ru(...n)),t.length=(...n)=>t.check(nu(...n)),t.nonempty=(...n)=>t.check(io(1,...n)),t.lowercase=n=>t.check(jp(n)),t.uppercase=n=>t.check(Lp(n)),t.trim=()=>t.check(Vp()),t.normalize=(...n)=>t.check(Zp(...n)),t.toLowerCase=()=>t.check(Bp()),t.toUpperCase=()=>t.check(Wp())}),WO=$("ZodString",(t,e)=>{Xc.init(t,e),OS.init(t,e),t.email=r=>t.check(Fw(HO,r)),t.url=r=>t.check(Ww(KO,r)),t.jwt=r=>t.check(aS(uz,r)),t.emoji=r=>t.check(Hw(JO,r)),t.guid=r=>t.check(Mp(AS,r)),t.uuid=r=>t.check(Uw(ou,r)),t.uuidv4=r=>t.check(Zw(ou,r)),t.uuidv6=r=>t.check(Vw(ou,r)),t.uuidv7=r=>t.check(Bw(ou,r)),t.nanoid=r=>t.check(Kw(GO,r)),t.guid=r=>t.check(Mp(AS,r)),t.cuid=r=>t.check(Jw(YO,r)),t.cuid2=r=>t.check(Gw(XO,r)),t.ulid=r=>t.check(Yw(QO,r)),t.base64=r=>t.check(sS(iz,r)),t.base64url=r=>t.check(oS(az,r)),t.xid=r=>t.check(Xw(ez,r)),t.ksuid=r=>t.check(Qw(tz,r)),t.ipv4=r=>t.check(eS(rz,r)),t.ipv6=r=>t.check(tS(nz,r)),t.cidrv4=r=>t.check(rS(sz,r)),t.cidrv6=r=>t.check(nS(oz,r)),t.e164=r=>t.check(iS(cz,r)),t.datetime=r=>t.check(Hp(r)),t.date=r=>t.check(Kp(r)),t.time=r=>t.check(Jp(r)),t.duration=r=>t.check(Gp(r))});function w(t){return qw(WO,t)}var Oe=$("ZodStringFormat",(t,e)=>{Te.init(t,e),OS.init(t,e)}),HO=$("ZodEmail",(t,e)=>{Jb.init(t,e),Oe.init(t,e)});var AS=$("ZodGUID",(t,e)=>{Hb.init(t,e),Oe.init(t,e)});var ou=$("ZodUUID",(t,e)=>{Kb.init(t,e),Oe.init(t,e)});var KO=$("ZodURL",(t,e)=>{Gb.init(t,e),Oe.init(t,e)});var JO=$("ZodEmoji",(t,e)=>{Yb.init(t,e),Oe.init(t,e)});var GO=$("ZodNanoID",(t,e)=>{Xb.init(t,e),Oe.init(t,e)});var YO=$("ZodCUID",(t,e)=>{Qb.init(t,e),Oe.init(t,e)});var XO=$("ZodCUID2",(t,e)=>{ew.init(t,e),Oe.init(t,e)});var QO=$("ZodULID",(t,e)=>{tw.init(t,e),Oe.init(t,e)});var ez=$("ZodXID",(t,e)=>{rw.init(t,e),Oe.init(t,e)});var tz=$("ZodKSUID",(t,e)=>{nw.init(t,e),Oe.init(t,e)});var rz=$("ZodIPv4",(t,e)=>{cw.init(t,e),Oe.init(t,e)});var nz=$("ZodIPv6",(t,e)=>{uw.init(t,e),Oe.init(t,e)});var sz=$("ZodCIDRv4",(t,e)=>{lw.init(t,e),Oe.init(t,e)});var oz=$("ZodCIDRv6",(t,e)=>{dw.init(t,e),Oe.init(t,e)});var iz=$("ZodBase64",(t,e)=>{fw.init(t,e),Oe.init(t,e)});var az=$("ZodBase64URL",(t,e)=>{mw.init(t,e),Oe.init(t,e)});var cz=$("ZodE164",(t,e)=>{hw.init(t,e),Oe.init(t,e)});var uz=$("ZodJWT",(t,e)=>{gw.init(t,e),Oe.init(t,e)});var zS=$("ZodNumber",(t,e)=>{Dp.init(t,e),je.init(t,e),t.gt=(n,s)=>t.check(eu(n,s)),t.gte=(n,s)=>t.check(Di(n,s)),t.min=(n,s)=>t.check(Di(n,s)),t.lt=(n,s)=>t.check(Qc(n,s)),t.lte=(n,s)=>t.check(Ci(n,s)),t.max=(n,s)=>t.check(Ci(n,s)),t.int=n=>t.check(CS(n)),t.safe=n=>t.check(CS(n)),t.positive=n=>t.check(eu(0,n)),t.nonnegative=n=>t.check(Di(0,n)),t.negative=n=>t.check(Qc(0,n)),t.nonpositive=n=>t.check(Ci(0,n)),t.multipleOf=(n,s)=>t.check(tu(n,s)),t.step=(n,s)=>t.check(tu(n,s)),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 ve(t){return pS(zS,t)}var lz=$("ZodNumberFormat",(t,e)=>{yw.init(t,e),zS.init(t,e)});function CS(t){return fS(lz,t)}var dz=$("ZodBoolean",(t,e)=>{vw.init(t,e),je.init(t,e)});function We(t){return mS(dz,t)}var pz=$("ZodNull",(t,e)=>{_w.init(t,e),je.init(t,e)});function MS(t){return hS(pz,t)}var fz=$("ZodUnknown",(t,e)=>{bw.init(t,e),je.init(t,e)});function ze(){return gS(fz)}var mz=$("ZodNever",(t,e)=>{ww.init(t,e),je.init(t,e)});function hz(t){return yS(mz,t)}var gz=$("ZodArray",(t,e)=>{Sw.init(t,e),je.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(io(r,n)),t.nonempty=r=>t.check(io(1,r)),t.max=(r,n)=>t.check(ru(r,n)),t.length=(r,n)=>t.check(nu(r,n)),t.unwrap=()=>t.element});function ie(t,e){return vS(gz,t,e)}var NS=$("ZodObject",(t,e)=>{$w.init(t,e),je.init(t,e),ye.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>wt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:ze()}),t.loose=()=>t.clone({...t._zod.def,catchall:ze()}),t.strict=()=>t.clone({...t._zod.def,catchall:hz()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ye.extend(t,r),t.merge=r=>ye.merge(t,r),t.pick=r=>ye.pick(t,r),t.omit=r=>ye.omit(t,r),t.partial=(...r)=>ye.partial(qS,t,r[0]),t.required=(...r)=>ye.required(FS,t,r[0])});function A(t,e){let r={type:"object",get shape(){return ye.assignProp(this,"shape",{...t}),this.shape},...ye.normalizeParams(e)};return new NS(r)}function pt(t,e){return new NS({type:"object",get shape(){return ye.assignProp(this,"shape",{...t}),this.shape},catchall:ze(),...ye.normalizeParams(e)})}var jS=$("ZodUnion",(t,e)=>{Op.init(t,e),je.init(t,e),t.options=e.options});function Ie(t,e){return new jS({type:"union",options:t,...ye.normalizeParams(e)})}var yz=$("ZodDiscriminatedUnion",(t,e)=>{jS.init(t,e),xw.init(t,e)});function Qp(t,e,r){return new yz({type:"union",options:e,discriminator:t,...ye.normalizeParams(r)})}var vz=$("ZodIntersection",(t,e)=>{Pw.init(t,e),je.init(t,e)});function iu(t,e){return new vz({type:"intersection",left:t,right:e})}var _z=$("ZodRecord",(t,e)=>{kw.init(t,e),je.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Ee(t,e,r){return new _z({type:"record",keyType:t,valueType:e,...ye.normalizeParams(r)})}var Yp=$("ZodEnum",(t,e)=>{Ew.init(t,e),je.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{let o={};for(let i of n)if(r.has(i))o[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Yp({...e,checks:[],...ye.normalizeParams(s),entries:o})},t.exclude=(n,s)=>{let o={...e.entries};for(let i of n)if(r.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new Yp({...e,checks:[],...ye.normalizeParams(s),entries:o})}});function wt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Yp({type:"enum",entries:r,...ye.normalizeParams(e)})}var bz=$("ZodLiteral",(t,e)=>{Tw.init(t,e),je.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 bz({type:"literal",values:Array.isArray(t)?t:[t],...ye.normalizeParams(e)})}var wz=$("ZodTransform",(t,e)=>{Iw.init(t,e),je.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(ye.issue(o,r.value,e));else{let i=o;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(ye.issue(i))}};let s=e.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});function LS(t){return new wz({type:"transform",transform:t})}var qS=$("ZodOptional",(t,e)=>{Rw.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Me(t){return new qS({type:"optional",innerType:t})}var Sz=$("ZodNullable",(t,e)=>{Aw.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});function DS(t){return new Sz({type:"nullable",innerType:t})}var $z=$("ZodDefault",(t,e)=>{Cw.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function xz(t,e){return new $z({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Pz=$("ZodPrefault",(t,e)=>{Dw.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});function kz(t,e){return new Pz({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var FS=$("ZodNonOptional",(t,e)=>{Ow.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ez(t,e){return new FS({type:"nonoptional",innerType:t,...ye.normalizeParams(e)})}var Tz=$("ZodCatch",(t,e)=>{zw.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Iz(t,e){return new Tz({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Rz=$("ZodPipe",(t,e)=>{Mw.init(t,e),je.init(t,e),t.in=e.in,t.out=e.out});function Xp(t,e){return new Rz({type:"pipe",in:t,out:e})}var Az=$("ZodReadonly",(t,e)=>{Nw.init(t,e),je.init(t,e)});function Cz(t){return new Az({type:"readonly",innerType:t})}var US=$("ZodCustom",(t,e)=>{jw.init(t,e),je.init(t,e)});function Dz(t){let e=new nt({check:"custom"});return e._zod.check=t,e}function ZS(t,e){return _S(US,t??(()=>!0),e)}function Oz(t,e={}){return bS(US,t,e)}function zz(t){let e=Dz(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ye.issue(n,r.value,e._zod.def));else{let s=n;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),r.issues.push(ye.issue(s))}},t(r.value,r)));return e}function ef(t,e){return Xp(LS(t),e)}Ut(Lw());var rf="2025-11-25";var VS=[rf,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],cn="io.modelcontextprotocol/related-task",cu="2.0",Ve=ZS(t=>t!==null&&(typeof t=="object"||typeof t=="function")),BS=Ie([w(),ve().int()]),WS=w(),c8=pt({ttl:ve().optional(),pollInterval:ve().optional()}),Mz=A({ttl:ve().optional()}),Nz=A({taskId:w()}),nf=pt({progressToken:BS.optional(),[cn]:Nz.optional()}),Ot=A({_meta:nf.optional()}),Ni=Ot.extend({task:Mz.optional()}),HS=t=>Ni.safeParse(t).success,Ge=A({method:w(),params:Ot.loose().optional()}),Zt=A({_meta:nf.optional()}),Vt=A({method:w(),params:Zt.loose().optional()}),Ye=pt({_meta:nf.optional()}),uu=Ie([w(),ve().int()]),KS=A({jsonrpc:z(cu),id:uu,...Ge.shape}).strict(),sf=t=>KS.safeParse(t).success,JS=A({jsonrpc:z(cu),...Vt.shape}).strict(),GS=t=>JS.safeParse(t).success,of=A({jsonrpc:z(cu),id:uu,result:Ye}).strict(),ji=t=>of.safeParse(t).success;var oe;(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"})(oe||(oe={}));var af=A({jsonrpc:z(cu),id:uu.optional(),error:A({code:ve().int(),message:w(),data:ze().optional()})}).strict();var YS=t=>af.safeParse(t).success;var XS=Ie([KS,JS,of,af]),u8=Ie([of,af]),lu=Ye.strict(),jz=Zt.extend({requestId:uu.optional(),reason:w().optional()}),du=Vt.extend({method:z("notifications/cancelled"),params:jz}),Lz=A({src:w(),mimeType:w().optional(),sizes:ie(w()).optional(),theme:wt(["light","dark"]).optional()}),Li=A({icons:ie(Lz).optional()}),co=A({name:w(),title:w().optional()}),QS=co.extend({...co.shape,...Li.shape,version:w(),websiteUrl:w().optional(),description:w().optional()}),qz=iu(A({applyDefaults:We().optional()}),Ee(w(),ze())),Fz=ef(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,iu(A({form:qz.optional(),url:Ve.optional()}),Ee(w(),ze()).optional())),Uz=pt({list:Ve.optional(),cancel:Ve.optional(),requests:pt({sampling:pt({createMessage:Ve.optional()}).optional(),elicitation:pt({create:Ve.optional()}).optional()}).optional()}),Zz=pt({list:Ve.optional(),cancel:Ve.optional(),requests:pt({tools:pt({call:Ve.optional()}).optional()}).optional()}),Vz=A({experimental:Ee(w(),Ve).optional(),sampling:A({context:Ve.optional(),tools:Ve.optional()}).optional(),elicitation:Fz.optional(),roots:A({listChanged:We().optional()}).optional(),tasks:Uz.optional(),extensions:Ee(w(),Ve).optional()}),Bz=Ot.extend({protocolVersion:w(),capabilities:Vz,clientInfo:QS}),cf=Ge.extend({method:z("initialize"),params:Bz});var Wz=A({experimental:Ee(w(),Ve).optional(),logging:Ve.optional(),completions:Ve.optional(),prompts:A({listChanged:We().optional()}).optional(),resources:A({subscribe:We().optional(),listChanged:We().optional()}).optional(),tools:A({listChanged:We().optional()}).optional(),tasks:Zz.optional(),extensions:Ee(w(),Ve).optional()}),Hz=Ye.extend({protocolVersion:w(),capabilities:Wz,serverInfo:QS,instructions:w().optional()}),uf=Vt.extend({method:z("notifications/initialized"),params:Zt.optional()});var pu=Ge.extend({method:z("ping"),params:Ot.optional()}),Kz=A({progress:ve(),total:Me(ve()),message:Me(w())}),Jz=A({...Zt.shape,...Kz.shape,progressToken:BS}),fu=Vt.extend({method:z("notifications/progress"),params:Jz}),Gz=Ot.extend({cursor:WS.optional()}),qi=Ge.extend({params:Gz.optional()}),Fi=Ye.extend({nextCursor:WS.optional()}),Yz=wt(["working","input_required","completed","failed","cancelled"]),Ui=A({taskId:w(),status:Yz,ttl:Ie([ve(),MS()]),createdAt:w(),lastUpdatedAt:w(),pollInterval:Me(ve()),statusMessage:Me(w())}),uo=Ye.extend({task:Ui}),Xz=Zt.merge(Ui),Zi=Vt.extend({method:z("notifications/tasks/status"),params:Xz}),mu=Ge.extend({method:z("tasks/get"),params:Ot.extend({taskId:w()})}),hu=Ye.merge(Ui),gu=Ge.extend({method:z("tasks/result"),params:Ot.extend({taskId:w()})}),l8=Ye.loose(),yu=qi.extend({method:z("tasks/list")}),vu=Fi.extend({tasks:ie(Ui)}),_u=Ge.extend({method:z("tasks/cancel"),params:Ot.extend({taskId:w()})}),e$=Ye.merge(Ui),t$=A({uri:w(),mimeType:Me(w()),_meta:Ee(w(),ze()).optional()}),r$=t$.extend({text:w()}),lf=w().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),n$=t$.extend({blob:lf}),Vi=wt(["user","assistant"]),lo=A({audience:ie(Vi).optional(),priority:ve().min(0).max(1).optional(),lastModified:zi.datetime({offset:!0}).optional()}),s$=A({...co.shape,...Li.shape,uri:w(),description:Me(w()),mimeType:Me(w()),size:Me(ve()),annotations:lo.optional(),_meta:Me(pt({}))}),Qz=A({...co.shape,...Li.shape,uriTemplate:w(),description:Me(w()),mimeType:Me(w()),annotations:lo.optional(),_meta:Me(pt({}))}),eM=qi.extend({method:z("resources/list")}),tM=Fi.extend({resources:ie(s$)}),rM=qi.extend({method:z("resources/templates/list")}),nM=Fi.extend({resourceTemplates:ie(Qz)}),df=Ot.extend({uri:w()}),sM=df,oM=Ge.extend({method:z("resources/read"),params:sM}),iM=Ye.extend({contents:ie(Ie([r$,n$]))}),aM=Vt.extend({method:z("notifications/resources/list_changed"),params:Zt.optional()}),cM=df,uM=Ge.extend({method:z("resources/subscribe"),params:cM}),lM=df,dM=Ge.extend({method:z("resources/unsubscribe"),params:lM}),pM=Zt.extend({uri:w()}),fM=Vt.extend({method:z("notifications/resources/updated"),params:pM}),mM=A({name:w(),description:Me(w()),required:Me(We())}),hM=A({...co.shape,...Li.shape,description:Me(w()),arguments:Me(ie(mM)),_meta:Me(pt({}))}),gM=qi.extend({method:z("prompts/list")}),yM=Fi.extend({prompts:ie(hM)}),vM=Ot.extend({name:w(),arguments:Ee(w(),w()).optional()}),_M=Ge.extend({method:z("prompts/get"),params:vM}),pf=A({type:z("text"),text:w(),annotations:lo.optional(),_meta:Ee(w(),ze()).optional()}),ff=A({type:z("image"),data:lf,mimeType:w(),annotations:lo.optional(),_meta:Ee(w(),ze()).optional()}),mf=A({type:z("audio"),data:lf,mimeType:w(),annotations:lo.optional(),_meta:Ee(w(),ze()).optional()}),bM=A({type:z("tool_use"),name:w(),id:w(),input:Ee(w(),ze()),_meta:Ee(w(),ze()).optional()}),wM=A({type:z("resource"),resource:Ie([r$,n$]),annotations:lo.optional(),_meta:Ee(w(),ze()).optional()}),SM=s$.extend({type:z("resource_link")}),hf=Ie([pf,ff,mf,SM,wM]),$M=A({role:Vi,content:hf}),xM=Ye.extend({description:w().optional(),messages:ie($M)}),PM=Vt.extend({method:z("notifications/prompts/list_changed"),params:Zt.optional()}),kM=A({title:w().optional(),readOnlyHint:We().optional(),destructiveHint:We().optional(),idempotentHint:We().optional(),openWorldHint:We().optional()}),EM=A({taskSupport:wt(["required","optional","forbidden"]).optional()}),o$=A({...co.shape,...Li.shape,description:w().optional(),inputSchema:A({type:z("object"),properties:Ee(w(),Ve).optional(),required:ie(w()).optional()}).catchall(ze()),outputSchema:A({type:z("object"),properties:Ee(w(),Ve).optional(),required:ie(w()).optional()}).catchall(ze()).optional(),annotations:kM.optional(),execution:EM.optional(),_meta:Ee(w(),ze()).optional()}),gf=qi.extend({method:z("tools/list")}),TM=Fi.extend({tools:ie(o$)}),bu=Ye.extend({content:ie(hf).default([]),structuredContent:Ee(w(),ze()).optional(),isError:We().optional()}),d8=bu.or(Ye.extend({toolResult:ze()})),IM=Ni.extend({name:w(),arguments:Ee(w(),ze()).optional()}),Bi=Ge.extend({method:z("tools/call"),params:IM}),RM=Vt.extend({method:z("notifications/tools/list_changed"),params:Zt.optional()}),p8=A({autoRefresh:We().default(!0),debounceMs:ve().int().nonnegative().default(300)}),Wi=wt(["debug","info","notice","warning","error","critical","alert","emergency"]),AM=Ot.extend({level:Wi}),yf=Ge.extend({method:z("logging/setLevel"),params:AM}),CM=Zt.extend({level:Wi,logger:w().optional(),data:ze()}),DM=Vt.extend({method:z("notifications/message"),params:CM}),OM=A({name:w().optional()}),zM=A({hints:ie(OM).optional(),costPriority:ve().min(0).max(1).optional(),speedPriority:ve().min(0).max(1).optional(),intelligencePriority:ve().min(0).max(1).optional()}),MM=A({mode:wt(["auto","required","none"]).optional()}),NM=A({type:z("tool_result"),toolUseId:w().describe("The unique identifier for the corresponding tool call."),content:ie(hf).default([]),structuredContent:A({}).loose().optional(),isError:We().optional(),_meta:Ee(w(),ze()).optional()}),jM=Qp("type",[pf,ff,mf]),au=Qp("type",[pf,ff,mf,bM,NM]),LM=A({role:Vi,content:Ie([au,ie(au)]),_meta:Ee(w(),ze()).optional()}),qM=Ni.extend({messages:ie(LM),modelPreferences:zM.optional(),systemPrompt:w().optional(),includeContext:wt(["none","thisServer","allServers"]).optional(),temperature:ve().optional(),maxTokens:ve().int(),stopSequences:ie(w()).optional(),metadata:Ve.optional(),tools:ie(o$).optional(),toolChoice:MM.optional()}),FM=Ge.extend({method:z("sampling/createMessage"),params:qM}),Hi=Ye.extend({model:w(),stopReason:Me(wt(["endTurn","stopSequence","maxTokens"]).or(w())),role:Vi,content:jM}),vf=Ye.extend({model:w(),stopReason:Me(wt(["endTurn","stopSequence","maxTokens","toolUse"]).or(w())),role:Vi,content:Ie([au,ie(au)])}),UM=A({type:z("boolean"),title:w().optional(),description:w().optional(),default:We().optional()}),ZM=A({type:z("string"),title:w().optional(),description:w().optional(),minLength:ve().optional(),maxLength:ve().optional(),format:wt(["email","uri","date","date-time"]).optional(),default:w().optional()}),VM=A({type:wt(["number","integer"]),title:w().optional(),description:w().optional(),minimum:ve().optional(),maximum:ve().optional(),default:ve().optional()}),BM=A({type:z("string"),title:w().optional(),description:w().optional(),enum:ie(w()),default:w().optional()}),WM=A({type:z("string"),title:w().optional(),description:w().optional(),oneOf:ie(A({const:w(),title:w()})),default:w().optional()}),HM=A({type:z("string"),title:w().optional(),description:w().optional(),enum:ie(w()),enumNames:ie(w()).optional(),default:w().optional()}),KM=Ie([BM,WM]),JM=A({type:z("array"),title:w().optional(),description:w().optional(),minItems:ve().optional(),maxItems:ve().optional(),items:A({type:z("string"),enum:ie(w())}),default:ie(w()).optional()}),GM=A({type:z("array"),title:w().optional(),description:w().optional(),minItems:ve().optional(),maxItems:ve().optional(),items:A({anyOf:ie(A({const:w(),title:w()}))}),default:ie(w()).optional()}),YM=Ie([JM,GM]),XM=Ie([HM,KM,YM]),QM=Ie([XM,UM,ZM,VM]),eN=Ni.extend({mode:z("form").optional(),message:w(),requestedSchema:A({type:z("object"),properties:Ee(w(),QM),required:ie(w()).optional()})}),tN=Ni.extend({mode:z("url"),message:w(),elicitationId:w(),url:w().url()}),rN=Ie([eN,tN]),nN=Ge.extend({method:z("elicitation/create"),params:rN}),sN=Zt.extend({elicitationId:w()}),oN=Vt.extend({method:z("notifications/elicitation/complete"),params:sN}),po=Ye.extend({action:wt(["accept","decline","cancel"]),content:ef(t=>t===null?void 0:t,Ee(w(),Ie([w(),ve(),We(),ie(w())])).optional())}),iN=A({type:z("ref/resource"),uri:w()});var aN=A({type:z("ref/prompt"),name:w()}),cN=Ot.extend({ref:Ie([aN,iN]),argument:A({name:w(),value:w()}),context:A({arguments:Ee(w(),w()).optional()}).optional()}),uN=Ge.extend({method:z("completion/complete"),params:cN});var lN=Ye.extend({completion:pt({values:ie(w()).max(100),total:Me(ve().int()),hasMore:Me(We())})}),dN=A({uri:w().startsWith("file://"),name:w().optional(),_meta:Ee(w(),ze()).optional()}),pN=Ge.extend({method:z("roots/list"),params:Ot.optional()}),_f=Ye.extend({roots:ie(dN)}),fN=Vt.extend({method:z("notifications/roots/list_changed"),params:Zt.optional()}),f8=Ie([pu,cf,uN,yf,_M,gM,eM,rM,oM,uM,dM,Bi,gf,mu,gu,yu,_u]),m8=Ie([du,fu,uf,fN,Zi]),h8=Ie([lu,Hi,vf,po,_f,hu,vu,uo]),g8=Ie([pu,FM,nN,pN,mu,gu,yu,_u]),y8=Ie([du,fu,DM,fM,aM,RM,PM,Zi,oN]),v8=Ie([lu,Hz,lN,xM,yM,tM,nM,iM,bu,TM,hu,vu,uo]),H=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===oe.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new tf(s.elicitations,r)}return new t(e,r,n)}},tf=class extends H{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(oe.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function un(t){return t==="completed"||t==="failed"||t==="cancelled"}var a$=Symbol("Let zodToJsonSchema decide on which parser to use");var i$={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"},c$=t=>typeof t=="string"?{...i$,name:t}:{...i$,...t};var u$=t=>{let e=c$(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,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function bf(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ae(t,e,r,n,s){t[e]=r,bf(t,e,n,s)}var wu=(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 Ne(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?wu(e,t.currentPath):e.join("/")}}function l$(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==T.ZodAny&&(r.items=Z(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ae(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ae(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ae(r,"minItems",t.exactLength.value,t.exactLength.message,e),ae(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function d$(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?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function p$(){return{type:"boolean"}}function Su(t,e){return Z(t.type._def,e)}var f$=(t,e)=>Z(t.innerType._def,e);function wf(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>wf(t,e,s))};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 mN(t,e)}}var mN=(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":ae(r,"minimum",n.value,n.message,e);break;case"max":ae(r,"maximum",n.value,n.message,e);break}return r};function m$(t,e){return{...Z(t.innerType._def,e),default:t.defaultValue()}}function h$(t,e){return e.effectStrategy==="input"?Z(t.schema._def,e):Ne(e)}function g$(t){return{type:"string",enum:Array.from(t.values)}}var hN=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function y$(t,e){let r=[Z(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Z(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(o=>{if(hN(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}function v$(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 Sf,rr={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:()=>(Sf===void 0&&(Sf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Sf),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 $u(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ae(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ae(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":nr(r,"email",n.message,e);break;case"format:idn-email":nr(r,"idn-email",n.message,e);break;case"pattern:zod":ft(r,rr.email,n.message,e);break}break;case"url":nr(r,"uri",n.message,e);break;case"uuid":nr(r,"uuid",n.message,e);break;case"regex":ft(r,n.regex,n.message,e);break;case"cuid":ft(r,rr.cuid,n.message,e);break;case"cuid2":ft(r,rr.cuid2,n.message,e);break;case"startsWith":ft(r,RegExp(`^${$f(n.value,e)}`),n.message,e);break;case"endsWith":ft(r,RegExp(`${$f(n.value,e)}$`),n.message,e);break;case"datetime":nr(r,"date-time",n.message,e);break;case"date":nr(r,"date",n.message,e);break;case"time":nr(r,"time",n.message,e);break;case"duration":nr(r,"duration",n.message,e);break;case"length":ae(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ae(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{ft(r,RegExp($f(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&nr(r,"ipv4",n.message,e),n.version!=="v4"&&nr(r,"ipv6",n.message,e);break}case"base64url":ft(r,rr.base64url,n.message,e);break;case"jwt":ft(r,rr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&ft(r,rr.ipv4Cidr,n.message,e),n.version!=="v4"&&ft(r,rr.ipv6Cidr,n.message,e);break}case"emoji":ft(r,rr.emoji(),n.message,e);break;case"ulid":{ft(r,rr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{nr(r,"binary",n.message,e);break}case"contentEncoding:base64":{ae(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{ft(r,rr.base64,n.message,e);break}}break}case"nanoid":ft(r,rr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function $f(t,e){return e.patternStrategy==="escape"?yN(t):t}var gN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function yN(t){let e="";for(let r=0;r<t.length;r++)gN.has(t[r])||(e+="\\"),e+=t[r];return e}function nr(t,e,r,n){t.format||t.anyOf?.some(s=>s.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}}})):ae(t,"format",e,r,n)}function ft(t,e,r,n){t.pattern||t.allOf?.some(s=>s.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:_$(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ae(t,"pattern",_$(e,n),r,n)}function _$(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,s="",o=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(o){s+=n[c],o=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(s+=n[c],s+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(s+=n[c],a=!0):s+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){s+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){s+=`(^|(?<=[\r
|
|
245
|
+
]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
|
|
246
|
+
]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
|
|
247
247
|
`:`[${n[c]}\r
|
|
248
|
-
]`;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 vu(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===T.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??je(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===T.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=yu(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===T.ZodBranded&&t.keyType._def.type._def.typeName===T.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=gu(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function fS(t,e){if(e.mapStrategy==="record")return vu(t,e);let r=Z(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||je(e),n=Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||je(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function mS(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 hS(t){return t.target==="openAi"?void 0:{not:je({...t,currentPath:[...t.currentPath,"not"]})}}function gS(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Fi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function vS(t,e){if(e.target==="openApi3")return yS(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Fi&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Fi[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 yS(t,e)}var yS=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Z(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 _S(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:Fi[t.innerType._def.typeName],nullable:!0}:{type:[Fi[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Z(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function bS(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",gf(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function wS(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=pj(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=Z(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=dj(t,e);return i!==void 0&&(n.additionalProperties=i),n}function dj(t,e){if(t.catchall._def.typeName!=="ZodNever")return Z(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 pj(t){try{return t.isOptional()}catch{return!0}}var $S=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Z(t.innerType._def,e);let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:je(e)},r]}:je(e)};var SS=(t,e)=>{if(e.pipeStrategy==="input")return Z(t.in._def,e);if(e.pipeStrategy==="output")return Z(t.out._def,e);let r=Z(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Z(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function xS(t,e){return Z(t.type._def,e)}function kS(t,e){let n={type:"array",uniqueItems:!0,items:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ae(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ae(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function PS(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Z(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function ES(t){return{not:je(t)}}function TS(t){return je(t)}var RS=(t,e)=>Z(t.innerType._def,e);var IS=(t,e,r)=>{switch(e){case T.ZodString:return yu(t,r);case T.ZodNumber:return bS(t,r);case T.ZodObject:return wS(t,r);case T.ZodBigInt:return oS(t,r);case T.ZodBoolean:return sS();case T.ZodDate:return yf(t,r);case T.ZodUndefined:return ES(r);case T.ZodNull:return gS(r);case T.ZodArray:return nS(t,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return vS(t,r);case T.ZodIntersection:return lS(t,r);case T.ZodTuple:return PS(t,r);case T.ZodRecord:return vu(t,r);case T.ZodLiteral:return dS(t,r);case T.ZodEnum:return uS(t);case T.ZodNativeEnum:return mS(t);case T.ZodNullable:return _S(t,r);case T.ZodOptional:return $S(t,r);case T.ZodMap:return fS(t,r);case T.ZodSet:return kS(t,r);case T.ZodLazy:return()=>t.getter()._def;case T.ZodPromise:return xS(t,r);case T.ZodNaN:case T.ZodNever:return hS(r);case T.ZodEffects:return cS(t,r);case T.ZodAny:return je(r);case T.ZodUnknown:return TS(r);case T.ZodDefault:return aS(t,r);case T.ZodBranded:return gu(t,r);case T.ZodReadonly:return RS(t,r);case T.ZodCatch:return iS(t,r);case T.ZodPipeline:return SS(t,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(n=>{})(e)}};function Z(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==eS)return a}if(n&&!r){let a=fj(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=IS(t,t.typeName,e),i=typeof s=="function"?Z(s(),e):s;if(i&&mj(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var fj=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:hu(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`),je(e)):e.$refStrategy==="seen"?je(e):void 0}},mj=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var _u=(t,e)=>{let r=rS(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Z(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??je(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Z(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??je(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 bf(t){let r=Qc(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=m$(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function wf(t,e){let r=on(t,e);if(!r.success)throw r.error;return r.data}var hj=6e4,bu=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(su,r=>{this._oncancel(r)}),this.setNotificationHandler(au,r=>{this._onprogress(r)}),this.setRequestHandler(iu,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(cu,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new H(se.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(lu,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 H(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 H(se.InvalidParams,`Task not found: ${s}`);if(!an(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(an(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[sn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(du,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 H(se.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(fu,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new H(se.InvalidParams,`Task not found: ${r.params.taskId}`);if(an(o.status))throw new H(se.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 H(se.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof H?o:new H(se.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),H.fromError(se.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){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");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),Ai(s)||V$(s)?this._onresponse(s):ef(s)?this._onrequest(s,i):Z$(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();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=H.fromError(se.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?.[sn]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:se.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=q$(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=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new H(se.ConnectionClosed,"Request was cancelled");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:se.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.get(e.id)===i&&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),Ai(e))n(e);else{let i=new H(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(Ai(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),Ai(e))o(e);else{let i=H.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 H?i:new H(se.InternalError,String(i))}}return}let s;try{let i=await this.request(e,ts,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new H(se.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},an(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new H(se.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new H(se.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 H?i:new H(se.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=b=>{l(b)};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(b){d(b);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||{},[sn]:c}});let m=b=>{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(b)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let _=b instanceof H?b:new H(se.RequestTimeout,String(b));l(_)};this._responseHandlers.set(p,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return l(b);try{let _=on(r,b.result);_.success?u(_.data):l(_.error)}catch(_){l(_)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??hj,y=()=>m(H.fromError(se.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let b=_=>{let k=this._responseHandlers.get(p);k?k(_):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,b),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(p),l(_)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(p),l(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},uu,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},pu,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},H$,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||{},[sn]: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||{},[sn]: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||{},[sn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=bf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=wf(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=bf(e);this._notificationHandlers.set(n,o=>{let s=wf(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"&&ef(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new H(se.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 H(se.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new H(se.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 H(se.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=Ni.parse({method:"notifications/tasks/status",params:a});await this.notification(c),an(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 H(se.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(an(a.status))throw new H(se.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=Ni.parse({method:"notifications/tasks/status",params:c});await this.notification(u),an(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function AS(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function CS(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];AS(i)&&AS(s)?r[o]={...i,...s}:r[o]=s}return r}var CE=Dy(ok(),1),DE=Dy(AE(),1);function t2(){let t=new CE.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,DE.default)(t),t}var Cl=class{constructor(e){this._ajv=e??t2()}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 Dl=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},qi,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},ns,r)}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 OE(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 zE(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 Ol=class extends bu{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Li.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 Cl,this.setRequestHandler(nf,n=>this._oninitialize(n)),this.setNotificationHandler(of,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ff,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Li.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Dl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=CS(this._capabilities,e)}setRequestHandler(e,r){let o=Qc(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Xo(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=on(Mi,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new H(se.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=on(ts,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new H(se.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=on(mu,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new H(se.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){zE(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&OE(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:j$.includes(r)?r:Qp,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"},ou)}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},mf,r):this.request({method:"sampling/createMessage",params:e},qi,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},ns,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},ns,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new H(se.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof H?i:new H(se.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},hf,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 jE from"node:process";var zl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
249
|
-
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),
|
|
250
|
-
`}var
|
|
251
|
-
`);return
|
|
252
|
-
`+e.text),
|
|
248
|
+
]`;continue}s+=n[c],n[c]==="\\"?o=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return s}function xu(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===T.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??Ne(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===T.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=$u(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===T.ZodBranded&&t.keyType._def.type._def.typeName===T.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=Su(t.keyType._def,e);return{...r,propertyNames:s}}}return r}function b$(t,e){if(e.mapStrategy==="record")return xu(t,e);let r=Z(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ne(e),n=Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ne(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function w$(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}function S$(t){return t.target==="openAi"?void 0:{not:Ne({...t,currentPath:[...t.currentPath,"not"]})}}function $$(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ki={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function P$(t,e){if(e.target==="openApi3")return x$(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ki&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=Ki[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return x$(t,e)}var x$=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>Z(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function k$(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:Ki[t.innerType._def.typeName],nullable:!0}:{type:[Ki[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Z(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function E$(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",bf(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ae(r,"minimum",n.value,n.message,e):ae(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ae(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ae(r,"maximum",n.value,n.message,e):ae(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ae(r,"maximum",n.value,n.message,e));break;case"multipleOf":ae(r,"multipleOf",n.value,n.message,e);break}return r}function T$(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let c=o[a];if(c===void 0||c._def===void 0)continue;let u=_N(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=Z(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||s.push(a))}s.length&&(n.required=s);let i=vN(t,e);return i!==void 0&&(n.additionalProperties=i),n}function vN(t,e){if(t.catchall._def.typeName!=="ZodNever")return Z(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 _N(t){try{return t.isOptional()}catch{return!0}}var I$=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Z(t.innerType._def,e);let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ne(e)},r]}:Ne(e)};var R$=(t,e)=>{if(e.pipeStrategy==="input")return Z(t.in._def,e);if(e.pipeStrategy==="output")return Z(t.out._def,e);let r=Z(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Z(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}};function A$(t,e){return Z(t.type._def,e)}function C$(t,e){let n={type:"array",uniqueItems:!0,items:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ae(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ae(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function D$(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Z(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function O$(t){return{not:Ne(t)}}function z$(t){return Ne(t)}var M$=(t,e)=>Z(t.innerType._def,e);var N$=(t,e,r)=>{switch(e){case T.ZodString:return $u(t,r);case T.ZodNumber:return E$(t,r);case T.ZodObject:return T$(t,r);case T.ZodBigInt:return d$(t,r);case T.ZodBoolean:return p$();case T.ZodDate:return wf(t,r);case T.ZodUndefined:return O$(r);case T.ZodNull:return $$(r);case T.ZodArray:return l$(t,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return P$(t,r);case T.ZodIntersection:return y$(t,r);case T.ZodTuple:return D$(t,r);case T.ZodRecord:return xu(t,r);case T.ZodLiteral:return v$(t,r);case T.ZodEnum:return g$(t);case T.ZodNativeEnum:return w$(t);case T.ZodNullable:return k$(t,r);case T.ZodOptional:return I$(t,r);case T.ZodMap:return b$(t,r);case T.ZodSet:return C$(t,r);case T.ZodLazy:return()=>t.getter()._def;case T.ZodPromise:return A$(t,r);case T.ZodNaN:case T.ZodNever:return S$(r);case T.ZodEffects:return h$(t,r);case T.ZodAny:return Ne(r);case T.ZodUnknown:return z$(r);case T.ZodDefault:return m$(t,r);case T.ZodBranded:return Su(t,r);case T.ZodReadonly:return M$(t,r);case T.ZodCatch:return f$(t,r);case T.ZodPipeline:return R$(t,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(n=>{})(e)}};function Z(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==a$)return a}if(n&&!r){let a=bN(n,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=N$(t,t.typeName,e),i=typeof o=="function"?Z(o(),e):o;if(i&&wN(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var bN=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:wu(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`),Ne(e)):e.$refStrategy==="seen"?Ne(e):void 0}},wN=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Pu=(t,e)=>{let r=u$(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:Z(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ne(r)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=Z(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??Ne(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.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=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};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 xf(t){let r=su(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=wS(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Pf(t,e){let r=an(t,e);if(!r.success)throw r.error;return r.data}var SN=6e4,ku=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(du,r=>{this._oncancel(r)}),this.setNotificationHandler(fu,r=>{this._onprogress(r)}),this.setRequestHandler(pu,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(mu,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new H(oe.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(gu,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,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 H(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(o,n.sessionId);if(!i)throw new H(oe.InvalidParams,`Task not found: ${o}`);if(!un(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(un(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[cn]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(yu,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new H(oe.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(_u,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new H(oe.InvalidParams,`Task not found: ${r.params.taskId}`);if(un(s.status))throw new H(oe.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new H(oe.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof H?s:new H(oe.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_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),H.fromError(oe.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){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),ji(o)||YS(o)?this._onresponse(o):sf(o)?this._onrequest(o,i):GS(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=H.fromError(oe.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,s=this._transport,o=e.params?._meta?.[cn]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:oe.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:l,timestamp:Date.now()},s?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):s?.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=HS(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};o&&(d.relatedTask={taskId:o}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new H(oe.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});let m=f.relatedTask?.taskId??o;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:o,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};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},s?.sessionId):await s?.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:oe.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId):await s?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ji(e))n(e);else{let i=new H(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===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 o=!1;if(ji(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"&&(o=!0,this._taskProgressTokens.set(a.taskId,r))}}if(o||this._progressHandlers.delete(r),ji(e))s(e);else{let i=H.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof H?i:new H(oe.InternalError,String(i))}}return}let o;try{let i=await this.request(e,uo,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new H(oe.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},un(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new H(oe.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new H(oe.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},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 H?i:new H(oe.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=b=>{l(b)};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(b){d(b);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||{},[cn]:c}});let m=b=>{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(b)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let _=b instanceof H?b:new H(oe.RequestTimeout,String(b));l(_)};this._responseHandlers.set(p,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return l(b);try{let _=an(r,b.result);_.success?u(_.data):l(_.error)}catch(_){l(_)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??SN,v=()=>m(H.fromError(oe.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,v,n?.resetTimeoutOnProgress??!1);let g=c?.taskId;if(g){let b=_=>{let P=this._responseHandlers.get(p);P?P(_):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,b),this._enqueueTaskMessage(g,{type:"request",message:f,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(p),l(_)})}else this._transport.send(f,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(p),l(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},hu,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},vu,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},e$,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||{},[cn]: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||{},[cn]: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||{},[cn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=xf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=Pf(e,s);return Promise.resolve(r(i,o))})}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=xf(e);this._notificationHandlers.set(n,s=>{let o=Pf(e,s);return Promise.resolve(r(o))})}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 s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&sf(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new H(oe.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new H(oe.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new H(oe.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new H(oe.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let a=await n.getTask(s,r);if(a){let c=Zi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),un(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let a=await n.getTask(s,r);if(!a)throw new H(oe.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(un(a.status))throw new H(oe.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let c=await n.getTask(s,r);if(c){let u=Zi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),un(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function j$(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function L$(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];j$(i)&&j$(o)?r[s]={...i,...o}:r[s]=o}return r}var LE=jy(dP(),1),qE=jy(jE(),1);function c2(){let t=new LE.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,qE.default)(t),t}var jl=class{constructor(e){this._ajv=e??c2()}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 Ll=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Hi,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},po,r)}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 FE(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 UE(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 ql=class extends ku{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Wi.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new jl,this.setRequestHandler(cf,n=>this._oninitialize(n)),this.setNotificationHandler(uf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(yf,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Wi.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ll(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=L$(this._capabilities,e)}setRequestHandler(e,r){let s=su(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(ao(s)){let a=s;o=a._zod?.def?.value??a.value}else{let a=s;o=a._def?.value??a.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(c,u)=>{let l=an(Bi,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new H(oe.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=an(uo,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new H(oe.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=an(bu,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new H(oe.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){UE(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&FE(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:VS.includes(r)?r:rf,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"},lu)}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],s=Array.isArray(n.content)?n.content:[n.content],o=s.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(o){if(s.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(s.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},vf,r):this.request({method:"sampling/createMessage",params:e},Hi,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 s=e;return this.request({method:"elicitation/create",params:s},po,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},po,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new H(oe.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof H?i:new H(oe.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}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},_f,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 VE from"node:process";var Fl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
249
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),u2(r)}clear(){this._buffer=void 0}};function u2(t){return XS.parse(JSON.parse(t))}function ZE(t){return JSON.stringify(t)+`
|
|
250
|
+
`}var Ul=class{constructor(e=VE.stdin,r=VE.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Fl,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=ZE(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{fileURLToPath as lH}from"url";var Yg={};lt(Yg,{AI_CHAT_TIMEOUT_MS:()=>JE,AI_CONTEXT_BINARY_SAMPLE_BYTES:()=>GE,AI_CONTEXT_MAX_FILE_BYTES:()=>Jg,AI_CONTEXT_MAX_TOTAL_BYTES:()=>Gg,getTools:()=>m2,handleTool:()=>v2});import{readFile as l2,stat as d2}from"fs/promises";import{join as p2}from"path";import{randomUUID as BE}from"crypto";function G(t){let e=Pu(t,{target:"jsonSchema7"});return delete e.$schema,delete e.additionalProperties,e.type==="object"&&!e.required&&(e.required=[]),e}var f2=y.object({title:y.string().describe("Document title"),metadata:y.record(y.string()).optional().describe("Optional key-value metadata"),kind:y.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(),WE=y.object({provider:y.string().describe("Provider ID (e.g. 'ollama', 'gemini', 'codex', 'claude')"),prompt:y.string().describe("Chat prompt to send"),model:y.string().optional().describe("Model override"),system:y.string().optional().describe("System prompt"),files:y.array(y.string()).optional().describe("File paths to include as context"),allow_external_paths:y.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:f2.describe("If provided, automatically save the response as a workspace document with the given title and metadata. Returns document ID in the result.")}),HE=y.object({provider:y.string().describe("Provider ID"),file_paths:y.array(y.string()).min(1).describe("File paths to analyze"),question:y.string().describe("Question to ask about the files"),save_to_file:y.string().optional().describe("Path to save the analysis result"),allow_external_paths:y.boolean().optional().describe("Opt-in: allow absolute file paths outside the workspace base directory. Default false.")}),KE=y.object({providers:y.array(y.string()).min(1).describe("List of provider IDs to compare"),prompt:y.string().describe("Prompt to send to all providers"),aggregate_provider:y.string().optional().describe("Provider ID to synthesize all responses into a unified document. If omitted, returns raw comparisons only."),aggregate_prompt:y.string().optional().describe("Custom synthesis prompt. Default: synthesize and identify agreements/disagreements.")}),JE=9e4,Jg=1e6,Gg=4e6,GE=4096;async function YE(t){let e=t.allowExternalPaths?Tv:nn,r=[],n=0;for(let s of t.paths){let o=e(s,t.baseDir),i=await d2(o);if(!i.isFile())throw new Error(`AI context path is not a file: ${o}`);if(i.size>Jg)throw new Error(`File exceeds per-file AI context limit (${i.size} > ${Jg} bytes): ${o}`);if(n+i.size>Gg)throw new Error(`Total AI context size exceeds limit (${n+i.size} > ${Gg} bytes).`);n+=i.size;let a=await l2(o),c=Buffer.isBuffer(a)?a:Buffer.from(a);if(c.subarray(0,GE).includes(0))throw new Error(`Binary file rejected from AI context: ${o}`);let l;try{l=new TextDecoder("utf-8",{fatal:!0}).decode(c)}catch{throw new Error(`Binary file rejected from AI context: ${o}`)}r.push({path:o,content:l})}return r}function XE(t,e,r,n){if(t)try{t.write({traceId:BE(),action:"chat",providerId:e,task:`${n.tool}:allow_external_paths`,request:{promptSummary:(n.promptSummary?n.promptSummary+" | ":"")+`external_files=${r.length}: ${r.join(", ")}`,fileCount:r.length},response:{success:!0,charLength:0},latencyMs:0})}catch{}}function QE(t,e,r){let n=`${r.tool}-${Date.now()}-${BE().slice(0,8)}`,s=p2(t,".agestra","pending-saves",`${n}.md`),o=[["id",n],["tool",r.tool],["provider",e.provider],["model",e.model],["created_at",new Date().toISOString()]];if(r.title&&o.push(["title",r.title]),r.originalTarget&&o.push(["original_target",r.originalTarget]),r.extraMetadata)for(let[a,c]of Object.entries(r.extraMetadata))c!=null&&c!==""&&o.push([a,c]);let i=["---",...o.map(([a,c])=>`${a}: ${JSON.stringify(c)}`),"---",""].join(`
|
|
251
|
+
`);return ge(s,i+`
|
|
252
|
+
`+e.text),s}function m2(){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:G(WE)},{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:G(HE)},{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:G(KE)}]}async function h2(t,e){let r=WE.parse(t),n=e.workspaceBaseDir??process.cwd(),s=e.qualityStatsProvider??e.traceWriter,o=r.provider==="auto"?e.registry.getBestForTask("chat",s)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!o)throw new Error("No providers available for auto-routing");r.allow_external_paths&&r.files&&r.files.length>0&&XE(e.traceWriter,o.id,r.files,{tool:"ai_chat",promptSummary:r.prompt.slice(0,80)});let i=r.files?.length?await YE({paths:r.files,baseDir:n,allowExternalPaths:r.allow_external_paths}):void 0,a=e.aiChatTimeoutMs??JE,c=new AbortController,u=!1,l,d=o.chat({prompt:r.prompt,model:r.model,system:r.system,workspaceBaseDir:n,signal:c.signal,files:i});d.catch(()=>{});let p;try{p=await Promise.race([d,new Promise((h,v)=>{l=setTimeout(()=>{u=!0,c.abort(new Error("__AI_CHAT_TIMEOUT__")),v(new Error("__AI_CHAT_TIMEOUT__"))},a)})])}catch(h){if(u&&e.jobManager){let v=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:3e5,saveAsDocument:r.save_as_document}),g=r.save_as_document?`
|
|
253
253
|
**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.
|
|
254
254
|
|
|
255
|
-
**Job ID:** ${
|
|
255
|
+
**Job ID:** ${v}${g}
|
|
256
256
|
|
|
257
|
-
Use \`cli_job_status\` to check progress.`}]}}throw h}finally{l!==void 0&&clearTimeout(l)}r.allow_external_paths&&(p={...p,text:
|
|
258
|
-
**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(h){m=!0;let
|
|
259
|
-
\u26A0 Document save failed: ${
|
|
260
|
-
**Pending save:** ${
|
|
261
|
-
\u26A0 Document save failed: ${
|
|
262
|
-
\u26A0 Pending-save dump also failed: ${
|
|
257
|
+
Use \`cli_job_status\` to check progress.`}]}}throw h}finally{l!==void 0&&clearTimeout(l)}r.allow_external_paths&&(p={...p,text:Zs(p.text)});let f="",m=!1;if(r.save_as_document&&e.documentManager)try{f=`
|
|
258
|
+
**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(h){m=!0;let v=D(h);try{let g=QE(n,p,{tool:"ai_chat",title:r.save_as_document.title,extraMetadata:{kind:r.save_as_document.kind,...r.save_as_document.metadata}});f=`
|
|
259
|
+
\u26A0 Document save failed: ${v}
|
|
260
|
+
**Pending save:** ${g}`}catch(g){f=`
|
|
261
|
+
\u26A0 Document save failed: ${v}
|
|
262
|
+
\u26A0 Pending-save dump also failed: ${D(g)}`}}return{content:[{type:"text",text:`**Provider:** ${p.provider}
|
|
263
263
|
**Model:** ${p.model}${f}
|
|
264
264
|
|
|
265
|
-
${p.text}`}],...m?{isError:!0}:{}}}async function
|
|
266
|
-
${
|
|
265
|
+
${p.text}`}],...m?{isError:!0}:{}}}async function g2(t,e){let r=HE.parse(t),n=e.workspaceBaseDir??process.cwd(),s=e.qualityStatsProvider??e.traceWriter,o=r.provider==="auto"?e.registry.getBestForTask("analysis",s)??e.registry.getAvailable()[0]:e.registry.get(r.provider);if(!o)throw new Error("No providers available for auto-routing");r.allow_external_paths&&XE(e.traceWriter,o.id,r.file_paths,{tool:"ai_analyze_files",promptSummary:r.question.slice(0,80)});let c=`${(await YE({paths:r.file_paths,baseDir:n,allowExternalPaths:r.allow_external_paths})).map(({path:p,content:f})=>`--- ${p} ---
|
|
266
|
+
${f}`).join(`
|
|
267
267
|
|
|
268
268
|
`)}
|
|
269
269
|
|
|
270
270
|
---
|
|
271
271
|
|
|
272
|
-
Question: ${r.question}`,u=await
|
|
272
|
+
Question: ${r.question}`,u=await o.chat({prompt:c,workspaceBaseDir:n});r.allow_external_paths&&(u={...u,text:Zs(u.text)});let l="",d=!1;if(r.save_to_file)try{let p=Ft(r.save_to_file,n);ge(p,u.text),l=`
|
|
273
273
|
|
|
274
|
-
_Result saved to: ${r.save_to_file}_`}catch(p){d=!0;let f=
|
|
274
|
+
_Result saved to: ${r.save_to_file}_`}catch(p){d=!0;let f=D(p);try{let m=QE(n,u,{tool:"ai_analyze_files",originalTarget:r.save_to_file,extraMetadata:{question:r.question,file_paths:r.file_paths.join(", ")}});l=`
|
|
275
275
|
|
|
276
276
|
\u26A0 Save to ${r.save_to_file} failed: ${f}
|
|
277
277
|
**Pending save:** ${m}`}catch(m){l=`
|
|
278
278
|
|
|
279
279
|
\u26A0 Save to ${r.save_to_file} failed: ${f}
|
|
280
|
-
\u26A0 Pending-save dump also failed: ${
|
|
280
|
+
\u26A0 Pending-save dump also failed: ${D(m)}`}}return{content:[{type:"text",text:`**Provider:** ${u.provider}
|
|
281
281
|
**Files analyzed:** ${r.file_paths.join(", ")}
|
|
282
282
|
|
|
283
|
-
${u.text}${l}`}],...d?{isError:!0}:{}}}async function
|
|
283
|
+
${u.text}${l}`}],...d?{isError:!0}:{}}}async function y2(t,e){let r=KE.parse(t),n=r.providers.map(c=>e.registry.get(c)),s=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:D(u)}}})),o=`# Comparison
|
|
284
284
|
|
|
285
285
|
**Prompt:** ${r.prompt}
|
|
286
286
|
|
|
287
|
-
`;for(let c of o
|
|
287
|
+
`;for(let c of s)o+=`## ${c.provider}
|
|
288
288
|
|
|
289
|
-
`,c.error?
|
|
289
|
+
`,c.error?o+=`**Error:** ${c.error}
|
|
290
290
|
|
|
291
|
-
`:
|
|
291
|
+
`:o+=`${c.text}
|
|
292
292
|
|
|
293
|
-
`;let i;if(r.aggregate_provider){let c=e.registry.get(r.aggregate_provider);if(
|
|
293
|
+
`;let i;if(r.aggregate_provider){let c=e.registry.get(r.aggregate_provider);if(s.filter(l=>l.text!==null).length>0){let l=["You are synthesizing multiple AI responses into a unified analysis.","For each topic covered, identify:","1. **Agreements** \u2014 points where all providers align","2. **Disagreements** \u2014 conflicting opinions with each side's reasoning","3. **Unique insights** \u2014 valuable points raised by only one provider","4. **Recommended conclusion** \u2014 your synthesis of the best answer","","Produce a structured document, not a simple concatenation."].join(`
|
|
294
294
|
`),d=`${r.aggregate_prompt??l}
|
|
295
295
|
|
|
296
296
|
---
|
|
297
297
|
|
|
298
|
-
${
|
|
298
|
+
${o}`;try{i=(await c.chat({prompt:d})).text}catch(p){i=`[Aggregation failed: ${D(p)}]`}}}let a=o;return i&&(a+=`---
|
|
299
299
|
|
|
300
300
|
# Synthesis
|
|
301
301
|
|
|
302
|
-
${i}`),{content:[{type:"text",text:a}]}}async function
|
|
302
|
+
${i}`),{content:[{type:"text",text:a}]}}async function v2(t,e,r){switch(t){case"ai_chat":return h2(e,r);case"ai_analyze_files":return g2(e,r);case"ai_compare":return y2(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var yy={};lt(yy,{getTools:()=>Xg,handleTool:()=>xI});var Zl=y.object({topic:y.string().describe("Topic for the debate"),providers:y.array(y.string()).min(1).describe("Provider IDs to participate"),max_rounds:y.number().int().positive().optional().default(3).describe("Maximum debate rounds"),goal:y.string().optional().describe("Quality goal for enhanced debate mode (enables quality validation loop)"),validator:y.string().optional().describe("Provider ID for quality validation (agent-tier recommended)"),min_rounds:y.number().int().positive().optional().default(2).describe("Minimum rounds before validation (default: 2)")}),Vl=y.object({items:y.array(y.object({provider:y.string().describe("Provider that produced the content"),content:y.string().describe("Content to validate"),task:y.string().describe("Original task description")})).min(1).describe("Items to cross-validate"),validators:y.array(y.string()).optional().describe("Provider IDs to use as validators (agent-tier only)"),criteria:y.string().optional().describe("Custom validation criteria")}),Bl=y.object({session_id:y.string().describe("Session ID to check")}),Wl=y.object({topic:y.string().describe("Topic for the debate"),providers:y.array(y.string()).min(1).describe("Provider IDs to participate"),goal:y.string().optional().describe("Quality goal for the debate"),save_document:y.boolean().optional().default(!0).describe("Save debate as a workspace document (default: true)")}),Hl=y.object({debate_id:y.string().describe("Debate session ID"),provider:y.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:y.string().optional().describe(`Claude's opinion. When provider is "claude", this becomes the turn content. Otherwise, injected before the provider responds.`),auto_specialist:y.boolean().optional().default(!1).describe("When true with provider 'claude', automatically select and record a specialist agent recommendation based on the debate topic.")}),Kl=y.object({debate_id:y.string().describe("Debate session ID to conclude"),summary:y.string().optional().describe("Claude's final summary of the debate"),quality_scores:y.array(y.object({provider:y.string(),score:y.number().min(0).max(1),feedback:y.string()})).optional().describe("Quality assessment of each provider's contribution")}),Jl=y.object({document:y.string().describe("Document content to review"),providers:y.array(y.string()).min(1).describe("Provider IDs to review the document"),review_prompt:y.string().optional().describe("Custom review instructions (default: agree/disagree with feedback)"),debate_id:y.string().optional().describe("Link reviews to an existing debate session's workspace document")}),Gl=y.object({task_id:y.string().describe("Task ID to review changes for")}),Yl=y.object({task_id:y.string().describe("Task ID whose changes to accept"),message:y.string().optional().describe("Commit message for the merge")}),Xl=y.object({task_id:y.string().describe("Task ID whose changes to reject"),reason:y.string().optional().describe("Reason for rejection")}),eT=y.object({agrees:y.union([y.boolean(),y.enum(["true","false"])]).transform(t=>typeof t=="boolean"?t:t==="true"),feedback:y.string().optional().default(""),suggestions:y.string().optional()}),_2=y.object({document_id:y.string().min(1).describe("Workspace document id from workspace_create_document."),provider:y.string().min(1).describe("Provider that authored this individual document.")}),Ql=y.object({mode:y.enum(["review","idea"]).optional().default("review").describe("Structured consensus mode. `review` reviews code/documents; `idea` explores improvement ideas."),topic:y.string().min(1).describe("Topic for the structured debate"),scope:y.string().optional().describe("What the leader wants debated (file list or task framing). Defaults to topic when omitted."),goal:y.string().optional().describe("Optional quality goal for the debate"),leader:y.string().optional().describe("Participant ID authorized to approve the final synthesis. Defaults to the session-context leader or the first participant."),participants:y.array(y.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:y.array(y.string()).optional().describe("Participant IDs to never inject/include. Applied regardless of `auto_inject_specialists`."),auto_inject_specialists:y.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:y.number().int().positive().max(50).optional().describe("Maximum number of rounds. Default: STRUCTURED_DEBATE_DEFAULT_MAX_ROUNDS."),participant_timeout_ms:y.number().int().positive().max(36e5).optional().describe("Optional per-participant inactivity timeout in milliseconds for structured debate provider turns."),individual_review_prompt:y.string().optional().describe("Override the system prompt used for individual-review fan-out."),source_documents:y.array(_2).optional().describe("Optional pre-created individual documents. When provided, the engine extracts initial items from these documents instead of running a new individual fan-out."),files:y.array(y.string()).optional().describe("Optional list of files to pass to participants as context."),locale:y.enum(["ko","zh","ja","en"]).optional().describe("Override config locale for moderator text in this debate only.")}),ed=y.object({session_id:y.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),leader_note:y.string().optional().describe("Optional note appended to the synthesis footer under 'Leader approval notes'.")}),td=y.object({session_id:y.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),additional_rounds:y.union([y.literal(3),y.literal(5),y.literal(10)]).describe("How many extra rounds to run beyond the current round count. Choose one of 3, 5, or 10.")}),rd=y.object({session_id:y.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),reason:y.string().optional().describe("Optional rejection reason, captured in the debate transcript footer."),spawn_issue:y.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 nd="agent_debate_structured",Bo="agent_debate_approve",Wo="agent_debate_continue",Ho="agent_debate_reject";function sd(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 tT(t,e){let r=sd(e);if(r)return r;let n;try{n=Ql.parse(t)}catch(o){return Jr(`Invalid arguments: ${D(o)}`)}let s=b2(n.leader,n.participants,e);if(!s)return Jr("Cannot resolve a leader. Provide `leader` explicitly or ensure the session context exposes one.");try{let o=await e.moderatorEngine.startDebate({mode:n.mode,topic:n.topic,...n.scope!==void 0?{scope:n.scope}:{},...n.goal!==void 0?{goal:n.goal}:{},leader:s,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.participant_timeout_ms!==void 0?{participantTimeoutMs:n.participant_timeout_ms}:{},...n.locale!==void 0?{locale:n.locale}:{},...n.individual_review_prompt!==void 0?{individualReviewPrompt:n.individual_review_prompt}:{},...n.source_documents!==void 0?{sourceDocuments:n.source_documents.map(a=>({documentId:a.document_id,provider:a.provider}))}:{},...n.files!==void 0?{files:n.files}:{},background:!0}),i=[o.terminalReport];return i.push(oT(o.sessionId,o.snapshot.status)),o.snapshot.status==="escalated"?i.push(aT(o.sessionId)):o.snapshot.status==="ready-for-approval"?i.push(iT(o.sessionId)):o.snapshot.status==="error"&&i.push(`Engine reported an error: ${o.errorMessage??"(no message)"}.`),{content:[{type:"text",text:i.filter(Boolean).join(`
|
|
303
303
|
|
|
304
|
-
`)}],...
|
|
304
|
+
`)}],...o.snapshot.status==="error"?{isError:!0}:{}}}catch(o){return Jr(`Failed to start structured debate: ${D(o)}`)}}async function rT(t,e){let r=sd(e);if(r)return r;let n;try{n=ed.parse(t)}catch(s){return Jr(`Invalid arguments: ${D(s)}`)}try{let s=await e.moderatorEngine.approve({sessionId:n.session_id,...n.leader_note!==void 0?{leaderNote:n.leader_note}:{}}),o=[s.terminalReport];return o.push(`Synthesis document: ${s.synthesisPath}`),o.push(`Status: ${s.snapshot.status} (session ${n.session_id})`),s.idempotentReplay&&o.push("(idempotent replay of existing approved state \u2014 no new synthesis written)"),{content:[{type:"text",text:o.join(`
|
|
305
305
|
|
|
306
|
-
`)}]}}catch(
|
|
306
|
+
`)}]}}catch(s){return Jr(`Approve failed: ${D(s)}`)}}async function nT(t,e){let r=sd(e);if(r)return r;let n;try{n=td.parse(t)}catch(s){return Jr(`Invalid arguments: ${D(s)}`)}try{let s=await e.moderatorEngine.continueDebate({sessionId:n.session_id,additionalRounds:n.additional_rounds,background:!0}),o=[s.terminalReport];return o.push(oT(n.session_id,s.snapshot.status)),s.snapshot.status==="escalated"?o.push(aT(n.session_id)):s.snapshot.status==="ready-for-approval"&&o.push(iT(n.session_id)),{content:[{type:"text",text:o.join(`
|
|
307
307
|
|
|
308
|
-
`)}]}}catch(
|
|
309
|
-
`)}]}}catch(
|
|
310
|
-
`)}function
|
|
311
|
-
`)}function
|
|
308
|
+
`)}]}}catch(s){return Jr(`Continue failed: ${D(s)}`)}}async function sT(t,e){let r=sd(e);if(r)return r;let n;try{n=rd.parse(t)}catch(s){return Jr(`Invalid arguments: ${D(s)}`)}try{let s=await e.moderatorEngine.reject({sessionId:n.session_id,...n.reason!==void 0?{reason:n.reason}:{},...n.spawn_issue!==void 0?{spawnIssue:n.spawn_issue}:{}}),o=s.snapshot.documentPaths.debate,i=[`Structured debate session ${n.session_id} rejected.`];return n.reason&&i.push(`Reason: ${n.reason}`),i.push(`Transcript: ${o}`),s.issuePath&&i.push(`Issue document: ${s.issuePath}`),s.idempotentReplay&&i.push("(idempotent replay of existing rejected state \u2014 no new artifacts written)"),{content:[{type:"text",text:i.join(`
|
|
309
|
+
`)}]}}catch(s){return Jr(`Reject failed: ${D(s)}`)}}function b2(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 oT(t,e){return`Session ID: ${t} \u2014 status: ${e}`}function iT(t){return["Next step \u2014 choose one:",`- Approve synthesis: call \`${Bo}\` with { session_id: "${t}" }`,`- Extend debate: call \`${Wo}\` with { session_id: "${t}", additional_rounds: 3 | 5 | 10 }`,`- Abandon session: call \`${Ho}\` with { session_id: "${t}" }`].join(`
|
|
310
|
+
`)}function aT(t){return["Debate escalated \u2014 max rounds exhausted with open proposals.","The leader should choose one of:",`- \`${Wo}\` with additional_rounds = 3 | 5 | 10 to run more rounds.`,`- \`${Bo}\` to accept the current synthesis with open items captured.`,`- \`${Ho}\` to abandon the session.`,`Session ID: ${t}`].join(`
|
|
311
|
+
`)}function Jr(t){return{content:[{type:"text",text:t}],isError:!0}}function Xg(){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:G(Zl)},{name:"agent_debate_status",title:"Check Debate Status",description:"Check the status and result of a debate session.",inputSchema:G(Bl)},{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:G(Vl)},{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:G(Wl)},{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:G(Hl)},{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:G(Kl)},{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:G(Jl)},{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:G(Gl)},{name:"agent_changes_accept",title:"Accept File Changes",description:"Accept and merge file changes from an isolated worktree back to the main branch.",inputSchema:G(Yl)},{name:"agent_changes_reject",title:"Reject File Changes",description:"Reject file changes and clean up the isolated worktree.",inputSchema:G(Xl)},{name:nd,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:G(Ql)},{name:Bo,title:"Approve Structured Debate",description:"Leader-approve a ready-for-approval structured-debate session. Writes the synthesis document and marks the session approved.",inputSchema:G(ed)},{name:Wo,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:G(td)},{name:Ho,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:G(rd)}]}import{join as J4}from"path";import{readFileSync as S2}from"fs";import{isAbsolute as $2,join as x2}from"path";function cT(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 s of n)if(s.patterns.some(o=>o.test(r)))return s.agent;return null}var od="claude-reviewer",id="claude-qa",w2={"agestra-reviewer":od,"agestra-qa":id};function uT(t){let{topic:e,goal:r,participants:n,excludeParticipants:s,autoInjectSpecialists:o}=t,i=new Set(s),a=n.filter(d=>!i.has(d)),c=cT(e,r),u=c!==null?w2[c]??null:null,l=[];return u===null?{participants:a,skipped:l}:o?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 lT="claude",Qg="claude-cli",P2=new Set([od,id]),ey=Object.freeze({[od]:"agestra-reviewer",[id]:"agestra-qa"});function k2(t){if(!t.startsWith("---"))return t;let e=t.indexOf(`
|
|
312
312
|
`,3);if(e<0)return t;let r=t.indexOf(`
|
|
313
313
|
---`,e);if(r<0)return t;let n=t.indexOf(`
|
|
314
|
-
`,r+4);return n<0?"":t.slice(n+1)}function h2(t,e){return f2.has(t)?e==="claude-code"?{transport:"task-subagent",agentName:Gg[t]}:{transport:"cli-bridge",providerId:Jg,agentName:Gg[t]}:t===Kg?e==="claude-code"?{transport:"read-only-chat",providerId:Kg}:{transport:"cli-bridge",providerId:Jg}:{transport:"read-only-chat",providerId:t}}function rT(t){if(!(!t||t.length===0))return t.map(e=>({path:e}))}var nT=18e4;function Hg(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Participant "${e}" stalled (no response after ${nT/1e3}s)`)),nT))])}function oT(t,e,r,n,o){if(e.system!==void 0)return e.system;let s=Gg[t];if(s===void 0)return;if(o.has(s))return o.get(s)??void 0;let i=sT(r,`${s}.md`);try{let a=m2(n(i)).trim(),c=a.length>0?a:null;return o.set(s,c),c??void 0}catch{o.set(s,null);return}}var Yg=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??sT(process.cwd(),"agents"),this.readFile=e.agentsFileReader??(r=>p2(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 Hg(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??Jg,i=this.lookupProviderOrNull(s);if(!i)return this.buildFailure(e,o,`CLI provider "${s}" not registered`);let a=oT(e,r,this.agentsDir,this.readFile,this.sysPromptCache),c=await Hg(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:rT(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?oT(e,r,this.agentsDir,this.readFile,this.sysPromptCache):r.system,c=await Hg(this.readOnlyAdapter.chat(i,{prompt:r.prompt,system:a,...r.files!==void 0?{files:rT(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,N(s))}}lookupProviderOrNull(e){try{return this.registry.get(e)}catch{return null}}resolveDescriptor(e){let r=h2(e,this.hostKind);return r.transport==="task-subagent"&&!this.subagentSpawner&&this.hostKind==="claude-code"?{transport:"read-only-chat",providerId:Kg,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 iT(t){return new Yg(t)}function aT(t,e){return e(t)}var g2=/[.,!?;:]/g,y2=/\s+/g;function cT(t){return t.toLowerCase().replace(g2," ").replace(y2," ").trim()}function uT(t){return typeof t.location=="string"&&t.location.length>0}function lT(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 v2(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 _2(t,e){let r=t.proposerIds[0],n=e.proposerIds[0];if(r===n)return{kind:"unrelated"};let o=cT(t.title)===cT(e.title),s=t.severity===e.severity,a=uT(t)&&uT(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 Sn=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=lT(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=b2(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(v2(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=lT(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 b2(t){return t.disagree>0||t.revise>0?"dissent":t.missing>0?"pending":t.agree>0?"consensus":"pending"}function dT(t){let e=new Sn,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=_2(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 w2=/<proposals>([\s\S]*?)<\/proposals>/i,$2=/<item\b([^>]*)>([\s\S]*?)<\/item>/g,S2=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*"([^"]*)"/g;function pT(t){let e=w2.exec(t);if(!e)return[];let r=e[1],n=[],o,s=new RegExp($2.source,"g");for(;(o=s.exec(r))!==null;){let i=o[1],a=o[2].trim(),c={},u=new RegExp(S2.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 fT(){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(`
|
|
315
|
-
`)}function
|
|
316
|
-
`)}function
|
|
317
|
-
`)}function
|
|
318
|
-
`)}function
|
|
319
|
-
`)}function
|
|
320
|
-
`)}function
|
|
321
|
-
`)}function
|
|
322
|
-
`)}function RT(t){return t.currentStances.map(e=>`${e.provider} ${bo[e.stance]}${e.automatic?"(\uC790\uB3D9)":""}`).join(", ")}function Ls(t){if(t.conclusion)return`\uACB0\uB860: ${t.conclusion}`;let e=t.currentStances.filter(r=>r.stance!=="agree"&&r.stance!=="not_assigned");return e.length===0?"\uC544\uC9C1 \uBAA8\uB4E0 \uCC38\uAC00\uC790\uC758 \uBA85\uC2DC \uB3D9\uC758\uAC00 \uBAA8\uC774\uC9C0 \uC54A\uC558\uB2E4.":`\uB9C9\uD78C \uC774\uC720: ${e.map(r=>`${r.provider} ${bo[r.stance]}`).join(", ")}`}function IT(t){let e=t.currentStances.filter(s=>s.stance==="agree").map(s=>s.provider).join(", ")||"-",r=t.currentStances.filter(s=>s.stance==="disagree").map(s=>s.provider).join(", ")||"-",n=t.currentStances.filter(s=>s.stance==="opinion"||s.stance==="revise").map(s=>`${s.provider} ${bo[s.stance]}`).join(", ")||"-",o=t.conclusion?t.conclusion:Ls(t);return`| ${t.id} | ${t.title} | ${t.displayStatus} | ${o} | ${t.proposer} | ${e} | ${r} | ${n} |`}function Xg(t,e,r){if(e.length===0){t.push(""),t.push("(\uC5C6\uC74C)");return}for(let n of e)if(t.push(""),t.push(`### ${n.id}: ${n.title}`),t.push(""),t.push(`\uBB34\uC5C7\uC744 \uC704\uD55C \uD56D\uBAA9: ${n.plainSummary}`),t.push(""),t.push(`\uCD5C\uC885 \uACB0\uC815: ${j2(n)}`),t.push(`\uB3D9\uC758\uD55C AI: ${PT(n,"agree")}`),t.push(`\uBC18\uB300\uD55C AI: ${PT(n,"disagree")}`),t.push(`\uD604\uC7AC \uC785\uC7A5: ${M2(n)}`),t.push(`\uBCC0\uACBD \uC5EC\uBD80: ${L2(n)}`),t.push(`\uD1A0\uB860/\uADFC\uAC70 \uC704\uCE58: ${q2(n,r)}`),(n.status==="unresolved"||n.status==="needs_opinion")&&(t.push(`\uB9C9\uD78C \uACB0\uC815: ${n.plainSummary}`),t.push("\uD574\uACB0\uD558\uB824\uBA74: \uBC18\uB300/\uC758\uACAC\uC744 \uB0B8 AI\uAC00 \uC694\uAD6C\uD55C \uADFC\uAC70\uB97C \uBCF4\uAC15\uD558\uAC70\uB098 \uC0AC\uC6A9\uC790\uAC00 \uCD5C\uC885 \uBC29\uD5A5\uC744 \uC120\uD0DD\uD574\uC57C \uD55C\uB2E4.")),t.push(`\uACB0\uC815 \uC774\uC720: ${F2(n)}`),n.comments.length>0){t.push(""),t.push("\uC8FC\uC694 \uC758\uACAC:");for(let o of n.comments.slice(-3))t.push(`- ${o.provider}: ${bo[o.stance]} - ${o.comment}`)}}function j2(t){return t.conclusion?t.conclusion:Ls(t)}function PT(t,e){let r=t.currentStances.filter(n=>n.stance===e).map(n=>`${n.provider}${n.automatic?"(\uC790\uB3D9)":""}`);return r.length>0?r.join(", "):"-"}function M2(t){return t.currentStances.map(e=>`${e.provider} ${bo[e.stance]}${e.automatic?"(\uC790\uB3D9)":""}`).join(", ")}function L2(t){if(t.parentId)return`${t.parentId}\uC5D0\uC11C \uB098\uC628 \uC218\uC815\uC548\uC774 \uD604\uC7AC \uD56D\uBAA9\uC774\uB2E4.`;let e=t.comments.map(r=>r.proposedItemId).filter(r=>r!==void 0);return e.length>0?`\uC218\uC815 \uC81C\uC548\uC774 ${Array.from(new Set(e)).join(", ")} \uD56D\uBAA9\uC73C\uB85C \uC774\uC5B4\uC84C\uB2E4.`:t.status==="accepted"?"\uC6D0\uC548 \uADF8\uB300\uB85C \uD569\uC758\uB428.":t.status==="excluded"?"\uC6D0\uC548\uC774 \uC81C\uC678 \uD569\uC758\uB85C \uB05D\uB0AC\uB2E4.":"\uC544\uC9C1 \uD655\uC815\uB41C \uBCC0\uACBD\uC548 \uC5C6\uC74C."}function q2(t,e){return Array.from(new Set([e.documents.debate,...t.sourceRefs])).join(", ")}function F2(t){return t.comments.length>0?t.comments.slice(-3).map(e=>`${e.provider}: ${bo[e.stance]} - ${e.comment}`).join(" / "):t.status==="accepted"?"\uD65C\uC131 \uCC38\uAC00\uC790\uC758 \uC785\uC7A5\uC774 \uBAA8\uB450 \uB3D9\uC758\uB85C \uBAA8\uC600\uB2E4.":t.status==="excluded"?"\uD65C\uC131 \uCC38\uAC00\uC790\uC758 \uC785\uC7A5\uC774 \uBAA8\uB450 \uBC18\uB300\uB85C \uBAA8\uC5EC \uC81C\uC678\uD558\uAE30\uB85C \uD588\uB2E4.":Ls(t)}function U2(t,e){let r=t.items.filter(a=>a.proposer===e).length,n=t.items.filter(a=>a.proposer===e&&a.status==="accepted").length,o=t.items.filter(a=>a.status==="excluded"&&a.currentStances.some(c=>c.provider===e&&c.stance==="disagree")).length,s=t.items.filter(a=>a.currentStances.some(c=>c.provider===e&&(c.stance==="disagree"||c.stance==="opinion"||c.stance==="revise"))).length,i=r>0?"\uC81C\uC548 \uAE30\uC5EC":"\uAC80\uD1A0 \uAE30\uC5EC";return`| ${e} | ${r} | ${n} | ${o} | ${s} | ${i} |`}var Z2=g.object({title:g.string().min(1),plainSummary:g.string().min(1),originalClaim:g.string().min(1)}),V2=g.object({id:g.string().min(1),stance:g.enum(["agree","disagree","opinion","revise"]),comment:g.string(),proposedItem:Z2.optional()}),B2=g.object({provider:g.string().min(1),round:g.number().int().nonnegative(),items:g.array(V2)});function ey(t,e){let r;try{r=JSON.parse(t)}catch{return{ok:!1,errors:["Response must be valid JSON."]}}let n=B2.safeParse(r);if(!n.success)return{ok:!1,errors:n.error.issues.map(c=>c.message)};let o=[],s=n.data;s.provider!==e.provider&&o.push(`provider mismatch: expected ${e.provider}, got ${s.provider}`),s.round!==e.round&&o.push(`round mismatch: expected ${e.round}, got ${s.round}`);let i=new Set(e.assignedItemIds),a=new Set;for(let c of s.items)i.has(c.id)||o.push(`unassigned item id: ${c.id}`),a.has(c.id)&&o.push(`duplicate item id: ${c.id}`),a.add(c.id),(c.stance==="disagree"||c.stance==="opinion"||c.stance==="revise")&&c.comment.trim().length===0&&o.push(`comment is required for ${c.stance} on ${c.id}`),c.stance==="revise"&&c.proposedItem===void 0&&o.push(`proposedItem is required for revise on ${c.id}`);for(let c of i)a.has(c)||o.push(`missing assigned item id: ${c}`);return o.length>0?{ok:!1,errors:o}:{ok:!0,value:s}}import{existsSync as W2,mkdirSync as H2,readFileSync as K2}from"fs";import{join as AT}from"path";var ur=class{debatesDir;constructor(e){this.debatesDir=AT(e,So)}pathForSession(e){return AT(this.debatesDir,`${e}.consensus.json`)}async write(e){H2(this.debatesDir,{recursive:!0});let r=this.pathForSession(e.sessionId),n={...e,documents:{...e.documents,ledger:r}};return Ve(r,n),r}async load(e){let r=this.pathForSession(e);return W2(r)?JSON.parse(K2(r,"utf-8")):null}};async function ty(t,e){for(;t.rounds<t.maxRounds;){if(t.consensusLedger.items.filter(s=>s.status==="unresolved"||s.status==="needs_opinion").length===0)return;t.rounds+=1;let n=t.rounds,o=new Set;for(let s of t.config.participants){if(t.unavailableParticipants.has(s))continue;let i=xT(t.consensusLedger,{provider:s,round:n,maxItems:10});if(i.assignedItems.length===0)continue;let a={prompt:hT(i,t.legacyProposalIdMap),round:n,...t.files.length>0?{files:t.files}:{}},c=await e.bridge.requestTurn(s,a);if(c.failed){CT(t,s,e.nowIso),t.consensusLedger=rd(t.consensusLedger,{provider:s,round:n,assignedItemIds:i.assignedItems.map(l=>l.id),rawResponse:"",parsedItems:[],validationErrors:[c.failureReason?c.failureReason:"provider failed"]}),await od(t,e);continue}o.add(s),Y2(t,s);let u=await J2(s,i,c.text,a,t.legacyProposalIdMap,e);u.ok?t.consensusLedger=rd(t.consensusLedger,{provider:s,round:n,assignedItemIds:i.assignedItems.map(l=>l.id),rawResponse:u.rawResponse,parsedItems:u.items}):(CT(t,s,e.nowIso),t.consensusLedger=rd(t.consensusLedger,{provider:s,round:n,assignedItemIds:i.assignedItems.map(l=>l.id),rawResponse:u.rawResponse,parsedItems:[],validationErrors:u.errors})),G2(t),await od(t,e)}if(o.size===0)return}}async function J2(t,e,r,n,o,s){let i=e.assignedItems.map(p=>p.id),a=ey(r,{provider:t,round:e.round,assignedItemIds:i});if(a.ok)return{ok:!0,rawResponse:r,items:a.value.items};let c=Qg(r,e,o);if(c.ok)return{ok:!0,rawResponse:r,items:c.items};let u=await s.bridge.requestTurn(t,{prompt:gT(e,[...a.errors,...c.errors],o),round:e.round,...n.files!==void 0?{files:n.files}:{}});if(u.failed)return{ok:!1,rawResponse:r,errors:[...a.errors,...c.errors,`retry failed: ${u.failureReason??"unknown"}`]};let l=ey(u.text,{provider:t,round:e.round,assignedItemIds:i});if(l.ok)return{ok:!0,rawResponse:u.text,items:l.value.items};let d=Qg(u.text,e,o);return d.ok?{ok:!0,rawResponse:u.text,items:d.items}:{ok:!1,rawResponse:u.text,errors:[...l.errors,...d.errors]}}async function od(t,e){let r=new ur(e.registry.getWorkspaceDir());t.consensusLedgerPath=await r.write(t.consensusLedger),t.consensusLedger={...t.consensusLedger,documents:{...t.consensusLedger.documents,individual:{...t.individualPaths},ledger:t.consensusLedgerPath,debate:t.debateDocPath}},await e.documentManager.replaceDocumentContent(t.debateDocId,nd(t.consensusLedger))}function G2(t){for(let e of t.consensusLedger.items){if(Array.from(t.legacyProposalIdMap.values()).includes(e.id))continue;let n=`P${t.legacyProposalIdMap.size+1}`;t.legacyProposalIdMap.set(n,e.id),e.sourceRefs.includes(n)||e.sourceRefs.unshift(n)}}function ry(t){for(let e of t.ledger.proposals.values()){if(e.status!=="merged"||!e.mergedInto)continue;let r=t.legacyProposalIdMap.get(e.id),n=t.legacyProposalIdMap.get(e.mergedInto);if(!r||!n)continue;let o=t.consensusLedger.items.find(s=>s.id===r);o&&(o.status="superseded",o.displayStatus="\uB300\uCCB4\uC548\uC73C\uB85C \uC774\uB3D9",o.conclusion=`\uB300\uCCB4\uC548\uC73C\uB85C \uC774\uB3D9. ${n} \uD56D\uBAA9\uACFC \uAC19\uC740 \uB0B4\uC6A9\uC73C\uB85C \uBCD1\uD569\uD588\uB2E4.`,o.sourceRefs=Array.from(new Set([...o.sourceRefs,n])))}}function CT(t,e,r){let n=(t.consecutiveFailures.get(e)??0)+1;t.consecutiveFailures.set(e,n),n>=xd&&(t.unavailableParticipants.add(e),t.consensusLedger={...t.consensusLedger,activeParticipants:t.consensusLedger.activeParticipants.filter(o=>o!==e),moderatorNotes:[...t.consensusLedger.moderatorNotes,{id:`NOTE-${t.consensusLedger.moderatorNotes.length+1}`,kind:"provider_unavailable",round:t.rounds,provider:e,message:`${e} marked unavailable after repeated failed turns.`,createdAt:r()}]})}function Y2(t,e){t.consecutiveFailures.delete(e)}function ny(t){if(t.consensusLedger.items.length>0)return t.consensusLedger.items.some(r=>r.status==="unresolved"||r.status==="needs_opinion")?"escalated":"ready-for-approval";for(let e of t.ledger.proposals.values())if(e.status==="open")return"escalated";return"ready-for-approval"}function DT(t){return t==="ready-for-approval"||t==="escalated"}function OT(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 zT(t){switch(t){case"accepted":return"accepted";case"excluded":return"rejected";case"superseded":return"superseded";case"needs_opinion":return"inconclusive";case"unresolved":return"open"}}function NT(t,e){for(let[r,n]of t)if(n===e)return r;return e}function jT(t){switch(t){case"agree":return"agree";case"disagree":return"disagree";case"revise":return"revise";case"opinion":return"abstain";case"no_response":case"not_assigned":return"missing"}}function oy(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 sd(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"<unstringifiable error>"}}function qs(t){let e=t.documentPaths.debate;return(e.split(/[\\/]/).pop()??e).replace(/\.md$/,"")}var Q2=Object.freeze(["same","different","unsure"]),Ba="alias-votes",X2=new Set(Q2);function e4(t){return X2.has(t)}function t4(t){let e=`<${Ba}>`,r=`</${Ba}>`,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 r4(t){let e=`<${Ba}>`;return t.includes(e)}var n4=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function o4(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 n4[r]??e})}function s4(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]=o4(u),n=o.index+o[0].length}return t.slice(n).trim().length>0?null:e}function MT(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}function sy(t,e){let r=t4(t);if(!r)return r4(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${Ba}> without matching </${Ba}>`}}:{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(!MT(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(!MT(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=s4(p.attrString);if(f===null){l.push({reason:"malformed-entry",raw:p.raw});continue}let m=f.pair,h=f.vote;if(typeof m!="string"||m.length===0||typeof h!="string"){l.push({pair:typeof m=="string"&&m.length>0?m:void 0,reason:"malformed-entry",raw:p.raw});continue}if(!e4(h)){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 b={pair:m,vote:h};v!==void 0&&(b.reason=v),u.push(b)}return{ok:!0,entries:u,entryErrors:l}}var i4="__";function a4(t){return`${t.proposalA}${i4}${t.proposalB}`}var c4=["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(" "),u4=["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(" "),l4=["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(`
|
|
323
|
-
`),d4="Candidate pairs:";function p4(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(`
|
|
324
|
-
`)
|
|
325
|
-
`)}function
|
|
326
|
-
`)}function
|
|
327
|
-
`)}function BT(){return{renderTerminal:$4,renderSynthesis:S4}}var x4=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 k4(t,e){let r=e.t(x4[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 WT(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=P4(n);r.push(`| ${o} | ${n.title} | ${n.severity} | ${s} |`)}return r}function P4(t){let e=`${t.agreeCount}/${t.totalVoters}`;return t.accepted||t.dissentSummary===void 0||t.dissentSummary.length===0?e:`${e} (${t.dissentSummary})`}function HT(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(uy(o))}return r}function uy(t){let e=`- **${t.participantId}:** ${t.vote}`;return t.reason===void 0||t.reason.length===0?e:`${e} \u2014 ${t.reason}`}function KT(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 E4(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 T4(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 R4(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(uy(s))}return n}function I4(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(uy(s))}return n}var Us=class{deps;sessions=new Map;formatter=BT();constructor(e){this.deps=e}async startDebate(e){let r=(this.deps.generateSessionId??A4)(),n=this.nowIso(),o=tT({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??Sd,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}:{}}),u=new ur(this.deps.registry.getWorkspaceDir()).pathForSession(r),l=td({sessionId:r,topic:e.topic,mode:"review",participants:s.slice(),leader:e.leader,maxRounds:i.maxRounds,documents:{individual:{},ledger:u,debate:a.path},items:[],now:()=>n}),d={sessionId:r,config:i,goal:e.goal,individualReviewPrompt:e.individualReviewPrompt,files:e.files??[],debateDocId:a.id,debateDocPath:a.path,individualPaths:{},createdAt:n,ledger:new Sn,rounds:0,maxRounds:i.maxRounds,consecutiveFailures:new Map,unavailableParticipants:new Set,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:1,consensusLedger:l,consensusLedgerPath:u,legacyProposalIdMap:new Map};this.sessions.set(r,d);try{let p=await this.runIndividualPhase(d,o);d.consensusLedger=td({sessionId:r,topic:e.topic,mode:"review",participants:s.slice(),leader:e.leader,maxRounds:i.maxRounds,documents:{individual:{...d.individualPaths},ledger:d.consensusLedgerPath,debate:d.debateDocPath},items:p.map(h=>({title:h.title,proposer:h.proposerId,plainSummary:h.description??h.title,originalClaim:h.description??h.title,sourceRefs:[h.id,...d.individualPaths[h.proposerId]!==void 0?[d.individualPaths[h.proposerId]]:[],...h.location!==void 0?[h.location]:[]]}))}),d.legacyProposalIdMap=new Map(p.map((h,y)=>[h.id,d.consensusLedger.items[y]?.id??h.id])),await od(d,this.consensusFlowDeps());let{ledger:f}=dT(p);d.ledger=f,d.nextProposalIndex=D4(p),ry(d),f.aliasCandidates.length>0&&await this.runAliasClarificationPhase(d),await ty(d,this.consensusFlowDeps());let m=this.buildSnapshot(d,ny({consensusLedger:d.consensusLedger,ledger:d.ledger}));return await this.deps.registry.persist(m),this.emitTrace(d,"debate_rfa",{status:m.status}),{sessionId:r,status:m.status,snapshot:m,terminalReport:this.renderTerminal(d,m)}}catch(p){let f=this.buildSnapshot(d,"error",sd(p));try{await this.deps.registry.persist(f)}catch{}return this.emitTrace(d,"debate_error",{error:sd(p)}),{sessionId:r,status:"error",snapshot:f,terminalReport:this.renderTerminal(d,f),errorMessage:sd(p)}}}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}}ly(r,["ready-for-approval","escalated"],"approve");let n=this.sessions.get(e.sessionId),o=n?.consensusLedger;!o&&r.documentPaths.consensusLedger&&(o=await new ur(this.deps.registry.getWorkspaceDir()).load(r.sessionId)??void 0);let s=o?ET({...o,documents:{...o.documents,...r.documentPaths.synthesis!==void 0?{synthesis:r.documentPaths.synthesis}:{}}}):this.formatter.renderSynthesis(n?this.buildReportData(n,r,e.leaderNote):JT(r,e.leaderNote),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}}:{}}),c={...r,status:"approved",documentPaths:{...r.documentPaths,synthesis:a.path}};if(o){let u={...o,documents:{...o.documents,synthesis:a.path},moderatorNotes:e.leaderNote!==void 0?[...o.moderatorNotes,{id:`NOTE-${o.moderatorNotes.length+1}`,kind:"format_correction",round:o.round,provider:r.config.leader,message:`Leader note: ${e.leaderNote}`,createdAt:this.nowIso()}]:o.moderatorNotes};await new ur(this.deps.registry.getWorkspaceDir()).write(u),n&&(n.consensusLedger=u,n.consensusLedgerPath=u.documents.ledger,await this.deps.documentManager.replaceDocumentContent(n.debateDocId,nd(n.consensusLedger)))}else await this.deps.documentManager.addComment(n?.debateDocId??qs(r),{author:"moderator",content:this.formatApprovalFooter(e.leaderNote)});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);ly(r,["ready-for-approval","escalated"],"continue");let n=this.sessions.get(e.sessionId);if(!n)if(r.documentPaths.consensusLedger)n=await this.rehydrateConsensusSessionContext(r),this.sessions.set(e.sessionId,n);else if(r.ledgerState)n=this.rehydrateSessionContext(r),this.sessions.set(e.sessionId,n);else 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.maxRounds=r.config.maxRounds+e.additionalRounds,n.consensusLedger={...n.consensusLedger,maxRounds:n.maxRounds};for(let i of n.ledger.proposals.values())i.status;await ty(n,this.consensusFlowDeps());let o=ny({consensusLedger:n.consensusLedger,ledger:n.ledger}),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}:{}};ly(r,["ready-for-approval","escalated","leader-timeout"],"reject");let n=this.sessions.get(e.sessionId),o=n?.debateDocId??qs(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:C4(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=qs(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=fT(),o=mT({topic:e.config.topic,scope:e.config.scope,goal:e.goal,files:e.files,individualReviewPrompt:e.individualReviewPrompt}),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=pT(u.text);for(let f of p){let m=O4(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 ZT({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=wT(r,this.deps.i18n);if(n.length>0){for(let o of r.mergesApplied){let s=e.legacyProposalIdMap.get(o.alias),i=e.legacyProposalIdMap.get(o.primary);if(!s||!i)continue;let a=e.consensusLedger.items.find(c=>c.id===s);a&&(a.status="superseded",a.displayStatus="\uB300\uCCB4\uC548\uC73C\uB85C \uC774\uB3D9",a.conclusion=`\uB300\uCCB4\uC548\uC73C\uB85C \uC774\uB3D9. ${i} \uD56D\uBAA9\uACFC \uAC19\uC740 \uB0B4\uC6A9\uC73C\uB85C \uBCD1\uD569\uD588\uB2E4.`,a.sourceRefs=Array.from(new Set([...a.sourceRefs,i])))}ry(e),e.consensusLedger={...e.consensusLedger,moderatorNotes:[...e.consensusLedger.moderatorNotes,{id:`NOTE-${e.consensusLedger.moderatorNotes.length+1}`,kind:"merge_candidate",round:e.rounds,message:n,createdAt:this.nowIso()}]},await this.deps.documentManager.addComment(e.debateDocId,{author:"moderator",content:n})}}consensusFlowDeps(){return{bridge:this.deps.bridge,documentManager:this.deps.documentManager,registry:this.deps.registry,nowIso:()=>this.nowIso()}}rehydrateSessionContext(e){if(!e.ledgerState)throw new Error(`rehydrateSessionContext: snapshot "${e.sessionId}" has no ledgerState`);let r=Sn.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:qs(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,consensusLedger:td({sessionId:e.sessionId,topic:e.config.topic,mode:"review",participants:e.config.participants.slice(),leader:e.config.leader,maxRounds:e.config.maxRounds,documents:{individual:{...e.documentPaths.individual},ledger:e.documentPaths.consensusLedger??new ur(this.deps.registry.getWorkspaceDir()).pathForSession(e.sessionId),debate:e.documentPaths.debate,...e.documentPaths.synthesis!==void 0?{synthesis:e.documentPaths.synthesis}:{}},items:e.aggregatedVotes.map(a=>({title:a.title,proposer:a.proposers[0]??e.config.leader,plainSummary:a.title,originalClaim:a.title,sourceRefs:a.location?[a.location]:[]}))}),consensusLedgerPath:e.documentPaths.consensusLedger??new ur(this.deps.registry.getWorkspaceDir()).pathForSession(e.sessionId),legacyProposalIdMap:new Map(e.aggregatedVotes.map((a,c)=>[a.proposalId,`ITEM-${String(c+1).padStart(2,"0")}`]))}}async rehydrateConsensusSessionContext(e){let r=new ur(this.deps.registry.getWorkspaceDir()),n=e.documentPaths.consensusLedger??r.pathForSession(e.sessionId),o=await r.load(e.sessionId);if(!o)throw new Error(`continueDebate: consensus ledger not found for session "${e.sessionId}" at ${n}`);let s=new Map;if(e.consecutiveFailuresByParticipant)for(let[i,a]of Object.entries(e.consecutiveFailuresByParticipant))a>0&&s.set(i,a);return{sessionId:e.sessionId,config:e.config,goal:void 0,individualReviewPrompt:void 0,files:[],debateDocId:qs(e),debateDocPath:e.documentPaths.debate,individualPaths:{...e.documentPaths.individual},createdAt:e.createdAt,ledger:e.ledgerState?Sn.fromJSON(e.ledgerState):new Sn,rounds:e.rounds,maxRounds:e.config.maxRounds,consecutiveFailures:s,unavailableParticipants:new Set(e.unavailableParticipants??[]),allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:1,consensusLedger:o,consensusLedgerPath:n,legacyProposalIdMap:bT(o)}}buildSnapshot(e,r,n){let o=this.nowIso(),s=DT(r)?aT(o,VT):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,consensusLedger:e.consensusLedgerPath},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){if(e.consensusLedger.items.length>0)return e.consensusLedger.items.map(n=>{let o={};for(let s of n.currentStances){let i=s.commentId?n.comments.find(a=>a.id===s.commentId):void 0;o[s.provider]={vote:jT(s.stance),roundRecorded:s.round,...i?.comment?{reason:i.comment}:{}}}return{proposalId:NT(e.legacyProposalIdMap,n.id),title:n.title,severity:"MEDIUM",proposers:[n.proposer],status:zT(n.status),votes:o,...n.parentId!==void 0?{supersededBy:n.parentId}:{}}});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:OT(n.status),votes:o,...n.supersededBy!==void 0?{supersededBy:n.supersededBy}:{}})}return r}renderTerminal(e,r){if(e?.consensusLedger)return[`Topic: ${e.consensusLedger.topic}`,`Status: ${r.status}`,`Readable status: ${r.status.replace(/-/g," ")}`,"",TT({...e.consensusLedger,documents:{...e.consensusLedger.documents,...r.documentPaths.synthesis!==void 0?{synthesis:r.documentPaths.synthesis}:{}}})].join(`
|
|
328
|
-
`)
|
|
314
|
+
`,r+4);return n<0?"":t.slice(n+1)}function E2(t,e){return P2.has(t)?e==="claude-code"?{transport:"task-subagent",agentName:ey[t]}:{transport:"cli-bridge",providerId:Qg,agentName:ey[t]}:t===lT?e==="claude-code"?{transport:"read-only-chat",providerId:lT}:{transport:"cli-bridge",providerId:Qg}:{transport:"read-only-chat",providerId:t}}function T2(t){if(!(!t||t.length===0))return t.map(e=>({path:e}))}function I2(t,e){if(e===void 0)return{clear:()=>{}};let r=new AbortController,n=setTimeout(()=>{r.abort(new Error(`Participant "${t}" stalled (no response after ${Math.round(e/1e3)}s)`))},e+1e3);return n.unref?.(),{signal:r.signal,clear:()=>clearTimeout(n)}}function dT(t,e,r,n,s){if(e.system!==void 0)return e.system;let o=ey[t];if(o===void 0)return;if(s.has(o))return s.get(o);let i=x2(r,`${o}.md`),a;try{a=n(i)}catch(u){throw new Error(`specialist prompt unavailable: ${i}: ${D(u)}`)}let c=k2(a).trim();if(c.length===0)throw new Error(`specialist prompt unavailable: ${i} is empty`);return s.set(o,c),c}var ty=class{registry;readOnlyAdapter;hostKind;agentsDir;readFile;subagentSpawner;sysPromptCache=new Map;constructor(e){if(this.registry=e.registry,this.readOnlyAdapter=e.readOnlyAdapter,this.hostKind=e.hostKind,!e.agentsDir)throw new Error("ParticipantBridge: agentsDir is required");if(!$2(e.agentsDir))throw new Error(`ParticipantBridge: agentsDir must be absolute: ${e.agentsDir}`);this.agentsDir=e.agentsDir,this.readFile=e.agentsFileReader??(r=>S2(r,"utf-8")),this.subagentSpawner=e.subagentSpawner}describe(e){return this.resolveDescriptor(e)}async requestTurn(e,r){let n=this.resolveDescriptor(e),s=performance.now();try{switch(n.transport){case"task-subagent":{if(!this.subagentSpawner)return this.buildFailure(e,s,"subagent spawner not wired (integration pending \u2014 T10/T12)");let o=await this.subagentSpawner({agentName:n.agentName??e,prompt:r.prompt,system:r.system});return this.buildSuccess(e,s,o.text)}case"cli-bridge":{let o=n.providerId??Qg,i=this.lookupProviderOrNull(o);if(!i)return this.buildFailure(e,s,`CLI provider "${o}" not registered`);let a=dT(e,r,this.agentsDir,this.readFile,this.sysPromptCache),c=await this.chatWithParticipantControls(e,i,r,a);return this.buildSuccess(e,s,c.text)}case"read-only-chat":{let o=n.providerId??e,i=this.lookupProviderOrNull(o);if(!i)return this.buildFailure(e,s,`provider "${o}" not registered`);let a=n.agentName!==void 0?dT(e,r,this.agentsDir,this.readFile,this.sysPromptCache):r.system,c=await this.chatWithParticipantControls(e,i,r,a);return this.buildSuccess(e,s,c.text)}default:{let o=n.transport;return this.buildFailure(e,s,`unknown transport: ${String(o)}`)}}}catch(o){return this.buildFailure(e,s,D(o))}}lookupProviderOrNull(e){try{return this.registry.get(e)}catch{return null}}async chatWithParticipantControls(e,r,n,s){let o=I2(e,n.timeoutMs);try{return await this.readOnlyAdapter.chat(r,{prompt:n.prompt,...s!==void 0?{system:s}:{},...n.files!==void 0?{files:T2(n.files)}:{},...n.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:{},...n.activity!==void 0?{activity:n.activity}:{},...o.signal!==void 0?{signal:o.signal}:{}})}finally{o.clear()}}resolveDescriptor(e){return E2(e,this.hostKind)}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 pT(t){return new ty(t)}function fT(t,e){return e(t)}var R2=/[.,!?;:]/g,A2=/\s+/g;function mT(t){return t.toLowerCase().replace(R2," ").replace(A2," ").trim()}function hT(t){return typeof t.location=="string"&&t.location.length>0}function gT(t,e){if(e.length===0)return t;let r=new Set(t),n=t.slice();for(let s of e)r.has(s)||(r.add(s),n.push(s));return n}function C2(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 D2(t,e){let r=t.proposerIds[0],n=e.proposerIds[0];if(r===n)return{kind:"unrelated"};let s=mT(t.title)===mT(e.title),o=t.severity===e.severity,a=hT(t)&&hT(e)&&t.location===e.location,c=[];if(s&&c.push("title"),o&&c.push("severity"),a&&c.push("location"),c.length===0)return{kind:"unrelated"};if(s&&o&&a)return{kind:"hard-merge"};let l;return s?o?l="location":l="severity":l="title",{kind:"alias",pair:{proposalA:t.id,proposalB:e.id,matchedFields:c,missingField:l}}}var Pn=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 s=this._proposals.get(e);if(!s)throw new Error(`ProposalLedger.recordVote: unknown proposal id "${e}"`);s.votes.set(r,{...n}),s.proposerIds.includes(r)&&n.vote==="revise"&&s.status==="open"&&(s.status="withdrawn-by-author")}countRevisesThisRound(e,r){let n=this._proposals.get(e);if(!n)return 0;let s=0;for(let[o,i]of n.votes)i.vote==="revise"&&i.roundRecorded===r&&(n.proposerIds.includes(o)||(s+=1));return s}markSuperseded(e,r,n){let s=this._proposals.get(e);if(!s)throw new Error(`ProposalLedger.markSuperseded: unknown old id "${e}"`);if(!this._proposals.has(r))throw new Error(`ProposalLedger.markSuperseded: successor id "${r}" not registered`);s.status="superseded",s.supersededBy=r;for(let o of s.votes.values())o.supersededAt===void 0&&(o.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),s=this._proposals.get(r);if(!n)throw new Error(`ProposalLedger.applyAliasMerge: unknown primary id "${e}"`);if(!s)throw new Error(`ProposalLedger.applyAliasMerge: unknown alias id "${r}"`);n.proposerIds=gT(n.proposerIds,s.proposerIds);for(let[o,i]of s.votes){let a=n.votes.get(o);if(!a){n.votes.set(o,{...i});continue}i.roundRecorded>a.roundRecorded&&n.votes.set(o,{...i})}s.status="merged",s.mergedInto=e;for(let o=this._aliasCandidates.length-1;o>=0;o-=1){let i=this._aliasCandidates[o];(i.proposalA===r||i.proposalB===r||i.proposalA===e||i.proposalB===e)&&this._aliasCandidates.splice(o,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 s=new Set(n),o=[];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){s.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=O2(a);o.push({proposalId:i.id,tally:a,verdict:c})}return o}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(C2(n));return r}toJSON(){let e=Array.from(this._proposals.values()).map(n=>{let s=[];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),s.push(c)}let o={id:n.id,proposerIds:n.proposerIds.slice(),title:n.title,severity:n.severity,roundOpened:n.roundOpened,status:n.status,votes:s};return n.location!==void 0&&(o.location=n.location),n.description!==void 0&&(o.description=n.description),n.supersededBy!==void 0&&(o.supersededBy=n.supersededBy),n.mergedInto!==void 0&&(o.mergedInto=n.mergedInto),o}),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 s of e.proposals){if(n.has(s.id))throw new Error(`ProposalLedger.fromJSON: duplicate proposal id "${s.id}"`);n.add(s.id);let o={id:s.id,proposerIds:s.proposerIds.slice(),title:s.title,severity:s.severity,roundOpened:s.roundOpened,status:s.status,votes:new Map};s.location!==void 0&&(o.location=s.location),s.description!==void 0&&(o.description=s.description),s.supersededBy!==void 0&&(o.supersededBy=s.supersededBy),s.mergedInto!==void 0&&(o.mergedInto=s.mergedInto);for(let i of s.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),o.votes.set(i.voter,a)}r._proposals.set(o.id,o)}for(let s of e.aliasCandidates)r._aliasCandidates.push({proposalA:s.proposalA,proposalB:s.proposalB,matchedFields:s.matchedFields.slice(),missingField:s.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=gT(n.proposerIds,r))}_maybeReplaceDescription(e,r){let n=this._proposals.get(e);if(!n||r===void 0)return;let s=n.description??"";r.length>s.length&&(n.description=r)}};function O2(t){return t.disagree>0||t.revise>0?"dissent":t.missing>0?"pending":t.agree>0?"consensus":"pending"}function yT(t){let e=new Pn,r=new Set;for(let o of t){if(r.has(o.id))throw new Error(`buildInitialLedger: duplicate proposal id "${o.id}"`);r.add(o.id),e.addProposal({id:o.id,proposerIds:[o.proposerId],title:o.title,severity:o.severity,...o.location!==void 0?{location:o.location}:{},...o.description!==void 0?{description:o.description}:{},roundOpened:o.roundOpened??1,status:"open"})}let n=new Set,s=t.map(o=>o.id);for(let o=0;o<s.length;o+=1){let i=s[o];if(n.has(i))continue;let a=e._rawProposal(i);if(a)for(let c=o+1;c<s.length;c+=1){let u=s[c];if(n.has(u))continue;let l=e._rawProposal(u);if(!l)continue;let d=D2(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 z2=/<proposals>([\s\S]*?)<\/proposals>/i,M2=/<item\b([^>]*)>([\s\S]*?)<\/item>/g,N2=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*"([^"]*)"/g;function ry(t){let e=z2.exec(t);if(!e)return[];let r=e[1],n=[],s,o=new RegExp(M2.source,"g");for(;(s=o.exec(r))!==null;){let i=s[1],a=s[2].trim(),c={},u=new RegExp(N2.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}var j2=y.object({title:y.string().min(1),plainSummary:y.string().min(1),originalClaim:y.string().min(1)}),L2=y.object({id:y.string().min(1),stance:y.enum(["agree","disagree","opinion","revise"]),comment:y.string(),proposedItem:j2.optional()}),vT=y.object({provider:y.string().min(1),round:y.number().int().nonnegative(),items:y.array(L2)});function _T(t){return t.issues.map(e=>`${e.path.length>0?`${e.path.join(".")}: `:""}${e.message}`)}function q2(t){return{provider:t.provider,round:t.round,items:t.assignedItems.map(e=>({id:e.id,stance:"agree",comment:"Explain the explicit reason for this stance."}))}}function ny(t){return["Return JSON only.","The top-level object must have exactly these fields: provider, round, items.","Do not use a votes key.","Do not use XML.","Do not include Markdown fences or prose.","Every assigned item must appear exactly once in items.","Use only these stance values: agree, disagree, opinion, revise.","disagree, opinion, and revise require a non-empty comment.","revise requires proposedItem with title, plainSummary, originalClaim.","","Response example:",JSON.stringify(q2(t),null,2)].join(`
|
|
315
|
+
`)}function bT(t="review"){let e=t==="idea"?"individual-idea phase of a structured multi-AI consensus workflow":"individual-review phase of a structured multi-AI debate",r=t==="idea"?"improvement ideas":"concrete findings",n=t==="idea"?"file:line, component, or idea area":"file:line or component";return[`You are a participant in the ${e}.`,`Produce concise source material and propose ${r}.`,"Findings or ideas 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="${n}">`," 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 should use CRITICAL, HIGH, MEDIUM, or LOW when possible.","- Description text is AI-native; the moderator preserves it verbatim."].join(`
|
|
316
|
+
`)}function wT(t){let e=[];if(e.push(`Mode: ${t.mode}`),e.push(`Topic: ${t.topic}`),t.goal&&e.push(`Goal: ${t.goal}`),e.push(`Scope: ${t.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(t.mode==="idea"?"Return your ideas followed by the required `<proposals>` block.":"Return your review followed by the required `<proposals>` block."),e.join(`
|
|
317
|
+
`)}function ST(t,e=new Map){let r=xT(t,e);return["You are a participant in a structured consensus round.","Read the JSON packet. It is the input, not your response shape.",...r.length>0?["","Legacy compatibility IDs:",...r]:[],"","Input packet:","```json",JSON.stringify(t,null,2),"```","",ny(t)].join(`
|
|
318
|
+
`)}function $T(t,e,r=new Map){let n=xT(t,r);return["Your previous response did not satisfy the JSON consensus contract.","Validation errors:",...e.map(s=>`- ${s}`),...n.length>0?["","Legacy compatibility IDs:",...n]:[],"","Input packet:","```json",JSON.stringify(t,null,2),"```","",ny(t)].join(`
|
|
319
|
+
`)}function xT(t,e){let r=[];for(let[n,s]of e){let o=t.assignedItems.find(i=>i.id===s);o&&r.push(`- ${n} (${o.id}): ${o.title}`)}return r}function PT(t){let e=new Map;for(let r of t.items)for(let n of r.sourceRefs)/^P\d+$/i.test(n)&&e.set(n,r.id);return e}function kT(t,e){let n=[`## ${e.t("moderator.narration.aliasClarification")}`];if(t.mergesApplied.length>0){n.push(""),n.push("Applied merges:");for(let s of t.mergesApplied)n.push(`- ${s.alias} \u2192 ${s.primary} (same=${s.voteBreakdown.same}, different=${s.voteBreakdown.different}, unsure=${s.voteBreakdown.unsure}, missing=${s.voteBreakdown.missing})`)}if(t.undecided.length>0){n.push(""),n.push("Undecided pairs (kept separate):");for(let s of t.undecided)n.push(`- ${s.pair.proposalA} \u2194 ${s.pair.proposalB} (${s.reason})`)}return n.join(`
|
|
320
|
+
`)}function ad(t){let e=t.now?t.now():new Date().toISOString();return{schemaVersion:1,sessionId:t.sessionId,topic:t.topic,mode:t.mode,participants:t.participants.slice(),activeParticipants:t.participants.slice(),leader:t.leader,round:0,maxRounds:t.maxRounds,documents:t.documents,items:t.items.map((r,n)=>{let s=`ITEM-${String(n+1).padStart(2,"0")}`;return F2(s,r,t.participants)}),turns:[],moderatorNotes:[],createdAt:e,updatedAt:e}}function F2(t,e,r){return{id:t,title:e.title,proposer:e.proposer,status:"unresolved",displayStatus:"\uBBF8\uD569\uC758",currentStances:r.map(n=>({provider:n,stance:n===e.proposer?"agree":"not_assigned",round:0,...n===e.proposer?{automatic:!0}:{}})),plainSummary:e.plainSummary,originalClaim:e.originalClaim,comments:[],sourceRefs:e.sourceRefs.slice()}}function IT(t,e){let r=U2(t,e);return{sessionId:t.sessionId,round:e.round,provider:e.provider,topic:t.topic,itemIndex:t.items.map(n=>({id:n.id,title:n.title,status:n.status,displayStatus:n.displayStatus,proposer:n.proposer,stanceSummary:n.currentStances.map(s=>`${s.provider} ${s.stance}${s.automatic?"(auto)":""}`).join(", "),blockedReason:TT(n)})),assignedItems:r.map(n=>({id:n.id,title:n.title,plainSummary:n.plainSummary,originalClaim:n.originalClaim,currentSummary:TT(n),recentComments:n.comments.slice(-4)})),responseContract:{allowedStances:["agree","disagree","opinion","revise"],mustAnswerEveryAssignedItem:!0,jsonOnly:!0}}}function U2(t,e){let r=t.items.filter(s=>s.status==="unresolved"||s.status==="needs_opinion");return e.maxItems<=0?[]:r.length<=e.maxItems?r:r.map((s,o)=>{let i=s.currentStances.find(l=>l.provider===e.provider)?.stance??"not_assigned",a=i==="not_assigned"||i==="no_response"?0:i==="opinion"||i==="disagree"||i==="revise"?1:2,c=(e.round-1)*e.maxItems,u=(o-c)%r.length;return{item:s,priority:a,rotation:u<0?u+r.length:u}}).sort((s,o)=>s.priority-o.priority||s.rotation-o.rotation).slice(0,e.maxItems).map(s=>s.item)}function RT(t,e){let r=e.now?e.now():new Date().toISOString(),n=AT(t);return n.nextTurn={round:e.round,provider:e.provider,assignedItemIds:e.assignedItemIds.slice()},n.updatedAt=r,e.totalActiveItems>e.maxItems&&n.moderatorNotes.push({id:`NOTE-${n.moderatorNotes.length+1}`,kind:"batching",round:e.round,provider:e.provider,message:`Assigned ${e.assignedItemIds.length} of ${e.totalActiveItems} active items to ${e.provider}; unassigned active items remain not_assigned for this turn.`,createdAt:r}),n}function cd(t,e){let r=e.now?e.now():new Date().toISOString(),n=AT(t);n.round=Math.max(n.round,e.round),n.updatedAt=r;let s=[],o=e.validationErrors!==void 0?e.validationErrors:[];if(o.length>0){for(let i of e.assignedItemIds)ET(n,i,e.provider,"no_response",e.round);n.moderatorNotes.push({id:`NOTE-${n.moderatorNotes.length+1}`,kind:"missing_stance",round:e.round,provider:e.provider,message:o.join("; "),createdAt:r})}else for(let i of e.parsedItems){s.push(i.id);let a=`C-${n.turns.length+1}-${s.length}`,c={id:a,itemId:i.id,provider:e.provider,round:e.round,stance:i.stance,comment:i.comment,createdAt:r,rawResponse:e.rawResponse},u=CT(n,i.id);if(u.comments.push(c),ET(n,i.id,e.provider,i.stance,e.round,a),i.stance==="revise"&&i.proposedItem){let l=Z2(n,i.id);c.proposedItemId=l,u.status="superseded",u.displayStatus="\uB300\uCCB4\uC548\uC73C\uB85C \uC774\uB3D9",u.conclusion=`\uB300\uCCB4\uC548\uC73C\uB85C \uC774\uB3D9. ${l} \uD56D\uBAA9\uC5D0\uC11C \uC218\uC815 \uC81C\uC548\uC744 \uAC80\uD1A0\uD55C\uB2E4.`,n.items.push({id:l,parentId:i.id,title:i.proposedItem.title,proposer:e.provider,status:"unresolved",displayStatus:"\uBBF8\uD569\uC758",currentStances:n.activeParticipants.map(d=>({provider:d,stance:d===e.provider?"agree":"not_assigned",round:e.round,...d===e.provider?{automatic:!0}:{}})),plainSummary:i.proposedItem.plainSummary,originalClaim:i.proposedItem.originalClaim,comments:[],sourceRefs:[i.id]})}}for(let i of n.items)V2(i,n.activeParticipants);return n.turns.push({id:`TURN-${n.turns.length+1}`,round:e.round,provider:e.provider,assignedItemIds:e.assignedItemIds.slice(),responseItemIds:s,accepted:o.length===0,createdAt:r,rawResponse:e.rawResponse,validationErrors:o.slice()}),n}function AT(t){return JSON.parse(JSON.stringify(t))}function CT(t,e){let r=t.items.find(n=>n.id===e);if(!r)throw new Error(`Unknown consensus item: ${e}`);return r}function ET(t,e,r,n,s,o){let i=CT(t,e),a=i.currentStances.find(u=>u.provider===r),c={provider:r,stance:n,round:s,...o?{commentId:o}:{}};if(a){a.stance=n,a.round=s,delete a.automatic,o?a.commentId=o:delete a.commentId;return}i.currentStances.push(c)}function Z2(t,e){let r=new Set(t.items.map(n=>n.id));for(let n=65;n<=90;n+=1){let s=`${e}-${String.fromCharCode(n)}`;if(!r.has(s))return s}throw new Error(`Too many child items for ${e}`)}function V2(t,e){if(t.status==="superseded"){t.displayStatus="\uB300\uCCB4\uC548\uC73C\uB85C \uC774\uB3D9";return}let r=e.map(n=>{let s=t.currentStances.find(o=>o.provider===n);return s?s.stance:"not_assigned"});if(r.every(n=>n==="agree")){t.status="accepted",t.displayStatus="\uD569\uC758\uB428",t.conclusion="\uD569\uC758\uB428. \uC804\uC6D0 \uB3D9\uC758\uB85C \uC774 \uD56D\uBAA9\uC744 \uD3EC\uD568\uD558\uAE30\uB85C \uD588\uB2E4.";return}if(r.every(n=>n==="disagree")){t.status="excluded",t.displayStatus="\uC81C\uC678 \uD569\uC758",t.conclusion="\uC81C\uC678 \uD569\uC758. \uC804\uC6D0 \uBC18\uB300\uB85C \uC774 \uD56D\uBAA9\uC744 \uD3EC\uD568\uD558\uC9C0 \uC54A\uAE30\uB85C \uD588\uB2E4.";return}if(r.some(n=>n==="opinion"||n==="no_response")){t.status="needs_opinion",t.displayStatus="\uC758\uACAC \uD544\uC694",delete t.conclusion;return}t.status="unresolved",t.displayStatus="\uBBF8\uD569\uC758",delete t.conclusion}function TT(t){if(t.conclusion)return`\uACB0\uB860: ${t.conclusion}`;let e=t.currentStances.filter(r=>r.stance!=="agree"&&r.stance!=="not_assigned");return e.length===0?"\uC544\uC9C1 \uBAA8\uB4E0 \uCC38\uAC00\uC790\uC758 \uBA85\uC2DC \uB3D9\uC758\uAC00 \uBAA8\uC774\uC9C0 \uC54A\uC558\uB2E4.":e.map(r=>`${r.provider} ${r.stance}`).join(", ")}var Ss={agree:"\uB3D9\uC758",disagree:"\uBC18\uB300",opinion:"\uC758\uACAC",revise:"\uC218\uC815 \uC81C\uC548",no_response:"\uC751\uB2F5 \uC5C6\uC74C",not_assigned:"\uC774\uBC88 \uD134 \uC81C\uC678"};function ud(t){let e=[];e.push(`# \uD1A0\uB860 \uCDE8\uD569 \uBB38\uC11C: ${t.topic}`),e.push(""),e.push(`**Session:** ${t.sessionId}`),e.push(`**\uC0C1\uD0DC \uC6D0\uBCF8 JSON:** ${t.documents.ledger}`),e.push(`**\uCC38\uC5EC AI:** ${t.participants.join(", ")}`),e.push(`**\uD604\uC7AC \uB77C\uC6B4\uB4DC:** ${t.round}/${t.maxRounds}`),e.push(""),e.push("## \uD56D\uBAA9 \uD604\uD669\uD310"),e.push(""),e.push("| ID | \uD56D\uBAA9 | \uC0C1\uD0DC | \uC81C\uC2DC\uC790 | \uB3D9\uC758 \uD604\uD669 | \uD604\uC7AC \uACB0\uB860/\uB9C9\uD78C \uC774\uC720 |"),e.push("|---|---|---|---|---|---|");for(let r of t.items)e.push(`| ${r.id} | ${r.title} | ${r.displayStatus} | ${r.proposer} | ${zT(r)} | ${Ko(r)} |`);for(let r of t.items)e.push(""),e.push(...B2(r));if(t.moderatorNotes.length>0){e.push(""),e.push("## Moderator Notes");for(let r of t.moderatorNotes)e.push(""),e.push(`- ${r.kind}: ${r.message}`)}return e.join(`
|
|
321
|
+
`)}function B2(t){let e=[];e.push(`## ${t.id}: ${t.title}`),e.push(""),e.push(`**\uC81C\uC2DC\uC790:** ${t.proposer}`),e.push(`**\uD604\uC7AC \uC0C1\uD0DC:** ${t.displayStatus}`),e.push(`**\uD604\uC7AC \uB3D9\uC758 \uD604\uD669:** ${zT(t)}`),e.push(""),e.push("**\uBB34\uC5C7\uC744 \uC704\uD55C \uD56D\uBAA9\uC778\uAC00.**"),e.push(t.plainSummary),e.push(""),e.push("**\uC6D0 \uC8FC\uC7A5.**"),e.push(t.originalClaim),e.push(""),e.push("### \uD604\uC7AC \uC815\uB9AC"),e.push(Ko(t));let r=Array.from(new Set(t.comments.map(n=>n.round))).sort((n,s)=>n-s);for(let n of r){e.push(""),e.push(`### Round ${n}`);for(let s of t.comments.filter(o=>o.round===n))e.push(""),e.push(`#### ${s.provider} \uC758\uACAC`),e.push(""),e.push(`\uC785\uC7A5: ${Ss[s.stance]}`),e.push(""),e.push(`\uB0B4\uC6A9: ${s.comment}`),s.proposedItemId&&(e.push(""),e.push(`\uC0C8 \uD56D\uBAA9 \uC81C\uC548: ${s.proposedItemId}`))}return t.conclusion&&(e.push(""),e.push("### \uACB0\uB860"),e.push(""),e.push(t.conclusion)),e}function oy(t){let e=t.items.filter(o=>o.status==="accepted"),r=t.items.filter(o=>o.status==="excluded"),n=t.items.filter(o=>o.status==="unresolved"||o.status==="needs_opinion"),s=[];s.push("## \uD55C\uB208\uC5D0 \uBCF4\uAE30"),s.push(""),s.push(`- \uC8FC\uC81C: ${t.topic}`),s.push(`- \uCC38\uC5EC AI: ${t.participants.join(", ")}`),s.push(`- \uD569\uC758\uAE4C\uC9C0 \uB3C4\uB2EC\uD55C \uB77C\uC6B4\uB4DC: ${t.round}/${t.maxRounds}`),s.push(`- \uD569\uC758\uB41C \uD56D\uBAA9: ${e.length}`),s.push(`- \uC81C\uC678 \uD569\uC758 \uD56D\uBAA9: ${r.length}`),s.push(`- \uBBF8\uD569\uC758 / \uC758\uACAC \uD544\uC694 \uD56D\uBAA9: ${n.length}`),s.push(`- JSON \uC7A5\uBD80: ${t.documents.ledger}`),s.push(`- \uCDE8\uD569\uBB38\uC11C: ${t.documents.debate}`),s.push(""),s.push("## \uCD5C\uC885 \uACB0\uB860\uD45C"),s.push(""),s.push("| ID | \uD56D\uBAA9 | \uCD5C\uC885 \uC0C1\uD0DC | \uACB0\uB860 | \uC81C\uC2DC\uC790 | \uB3D9\uC758\uD55C AI | \uBC18\uB300\uD55C AI | \uC758\uACAC/\uC218\uC815 \uC81C\uC548 |"),s.push("|---|---|---|---|---|---|---|---|");for(let o of t.items)s.push(MT(o));s.push(""),s.push("## \uD569\uC758\uB41C \uD56D\uBAA9"),sy(s,e,t),s.push(""),s.push("## \uC81C\uC678 \uD569\uC758 \uD56D\uBAA9"),sy(s,r,t),s.push(""),s.push("## \uBBF8\uD569\uC758 / \uC758\uACAC \uD544\uC694 \uD56D\uBAA9"),sy(s,n,t),s.push(""),s.push("## \uD504\uB85C\uBC14\uC774\uB354\uBCC4 \uC131\uACFC"),s.push(""),s.push("| Provider | \uC81C\uC548 \uC218 | \uD569\uC758\uB41C \uC81C\uC548 | \uC81C\uC678 \uD569\uC758\uC5D0 \uAE30\uC5EC | \uBC18\uB300/\uC758\uACAC\uC73C\uB85C \uAE30\uC5EC\uD55C \uD56D\uBAA9 | \uD2B9\uC9D5 |"),s.push("|---|---|---|---|---|---|");for(let o of t.participants)s.push(Y2(t,o));s.push(""),s.push("## \uCC38\uC870 \uBB38\uC11C"),s.push(""),s.push(`- JSON \uC7A5\uBD80: ${t.documents.ledger}`),s.push(`- \uCDE8\uD569\uBB38\uC11C: ${t.documents.debate}`),t.documents.synthesis&&s.push(`- \uACB0\uB860\uBB38\uC11C: ${t.documents.synthesis}`);for(let[o,i]of Object.entries(t.documents.individual))s.push(`- ${o} \uAC1C\uBCC4 \uBB38\uC11C: ${i}`);return s.join(`
|
|
322
|
+
`)}function OT(t){let e=[];e.push("## \uCD5C\uC885 \uACB0\uB860\uD45C"),e.push(""),e.push("| ID | \uD56D\uBAA9 | \uC0C1\uD0DC | \uACB0\uB860/\uB9C9\uD78C \uC774\uC720 | \uC81C\uC2DC\uC790 | \uB3D9\uC758\uD55C AI | \uBC18\uB300\uD55C AI | \uC758\uACAC/\uC218\uC815 \uC81C\uC548 |"),e.push("|---|---|---|---|---|---|---|---|");for(let n of t.items)e.push(MT(n));let r=t.items.filter(n=>n.status==="unresolved"||n.status==="needs_opinion");if(r.length>0){e.push(""),e.push("## \uBBF8\uD569\uC758 \uD56D\uBAA9 \uC124\uBA85");for(let n of r)e.push(""),e.push(`### ${n.id}: ${n.title}`),e.push(n.plainSummary),e.push(Ko(n))}return e.push(""),e.push("## \uBB38\uC11C \uACBD\uB85C"),e.push(`- JSON \uC7A5\uBD80: ${t.documents.ledger}`),e.push(`- \uCDE8\uD569\uBB38\uC11C: ${t.documents.debate}`),e.push(`- \uACB0\uB860\uBB38\uC11C: ${t.documents.synthesis?t.documents.synthesis:"(\uC544\uC9C1 \uC0DD\uC131\uB418\uC9C0 \uC54A\uC74C)"}`),e.join(`
|
|
323
|
+
`)}function zT(t){return t.currentStances.map(e=>`${e.provider} ${Ss[e.stance]}${e.automatic?"(\uC790\uB3D9)":""}`).join(", ")}function Ko(t){if(t.conclusion)return`\uACB0\uB860: ${t.conclusion}`;let e=t.currentStances.filter(r=>r.stance!=="agree"&&r.stance!=="not_assigned");return e.length===0?"\uC544\uC9C1 \uBAA8\uB4E0 \uCC38\uAC00\uC790\uC758 \uBA85\uC2DC \uB3D9\uC758\uAC00 \uBAA8\uC774\uC9C0 \uC54A\uC558\uB2E4.":`\uB9C9\uD78C \uC774\uC720: ${e.map(r=>`${r.provider} ${Ss[r.stance]}`).join(", ")}`}function MT(t){let e=t.currentStances.filter(o=>o.stance==="agree").map(o=>o.provider).join(", ")||"-",r=t.currentStances.filter(o=>o.stance==="disagree").map(o=>o.provider).join(", ")||"-",n=t.currentStances.filter(o=>o.stance==="opinion"||o.stance==="revise").map(o=>`${o.provider} ${Ss[o.stance]}`).join(", ")||"-",s=t.conclusion?t.conclusion:Ko(t);return`| ${t.id} | ${t.title} | ${t.displayStatus} | ${s} | ${t.proposer} | ${e} | ${r} | ${n} |`}function sy(t,e,r){if(e.length===0){t.push(""),t.push("(\uC5C6\uC74C)");return}for(let n of e)if(t.push(""),t.push(`### ${n.id}: ${n.title}`),t.push(""),t.push(`\uBB34\uC5C7\uC744 \uC704\uD55C \uD56D\uBAA9: ${n.plainSummary}`),t.push(""),t.push(`\uCD5C\uC885 \uACB0\uC815: ${W2(n)}`),t.push(`\uB3D9\uC758\uD55C AI: ${DT(n,"agree")}`),t.push(`\uBC18\uB300\uD55C AI: ${DT(n,"disagree")}`),t.push(`\uD604\uC7AC \uC785\uC7A5: ${H2(n)}`),t.push(`\uBCC0\uACBD \uC5EC\uBD80: ${K2(n)}`),t.push(`\uD1A0\uB860/\uADFC\uAC70 \uC704\uCE58: ${J2(n,r)}`),(n.status==="unresolved"||n.status==="needs_opinion")&&(t.push(`\uB9C9\uD78C \uACB0\uC815: ${n.plainSummary}`),t.push("\uD574\uACB0\uD558\uB824\uBA74: \uBC18\uB300/\uC758\uACAC\uC744 \uB0B8 AI\uAC00 \uC694\uAD6C\uD55C \uADFC\uAC70\uB97C \uBCF4\uAC15\uD558\uAC70\uB098 \uC0AC\uC6A9\uC790\uAC00 \uCD5C\uC885 \uBC29\uD5A5\uC744 \uC120\uD0DD\uD574\uC57C \uD55C\uB2E4.")),t.push(`\uACB0\uC815 \uC774\uC720: ${G2(n)}`),n.comments.length>0){t.push(""),t.push("\uC8FC\uC694 \uC758\uACAC:");for(let s of n.comments.slice(-3))t.push(`- ${s.provider}: ${Ss[s.stance]} - ${s.comment}`)}}function W2(t){return t.conclusion?t.conclusion:Ko(t)}function DT(t,e){let r=t.currentStances.filter(n=>n.stance===e).map(n=>`${n.provider}${n.automatic?"(\uC790\uB3D9)":""}`);return r.length>0?r.join(", "):"-"}function H2(t){return t.currentStances.map(e=>`${e.provider} ${Ss[e.stance]}${e.automatic?"(\uC790\uB3D9)":""}`).join(", ")}function K2(t){if(t.parentId)return`${t.parentId}\uC5D0\uC11C \uB098\uC628 \uC218\uC815\uC548\uC774 \uD604\uC7AC \uD56D\uBAA9\uC774\uB2E4.`;let e=t.comments.map(r=>r.proposedItemId).filter(r=>r!==void 0);return e.length>0?`\uC218\uC815 \uC81C\uC548\uC774 ${Array.from(new Set(e)).join(", ")} \uD56D\uBAA9\uC73C\uB85C \uC774\uC5B4\uC84C\uB2E4.`:t.status==="accepted"?"\uC6D0\uC548 \uADF8\uB300\uB85C \uD569\uC758\uB428.":t.status==="excluded"?"\uC6D0\uC548\uC774 \uC81C\uC678 \uD569\uC758\uB85C \uB05D\uB0AC\uB2E4.":"\uC544\uC9C1 \uD655\uC815\uB41C \uBCC0\uACBD\uC548 \uC5C6\uC74C."}function J2(t,e){return Array.from(new Set([e.documents.debate,...t.sourceRefs])).join(", ")}function G2(t){return t.comments.length>0?t.comments.slice(-3).map(e=>`${e.provider}: ${Ss[e.stance]} - ${e.comment}`).join(" / "):t.status==="accepted"?"\uD65C\uC131 \uCC38\uAC00\uC790\uC758 \uC785\uC7A5\uC774 \uBAA8\uB450 \uB3D9\uC758\uB85C \uBAA8\uC600\uB2E4.":t.status==="excluded"?"\uD65C\uC131 \uCC38\uAC00\uC790\uC758 \uC785\uC7A5\uC774 \uBAA8\uB450 \uBC18\uB300\uB85C \uBAA8\uC5EC \uC81C\uC678\uD558\uAE30\uB85C \uD588\uB2E4.":Ko(t)}function Y2(t,e){let r=t.items.filter(a=>a.proposer===e).length,n=t.items.filter(a=>a.proposer===e&&a.status==="accepted").length,s=t.items.filter(a=>a.status==="excluded"&&a.currentStances.some(c=>c.provider===e&&c.stance==="disagree")).length,o=t.items.filter(a=>a.currentStances.some(c=>c.provider===e&&(c.stance==="disagree"||c.stance==="opinion"||c.stance==="revise"))).length,i=r>0?"\uC81C\uC548 \uAE30\uC5EC":"\uAC80\uD1A0 \uAE30\uC5EC";return`| ${e} | ${r} | ${n} | ${s} | ${o} | ${i} |`}function iy(t,e){let r;try{r=JSON.parse(t)}catch{return{ok:!1,errors:["Response must be valid JSON."]}}let n=vT.safeParse(r);if(!n.success)return{ok:!1,errors:_T(n.error)};let s=[],o=n.data;o.provider!==e.provider&&s.push(`provider mismatch: expected ${e.provider}, got ${o.provider}`),o.round!==e.round&&s.push(`round mismatch: expected ${e.round}, got ${o.round}`);let i=new Set(e.assignedItemIds),a=new Set;for(let c of o.items)i.has(c.id)||s.push(`unassigned item id: ${c.id}`),a.has(c.id)&&s.push(`duplicate item id: ${c.id}`),a.add(c.id),(c.stance==="disagree"||c.stance==="opinion"||c.stance==="revise")&&c.comment.trim().length===0&&s.push(`comment is required for ${c.stance} on ${c.id}`),c.stance==="revise"&&c.proposedItem===void 0&&s.push(`proposedItem is required for revise on ${c.id}`);for(let c of i)a.has(c)||s.push(`missing assigned item id: ${c}`);return s.length>0?{ok:!1,errors:s}:{ok:!0,value:o}}import{existsSync as X2,mkdirSync as Q2,readFileSync as e4}from"fs";import{join as NT}from"path";var zt=class{debatesDir;constructor(e){this.debatesDir=NT(e,Is)}pathForSession(e){return NT(this.debatesDir,`${e}.consensus.json`)}async write(e){Q2(this.debatesDir,{recursive:!0});let r=this.pathForSession(e.sessionId),n={...e,documents:{...e.documents,ledger:r}};return Ze(r,n),r}async load(e){let r=this.pathForSession(e);return X2(r)?JSON.parse(e4(r,"utf-8")):null}};async function ay(t,e){for(;t.rounds<t.maxRounds;){if(t.consensusLedger.items.filter(o=>o.status==="unresolved"||o.status==="needs_opinion").length===0)return;t.rounds+=1;let n=t.rounds;t.phase="consensus-round";let s=new Set;for(let o of t.config.participants){if(t.unavailableParticipants.has(o))continue;let i=t.consensusLedger.items.filter(d=>d.status==="unresolved"||d.status==="needs_opinion").length,a=IT(t.consensusLedger,{provider:o,round:n,maxItems:10});if(a.assignedItems.length===0)continue;t.consensusLedger=RT(t.consensusLedger,{round:n,provider:o,assignedItemIds:a.assignedItems.map(d=>d.id),totalActiveItems:i,maxItems:10,now:e.nowIso}),await $s(t,e);let c={prompt:ST(a,t.legacyProposalIdMap),round:n,timeoutMs:t.participantTimeoutMs??18e4,...e.createActivitySink!==void 0?{activity:e.createActivitySink(t,o,"consensus-round",n)}:{},...t.files.length>0?{files:t.files}:{}};await e.setCurrentProvider?.(t,o),await e.markParticipantProgress?.(t,o,{status:"running",phase:"consensus-round",round:n,startedAt:e.nowIso(),lastActivityAt:e.nowIso(),lastEvent:`round ${n} turn started`});let u=await e.bridge.requestTurn(o,c);if(u.failed){jT(t,o,e.nowIso),await e.markParticipantProgress?.(t,o,{status:"failed",phase:"consensus-round",round:n,completedAt:e.nowIso(),lastActivityAt:e.nowIso(),lastEvent:`round ${n} turn failed`,latencyMs:u.latencyMs,failureReason:u.failureReason??"provider failed"}),t.consensusLedger=cd(t.consensusLedger,{provider:o,round:n,assignedItemIds:a.assignedItems.map(d=>d.id),rawResponse:"",parsedItems:[],validationErrors:[u.failureReason?u.failureReason:"provider failed"]}),await $s(t,e);continue}s.add(o),n4(t,o);let l=await t4(o,a,u.text,c,t.legacyProposalIdMap,e);l.ok?(await e.markParticipantProgress?.(t,o,{status:"completed",phase:"consensus-round",round:n,completedAt:e.nowIso(),lastActivityAt:e.nowIso(),lastEvent:`round ${n} turn accepted`,latencyMs:u.latencyMs}),t.consensusLedger=cd(t.consensusLedger,{provider:o,round:n,assignedItemIds:a.assignedItems.map(d=>d.id),rawResponse:l.rawResponse,parsedItems:l.items})):(jT(t,o,e.nowIso),await e.markParticipantProgress?.(t,o,{status:"format-error",phase:"consensus-round",round:n,completedAt:e.nowIso(),lastActivityAt:e.nowIso(),lastEvent:`round ${n} turn rejected by JSON contract`,latencyMs:u.latencyMs,failureReason:l.errors.join("; ")}),t.consensusLedger=cd(t.consensusLedger,{provider:o,round:n,assignedItemIds:a.assignedItems.map(d=>d.id),rawResponse:l.rawResponse,parsedItems:[],validationErrors:l.errors})),r4(t),await $s(t,e)}if(await e.setCurrentProvider?.(t,void 0),s.size===0)return}}async function t4(t,e,r,n,s,o){let i=e.assignedItems.map(l=>l.id),a=iy(r,{provider:t,round:e.round,assignedItemIds:i});if(a.ok)return{ok:!0,rawResponse:r,items:a.value.items};let c=await o.bridge.requestTurn(t,{prompt:$T(e,a.errors,s),round:e.round,timeoutMs:n.timeoutMs,...n.activity!==void 0?{activity:n.activity}:{},...n.files!==void 0?{files:n.files}:{}});if(c.failed)return{ok:!1,rawResponse:r,errors:[...a.errors,`retry failed: ${c.failureReason??"unknown"}`]};let u=iy(c.text,{provider:t,round:e.round,assignedItemIds:i});return u.ok?{ok:!0,rawResponse:c.text,items:u.value.items}:{ok:!1,rawResponse:c.text,errors:u.errors}}async function $s(t,e){let r=new zt(e.registry.getWorkspaceDir());t.consensusLedgerPath=await r.write(t.consensusLedger),t.consensusLedger={...t.consensusLedger,documents:{...t.consensusLedger.documents,individual:{...t.individualPaths},ledger:t.consensusLedgerPath,debate:t.debateDocPath}},await e.documentManager.replaceDocumentContent(t.debateDocId,ud(t.consensusLedger))}function r4(t){for(let e of t.consensusLedger.items){if(Array.from(t.legacyProposalIdMap.values()).includes(e.id))continue;let n=`P${t.legacyProposalIdMap.size+1}`;t.legacyProposalIdMap.set(n,e.id),e.sourceRefs.includes(n)||e.sourceRefs.unshift(n)}}function cy(t){for(let e of t.ledger.proposals.values()){if(e.status!=="merged"||!e.mergedInto)continue;let r=t.legacyProposalIdMap.get(e.id),n=t.legacyProposalIdMap.get(e.mergedInto);if(!r||!n)continue;let s=t.consensusLedger.items.find(o=>o.id===r);s&&(s.status="superseded",s.displayStatus="\uB300\uCCB4\uC548\uC73C\uB85C \uC774\uB3D9",s.conclusion=`\uB300\uCCB4\uC548\uC73C\uB85C \uC774\uB3D9. ${n} \uD56D\uBAA9\uACFC \uAC19\uC740 \uB0B4\uC6A9\uC73C\uB85C \uBCD1\uD569\uD588\uB2E4.`,s.sourceRefs=Array.from(new Set([...s.sourceRefs,n])))}}function jT(t,e,r){let n=(t.consecutiveFailures.get(e)??0)+1;t.consecutiveFailures.set(e,n),n>=Id&&(t.unavailableParticipants.add(e),t.consensusLedger={...t.consensusLedger,activeParticipants:t.consensusLedger.activeParticipants.filter(s=>s!==e),moderatorNotes:[...t.consensusLedger.moderatorNotes,{id:`NOTE-${t.consensusLedger.moderatorNotes.length+1}`,kind:"provider_unavailable",round:t.rounds,provider:e,message:`${e} marked unavailable after repeated failed turns.`,createdAt:r()}]})}function n4(t,e){t.consecutiveFailures.delete(e)}function uy(t){if(t.consensusLedger.items.length>0)return t.consensusLedger.items.some(r=>r.status==="unresolved"||r.status==="needs_opinion")?"escalated":"ready-for-approval";for(let e of t.ledger.proposals.values())if(e.status==="open")return"escalated";return"ready-for-approval"}function LT(t){return t==="ready-for-approval"||t==="escalated"}function qT(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 FT(t){switch(t){case"accepted":return"accepted";case"excluded":return"rejected";case"superseded":return"superseded";case"needs_opinion":return"inconclusive";case"unresolved":return"open"}}function UT(t,e){for(let[r,n]of t)if(n===e)return r;return e}function ZT(t){switch(t){case"agree":return"agree";case"disagree":return"disagree";case"revise":return"revise";case"opinion":return"abstain";case"no_response":case"not_assigned":return"missing"}}function ly(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 Xa(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"<unstringifiable error>"}}function xs(t){let e=t.documentPaths.debate;return(e.split(/[\\/]/).pop()??e).replace(/\.md$/,"")}var s4=Object.freeze(["same","different","unsure"]),Qa="alias-votes",o4=new Set(s4);function i4(t){return o4.has(t)}function a4(t){let e=`<${Qa}>`,r=`</${Qa}>`,n=t.lastIndexOf(r);if(n<0)return null;let s=t.lastIndexOf(e,n);return s<0?null:{inner:t.slice(s+e.length,n)}}function c4(t){let e=`<${Qa}>`;return t.includes(e)}var u4=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function l4(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 s=parseInt(r.slice(2),16);return Number.isFinite(s)?String.fromCodePoint(s):e}if(r.startsWith("#")){let s=parseInt(r.slice(1),10);return Number.isFinite(s)?String.fromCodePoint(s):e}return u4[r]??e})}function d4(t){let e={},r=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,n=0,s;for(;(s=r.exec(t))!==null;){if(t.slice(n,s.index).trim().length>0)return null;let i=s[1],a=s[2],c=s[3],u=a!==void 0?a:c??"";if(Object.prototype.hasOwnProperty.call(e,i))return null;e[i]=l4(u),n=s.index+s[0].length}return t.slice(n).trim().length>0?null:e}function VT(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}function dy(t,e){let r=a4(t);if(!r)return c4(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${Qa}> without matching </${Qa}>`}}:{ok:!1,error:{kind:"missing-block"}};let n=new Set(e),s=/<item\b([^>]*?)\/>/g,o=[],i;for(;(i=s.exec(r.inner))!==null;)o.push({raw:i[0],attrString:i[1],index:i.index,length:i[0].length});let a=0;for(let p of o){let f=r.inner.slice(a,p.index);if(!VT(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(!VT(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 o){let f=d4(p.attrString);if(f===null){l.push({reason:"malformed-entry",raw:p.raw});continue}let m=f.pair,h=f.vote;if(typeof m!="string"||m.length===0||typeof h!="string"){l.push({pair:typeof m=="string"&&m.length>0?m:void 0,reason:"malformed-entry",raw:p.raw});continue}if(!i4(h)){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 v=f.reason,g=typeof v=="string"&&v.length>0?v:void 0;d.add(m);let b={pair:m,vote:h};g!==void 0&&(b.reason=g),u.push(b)}return{ok:!0,entries:u,entryErrors:l}}var p4="__";function f4(t){return`${t.proposalA}${p4}${t.proposalB}`}var m4=["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(" "),h4=["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(" "),g4=["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(`
|
|
324
|
+
`),y4="Candidate pairs:";function v4(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(`
|
|
325
|
+
`)}async function JT(t){let{ledger:e,participantIds:r,askParticipant:n}=t,s=e.aliasCandidates;if(s.length===0)return{mergesApplied:[],undecided:[],parseFailures:[]};let o=s.map(f4),i=new Map;for(let f=0;f<s.length;f+=1)i.set(o[f],s[f]);let a=_4(e,s,o),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 o)l.set(f,{same:0,different:0,unsure:0,missing:0});for(let f=0;f<c.length;f+=1){let m=c[f],h=r[f];if(m.status==="rejected"){u.push({participantId:h,reason:KT(m.reason)}),ld(l,o);continue}let{response:v}=m.value;if(v.failed===!0){u.push({participantId:h,reason:"askParticipant reported failed=true"}),ld(l,o);continue}let g=dy(v.text,o),b=new Set;if(!g.ok){let _=await n(h,v4(o,g.error.details!==void 0?`${g.error.kind}: ${g.error.details}`:g.error.kind)).catch(x=>({text:"",failed:!0,reason:KT(x)}));if(_.failed===!0){u.push({participantId:h,reason:"reason"in _&&typeof _.reason=="string"?_.reason:"retry failed"}),ld(l,o);continue}let P=dy(_.text,o);if(!P.ok){u.push({participantId:h,reason:P.error.details!==void 0?`${P.error.kind}: ${P.error.details}`:P.error.kind}),ld(l,o);continue}for(let x of P.entries)HT(l,x),b.add(x.pair);for(let x of o)if(!b.has(x)){let j=l.get(x);j!==void 0&&(j.missing+=1)}continue}for(let _ of g.entries)HT(l,_),b.add(_.pair);for(let _ of o)if(!b.has(_)){let P=l.get(_);P!==void 0&&(P.missing+=1)}}let d=[],p=[];for(let f of o){let m=i.get(f),h=l.get(f);if(m===void 0||h===void 0)continue;let v=w4(h);if(v.kind==="merge"){let g=m.proposalA,b=m.proposalB;if(e.proposals.get(g)===void 0||e.proposals.get(b)===void 0)continue;e.applyAliasMerge(g,b),d.push({primary:g,alias:b,voteBreakdown:{...h}});continue}p.push({pair:m,voteBreakdown:{...h},reason:v.reason})}return{mergesApplied:d,undecided:p,parseFailures:u}}function _4(t,e,r){let n=[];n.push(m4),n.push(""),n.push(h4),n.push(""),n.push(y4),n.push("");for(let s=0;s<e.length;s+=1){let o=e[s],i=r[s],a=t.proposals.get(o.proposalA),c=t.proposals.get(o.proposalB);n.push(`Pair ${s+1} \u2014 pair="${i}"`),n.push(` matched fields: ${o.matchedFields.join(", ")||"(none)"}`),n.push(` blocking field: ${o.missingField}`),n.push(" Proposal A:"),BT(n,a),n.push(" Proposal B:"),BT(n,c),n.push("")}return n.push(g4),n.join(`
|
|
326
|
+
`)}function BT(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=b4(e.description);t.push(` description: ${r}`)}}var WT=400;function b4(t){return t.length<=WT?t:`${t.slice(0,WT)}\u2026`}function HT(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 ld(t,e){for(let r of e){let n=t.get(r);n!==void 0&&(n.missing+=1)}}function w4(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 KT(t){if(t instanceof Error)return`askParticipant threw: ${t.message}`;try{return`askParticipant threw: ${String(t)}`}catch{return"askParticipant threw: <unstringifiable>"}}import{readdir as S4}from"fs/promises";import{readFileSync as $4,existsSync as dd,unlinkSync as x4,mkdirSync as P4}from"fs";import{join as Ps}from"path";var fy=".session.json",pd=".approval.json";function py(t){return`${t}${fy}`}function k4(t){return t.endsWith(fy)?{sessionId:t.slice(0,t.length-fy.length),legacy:!1}:t.endsWith(pd)?{sessionId:t.slice(0,t.length-pd.length),legacy:!0}:null}function GT(t){let e=Date.parse(t);if(Number.isNaN(e))throw new Error(`computeApprovalDeadline: invalid readyAt ISO string: ${t}`);return new Date(e+Xy).toISOString()}var Jo=class{constructor(e){this.workspaceDir=e;if(!e||typeof e!="string")throw new Error("StructuredSessionRegistry: baseDir is required");this.debatesDir=Ps(e,Is)}workspaceDir;debatesDir;cache=new Map;hydrated=!1;getWorkspaceDir(){return this.workspaceDir}getDebatesDir(){return this.debatesDir}async persist(e){if(!e||!e.sessionId)throw new Error("StructuredSessionRegistry.persist: snapshot.sessionId is required");if(e.schemaVersion!==2)throw new Error(`StructuredSessionRegistry.persist: unsupported schemaVersion=${e.schemaVersion}`);P4(this.debatesDir,{recursive:!0});let r=Ps(this.debatesDir,py(e.sessionId));Ze(r,e),this.cache.set(e.sessionId,e)}async load(e){let r=this.cache.get(e);if(r)return r;let n=Ps(this.debatesDir,py(e));if(!dd(n)){let o=Ps(this.debatesDir,`${e}${pd}`);if(!dd(o))return null;let i=this.readSnapshotFile(o);return i&&this.cache.set(e,i),i}let s=this.readSnapshotFile(n);return s&&this.cache.set(e,s),s}async remove(e){this.cache.delete(e);for(let r of[Ps(this.debatesDir,py(e)),Ps(this.debatesDir,`${e}${pd}`)])if(dd(r))try{x4(r)}catch(n){if(n.code!=="ENOENT")throw n}}async update(e,r){let n=await this.load(e);if(!n)throw new Error(`StructuredSessionRegistry.update: session not found: ${e}`);let s=r(n);return await this.persist(s),s}async hydrateFromDisk(){if(this.cache.clear(),!dd(this.debatesDir)){this.hydrated=!0;return}let e;try{e=await S4(this.debatesDir)}catch(r){if(r.code==="ENOENT"){this.hydrated=!0;return}throw r}for(let r of e){let n=k4(r);if(!n)continue;let s=this.readSnapshotFile(Ps(this.debatesDir,r));s&&s.sessionId===n.sessionId&&this.cache.set(n.sessionId,s)}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=[],s=[];for(let o of this.cache.values()){if(o.status!=="ready-for-approval")continue;let i=Date.parse(o.deadline);if(Number.isNaN(i)||r<=i)continue;let a={...o,status:"leader-timeout",phase:"terminal",updatedAt:e.toISOString(),terminalNote:o.terminalNote??"leader-timeout after approval window",summary:{...o.summary,terminalNote:o.summary.terminalNote??"leader-timeout after approval window"}};try{await this.persist(a),n.push(a)}catch(c){s.push({sessionId:o.sessionId,error:c})}}return s.length>0&&console.warn(`[session-registry] sweepTimeouts: ${s.length} snapshot(s) failed to transition; will retry on next sweep`,s.map(o=>({sessionId:o.sessionId,message:o.error instanceof Error?o.error.message:String(o.error)}))),n}isHydrated(){return this.hydrated}readSnapshotFile(e){let r;try{r=$4(e,"utf-8")}catch(s){if(s.code==="ENOENT")return null;throw s}let n;try{n=JSON.parse(r)}catch{return console.warn(`[session-registry] skipping unparseable snapshot file: ${e}`),null}return E4(n)?n:T4(n)?I4(n):(console.warn(`[session-registry] skipping snapshot with unexpected shape: ${e}`),null)}};function E4(t){if(!t||typeof t!="object")return!1;let e=t;return e.schemaVersion===2&&typeof e.sessionId=="string"&&typeof e.status=="string"&&typeof e.phase=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"&&typeof e.readyAt=="string"&&typeof e.deadline=="string"&&typeof e.config=="object"&&e.config!==null&&typeof e.rounds=="number"&&typeof e.progress=="object"&&e.progress!==null&&typeof e.summary=="object"&&e.summary!==null&&Array.isArray(e.aggregatedVotes)&&typeof e.documentPaths=="object"&&e.documentPaths!==null}function T4(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 I4(t){let e=t.config.participants,r=R4(t.status),n=t.aggregatedVotes.length,s=t.aggregatedVotes.filter(o=>o.status!=="open"&&o.status!=="inconclusive").length;return{...t,schemaVersion:2,phase:r?"terminal":"approval-gate",updatedAt:t.readyAt,progress:{round:t.rounds,maxRounds:t.config.maxRounds,participants:Object.fromEntries(e.map(o=>[o,{participantId:o,status:"completed",phase:r?"terminal":"approval-gate",round:t.rounds}]))},summary:{totalItems:n,resolvedItems:s,openItems:n-s,...t.terminalNote!==void 0?{terminalNote:t.terminalNote}:{}}}}function R4(t){return t==="approved"||t==="rejected"||t==="leader-timeout"||t==="error"}function A4(t,e){let r=[];r.push(...O4(t,e)),r.push(""),r.push(...XT(t,e));let n=QT(t,e);return n.length>0&&(r.push(""),r.push(...n)),r.push(""),r.push(...eI(t,e)),r.push(""),r.push(...M4(t,e)),r.join(`
|
|
327
|
+
`)}function C4(t,e){let r=[];r.push(...XT(t,e));let n=N4(t,e);n.length>0&&(r.push(""),r.push(...n));let s=j4(t,e);s.length>0&&(r.push(""),r.push(...s));let o=L4(t,e);o.length>0&&(r.push(""),r.push(...o));let i=QT(t,e);return i.length>0&&(r.push(""),r.push(...i)),r.push(""),r.push(...eI(t,e)),r.join(`
|
|
328
|
+
`)}function YT(){return{renderTerminal:A4,renderSynthesis:C4}}var D4=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 O4(t,e){let r=e.t(D4[t.status]),n=e.t("report.header.topic"),s=e.t("report.header.participants"),o=e.t("report.header.individualDocs"),i=[`## ${n}: ${t.topic} (${t.rounds}/${t.maxRounds} \u2014 ${r})`,`## ${s}: ${t.participantIds.join(", ")}`,`## ${o}:`],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 XT(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 s=n.proposerIds.join(", "),o=z4(n);r.push(`| ${s} | ${n.title} | ${n.severity} | ${o} |`)}return r}function z4(t){let e=`${t.agreeCount}/${t.totalVoters}`;return t.accepted||t.dissentSummary===void 0||t.dissentSummary.length===0?e:`${e} (${t.dissentSummary})`}function QT(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 s of n.perParticipant)r.push(my(s))}return r}function my(t){let e=`- **${t.participantId}:** ${t.vote}`;return t.reason===void 0||t.reason.length===0?e:`${e} \u2014 ${t.reason}`}function eI(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 s of t.contributionSummary){let o=s.proposed===0?"\u2014":String(s.consensusReceived);n.push(`| ${s.participantId} | ${s.proposed} | ${o} | ${s.revisesProposed} | ${s.abstains} |`)}return n}function M4(t,e){let r=e.t("report.footer.synthesisPath"),n=e.t("report.footer.debatePath"),s=t.synthesisPath??e.t("report.footer.pendingSynthesis"),o=[`## ${r}: ${s}`,`## ${n}: ${t.debatePath}`];return t.status==="ready-for-approval"&&(o.push(""),o.push(e.t("approval.pending"))),o}function N4(t,e){let r=t.acceptedItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.acceptedItems")}`];for(let s of r)n.push(""),n.push(`### ${s.id} \u2014 ${s.title}`),n.push(`**${e.t("report.table.severity")}:** ${s.severity}`),n.push(`**${e.t("report.table.proposer")}:** ${s.proposerIds.join(", ")}`),n.push(`**${e.t("report.table.agreement")}:** ${s.agreeCount}/${s.totalVoters}`),s.finalStatement.length>0&&(n.push(""),n.push(s.finalStatement));return n}function j4(t,e){let r=t.rejectedItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.rejectedItems")}`];for(let s of r){n.push(""),n.push(`### ${s.id} \u2014 ${s.title}`),n.push(`**${e.t("report.table.severity")}:** ${s.severity}`),s.rejectionReason.length>0&&(n.push(""),n.push(s.rejectionReason));for(let o of s.dissentVotes)n.push(my(o))}return n}function L4(t,e){let r=t.openItems??[];if(r.length===0)return[];let n=[`## ${e.t("synthesis.section.openItems")}`];for(let s of r){n.push(""),n.push(`### ${s.id} \u2014 ${s.title}`),n.push(`**${e.t("report.table.severity")}:** ${s.severity}`),n.push(`**${e.t("report.table.agreement")}:** ${s.agreeCount}/${s.totalVoters}`);for(let o of s.perParticipant)n.push(my(o))}return n}var Go=class{deps;sessions=new Map;backgroundRuns=new Map;formatter=YT();constructor(e){this.deps=e}waitForSessionForTests(e){return this.backgroundRuns.get(e)??Promise.resolve()}scheduleBackgroundRun(e,r){let n=new Promise(s=>{setImmediate(()=>{r().catch(async o=>{let i=this.sessions.get(e);i&&(i.phase="terminal",await this.deps.registry.persist(this.buildSnapshot(i,"error",Xa(o))))}).finally(s)})}).finally(()=>{this.backgroundRuns.delete(e)});this.backgroundRuns.set(e,n)}async startDebate(e){let r=(this.deps.generateSessionId??F4)(),n=this.nowIso(),s=e.mode??"review",o=uT({topic:e.topic,...e.goal!==void 0?{goal:e.goal}:{},participants:e.participants,excludeParticipants:e.excludeParticipants??[],autoInjectSpecialists:e.autoInjectSpecialists??!0}),i=o.participants,a={topic:e.topic,scope:e.scope??e.topic,participants:i,excludeParticipants:e.excludeParticipants??[],leader:e.leader,maxRounds:e.maxRounds??Td,locale:e.locale??this.deps.i18n.locale,autoInjectSpecialists:e.autoInjectSpecialists??!0,...e.participantTimeoutMs!==void 0?{participantTimeoutMs:e.participantTimeoutMs}:{}},c=await this.deps.documentManager.createDebateDocument({topic:e.topic,providers:i.slice(),...e.goal!==void 0?{goal:e.goal}:{}}),l=new zt(this.deps.registry.getWorkspaceDir()).pathForSession(r),d=ad({sessionId:r,topic:e.topic,mode:s,participants:i.slice(),leader:e.leader,maxRounds:a.maxRounds,documents:{individual:{},ledger:l,debate:c.path},items:[],now:()=>n}),p={sessionId:r,mode:s,config:a,goal:e.goal,individualReviewPrompt:e.individualReviewPrompt,files:e.files??[],sourceDocuments:e.sourceDocuments??[],debateDocId:c.id,debateDocPath:c.path,individualPaths:{},createdAt:n,ledger:new Pn,rounds:0,maxRounds:a.maxRounds,consecutiveFailures:new Map,unavailableParticipants:new Set,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:1,consensusLedger:d,consensusLedgerPath:l,legacyProposalIdMap:new Map,phase:"starting",...e.participantTimeoutMs!==void 0?{participantTimeoutMs:e.participantTimeoutMs}:{},participantProgress:new Map(i.map(m=>[m,{participantId:m,status:"pending"}]))};this.sessions.set(r,p);let f=async()=>{try{let m=p.sourceDocuments.length>0?await this.loadSourceDocumentPhase(p):await this.runIndividualPhase(p,o);if(p.consensusLedger=ad({sessionId:r,topic:e.topic,mode:s,participants:i.slice(),leader:e.leader,maxRounds:a.maxRounds,documents:{individual:{...p.individualPaths},ledger:p.consensusLedgerPath,debate:p.debateDocPath},items:m.map(g=>({title:g.title,proposer:g.proposerId,plainSummary:g.description??g.title,originalClaim:g.description??g.title,sourceRefs:[g.id,...p.individualPaths[g.proposerId]!==void 0?[p.individualPaths[g.proposerId]]:[],...g.location!==void 0?[g.location]:[]]}))}),p.legacyProposalIdMap=new Map(m.map((g,b)=>[g.id,p.consensusLedger.items[b]?.id??g.id])),await $s(p,this.consensusFlowDeps()),m.length===0){let g="No proposals were extracted from individual source material.";await this.deps.documentManager.addComment(p.debateDocId,{author:"Moderator",content:g}),p.phase="terminal";let b=this.buildSnapshot(p,"error",g);return await this.deps.registry.persist(b),this.emitTrace(p,"debate_no_proposals",{status:b.status}),{sessionId:r,status:b.status,snapshot:b,terminalReport:this.renderTerminal(p,b),errorMessage:g}}let{ledger:h}=yT(m);p.ledger=h,p.nextProposalIndex=W4(m),cy(p),h.aliasCandidates.length>0&&await this.runAliasClarificationPhase(p),await ay(p,this.consensusFlowDeps()),p.phase="approval-gate",delete p.currentProvider,p.consensusLedger=rI(p.consensusLedger),await $s(p,this.consensusFlowDeps());let v=this.buildSnapshot(p,uy({consensusLedger:p.consensusLedger,ledger:p.ledger}));return await this.deps.registry.persist(v),this.emitTrace(p,"debate_rfa",{status:v.status}),{sessionId:r,status:v.status,snapshot:v,terminalReport:this.renderTerminal(p,v)}}catch(m){p.phase="terminal";let h=this.buildSnapshot(p,"error",Xa(m));try{await this.deps.registry.persist(h)}catch{}return this.emitTrace(p,"debate_error",{error:Xa(m)}),{sessionId:r,status:"error",snapshot:h,terminalReport:this.renderTerminal(p,h),errorMessage:Xa(m)}}};if(e.background===!0){let m=this.buildSnapshot(p,"running");return await this.deps.registry.persist(m),this.scheduleBackgroundRun(r,async()=>{await f()}),{sessionId:r,status:"running",snapshot:m,terminalReport:["Structured debate session started.",`Session ID: ${r}`,"Status: running","Use agent_debate_status to monitor progress."].join(`
|
|
329
|
+
`)}}return f()}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}}hy(r,["ready-for-approval","escalated"],"approve");let n=this.sessions.get(e.sessionId),s=n?.consensusLedger;!s&&r.documentPaths.consensusLedger&&(s=await new zt(this.deps.registry.getWorkspaceDir()).load(r.sessionId)??void 0);let o=s?oy({...s,documents:{...s.documents,...r.documentPaths.synthesis!==void 0?{synthesis:r.documentPaths.synthesis}:{}}}):this.formatter.renderSynthesis(n?this.buildReportData(n,r,e.leaderNote):nI(r,e.leaderNote),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:o,...e.leaderNote!==void 0?{metadata:{"Leader Note":e.leaderNote}}:{}}),c={...r,status:"approved",phase:"terminal",updatedAt:this.nowIso(),summary:{...r.summary,...e.leaderNote!==void 0?{terminalNote:e.leaderNote}:{}},documentPaths:{...r.documentPaths,synthesis:a.path}};if(s){let u={...s,documents:{...s.documents,synthesis:a.path},moderatorNotes:e.leaderNote!==void 0?[...s.moderatorNotes,{id:`NOTE-${s.moderatorNotes.length+1}`,kind:"format_correction",round:s.round,provider:r.config.leader,message:`Leader note: ${e.leaderNote}`,createdAt:this.nowIso()}]:s.moderatorNotes},l=oy(u);await this.deps.documentManager.replaceSynthesis({synthesisId:a.id,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:l,...e.leaderNote!==void 0?{metadata:{"Leader Note":e.leaderNote}}:{}}),await new zt(this.deps.registry.getWorkspaceDir()).write(u),n&&(n.consensusLedger=u,n.consensusLedgerPath=u.documents.ledger),await this.deps.documentManager.replaceDocumentContent(n?.debateDocId??xs(r),ud(u))}else await this.deps.documentManager.addComment(n?.debateDocId??xs(r),{author:"moderator",content:this.formatApprovalFooter(e.leaderNote)});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);if(r.status==="running")throw new Error(`continue: session "${e.sessionId}" is already running.`);hy(r,["ready-for-approval","escalated"],"continue");let n=this.sessions.get(e.sessionId);if(!n)if(r.documentPaths.consensusLedger)n=await this.rehydrateConsensusSessionContext(r),this.sessions.set(e.sessionId,n);else if(r.ledgerState)n=this.rehydrateSessionContext(r),this.sessions.set(e.sessionId,n);else 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.maxRounds=r.config.maxRounds+e.additionalRounds,n.phase="consensus-round",n.consensusLedger={...n.consensusLedger,maxRounds:n.maxRounds};for(let i of n.ledger.proposals.values())i.status;let s=async()=>{await ay(n,this.consensusFlowDeps());let i=uy({consensusLedger:n.consensusLedger,ledger:n.ledger});n.phase="approval-gate",delete n.currentProvider,n.consensusLedger=rI(n.consensusLedger),await $s(n,this.consensusFlowDeps());let a=this.buildSnapshot(n,i);return await this.deps.registry.persist(a),this.emitTrace(n,"debate_continued",{additionalRounds:e.additionalRounds,status:a.status}),a};if(e.background===!0){let i=this.buildSnapshot(n,"running");return await this.deps.registry.persist(i),this.scheduleBackgroundRun(e.sessionId,async()=>{await s()}),{snapshot:i,terminalReport:["Structured debate session continued.",`Session ID: ${e.sessionId}`,"Status: running","Use agent_debate_status to monitor progress."].join(`
|
|
330
|
+
`)}}let o=await s();return{snapshot:o,terminalReport:this.renderTerminal(n,o)}}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}:{}};hy(r,["ready-for-approval","escalated","leader-timeout"],"reject");let n=this.sessions.get(e.sessionId),s=n?.debateDocId??xs(r);await this.deps.documentManager.addComment(s,{author:"moderator",content:this.formatRejectionFooter(e.reason)});let o;e.spawnIssue===!0&&(o=(await this.deps.documentManager.createIssueDocument({sessionId:r.sessionId,topic:r.config.topic,...e.reason!==void 0?{reason:e.reason}:{},items:B4(r)})).path);let i={...r,status:"rejected",phase:"terminal",updatedAt:this.nowIso(),terminalNote:e.reason??r.terminalNote,summary:{...r.summary,terminalNote:e.reason??r.summary.terminalNote??r.terminalNote},documentPaths:{...r.documentPaths,...o!==void 0?{issue:o}:{}}};return await this.deps.registry.persist(i),this.emitTrace(n??null,"debate_rejected",{sessionId:r.sessionId,...o!==void 0?{issuePath:o}:{}}),{snapshot:i,...o!==void 0?{issuePath:o}:{}}}async handleTimedOutSnapshots(e){for(let r of e){if(r.status!=="leader-timeout")continue;let n=xs(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 loadSourceDocumentPhase(e){e.phase="individual-review",await this.persistRunningSnapshot(e);let r=[];for(let n of e.sourceDocuments){if(!e.config.participants.includes(n.provider))throw new Error(`source document provider "${n.provider}" is not in participants: ${e.config.participants.join(", ")}`);let s=await this.deps.documentManager.read(n.documentId);e.individualPaths[n.provider]=s.path,await this.markParticipantProgress(e,n.provider,{status:"completed",phase:"individual-review",round:0,completedAt:this.nowIso(),lastActivityAt:this.nowIso(),lastEvent:`loaded source document ${n.documentId}`});let o=ry(s.content);for(let i of o){let a=tI(e,i.id);r.push({id:a,proposerId:n.provider,title:i.title,severity:i.severity,...i.location!==void 0?{location:i.location}:{},...i.description!==void 0?{description:i.description}:{},roundOpened:1})}}return r}async runIndividualPhase(e,r){e.phase="individual-review",await this.persistRunningSnapshot(e);let n=bT(e.mode),s=wT({mode:e.mode,topic:e.config.topic,scope:e.config.scope,goal:e.goal,files:e.files,individualReviewPrompt:e.individualReviewPrompt}),o=await Promise.allSettled(e.config.participants.map(async a=>{await this.markParticipantProgress(e,a,{status:"running",phase:"individual-review",round:0,startedAt:this.nowIso(),lastActivityAt:this.nowIso(),lastEvent:"individual review started"});let c=await this.deps.bridge.requestTurn(a,{prompt:s,system:n,round:0,timeoutMs:e.participantTimeoutMs??18e4,activity:this.createParticipantActivitySink(e,a,"individual-review",0),...e.files.length>0?{files:e.files}:{}});return{participantId:a,resp:c}})),i=[];for(let a of o){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){await this.markParticipantProgress(e,c,{status:"failed",phase:"individual-review",round:0,completedAt:this.nowIso(),lastActivityAt:this.nowIso(),lastEvent:"individual review failed",latencyMs:u.latencyMs,failureReason:u.failureReason??"provider failed"});continue}await this.markParticipantProgress(e,c,{status:"completed",phase:"individual-review",round:0,completedAt:this.nowIso(),lastActivityAt:this.nowIso(),lastEvent:"individual review completed",latencyMs:u.latencyMs});let p=ry(u.text);for(let f of p){let m=tI(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 JT({ledger:e.ledger,participantIds:e.config.participants,askParticipant:async(s,o)=>{let i=await this.deps.bridge.requestTurn(s,{prompt:o,round:0,timeoutMs:e.participantTimeoutMs??18e4,...e.files.length>0?{files:e.files}:{}});return i.failed?{text:"",failed:!0}:{text:i.text}}}),n=kT(r,this.deps.i18n);if(n.length>0){for(let s of r.mergesApplied){let o=e.legacyProposalIdMap.get(s.alias),i=e.legacyProposalIdMap.get(s.primary);if(!o||!i)continue;let a=e.consensusLedger.items.find(c=>c.id===o);a&&(a.status="superseded",a.displayStatus="\uB300\uCCB4\uC548\uC73C\uB85C \uC774\uB3D9",a.conclusion=`\uB300\uCCB4\uC548\uC73C\uB85C \uC774\uB3D9. ${i} \uD56D\uBAA9\uACFC \uAC19\uC740 \uB0B4\uC6A9\uC73C\uB85C \uBCD1\uD569\uD588\uB2E4.`,a.sourceRefs=Array.from(new Set([...a.sourceRefs,i])))}cy(e),e.consensusLedger={...e.consensusLedger,moderatorNotes:[...e.consensusLedger.moderatorNotes,{id:`NOTE-${e.consensusLedger.moderatorNotes.length+1}`,kind:"merge_candidate",round:e.rounds,message:n,createdAt:this.nowIso()}]},await this.deps.documentManager.addComment(e.debateDocId,{author:"moderator",content:n})}}consensusFlowDeps(){return{bridge:this.deps.bridge,documentManager:this.deps.documentManager,registry:this.deps.registry,nowIso:()=>this.nowIso(),markParticipantProgress:(e,r,n)=>this.markParticipantProgress(e,r,n),setCurrentProvider:(e,r)=>this.setCurrentProvider(e,r),createActivitySink:(e,r,n,s)=>this.createParticipantActivitySink(e,r,n,s)}}createParticipantActivitySink(e,r,n,s){return o=>{this.markParticipantProgress(e,r,{status:"running",phase:n,round:s,lastActivityAt:this.nowIso(),lastEvent:U4(o)}).catch(()=>{})}}async markParticipantProgress(e,r,n){let s=e.participantProgress.get(r)??{participantId:r,status:"pending"};e.participantProgress.set(r,{...s,...n,participantId:r}),await this.persistRunningSnapshot(e)}async setCurrentProvider(e,r){r===void 0?delete e.currentProvider:e.currentProvider=r,await this.persistRunningSnapshot(e)}async persistRunningSnapshot(e){let r=e.phase==="terminal"?"error":"running";await this.deps.registry.persist(this.buildSnapshot(e,r))}rehydrateSessionContext(e){if(!e.ledgerState)throw new Error(`rehydrateSessionContext: snapshot "${e.sessionId}" has no ledgerState`);let r=Pn.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 s=new Set(e.unavailableParticipants??[]),o=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>o&&(o=u)}}return{sessionId:e.sessionId,mode:"review",config:e.config,goal:void 0,individualReviewPrompt:void 0,files:[],sourceDocuments:[],debateDocId:xs(e),debateDocPath:e.documentPaths.debate,individualPaths:{...e.documentPaths.individual},createdAt:e.createdAt,ledger:r,rounds:e.rounds,maxRounds:e.config.maxRounds,consecutiveFailures:n,unavailableParticipants:s,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:o+1,consensusLedger:ad({sessionId:e.sessionId,topic:e.config.topic,mode:"review",participants:e.config.participants.slice(),leader:e.config.leader,maxRounds:e.config.maxRounds,documents:{individual:{...e.documentPaths.individual},ledger:e.documentPaths.consensusLedger??new zt(this.deps.registry.getWorkspaceDir()).pathForSession(e.sessionId),debate:e.documentPaths.debate,...e.documentPaths.synthesis!==void 0?{synthesis:e.documentPaths.synthesis}:{}},items:e.aggregatedVotes.map(a=>({title:a.title,proposer:a.proposers[0]??e.config.leader,plainSummary:a.title,originalClaim:a.title,sourceRefs:a.location?[a.location]:[]}))}),consensusLedgerPath:e.documentPaths.consensusLedger??new zt(this.deps.registry.getWorkspaceDir()).pathForSession(e.sessionId),legacyProposalIdMap:new Map(e.aggregatedVotes.map((a,c)=>[a.proposalId,`ITEM-${String(c+1).padStart(2,"0")}`])),phase:e.phase,...e.config.participantTimeoutMs!==void 0?{participantTimeoutMs:e.config.participantTimeoutMs}:{},participantProgress:new Map(Object.entries(e.progress.participants)),...e.progress.currentProvider!==void 0?{currentProvider:e.progress.currentProvider}:{}}}async rehydrateConsensusSessionContext(e){let r=new zt(this.deps.registry.getWorkspaceDir()),n=e.documentPaths.consensusLedger??r.pathForSession(e.sessionId),s=await r.load(e.sessionId);if(!s)throw new Error(`continueDebate: consensus ledger not found for session "${e.sessionId}" at ${n}`);let o=new Map;if(e.consecutiveFailuresByParticipant)for(let[i,a]of Object.entries(e.consecutiveFailuresByParticipant))a>0&&o.set(i,a);return{sessionId:e.sessionId,mode:s.mode,config:e.config,goal:void 0,individualReviewPrompt:void 0,files:[],sourceDocuments:[],debateDocId:xs(e),debateDocPath:e.documentPaths.debate,individualPaths:{...e.documentPaths.individual},createdAt:e.createdAt,ledger:e.ledgerState?Pn.fromJSON(e.ledgerState):new Pn,rounds:e.rounds,maxRounds:e.config.maxRounds,consecutiveFailures:o,unavailableParticipants:new Set(e.unavailableParticipants??[]),allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:1,consensusLedger:s,consensusLedgerPath:n,legacyProposalIdMap:PT(s),phase:e.phase,...e.config.participantTimeoutMs!==void 0?{participantTimeoutMs:e.config.participantTimeoutMs}:{},participantProgress:new Map(Object.entries(e.progress.participants)),...e.progress.currentProvider!==void 0?{currentProvider:e.progress.currentProvider}:{}}}buildSnapshot(e,r,n){let s=this.nowIso(),o=LT(r)?fT(s,GT):s,i=this.snapshotAggregatedVotes(e),a=Z4(e.phase,r),c=V4(i,n),u={};for(let[d,p]of e.consecutiveFailures)p>0&&(u[d]=p);return{schemaVersion:2,sessionId:e.sessionId,status:r,phase:a,createdAt:e.createdAt,updatedAt:s,readyAt:s,deadline:o,config:{...e.config,maxRounds:e.maxRounds},rounds:e.rounds,progress:{round:e.rounds,maxRounds:e.maxRounds,...e.currentProvider!==void 0?{currentProvider:e.currentProvider}:{},participants:Object.fromEntries(e.participantProgress)},summary:c,aggregatedVotes:i,documentPaths:{individual:{...e.individualPaths},debate:e.debateDocPath,consensusLedger:e.consensusLedgerPath},ledgerState:e.ledger.toJSON(),...Object.keys(u).length>0?{consecutiveFailuresByParticipant:u}:{},...e.unavailableParticipants.size>0?{unavailableParticipants:Array.from(e.unavailableParticipants)}:{},...n!==void 0?{terminalNote:n}:{}}}snapshotAggregatedVotes(e){if(e.consensusLedger.items.length>0)return e.consensusLedger.items.map(n=>{let s={};for(let o of n.currentStances){let i=o.commentId?n.comments.find(a=>a.id===o.commentId):void 0;s[o.provider]={vote:ZT(o.stance),roundRecorded:o.round,...i?.comment?{reason:i.comment}:{}}}return{proposalId:UT(e.legacyProposalIdMap,n.id),title:n.title,severity:"MEDIUM",proposers:[n.proposer],status:FT(n.status),votes:s,...n.parentId!==void 0?{supersededBy:n.parentId}:{}}});let r=[];for(let n of e.ledger.proposals.values()){if(n.status==="merged")continue;let s={};for(let[o,i]of n.votes)s[o]={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:qT(n.status),votes:s,...n.supersededBy!==void 0?{supersededBy:n.supersededBy}:{}})}return r}renderTerminal(e,r){if(e?.consensusLedger)return[`Topic: ${e.consensusLedger.topic}`,`Status: ${r.status}`,`Readable status: ${r.status.replace(/-/g," ")}`,"",OT({...e.consensusLedger,documents:{...e.consensusLedger.documents,...r.documentPaths.synthesis!==void 0?{synthesis:r.documentPaths.synthesis}:{}}})].join(`
|
|
331
|
+
`);let n=e?this.buildReportData(e,r):nI(r);return this.formatter.renderTerminal(n,this.deps.i18n)}buildReportData(e,r,n){let s=[],o=[],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=H4(l,d);s.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"&&o.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=K4(e);return{topic:e.config.topic,rounds:e.rounds,maxRounds:e.maxRounds,status:ly(r.status),participantIds:e.config.participants,individualPaths:Object.values(e.individualPaths),debatePath:e.debateDocPath,...r.documentPaths.synthesis!==void 0?{synthesisPath:r.documentPaths.synthesis}:{},proposals:s,contributionSummary:u,dissentDetails:o,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}
|
|
329
332
|
|
|
330
333
|
**${n}:** ${e}`}formatRejectionFooter(e){let r=this.deps.i18n.t("moderator.narration.rejected");return e?`${r}
|
|
331
334
|
|
|
332
|
-
Reason: ${e}`:r}formatLeaderTimeoutFooter(e){let r=this.deps.i18n.t("moderator.narration.leaderTimeoutFooter"),n=Date.parse(e.readyAt),
|
|
335
|
+
Reason: ${e}`:r}formatLeaderTimeoutFooter(e){let r=this.deps.i18n.t("moderator.narration.leaderTimeoutFooter"),n=Date.parse(e.readyAt),s=Date.parse(e.deadline),o=Number.isFinite(n)&&Number.isFinite(s)&&s>n?Math.round((s-n)/(3600*1e3)):24,i=this.deps.i18n.t("approval.timeout",{hours:o});return`## ${r}
|
|
333
336
|
|
|
334
|
-
${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
|
|
337
|
+
${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 F4(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return`s-${t}-${e}`}function hy(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 U4(t){let e=t.type==="stdout"||t.type==="stderr"?`${t.type}: ${t.preview??"(output)"}`:t.type;return t.type==="timeout"&&t.timeoutMs!==void 0?`timeout after ${t.timeoutMs}ms`:t.type==="abort"&&t.reason?`abort: ${t.reason}`:t.type==="close"?`close: exit=${t.exitCode??"null"} signal=${t.signalCode??"null"}`:e}function Z4(t,e){return e==="approved"||e==="rejected"||e==="leader-timeout"||e==="error"?"terminal":e==="ready-for-approval"||e==="escalated"?"approval-gate":t}function V4(t,e){let r=t.filter(s=>s.status!=="open"&&s.status!=="inconclusive").length,n=t.length;return{totalItems:n,resolvedItems:r,openItems:n-r,...e!==void 0?{terminalNote:e}:{}}}function B4(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 s of Object.values(r.votes))switch(n.total+=1,s.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 W4(t){let e=0;for(let r of t){let n=r.id.match(/^P(\d+)$/);if(n){let s=Number.parseInt(n[1],10);Number.isFinite(s)&&s>e&&(e=s)}}return e+1}function tI(t,e){let r=`P${t.nextProposalIndex}`;return t.nextProposalIndex+=1,r}function rI(t){if(t.nextTurn===void 0)return t;let e={...t};return delete e.nextTurn,e}function H4(t,e){let r=0,n=0,s=[];for(let a of e){let c=t.votes.get(a);if(!c){s.push({participantId:a,vote:"missing"});continue}s.push({participantId:a,vote:c.vote,...c.reason!==void 0?{reason:c.reason}:{}}),c.vote==="agree"?r+=1:c.vote==="abstain"&&(n+=1)}let o=e.length-n,i=[];for(let a of s)a.vote==="agree"||a.vote==="abstain"||i.push(`${a.participantId} ${a.vote}`);return{agree:r,denominator:o,perParticipant:s,...i.length>0?{dissentSummary:i.join(", ")}:{}}}function K4(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 s=e.get(n);s&&(s.proposed+=1,r.status==="consensus"&&(s.consensusReceived+=1))}for(let[n,s]of r.votes){let o=e.get(n);o&&(s.vote==="revise"&&(o.revisesProposed+=1),s.vote==="abstain"&&(o.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 nI(t,e){let r=[],n=[],s=[],o=[],i=[];for(let a of t.aggregatedVotes){let c=t.config.participants.filter(m=>!a.proposers.includes(m)),u=c.map(m=>{let h=a.votes[m];return h?{participantId:m,vote:h.vote,...h.reason!==void 0?{reason:h.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"?s.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"&&o.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:ly(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:s,openItems:o}}var sI=18e4;function ec(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Provider "${e}" stalled (no response after ${sI/1e3}s)`)),sI))])}function iI(t){return new Qs({tools:qc(),baseDir:t})}var gy;function aI(){return gy||(gy=new gi),gy}var Yo;function fd(t,e,r){if(Yo&&Yo.registry===t&&Yo.hostKind===e&&Yo.baseDir===r)return Yo.bridge;let n=new Qs({tools:qc(),baseDir:r}),s=pT({registry:t,readOnlyAdapter:n,hostKind:e,agentsDir:J4(r,"agents")});return Yo={bridge:s,registry:t,hostKind:e,baseDir:r},s}var oI=new Map;function cI(t){let e=oI.get(t.workspaceBaseDir);if(e&&e.registry===t.structuredSessionRegistry&&e.documentManager===t.documentManager&&e.bridge===t.bridge)return e.engine;let r=new Go({bridge:t.bridge,documentManager:t.documentManager,registry:t.structuredSessionRegistry,i18n:t.i18n,...t.traceWriter!==void 0?{traceWriter:t.traceWriter}:{}});return oI.set(t.workspaceBaseDir,{engine:r,registry:t.structuredSessionRegistry,documentManager:t.documentManager,bridge:t.bridge}),r}function uI(t,e,r){if(r!==void 0){if(r.length===0)throw new Error("Quality score unavailable: no manual scores provided.");for(let i of r)e?.updateQuality(t.id,i.provider,{score:i.score,evaluator:"claude",feedback:i.feedback});return{avgQuality:r.reduce((i,a)=>i+a.score,0)/r.length}}let n=new Map;for(let i of t.turns){if(i.speaker==="claude")continue;let a=t.turns.filter(l=>l.turnNumber<i.turnNumber).map(l=>({speaker:l.speaker,content:l.content})),c=wi(i.content,a,t.topic),u=n.get(i.speaker)??[];u.push(c.score),n.set(i.speaker,u)}let s=0,o=0;for(let[i,a]of n){let c=a.reduce((u,l)=>u+l,0)/a.length;e?.updateQuality(t.id,i,{score:c,evaluator:"auto_rule_based",feedback:`Auto-aggregated from ${a.length} turns`}),s+=c,o++}if(o===0)throw new Error("Quality score unavailable: no provider turns to evaluate.");return{avgQuality:s/o}}function md(t,e,r){r.alreadyConcluded||t.debateEngine.conclude(e);let n=t.debateEngine.buildTurnTranscript(e);return t.debateEngine.delete(e),n}function lI(t){let e=[`**Structured Debate Session:** ${t.sessionId}`,`**Status:** ${t.status}`,`**Phase:** ${t.phase}`,`**Updated:** ${t.updatedAt}`,`**Round:** ${t.progress.round}/${t.progress.maxRounds}`];t.progress.currentProvider&&e.push(`**Current Provider:** ${t.progress.currentProvider}`),e.push(`**Items:** ${t.summary.resolvedItems}/${t.summary.totalItems} resolved (${t.summary.openItems} open)`),t.summary.terminalNote&&e.push(`**Terminal Note:** ${t.summary.terminalNote}`);let r=Object.values(t.progress.participants);if(r.length>0){e.push("","## Participant Progress");for(let n of r){let s=[n.phase,n.round!==void 0?`round ${n.round}`:void 0,n.lastEvent].filter(Boolean);e.push(`- ${n.participantId}: ${n.status}${s.length>0?` (${s.join(", ")})`:""}`)}}return e.push("","## Documents"),e.push(`- Debate: ${t.documentPaths.debate}`),t.documentPaths.consensusLedger&&e.push(`- Consensus ledger: ${t.documentPaths.consensusLedger}`),t.documentPaths.synthesis&&e.push(`- Synthesis: ${t.documentPaths.synthesis}`),t.documentPaths.issue&&e.push(`- Issue: ${t.documentPaths.issue}`),e.join(`
|
|
338
|
+
`)}function dI(t){let e=t.items.filter(s=>["accepted","excluded","superseded"].includes(s.status)).length,r=t.items.length-e,n=[`**Structured Debate Ledger:** ${t.sessionId}`,"**Status:** ledger-only",`**Mode:** ${t.mode}`,`**Updated:** ${t.updatedAt}`,`**Round:** ${t.round}/${t.maxRounds}`,`**Items:** ${e}/${t.items.length} resolved (${r} open)`,"","## Documents",`- Debate: ${t.documents.debate}`,`- Consensus ledger: ${t.documents.ledger}`];if(t.items.length>0){n.push("","## Items");for(let s of t.items.slice(0,10))n.push(`- ${s.id}: ${s.title} (${s.displayStatus})`);t.items.length>10&&n.push(`- ... ${t.items.length-10} more item(s)`)}return n.join(`
|
|
339
|
+
`)}async function pI(t,e){let r=Zl.parse(t),n=new Map(r.providers.map(l=>[l,e.registry.get(l)])),s=e.sessionManager.createSession("debate",{topic:r.topic,providers:r.providers,maxRounds:r.max_rounds});e.sessionManager.updateSessionStatus(s.id,"in_progress");let o=e.debateEngine,i=o.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 h=o.buildPromptForProvider(i.id,f);l&&(h+=`
|
|
335
340
|
|
|
336
341
|
Validator feedback from previous round:
|
|
337
|
-
${l}`);let
|
|
342
|
+
${l}`);let v=await ec(e.readOnlyAdapter.chat(m,{prompt:h}),f);o.addTurn(i.id,f,v.text)}if(a&&c&&p+1>=u){let f=o.buildTurnTranscript(i.id),m=`Evaluate this debate against the goal: "${r.goal}"
|
|
338
343
|
|
|
339
344
|
Current discussion:
|
|
340
345
|
${f}
|
|
@@ -346,38 +351,38 @@ Respond in JSON:
|
|
|
346
351
|
"accuracy": true/false,
|
|
347
352
|
"consistency": true/false,
|
|
348
353
|
"feedback": "..."
|
|
349
|
-
}`,h=await
|
|
350
|
-
**Session ID:** ${
|
|
354
|
+
}`,h=await ec(e.readOnlyAdapter.chat(c,{prompt:m}),c.id);try{let v=JSON.parse(h.text);if(v.goalAchievement&&v.completeness&&v.accuracy&&v.consistency)break;l=String(v.feedback??"")}catch{l=h.text}}}let d=md(e,i.id,{topic:r.topic,providerIds:r.providers});e.sessionManager.completeSession(s.id,d)}catch(l){let d=D(l);try{o.delete(i.id)}catch{}e.sessionManager.updateSessionStatus(s.id,"failed")}})(),{content:[{type:"text",text:`**Debate started**
|
|
355
|
+
**Session ID:** ${s.id}
|
|
351
356
|
**Topic:** ${r.topic}
|
|
352
357
|
**Participants:** ${r.providers.join(", ")}
|
|
353
358
|
|
|
354
|
-
Use \`agent_debate_status\` to check progress.`}]}}async function
|
|
355
|
-
**Type:** ${
|
|
356
|
-
**Status:** ${
|
|
357
|
-
**Created:** ${
|
|
358
|
-
**Updated:** ${
|
|
359
|
-
**Topic:** ${
|
|
360
|
-
**Providers:** ${
|
|
359
|
+
Use \`agent_debate_status\` to check progress.`}]}}async function fI(t,e){let r=Bl.parse(t),n=await e.structuredSessionRegistry?.load(r.session_id);if(n)return{content:[{type:"text",text:lI(n)}]};if(e.structuredSessionRegistry){let i=await new zt(e.structuredSessionRegistry.getWorkspaceDir()).load(r.session_id);if(i)return{content:[{type:"text",text:dI(i)}]}}let s=e.sessionManager.getSession(r.session_id);if(!s)return{content:[{type:"text",text:`Session not found: ${r.session_id}`}],isError:!0};let o=`**Session ID:** ${s.id}
|
|
360
|
+
**Type:** ${s.type}
|
|
361
|
+
**Status:** ${s.status}
|
|
362
|
+
**Created:** ${s.createdAt}
|
|
363
|
+
**Updated:** ${s.updatedAt}`;if(s.config){let i=s.config;i.topic&&(o+=`
|
|
364
|
+
**Topic:** ${i.topic}`),i.providers&&(o+=`
|
|
365
|
+
**Providers:** ${i.providers.join(", ")}`)}return s.result&&(o+=`
|
|
361
366
|
|
|
362
367
|
---
|
|
363
368
|
|
|
364
|
-
${
|
|
369
|
+
${s.result}`),{content:[{type:"text",text:o}]}}async function mI(t,e){let r=Vl.parse(t),n=new vi(e.registry,e.readOnlyAdapter);try{let s=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}),o=`**Cross-Validation ${s.overallPass?"PASSED":"FAILED"}**
|
|
365
370
|
|
|
366
|
-
`;for(let i of
|
|
367
|
-
`,
|
|
368
|
-
`,
|
|
369
|
-
`,i.suggestedFixes&&(
|
|
370
|
-
`),
|
|
371
|
-
`;return
|
|
372
|
-
${
|
|
371
|
+
`;for(let i of s.reviews)o+=`### ${i.targetProvider} reviewed by ${i.reviewerProvider}
|
|
372
|
+
`,o+=`**Result:** ${i.passed?"PASS":"FAIL"}
|
|
373
|
+
`,o+=`**Feedback:** ${i.feedback}
|
|
374
|
+
`,i.suggestedFixes&&(o+=`**Suggested Fixes:** ${i.suggestedFixes}
|
|
375
|
+
`),o+=`
|
|
376
|
+
`;return s.conflicts.length>0&&(o+=`## Conflicts
|
|
377
|
+
${s.conflicts.map(i=>`- ${i}`).join(`
|
|
373
378
|
`)}
|
|
374
|
-
`),{content:[{type:"text",text:
|
|
379
|
+
`),{content:[{type:"text",text:o}]}}catch(s){return{content:[{type:"text",text:`**Cross-validation failed:** ${D(s)}`}],isError:!0}}}async function hI(t,e){let r=Wl.parse(t);for(let o of r.providers)o!=="claude"&&e.registry.get(o);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**
|
|
375
380
|
**Debate ID:** ${e.debateEngine.create({topic:r.topic,providerIds:r.providers,goal:r.goal,documentId:n}).id}
|
|
376
381
|
**Topic:** ${r.topic}
|
|
377
382
|
**Participants:** ${r.providers.join(", ")}${n?`
|
|
378
|
-
**Document ID:** ${n}`:""}`}]}}async function
|
|
383
|
+
**Document ID:** ${n}`:""}`}]}}async function gI(t,e){let r=Hl.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 s=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 o=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(s,{prompt:o})}catch(p){let f=Math.round(performance.now()-a),m=D(p);return e.traceWriter&&e.traceWriter.write({traceId:n.id,action:"debate_turn",providerId:r.provider,task:n.topic,request:{promptSummary:o.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:o.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=wi(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}
|
|
379
384
|
|
|
380
|
-
_Quality: ${d.score.toFixed(2)}_`}]}}async function
|
|
385
|
+
_Quality: ${d.score.toFixed(2)}_`}]}}async function yI(t,e){let r=Kl.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}));let s;try{({avgQuality:s}=uI(n,e.traceWriter,r.quality_scores))}catch(a){return{content:[{type:"text",text:`Cannot conclude debate: ${D(a)}`}],isError:!0}}e.debateEngine.conclude(r.debate_id);let o=md(e,r.debate_id,{topic:n.topic,providerIds:n.providerIds,importance:.5+s*.5,confidence:s,alreadyConcluded:!0}),i=`**Debate concluded**
|
|
381
386
|
**Debate ID:** ${r.debate_id}
|
|
382
387
|
**Topic:** ${n.topic}
|
|
383
388
|
**Turns:** ${n.turns.length}`;return n.documentId&&(i+=`
|
|
@@ -385,50 +390,50 @@ _Quality: ${d.score.toFixed(2)}_`}]}}async function aR(t,e){let r=Ul.parse(t),n=
|
|
|
385
390
|
|
|
386
391
|
---
|
|
387
392
|
|
|
388
|
-
${
|
|
393
|
+
${o}`,{content:[{type:"text",text:i}]}}async function vI(t,e,r,n){e&&await t.documentManager.addComment(e,{author:r,content:n})}function hd(t){switch(t.kind){case"agree":return"AGREES";case"disagree":return"DISAGREES";case"parseError":return"PARSE_ERROR";case"unavailable":return"UNAVAILABLE"}}function gd(t){switch(t.kind){case"agree":case"disagree":{let e=t.suggestions?`
|
|
389
394
|
|
|
390
395
|
**Suggestions:** ${t.suggestions}`:"";return`${t.feedback}${e}`}case"parseError":return`[Parse error: ${t.reason}]
|
|
391
396
|
|
|
392
397
|
**Raw response:**
|
|
393
398
|
|
|
394
|
-
${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function
|
|
399
|
+
${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function _I(t,e,r,n,s){if(!e)return;let o=await t.documentManager.createReview({files:[],rules:[`Independent review from ${s.provider}`,`Parent document: ${e}`,...r?[`Debate ID: ${r}`]:[]],provider:s.provider,topic:`review-${e.slice(0,12)}`});await t.documentManager.addComment(o.id,{author:"Moderator",content:`## Review Target
|
|
395
400
|
|
|
396
401
|
Parent document: ${e}${r?`
|
|
397
402
|
Debate ID: ${r}`:""}
|
|
398
403
|
|
|
399
404
|
## Reviewed Content
|
|
400
405
|
|
|
401
|
-
${n}`});let i=
|
|
406
|
+
${n}`});let i=s.rawResponse?`
|
|
402
407
|
|
|
403
408
|
**Raw response:**
|
|
404
409
|
|
|
405
|
-
${
|
|
410
|
+
${s.rawResponse}`:"";return await t.documentManager.addComment(o.id,{author:`${s.provider} (independent review)`,content:`**${hd(s.outcome)}**
|
|
406
411
|
|
|
407
|
-
${
|
|
408
|
-
${
|
|
409
|
-
**Excluded Providers:** ${
|
|
412
|
+
${gd(s.outcome)}${i}`}),o.id}function G4(t){return`${t?.trim()??"Review the following document carefully and state whether you agree with its content."}
|
|
413
|
+
${tv}`}function Y4(t){let e=Xs(t);if(e===null||typeof e!="object")return{kind:"parseError",rawResponse:t,reason:"Response did not contain a parseable JSON object."};let r=eT.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:s,suggestions:o}=r.data;return n?{kind:"agree",feedback:s,suggestions:o}:{kind:"disagree",feedback:s,suggestions:o}}async function bI(t,e){let r=Jl.parse(t),n=[...r.providers],s=[],o=r.debate_id?e.debateEngine.getState(r.debate_id):void 0,i=o?.documentId;if(r.debate_id&&o){let g=new Set(e.debateEngine.getActiveProviders(r.debate_id)),b=[];for(let _ of n)if(_==="claude"||g.has(_))b.push(_);else{let P=(o.unavailableProviders??[]).find(x=>x.providerId===_);s.push({id:_,reason:P?`Marked unavailable for this debate: ${P.reason}`:"Not currently active in this debate."})}n=b}let a=s.length===0?"":`
|
|
414
|
+
**Excluded Providers:** ${s.map(g=>`${g.id} (${g.reason})`).join(", ")}`;if(n.length===0)return{content:[{type:"text",text:`No review-capable providers remain after exclusions.${a}`}],isError:!0};let c=G4(r.review_prompt),u=[],l=n.map(async g=>{if(g==="claude")return null;let b=e.registry.get(g),_=`${c}
|
|
410
415
|
|
|
411
416
|
---
|
|
412
417
|
|
|
413
|
-
${r.document}`,
|
|
418
|
+
${r.document}`,P,x;try{let k=await ec(e.readOnlyAdapter.chat(b,{prompt:_}),g);P=k.text,x=Y4(k.text)}catch(k){let O=D(k);if(x={kind:"unavailable",reason:O},r.debate_id&&o){let L=k instanceof xe?`Provider reported unavailable: ${O}`:`Chat failed: ${O}`;e.debateEngine.markProviderUnavailable(r.debate_id,g,L),o=e.debateEngine.getState(r.debate_id)}}let j={provider:g,outcome:x,rawResponse:P};if(j.linkedDocumentId=await _I(e,i,r.debate_id,r.document,j),i){let k=gd(j.outcome),O=j.linkedDocumentId?`
|
|
414
419
|
|
|
415
|
-
**Independent review document:** ${
|
|
420
|
+
**Independent review document:** ${j.linkedDocumentId}`:"";await e.documentManager.addComment(i,{author:`${g} (review)`,content:`**${hd(j.outcome)}**
|
|
416
421
|
|
|
417
|
-
${
|
|
422
|
+
${k}${O}`})}return j}),d=await Promise.all(l);for(let g of d)g&&u.push(g);let p=u.filter(g=>g.outcome.kind==="agree"||g.outcome.kind==="disagree"),f=u.length>0&&p.length===u.length&&p.every(g=>g.outcome.kind==="agree"),m=u.filter(g=>g.outcome.kind==="parseError"||g.outcome.kind==="unavailable"),v=`**Document Review** \u2014 ${f?"ALL AGREE \u2713":m.length>0&&p.length===0?"NO RESPONSES":"DISAGREEMENTS FOUND"}${a}
|
|
418
423
|
|
|
419
|
-
`;for(let
|
|
420
|
-
`,
|
|
421
|
-
`,
|
|
422
|
-
`),
|
|
423
|
-
`;if(!f){let
|
|
424
|
+
`;for(let g of u)v+=`### ${g.provider}: ${hd(g.outcome)}
|
|
425
|
+
`,v+=`${gd(g.outcome)}
|
|
426
|
+
`,g.linkedDocumentId&&(v+=`**Independent review document:** ${g.linkedDocumentId}
|
|
427
|
+
`),v+=`
|
|
428
|
+
`;if(!f){let g=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.";v+=`---
|
|
424
429
|
|
|
425
|
-
**Next step:** ${
|
|
430
|
+
**Next step:** ${g}`}return await vI(e,i,"Moderator (Review Aggregation)",v),{content:[{type:"text",text:v}]}}async function wI(t,e){let r=Gl.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(o){return{content:[{type:"text",text:D(o)}],isError:!0}}let s=`**File Change Review**
|
|
426
431
|
**Task ID:** ${r.task_id}
|
|
427
432
|
**Worktree:** ${n.worktreePath}
|
|
428
433
|
**Branch:** ${n.branch}
|
|
429
434
|
**Files changed:** ${n.filesChanged.length}
|
|
430
435
|
|
|
431
|
-
`;return n.filesChanged.length===0?
|
|
436
|
+
`;return n.filesChanged.length===0?s+="No changes detected.":s+=`### Diff Stat
|
|
432
437
|
\`\`\`
|
|
433
438
|
${n.diffStat}
|
|
434
439
|
\`\`\`
|
|
@@ -436,149 +441,150 @@ ${n.diffStat}
|
|
|
436
441
|
### Changes
|
|
437
442
|
\`\`\`diff
|
|
438
443
|
${n.fullDiff}
|
|
439
|
-
\`\`\``,{content:[{type:"text",text:
|
|
444
|
+
\`\`\``,{content:[{type:"text",text:s}]}}async function SI(t,e){let r=Yl.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**
|
|
440
445
|
**Task ID:** ${r.task_id}
|
|
441
446
|
**Merged files:** ${n.merged.length}
|
|
442
447
|
|
|
443
|
-
${n.merged.map(
|
|
444
|
-
`)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${
|
|
448
|
+
${n.merged.map(s=>`- ${s}`).join(`
|
|
449
|
+
`)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${D(n)}`}],isError:!0}}}async function $I(t,e){let r=Xl.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(s){return{content:[{type:"text",text:D(s)}],isError:!0}}let n=`**Changes rejected**
|
|
445
450
|
**Task ID:** ${r.task_id}`;return r.reason&&(n+=`
|
|
446
|
-
**Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}import{join as
|
|
451
|
+
**Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}import{join as X4}from"path";var Q4="unknown";async function xI(t,e,r){let n=r.workspaceBaseDir??process.cwd(),s=r.structuredSessionRegistry??new Jo(X4(n,ni)),o=fd(r.registry,r.sessionContext?.hostKind??Q4,n),i=r.moderatorEngine??cI({workspaceBaseDir:n,bridge:o,documentManager:r.documentManager,structuredSessionRegistry:s,i18n:r.i18n,...r.traceWriter!==void 0?{traceWriter:r.traceWriter}:{}}),a={...r,debateEngine:aI(),readOnlyAdapter:iI(n),structuredSessionRegistry:s,moderatorEngine:i};switch(t){case"agent_debate_start":return pI(e,a);case"agent_debate_status":return fI(e,a);case"agent_cross_validate":return mI(e,a);case"agent_debate_create":return hI(e,a);case"agent_debate_turn":return gI(e,a);case"agent_debate_conclude":return yI(e,a);case"agent_debate_review":return bI(e,a);case"agent_changes_review":return wI(e,a);case"agent_changes_accept":return SI(e,a);case"agent_changes_reject":return $I(e,a);case nd:return tT(e,a);case Bo:return rT(e,a);case Wo:return nT(e,a);case Ho:return sT(e,a);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var vy={};lt(vy,{getTools:()=>eW,handleTool:()=>cW});var PI=y.object({files:y.array(y.string()).min(1).describe("File paths to include in the review"),rules:y.array(y.string()).describe("Review rules/guidelines to apply")}),kI=y.object({doc_id:y.string().describe("Document ID to request review for"),provider:y.union([y.string(),y.array(y.string()).min(1)]).describe("Provider ID(s) to perform the review")}),EI=y.object({session_id:y.string().describe("Session ID returned by workspace_request_review")}),TI=y.object({doc_id:y.string().describe("Document ID to comment on"),author:y.string().describe("Comment author name"),content:y.string().describe("Comment content")}),II=y.object({doc_id:y.string().describe("Document ID to read")}),RI=y.object({title:y.string().describe("Document title"),content:y.string().describe("Document content (markdown)"),metadata:y.record(y.string()).optional().describe("Optional key-value metadata (e.g. Provider, Task, Mode)"),kind:y.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.")}),AI=y.object({});function eW(){return[{name:"workspace_create_review",title:"Create Code Review",description:"Create a code review document for the specified files with given review rules.",inputSchema:G(PI)},{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:G(kI)},{name:"workspace_review_status",title:"Check Review Status",description:"Check the status of an async review session started by workspace_request_review.",inputSchema:G(EI)},{name:"workspace_add_comment",title:"Add Review Comment",description:"Add a comment to an existing review document.",inputSchema:G(TI)},{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:G(RI)},{name:"workspace_read",title:"Read Document",description:"Read the contents of a workspace document.",inputSchema:G(II)},{name:"workspace_list",title:"List Documents",description:"List all workspace documents.",inputSchema:G(AI)}]}async function tW(t,e){let r=PI.parse(t),n=await e.documentManager.createReview({files:r.files,rules:r.rules});return{content:[{type:"text",text:`**Review created**
|
|
447
452
|
**Document ID:** ${n.id}
|
|
448
453
|
**Path:** ${n.path}
|
|
449
454
|
**Files:** ${r.files.join(", ")}
|
|
450
|
-
**Rules:** ${r.rules.length}`}]}}async function
|
|
455
|
+
**Rules:** ${r.rules.length}`}]}}async function rW(t,e){let r=kI.parse(t),n=Array.isArray(r.provider)?r.provider:[r.provider],s=[];for(let c of n){let u=e.registry.get(c);s.push({id:c,provider:u})}let o=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=s.map(async({id:c,provider:u})=>{try{let l=await u.chat({prompt:`Please review the following document and provide feedback:
|
|
451
456
|
|
|
452
|
-
${
|
|
457
|
+
${o.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=D(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=up({providers:n.length,failed:l.length});e.sessionManager.transitionSession(i.id,p,d)}catch{}}),{content:[{type:"text",text:`**Review started (async)**
|
|
453
458
|
**Session ID:** ${i.id}
|
|
454
459
|
**Document ID:** ${r.doc_id}
|
|
455
460
|
**Providers:** ${n.join(", ")}
|
|
456
461
|
|
|
457
|
-
Use \`workspace_review_status\` with session_id to check progress.`}]}}async function
|
|
462
|
+
Use \`workspace_review_status\` with session_id to check progress.`}]}}async function nW(t,e){let r=EI.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 s=n.config.providers||[],o=n.config.completed||[],i=n.config.failed||[],a=s.filter(u=>!o.includes(u)&&!i.includes(u)),c=`**Review Session Status**
|
|
458
463
|
`;return c+=`**Session ID:** ${n.id}
|
|
459
464
|
`,c+=`**Status:** ${n.status}
|
|
460
465
|
`,c+=`**Document:** ${n.config.doc_id}
|
|
461
|
-
`,c+=`**Providers:** ${
|
|
466
|
+
`,c+=`**Providers:** ${s.join(", ")}
|
|
462
467
|
|
|
463
|
-
`,c+=`- Completed: ${
|
|
468
|
+
`,c+=`- Completed: ${o.join(", ")||"none"}
|
|
464
469
|
`,c+=`- Failed: ${i.join(", ")||"none"}
|
|
465
470
|
`,c+=`- Pending: ${a.join(", ")||"none"}
|
|
466
471
|
`,n.result&&(c+=`
|
|
467
|
-
**Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function
|
|
472
|
+
**Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function sW(t,e){let r=TI.parse(t);return await e.documentManager.addComment(r.doc_id,{author:r.author,content:r.content}),{content:[{type:"text",text:`**Comment added**
|
|
468
473
|
**Document ID:** ${r.doc_id}
|
|
469
474
|
**Author:** ${r.author}
|
|
470
475
|
|
|
471
|
-
${r.content}`}]}}async function
|
|
476
|
+
${r.content}`}]}}async function oW(t,e){let r=RI.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**
|
|
472
477
|
**Document ID:** ${n.id}
|
|
473
478
|
**Path:** ${n.path}
|
|
474
|
-
**Title:** ${r.title}`}]}}async function
|
|
479
|
+
**Title:** ${r.title}`}]}}async function iW(t,e){let r=II.parse(t),n=await e.documentManager.read(r.doc_id);return{content:[{type:"text",text:`**Document ID:** ${n.id}
|
|
475
480
|
**Path:** ${n.path}
|
|
476
481
|
|
|
477
|
-
${n.content}`}]}}async function
|
|
482
|
+
${n.content}`}]}}async function aW(t,e){AI.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
|
|
478
483
|
|
|
479
484
|
**Total:** ${r.length}
|
|
480
485
|
|
|
481
|
-
`;for(let
|
|
482
|
-
|
|
486
|
+
`;for(let s of r)n+=`- **${s.id}** \u2014 ${s.kind}, ${s.sizeBytes} bytes, ${s.modifiedAt}
|
|
487
|
+
`,n+=` Path: ${s.path}
|
|
488
|
+
`;return{content:[{type:"text",text:n}]}}async function cW(t,e,r){switch(t){case"workspace_create_review":return tW(e,r);case"workspace_request_review":return rW(e,r);case"workspace_review_status":return nW(e,r);case"workspace_add_comment":return sW(e,r);case"workspace_create_document":return oW(e,r);case"workspace_read":return iW(e,r);case"workspace_list":return aW(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var _y={};lt(_y,{getTools:()=>lW,handleTool:()=>fW});function yd(t,e){return t==="claude-only"&&e!=="claude-code"?"leader-only":t}var uW=y.object({provider:y.string().optional().describe("Provider ID to check (omit to check all)")});function lW(){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 dW(t){let e=t.registry.getAll();if(e.length===0)return{content:[{type:"text",text:"No providers registered."}]};let r=`# Registered Providers (${e.length})
|
|
483
489
|
|
|
484
490
|
`;t.sessionContext&&(r+=`## Host Session
|
|
485
491
|
`,r+=`- **Host:** ${t.sessionContext.hostId} (${t.sessionContext.hostKind})
|
|
486
492
|
`,r+=`- **Leader Provider:** ${t.sessionContext.leaderProviderId}
|
|
487
|
-
`,r+=`- **Execution Mode:** ${
|
|
493
|
+
`,r+=`- **Execution Mode:** ${yd(t.sessionContext.executionMode,t.sessionContext.hostKind)}
|
|
488
494
|
`,r+=`- **Participants:** ${t.sessionContext.participantProviderIds.join(", ")}
|
|
489
495
|
|
|
490
|
-
`);for(let n of e){let
|
|
496
|
+
`);for(let n of e){let s=n.isAvailable(),o=n.getCapabilities(),i=typeof t.registry.getDescriptor=="function"?t.registry.getDescriptor(n.id):Yr(n,o),a=s?"Available":"Unavailable";r+=`## ${n.id} (${n.type})
|
|
491
497
|
`,r+=`- **Status:** ${a}
|
|
492
498
|
`,r+=`- **Invocation:** ${i.invocation}
|
|
493
499
|
`,r+=`- **Roles:** ${i.roles.join(", ")}
|
|
494
500
|
`,r+=`- **Autonomous Execution:** ${i.supportsAutonomousExecution?"Yes":"No"}
|
|
495
501
|
`,r+=`- **Read-Only Chat:** ${i.supportsReadOnlyChat?"Yes":"No"}
|
|
496
|
-
`,r+=`- **Max Context:** ${
|
|
497
|
-
`,r+=`- **System Prompt:** ${
|
|
498
|
-
`,r+=`- **Files:** ${
|
|
499
|
-
`,r+=`- **Streaming:** ${
|
|
500
|
-
`,r+=`- **JSON Output:** ${
|
|
501
|
-
`,r+=`- **Tool Use:** ${
|
|
502
|
-
`,
|
|
503
|
-
`),
|
|
502
|
+
`,r+=`- **Max Context:** ${o.maxContext}
|
|
503
|
+
`,r+=`- **System Prompt:** ${o.supportsSystemPrompt?"Yes":"No"}
|
|
504
|
+
`,r+=`- **Files:** ${o.supportsFiles?"Yes":"No"}
|
|
505
|
+
`,r+=`- **Streaming:** ${o.supportsStreaming?"Yes":"No"}
|
|
506
|
+
`,r+=`- **JSON Output:** ${o.supportsJsonOutput?"Yes":"No"}
|
|
507
|
+
`,r+=`- **Tool Use:** ${o.supportsToolUse?"Yes":"No"}
|
|
508
|
+
`,o.strengths.length>0&&(r+=`- **Strengths:** ${o.strengths.join(", ")}
|
|
509
|
+
`),o.models.length>0&&(r+=`- **Models:** ${o.models.map(c=>c.name).join(", ")}
|
|
504
510
|
`),r+=`
|
|
505
|
-
`}return{content:[{type:"text",text:r}]}}async function
|
|
506
|
-
|
|
507
|
-
`;for(let i of
|
|
508
|
-
`,
|
|
509
|
-
`,i.message&&(
|
|
510
|
-
`),i.error&&(
|
|
511
|
-
`),
|
|
512
|
-
`}return{content:[{type:"text",text:
|
|
513
|
-
`)}]}}async function
|
|
514
|
-
`)}]}}async function
|
|
515
|
-
|
|
516
|
-
`;for(let
|
|
517
|
-
`,n+=`- **Size:** ${
|
|
518
|
-
`,
|
|
511
|
+
`}return{content:[{type:"text",text:r}]}}async function pW(t,e){let r=uW.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 s=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:D(a),details:void 0,error:D(a)}}})),o=`# Health Check Results
|
|
512
|
+
|
|
513
|
+
`;for(let i of s){let a=i.status==="ok"?"OK":i.status==="degraded"?"DEGRADED":"ERROR";o+=`## ${i.id} (${i.type})
|
|
514
|
+
`,o+=`- **Status:** ${a}
|
|
515
|
+
`,i.message&&(o+=`- **Message:** ${i.message}
|
|
516
|
+
`),i.error&&(o+=`- **Error:** ${i.error}
|
|
517
|
+
`),o+=`
|
|
518
|
+
`}return{content:[{type:"text",text:o}]}}async function fW(t,e,r){switch(t){case"provider_list":return dW(r);case"provider_health":return pW(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var wy={};lt(wy,{getTools:()=>PW,handleTool:()=>TW});import{existsSync as _W,readFileSync as bW}from"fs";import{readFileSync as mW,existsSync as hW}from"fs";var gW={ollama:{executionPolicy:"workspace-write",config:{host:ri,defaultModel:"auto"}},"gemini-cli":{executionPolicy:Mr("gemini-cli"),config:{timeout:12e4}},"codex-cli":{executionPolicy:Mr("codex-cli"),config:{timeout:12e4}},"claude-cli":{executionPolicy:Mr("claude-cli"),config:{timeout:12e4}}};async function Xo(t){let e=t?.workspaceBaseDir,r=[{id:"ollama",type:"ollama",provider:new Jn({id:"ollama",host:ri})},{id:"gemini",type:"gemini-cli",provider:new Gn({id:"gemini"})},{id:"codex",type:"codex-cli",provider:new Yn({id:"codex",workspaceBaseDir:e})},{id:"claude-cli",type:"claude-cli",provider:new Xn({id:"claude-cli"})}],n=[],s=[];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&&s.push(i.provider)}));let o=["ollama","gemini","codex","claude-cli"];return n.sort((i,a)=>o.indexOf(i.id)-o.indexOf(a.id)),s.sort((i,a)=>o.indexOf(i.id)-o.indexOf(a.id)),{results:n,providers:s}}function yW(t){if(!hW(t))return null;try{return JSON.parse(mW(t,"utf-8"))}catch{return null}}function vW(t){return t==="auto"?"auto":"default-only"}function CI(t,e,r){let n=yW(t),s=new Set(r.enabledIds??[]),o=new Map((n?.providers??[]).map(d=>[d.id,d])),i=e.map(d=>{let p=gW[d.type]||{executionPolicy:Mr(d.type),config:{}},f=o.get(d.id);return o.delete(d.id),{id:d.id,type:d.type,enabled:d.available&&s.has(d.id),executionPolicy:f?.executionPolicy??p.executionPolicy,config:{...f?.config??p.config}}});for(let d of o.values())i.push({...d,enabled:s.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:vW(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"&&(bv(t),Ze(t,a)),{action:l,path:t,config:a}}function DI(t,e){by(t,e)}function by(t,e,r){let n=[];for(let s of t)e.has(s.id)||r?.excludeIds?.has(s.id)||r?.excludeTypes?.has(s.type)||(e.register(s),n.push(s));return n}var wW=y.object({}),SW=y.object({enabled_providers:y.array(y.string()).describe("Provider IDs to enable for Agestra workflows."),locale:y.enum(["ko","en","ja","zh"]).describe("UI language for moderator/setup-facing text."),selection_policy:y.enum(["default-only","auto"]).optional().default("default-only").describe("Provider selection policy stored in providers.config.json."),dry_run:y.boolean().optional().default(!1).describe("When true, compute the resulting config without writing it to disk.")});function $W(t){if(!_W(t))return null;try{return JSON.parse(bW(t,"utf-8"))}catch{return null}}function xW(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 PW(){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 kW(t){let e=ci(),r=$W(e),{results:n}=await Xo(t.workspaceBaseDir!==void 0?{workspaceBaseDir:t.workspaceBaseDir}:void 0),s=["# Agestra Setup"];if(s.push(""),s.push(...xW(r,e)),s.push(""),s.push("Detected providers:"),n.length===0)s.push("- (none detected)");else for(let o of n)s.push(`- ${o.id} (${o.type}) \u2014 ${o.available?"available":"unavailable"}`);return{content:[{type:"text",text:s.join(`
|
|
519
|
+
`)}]}}async function EW(t,e){let r=SW.parse(t),n=ci(),{results:s}=await Xo(e.workspaceBaseDir!==void 0?{workspaceBaseDir:e.workspaceBaseDir}:void 0);if(s.length===0)return{content:[{type:"text",text:"No AI providers were detected, so setup could not be applied."}],isError:!0};let o=new Set(s.filter(l=>l.available).map(l=>l.id)),i=r.enabled_providers.filter(l=>!o.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=CI(n,s,{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(`
|
|
520
|
+
`)}]}}async function TW(t,e,r){switch(t){case"setup_status":return wW.parse(e),kW(r);case"setup_apply":return EW(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Sy={};lt(Sy,{getTools:()=>RW,handleTool:()=>DW});var IW=y.object({model:y.string().describe("Model name to download (e.g. 'llama3', 'codellama')")});function RW(){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 OI(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 AW(t){let r=OI(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})
|
|
521
|
+
|
|
522
|
+
`;for(let s of r){let o=(s.size/1e9).toFixed(1);n+=`## ${s.name}
|
|
523
|
+
`,n+=`- **Size:** ${o} GB
|
|
524
|
+
`,s.strengths.length>0&&(n+=`- **Strengths:** ${s.strengths.join(", ")}
|
|
519
525
|
`),n+=`
|
|
520
|
-
`}return{content:[{type:"text",text:n}]}}async function
|
|
526
|
+
`}return{content:[{type:"text",text:n}]}}async function CW(t,e){let r=IW.parse(t),n=OI(e);try{let s=n.getConnectionInfo().host,o=await fetch(`${s}/api/pull`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:r.model,stream:!1})});if(!o.ok){let a=await o.text();return{content:[{type:"text",text:`**Pull failed**
|
|
521
527
|
**Model:** ${r.model}
|
|
522
|
-
**Error:** HTTP ${
|
|
528
|
+
**Error:** HTTP ${o.status}: ${a}`}],isError:!0}}let i=await o.json();return{content:[{type:"text",text:`**Model pulled successfully**
|
|
523
529
|
**Model:** ${r.model}
|
|
524
|
-
**Status:** ${i.status||"success"}`}]}}catch(
|
|
530
|
+
**Status:** ${i.status||"success"}`}]}}catch(s){let o=D(s);return{content:[{type:"text",text:`**Pull failed**
|
|
525
531
|
**Model:** ${r.model}
|
|
526
|
-
**Error:** ${
|
|
532
|
+
**Error:** ${o}`}],isError:!0}}}async function DW(t,e,r){switch(t){case"ollama_models":return AW(r);case"ollama_pull":return CW(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var $y={};lt($y,{getTools:()=>zW,handleTool:()=>jW});var OW=y.object({title:y.string().describe("Document title"),metadata:y.record(y.string()).optional().describe("Optional key-value metadata"),kind:y.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' / 'debate' / 'synthesis' / 'general' (default).")}).optional(),zI=y.object({provider:y.string().describe("Provider ID (e.g. 'gemini', 'codex')"),prompt:y.string().describe("Prompt to send to the provider CLI"),timeout:y.number().int().positive().optional().describe("Timeout in ms (default: 300000)"),save_as_document:OW.describe("If set, the job output will be saved as a workspace document on completion. Returned via cli_job_status once finalized.")}).strict(),MI=y.object({job_id:y.string().describe("Job ID returned by cli_job_submit")});function zW(){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:G(zI)},{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:G(MI)}]}async function MW(t,e){let r=zI.parse(t),n=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:r.timeout,saveAsDocument:r.save_as_document}),s=r.save_as_document?`
|
|
527
533
|
**Save on complete:** ${r.save_as_document.title}`:"";return{content:[{type:"text",text:`**Job submitted**
|
|
528
534
|
**Job ID:** ${n}
|
|
529
|
-
**Provider:** ${r.provider}${
|
|
535
|
+
**Provider:** ${r.provider}${s}
|
|
530
536
|
|
|
531
|
-
Use \`cli_job_status\` with this job_id to check progress.`}]}}async function
|
|
532
|
-
**State:** ${n.state}`;return n.exitCode!==void 0&&(
|
|
533
|
-
**Exit Code:** ${n.exitCode}`),n.savedDocumentId?
|
|
534
|
-
**Document ID:** ${n.savedDocumentId}`:n.saveError&&(
|
|
535
|
-
**Save error:** ${n.saveError}`),n.output&&(
|
|
537
|
+
Use \`cli_job_status\` with this job_id to check progress.`}]}}async function NW(t,e){let r=MI.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 s=`**Job ID:** ${n.id}
|
|
538
|
+
**State:** ${n.state}`;return n.exitCode!==void 0&&(s+=`
|
|
539
|
+
**Exit Code:** ${n.exitCode}`),n.savedDocumentId?s+=`
|
|
540
|
+
**Document ID:** ${n.savedDocumentId}`:n.saveError&&(s+=`
|
|
541
|
+
**Save error:** ${n.saveError}`),n.output&&(s+=`
|
|
536
542
|
|
|
537
543
|
---
|
|
538
544
|
|
|
539
545
|
**Output:**
|
|
540
|
-
${n.output}`),n.error&&(
|
|
546
|
+
${n.output}`),n.error&&(s+=`
|
|
541
547
|
|
|
542
548
|
**Stderr:**
|
|
543
|
-
${n.error}`),{content:[{type:"text",text:
|
|
549
|
+
${n.error}`),{content:[{type:"text",text:s}],isError:n.state==="error"||n.state==="missing_cli"}}async function jW(t,e,r){switch(t){case"cli_job_submit":return MW(e,r);case"cli_job_status":return NW(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var xy={};lt(xy,{getTools:()=>LW,handleTool:()=>qW});var NI=y.object({provider_id:y.string().optional(),task:y.string().optional(),trace_id:y.string().optional(),days_back:y.number().optional().default(7),limit:y.number().optional().default(50)}),jI=y.object({days_back:y.number().optional().default(30)}),LI=y.object({trace_id:y.string()});function LW(){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:G(NI)},{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:G(jI)},{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:G(LI)}]}async function qW(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 FW(e,n);case"trace_summary":return UW(e,n);case"trace_visualize":return ZW(e,n);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}function FW(t,e){let r=NI.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 s=`**Trace Records** (${n.length} results)
|
|
544
550
|
|
|
545
|
-
`;for(let
|
|
546
|
-
`;return{content:[{type:"text",text:
|
|
551
|
+
`;for(let o of n)s+=`| ${o.timestamp?.slice(0,19)} | ${o.providerId} | ${o.task} | ${o.latencyMs}ms | ${o.response.success?"OK":"FAIL"} |`,o.quality&&(s+=` quality: ${o.quality.score}`),s+=`
|
|
552
|
+
`;return{content:[{type:"text",text:s}]}}function UW(t,e){let r=jI.parse(t),n=e.traceWriter.getQualityStats(r.days_back);if(n.size===0)return{content:[{type:"text",text:"No quality data available yet."}]};let s=`**Provider Quality Summary** (last ${r.days_back} days)
|
|
547
553
|
|
|
548
|
-
`;
|
|
549
|
-
`,
|
|
550
|
-
`;for(let[a,c]of n)
|
|
551
|
-
`;let
|
|
554
|
+
`;s+=`| Provider:Task | Avg Quality | Count | Avg Latency |
|
|
555
|
+
`,s+=`|---|---|---|---|
|
|
556
|
+
`;for(let[a,c]of n)s+=`| ${a} | ${c.avgScore.toFixed(2)} | ${c.count} | ${Math.round(c.avgLatencyMs)}ms |
|
|
557
|
+
`;let o=new Map;for(let[a,c]of n){let u=a.split(":")[0],l=o.get(u)??{totalScore:0,count:0};l.totalScore+=c.avgScore*c.count,l.count+=c.count,o.set(u,l)}let i=["low","medium","high"];s+=`
|
|
552
558
|
**Provider Difficulty Qualification**
|
|
553
559
|
|
|
554
|
-
`,
|
|
555
|
-
`,
|
|
556
|
-
`;for(let[a,c]of
|
|
557
|
-
`}return{content:[{type:"text",text:
|
|
558
|
-
`;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`;
|
|
559
|
-
`;let l=a.response.success?`${a.response.charLength} chars, ${a.latencyMs}ms`:`FAIL: ${a.response.error?.slice(0,30)??"error"}`;
|
|
560
|
-
`,a.quality&&(
|
|
561
|
-
`)}return
|
|
560
|
+
`,s+=`| Provider | Overall Avg | Samples | Low | Medium (>=${ac.medium}) | High (>=${ac.high}) |
|
|
561
|
+
`,s+=`|---|---|---|---|---|---|
|
|
562
|
+
`;for(let[a,c]of o){let u=c.totalScore/c.count,l=i.map(d=>cc(u,d)?"YES":"no");s+=`| ${a} | ${u.toFixed(2)} | ${c.count} | ${l[0]} | ${l[1]} | ${l[2]} |
|
|
563
|
+
`}return{content:[{type:"text",text:s}]}}function ZW(t,e){let r=LI.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 s="```mermaid\ngraph LR\n";s+=` A[User Request] --> B{Provider Selection}
|
|
564
|
+
`;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`;s+=` B -->|${u}| ${c}[${a.providerId}]
|
|
565
|
+
`;let l=a.response.success?`${a.response.charLength} chars, ${a.latencyMs}ms`:`FAIL: ${a.response.error?.slice(0,30)??"error"}`;s+=` ${c} --> ${c}R[${l}]
|
|
566
|
+
`,a.quality&&(s+=` ${c}R --> ${c}Q[Quality: ${a.quality.score}]
|
|
567
|
+
`)}return s+="```",{content:[{type:"text",text:`**Trace Visualization: ${r.trace_id}**
|
|
562
568
|
|
|
563
|
-
${
|
|
569
|
+
${s}`}]}}var ky={};lt(ky,{getTools:()=>HW,handleTool:()=>GW,resetCache:()=>KW});import{execFile as VW}from"child_process";import{promisify as BW}from"util";var FI=BW(VW),UI=5e3;async function tc(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:r}=await FI(e,[t],{timeout:UI,encoding:"utf-8"});return r.split(/\r?\n/).map(s=>s.trim()).find(Boolean)||null}catch{return null}}async function WW(){try{return await FI("git",["worktree","list"],{timeout:UI,encoding:"utf-8"}),!0}catch{return!1}}function HW(){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 vd=null,Py=null;function KW(){vd=null,Py=null}async function JW(t,e){let r=JSON.stringify(e.sessionContext??null);if(vd&&Py===r&&!t.force_refresh)return{content:[{type:"text",text:qI(vd)}]};let n=typeof e.registry.getAvailable=="function"?e.registry.getAvailable():e.registry.getAll().filter(q=>q.isAvailable()),s=n.find(q=>q.type==="claude-cli"),o=n.find(q=>q.type==="claude-host"),i=n.find(q=>q.type==="codex-cli"),a=n.find(q=>q.type==="codex-host"),c=n.find(q=>q.type==="gemini-cli"),u=n.find(q=>q.type==="gemini-host"),[l,d,p,f,m,h]=await Promise.all([tc("claude"),tc("codex"),tc("gemini"),tc("tmux"),tc("git"),WW()]),v=[],g=e.registry.getAll(),b=g.find(q=>q.id==="ollama");if(b?.isAvailable()){let q=b.getCapabilities();for(let $e of q.models){let He=$e.sizeGb??0;v.push({name:$e.name,size_gb:He,tier:Ad(He)})}}let _=i!==void 0||c!==void 0,P=f!==null,x=m!==null&&h,j=a!==void 0||u!==void 0||e.sessionContext?.hostKind==="codex-cli"||e.sessionContext?.hostKind==="gemini-cli",k=g.some(q=>q.isAvailable()&&!q.type.endsWith("-host")&&q.id!=="ollama"),O=[j?"leader_only":"claude_only"];(k||v.length>0)&&O.push("independent","debate"),_&&x&&O.push("team");let L={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:b?.isAvailable()??!1,models:v},claude:{available:s!==void 0||o!==void 0,cli_path:l,host_backed:o!==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:P,path:f},git:{available:m!==null,worktree_support:x}},capabilities:{can_autonomous_work:_&&x,can_tmux_visible:P,can_parallel_workers:_&&x,max_parallel_workers:_?3:0,available_modes:O}};return vd=L,Py=r,{content:[{type:"text",text:qI(L)}]}}function qI(t){let e=`# Environment Check
|
|
564
570
|
|
|
565
571
|
`;t.host&&(e+=`## Host Session
|
|
566
572
|
|
|
567
573
|
`,e+=`- **Host:** ${t.host.id}
|
|
568
574
|
`,e+=`- **Kind:** ${t.host.kind}
|
|
569
575
|
`,e+=`- **Leader Provider:** ${t.host.leader_provider}
|
|
570
|
-
`,e+=`- **Execution Mode:** ${
|
|
576
|
+
`,e+=`- **Execution Mode:** ${yd(t.host.execution_mode,t.host.kind)}
|
|
571
577
|
`,e+=`- **Participants:** ${t.host.participant_providers.join(", ")}
|
|
572
578
|
|
|
573
579
|
`),e+=`## Providers
|
|
574
580
|
|
|
575
|
-
`;for(let[r,n]of Object.entries(t.providers)){let
|
|
576
|
-
- **Status:** ${
|
|
581
|
+
`;for(let[r,n]of Object.entries(t.providers)){let s=n.available?"Available":"Not found";if(e+=`### ${r}
|
|
582
|
+
- **Status:** ${s}
|
|
577
583
|
`,n.cli_path&&(e+=`- **CLI Path:** ${n.cli_path}
|
|
578
584
|
`),n.autonomous_capable&&(e+=`- **Autonomous:** Yes
|
|
579
585
|
`),n.host_backed&&(e+=`- **Host-backed:** Yes
|
|
580
586
|
`),n.models&&n.models.length>0){e+=`- **Models:**
|
|
581
|
-
`;for(let
|
|
587
|
+
`;for(let o of n.models)e+=` - ${o.name} (${o.size_gb.toFixed(1)} GB, tier: ${o.tier})
|
|
582
588
|
`}e+=`
|
|
583
589
|
`}return e+=`## Infrastructure
|
|
584
590
|
|
|
@@ -591,14 +597,14 @@ ${o}`}]}}var wy={};lt(wy,{getTools:()=>zW,handleTool:()=>MW,resetCache:()=>NW});
|
|
|
591
597
|
`,e+=`- **tmux visible:** ${t.capabilities.can_tmux_visible?"Yes":"No"}
|
|
592
598
|
`,e+=`- **Parallel workers:** ${t.capabilities.can_parallel_workers?`Yes (max ${t.capabilities.max_parallel_workers})`:"No"}
|
|
593
599
|
`,e+=`- **Available modes:** ${t.capabilities.available_modes.join(", ")}
|
|
594
|
-
`,e}async function
|
|
600
|
+
`,e}async function GW(t,e,r){return t==="environment_check"?JW(e??{},r):{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var Ey={};lt(Ey,{getTools:()=>YW,handleTool:()=>iH});var ZI=y.object({provider:y.string().trim().min(1),task_description:y.string().trim().min(1),working_dir:y.string().trim().min(1),files_to_read:y.array(y.string().trim().min(1)).optional(),files_to_modify:y.array(y.string().trim().min(1)).optional(),constraints:y.string().optional(),success_criteria:y.array(y.string().trim().min(1)).optional(),timeout_minutes:y.number().positive().optional(),use_worktree:y.boolean().optional(),use_tmux:y.boolean().optional()}).strict(),VI=y.object({worker_id:y.string().trim().min(1).optional()}).strict(),BI=y.object({worker_id:y.string().trim().min(1)}).strict(),WI=y.object({worker_id:y.string().trim().min(1)}).strict();function YW(){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:G(ZI)},{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:G(VI)},{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:G(BI)},{name:"cli_worker_stop",title:"Stop CLI Worker",description:"Stop a running CLI worker. Sends SIGTERM, then SIGKILL after 5 seconds.",inputSchema:G(WI)}]}function _d(t){if(!t.cliWorkerManager)throw new Error("CliWorkerManager not initialized \u2014 cli_worker tools are unavailable");return t.cliWorkerManager}function fr(t,e){return{content:[{type:"text",text:t}],...e?{isError:e}:{}}}function XW(t){let e=`# Worker Spawned
|
|
595
601
|
|
|
596
602
|
`;return e+=`- **Worker ID:** ${t.workerId}
|
|
597
603
|
`,e+=`- **Provider:** ${t.provider}
|
|
598
604
|
`,e+=`- **State:** ${t.state}
|
|
599
605
|
`,e+=`- **PID:** ${t.pid??"N/A"}
|
|
600
606
|
`,t.worktreeBranch&&(e+=`- **Worktree Branch:** ${t.worktreeBranch}
|
|
601
|
-
`),e}function
|
|
607
|
+
`),e}function QW(t){let e=`# Worker Status
|
|
602
608
|
|
|
603
609
|
`;return e+=`- **Worker ID:** ${t.workerId}
|
|
604
610
|
`,e+=`- **Provider:** ${t.provider}
|
|
@@ -607,18 +613,18 @@ ${o}`}]}}var wy={};lt(wy,{getTools:()=>zW,handleTool:()=>MW,resetCache:()=>NW});
|
|
|
607
613
|
`,e+=`- **PID:** ${t.pid??"N/A"}
|
|
608
614
|
`,e+=`- **Retry Count:** ${t.retryCount}
|
|
609
615
|
`,t.worktreeBranch&&(e+=`- **Worktree Branch:** ${t.worktreeBranch}
|
|
610
|
-
`),t.state===
|
|
616
|
+
`),t.state===qe.COLLECTING&&(e+="- **Next Step:** Worker exited successfully and is ready for `cli_worker_collect`\n"),t.outputTail&&(e+=`
|
|
611
617
|
## Recent Output
|
|
612
618
|
|
|
613
619
|
\`\`\`
|
|
614
620
|
${t.outputTail}
|
|
615
621
|
\`\`\`
|
|
616
|
-
`),e}function
|
|
622
|
+
`),e}function eH(t){if(t.length===0)return`# Workers
|
|
617
623
|
|
|
618
624
|
No tracked workers.`;let e=`# Workers (${t.length})
|
|
619
625
|
|
|
620
626
|
`;for(let r of t)e+=`- **${r.workerId}** \u2014 ${r.provider} \u2014 ${r.state}`,r.pid&&(e+=` (PID ${r.pid})`),e+=`
|
|
621
|
-
`;return e}function
|
|
627
|
+
`;return e}function tH(t){let e=`# Worker Results
|
|
622
628
|
|
|
623
629
|
`;if(e+=`- **Worker ID:** ${t.workerId}
|
|
624
630
|
`,e+=`- **State:** ${t.state}
|
|
@@ -640,7 +646,7 @@ ${t.gitDiff}
|
|
|
640
646
|
\`\`\`
|
|
641
647
|
${t.outputFull}
|
|
642
648
|
\`\`\`
|
|
643
|
-
`),e}async function
|
|
649
|
+
`),e}async function rH(t,e){let r=_d(e),n=ZI.parse(t),s=r.knownProviders();if(!s.includes(n.provider))return fr(`Unknown provider: "${n.provider}". Known: [${s.join(", ")}]`,!0);let o={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(o);return fr(XW(i))}catch(i){let a=D(i);return fr(`Error spawning worker: ${a}`,!0)}}async function nH(t,e){let r=_d(e),n=VI.parse(t);if(!n.worker_id){let o=r.listAll();return fr(eH(o))}let s=r.getStatus(n.worker_id);return s?fr(QW(s)):fr(`Worker not found: ${n.worker_id}`,!0)}async function sH(t,e){let r=_d(e),n=BI.parse(t),s=r.collect(n.worker_id);return s?fr(tH(s)):fr(`Worker not found: ${n.worker_id}`,!0)}async function oH(t,e){let r=_d(e),n=WI.parse(t);return r.stop(n.worker_id),fr(`Stop signal sent to worker: ${n.worker_id}`)}async function iH(t,e,r){try{switch(t){case"cli_worker_spawn":return await rH(e??{},r);case"cli_worker_status":return await nH(e??{},r);case"cli_worker_collect":return await sH(e??{},r);case"cli_worker_stop":return await oH(e??{},r);default:return fr(`Unknown tool: ${t}`,!0)}}catch(n){let s=D(n);return fr(`Error: ${s}`,!0)}}var Ty={};lt(Ty,{getTools:()=>aH,handleTool:()=>uH});var HI=y.object({design_doc:y.string().optional().describe("Optional design document path to verify against"),build_profile:y.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:y.number().int().positive().optional().describe("Timeout per command in milliseconds")}).strict();function aH(){return[{name:"qa_run",title:"Run Workspace QA",description:"Run vetted build/test QA profiles for the target workspace. Optionally includes a design document reference and returns a PASS/FAIL summary with captured output.",inputSchema:G(HI)}]}function cH(t){let e=`# Workspace QA
|
|
644
650
|
|
|
645
651
|
${t.summary}
|
|
646
652
|
`;return t.designDoc&&(e+=`
|
|
@@ -657,12 +663,12 @@ ${t.buildOutput||"(no output)"}
|
|
|
657
663
|
\`\`\`
|
|
658
664
|
${t.testOutput||"(no output)"}
|
|
659
665
|
\`\`\`
|
|
660
|
-
`,e}async function
|
|
666
|
+
`,e}async function uH(t,e,r){if(t==="qa_run"){let n=HI.parse(e??{}),o=await new bi(r?.workspaceBaseDir??process.cwd()).run({designDoc:n.design_doc,buildProfile:n.build_profile??"auto",timeoutMs:n.timeout_ms});return{content:[{type:"text",text:cH(o)}],isError:!(o.buildPassed&&o.testsPassed)}}else return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var JI=[Yg,yy,vy,_y,wy,Sy,$y,xy,ky,Ey,Ty];function GI(){let t=[];for(let e of JI)t.push(...e.getTools());return t}var rc=new Map,dH=100;function pH(t,e){if(rc.set(t,e),rc.size>dH){let r=rc.keys().next().value;r!==void 0&&rc.delete(r)}}function fH(t){return t.sessionId??"__default__"}function mH(t){for(let e of t)if(!(typeof e.uri!="string"||!e.uri.startsWith("file://")))try{return lH(e.uri)}catch{}}async function hH(t,e,r){let n=fH(r);try{let s=await t.listRoots(void 0,{timeout:1500}),o=mH(s.roots);if(o)return pH(n,o),o}catch{}return rc.get(n)??e.workspaceBaseDir??process.cwd()}function gH(t,e){return t.filter(r=>YI(r.name,e))}function yH(t,e){let r=Yr(t);if(r.invocation!=="cli"||!r.roles.includes("worker"))return!1;let n=e?.get(t.id)??"workspace-write";return hc(n)}function YI(t,e){let r=e.registry.getAvailable(),n=r.length>0,s=r.some(i=>i.type==="ollama"),o=r.some(i=>yH(i,e.providerPolicies));return t.startsWith("ollama_")?s:t.startsWith("cli_worker_")||t.startsWith("agent_changes_")?o&&e.cliWorkerManager!==void 0:t.startsWith("ai_")||t.startsWith("agent_debate_")||t==="agent_cross_validate"?n:!0}function vH(t,e){let r=[],n=0;for(let s of t){let o=Buffer.byteLength(s,"utf-8");if(n+o>e)break;r.push(s),n+=o}return r.join("")}var Iy=null;function _H(){if(Iy)return Iy;let t=new Map;for(let e of JI)for(let r of e.getTools())t.set(r.name,e);return Iy=t,t}function XI(t){let e=t.content.map(r=>r.type==="text"&&Buffer.byteLength(r.text,"utf-8")>51200?{type:"text",text:vH(r.text,51200)+`
|
|
661
667
|
|
|
662
|
-
... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function
|
|
668
|
+
... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function QI(t,e,r){let s=_H().get(t);if(!s)return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0};if(await r.ensureRuntimeReady?.(),!YI(t,r))return{content:[{type:"text",text:`Tool unavailable in current environment: ${t}`}],isError:!0};let o={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 s.handleTool(t,e,o);return XI(i)}function Ry(t){let e=new ql({name:"agestra",version:Ly},{capabilities:{tools:{}}});return e.setRequestHandler(gf,async()=>(await t.ensureRuntimeReady?.(),{tools:gH(GI(),t)})),e.setRequestHandler(Bi,async(r,n)=>{let{name:s,arguments:o}=r.params;try{await t.ensureRuntimeReady?.();let i=await hH(e,t,n),a=await t.resolveWorkspaceServices?.(i)??{},c=await QI(s,o??{},{...t,...a,workspaceBaseDir:i});return{content:c.content,isError:c.isError}}catch(i){return{content:[{type:"text",text:`Error: ${D(i)}`}],isError:!0}}}),e}async function Ay(t){let e=new Ul;await t.connect(e)}function eR(t){return typeof t=="object"&&t!==null&&t.type==="text"&&typeof t.text=="string"}function bH(t){return Array.isArray(t)?t.filter(eR).map(e=>e.text).join(`
|
|
663
669
|
|
|
664
|
-
`).trim():
|
|
665
|
-
`),e=
|
|
666
|
-
`),process.exit(1)}),t(`Starting MCP server with ${
|
|
667
|
-
`),process.exit(1)});export{
|
|
670
|
+
`).trim():eR(t)?t.text:""}function tR(t,e){let r=t?.[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function rR(t,e){let r=t?.[e];return typeof r=="string"&&r.length>0?r:void 0}function Qo(t){let e=t?.toLowerCase()??"";return e.includes("claude")?"claude-code":e.includes("codex")?"codex-cli":e.includes("gemini")?"gemini-cli":"unknown"}function Cy(t,e,r){let n=()=>Qo(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 s=n();return s!==r.expectedHostKind?{status:"error",message:`${r.displayName} host bridge requires a ${r.displayName} host, got ${s}`}:{status:"ok",message:`${r.displayName} host bridge available via ${t.getClientVersion()?.name??"unknown client"}`}},async runTurn(s){if(!this.isAvailable())throw new Error(r.unavailableMessage);let o=await t.createMessage({messages:[{role:"user",content:{type:"text",text:s.prompt}}],systemPrompt:s.system,includeContext:"none",maxTokens:tR(s.metadata,"maxTokens")??4096,temperature:tR(s.metadata,"temperature"),modelPreferences:rR(s.metadata,"model")?{hints:[{name:rR(s.metadata,"model")}]}:void 0,metadata:s.metadata}),i=bH(o.content);if(!i)throw new Error("Claude host bridge returned no text content");return{text:i,metadata:{model:o.model,stopReason:o.stopReason,hostKind:n()}}}}}function bd(t,e="claude"){return Cy(t,e,{expectedHostKind:"claude-code",displayName:"Claude",unavailableMessage:"Claude host bridge unavailable or client does not support sampling"})}function wd(t,e="codex-host"){return Cy(t,e,{expectedHostKind:"codex-cli",displayName:"Codex",unavailableMessage:"Codex host bridge unavailable or client does not support sampling"})}function Sd(t,e="gemini-host"){return Cy(t,e,{expectedHostKind:"gemini-cli",displayName:"Gemini",unavailableMessage:"Gemini host bridge unavailable or client does not support sampling"})}var wH=[{type:"claude-host",defaultId:"claude",supportedHosts:["claude-code"],createProvider:(t,e)=>new Cc({id:e,bridge:bd(t,e)})},{type:"codex-host",defaultId:"codex-host",supportedHosts:["codex-cli"],createProvider:(t,e)=>new Dc({id:e,bridge:wd(t,e)})},{type:"gemini-host",defaultId:"gemini-host",supportedHosts:["gemini-cli"],createProvider:(t,e)=>new Oc({id:e,bridge:Sd(t,e)})}];function ei(t,e,r){return t?.providers.find(s=>s.type===e||s.id===r)?.id??r}function SH(t){switch(t){case"claude-code":return"claude-host";case"codex-cli":return"codex-host";case"gemini-cli":return"gemini-host";default:return}}function $H(t){switch(t){case"claude-code":return"claude-cli";case"codex-cli":return"codex-cli";case"gemini-cli":return"gemini-cli";default:return}}function xH(t,e){switch(t){case"claude-code":return ei(e,"claude-host","claude");case"codex-cli":return ei(e,"codex-host","codex-host");case"gemini-cli":return ei(e,"gemini-host","gemini-host");default:return}}function PH(t,e){return t.some(s=>s.roles.includes("worker")&&s.supportsAutonomousExecution)?"team":t.some(s=>s.id!==e&&s.supportsReadOnlyChat)&&t.length>1?"debate":"claude-only"}function Dy(t,e){let r=()=>Qo(t.getClientVersion()?.name),n=()=>SH(r()),s=()=>xH(r(),e);return{get id(){return r()},get kind(){return r()},get leaderProviderId(){return s()},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 o=ei(e,"claude-host","claude");return bd(t,o)}case"codex-cli":{let o=ei(e,"codex-host","codex-host");return wd(t,o)}case"gemini-cli":{let o=ei(e,"gemini-host","gemini-host");return Sd(t,o)}default:return null}},createHostProviders(){let o=r();return wH.flatMap(i=>{if(o==="unknown"||!i.supportedHosts.includes(o))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??Mr(i.type),provider:i.createProvider(t,c)}]})},createSessionContext(o){let i=o.filter(l=>l.supportsReadOnlyChat);if(i.length===0)return;let a=s(),c=$H(r()),u=(a?i.find(l=>l.id===a):void 0)??(n()?i.find(l=>l.type===n()):void 0)??(c?i.find(l=>l.type===c):void 0)??i.find(l=>l.roles.includes("leader"))??i[0];return{hostId:r(),hostKind:r(),leaderProviderId:u.id,participantProviderIds:i.map(l=>l.id),executionMode:PH(i,u.id)}}}}async function Oy(t,e,r,n){let s=t.createHostProviders();for(let o of s)e.has(o.id)||(await o.provider.initialize(),e.register(o.provider),r.set(o.id,o.executionPolicy),n(`Registered provider: ${o.id} (${o.type})`))}function zy(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 nR}from"fs";import{dirname as oR,join as $d,resolve as iR,sep as kH}from"path";import{fileURLToPath as EH}from"url";var TH=[$d(".claude","plugins","cache"),$d(".claude","plugins","local")];function IH(t){let e=t.split(/[\\/]/).join(kH);return TH.some(r=>e.includes(r))}function RH(t){return!(!nR($d(t,"package.json"))||!nR($d(t,"AGENTS.md"))||IH(t))}function sR(t){let e=iR(t);for(;;){if(RH(e))return e;let r=oR(e);if(r===e)return null;e=r}}function aR(){let t=process.env.AGESTRA_BASE_DIR?.trim();if(t)return iR(t);let e=oR(EH(import.meta.url));return sR(process.cwd())??sR(e)??process.cwd()}function DH(t){return{ollama:e=>new Jn({id:e.id,host:e.config?.host||ri}),"gemini-cli":e=>new Gn({id:e.id,timeout:e.config?.timeout,workspaceBaseDir:t}),"codex-cli":e=>new Yn({id:e.id,timeout:e.config?.timeout,workspaceBaseDir:t}),"claude-cli":e=>new Xn({id:e.id,timeout:e.config?.timeout,workspaceBaseDir:t})}}async function OH(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:s}=await Xo({workspaceBaseDir:e}),o=n.filter(i=>i.available);return o.length===0?(r("Auto-detect found no available providers."),{detected:0}):(DI(s,t),r(`Auto-detected ${o.length} provider(s): ${o.map(i=>i.id).join(", ")}`),{detected:o.length})}catch(n){return r(`Auto-detect failed (non-fatal): ${D(n)}`),{detected:0}}}function zH(t,e){return t===null&&e===0}async function MH(){let t=k=>process.stderr.write(`[mcp-server] ${k}
|
|
671
|
+
`),e=aR(),r=ci(),n;try{let k=AH(r,"utf-8");n=JSON.parse(k)}catch(k){t(`Warning: Could not load ${r}: ${D(k)}`),t("Starting with empty provider registry."),n=null}let s=new uc,o=null;if(n)try{o=gv(n)}catch(k){t(`Warning: Invalid provider config in ${r}: ${D(k)}`),t("Ignoring config and continuing with auto-detect defaults."),n=null}let i=DH(e);if(o){let k=o.enabledProviders.map(L=>{let q=i[L.type];if(!q)return t(`Unknown provider type: ${L.type} (id: ${L.id}), skipping`),null;let $e=q(L);return{pc:L,provider:$e}}).filter(L=>L!==null),O=await Promise.allSettled(k.map(async({pc:L,provider:q})=>(await q.initialize(),{pc:L,provider:q})));for(let L of O)if(L.status==="fulfilled"){let{pc:q,provider:$e}=L.value;s.register($e),t(`Registered provider: ${q.id} (${q.type})`)}else t(`Failed to initialize provider: ${D(L.reason)}`)}if(zH(o,s.getAll().length)?await OH(s,e,t):o&&s.getAll().length===0&&t("Provider config present but no configured providers initialized; skipping auto-detect."),o){let k=new Set(o.providers.filter(L=>!L.enabled).map(L=>L.id)),O=new Set(o.providers.filter(L=>!L.enabled).map(L=>L.type));try{let{providers:L}=await Xo({workspaceBaseDir:e}),q=by(L,s,{excludeIds:k,excludeTypes:O});for(let $e of q)t(`Registered newly detected provider: ${$e.id} (${$e.type})`)}catch(L){t(`Supplemental provider detection failed (non-fatal): ${D(L)}`)}}let a=new Map(o?.providers.map(k=>[k.id,k.executionPolicy])??[]),c=new Map(s.getAll().map(k=>[k.id,a.get(k.id)??Mr(k.type)])),u;try{u=rp(o?.locale)}catch(k){let O=k instanceof Error?k.message:String(k);t(`[i18n] failed to load requested locale (${o?.locale??"default"}): ${O}. Retrying with default bundle.`),u=rp(void 0)}t(`Localization active: ${u.locale}`);let l=new Map,d=()=>"unknown",p=async()=>{},f=async k=>{let O=d(),L=l.get(k);if(L){if(L.hostKind===O)return L;L.traceWriter.shutdown()}let q=new yi(My(k,Vy)),$e=new $i(My(k,ni)),He=new xc(k,{completionHandler:async({descriptor:mr,result:xd,saveAsDocument:Pd})=>!xd.output||xd.output.trim().length===0?null:{documentId:(await $e.createDocument({title:Pd.title,content:xd.output,metadata:{...Pd.metadata,Provider:mr.provider,Model:mr.provider,JobId:mr.id},kind:Pd.kind})).id}});try{let mr=He.reconcileOrphans();mr>0&&t(`Reconciled ${mr} orphaned job(s) in ${k}`)}catch(mr){t(`Job orphan reconcile failed for ${k}: ${D(mr)}`)}let Rt=new Pc(k);Rt.cleanup(30);let Mt=new Rc(Rt,{ttlMs:6e4}),Ny=new mi(k,{providerPolicies:c}),ks=new Jo(My(k,ni));try{await ks.hydrateFromDisk()}catch(mr){t(`Structured session registry hydrate failed for ${k}: ${D(mr)}`)}let At=fd(s,O,k),kn=new Go({bridge:At,documentManager:$e,registry:ks,i18n:u,traceWriter:Rt}),ti={hostKind:O,sessionManager:q,documentManager:$e,jobManager:He,traceWriter:Rt,qualityStatsProvider:Mt,cliWorkerManager:Ny,structuredSessionRegistry:ks,moderatorEngine:kn};return l.set(k,ti),ti},m=await f(e),h={registry:s,...m,providerPolicies:c,workspaceBaseDir:e,ensureRuntimeReady:()=>p(),resolveWorkspaceServices:async k=>(await p(),f(k)),i18n:u},v=Ry(h),g=Dy(v,o);d=()=>Qo(v.getClientVersion()?.name);let b,_=null;p=async()=>{let k=d();k==="unknown"||b===k||(_||(_=(async()=>{try{await Oy(g,s,c,t),b=k}catch(O){t(`Host-backed provider registration failed (non-fatal): ${D(O)}`)}finally{_=null}})()),await _)},h.resolveSessionContext=()=>zy(g,s);let P=setInterval(()=>{(async()=>{for(let k of l.values())try{let O=await k.structuredSessionRegistry.sweepTimeouts();O.length>0&&await k.moderatorEngine.handleTimedOutSnapshots(O)}catch(O){t(`Session sweep failed: ${D(O)}`)}})()},Qy);P.unref?.();let x=!1,j=async()=>{if(!x){x=!0,t("Shutting down..."),clearInterval(P);for(let k of l.values())k.traceWriter.shutdown();for(let k of s.getAll())if(k.shutdown)try{await k.shutdown()}catch{}}};process.on("SIGTERM",()=>{j().finally(()=>process.exit(0))}),process.on("SIGINT",()=>{j().finally(()=>process.exit(0))}),process.on("uncaughtException",k=>{for(let O of l.values())O.traceWriter.panicFlush();process.stderr.write(`[mcp-server] Uncaught: ${k}
|
|
672
|
+
`),process.exit(1)}),t(`Starting MCP server with ${s.getAll().length} provider(s)...`),await Ay(v),t("MCP server connected via stdio.")}var NH=(()=>{if(typeof process>"u"||!process.argv[1])return!1;try{let t=CH(import.meta.url),e=process.argv[1];return e===t||e.endsWith("/dist/bundle.js")}catch{return!1}})();NH&&MH().catch(t=>{process.stderr.write(`[mcp-server] Fatal: ${t}
|
|
673
|
+
`),process.exit(1)});export{OH as autoDetectIfNeeded,GI as collectTools,Ay as connectStdio,bd as createClaudeLeaderBridge,wd as createCodexLeaderBridge,Sd as createGeminiLeaderBridge,Dy as createRuntimeHostAdapter,Ry as createServer,QI as dispatch,Qo as inferHostKindFromClientName,Oy as registerHostBackedProviders,zy as resolveSessionContext,zH as shouldRunStartupAutoDetect,XI as truncateResponse};
|
|
668
674
|
//# sourceMappingURL=bundle.js.map
|