agestra 4.13.2 → 4.13.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 +10 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.ja.md +102 -59
- package/README.ko.md +74 -20
- package/README.md +70 -16
- package/README.zh.md +105 -62
- package/agents/agestra-moderator.md +8 -8
- package/agents/agestra-team-lead.md +90 -35
- package/commands/design.md +1 -1
- package/commands/idea.md +2 -2
- package/commands/implement.md +5 -4
- package/commands/qa.md +3 -2
- package/commands/review.md +4 -2
- package/commands/security.md +2 -1
- package/dist/bundle.js +189 -180
- package/hooks/user-prompt-submit.js +2 -2
- package/package.json +9 -3
- package/skills/design.md +1 -1
- package/skills/idea.md +1 -1
- package/skills/provider-guide.md +8 -8
- package/skills/review.md +1 -1
package/dist/bundle.js
CHANGED
|
@@ -1,69 +1,69 @@
|
|
|
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{_C(a)}catch{}try{Mv(t)}catch{}}}var xC,PC,kC,Vd,bc=Ar(()=>{"use strict";xC=3e4,PC=5e3,kC=10,Vd=class extends Error{constructor(e,r){super(`withFileLock: timed out after ${r}ms waiting for ${e}`),this.name="FileLockTimeoutError"}}});import{existsSync as zv,realpathSync as TC}from"fs";import{basename as IC,dirname as RC,isAbsolute as Hd,join as AC,normalize as Nv,resolve as Wd,relative as CC}from"path";function DC(t){return t===""||!t.startsWith("..")&&!Hd(t)}function Bd(t){let e=[],r=Wd(t);for(;!zv(r);){let s=RC(r);if(s===r)break;e.unshift(IC(r)),r=s}let n=zv(r)?TC(r):r;return e.reduce((s,o)=>AC(s,o),n)}function Lv(t,e){let r=Bd(e),n=Bd(t),s=CC(r,n);return DC(s)}function Kd(t,e){let r=Wd(e,t);return Lv(r,e)}function Ft(t,e){let r=Wd(e,t);if(!Lv(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 sn(t,e){if(Hd(t)){let r=Nv(t);if(!Kd(r,e))throw new Error(`Read path outside base directory: ${t} is not within ${e}`);return r}return Ft(t,e)}function qv(t,e){return Hd(t)?Bd(Nv(t)):Ft(t,e)}function Nr(t){return OC.test(t)}function wc(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(!jv.has(t))throw new Ct(t,`command is not in the allowlist (${[...jv].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 OC,jv,MC,Ct,Vs=Ar(()=>{"use strict";OC=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;jv=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 zC}from"fs";import{join as jC}from"path";function Ve(t,e){let r=jC(t,"status.json"),n=`${r}.lock`;Kn(n,()=>{let s=JSON.parse(zC(r,"utf-8"));Ze(r,{...s,...e})})}var fi=Ar(()=>{"use strict";nn();bc()});import{spawn as NC}from"child_process";import{join as Jd}from"path";function Fv(t){let e=t.replace(/\s+/g," ").trim();return e.length>200?`${e.slice(0,200)}...`:e}function Sc(t){return new Promise(e=>{let r=An(t.command,t.args),n={kind:"start",updatedAt:new Date().toISOString(),message:"CLI process started",command:r.command,timeoutMs:t.timeoutMs,stdoutBytes:0,stderrBytes:0},s=0,o,i=(y,g={})=>{Object.assign(n,y,{updatedAt:new Date().toISOString()});let b=Date.now(),_=n.kind!==o;if(!(!g.force&&!_&&b-s<LC))try{Ve(t.jobDir,{activity:{...n}}),s=b,o=n.kind}catch{}};i(n,{force:!0});let a=NC(r.command,r.args,{cwd:t.cwd,stdio:["ignore","pipe","pipe"],windowsHide:!0});if(t.recordPid&&typeof a.pid=="number"&&a.pid>0)try{Ve(t.jobDir,{pid:a.pid})}catch{}if(!a.stdout||!a.stderr){try{a.kill()}catch{}try{ge(Jd(t.jobDir,"error.txt"),"Worker stdout/stderr streams unavailable (pipe allocation failed)"),Ve(t.jobDir,{state:"error",completedAt:new Date().toISOString()})}catch{}e();return}let c="",u="",l=0,d=0,p=!1,f=!1;a.stdout.on("data",y=>{l+=y.length,i({kind:"stdout",message:"stdout received",stdoutBytes:l,stderrBytes:d,lastStdoutPreview:Fv(y.toString())}),l<=10485760?c+=y.toString():p||(p=!0,Qt(a))}),a.stderr.on("data",y=>{d+=y.length,i({kind:"stderr",message:"stderr received",stdoutBytes:l,stderrBytes:d,lastStderrPreview:Fv(y.toString())}),d<=10485760&&(u+=y.toString())});let m=(y,g)=>{if(!f){f=!0,clearTimeout(h);try{ge(Jd(t.jobDir,"output.txt"),c),ge(Jd(t.jobDir,"error.txt"),g!==void 0?g:u),Ve(t.jobDir,y)}catch{}e()}},h=setTimeout(()=>{Qt(a),i({kind:"timeout",message:`timed out after ${t.timeoutMs}ms`,timeoutMs:t.timeoutMs,stdoutBytes:l,stderrBytes:d},{force:!0}),m({state:"timed_out",completedAt:new Date().toISOString()})},t.timeoutMs);a.on("close",y=>{if(f)return;let g=c.trim().length>0,b=y===0||g?"completed":"error";i({kind:"close",message:"CLI process closed",exitCode:y??1,stdoutBytes:l,stderrBytes:d},{force:!0}),m({state:b,exitCode:y??1,completedAt:new Date().toISOString()})}),a.on("error",y=>{if(f)return;let g=y.code==="ENOENT"?"missing_cli":"error";i({kind:"close",message:`CLI spawn error: ${y.message}`,stdoutBytes:l,stderrBytes:d},{force:!0}),m({state:g,completedAt:new Date().toISOString()},y.message)})})}var LC,Gd=Ar(()=>{"use strict";nn();ii();Os();fi();LC=1e3});var Bv={};rt(Bv,{CLI_PROVIDERS:()=>Zv,resolveCliConfig:()=>Vv});import{readFileSync as Uv}from"fs";import{join as Jn}from"path";function Vv(t){let e=qC[t.provider]??t.provider;return Zv[e]??null}async function FC(){let t=process.argv[2];t||process.exit(1);let e;try{e=JSON.parse(Uv(Jn(t,"job.json"),"utf-8"))}catch{try{Ze(Jn(t,"status.json"),{id:"unknown",state:"error",provider:"unknown",completedAt:new Date().toISOString()}),ge(Jn(t,"error.txt"),"Failed to read job.json")}catch{}process.exit(1)}let r=Vv(e);r||(Ve(t,{state:"missing_cli",completedAt:new Date().toISOString()}),ge(Jn(t,"error.txt"),`No CLI mapping for provider: ${e.provider}`),process.exit(1));let{command:n,buildArgs:s}=r;Ve(t,{state:"running",startedAt:new Date().toISOString()});let o=Uv(Jn(t,"prompt.txt"),"utf-8"),i=s(o);try{wc(n,i)}catch(c){let u=c instanceof Ct?c.message:`Argv rejected: ${c.message}`;Ve(t,{state:"error",completedAt:new Date().toISOString()}),ge(Jn(t,"error.txt"),u);return}let a;if(e.cwd)try{a=Ft(e.cwd,process.cwd())}catch(c){Ve(t,{state:"error",completedAt:new Date().toISOString()}),ge(Jn(t,"error.txt"),`Rejected descriptor.cwd: ${c.message}`);return}await Sc({jobDir:t,command:n,args:i,cwd:a,timeoutMs:e.timeout,recordPid:!1})}var qC,Zv,UC,Hv=Ar(()=>{"use strict";nn();Vs();Gd();fi();qC={"gemini-cli":"gemini","codex-cli":"codex","claude-cli":"claude"},Zv={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]}};UC=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");UC&&FC().catch(()=>process.exit(1))});var Qi=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 Yi=class{};me._CodeOrName=Yi;me.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ss=class extends Yi{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=ss;var Bt=class extends Yi{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 ss&&(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;)Df(r,e[n]),r.push(t[++n]);return new Bt(r)}me._=Q$;var Cf=new Bt("+");function ex(t,...e){let r=[Xi(t[0])],n=0;for(;n<e.length;)r.push(Cf),Df(r,e[n]),r.push(Cf,Xi(t[++n]));return Bj(r),new Bt(r)}me.str=ex;function Df(t,e){e instanceof Bt?t.push(...e._items):e instanceof ss?t.push(e):t.push(Kj(e))}me.addCodeArg=Df;function Bj(t){let e=1;for(;e<t.length-1;){if(t[e]===Cf){let r=Hj(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Hj(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof ss||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 ss))return`"${t}${e.slice(1)}`}function Wj(t,e){return e.emptyStr()?t:t.emptyStr()?e:ex`${t}${e}`}me.strConcat=Wj;function Kj(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Xi(Array.isArray(t)?t.join(","):t)}function Jj(t){return new Bt(Xi(t))}me.stringify=Jj;function Xi(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}me.safeStringify=Xi;function Gj(t){return typeof t=="string"&&me.IDENTIFIER.test(t)?new Bt(`.${t}`):Q$`[${t}]`}me.getProperty=Gj;function Yj(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=Yj;function Xj(t){return new Bt(t.toString())}me.regexpCode=Xj});var zf=S($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.ValueScope=$t.ValueScopeName=$t.Scope=$t.varKinds=$t.UsedValueState=void 0;var St=Qi(),Of=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Iu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Iu||($t.UsedValueState=Iu={}));$t.varKinds={const:new St.Name("const"),let:new St.Name("let"),var:new St.Name("var")};var Ru=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=Ru;var Au=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=Au;var Qj=(0,St._)`\n`,Mf=class extends Ru{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Qj:St.nil}}get(){return this._scope}name(e){return new Au(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,Iu.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 Of(u);c.set(u,Iu.Completed)})}return o}};$t.ValueScope=Mf});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=Qi(),sr=zf(),dn=Qi();Object.defineProperty(Q,"_",{enumerable:!0,get:function(){return dn._}});Object.defineProperty(Q,"str",{enumerable:!0,get:function(){return dn.str}});Object.defineProperty(Q,"strConcat",{enumerable:!0,get:function(){return dn.strConcat}});Object.defineProperty(Q,"nil",{enumerable:!0,get:function(){return dn.nil}});Object.defineProperty(Q,"getProperty",{enumerable:!0,get:function(){return dn.getProperty}});Object.defineProperty(Q,"stringify",{enumerable:!0,get:function(){return dn.stringify}});Object.defineProperty(Q,"regexpCode",{enumerable:!0,get:function(){return dn.regexpCode}});Object.defineProperty(Q,"Name",{enumerable:!0,get:function(){return dn.Name}});var Mu=zf();Object.defineProperty(Q,"Scope",{enumerable:!0,get:function(){return Mu.Scope}});Object.defineProperty(Q,"ValueScope",{enumerable:!0,get:function(){return Mu.ValueScope}});Object.defineProperty(Q,"ValueScopeName",{enumerable:!0,get:function(){return Mu.ValueScopeName}});Object.defineProperty(Q,"varKinds",{enumerable:!0,get:function(){return Mu.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 Fr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},jf=class extends Fr{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=go(this.rhs,e,r)),this}get names(){return this.rhs instanceof ce._CodeOrName?this.rhs.names:{}}},Cu=class extends Fr{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=go(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ce.Name?{}:{...this.lhs.names};return Ou(e,this.rhs)}},Nf=class extends Cu{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Lf=class extends Fr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},qf=class extends Fr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ff=class extends Fr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Uf=class extends Fr{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=go(this.code,e,r),this}get names(){return this.code instanceof ce._CodeOrName?this.code.names:{}}},ea=class extends Fr{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)||(eN(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>as(e,r.names),{})}},Ur=class extends ea{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Zf=class extends ea{},ho=class extends Ur{};ho.kind="else";var os=class t extends Ur{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 ho(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(tx(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=go(this.condition,e,r),this}get names(){let e=super.names;return Ou(e,this.condition),this.else&&as(e,this.else.names),e}};os.kind="if";var is=class extends Ur{};is.kind="for";var Vf=class extends is{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=go(this.iteration,e,r),this}get names(){return as(super.names,this.iteration.names)}},Bf=class extends is{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=Ou(super.names,this.from);return Ou(e,this.to)}},Du=class extends is{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=go(this.iterable,e,r),this}get names(){return as(super.names,this.iterable.names)}},ta=class extends Ur{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 ra=class extends ea{render(e){return"return "+super.render(e)}};ra.kind="return";var Hf=class extends Ur{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&&as(e,this.catch.names),this.finally&&as(e,this.finally.names),e}},na=class extends Ur{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};na.kind="catch";var sa=class extends Ur{render(e){return"finally"+super.render(e)}};sa.kind="finally";var Wf=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 Zf]}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 jf(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 Cu(e,r,n))}add(e,r){return this._leafNode(new Nf(e,Q.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ce.nil&&this._leafNode(new Uf(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 os(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 os(e))}else(){return this._elseNode(new ho)}endIf(){return this._endBlockNode(os,ho)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Vf(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 Bf(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 Du("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 Du("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(is)}label(e){return this._leafNode(new Lf(e))}break(e){return this._leafNode(new qf(e))}return(e){let r=new ra;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ra)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Hf;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new na(o),r(o)}return n&&(this._currNode=s.finally=new sa,this.code(n)),this._endBlockNode(na,sa)}throw(e){return this._leafNode(new Ff(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 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 os))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=Wf;function as(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ou(t,e){return e instanceof ce._CodeOrName?as(t,e.names):t}function go(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 eN(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function tx(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ce._)`!${Kf(t)}`}Q.not=tx;var tN=rx(Q.operators.AND);function rN(...t){return t.reduce(tN)}Q.and=rN;var nN=rx(Q.operators.OR);function sN(...t){return t.reduce(nN)}Q.or=sN;function rx(t){return(e,r)=>e===ce.nil?r:r===ce.nil?e:(0,ce._)`${Kf(e)} ${t} ${Kf(r)}`}function Kf(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(),oN=Qi();function iN(t){let e={};for(let r of t)e[r]=!0;return e}re.toHash=iN;function aN(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ox(t,e),!ix(e,t.self.RULES.all))}re.alwaysValidSchema=aN;function ox(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]||ux(t,`unknown keyword: "${o}"`)}re.checkUnknownRules=ox;function ix(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}re.schemaHasRules=ix;function cN(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=cN;function uN({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=uN;function lN(t){return ax(decodeURIComponent(t))}re.unescapeFragment=lN;function dN(t){return encodeURIComponent(Gf(t))}re.escapeFragment=dN;function Gf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=Gf;function ax(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=ax;function pN(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}re.eachItem=pN;function nx({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:nx({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} || {}`),Yf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:cx}),items:nx({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 cx(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,we._)`{}`);return e!==void 0&&Yf(t,r,e),r}re.evaluatedPropsToName=cx;function Yf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,we._)`${e}${(0,we.getProperty)(n)}`,!0))}re.setEvaluated=Yf;var sx={};function fN(t,e){return t.scopeValue("func",{ref:e,code:sx[e.code]||(sx[e.code]=new oN._Code(e.code))})}re.useFunc=fN;var Jf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Jf||(re.Type=Jf={}));function mN(t,e,r){if(t instanceof we.Name){let n=e===Jf.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():"/"+Gf(t)}re.getErrorPath=mN;function ux(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=ux});var Zr=S(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var ot=te(),hN={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")};Xf.default=hN});var oa=S(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.extendErrors=it.resetErrorsCount=it.reportExtraError=it.reportError=it.keyword$DataError=it.keywordError=void 0;var de=te(),zu=le(),mt=Zr();it.keywordError={message:({keyword:t})=>(0,de.str)`must pass "${t}" keyword validation`};it.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 gN(t,e=it.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=px(t,e,r);n??(i||a)?lx(o,c):dx(s,(0,de._)`[${c}]`)}it.reportError=gN;function yN(t,e=it.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=px(t,e,r);lx(s,a),o||i||dx(n,mt.default.vErrors)}it.reportExtraError=yN;function vN(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)))}it.resetErrorsCount=vN;function _N({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))})}it.extendErrors=_N;function lx(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 dx(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 cs={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 px(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,de._)`{}`:bN(t,e,r)}function bN(t,e,r={}){let{gen:n,it:s}=t,o=[wN(s,r),SN(t,r)];return $N(t,e,o),n.object(...o)}function wN({errorPath:t},{instancePath:e}){let r=e?(0,de.str)`${t}${(0,zu.getErrorPath)(e,zu.Type.Str)}`:t;return[mt.default.instancePath,(0,de.strConcat)(mt.default.instancePath,r)]}function SN({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,zu.getErrorPath)(r,zu.Type.Str)}`),[cs.schemaPath,s]}function $N(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([cs.keyword,s],[cs.params,typeof e=="function"?e(t):e||(0,de._)`{}`]),c.messages&&n.push([cs.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([cs.schema,i],[cs.parentSchema,(0,de._)`${l}${d}`],[mt.default.data,o]),u&&n.push([cs.propertyName,u])}});var mx=S(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.boolOrEmptySchema=yo.topBoolOrEmptySchema=void 0;var xN=oa(),PN=te(),kN=Zr(),EN={message:"boolean schema is false"};function TN(t){let{gen:e,schema:r,validateName:n}=t;r===!1?fx(t,!1):typeof r=="object"&&r.$async===!0?e.return(kN.default.data):(e.assign((0,PN._)`${n}.errors`,null),e.return(!0))}yo.topBoolOrEmptySchema=TN;function IN(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),fx(t)):r.var(e,!0)}yo.boolOrEmptySchema=IN;function fx(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,xN.reportError)(s,EN,void 0,e)}});var Qf=S(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.getRules=vo.isJSONType=void 0;var RN=["string","number","integer","boolean","null","object","array"],AN=new Set(RN);function CN(t){return typeof t=="string"&&AN.has(t)}vo.isJSONType=CN;function DN(){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:{}}}vo.getRules=DN});var em=S(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.shouldUseRule=pn.shouldUseGroup=pn.schemaHasRulesForType=void 0;function ON({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&hx(t,n)}pn.schemaHasRulesForType=ON;function hx(t,e){return e.rules.some(r=>gx(t,r))}pn.shouldUseGroup=hx;function gx(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))}pn.shouldUseRule=gx});var ia=S(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.reportTypeError=at.checkDataTypes=at.checkDataType=at.coerceAndCheckDataType=at.getJSONTypes=at.getSchemaTypes=at.DataType=void 0;var MN=Qf(),zN=em(),jN=oa(),K=te(),yx=le(),_o;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(_o||(at.DataType=_o={}));function NN(t){let e=vx(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}at.getSchemaTypes=NN;function vx(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(MN.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}at.getJSONTypes=vx;function LN(t,e){let{gen:r,data:n,opts:s}=t,o=qN(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,zN.schemaHasRulesForType)(t,e[0]));if(i){let a=rm(e,n,s.strictNumbers,_o.Wrong);r.if(a,()=>{o.length?FN(t,e,o):nm(t)})}return i}at.coerceAndCheckDataType=LN;var _x=new Set(["string","number","integer","boolean","null"]);function qN(t,e){return e?t.filter(r=>_x.has(r)||e==="array"&&r==="array"):[]}function FN(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(rm(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,K._)`${a} !== undefined`);for(let u of r)(_x.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),nm(t),n.endIf(),n.if((0,K._)`${a} !== undefined`,()=>{n.assign(s,a),UN(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 UN({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,K._)`${e} !== undefined`,()=>t.assign((0,K._)`${e}[${r}]`,n))}function tm(t,e,r,n=_o.Correct){let s=n===_o.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===_o.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)}}at.checkDataType=tm;function rm(t,e,r,n){if(t.length===1)return tm(t[0],e,r,n);let s,o=(0,yx.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,tm(i,e,r,n));return s}at.checkDataTypes=rm;var ZN={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,K._)`{type: ${t}}`:(0,K._)`{type: ${e}}`};function nm(t){let e=VN(t);(0,jN.reportError)(e,ZN)}at.reportTypeError=nm;function VN(t){let{gen:e,data:r,schema:n}=t,s=(0,yx.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var wx=S(ju=>{"use strict";Object.defineProperty(ju,"__esModule",{value:!0});ju.assignDefaults=void 0;var bo=te(),BN=le();function HN(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)bx(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>bx(t,o,s.default))}ju.assignDefaults=HN;function bx(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,bo._)`${o}${(0,bo.getProperty)(e)}`;if(s){(0,BN.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,bo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,bo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,bo._)`${a} = ${(0,bo.stringify)(r)}`)}});var Ht=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(),sm=le(),fn=Zr(),WN=le();function KN(t,e){let{gen:r,data:n,it:s}=t;r.if(im(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Re._)`${e}`},!0),t.error()})}_e.checkReportMissingProp=KN;function JN({gen:t,data:e,it:{opts:r}},n,s){return(0,Re.or)(...n.map(o=>(0,Re.and)(im(t,e,o,r.ownProperties),(0,Re._)`${s} = ${o}`)))}_e.checkMissingProp=JN;function GN(t,e){t.setParams({missingProperty:e},!0),t.error()}_e.reportMissingProp=GN;function Sx(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Re._)`Object.prototype.hasOwnProperty`})}_e.hasPropFunc=Sx;function om(t,e,r){return(0,Re._)`${Sx(t)}.call(${e}, ${r})`}_e.isOwnProperty=om;function YN(t,e,r,n){let s=(0,Re._)`${e}${(0,Re.getProperty)(r)} !== undefined`;return n?(0,Re._)`${s} && ${om(t,e,r)}`:s}_e.propertyInData=YN;function im(t,e,r,n){let s=(0,Re._)`${e}${(0,Re.getProperty)(r)} === undefined`;return n?(0,Re.or)(s,(0,Re.not)(om(t,e,r))):s}_e.noPropertyInData=im;function $x(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}_e.allSchemaProperties=$x;function XN(t,e){return $x(e).filter(r=>!(0,sm.alwaysValidSchema)(t,e[r]))}_e.schemaProperties=XN;function QN({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=[[fn.default.instancePath,(0,Re.strConcat)(fn.default.instancePath,o)],[fn.default.parentData,i.parentData],[fn.default.parentDataProperty,i.parentDataProperty],[fn.default.rootData,fn.default.rootData]];i.opts.dynamicRef&&d.push([fn.default.dynamicAnchors,fn.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=QN;var e1=(0,Re._)`new RegExp`;function t1({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"?e1:(0,WN.useFunc)(t,s)}(${r}, ${n})`})}_e.usePattern=t1;function r1(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:sm.Type.Num},o),e.if((0,Re.not)(o),a)})}}_e.validateArray=r1;function n1(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,sm.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=n1});var kx=S(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.validateKeywordUsage=wr.validSchemaType=wr.funcKeywordCode=wr.macroKeywordCode=void 0;var ht=te(),us=Zr(),s1=Ht(),o1=oa();function i1(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=i1;function a1(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;u1(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&&xx(t),y(()=>t.error());else{let g=e.async?f():m();e.modifying&&xx(t),y(()=>c1(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?us.default.this:us.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ht._)`${g}${(0,s1.callValidateCode)(t,l,b,_)}`,e.modifying)}function y(g){var b;n.if((0,ht.not)((b=e.valid)!==null&&b!==void 0?b:d),g)}}wr.funcKeywordCode=a1;function xx(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ht._)`${n.parentData}[${n.parentDataProperty}]`))}function c1(t,e){let{gen:r}=t;r.if((0,ht._)`Array.isArray(${e})`,()=>{r.assign(us.default.vErrors,(0,ht._)`${us.default.vErrors} === null ? ${e} : ${us.default.vErrors}.concat(${e})`).assign(us.default.errors,(0,ht._)`${us.default.vErrors}.length`),(0,o1.extendErrors)(t)},()=>t.error())}function u1({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 l1(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=l1;function d1({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=d1});var Tx=S(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.extendSubschemaMode=mn.extendSubschemaData=mn.getSubschema=void 0;var Sr=te(),Ex=le();function p1(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,Ex.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')}mn.getSubschema=p1;function f1(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,Ex.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]}}mn.extendSubschemaData=f1;function m1(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}mn.extendSubschemaMode=m1});var aa=S((v7,Ix)=>{"use strict";Ix.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 Ax=S((_7,Rx)=>{"use strict";var hn=Rx.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(){};Nu(e,n,s,t,"",t)};hn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};hn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};hn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};hn.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 Nu(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 hn.arrayKeywords)for(var p=0;p<d.length;p++)Nu(t,e,r,d[p],s+"/"+l+"/"+p,o,s,l,n,p)}else if(l in hn.propsKeywords){if(d&&typeof d=="object")for(var f in d)Nu(t,e,r,d[f],s+"/"+l+"/"+h1(f),o,s,l,n,f)}else(l in hn.keywords||t.allKeys&&!(l in hn.skipKeywords))&&Nu(t,e,r,d,s+"/"+l,o,s,l,n)}r(n,s,o,i,a,c,u)}}function h1(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ca=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 g1=le(),y1=aa(),v1=Ax(),_1=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function b1(t,e=!0){return typeof t=="boolean"?!0:e===!0?!am(t):e?Cx(t)<=e:!1}xt.inlineRef=b1;var w1=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function am(t){for(let e in t){if(w1.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(am)||typeof r=="object"&&am(r))return!0}return!1}function Cx(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!_1.has(r)&&(typeof t[r]=="object"&&(0,g1.eachItem)(t[r],n=>e+=Cx(n)),e===1/0))return 1/0}return e}function Dx(t,e="",r){r!==!1&&(e=wo(e));let n=t.parse(e);return Ox(t,n)}xt.getFullPath=Dx;function Ox(t,e){return t.serialize(e).split("#")[0]+"#"}xt._getFullPath=Ox;var S1=/#\/?$/;function wo(t){return t?t.replace(S1,""):""}xt.normalizeId=wo;function $1(t,e,r){return r=wo(r),t.resolve(e,r)}xt.resolveUrl=$1;var x1=/^[a-z_][-a-z0-9._]*$/i;function P1(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=wo(t[r]||e),o={"":s},i=Dx(n,s,!1),a={},c=new Set;return v1(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=i+p,y=o[m];typeof d[r]=="string"&&(y=g.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),o[p]=y;function g(_){let P=this.opts.uriResolver.resolve;if(_=wo(y?P(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,_):_!==wo(h)&&(_[0]==="#"?(u(d,a[_],_),a[_]=d):this.refs[_]=h),_}function b(_){if(typeof _=="string"){if(!x1.test(_))throw new Error(`invalid anchor "${_}"`);g.call(this,`#${_}`)}}}),a;function u(d,p,f){if(p!==void 0&&!y1(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}xt.getSchemaRefs=P1});var da=S(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.getData=gn.KeywordCxt=gn.validateFunctionCode=void 0;var Lx=mx(),Mx=ia(),um=em(),Lu=ia(),k1=wx(),la=kx(),cm=Tx(),z=te(),V=Zr(),E1=ca(),Vr=le(),ua=oa();function T1(t){if(Ux(t)&&(Zx(t),Fx(t))){A1(t);return}qx(t,()=>(0,Lx.topBoolOrEmptySchema)(t))}gn.validateFunctionCode=T1;function qx({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,z._)`${V.default.data}, ${V.default.valCxt}`,n.$async,()=>{t.code((0,z._)`"use strict"; ${zx(r,s)}`),R1(t,s),t.code(o)}):t.func(e,(0,z._)`${V.default.data}, ${I1(s)}`,n.$async,()=>t.code(zx(r,s)).code(o))}function I1(t){return(0,z._)`{${V.default.instancePath}="", ${V.default.parentData}, ${V.default.parentDataProperty}, ${V.default.rootData}=${V.default.data}${t.dynamicRef?(0,z._)`, ${V.default.dynamicAnchors}={}`:z.nil}}={}`}function R1(t,e){t.if(V.default.valCxt,()=>{t.var(V.default.instancePath,(0,z._)`${V.default.valCxt}.${V.default.instancePath}`),t.var(V.default.parentData,(0,z._)`${V.default.valCxt}.${V.default.parentData}`),t.var(V.default.parentDataProperty,(0,z._)`${V.default.valCxt}.${V.default.parentDataProperty}`),t.var(V.default.rootData,(0,z._)`${V.default.valCxt}.${V.default.rootData}`),e.dynamicRef&&t.var(V.default.dynamicAnchors,(0,z._)`${V.default.valCxt}.${V.default.dynamicAnchors}`)},()=>{t.var(V.default.instancePath,(0,z._)`""`),t.var(V.default.parentData,(0,z._)`undefined`),t.var(V.default.parentDataProperty,(0,z._)`undefined`),t.var(V.default.rootData,V.default.data),e.dynamicRef&&t.var(V.default.dynamicAnchors,(0,z._)`{}`)})}function A1(t){let{schema:e,opts:r,gen:n}=t;qx(t,()=>{r.$comment&&e.$comment&&Bx(t),z1(t),n.let(V.default.vErrors,null),n.let(V.default.errors,0),r.unevaluated&&C1(t),Vx(t),L1(t)})}function C1(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 zx(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 D1(t,e){if(Ux(t)&&(Zx(t),Fx(t))){O1(t,e);return}(0,Lx.boolOrEmptySchema)(t,e)}function Fx({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 Ux(t){return typeof t.schema!="boolean"}function O1(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&Bx(t),j1(t),N1(t);let o=n.const("_errs",V.default.errors);Vx(t,o),n.var(e,(0,z._)`${o} === ${V.default.errors}`)}function Zx(t){(0,Vr.checkUnknownRules)(t),M1(t)}function Vx(t,e){if(t.opts.jtd)return jx(t,[],!1,e);let r=(0,Mx.getSchemaTypes)(t.schema),n=(0,Mx.coerceAndCheckDataType)(t,r);jx(t,r,!n,e)}function M1(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Vr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function z1(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Vr.checkStrictMode)(t,"default is ignored in the schema root")}function j1(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,E1.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function N1(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Bx({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,z._)`${V.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,z.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,z._)`${V.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function L1(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,z._)`${V.default.errors} === 0`,()=>e.return(V.default.data),()=>e.throw((0,z._)`new ${s}(${V.default.vErrors})`)):(e.assign((0,z._)`${n}.errors`,V.default.vErrors),o.unevaluated&&q1(t),e.return((0,z._)`${V.default.errors} === 0`))}function q1({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 jx(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,Vr.schemaHasRulesButRef)(o,l))){s.block(()=>Wx(t,"$ref",l.all.$ref.definition));return}c.jtd||F1(t,e),s.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,um.shouldUseGroup)(o,p)&&(p.type?(s.if((0,Lu.checkDataType)(p.type,i,c.strictNumbers)),Nx(t,p),e.length===1&&e[0]===p.type&&r&&(s.else(),(0,Lu.reportTypeError)(t)),s.endIf()):Nx(t,p),a||s.if((0,z._)`${V.default.errors} === ${n||0}`))}}function Nx(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,k1.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,um.shouldUseRule)(n,o)&&Wx(t,o.keyword,o.definition,e.type)})}function F1(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(U1(t,e),t.opts.allowUnionTypes||Z1(t,e),V1(t,t.dataTypes))}function U1(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Hx(t.dataTypes,r)||lm(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),H1(t,e)}}function Z1(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&lm(t,"use allowUnionTypes to allow union type keyword")}function V1(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,um.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>B1(e,i))&&lm(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function B1(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Hx(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function H1(t,e){let r=[];for(let n of t.dataTypes)Hx(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function lm(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Vr.checkStrictMode)(t,e,t.opts.strictTypes)}var qu=class{constructor(e,r,n){if((0,la.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,Vr.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",Kx(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,la.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,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?ua.reportExtraError:ua.reportError)(this,this.def.error,r)}$dataError(){(0,ua.reportError)(this,this.def.$dataError||ua.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ua.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:s,schemaType:o,def:i}=this;n.if((0,z.or)((0,z._)`${s} === undefined`,r)),e!==z.nil&&n.assign(e,!0),(o.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:s,it:o}=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,Lu.checkDataTypes)(c,r,o.opts.strictNumbers,Lu.DataType.Wrong)}`}return z.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,z._)`!${c}(${r})`}return z.nil}}subschema(e,r){let n=(0,cm.getSubschema)(this.it,e);(0,cm.extendSubschemaData)(n,this.it,e),(0,cm.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=Vr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Vr.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,z.Name)),!0}};gn.KeywordCxt=qu;function Wx(t,e,r,n){let s=new qu(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,la.funcKeywordCode)(s,r):"macro"in r?(0,la.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,la.funcKeywordCode)(s,r)}var W1=/^\/(?:[^~]|~0|~1)*$/,K1=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Kx(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return V.default.rootData;if(t[0]==="/"){if(!W1.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,z._)`${o}${(0,z.getProperty)((0,Vr.unescapeJsonPointer)(u))}`,i=(0,z._)`${i} && ${o}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}gn.getData=Kx});var Fu=S(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});var dm=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};pm.default=dm});var pa=S(hm=>{"use strict";Object.defineProperty(hm,"__esModule",{value:!0});var fm=ca(),mm=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,fm.resolveUrl)(e,r,n),this.missingSchema=(0,fm.normalizeId)((0,fm.getFullPath)(e,this.missingRef))}};hm.default=mm});var Zu=S(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.resolveSchema=Wt.getCompilingSchema=Wt.resolveRef=Wt.compileSchema=Wt.SchemaEnv=void 0;var or=te(),J1=Fu(),ls=Zr(),ir=ca(),Jx=le(),G1=da(),So=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={}}};Wt.SchemaEnv=So;function ym(t){let e=Gx.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:J1.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:ls.default.data,parentData:ls.default.parentData,parentDataProperty:ls.default.parentDataProperty,dataNames:[ls.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,G1.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(ls.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${ls.default.self}`,`${ls.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)}}Wt.compileSchema=ym;function Y1(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=eL.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 So({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=X1.call(this,o)}Wt.resolveRef=Y1;function X1(t){return(0,ir.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:ym.call(this,t)}function Gx(t){for(let e of this._compilations)if(Q1(e,t))return e}Wt.getCompilingSchema=Gx;function Q1(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function eL(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Uu.call(this,t,e)}function Uu(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 gm.call(this,r,t);let o=(0,ir.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Uu.call(this,t,i);return typeof a?.schema!="object"?void 0:gm.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||ym.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 So({schema:a,schemaId:c,root:t,baseId:s})}return gm.call(this,r,i)}}Wt.resolveSchema=Uu;var tL=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function gm(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,Jx.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!tL.has(a)&&u&&(e=(0,ir.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,Jx.schemaHasRulesButRef)(r,this.RULES)){let a=(0,ir.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Uu.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new So({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var Yx=S((P7,rL)=>{rL.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 _m=S((k7,t0)=>{"use strict";var nL=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 vm(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 sL=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Xx(t){return t.length=0,!0}function oL(t,e,r){if(t.length){let n=vm(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function iL(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=oL;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=Xx}else{s.push(u);continue}}return s.length&&(a===Xx?r.zone=s.join(""):i?n.push(s.join("")):n.push(vm(s))),r.address=n.join(""),r}function e0(t){if(aL(t,":")<2)return{host:t,isIPV6:!1};let e=iL(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 aL(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function cL(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 uL(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 lL(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=e0(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}t0.exports={nonSimpleDomain:sL,recomposeAuthority:lL,normalizeComponentEncoding:uL,removeDotSegments:cL,isIPv4:Qx,isUUID:nL,normalizeIPv6:e0,stringArrayToHexStripped:vm}});var i0=S((E7,o0)=>{"use strict";var{isUUID:dL}=_m(),pL=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,fL=["http","https","ws","wss","urn","urn:uuid"];function mL(t){return fL.indexOf(t)!==-1}function bm(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 r0(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function n0(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 hL(t){return t.secure=bm(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function gL(t){if((t.port===(bm(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 yL(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(pL);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=wm(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function vL(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=wm(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 _L(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!dL(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function bL(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var s0={scheme:"http",domainHost:!0,parse:r0,serialize:n0},wL={scheme:"https",domainHost:s0.domainHost,parse:r0,serialize:n0},Vu={scheme:"ws",domainHost:!0,parse:hL,serialize:gL},SL={scheme:"wss",domainHost:Vu.domainHost,parse:Vu.parse,serialize:Vu.serialize},$L={scheme:"urn",parse:yL,serialize:vL,skipNormalize:!0},xL={scheme:"urn:uuid",parse:_L,serialize:bL,skipNormalize:!0},Bu={http:s0,https:wL,ws:Vu,wss:SL,urn:$L,"urn:uuid":xL};Object.setPrototypeOf(Bu,null);function wm(t){return t&&(Bu[t]||Bu[t.toLowerCase()])||void 0}o0.exports={wsIsSecure:bm,SCHEMES:Bu,isValidSchemeName:mL,getSchemeHandler:wm}});var $m=S((T7,Wu)=>{"use strict";var{normalizeIPv6:PL,removeDotSegments:fa,recomposeAuthority:kL,normalizeComponentEncoding:Hu,isIPv4:EL,nonSimpleDomain:TL}=_m(),{SCHEMES:IL,getSchemeHandler:a0}=i0();function RL(t,e){return typeof t=="string"?t=$r(Br(t,e),e):typeof t=="object"&&(t=Br($r(t,e),e)),t}function AL(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=c0(Br(t,n),Br(e,n),n,!0);return n.skipEscape=!0,$r(s,n)}function c0(t,e,r,n){let s={};return n||(t=Br($r(t,r),r),e=Br($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=fa(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=fa(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=fa(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=fa(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 CL(t,e,r){return typeof t=="string"?(t=unescape(t),t=$r(Hu(Br(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=$r(Hu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=$r(Hu(Br(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=$r(Hu(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=a0(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=kL(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=fa(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 Br(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(EL(n.host)===!1){let c=PL(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=a0(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&TL(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 Sm={SCHEMES:IL,normalize:RL,resolve:AL,resolveComponent:c0,equal:CL,serialize:$r,parse:Br};Wu.exports=Sm;Wu.exports.default=Sm;Wu.exports.fastUri=Sm});var l0=S(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});var u0=$m();u0.code='require("ajv/dist/runtime/uri").default';xm.default=u0});var v0=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 OL=da();Object.defineProperty(Xe,"KeywordCxt",{enumerable:!0,get:function(){return OL.KeywordCxt}});var $o=te();Object.defineProperty(Xe,"_",{enumerable:!0,get:function(){return $o._}});Object.defineProperty(Xe,"str",{enumerable:!0,get:function(){return $o.str}});Object.defineProperty(Xe,"stringify",{enumerable:!0,get:function(){return $o.stringify}});Object.defineProperty(Xe,"nil",{enumerable:!0,get:function(){return $o.nil}});Object.defineProperty(Xe,"Name",{enumerable:!0,get:function(){return $o.Name}});Object.defineProperty(Xe,"CodeGen",{enumerable:!0,get:function(){return $o.CodeGen}});var ML=Fu(),h0=pa(),zL=Qf(),ma=Zu(),jL=te(),ha=ca(),Ku=ia(),km=le(),d0=Yx(),NL=l0(),g0=(t,e)=>new RegExp(t,e);g0.code="new RegExp";var LL=["removeAdditional","useDefaults","coerceTypes"],qL=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),FL={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."},UL={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},p0=200;function ZL(t){var e,r,n,s,o,i,a,c,u,l,d,p,f,m,h,y,g,b,_,P,x,N,k,O,L;let q=t.strict,$e=(e=t.code)===null||e===void 0?void 0:e.optimize,We=$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:g0,zt=(s=t.uriResolver)!==null&&s!==void 0?s:NL.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:We,regExp:Rt}:{optimize:We,regExp:Rt},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:p0,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:p0,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:(N=t.validateSchema)!==null&&N!==void 0?N:!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:zt}}var ga=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,...ZL(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new jL.ValueScope({scope:{},prefixes:qL,es5:r,lines:n}),this.logger=JL(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,zL.getRules)(),f0.call(this,FL,e,"NOT SUPPORTED"),f0.call(this,UL,e,"DEPRECATED","warn"),this._metaOpts=WL.call(this),e.formats&&BL.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&HL.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),VL.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=d0;n==="id"&&(s={...d0},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 h0.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,ha.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=m0.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new ma.SchemaEnv({schema:{},schemaId:n});if(r=ma.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=m0.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,ha.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(YL.call(this,n,r),!r)return(0,km.eachItem)(n,o=>Pm.call(this,o)),this;QL.call(this,r);let s={...r,type:(0,Ku.getJSONTypes)(r.type),schemaType:(0,Ku.getJSONTypes)(r.schemaType)};return(0,km.eachItem)(n,s.type.length===0?o=>Pm.call(this,o,s):o=>s.type.forEach(i=>Pm.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]=y0(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,ha.normalizeId)(i||n);let u=ha.getSchemaRefs.call(this,e,n);return c=new ma.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):ma.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{ma.compileSchema.call(this,e)}finally{this.opts=r}}};ga.ValidationError=ML.default;ga.MissingRefError=h0.default;Xe.default=ga;function f0(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 m0(t){return t=(0,ha.normalizeId)(t),this.schemas[t]||this.refs[t]}function VL(){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 BL(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function HL(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 WL(){let t={...this.opts};for(let e of LL)delete t[e];return t}var KL={log(){},warn(){},error(){}};function JL(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 GL=/^[a-z_$][a-z0-9_$:-]*$/i;function YL(t,e){let{RULES:r}=this;if((0,km.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!GL.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 Pm(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,Ku.getJSONTypes)(e.type),schemaType:(0,Ku.getJSONTypes)(e.schemaType)}};e.before?XL.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 XL(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 QL(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=y0(e)),t.validateSchema=this.compile(e,!0))}var eq={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function y0(t){return{anyOf:[t,eq]}}});var _0=S(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});var tq={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Em.default=tq});var $0=S(ds=>{"use strict";Object.defineProperty(ds,"__esModule",{value:!0});ds.callRef=ds.getValidate=void 0;var rq=pa(),b0=Ht(),Pt=te(),xo=Zr(),w0=Zu(),Ju=le(),nq={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=w0.resolveRef.call(c,u,s,r);if(l===void 0)throw new rq.default(n.opts.uriResolver,s,r);if(l instanceof w0.SchemaEnv)return p(l);return f(l);function d(){if(o===u)return Gu(t,i,o,o.$async);let m=e.scopeValue("root",{ref:u});return Gu(t,(0,Pt._)`${m}.validate`,u,u.$async)}function p(m){let h=S0(t,m);Gu(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}),y=e.name("valid"),g=t.subschema({schema:m,dataTypes:[],schemaPath:Pt.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(g),t.ok(y)}}};function S0(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Pt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}ds.getValidate=S0;function Gu(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?xo.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,b0.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,b0.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,Pt._)`${m}.errors`;s.assign(xo.default.vErrors,(0,Pt._)`${xo.default.vErrors} === null ? ${h} : ${xo.default.vErrors}.concat(${h})`),s.assign(xo.default.errors,(0,Pt._)`${xo.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(o.props=Ju.mergeEvaluated.props(s,y.props,o.props));else{let g=s.var("props",(0,Pt._)`${m}.evaluated.props`);o.props=Ju.mergeEvaluated.props(s,g,o.props,Pt.Name)}if(o.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(o.items=Ju.mergeEvaluated.items(s,y.items,o.items));else{let g=s.var("items",(0,Pt._)`${m}.evaluated.items`);o.items=Ju.mergeEvaluated.items(s,g,o.items,Pt.Name)}}}ds.callRef=Gu;ds.default=nq});var x0=S(Tm=>{"use strict";Object.defineProperty(Tm,"__esModule",{value:!0});var sq=_0(),oq=$0(),iq=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",sq.default,oq.default];Tm.default=iq});var P0=S(Im=>{"use strict";Object.defineProperty(Im,"__esModule",{value:!0});var Yu=te(),yn=Yu.operators,Xu={maximum:{okStr:"<=",ok:yn.LTE,fail:yn.GT},minimum:{okStr:">=",ok:yn.GTE,fail:yn.LT},exclusiveMaximum:{okStr:"<",ok:yn.LT,fail:yn.GTE},exclusiveMinimum:{okStr:">",ok:yn.GT,fail:yn.LTE}},aq={message:({keyword:t,schemaCode:e})=>(0,Yu.str)`must be ${Xu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Yu._)`{comparison: ${Xu[t].okStr}, limit: ${e}}`},cq={keyword:Object.keys(Xu),type:"number",schemaType:"number",$data:!0,error:aq,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Yu._)`${r} ${Xu[e].fail} ${n} || isNaN(${r})`)}};Im.default=cq});var k0=S(Rm=>{"use strict";Object.defineProperty(Rm,"__esModule",{value:!0});var ya=te(),uq={message:({schemaCode:t})=>(0,ya.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ya._)`{multipleOf: ${t}}`},lq={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:uq,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,ya._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,ya._)`${i} !== parseInt(${i})`;t.fail$data((0,ya._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Rm.default=lq});var T0=S(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});function E0(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}Am.default=E0;E0.code='require("ajv/dist/runtime/ucs2length").default'});var I0=S(Cm=>{"use strict";Object.defineProperty(Cm,"__esModule",{value:!0});var ps=te(),dq=le(),pq=T0(),fq={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,ps.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,ps._)`{limit: ${t}}`},mq={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:fq,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?ps.operators.GT:ps.operators.LT,i=s.opts.unicode===!1?(0,ps._)`${r}.length`:(0,ps._)`${(0,dq.useFunc)(t.gen,pq.default)}(${r})`;t.fail$data((0,ps._)`${i} ${o} ${n}`)}};Cm.default=mq});var R0=S(Dm=>{"use strict";Object.defineProperty(Dm,"__esModule",{value:!0});var hq=Ht(),gq=le(),Po=te(),yq={message:({schemaCode:t})=>(0,Po.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Po._)`{pattern: ${t}}`},vq={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:yq,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,Po._)`new RegExp`:(0,gq.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Po._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Po._)`!${l}`)}else{let c=(0,hq.usePattern)(t,s);t.fail$data((0,Po._)`!${c}.test(${r})`)}}};Dm.default=vq});var A0=S(Om=>{"use strict";Object.defineProperty(Om,"__esModule",{value:!0});var va=te(),_q={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,va.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,va._)`{limit: ${t}}`},bq={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:_q,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?va.operators.GT:va.operators.LT;t.fail$data((0,va._)`Object.keys(${r}).length ${s} ${n}`)}};Om.default=bq});var C0=S(Mm=>{"use strict";Object.defineProperty(Mm,"__esModule",{value:!0});var _a=Ht(),ba=te(),wq=le(),Sq={message:({params:{missingProperty:t}})=>(0,ba.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ba._)`{missingProperty: ${t}}`},$q={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Sq,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 y=i.schemaEnv.baseId+i.errSchemaPath,g=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,wq.checkStrictMode)(i,g,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(ba.nil,d);else for(let f of r)(0,_a.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,_a.checkMissingProp)(t,r,f)),(0,_a.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,_a.noPropertyInData)(e,s,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,_a.propertyInData)(e,s,f,a.ownProperties)),e.if((0,ba.not)(m),()=>{t.error(),e.break()})},ba.nil)}}};Mm.default=$q});var D0=S(zm=>{"use strict";Object.defineProperty(zm,"__esModule",{value:!0});var wa=te(),xq={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}}`},Pq={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:xq,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}`)}};zm.default=Pq});var Qu=S(jm=>{"use strict";Object.defineProperty(jm,"__esModule",{value:!0});var O0=aa();O0.code='require("ajv/dist/runtime/equal").default';jm.default=O0});var M0=S(Lm=>{"use strict";Object.defineProperty(Lm,"__esModule",{value:!0});var Nm=ia(),Qe=te(),kq=le(),Eq=Qu(),Tq={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}}`},Iq={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Tq,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,Nm.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 y=e.name("item"),g=(0,Nm.checkDataTypes)(u,y,a.opts.strictNumbers,Nm.DataType.Wrong),b=e.const("indices",(0,Qe._)`{}`);e.for((0,Qe._)`;${m}--;`,()=>{e.let(y,(0,Qe._)`${r}[${m}]`),e.if(g,(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,kq.useFunc)(e,Eq.default),g=e.name("outer");e.label(g).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(g)})))}}};Lm.default=Iq});var z0=S(Fm=>{"use strict";Object.defineProperty(Fm,"__esModule",{value:!0});var qm=te(),Rq=le(),Aq=Qu(),Cq={message:"must be equal to constant",params:({schemaCode:t})=>(0,qm._)`{allowedValue: ${t}}`},Dq={keyword:"const",$data:!0,error:Cq,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,qm._)`!${(0,Rq.useFunc)(e,Aq.default)}(${r}, ${s})`):t.fail((0,qm._)`${o} !== ${r}`)}};Fm.default=Dq});var j0=S(Um=>{"use strict";Object.defineProperty(Um,"__esModule",{value:!0});var Sa=te(),Oq=le(),Mq=Qu(),zq={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Sa._)`{allowedValues: ${t}}`},jq={keyword:"enum",schemaType:"array",$data:!0,error:zq,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,Oq.useFunc)(e,Mq.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,Sa.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,Sa._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let h=s[m];return typeof h=="object"&&h!==null?(0,Sa._)`${u()}(${r}, ${f}[${m}])`:(0,Sa._)`${r} === ${h}`}}};Um.default=jq});var N0=S(Zm=>{"use strict";Object.defineProperty(Zm,"__esModule",{value:!0});var Nq=P0(),Lq=k0(),qq=I0(),Fq=R0(),Uq=A0(),Zq=C0(),Vq=D0(),Bq=M0(),Hq=z0(),Wq=j0(),Kq=[Nq.default,Lq.default,qq.default,Fq.default,Uq.default,Zq.default,Vq.default,Bq.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Hq.default,Wq.default];Zm.default=Kq});var Bm=S($a=>{"use strict";Object.defineProperty($a,"__esModule",{value:!0});$a.validateAdditionalItems=void 0;var fs=te(),Vm=le(),Jq={message:({params:{len:t}})=>(0,fs.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,fs._)`{limit: ${t}}`},Gq={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Jq,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Vm.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}L0(t,n)}};function L0(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,fs._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,fs._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Vm.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,fs._)`${a} <= ${e.length}`);r.if((0,fs.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:o,dataProp:l,dataPropType:Vm.Type.Num},u),i.allErrors||r.if((0,fs.not)(u),()=>r.break())})}}$a.validateAdditionalItems=L0;$a.default=Gq});var Hm=S(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.validateTuple=void 0;var q0=te(),el=le(),Yq=Ht(),Xq={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return F0(t,"additionalItems",e);r.items=!0,!(0,el.alwaysValidSchema)(r,e)&&t.ok((0,Yq.validateArray)(t))}};function F0(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=el.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,q0._)`${o}.length`);r.forEach((d,p)=>{(0,el.alwaysValidSchema)(a,d)||(n.if((0,q0._)`${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,el.checkStrictMode)(a,y,p.strictTuples)}}}xa.validateTuple=F0;xa.default=Xq});var U0=S(Wm=>{"use strict";Object.defineProperty(Wm,"__esModule",{value:!0});var Qq=Hm(),eF={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Qq.validateTuple)(t,"items")};Wm.default=eF});var V0=S(Km=>{"use strict";Object.defineProperty(Km,"__esModule",{value:!0});var Z0=te(),tF=le(),rF=Ht(),nF=Bm(),sF={message:({params:{len:t}})=>(0,Z0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Z0._)`{limit: ${t}}`},oF={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:sF,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,tF.alwaysValidSchema)(n,e)&&(s?(0,nF.validateAdditionalItems)(t,s):t.ok((0,rF.validateArray)(t)))}};Km.default=oF});var B0=S(Jm=>{"use strict";Object.defineProperty(Jm,"__esModule",{value:!0});var Kt=te(),tl=le(),iF={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}}`},aF={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:iF,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,tl.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,tl.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,tl.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"),y=e.let("count",0);f(h,()=>e.if(h,()=>m(y)))}function f(h,y){e.forRange("i",0,l,g=>{t.subschema({keyword:"contains",dataProp:g,dataPropType:tl.Type.Num,compositeRule:!0},h),y()})}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)))}}};Jm.default=aF});var K0=S(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.validateSchemaDeps=xr.validatePropertyDeps=xr.error=void 0;var Gm=te(),cF=le(),Pa=Ht();xr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Gm.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Gm._)`{property: ${t},
|
|
10
|
-
missingProperty: ${n},
|
|
11
|
-
depsCount: ${e},
|
|
12
|
-
deps: ${r}}`};var uF={keyword:"dependencies",type:"object",schemaType:"object",error:xr.error,code(t){let[e,r]=lF(t);H0(t,e),W0(t,r)}};function lF({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 H0(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,Pa.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,Pa.checkReportMissingProp)(t,u)}):(r.if((0,Gm._)`${c} && (${(0,Pa.checkMissingProp)(t,a,o)})`),(0,Pa.reportMissingProp)(t,o),r.else())}}xr.validatePropertyDeps=H0;function W0(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,cF.alwaysValidSchema)(o,e[a])||(r.if((0,Pa.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=W0;xr.default=uF});var G0=S(Ym=>{"use strict";Object.defineProperty(Ym,"__esModule",{value:!0});var J0=te(),dF=le(),pF={message:"property name must be valid",params:({params:t})=>(0,J0._)`{propertyName: ${t.propertyName}}`},fF={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:pF,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,dF.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,J0.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Ym.default=fF});var Qm=S(Xm=>{"use strict";Object.defineProperty(Xm,"__esModule",{value:!0});var rl=Ht(),ar=te(),mF=Zr(),nl=le(),hF={message:"must NOT have additional properties",params:({params:t})=>(0,ar._)`{additionalProperty: ${t.additionalProperty}}`},gF={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:hF,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,nl.alwaysValidSchema)(i,r))return;let u=(0,rl.allSchemaProperties)(n.properties),l=(0,rl.allSchemaProperties)(n.patternProperties);d(),t.ok((0,ar._)`${o} === ${mF.default.errors}`);function d(){e.forIn("key",s,y=>{!u.length&&!l.length?m(y):e.if(p(y),()=>m(y))})}function p(y){let g;if(u.length>8){let b=(0,nl.schemaRefOrVal)(i,n.properties,"properties");g=(0,rl.isOwnProperty)(e,b,y)}else u.length?g=(0,ar.or)(...u.map(b=>(0,ar._)`${y} === ${b}`)):g=ar.nil;return l.length&&(g=(0,ar.or)(g,...l.map(b=>(0,ar._)`${(0,rl.usePattern)(t,b)}.test(${y})`))),(0,ar.not)(g)}function f(y){e.code((0,ar._)`delete ${s}[${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,nl.alwaysValidSchema)(i,r)){let g=e.name("valid");c.removeAdditional==="failing"?(h(y,g,!1),e.if((0,ar.not)(g),()=>{t.reset(),f(y)})):(h(y,g),a||e.if((0,ar.not)(g),()=>e.break()))}}function h(y,g,b){let _={keyword:"additionalProperties",dataProp:y,dataPropType:nl.Type.Str};b===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,g)}}};Xm.default=gF});var Q0=S(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var yF=da(),Y0=Ht(),eh=le(),X0=Qm(),vF={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&&X0.default.code(new yF.KeywordCxt(o,X0.default,"additionalProperties"));let i=(0,Y0.allSchemaProperties)(r);for(let d of i)o.definedProperties.add(d);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=eh.mergeEvaluated.props(e,(0,eh.toHash)(i),o.props));let a=i.filter(d=>!(0,eh.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,Y0.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)}}};th.default=vF});var nP=S(rh=>{"use strict";Object.defineProperty(rh,"__esModule",{value:!0});var eP=Ht(),sl=te(),tP=le(),rP=le(),_F={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,eP.allSchemaProperties)(r),c=a.filter(h=>(0,tP.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 sl.Name)&&(o.props=(0,rP.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 y in u)new RegExp(h).test(y)&&(0,tP.checkStrictMode)(o,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,sl._)`${(0,eP.usePattern)(t,h)}.test(${y})`,()=>{let g=c.includes(h);g||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:rP.Type.Str},l),o.opts.unevaluated&&d!==!0?e.assign((0,sl._)`${d}[${y}]`,!0):!g&&!o.allErrors&&e.if((0,sl.not)(l),()=>e.break())})})}}};rh.default=_F});var sP=S(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});var bF=le(),wF={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,bF.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"}};nh.default=wF});var oP=S(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var SF=Ht(),$F={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:SF.validateUnion,error:{message:"must match a schema in anyOf"}};sh.default=$F});var iP=S(oh=>{"use strict";Object.defineProperty(oh,"__esModule",{value:!0});var ol=te(),xF=le(),PF={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ol._)`{passingSchemas: ${t.passing}}`},kF={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:PF,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,xF.alwaysValidSchema)(s,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,ol._)`${c} && ${i}`).assign(i,!1).assign(a,(0,ol._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,ol.Name)})})}}};oh.default=kF});var aP=S(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});var EF=le(),TF={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,EF.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};ih.default=TF});var lP=S(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var il=te(),uP=le(),IF={message:({params:t})=>(0,il.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,il._)`{failingKeyword: ${t.ifClause}}`},RF={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:IF,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,uP.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=cP(n,"then"),o=cP(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,il.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,il._)`${l}`):t.setParams({ifClause:l})}}}};function cP(t,e){let r=t.schema[e];return r!==void 0&&!(0,uP.alwaysValidSchema)(t,r)}ah.default=RF});var dP=S(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var AF=le(),CF={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,AF.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};ch.default=CF});var pP=S(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var DF=Bm(),OF=U0(),MF=Hm(),zF=V0(),jF=B0(),NF=K0(),LF=G0(),qF=Qm(),FF=Q0(),UF=nP(),ZF=sP(),VF=oP(),BF=iP(),HF=aP(),WF=lP(),KF=dP();function JF(t=!1){let e=[ZF.default,VF.default,BF.default,HF.default,WF.default,KF.default,LF.default,qF.default,NF.default,FF.default,UF.default];return t?e.push(OF.default,zF.default):e.push(DF.default,MF.default),e.push(jF.default),e}uh.default=JF});var fP=S(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});var Fe=te(),GF={message:({schemaCode:t})=>(0,Fe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Fe._)`{format: ${t}}`},YF={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:GF,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}]`),y=r.let("fType"),g=r.let("format");r.if((0,Fe._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,Fe._)`${h}.type || "string"`).assign(g,(0,Fe._)`${h}.validate`),()=>r.assign(y,(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 && ${y} === ${e} && !${x}`}}function f(){let m=d.formats[o];if(!m){b();return}if(m===!0)return;let[h,y,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 N=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:N});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 y=="function"?(0,Fe._)`${g}(${n})`:(0,Fe._)`${g}.test(${n})`}}}};lh.default=YF});var mP=S(dh=>{"use strict";Object.defineProperty(dh,"__esModule",{value:!0});var XF=fP(),QF=[XF.default];dh.default=QF});var hP=S(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.contentVocabulary=ko.metadataVocabulary=void 0;ko.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ko.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var yP=S(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var eU=x0(),tU=N0(),rU=pP(),nU=mP(),gP=hP(),sU=[eU.default,tU.default,(0,rU.default)(),nU.default,gP.metadataVocabulary,gP.contentVocabulary];ph.default=sU});var _P=S(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.DiscrError=void 0;var vP;(function(t){t.Tag="tag",t.Mapping="mapping"})(vP||(al.DiscrError=vP={}))});var wP=S(mh=>{"use strict";Object.defineProperty(mh,"__esModule",{value:!0});var Eo=te(),fh=_P(),bP=Zu(),oU=pa(),iU=le(),aU={message:({params:{discrError:t,tagName:e}})=>t===fh.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Eo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},cU={keyword:"discriminator",type:"object",schemaType:"object",error:aU,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,Eo._)`${r}${(0,Eo.getProperty)(a)}`);e.if((0,Eo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:fh.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,Eo._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:fh.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,Eo.Name),m}function p(){var f;let m={},h=g(s),y=!0;for(let P=0;P<i.length;P++){let x=i[P];if(x?.$ref&&!(0,iU.schemaHasRulesButRef)(x,o.self.RULES)){let k=x.$ref;if(x=bP.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,k),x instanceof bP.SchemaEnv&&(x=x.schema),x===void 0)throw new oU.default(o.opts.uriResolver,o.baseId,k)}let N=(f=x?.properties)===null||f===void 0?void 0:f[a];if(typeof N!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||g(x)),b(N,P)}if(!y)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 N of P.enum)_(N,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}}}};mh.default=cU});var SP=S((gee,uU)=>{uU.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 xP=S((Ae,hh)=>{"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 lU=v0(),dU=yP(),pU=wP(),$P=SP(),fU=["/properties"],cl="http://json-schema.org/draft-07/schema",To=class extends lU.default{_addVocabularies(){super._addVocabularies(),dU.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(pU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema($P,fU):$P;this.addMetaSchema(e,cl,!1),this.refs["http://json-schema.org/schema"]=cl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(cl)?cl:void 0)}};Ae.Ajv=To;hh.exports=Ae=To;hh.exports.Ajv=To;Object.defineProperty(Ae,"__esModule",{value:!0});Ae.default=To;var mU=da();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return mU.KeywordCxt}});var Io=te();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return Io._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return Io.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return Io.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return Io.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return Io.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return Io.CodeGen}});var hU=Fu();Object.defineProperty(Ae,"ValidationError",{enumerable:!0,get:function(){return hU.default}});var gU=pa();Object.defineProperty(Ae,"MissingRefError",{enumerable:!0,get:function(){return gU.default}})});var CP=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(TP,_h),time:Pr(yh(!0),bh),"date-time":Pr(PP(!0),RP),"iso-time":Pr(yh(),IP),"iso-date-time":Pr(PP(),AP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:SU,"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:IU,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:$U,int32:{type:"number",validate:kU},int64:{type:"number",validate:EU},float:{type:"number",validate:EP},double:{type:"number",validate:EP},password:!0,binary:!0};kr.fastFormats={...kr.fullFormats,date:Pr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,_h),time:Pr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,bh),"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,RP),"iso-time":Pr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,IP),"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,AP),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 yU(t){return t%4===0&&(t%100!==0||t%400===0)}var vU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,_U=[0,31,28,31,30,31,30,31,31,30,31,30,31];function TP(t){let e=vU.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&&yU(r)?29:_U[n])}function _h(t,e){if(t&&e)return t>e?1:t<e?-1:0}var gh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function yh(t){return function(r){let n=gh.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 bh(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 IP(t,e){if(!(t&&e))return;let r=gh.exec(t),n=gh.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 vh=/t|\s/i;function PP(t){let e=yh(t);return function(n){let s=n.split(vh);return s.length===2&&TP(s[0])&&e(s[1])}}function RP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function AP(t,e){if(!(t&&e))return;let[r,n]=t.split(vh),[s,o]=e.split(vh),i=_h(r,s);if(i!==void 0)return i||bh(n,o)}var bU=/\/|:/,wU=/^(?:[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 SU(t){return bU.test(t)&&wU.test(t)}var kP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function $U(t){return kP.lastIndex=0,kP.test(t)}var xU=-(2**31),PU=2**31-1;function kU(t){return Number.isInteger(t)&&t<=PU&&t>=xU}function EU(t){return Number.isInteger(t)}function EP(){return!0}var TU=/[^\\]\\Z/;function IU(t){if(TU.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Ta=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 ka=class{};he._CodeOrName=ka;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ms=class extends ka{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=ms;var Jt=class extends ka{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 ms&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=Jt;he.nil=new Jt("");function DP(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Sh(r,e[n]),r.push(t[++n]);return new Jt(r)}he._=DP;var wh=new Jt("+");function OP(t,...e){let r=[Ea(t[0])],n=0;for(;n<e.length;)r.push(wh),Sh(r,e[n]),r.push(wh,Ea(t[++n]));return RU(r),new Jt(r)}he.str=OP;function Sh(t,e){e instanceof Jt?t.push(...e._items):e instanceof ms?t.push(e):t.push(DU(e))}he.addCodeArg=Sh;function RU(t){let e=1;for(;e<t.length-1;){if(t[e]===wh){let r=AU(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function AU(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof ms||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 ms))return`"${t}${e.slice(1)}`}function CU(t,e){return e.emptyStr()?t:t.emptyStr()?e:OP`${t}${e}`}he.strConcat=CU;function DU(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ea(Array.isArray(t)?t.join(","):t)}function OU(t){return new Jt(Ea(t))}he.stringify=OU;function Ea(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Ea;function MU(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new Jt(`.${t}`):DP`[${t}]`}he.getProperty=MU;function zU(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=zU;function jU(t){return new Jt(t.toString())}he.regexpCode=jU});var Ph=S(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.ValueScope=Et.ValueScopeName=Et.Scope=Et.varKinds=Et.UsedValueState=void 0;var kt=Ta(),$h=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},ul;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(ul||(Et.UsedValueState=ul={}));Et.varKinds={const:new kt.Name("const"),let:new kt.Name("let"),var:new kt.Name("var")};var ll=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=ll;var dl=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=dl;var NU=(0,kt._)`\n`,xh=class extends ll{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?NU:kt.nil}}get(){return this._scope}name(e){return new dl(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,ul.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 $h(u);c.set(u,ul.Completed)})}return o}};Et.ValueScope=xh});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=Ta(),cr=Ph(),vn=Ta();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return vn._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return vn.str}});Object.defineProperty(ee,"strConcat",{enumerable:!0,get:function(){return vn.strConcat}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return vn.nil}});Object.defineProperty(ee,"getProperty",{enumerable:!0,get:function(){return vn.getProperty}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return vn.stringify}});Object.defineProperty(ee,"regexpCode",{enumerable:!0,get:function(){return vn.regexpCode}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return vn.Name}});var hl=Ph();Object.defineProperty(ee,"Scope",{enumerable:!0,get:function(){return hl.Scope}});Object.defineProperty(ee,"ValueScope",{enumerable:!0,get:function(){return hl.ValueScope}});Object.defineProperty(ee,"ValueScopeName",{enumerable:!0,get:function(){return hl.ValueScopeName}});Object.defineProperty(ee,"varKinds",{enumerable:!0,get:function(){return hl.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 Hr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},kh=class extends Hr{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=Ao(this.rhs,e,r)),this}get names(){return this.rhs instanceof ue._CodeOrName?this.rhs.names:{}}},pl=class extends Hr{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=Ao(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ue.Name?{}:{...this.lhs.names};return ml(e,this.rhs)}},Eh=class extends pl{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Th=class extends Hr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ih=class extends Hr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Rh=class extends Hr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ah=class extends Hr{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=Ao(this.code,e,r),this}get names(){return this.code instanceof ue._CodeOrName?this.code.names:{}}},Ia=class extends Hr{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)||(LU(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>ys(e,r.names),{})}},Wr=class extends Ia{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ch=class extends Ia{},Ro=class extends Wr{};Ro.kind="else";var hs=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 Ro(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(MP(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=Ao(this.condition,e,r),this}get names(){let e=super.names;return ml(e,this.condition),this.else&&ys(e,this.else.names),e}};hs.kind="if";var gs=class extends Wr{};gs.kind="for";var Dh=class extends gs{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=Ao(this.iteration,e,r),this}get names(){return ys(super.names,this.iteration.names)}},Oh=class extends gs{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=ml(super.names,this.from);return ml(e,this.to)}},fl=class extends gs{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=Ao(this.iterable,e,r),this}get names(){return ys(super.names,this.iterable.names)}},Ra=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)}};Ra.kind="func";var Aa=class extends Ia{render(e){return"return "+super.render(e)}};Aa.kind="return";var Mh=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&&ys(e,this.catch.names),this.finally&&ys(e,this.finally.names),e}},Ca=class extends Wr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ca.kind="catch";var Da=class extends Wr{render(e){return"finally"+super.render(e)}};Da.kind="finally";var zh=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 Ch]}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 kh(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 pl(e,r,n))}add(e,r){return this._leafNode(new Eh(e,ee.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ue.nil&&this._leafNode(new Ah(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 hs(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 hs(e))}else(){return this._elseNode(new Ro)}endIf(){return this._endBlockNode(hs,Ro)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Dh(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 Oh(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 fl("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 fl("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(gs)}label(e){return this._leafNode(new Th(e))}break(e){return this._leafNode(new Ih(e))}return(e){let r=new Aa;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Aa)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Mh;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new Ca(o),r(o)}return n&&(this._currNode=s.finally=new Da,this.code(n)),this._endBlockNode(Ca,Da)}throw(e){return this._leafNode(new Rh(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 Ra(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Ra)}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 hs))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=zh;function ys(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ml(t,e){return e instanceof ue._CodeOrName?ys(t,e.names):t}function Ao(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 LU(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function MP(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ue._)`!${jh(t)}`}ee.not=MP;var qU=zP(ee.operators.AND);function FU(...t){return t.reduce(qU)}ee.and=FU;var UU=zP(ee.operators.OR);function ZU(...t){return t.reduce(UU)}ee.or=ZU;function zP(t){return(e,r)=>e===ue.nil?r:r===ue.nil?e:(0,ue._)`${jh(e)} ${t} ${jh(r)}`}function jh(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(),VU=Ta();function BU(t){let e={};for(let r of t)e[r]=!0;return e}ne.toHash=BU;function HU(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(LP(t,e),!qP(e,t.self.RULES.all))}ne.alwaysValidSchema=HU;function LP(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]||ZP(t,`unknown keyword: "${o}"`)}ne.checkUnknownRules=LP;function qP(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ne.schemaHasRules=qP;function WU(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=WU;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 JU(t){return FP(decodeURIComponent(t))}ne.unescapeFragment=JU;function GU(t){return encodeURIComponent(Lh(t))}ne.escapeFragment=GU;function Lh(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ne.escapeJsonPointer=Lh;function FP(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ne.unescapeJsonPointer=FP;function YU(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ne.eachItem=YU;function jP({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:jP({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} || {}`),qh(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:UP}),items:jP({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 UP(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Se._)`{}`);return e!==void 0&&qh(t,r,e),r}ne.evaluatedPropsToName=UP;function qh(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Se._)`${e}${(0,Se.getProperty)(n)}`,!0))}ne.setEvaluated=qh;var NP={};function XU(t,e){return t.scopeValue("func",{ref:e,code:NP[e.code]||(NP[e.code]=new VU._Code(e.code))})}ne.useFunc=XU;var Nh;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Nh||(ne.Type=Nh={}));function QU(t,e,r){if(t instanceof Se.Name){let n=e===Nh.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():"/"+Lh(t)}ne.getErrorPath=QU;function ZP(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=ZP});var Kr=S(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});var ct=X(),eZ={data:new ct.Name("data"),valCxt:new ct.Name("valCxt"),instancePath:new ct.Name("instancePath"),parentData:new ct.Name("parentData"),parentDataProperty:new ct.Name("parentDataProperty"),rootData:new ct.Name("rootData"),dynamicAnchors:new ct.Name("dynamicAnchors"),vErrors:new ct.Name("vErrors"),errors:new ct.Name("errors"),this:new ct.Name("this"),self:new ct.Name("self"),scope:new ct.Name("scope"),json:new ct.Name("json"),jsonPos:new ct.Name("jsonPos"),jsonLen:new ct.Name("jsonLen"),jsonPart:new ct.Name("jsonPart")};Fh.default=eZ});var Oa=S(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.extendErrors=ut.resetErrorsCount=ut.reportExtraError=ut.reportError=ut.keyword$DataError=ut.keywordError=void 0;var fe=X(),gl=pe(),gt=Kr();ut.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};ut.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 tZ(t,e=ut.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=HP(t,e,r);n??(i||a)?VP(o,c):BP(s,(0,fe._)`[${c}]`)}ut.reportError=tZ;function rZ(t,e=ut.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=HP(t,e,r);VP(s,a),o||i||BP(n,gt.default.vErrors)}ut.reportExtraError=rZ;function nZ(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)))}ut.resetErrorsCount=nZ;function sZ({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))})}ut.extendErrors=sZ;function VP(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 BP(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 vs={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 HP(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,fe._)`{}`:oZ(t,e,r)}function oZ(t,e,r={}){let{gen:n,it:s}=t,o=[iZ(s,r),aZ(t,r)];return cZ(t,e,o),n.object(...o)}function iZ({errorPath:t},{instancePath:e}){let r=e?(0,fe.str)`${t}${(0,gl.getErrorPath)(e,gl.Type.Str)}`:t;return[gt.default.instancePath,(0,fe.strConcat)(gt.default.instancePath,r)]}function aZ({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,gl.getErrorPath)(r,gl.Type.Str)}`),[vs.schemaPath,s]}function cZ(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([vs.keyword,s],[vs.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&n.push([vs.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([vs.schema,i],[vs.parentSchema,(0,fe._)`${l}${d}`],[gt.default.data,o]),u&&n.push([vs.propertyName,u])}});var KP=S(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.boolOrEmptySchema=Co.topBoolOrEmptySchema=void 0;var uZ=Oa(),lZ=X(),dZ=Kr(),pZ={message:"boolean schema is false"};function fZ(t){let{gen:e,schema:r,validateName:n}=t;r===!1?WP(t,!1):typeof r=="object"&&r.$async===!0?e.return(dZ.default.data):(e.assign((0,lZ._)`${n}.errors`,null),e.return(!0))}Co.topBoolOrEmptySchema=fZ;function mZ(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),WP(t)):r.var(e,!0)}Co.boolOrEmptySchema=mZ;function WP(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,uZ.reportError)(s,pZ,void 0,e)}});var Uh=S(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.getRules=Do.isJSONType=void 0;var hZ=["string","number","integer","boolean","null","object","array"],gZ=new Set(hZ);function yZ(t){return typeof t=="string"&&gZ.has(t)}Do.isJSONType=yZ;function vZ(){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:{}}}Do.getRules=vZ});var Zh=S(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.shouldUseRule=_n.shouldUseGroup=_n.schemaHasRulesForType=void 0;function _Z({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&JP(t,n)}_n.schemaHasRulesForType=_Z;function JP(t,e){return e.rules.some(r=>GP(t,r))}_n.shouldUseGroup=JP;function GP(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))}_n.shouldUseRule=GP});var Ma=S(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.reportTypeError=lt.checkDataTypes=lt.checkDataType=lt.coerceAndCheckDataType=lt.getJSONTypes=lt.getSchemaTypes=lt.DataType=void 0;var bZ=Uh(),wZ=Zh(),SZ=Oa(),J=X(),YP=pe(),Oo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Oo||(lt.DataType=Oo={}));function $Z(t){let e=XP(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}lt.getSchemaTypes=$Z;function XP(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(bZ.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}lt.getJSONTypes=XP;function xZ(t,e){let{gen:r,data:n,opts:s}=t,o=PZ(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,wZ.schemaHasRulesForType)(t,e[0]));if(i){let a=Bh(e,n,s.strictNumbers,Oo.Wrong);r.if(a,()=>{o.length?kZ(t,e,o):Hh(t)})}return i}lt.coerceAndCheckDataType=xZ;var QP=new Set(["string","number","integer","boolean","null"]);function PZ(t,e){return e?t.filter(r=>QP.has(r)||e==="array"&&r==="array"):[]}function kZ(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(Bh(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(),Hh(t),n.endIf(),n.if((0,J._)`${a} !== undefined`,()=>{n.assign(s,a),EZ(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
|
|
3
|
+
var FR=Object.create;var Ld=Object.defineProperty;var qR=Object.getOwnPropertyDescriptor;var UR=Object.getOwnPropertyNames;var ZR=Object.getPrototypeOf,VR=Object.prototype.hasOwnProperty;var Or=(t,e)=>()=>(t&&(e=t(t=0)),e);var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),rt=(t,e)=>{for(var r in e)Ld(t,r,{get:e[r],enumerable:!0})},BR=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of UR(e))!VR.call(t,s)&&s!==r&&Ld(t,s,{get:()=>e[s],enumerable:!(n=qR(e,s))||n.enumerable});return t};var cv=(t,e,r)=>(r=t!=null?FR(ZR(t)):{},BR(e||!t||!t.__esModule?Ld(r,"default",{value:t,enumerable:!0}):r,t));var uv,ci,lv,dv,pv,fv,mv,ui,hv,Os,gv,yv,vv,_v,bv,wv,An,Fd,qd,NK,LK,Ud,Sv,$v,hc,Cn,Zd,xv,Pv,Ms,Mr=Or(()=>{"use strict";uv="4.13.4",ci="http://localhost:11434",lv="llama3",dv=".agestra/.jobs",pv=".agestra/traces",fv=".agestra/worktrees",mv=".agestra/sessions",ui=".agestra/workspace",hv="individual",Os="debates",gv="synthesis",yv="issue",vv=".agestra/workers",_v=Object.freeze(["PATH","HOME","USER","USERPROFILE","APPDATA","LOCALAPPDATA","TEMP","TMP","TMPDIR","SHELL","LANG","LC_ALL","NODE_PATH","SystemRoot","SystemDrive","COMSPEC","ComSpec","windir"]),bv=2,wv=6e4,An=20,Fd=5e4,qd=10,NK=Object.freeze([3,5,10]),LK=Object.freeze(["agree","disagree","abstain","revise"]),Ud=2,Sv=1440*60*1e3,$v=3600*1e3,hc=Object.freeze(["ko","zh","ja","en"]),Cn="ko",Zd="en",xv="[REDACTED]",Pv=["","--- 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
|
+
`),Ms=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 HR}from"child_process";function zs(t){if(!Number.isFinite(t)||t<=0)return{delivered:!1};if(process.platform==="win32")try{return HR("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 tr(t,e=3e3){let r=t.pid;if(r)zs(r);else try{t.kill("SIGTERM")}catch{}setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},e).unref?.()}var js=Or(()=>{"use strict"});import{execFileSync as WR,spawn as KR}from"child_process";import{existsSync as JR}from"fs";function kv(t){let e=t.replace(/\s+/g," ").trim();return e.length>200?`${e.slice(0,200)}...`:e}function Xr(t,e){if(t)try{t({...e,at:new Date().toISOString()})}catch{}}function YR(t){return process.platform!=="win32"||t.includes("/")||t.includes("\\")?!1:GR.has(t.toLowerCase())}function XR(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 QR(t){let e=t.toLowerCase();if(Ns.has(e))return Ns.get(e)??null;try{let n=WR("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 Ns.set(e,null),null;let s=n.find(a=>/\.(cmd|bat)$/i.test(a));if(s){let a={type:"cmd",path:s};return Ns.set(e,a),a}let i=`${n[0]}.ps1`;if(JR(i)){let a={type:"powershell",path:i};return Ns.set(e,a),a}}catch{}return Ns.set(e,null),null}function Dn(t,e){if(!YR(t))return{command:t,args:e};let r=QR(t);return r?r.type==="cmd"?{command:"cmd.exe",args:["/d","/s","/c",r.path,...e.map(n=>XR(n))]}:{command:"powershell.exe",args:["-NoProfile","-ExecutionPolicy","RemoteSigned","-File",r.path,...e]}:{command:t,args:e}}function _t(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){Xr(l,{type:"abort",command:e,args:r,reason:String(d.reason??"aborted before spawn")}),f(new Lt(d.reason));return}let m=Dn(e,r);Xr(l,{type:"start",command:m.command,args:m.args,timeoutMs:n});let h=KR(m.command,m.args,{cwd:o,env:i?{...process.env,...i}:void 0,stdio:[a?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),y="",v="",_=0,b=0,P=!1,x=null,N=!1,k=null,O=()=>{k&&d&&d.removeEventListener("abort",k)},L=!1,F=()=>{!L&&_+b>c&&(P=!0,L=!0,tr(h))},xe=null,We=()=>{xe&&(clearTimeout(xe),xe=null)},Ct=()=>{N||(tr(h),N=!0,We(),O(),Xr(l,{type:"timeout",command:e,args:r,timeoutMs:n}),f(new Error(`CLI timeout after ${n}ms of inactivity: ${e} ${r.join(" ")}`)))},Nt=setTimeout(Ct,n);xe=s!==void 0?setTimeout(()=>{N||(tr(h),N=!0,clearTimeout(Nt),We(),O(),Xr(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=()=>{N||(N=!0,clearTimeout(Nt),We(),tr(h),O(),Xr(l,{type:"abort",command:e,args:r,reason:String(d.reason??"aborted")}),f(new Lt(d.reason)))},d.addEventListener("abort",k));let As=()=>{L||(clearTimeout(Nt),Nt=setTimeout(Ct,n))};if(h.stdout.on("data",Dt=>{_+=Dt.length,Xr(l,{type:"stdout",command:e,args:r,preview:kv(Dt.toString())}),_<=c&&(y+=Dt.toString()),F(),As()}),h.stderr.on("data",Dt=>{b+=Dt.length;let Rn=Dt.toString();if(Xr(l,{type:"stderr",command:e,args:r,preview:kv(Rn)}),b<=c&&(v+=Rn),F(),!L&&u){let ai=u(Rn);ai&&(x=ai,L=!0,tr(h))}As()}),a&&h.stdin){h.stdin.on("error",()=>{});try{h.stdin.write(a),h.stdin.end()}catch{}}h.on("close",(Dt,Rn)=>{if(clearTimeout(Nt),We(),!N){if(Xr(l,{type:"close",command:e,args:r,exitCode:Dt,signalCode:Rn}),x){N=!0,O(),f(x);return}N=!0,O(),p({stdout:y,stderr:v,exitCode:Dt??1,truncated:P})}}),h.on("error",Dt=>{clearTimeout(Nt),We(),!N&&(N=!0,O(),f(new Error(`CLI spawn error: ${Dt.message}`)))})})}var Lt,GR,Ns,li=Or(()=>{"use strict";js();Lt=class extends Error{constructor(e){let r=e instanceof Error?`: ${e.message}`:typeof e=="string"&&e?`: ${e}`:"";super(`CLI aborted${r}`),this.name="CliAbortedError"}};GR=new Set(["codex","gemini","npm","npx"]),Ns=new Map});import{writeFileSync as SC,mkdirSync as hi,openSync as Kd,writeSync as Jd,fsyncSync as Hv,closeSync as Gd,renameSync as $C,unlinkSync as Bv,appendFileSync as xC,copyFileSync as PC}from"fs";import{dirname as gi,join as kC}from"path";import{randomUUID as TC}from"crypto";function ge(t,e){let r=gi(t);hi(r,{recursive:!0});let n=kC(r,`.tmp-${TC().slice(0,8)}`);try{SC(n,e,"utf-8");try{$C(n,t)}catch(s){if(s.code!=="EXDEV")throw s;PC(n,t),Bv(n)}}catch(s){try{Bv(n)}catch{}throw s}}function Ze(t,e){ge(t,JSON.stringify(e,null,2))}function Tc(t,e){let r=gi(t);hi(r,{recursive:!0});let n=Kd(t,"a");try{Jd(n,e),Hv(n)}finally{Gd(n)}}var kc,sn=Or(()=>{"use strict";kc=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)Tc(e,r);else{let o=gi(e);hi(o,{recursive:!0}),xC(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=gi(e);hi(n,{recursive:!0});let s=Kd(e,"a");try{Jd(s,r.join("")),Hv(s)}finally{Gd(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=gi(e);hi(n,{recursive:!0});let s=Kd(e,"a");try{Jd(s,r.join(""))}finally{Gd(s)}this.buffer.delete(e)}}});import{openSync as EC,writeSync as IC,closeSync as RC,unlinkSync as Wv,statSync as AC,mkdirSync as CC}from"fs";import{dirname as DC}from"path";function jC(t){if(t<=0)return;let e=new SharedArrayBuffer(4),r=new Int32Array(e);Atomics.wait(r,0,0,t)}function Gn(t,e,r={}){let n=r.staleMs??OC,s=r.acquireTimeoutMs??MC,o=r.pollMs??zC;CC(DC(t),{recursive:!0});let i=Date.now(),a=null;for(;a===null;)try{a=EC(t,"wx")}catch(c){let u=c.code;if(!(u==="EEXIST"||process.platform==="win32"&&u==="EPERM"))throw c;let d=!1;try{let f=AC(t);d=Date.now()-f.mtimeMs>n}catch{}if(d){try{Wv(t)}catch{}continue}let p=Date.now()-i;if(p>=s)throw new Yd(t,p);jC(o)}try{try{IC(a,`${process.pid}@${Date.now()}
|
|
5
|
+
`)}catch{}return e()}finally{try{RC(a)}catch{}try{Wv(t)}catch{}}}var OC,MC,zC,Yd,Ec=Or(()=>{"use strict";OC=3e4,MC=5e3,zC=10,Yd=class extends Error{constructor(e,r){super(`withFileLock: timed out after ${r}ms waiting for ${e}`),this.name="FileLockTimeoutError"}}});import{existsSync as Kv,realpathSync as NC}from"fs";import{basename as LC,dirname as FC,isAbsolute as Qd,join as qC,normalize as Gv,resolve as ep,relative as UC}from"path";function ZC(t){return t===""||!t.startsWith("..")&&!Qd(t)}function Xd(t){let e=[],r=ep(t);for(;!Kv(r);){let s=FC(r);if(s===r)break;e.unshift(LC(r)),r=s}let n=Kv(r)?NC(r):r;return e.reduce((s,o)=>qC(s,o),n)}function Yv(t,e){let r=Xd(e),n=Xd(t),s=UC(r,n);return ZC(s)}function tp(t,e){let r=ep(e,t);return Yv(r,e)}function Zt(t,e){let r=ep(e,t);if(!Yv(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 Zt(t,e)}function on(t,e){if(Qd(t)){let r=Gv(t);if(!tp(r,e))throw new Error(`Read path outside base directory: ${t} is not within ${e}`);return r}return Zt(t,e)}function Xv(t,e){return Qd(t)?Xd(Gv(t)):Zt(t,e)}function Fr(t){return VC.test(t)}function Ic(t,e){if(!t||typeof t!="string")throw new Mt(String(t),"command must be a non-empty string");if(t.includes("\0"))throw new Mt(t,"command contains null byte");if(t.includes("/")||t.includes("\\"))throw new Mt(t,"command must not contain path separators");if(!Jv.has(t))throw new Mt(t,`command is not in the allowlist (${[...Jv].join(", ")})`);for(let r of e){if(typeof r!="string")throw new Mt(t,`args contain a non-string entry: ${JSON.stringify(r)}`);if(r.includes("\0"))throw new Mt(t,`arg contains null byte: ${JSON.stringify(r)}`);if(BC.has(r))throw new Mt(t,`arg ${JSON.stringify(r)} is a code-execution flag and is not permitted`)}}var VC,Jv,BC,Mt,Ks=Or(()=>{"use strict";VC=/^[a-zA-Z0-9_-]+-\d+-[a-f0-9]{6}$/;Jv=new Set(["gemini","codex","claude","npx","node","npm","tsc"]),BC=new Set(["-e","--eval","-c","--command","-E","--execute","--exec"]),Mt=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 WC}from"path";function Ve(t,e){let r=WC(t,"status.json"),n=`${r}.lock`;Gn(n,()=>{let s=JSON.parse(HC(r,"utf-8"));Ze(r,{...s,...e})})}var yi=Or(()=>{"use strict";sn();Ec()});import{spawn as KC}from"child_process";import{join as rp}from"path";function Qv(t){let e=t.replace(/\s+/g," ").trim();return e.length>200?`${e.slice(0,200)}...`:e}function Rc(t){return new Promise(e=>{let r=Dn(t.command,t.args),n={kind:"start",updatedAt:new Date().toISOString(),message:"CLI process started",command:r.command,timeoutMs:t.timeoutMs,stdoutBytes:0,stderrBytes:0},s=0,o,i=(y,v={})=>{Object.assign(n,y,{updatedAt:new Date().toISOString()});let _=Date.now(),b=n.kind!==o;if(!(!v.force&&!b&&_-s<JC))try{Ve(t.jobDir,{activity:{...n}}),s=_,o=n.kind}catch{}};i(n,{force:!0});let a=KC(r.command,r.args,{cwd:t.cwd,stdio:["ignore","pipe","pipe"],windowsHide:!0});if(t.recordPid&&typeof a.pid=="number"&&a.pid>0)try{Ve(t.jobDir,{pid:a.pid})}catch{}if(!a.stdout||!a.stderr){try{a.kill()}catch{}try{ge(rp(t.jobDir,"error.txt"),"Worker stdout/stderr streams unavailable (pipe allocation failed)"),Ve(t.jobDir,{state:"error",completedAt:new Date().toISOString()})}catch{}e();return}let c="",u="",l=0,d=0,p=!1,f=!1;a.stdout.on("data",y=>{l+=y.length,i({kind:"stdout",message:"stdout received",stdoutBytes:l,stderrBytes:d,lastStdoutPreview:Qv(y.toString())}),l<=10485760?c+=y.toString():p||(p=!0,tr(a))}),a.stderr.on("data",y=>{d+=y.length,i({kind:"stderr",message:"stderr received",stdoutBytes:l,stderrBytes:d,lastStderrPreview:Qv(y.toString())}),d<=10485760&&(u+=y.toString())});let m=(y,v)=>{if(!f){f=!0,clearTimeout(h);try{ge(rp(t.jobDir,"output.txt"),c),ge(rp(t.jobDir,"error.txt"),v!==void 0?v:u),Ve(t.jobDir,y)}catch{}e()}},h=setTimeout(()=>{tr(a),i({kind:"timeout",message:`timed out after ${t.timeoutMs}ms`,timeoutMs:t.timeoutMs,stdoutBytes:l,stderrBytes:d},{force:!0}),m({state:"timed_out",completedAt:new Date().toISOString()})},t.timeoutMs);a.on("close",y=>{if(f)return;let v=c.trim().length>0,_=y===0||v?"completed":"error";i({kind:"close",message:"CLI process closed",exitCode:y??1,stdoutBytes:l,stderrBytes:d},{force:!0}),m({state:_,exitCode:y??1,completedAt:new Date().toISOString()})}),a.on("error",y=>{if(f)return;let v=y.code==="ENOENT"?"missing_cli":"error";i({kind:"close",message:`CLI spawn error: ${y.message}`,stdoutBytes:l,stderrBytes:d},{force:!0}),m({state:v,completedAt:new Date().toISOString()},y.message)})})}var JC,np=Or(()=>{"use strict";sn();li();js();yi();JC=1e3});var n_={};rt(n_,{CLI_PROVIDERS:()=>t_,resolveCliConfig:()=>r_});import{readFileSync as e_}from"fs";import{join as Yn}from"path";function r_(t){let e=GC[t.provider]??t.provider;return t_[e]??null}async function YC(){let t=process.argv[2];t||process.exit(1);let e;try{e=JSON.parse(e_(Yn(t,"job.json"),"utf-8"))}catch{try{Ze(Yn(t,"status.json"),{id:"unknown",state:"error",provider:"unknown",completedAt:new Date().toISOString()}),ge(Yn(t,"error.txt"),"Failed to read job.json")}catch{}process.exit(1)}let r=r_(e);r||(Ve(t,{state:"missing_cli",completedAt:new Date().toISOString()}),ge(Yn(t,"error.txt"),`No CLI mapping for provider: ${e.provider}`),process.exit(1));let{command:n,buildArgs:s}=r;Ve(t,{state:"running",startedAt:new Date().toISOString()});let o=e_(Yn(t,"prompt.txt"),"utf-8"),i=s(o);try{Ic(n,i)}catch(c){let u=c instanceof Mt?c.message:`Argv rejected: ${c.message}`;Ve(t,{state:"error",completedAt:new Date().toISOString()}),ge(Yn(t,"error.txt"),u);return}let a;if(e.cwd)try{a=Zt(e.cwd,process.cwd())}catch(c){Ve(t,{state:"error",completedAt:new Date().toISOString()}),ge(Yn(t,"error.txt"),`Rejected descriptor.cwd: ${c.message}`);return}await Rc({jobDir:t,command:n,args:i,cwd:a,timeoutMs:e.timeout,recordPid:!1})}var GC,t_,XC,s_=Or(()=>{"use strict";sn();Ks();np();yi();GC={"gemini-cli":"gemini","codex-cli":"codex","claude-cli":"claude"},t_={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]}};XC=process.argv[1]?.endsWith("job-worker.js")||process.argv[1]?.endsWith("job-worker.ts");XC&&YC().catch(()=>process.exit(1))});var sa=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 ra=class{};me._CodeOrName=ra;me.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var is=class extends ra{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=is;var Wt=class extends ra{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 is&&(r[n.str]=(r[n.str]||0)+1),r),{})}};me._Code=Wt;me.nil=new Wt("");function dx(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Lf(r,e[n]),r.push(t[++n]);return new Wt(r)}me._=dx;var Nf=new Wt("+");function px(t,...e){let r=[na(t[0])],n=0;for(;n<e.length;)r.push(Nf),Lf(r,e[n]),r.push(Nf,na(t[++n]));return tN(r),new Wt(r)}me.str=px;function Lf(t,e){e instanceof Wt?t.push(...e._items):e instanceof is?t.push(e):t.push(sN(e))}me.addCodeArg=Lf;function tN(t){let e=1;for(;e<t.length-1;){if(t[e]===Nf){let r=rN(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function rN(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof is||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 is))return`"${t}${e.slice(1)}`}function nN(t,e){return e.emptyStr()?t:t.emptyStr()?e:px`${t}${e}`}me.strConcat=nN;function sN(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:na(Array.isArray(t)?t.join(","):t)}function oN(t){return new Wt(na(t))}me.stringify=oN;function na(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}me.safeStringify=na;function iN(t){return typeof t=="string"&&me.IDENTIFIER.test(t)?new Wt(`.${t}`):dx`[${t}]`}me.getProperty=iN;function aN(t){if(typeof t=="string"&&me.IDENTIFIER.test(t))return new Wt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}me.getEsmExportName=aN;function cN(t){return new Wt(t.toString())}me.regexpCode=cN});var Uf=S(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.ValueScope=xt.ValueScopeName=xt.Scope=xt.varKinds=xt.UsedValueState=void 0;var $t=sa(),Ff=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},zu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(zu||(xt.UsedValueState=zu={}));xt.varKinds={const:new $t.Name("const"),let:new $t.Name("let"),var:new $t.Name("var")};var ju=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}}};xt.Scope=ju;var Nu=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}]`}};xt.ValueScopeName=Nu;var uN=(0,$t._)`\n`,qf=class extends ju{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?uN:$t.nil}}get(){return this._scope}name(e){return new Nu(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,$t._)`${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=$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,zu.Started);let l=r(u);if(l){let d=this.opts.es5?xt.varKinds.var:xt.varKinds.const;o=(0,$t._)`${o}${d} ${u} = ${l};${this.opts._n}`}else if(l=s?.(u))o=(0,$t._)`${o}${l}${this.opts._n}`;else throw new Ff(u);c.set(u,zu.Completed)})}return o}};xt.ValueScope=qf});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=sa(),ir=Uf(),fn=sa();Object.defineProperty(Q,"_",{enumerable:!0,get:function(){return fn._}});Object.defineProperty(Q,"str",{enumerable:!0,get:function(){return fn.str}});Object.defineProperty(Q,"strConcat",{enumerable:!0,get:function(){return fn.strConcat}});Object.defineProperty(Q,"nil",{enumerable:!0,get:function(){return fn.nil}});Object.defineProperty(Q,"getProperty",{enumerable:!0,get:function(){return fn.getProperty}});Object.defineProperty(Q,"stringify",{enumerable:!0,get:function(){return fn.stringify}});Object.defineProperty(Q,"regexpCode",{enumerable:!0,get:function(){return fn.regexpCode}});Object.defineProperty(Q,"Name",{enumerable:!0,get:function(){return fn.Name}});var Uu=Uf();Object.defineProperty(Q,"Scope",{enumerable:!0,get:function(){return Uu.Scope}});Object.defineProperty(Q,"ValueScope",{enumerable:!0,get:function(){return Uu.ValueScope}});Object.defineProperty(Q,"ValueScopeName",{enumerable:!0,get:function(){return Uu.ValueScopeName}});Object.defineProperty(Q,"varKinds",{enumerable:!0,get:function(){return Uu.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 Zr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Zf=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?ir.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=wo(this.rhs,e,r)),this}get names(){return this.rhs instanceof ce._CodeOrName?this.rhs.names:{}}},Lu=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 ce.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=wo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ce.Name?{}:{...this.lhs.names};return qu(e,this.rhs)}},Vf=class extends Lu{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Bf=class extends Zr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Hf=class extends Zr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Wf=class extends Zr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Kf=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=wo(this.code,e,r),this}get names(){return this.code instanceof ce._CodeOrName?this.code.names:{}}},oa=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,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(lN(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>us(e,r.names),{})}},Vr=class extends oa{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Jf=class extends oa{},bo=class extends Vr{};bo.kind="else";var as=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 bo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(fx(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=wo(this.condition,e,r),this}get names(){let e=super.names;return qu(e,this.condition),this.else&&us(e,this.else.names),e}};as.kind="if";var cs=class extends Vr{};cs.kind="for";var Gf=class extends cs{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=wo(this.iteration,e,r),this}get names(){return us(super.names,this.iteration.names)}},Yf=class extends cs{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?ir.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=qu(super.names,this.from);return qu(e,this.to)}},Fu=class extends cs{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=wo(this.iterable,e,r),this}get names(){return us(super.names,this.iterable.names)}},ia=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)}};ia.kind="func";var aa=class extends oa{render(e){return"return "+super.render(e)}};aa.kind="return";var Xf=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,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&&us(e,this.catch.names),this.finally&&us(e,this.finally.names),e}},ca=class extends Vr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ca.kind="catch";var ua=class extends Vr{render(e){return"finally"+super.render(e)}};ua.kind="finally";var Qf=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
6
|
+
`:""},this._extScope=e,this._scope=new ir.Scope({parent:e}),this._nodes=[new Jf]}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 Zf(e,o,n)),o}const(e,r,n){return this._def(ir.varKinds.const,e,r,n)}let(e,r,n){return this._def(ir.varKinds.let,e,r,n)}var(e,r,n){return this._def(ir.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Lu(e,r,n))}add(e,r){return this._leafNode(new Vf(e,Q.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ce.nil&&this._leafNode(new Kf(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 as(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 as(e))}else(){return this._elseNode(new bo)}endIf(){return this._endBlockNode(as,bo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Gf(e),r)}forRange(e,r,n,s,o=this.opts.es5?ir.varKinds.var:ir.varKinds.let){let i=this._scope.toName(e);return this._for(new Yf(o,i,r,n),()=>s(i))}forOf(e,r,n,s=ir.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 Fu("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?ir.varKinds.var:ir.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 Fu("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(cs)}label(e){return this._leafNode(new Bf(e))}break(e){return this._leafNode(new Hf(e))}return(e){let r=new aa;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(aa)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Xf;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new ca(o),r(o)}return n&&(this._currNode=s.finally=new ua,this.code(n)),this._endBlockNode(ca,ua)}throw(e){return this._leafNode(new Wf(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 ia(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(ia)}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 as))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=Qf;function us(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function qu(t,e){return e instanceof ce._CodeOrName?us(t,e.names):t}function wo(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 lN(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function fx(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ce._)`!${em(t)}`}Q.not=fx;var dN=mx(Q.operators.AND);function pN(...t){return t.reduce(dN)}Q.and=pN;var fN=mx(Q.operators.OR);function mN(...t){return t.reduce(fN)}Q.or=mN;function mx(t){return(e,r)=>e===ce.nil?r:r===ce.nil?e:(0,ce._)`${em(e)} ${t} ${em(r)}`}function em(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 Se=te(),hN=sa();function gN(t){let e={};for(let r of t)e[r]=!0;return e}re.toHash=gN;function yN(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(yx(t,e),!vx(e,t.self.RULES.all))}re.alwaysValidSchema=yN;function yx(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]||wx(t,`unknown keyword: "${o}"`)}re.checkUnknownRules=yx;function vx(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}re.schemaHasRules=vx;function vN(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=vN;function _N({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)}`}re.schemaRefOrVal=_N;function bN(t){return _x(decodeURIComponent(t))}re.unescapeFragment=bN;function wN(t){return encodeURIComponent(rm(t))}re.escapeFragment=wN;function rm(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=rm;function _x(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=_x;function SN(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}re.eachItem=SN;function hx({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}}re.mergeEvaluated={props:hx({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} || {}`),nm(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:bx}),items:hx({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 bx(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Se._)`{}`);return e!==void 0&&nm(t,r,e),r}re.evaluatedPropsToName=bx;function nm(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Se._)`${e}${(0,Se.getProperty)(n)}`,!0))}re.setEvaluated=nm;var gx={};function $N(t,e){return t.scopeValue("func",{ref:e,code:gx[e.code]||(gx[e.code]=new hN._Code(e.code))})}re.useFunc=$N;var tm;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(tm||(re.Type=tm={}));function xN(t,e,r){if(t instanceof Se.Name){let n=e===tm.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():"/"+rm(t)}re.getErrorPath=xN;function wx(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=wx});var Br=S(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});var ot=te(),PN={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")};sm.default=PN});var la=S(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.extendErrors=it.resetErrorsCount=it.reportExtraError=it.reportError=it.keyword$DataError=it.keywordError=void 0;var de=te(),Zu=le(),mt=Br();it.keywordError={message:({keyword:t})=>(0,de.str)`must pass "${t}" keyword validation`};it.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=it.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=xx(t,e,r);n??(i||a)?Sx(o,c):$x(s,(0,de._)`[${c}]`)}it.reportError=kN;function TN(t,e=it.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=xx(t,e,r);Sx(s,a),o||i||$x(n,mt.default.vErrors)}it.reportExtraError=TN;function EN(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)))}it.resetErrorsCount=EN;function IN({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))})}it.extendErrors=IN;function Sx(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 ls={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 xx(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,de._)`{}`:RN(t,e,r)}function RN(t,e,r={}){let{gen:n,it:s}=t,o=[AN(s,r),CN(t,r)];return DN(t,e,o),n.object(...o)}function AN({errorPath:t},{instancePath:e}){let r=e?(0,de.str)`${t}${(0,Zu.getErrorPath)(e,Zu.Type.Str)}`:t;return[mt.default.instancePath,(0,de.strConcat)(mt.default.instancePath,r)]}function CN({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,Zu.getErrorPath)(r,Zu.Type.Str)}`),[ls.schemaPath,s]}function DN(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([ls.keyword,s],[ls.params,typeof e=="function"?e(t):e||(0,de._)`{}`]),c.messages&&n.push([ls.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([ls.schema,i],[ls.parentSchema,(0,de._)`${l}${d}`],[mt.default.data,o]),u&&n.push([ls.propertyName,u])}});var kx=S(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.boolOrEmptySchema=So.topBoolOrEmptySchema=void 0;var ON=la(),MN=te(),zN=Br(),jN={message:"boolean schema is false"};function NN(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Px(t,!1):typeof r=="object"&&r.$async===!0?e.return(zN.default.data):(e.assign((0,MN._)`${n}.errors`,null),e.return(!0))}So.topBoolOrEmptySchema=NN;function LN(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Px(t)):r.var(e,!0)}So.boolOrEmptySchema=LN;function Px(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,ON.reportError)(s,jN,void 0,e)}});var om=S($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.getRules=$o.isJSONType=void 0;var FN=["string","number","integer","boolean","null","object","array"],qN=new Set(FN);function UN(t){return typeof t=="string"&&qN.has(t)}$o.isJSONType=UN;function ZN(){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:{}}}$o.getRules=ZN});var im=S(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.shouldUseRule=mn.shouldUseGroup=mn.schemaHasRulesForType=void 0;function VN({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Tx(t,n)}mn.schemaHasRulesForType=VN;function Tx(t,e){return e.rules.some(r=>Ex(t,r))}mn.shouldUseGroup=Tx;function Ex(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))}mn.shouldUseRule=Ex});var da=S(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.reportTypeError=at.checkDataTypes=at.checkDataType=at.coerceAndCheckDataType=at.getJSONTypes=at.getSchemaTypes=at.DataType=void 0;var BN=om(),HN=im(),WN=la(),J=te(),Ix=le(),xo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(xo||(at.DataType=xo={}));function KN(t){let e=Rx(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}at.getSchemaTypes=KN;function Rx(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(BN.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}at.getJSONTypes=Rx;function JN(t,e){let{gen:r,data:n,opts:s}=t,o=GN(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,HN.schemaHasRulesForType)(t,e[0]));if(i){let a=cm(e,n,s.strictNumbers,xo.Wrong);r.if(a,()=>{o.length?YN(t,e,o):um(t)})}return i}at.coerceAndCheckDataType=JN;var Ax=new Set(["string","number","integer","boolean","null"]);function GN(t,e){return e?t.filter(r=>Ax.has(r)||e==="array"&&r==="array"):[]}function YN(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(cm(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,J._)`${a} !== undefined`);for(let u of r)(Ax.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),um(t),n.endIf(),n.if((0,J._)`${a} !== undefined`,()=>{n.assign(s,a),XN(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
7
|
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,J._)`+${s}`);return;case"integer":n.elseIf((0,J._)`${i} === "boolean" || ${s} === null
|
|
15
8
|
|| (${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 EZ({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,J._)`${e} !== undefined`,()=>t.assign((0,J._)`${e}[${r}]`,n))}function Vh(t,e,r,n=Oo.Correct){let s=n===Oo.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===Oo.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)}}lt.checkDataType=Vh;function Bh(t,e,r,n){if(t.length===1)return Vh(t[0],e,r,n);let s,o=(0,YP.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,Vh(i,e,r,n));return s}lt.checkDataTypes=Bh;var TZ={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,J._)`{type: ${t}}`:(0,J._)`{type: ${e}}`};function Hh(t){let e=IZ(t);(0,SZ.reportError)(e,TZ)}lt.reportTypeError=Hh;function IZ(t){let{gen:e,data:r,schema:n}=t,s=(0,YP.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var tk=S(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});yl.assignDefaults=void 0;var Mo=X(),RZ=pe();function AZ(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)ek(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>ek(t,o,s.default))}yl.assignDefaults=AZ;function ek(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,Mo._)`${o}${(0,Mo.getProperty)(e)}`;if(s){(0,RZ.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Mo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Mo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Mo._)`${a} = ${(0,Mo.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(),Wh=pe(),bn=Kr(),CZ=pe();function DZ(t,e){let{gen:r,data:n,it:s}=t;r.if(Jh(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ce._)`${e}`},!0),t.error()})}be.checkReportMissingProp=DZ;function OZ({gen:t,data:e,it:{opts:r}},n,s){return(0,Ce.or)(...n.map(o=>(0,Ce.and)(Jh(t,e,o,r.ownProperties),(0,Ce._)`${s} = ${o}`)))}be.checkMissingProp=OZ;function MZ(t,e){t.setParams({missingProperty:e},!0),t.error()}be.reportMissingProp=MZ;function rk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ce._)`Object.prototype.hasOwnProperty`})}be.hasPropFunc=rk;function Kh(t,e,r){return(0,Ce._)`${rk(t)}.call(${e}, ${r})`}be.isOwnProperty=Kh;function zZ(t,e,r,n){let s=(0,Ce._)`${e}${(0,Ce.getProperty)(r)} !== undefined`;return n?(0,Ce._)`${s} && ${Kh(t,e,r)}`:s}be.propertyInData=zZ;function Jh(t,e,r,n){let s=(0,Ce._)`${e}${(0,Ce.getProperty)(r)} === undefined`;return n?(0,Ce.or)(s,(0,Ce.not)(Kh(t,e,r))):s}be.noPropertyInData=Jh;function nk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}be.allSchemaProperties=nk;function jZ(t,e){return nk(e).filter(r=>!(0,Wh.alwaysValidSchema)(t,e[r]))}be.schemaProperties=jZ;function NZ({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=[[bn.default.instancePath,(0,Ce.strConcat)(bn.default.instancePath,o)],[bn.default.parentData,i.parentData],[bn.default.parentDataProperty,i.parentDataProperty],[bn.default.rootData,bn.default.rootData]];i.opts.dynamicRef&&d.push([bn.default.dynamicAnchors,bn.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=NZ;var LZ=(0,Ce._)`new RegExp`;function qZ({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"?LZ:(0,CZ.useFunc)(t,s)}(${r}, ${n})`})}be.usePattern=qZ;function FZ(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:Wh.Type.Num},o),e.if((0,Ce.not)(o),a)})}}be.validateArray=FZ;function UZ(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,Wh.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=UZ});var ik=S(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.validateKeywordUsage=Er.validSchemaType=Er.funcKeywordCode=Er.macroKeywordCode=void 0;var yt=X(),_s=Kr(),ZZ=Gt(),VZ=Oa();function BZ(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=ok(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=BZ;function HZ(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=ok(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&&sk(t),y(()=>t.error());else{let g=e.async?f():m();e.modifying&&sk(t),y(()=>WZ(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?_s.default.this:_s.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,yt._)`${g}${(0,ZZ.callValidateCode)(t,l,b,_)}`,e.modifying)}function y(g){var b;n.if((0,yt.not)((b=e.valid)!==null&&b!==void 0?b:d),g)}}Er.funcKeywordCode=HZ;function sk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,yt._)`${n.parentData}[${n.parentDataProperty}]`))}function WZ(t,e){let{gen:r}=t;r.if((0,yt._)`Array.isArray(${e})`,()=>{r.assign(_s.default.vErrors,(0,yt._)`${_s.default.vErrors} === null ? ${e} : ${_s.default.vErrors}.concat(${e})`).assign(_s.default.errors,(0,yt._)`${_s.default.vErrors}.length`),(0,VZ.extendErrors)(t)},()=>t.error())}function KZ({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function ok(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 JZ(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=JZ;function GZ({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=GZ});var ck=S(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.extendSubschemaMode=wn.extendSubschemaData=wn.getSubschema=void 0;var Tr=X(),ak=pe();function YZ(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,ak.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')}wn.getSubschema=YZ;function XZ(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,ak.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]}}wn.extendSubschemaData=XZ;function QZ(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}wn.extendSubschemaMode=QZ});var lk=S((Cee,uk)=>{"use strict";var Sn=uk.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(){};vl(e,n,s,t,"",t)};Sn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Sn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Sn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Sn.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 vl(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 Sn.arrayKeywords)for(var p=0;p<d.length;p++)vl(t,e,r,d[p],s+"/"+l+"/"+p,o,s,l,n,p)}else if(l in Sn.propsKeywords){if(d&&typeof d=="object")for(var f in d)vl(t,e,r,d[f],s+"/"+l+"/"+eV(f),o,s,l,n,f)}else(l in Sn.keywords||t.allKeys&&!(l in Sn.skipKeywords))&&vl(t,e,r,d,s+"/"+l,o,s,l,n)}r(n,s,o,i,a,c,u)}}function eV(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var za=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 tV=pe(),rV=aa(),nV=lk(),sV=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function oV(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Gh(t):e?dk(t)<=e:!1}Tt.inlineRef=oV;var iV=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Gh(t){for(let e in t){if(iV.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Gh)||typeof r=="object"&&Gh(r))return!0}return!1}function dk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!sV.has(r)&&(typeof t[r]=="object"&&(0,tV.eachItem)(t[r],n=>e+=dk(n)),e===1/0))return 1/0}return e}function pk(t,e="",r){r!==!1&&(e=zo(e));let n=t.parse(e);return fk(t,n)}Tt.getFullPath=pk;function fk(t,e){return t.serialize(e).split("#")[0]+"#"}Tt._getFullPath=fk;var aV=/#\/?$/;function zo(t){return t?t.replace(aV,""):""}Tt.normalizeId=zo;function cV(t,e,r){return r=zo(r),t.resolve(e,r)}Tt.resolveUrl=cV;var uV=/^[a-z_][-a-z0-9._]*$/i;function lV(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=zo(t[r]||e),o={"":s},i=pk(n,s,!1),a={},c=new Set;return nV(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=i+p,y=o[m];typeof d[r]=="string"&&(y=g.call(this,d[r])),b.call(this,d.$anchor),b.call(this,d.$dynamicAnchor),o[p]=y;function g(_){let P=this.opts.uriResolver.resolve;if(_=zo(y?P(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,_):_!==zo(h)&&(_[0]==="#"?(u(d,a[_],_),a[_]=d):this.refs[_]=h),_}function b(_){if(typeof _=="string"){if(!uV.test(_))throw new Error(`invalid anchor "${_}"`);g.call(this,`#${_}`)}}}),a;function u(d,p,f){if(p!==void 0&&!rV(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Tt.getSchemaRefs=lV});var La=S($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.getData=$n.KeywordCxt=$n.validateFunctionCode=void 0;var vk=KP(),mk=Ma(),Xh=Zh(),_l=Ma(),dV=tk(),Na=ik(),Yh=ck(),j=X(),B=Kr(),pV=za(),Jr=pe(),ja=Oa();function fV(t){if(wk(t)&&(Sk(t),bk(t))){gV(t);return}_k(t,()=>(0,vk.topBoolOrEmptySchema)(t))}$n.validateFunctionCode=fV;function _k({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,j._)`${B.default.data}, ${B.default.valCxt}`,n.$async,()=>{t.code((0,j._)`"use strict"; ${hk(r,s)}`),hV(t,s),t.code(o)}):t.func(e,(0,j._)`${B.default.data}, ${mV(s)}`,n.$async,()=>t.code(hk(r,s)).code(o))}function mV(t){return(0,j._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${t.dynamicRef?(0,j._)`, ${B.default.dynamicAnchors}={}`:j.nil}}={}`}function hV(t,e){t.if(B.default.valCxt,()=>{t.var(B.default.instancePath,(0,j._)`${B.default.valCxt}.${B.default.instancePath}`),t.var(B.default.parentData,(0,j._)`${B.default.valCxt}.${B.default.parentData}`),t.var(B.default.parentDataProperty,(0,j._)`${B.default.valCxt}.${B.default.parentDataProperty}`),t.var(B.default.rootData,(0,j._)`${B.default.valCxt}.${B.default.rootData}`),e.dynamicRef&&t.var(B.default.dynamicAnchors,(0,j._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{t.var(B.default.instancePath,(0,j._)`""`),t.var(B.default.parentData,(0,j._)`undefined`),t.var(B.default.parentDataProperty,(0,j._)`undefined`),t.var(B.default.rootData,B.default.data),e.dynamicRef&&t.var(B.default.dynamicAnchors,(0,j._)`{}`)})}function gV(t){let{schema:e,opts:r,gen:n}=t;_k(t,()=>{r.$comment&&e.$comment&&xk(t),wV(t),n.let(B.default.vErrors,null),n.let(B.default.errors,0),r.unevaluated&&yV(t),$k(t),xV(t)})}function yV(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,j._)`${r}.evaluated`),e.if((0,j._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,j._)`${t.evaluated}.props`,(0,j._)`undefined`)),e.if((0,j._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,j._)`${t.evaluated}.items`,(0,j._)`undefined`))}function hk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,j._)`/*# sourceURL=${r} */`:j.nil}function vV(t,e){if(wk(t)&&(Sk(t),bk(t))){_V(t,e);return}(0,vk.boolOrEmptySchema)(t,e)}function bk({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 wk(t){return typeof t.schema!="boolean"}function _V(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&xk(t),SV(t),$V(t);let o=n.const("_errs",B.default.errors);$k(t,o),n.var(e,(0,j._)`${o} === ${B.default.errors}`)}function Sk(t){(0,Jr.checkUnknownRules)(t),bV(t)}function $k(t,e){if(t.opts.jtd)return gk(t,[],!1,e);let r=(0,mk.getSchemaTypes)(t.schema),n=(0,mk.coerceAndCheckDataType)(t,r);gk(t,r,!n,e)}function bV(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Jr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function wV(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Jr.checkStrictMode)(t,"default is ignored in the schema root")}function SV(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,pV.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function $V(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function xk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,j._)`${B.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,j.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,j._)`${B.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function xV(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,j._)`${B.default.errors} === 0`,()=>e.return(B.default.data),()=>e.throw((0,j._)`new ${s}(${B.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,B.default.vErrors),o.unevaluated&&PV(t),e.return((0,j._)`${B.default.errors} === 0`))}function PV({gen:t,evaluated:e,props:r,items:n}){r instanceof j.Name&&t.assign((0,j._)`${e}.props`,r),n instanceof j.Name&&t.assign((0,j._)`${e}.items`,n)}function gk(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,Jr.schemaHasRulesButRef)(o,l))){s.block(()=>kk(t,"$ref",l.all.$ref.definition));return}c.jtd||kV(t,e),s.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Xh.shouldUseGroup)(o,p)&&(p.type?(s.if((0,_l.checkDataType)(p.type,i,c.strictNumbers)),yk(t,p),e.length===1&&e[0]===p.type&&r&&(s.else(),(0,_l.reportTypeError)(t)),s.endIf()):yk(t,p),a||s.if((0,j._)`${B.default.errors} === ${n||0}`))}}function yk(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,dV.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,Xh.shouldUseRule)(n,o)&&kk(t,o.keyword,o.definition,e.type)})}function kV(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(EV(t,e),t.opts.allowUnionTypes||TV(t,e),IV(t,t.dataTypes))}function EV(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Pk(t.dataTypes,r)||Qh(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),AV(t,e)}}function TV(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Qh(t,"use allowUnionTypes to allow union type keyword")}function IV(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,Xh.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>RV(e,i))&&Qh(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function RV(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 AV(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 Qh(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Jr.checkStrictMode)(t,e,t.opts.strictTypes)}var bl=class{constructor(e,r,n){if((0,Na.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,Jr.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",Ek(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Na.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,j.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,j.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,j._)`${r} !== undefined && (${(0,j.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?ja.reportExtraError:ja.reportError)(this,this.def.error,r)}$dataError(){(0,ja.reportError)(this,this.def.$dataError||ja.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ja.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=j.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=j.nil,r=j.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,j.or)((0,j._)`${s} === undefined`,r)),e!==j.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==j.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,j.or)(i(),a());function i(){if(n.length){if(!(r instanceof j.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,j._)`${(0,_l.checkDataTypes)(c,r,o.opts.strictNumbers,_l.DataType.Wrong)}`}return j.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,j._)`!${c}(${r})`}return j.nil}}subschema(e,r){let n=(0,Yh.getSubschema)(this.it,e);(0,Yh.extendSubschemaData)(n,this.it,e),(0,Yh.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return vV(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Jr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Jr.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,j.Name)),!0}};$n.KeywordCxt=bl;function kk(t,e,r,n){let s=new bl(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Na.funcKeywordCode)(s,r):"macro"in r?(0,Na.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Na.funcKeywordCode)(s,r)}var CV=/^\/(?:[^~]|~0|~1)*$/,DV=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ek(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return B.default.rootData;if(t[0]==="/"){if(!CV.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,j._)`${o}${(0,j.getProperty)((0,Jr.unescapeJsonPointer)(u))}`,i=(0,j._)`${i} && ${o}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}$n.getData=Ek});var wl=S(tg=>{"use strict";Object.defineProperty(tg,"__esModule",{value:!0});var eg=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};tg.default=eg});var qa=S(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});var rg=za(),ng=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,rg.resolveUrl)(e,r,n),this.missingSchema=(0,rg.normalizeId)((0,rg.getFullPath)(e,this.missingRef))}};sg.default=ng});var $l=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(),OV=wl(),bs=Kr(),lr=za(),Tk=pe(),MV=La(),jo=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=jo;function ig(t){let e=Ik.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:OV.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:bs.default.data,parentData:bs.default.parentData,parentDataProperty:bs.default.parentDataProperty,dataNames:[bs.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,MV.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(bs.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${bs.default.self}`,`${bs.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=ig;function zV(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=LV.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 jo({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=jV.call(this,o)}Yt.resolveRef=zV;function jV(t){return(0,lr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:ig.call(this,t)}function Ik(t){for(let e of this._compilations)if(NV(e,t))return e}Yt.getCompilingSchema=Ik;function NV(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]||Sl.call(this,t,e)}function Sl(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 og.call(this,r,t);let o=(0,lr.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Sl.call(this,t,i);return typeof a?.schema!="object"?void 0:og.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||ig.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 jo({schema:a,schemaId:c,root:t,baseId:s})}return og.call(this,r,i)}}Yt.resolveSchema=Sl;var qV=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function og(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,Tk.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!qV.has(a)&&u&&(e=(0,lr.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,Tk.schemaHasRulesButRef)(r,this.RULES)){let a=(0,lr.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Sl.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new jo({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var Rk=S((Nee,FV)=>{FV.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 Ck=S(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});var Ak=$m();Ak.code='require("ajv/dist/runtime/uri").default';ag.default=Ak});var qk=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 UV=La();Object.defineProperty(et,"KeywordCxt",{enumerable:!0,get:function(){return UV.KeywordCxt}});var No=X();Object.defineProperty(et,"_",{enumerable:!0,get:function(){return No._}});Object.defineProperty(et,"str",{enumerable:!0,get:function(){return No.str}});Object.defineProperty(et,"stringify",{enumerable:!0,get:function(){return No.stringify}});Object.defineProperty(et,"nil",{enumerable:!0,get:function(){return No.nil}});Object.defineProperty(et,"Name",{enumerable:!0,get:function(){return No.Name}});Object.defineProperty(et,"CodeGen",{enumerable:!0,get:function(){return No.CodeGen}});var ZV=wl(),jk=qa(),VV=Uh(),Fa=$l(),BV=X(),Ua=za(),xl=Ma(),ug=pe(),Dk=Rk(),HV=Ck(),Nk=(t,e)=>new RegExp(t,e);Nk.code="new RegExp";var WV=["removeAdditional","useDefaults","coerceTypes"],KV=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),JV={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."},GV={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ok=200;function YV(t){var e,r,n,s,o,i,a,c,u,l,d,p,f,m,h,y,g,b,_,P,x,N,k,O,L;let q=t.strict,$e=(e=t.code)===null||e===void 0?void 0:e.optimize,We=$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:Nk,zt=(s=t.uriResolver)!==null&&s!==void 0?s:HV.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:We,regExp:Rt}:{optimize:We,regExp:Rt},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Ok,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Ok,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:(N=t.validateSchema)!==null&&N!==void 0?N:!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:zt}}var Za=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,...YV(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new BV.ValueScope({scope:{},prefixes:KV,es5:r,lines:n}),this.logger=nB(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,VV.getRules)(),Mk.call(this,JV,e,"NOT SUPPORTED"),Mk.call(this,GV,e,"DEPRECATED","warn"),this._metaOpts=tB.call(this),e.formats&&QV.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&eB.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),XV.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Dk;n==="id"&&(s={...Dk},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 jk.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,Ua.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=zk.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Fa.SchemaEnv({schema:{},schemaId:n});if(r=Fa.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=zk.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,Ua.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(oB.call(this,n,r),!r)return(0,ug.eachItem)(n,o=>cg.call(this,o)),this;aB.call(this,r);let s={...r,type:(0,xl.getJSONTypes)(r.type),schemaType:(0,xl.getJSONTypes)(r.schemaType)};return(0,ug.eachItem)(n,s.type.length===0?o=>cg.call(this,o,s):o=>s.type.forEach(i=>cg.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]=Lk(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,Ua.normalizeId)(i||n);let u=Ua.getSchemaRefs.call(this,e,n);return c=new Fa.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):Fa.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{Fa.compileSchema.call(this,e)}finally{this.opts=r}}};Za.ValidationError=ZV.default;Za.MissingRefError=jk.default;et.default=Za;function Mk(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 zk(t){return t=(0,Ua.normalizeId)(t),this.schemas[t]||this.refs[t]}function XV(){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 QV(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function eB(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 tB(){let t={...this.opts};for(let e of WV)delete t[e];return t}var rB={log(){},warn(){},error(){}};function nB(t){if(t===!1)return rB;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 sB=/^[a-z_$][a-z0-9_$:-]*$/i;function oB(t,e){let{RULES:r}=this;if((0,ug.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!sB.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 cg(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,xl.getJSONTypes)(e.type),schemaType:(0,xl.getJSONTypes)(e.schemaType)}};e.before?iB.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 iB(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 aB(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Lk(e)),t.validateSchema=this.compile(e,!0))}var cB={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Lk(t){return{anyOf:[t,cB]}}});var Fk=S(lg=>{"use strict";Object.defineProperty(lg,"__esModule",{value:!0});var uB={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};lg.default=uB});var Bk=S(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});ws.callRef=ws.getValidate=void 0;var lB=qa(),Uk=Gt(),It=X(),Lo=Kr(),Zk=$l(),Pl=pe(),dB={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=Zk.resolveRef.call(c,u,s,r);if(l===void 0)throw new lB.default(n.opts.uriResolver,s,r);if(l instanceof Zk.SchemaEnv)return p(l);return f(l);function d(){if(o===u)return kl(t,i,o,o.$async);let m=e.scopeValue("root",{ref:u});return kl(t,(0,It._)`${m}.validate`,u,u.$async)}function p(m){let h=Vk(t,m);kl(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}),y=e.name("valid"),g=t.subschema({schema:m,dataTypes:[],schemaPath:It.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(g),t.ok(y)}}};function Vk(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,It._)`${r.scopeValue("wrapper",{ref:e})}.validate`}ws.getValidate=Vk;function kl(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?Lo.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,Uk.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,Uk.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,It._)`${m}.errors`;s.assign(Lo.default.vErrors,(0,It._)`${Lo.default.vErrors} === null ? ${h} : ${Lo.default.vErrors}.concat(${h})`),s.assign(Lo.default.errors,(0,It._)`${Lo.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(o.props=Pl.mergeEvaluated.props(s,y.props,o.props));else{let g=s.var("props",(0,It._)`${m}.evaluated.props`);o.props=Pl.mergeEvaluated.props(s,g,o.props,It.Name)}if(o.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(o.items=Pl.mergeEvaluated.items(s,y.items,o.items));else{let g=s.var("items",(0,It._)`${m}.evaluated.items`);o.items=Pl.mergeEvaluated.items(s,g,o.items,It.Name)}}}ws.callRef=kl;ws.default=dB});var Hk=S(dg=>{"use strict";Object.defineProperty(dg,"__esModule",{value:!0});var pB=Fk(),fB=Bk(),mB=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",pB.default,fB.default];dg.default=mB});var Wk=S(pg=>{"use strict";Object.defineProperty(pg,"__esModule",{value:!0});var El=X(),xn=El.operators,Tl={maximum:{okStr:"<=",ok:xn.LTE,fail:xn.GT},minimum:{okStr:">=",ok:xn.GTE,fail:xn.LT},exclusiveMaximum:{okStr:"<",ok:xn.LT,fail:xn.GTE},exclusiveMinimum:{okStr:">",ok:xn.GT,fail:xn.LTE}},hB={message:({keyword:t,schemaCode:e})=>(0,El.str)`must be ${Tl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,El._)`{comparison: ${Tl[t].okStr}, limit: ${e}}`},gB={keyword:Object.keys(Tl),type:"number",schemaType:"number",$data:!0,error:hB,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,El._)`${r} ${Tl[e].fail} ${n} || isNaN(${r})`)}};pg.default=gB});var Kk=S(fg=>{"use strict";Object.defineProperty(fg,"__esModule",{value:!0});var Va=X(),yB={message:({schemaCode:t})=>(0,Va.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Va._)`{multipleOf: ${t}}`},vB={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:yB,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Va._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Va._)`${i} !== parseInt(${i})`;t.fail$data((0,Va._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};fg.default=vB});var Gk=S(mg=>{"use strict";Object.defineProperty(mg,"__esModule",{value:!0});function Jk(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}mg.default=Jk;Jk.code='require("ajv/dist/runtime/ucs2length").default'});var Yk=S(hg=>{"use strict";Object.defineProperty(hg,"__esModule",{value:!0});var Ss=X(),_B=pe(),bB=Gk(),wB={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Ss.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Ss._)`{limit: ${t}}`},SB={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:wB,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?Ss.operators.GT:Ss.operators.LT,i=s.opts.unicode===!1?(0,Ss._)`${r}.length`:(0,Ss._)`${(0,_B.useFunc)(t.gen,bB.default)}(${r})`;t.fail$data((0,Ss._)`${i} ${o} ${n}`)}};hg.default=SB});var Xk=S(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var $B=Gt(),xB=pe(),qo=X(),PB={message:({schemaCode:t})=>(0,qo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,qo._)`{pattern: ${t}}`},kB={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:PB,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,qo._)`new RegExp`:(0,xB.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,qo._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,qo._)`!${l}`)}else{let c=(0,$B.usePattern)(t,s);t.fail$data((0,qo._)`!${c}.test(${r})`)}}};gg.default=kB});var Qk=S(yg=>{"use strict";Object.defineProperty(yg,"__esModule",{value:!0});var Ba=X(),EB={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Ba.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ba._)`{limit: ${t}}`},TB={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:EB,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Ba.operators.GT:Ba.operators.LT;t.fail$data((0,Ba._)`Object.keys(${r}).length ${s} ${n}`)}};yg.default=TB});var eE=S(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});var Ha=Gt(),Wa=X(),IB=pe(),RB={message:({params:{missingProperty:t}})=>(0,Wa.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Wa._)`{missingProperty: ${t}}`},AB={keyword:"required",type:"object",schemaType:"array",$data:!0,error:RB,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 y=i.schemaEnv.baseId+i.errSchemaPath,g=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,IB.checkStrictMode)(i,g,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(Wa.nil,d);else for(let f of r)(0,Ha.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,Ha.checkMissingProp)(t,r,f)),(0,Ha.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Ha.noPropertyInData)(e,s,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,Ha.propertyInData)(e,s,f,a.ownProperties)),e.if((0,Wa.not)(m),()=>{t.error(),e.break()})},Wa.nil)}}};vg.default=AB});var tE=S(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});var Ka=X(),CB={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ka.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ka._)`{limit: ${t}}`},DB={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:CB,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Ka.operators.GT:Ka.operators.LT;t.fail$data((0,Ka._)`${r}.length ${s} ${n}`)}};_g.default=DB});var Il=S(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});var rE=aa();rE.code='require("ajv/dist/runtime/equal").default';bg.default=rE});var nE=S(Sg=>{"use strict";Object.defineProperty(Sg,"__esModule",{value:!0});var wg=Ma(),tt=X(),OB=pe(),MB=Il(),zB={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}}`},jB={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:zB,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,wg.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 y=e.name("item"),g=(0,wg.checkDataTypes)(u,y,a.opts.strictNumbers,wg.DataType.Wrong),b=e.const("indices",(0,tt._)`{}`);e.for((0,tt._)`;${m}--;`,()=>{e.let(y,(0,tt._)`${r}[${m}]`),e.if(g,(0,tt._)`continue`),u.length>1&&e.if((0,tt._)`typeof ${y} == "string"`,(0,tt._)`${y} += "_"`),e.if((0,tt._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(h,(0,tt._)`${b}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,tt._)`${b}[${y}] = ${m}`)})}function f(m,h){let y=(0,OB.useFunc)(e,MB.default),g=e.name("outer");e.label(g).for((0,tt._)`;${m}--;`,()=>e.for((0,tt._)`${h} = ${m}; ${h}--;`,()=>e.if((0,tt._)`${y}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(g)})))}}};Sg.default=jB});var sE=S(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var $g=X(),NB=pe(),LB=Il(),qB={message:"must be equal to constant",params:({schemaCode:t})=>(0,$g._)`{allowedValue: ${t}}`},FB={keyword:"const",$data:!0,error:qB,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,$g._)`!${(0,NB.useFunc)(e,LB.default)}(${r}, ${s})`):t.fail((0,$g._)`${o} !== ${r}`)}};xg.default=FB});var oE=S(Pg=>{"use strict";Object.defineProperty(Pg,"__esModule",{value:!0});var Ja=X(),UB=pe(),ZB=Il(),VB={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ja._)`{allowedValues: ${t}}`},BB={keyword:"enum",schemaType:"array",$data:!0,error:VB,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,UB.useFunc)(e,ZB.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,Ja.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,Ja._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let h=s[m];return typeof h=="object"&&h!==null?(0,Ja._)`${u()}(${r}, ${f}[${m}])`:(0,Ja._)`${r} === ${h}`}}};Pg.default=BB});var iE=S(kg=>{"use strict";Object.defineProperty(kg,"__esModule",{value:!0});var HB=Wk(),WB=Kk(),KB=Yk(),JB=Xk(),GB=Qk(),YB=eE(),XB=tE(),QB=nE(),e9=sE(),t9=oE(),r9=[HB.default,WB.default,KB.default,JB.default,GB.default,YB.default,XB.default,QB.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},e9.default,t9.default];kg.default=r9});var Tg=S(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.validateAdditionalItems=void 0;var $s=X(),Eg=pe(),n9={message:({params:{len:t}})=>(0,$s.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,$s._)`{limit: ${t}}`},s9={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:n9,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Eg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}aE(t,n)}};function aE(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,$s._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,$s._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Eg.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,$s._)`${a} <= ${e.length}`);r.if((0,$s.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:o,dataProp:l,dataPropType:Eg.Type.Num},u),i.allErrors||r.if((0,$s.not)(u),()=>r.break())})}}Ga.validateAdditionalItems=aE;Ga.default=s9});var Ig=S(Ya=>{"use strict";Object.defineProperty(Ya,"__esModule",{value:!0});Ya.validateTuple=void 0;var cE=X(),Rl=pe(),o9=Gt(),i9={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return uE(t,"additionalItems",e);r.items=!0,!(0,Rl.alwaysValidSchema)(r,e)&&t.ok((0,o9.validateArray)(t))}};function uE(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=Rl.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,cE._)`${o}.length`);r.forEach((d,p)=>{(0,Rl.alwaysValidSchema)(a,d)||(n.if((0,cE._)`${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,Rl.checkStrictMode)(a,y,p.strictTuples)}}}Ya.validateTuple=uE;Ya.default=i9});var lE=S(Rg=>{"use strict";Object.defineProperty(Rg,"__esModule",{value:!0});var a9=Ig(),c9={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,a9.validateTuple)(t,"items")};Rg.default=c9});var pE=S(Ag=>{"use strict";Object.defineProperty(Ag,"__esModule",{value:!0});var dE=X(),u9=pe(),l9=Gt(),d9=Tg(),p9={message:({params:{len:t}})=>(0,dE.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,dE._)`{limit: ${t}}`},f9={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:p9,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,u9.alwaysValidSchema)(n,e)&&(s?(0,d9.validateAdditionalItems)(t,s):t.ok((0,l9.validateArray)(t)))}};Ag.default=f9});var fE=S(Cg=>{"use strict";Object.defineProperty(Cg,"__esModule",{value:!0});var Xt=X(),Al=pe(),m9={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}}`},h9={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:m9,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,Al.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Al.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Al.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"),y=e.let("count",0);f(h,()=>e.if(h,()=>m(y)))}function f(h,y){e.forRange("i",0,l,g=>{t.subschema({keyword:"contains",dataProp:g,dataPropType:Al.Type.Num,compositeRule:!0},h),y()})}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)))}}};Cg.default=h9});var gE=S(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateSchemaDeps=Ir.validatePropertyDeps=Ir.error=void 0;var Dg=X(),g9=pe(),Xa=Gt();Ir.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Dg.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Dg._)`{property: ${t},
|
|
9
|
+
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,J._)`[${s}]`)}}}function XN({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,J._)`${e} !== undefined`,()=>t.assign((0,J._)`${e}[${r}]`,n))}function am(t,e,r,n=xo.Correct){let s=n===xo.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===xo.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)}}at.checkDataType=am;function cm(t,e,r,n){if(t.length===1)return am(t[0],e,r,n);let s,o=(0,Ix.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,am(i,e,r,n));return s}at.checkDataTypes=cm;var QN={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,J._)`{type: ${t}}`:(0,J._)`{type: ${e}}`};function um(t){let e=e1(t);(0,WN.reportError)(e,QN)}at.reportTypeError=um;function e1(t){let{gen:e,data:r,schema:n}=t,s=(0,Ix.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var Dx=S(Vu=>{"use strict";Object.defineProperty(Vu,"__esModule",{value:!0});Vu.assignDefaults=void 0;var Po=te(),t1=le();function r1(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)Cx(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>Cx(t,o,s.default))}Vu.assignDefaults=r1;function Cx(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,Po._)`${o}${(0,Po.getProperty)(e)}`;if(s){(0,t1.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Po._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Po._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Po._)`${a} = ${(0,Po.stringify)(r)}`)}});var Kt=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 Re=te(),lm=le(),hn=Br(),n1=le();function s1(t,e){let{gen:r,data:n,it:s}=t;r.if(pm(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Re._)`${e}`},!0),t.error()})}be.checkReportMissingProp=s1;function o1({gen:t,data:e,it:{opts:r}},n,s){return(0,Re.or)(...n.map(o=>(0,Re.and)(pm(t,e,o,r.ownProperties),(0,Re._)`${s} = ${o}`)))}be.checkMissingProp=o1;function i1(t,e){t.setParams({missingProperty:e},!0),t.error()}be.reportMissingProp=i1;function Ox(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Re._)`Object.prototype.hasOwnProperty`})}be.hasPropFunc=Ox;function dm(t,e,r){return(0,Re._)`${Ox(t)}.call(${e}, ${r})`}be.isOwnProperty=dm;function a1(t,e,r,n){let s=(0,Re._)`${e}${(0,Re.getProperty)(r)} !== undefined`;return n?(0,Re._)`${s} && ${dm(t,e,r)}`:s}be.propertyInData=a1;function pm(t,e,r,n){let s=(0,Re._)`${e}${(0,Re.getProperty)(r)} === undefined`;return n?(0,Re.or)(s,(0,Re.not)(dm(t,e,r))):s}be.noPropertyInData=pm;function Mx(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}be.allSchemaProperties=Mx;function c1(t,e){return Mx(e).filter(r=>!(0,lm.alwaysValidSchema)(t,e[r]))}be.schemaProperties=c1;function u1({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=[[hn.default.instancePath,(0,Re.strConcat)(hn.default.instancePath,o)],[hn.default.parentData,i.parentData],[hn.default.parentDataProperty,i.parentDataProperty],[hn.default.rootData,hn.default.rootData]];i.opts.dynamicRef&&d.push([hn.default.dynamicAnchors,hn.default.dynamicAnchors]);let p=(0,Re._)`${l}, ${r.object(...d)}`;return c!==Re.nil?(0,Re._)`${a}.call(${c}, ${p})`:(0,Re._)`${a}(${p})`}be.callValidateCode=u1;var l1=(0,Re._)`new RegExp`;function d1({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"?l1:(0,n1.useFunc)(t,s)}(${r}, ${n})`})}be.usePattern=d1;function p1(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:lm.Type.Num},o),e.if((0,Re.not)(o),a)})}}be.validateArray=p1;function f1(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,lm.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))}be.validateUnion=f1});var Nx=S($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.validateKeywordUsage=$r.validSchemaType=$r.funcKeywordCode=$r.macroKeywordCode=void 0;var ht=te(),ds=Br(),m1=Kt(),h1=la();function g1(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=jx(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))}$r.macroKeywordCode=g1;function y1(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;_1(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,l=jx(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&&zx(t),y(()=>t.error());else{let v=e.async?f():m();e.modifying&&zx(t),y(()=>v1(t,v))}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>h((0,ht._)`await `),_=>n.assign(d,!1).if((0,ht._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,ht._)`${_}.errors`),()=>n.throw(_))),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 _=c.opts.passContext?ds.default.this:ds.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ht._)`${v}${(0,m1.callValidateCode)(t,l,_,b)}`,e.modifying)}function y(v){var _;n.if((0,ht.not)((_=e.valid)!==null&&_!==void 0?_:d),v)}}$r.funcKeywordCode=y1;function zx(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ht._)`${n.parentData}[${n.parentDataProperty}]`))}function v1(t,e){let{gen:r}=t;r.if((0,ht._)`Array.isArray(${e})`,()=>{r.assign(ds.default.vErrors,(0,ht._)`${ds.default.vErrors} === null ? ${e} : ${ds.default.vErrors}.concat(${e})`).assign(ds.default.errors,(0,ht._)`${ds.default.vErrors}.length`),(0,h1.extendErrors)(t)},()=>t.error())}function _1({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function jx(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 b1(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")}$r.validSchemaType=b1;function w1({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)}}$r.validateKeywordUsage=w1});var Fx=S(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.extendSubschemaMode=gn.extendSubschemaData=gn.getSubschema=void 0;var xr=te(),Lx=le();function S1(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,xr._)`${t.schemaPath}${(0,xr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,xr._)`${t.schemaPath}${(0,xr.getProperty)(e)}${(0,xr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Lx.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')}gn.getSubschema=S1;function $1(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,xr._)`${e.data}${(0,xr.getProperty)(r)}`,!0);c(p),t.errorPath=(0,xr.str)`${u}${(0,Lx.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,xr._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(s!==void 0){let u=s instanceof xr.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]}}gn.extendSubschemaData=$1;function x1(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}gn.extendSubschemaMode=x1});var pa=S((A7,qx)=>{"use strict";qx.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 Zx=S((C7,Ux)=>{"use strict";var yn=Ux.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(){};Bu(e,n,s,t,"",t)};yn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};yn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};yn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};yn.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 Bu(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 yn.arrayKeywords)for(var p=0;p<d.length;p++)Bu(t,e,r,d[p],s+"/"+l+"/"+p,o,s,l,n,p)}else if(l in yn.propsKeywords){if(d&&typeof d=="object")for(var f in d)Bu(t,e,r,d[f],s+"/"+l+"/"+P1(f),o,s,l,n,f)}else(l in yn.keywords||t.allKeys&&!(l in yn.skipKeywords))&&Bu(t,e,r,d,s+"/"+l,o,s,l,n)}r(n,s,o,i,a,c,u)}}function P1(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var fa=S(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.getSchemaRefs=Pt.resolveUrl=Pt.normalizeId=Pt._getFullPath=Pt.getFullPath=Pt.inlineRef=void 0;var k1=le(),T1=pa(),E1=Zx(),I1=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function R1(t,e=!0){return typeof t=="boolean"?!0:e===!0?!fm(t):e?Vx(t)<=e:!1}Pt.inlineRef=R1;var A1=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function fm(t){for(let e in t){if(A1.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(fm)||typeof r=="object"&&fm(r))return!0}return!1}function Vx(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!I1.has(r)&&(typeof t[r]=="object"&&(0,k1.eachItem)(t[r],n=>e+=Vx(n)),e===1/0))return 1/0}return e}function Bx(t,e="",r){r!==!1&&(e=ko(e));let n=t.parse(e);return Hx(t,n)}Pt.getFullPath=Bx;function Hx(t,e){return t.serialize(e).split("#")[0]+"#"}Pt._getFullPath=Hx;var C1=/#\/?$/;function ko(t){return t?t.replace(C1,""):""}Pt.normalizeId=ko;function D1(t,e,r){return r=ko(r),t.resolve(e,r)}Pt.resolveUrl=D1;var O1=/^[a-z_][-a-z0-9._]*$/i;function M1(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=ko(t[r]||e),o={"":s},i=Bx(n,s,!1),a={},c=new Set;return E1(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=i+p,y=o[m];typeof d[r]=="string"&&(y=v.call(this,d[r])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),o[p]=y;function v(b){let P=this.opts.uriResolver.resolve;if(b=ko(y?P(y,b):b),c.has(b))throw l(b);c.add(b);let x=this.refs[b];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?u(d,x.schema,b):b!==ko(h)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=h),b}function _(b){if(typeof b=="string"){if(!O1.test(b))throw new Error(`invalid anchor "${b}"`);v.call(this,`#${b}`)}}}),a;function u(d,p,f){if(p!==void 0&&!T1(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Pt.getSchemaRefs=M1});var ga=S(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.getData=vn.KeywordCxt=vn.validateFunctionCode=void 0;var Yx=kx(),Wx=da(),hm=im(),Hu=da(),z1=Dx(),ha=Nx(),mm=Fx(),z=te(),V=Br(),j1=fa(),Hr=le(),ma=la();function N1(t){if(e0(t)&&(t0(t),Qx(t))){q1(t);return}Xx(t,()=>(0,Yx.topBoolOrEmptySchema)(t))}vn.validateFunctionCode=N1;function Xx({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,z._)`${V.default.data}, ${V.default.valCxt}`,n.$async,()=>{t.code((0,z._)`"use strict"; ${Kx(r,s)}`),F1(t,s),t.code(o)}):t.func(e,(0,z._)`${V.default.data}, ${L1(s)}`,n.$async,()=>t.code(Kx(r,s)).code(o))}function L1(t){return(0,z._)`{${V.default.instancePath}="", ${V.default.parentData}, ${V.default.parentDataProperty}, ${V.default.rootData}=${V.default.data}${t.dynamicRef?(0,z._)`, ${V.default.dynamicAnchors}={}`:z.nil}}={}`}function F1(t,e){t.if(V.default.valCxt,()=>{t.var(V.default.instancePath,(0,z._)`${V.default.valCxt}.${V.default.instancePath}`),t.var(V.default.parentData,(0,z._)`${V.default.valCxt}.${V.default.parentData}`),t.var(V.default.parentDataProperty,(0,z._)`${V.default.valCxt}.${V.default.parentDataProperty}`),t.var(V.default.rootData,(0,z._)`${V.default.valCxt}.${V.default.rootData}`),e.dynamicRef&&t.var(V.default.dynamicAnchors,(0,z._)`${V.default.valCxt}.${V.default.dynamicAnchors}`)},()=>{t.var(V.default.instancePath,(0,z._)`""`),t.var(V.default.parentData,(0,z._)`undefined`),t.var(V.default.parentDataProperty,(0,z._)`undefined`),t.var(V.default.rootData,V.default.data),e.dynamicRef&&t.var(V.default.dynamicAnchors,(0,z._)`{}`)})}function q1(t){let{schema:e,opts:r,gen:n}=t;Xx(t,()=>{r.$comment&&e.$comment&&n0(t),H1(t),n.let(V.default.vErrors,null),n.let(V.default.errors,0),r.unevaluated&&U1(t),r0(t),J1(t)})}function U1(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 Kx(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 Z1(t,e){if(e0(t)&&(t0(t),Qx(t))){V1(t,e);return}(0,Yx.boolOrEmptySchema)(t,e)}function Qx({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 e0(t){return typeof t.schema!="boolean"}function V1(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&n0(t),W1(t),K1(t);let o=n.const("_errs",V.default.errors);r0(t,o),n.var(e,(0,z._)`${o} === ${V.default.errors}`)}function t0(t){(0,Hr.checkUnknownRules)(t),B1(t)}function r0(t,e){if(t.opts.jtd)return Jx(t,[],!1,e);let r=(0,Wx.getSchemaTypes)(t.schema),n=(0,Wx.coerceAndCheckDataType)(t,r);Jx(t,r,!n,e)}function B1(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Hr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function H1(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Hr.checkStrictMode)(t,"default is ignored in the schema root")}function W1(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,j1.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function K1(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function n0({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,z._)`${V.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,z.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,z._)`${V.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function J1(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,z._)`${V.default.errors} === 0`,()=>e.return(V.default.data),()=>e.throw((0,z._)`new ${s}(${V.default.vErrors})`)):(e.assign((0,z._)`${n}.errors`,V.default.vErrors),o.unevaluated&&G1(t),e.return((0,z._)`${V.default.errors} === 0`))}function G1({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 Jx(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,Hr.schemaHasRulesButRef)(o,l))){s.block(()=>o0(t,"$ref",l.all.$ref.definition));return}c.jtd||Y1(t,e),s.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,hm.shouldUseGroup)(o,p)&&(p.type?(s.if((0,Hu.checkDataType)(p.type,i,c.strictNumbers)),Gx(t,p),e.length===1&&e[0]===p.type&&r&&(s.else(),(0,Hu.reportTypeError)(t)),s.endIf()):Gx(t,p),a||s.if((0,z._)`${V.default.errors} === ${n||0}`))}}function Gx(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,z1.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,hm.shouldUseRule)(n,o)&&o0(t,o.keyword,o.definition,e.type)})}function Y1(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(X1(t,e),t.opts.allowUnionTypes||Q1(t,e),eL(t,t.dataTypes))}function X1(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{s0(t.dataTypes,r)||gm(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),rL(t,e)}}function Q1(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&gm(t,"use allowUnionTypes to allow union type keyword")}function eL(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,hm.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>tL(e,i))&&gm(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function tL(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function s0(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function rL(t,e){let r=[];for(let n of t.dataTypes)s0(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function gm(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Hr.checkStrictMode)(t,e,t.opts.strictTypes)}var Wu=class{constructor(e,r,n){if((0,ha.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,Hr.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",i0(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ha.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,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?ma.reportExtraError:ma.reportError)(this,this.def.error,r)}$dataError(){(0,ma.reportError)(this,this.def.$dataError||ma.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ma.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:s,schemaType:o,def:i}=this;n.if((0,z.or)((0,z._)`${s} === undefined`,r)),e!==z.nil&&n.assign(e,!0),(o.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:s,it:o}=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,Hu.checkDataTypes)(c,r,o.opts.strictNumbers,Hu.DataType.Wrong)}`}return z.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,z._)`!${c}(${r})`}return z.nil}}subschema(e,r){let n=(0,mm.getSubschema)(this.it,e);(0,mm.extendSubschemaData)(n,this.it,e),(0,mm.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return Z1(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Hr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Hr.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,z.Name)),!0}};vn.KeywordCxt=Wu;function o0(t,e,r,n){let s=new Wu(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,ha.funcKeywordCode)(s,r):"macro"in r?(0,ha.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,ha.funcKeywordCode)(s,r)}var nL=/^\/(?:[^~]|~0|~1)*$/,sL=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function i0(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return V.default.rootData;if(t[0]==="/"){if(!nL.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=V.default.rootData}else{let u=sL.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,z._)`${o}${(0,z.getProperty)((0,Hr.unescapeJsonPointer)(u))}`,i=(0,z._)`${i} && ${o}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}vn.getData=i0});var Ku=S(vm=>{"use strict";Object.defineProperty(vm,"__esModule",{value:!0});var ym=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};vm.default=ym});var ya=S(wm=>{"use strict";Object.defineProperty(wm,"__esModule",{value:!0});var _m=fa(),bm=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,_m.resolveUrl)(e,r,n),this.missingSchema=(0,_m.normalizeId)((0,_m.getFullPath)(e,this.missingRef))}};wm.default=bm});var Gu=S(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.resolveSchema=Jt.getCompilingSchema=Jt.resolveRef=Jt.compileSchema=Jt.SchemaEnv=void 0;var ar=te(),oL=Ku(),ps=Br(),cr=fa(),a0=le(),iL=ga(),To=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,cr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Jt.SchemaEnv=To;function $m(t){let e=c0.call(this,t);if(e)return e;let r=(0,cr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new ar.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:oL.default,code:(0,ar._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:ps.default.data,parentData:ps.default.parentData,parentDataProperty:ps.default.parentDataProperty,dataNames:[ps.default.data],dataPathArr:[ar.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ar.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ar.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ar._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,iL.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(ps.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${ps.default.self}`,`${ps.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 ar.Name?void 0:m,items:h instanceof ar.Name?void 0:h,dynamicProps:m instanceof ar.Name,dynamicItems:h instanceof ar.Name},f.source&&(f.source.evaluated=(0,ar.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)}}Jt.compileSchema=$m;function aL(t,e,r){var n;r=(0,cr.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=lL.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 To({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=cL.call(this,o)}Jt.resolveRef=aL;function cL(t){return(0,cr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:$m.call(this,t)}function c0(t){for(let e of this._compilations)if(uL(e,t))return e}Jt.getCompilingSchema=c0;function uL(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function lL(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ju.call(this,t,e)}function Ju(t,e){let r=this.opts.uriResolver.parse(e),n=(0,cr._getFullPath)(this.opts.uriResolver,r),s=(0,cr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return Sm.call(this,r,t);let o=(0,cr.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Ju.call(this,t,i);return typeof a?.schema!="object"?void 0:Sm.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||$m.call(this,i),o===(0,cr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,cr.resolveUrl)(this.opts.uriResolver,s,u)),new To({schema:a,schemaId:c,root:t,baseId:s})}return Sm.call(this,r,i)}}Jt.resolveSchema=Ju;var dL=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Sm(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,a0.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!dL.has(a)&&u&&(e=(0,cr.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,a0.schemaHasRulesButRef)(r,this.RULES)){let a=(0,cr.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Ju.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new To({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var u0=S((N7,pL)=>{pL.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 Pm=S((L7,f0)=>{"use strict";var fL=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),d0=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 xm(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 mL=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function l0(t){return t.length=0,!0}function hL(t,e,r){if(t.length){let n=xm(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function gL(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=hL;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=l0}else{s.push(u);continue}}return s.length&&(a===l0?r.zone=s.join(""):i?n.push(s.join("")):n.push(xm(s))),r.address=n.join(""),r}function p0(t){if(yL(t,":")<2)return{host:t,isIPV6:!1};let e=gL(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 yL(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function vL(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 _L(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 bL(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!d0(r)){let n=p0(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}f0.exports={nonSimpleDomain:mL,recomposeAuthority:bL,normalizeComponentEncoding:_L,removeDotSegments:vL,isIPv4:d0,isUUID:fL,normalizeIPv6:p0,stringArrayToHexStripped:xm}});var v0=S((F7,y0)=>{"use strict";var{isUUID:wL}=Pm(),SL=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,$L=["http","https","ws","wss","urn","urn:uuid"];function xL(t){return $L.indexOf(t)!==-1}function km(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 m0(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function h0(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 PL(t){return t.secure=km(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function kL(t){if((t.port===(km(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 TL(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(SL);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=Tm(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function EL(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=Tm(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 IL(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!wL(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function RL(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var g0={scheme:"http",domainHost:!0,parse:m0,serialize:h0},AL={scheme:"https",domainHost:g0.domainHost,parse:m0,serialize:h0},Yu={scheme:"ws",domainHost:!0,parse:PL,serialize:kL},CL={scheme:"wss",domainHost:Yu.domainHost,parse:Yu.parse,serialize:Yu.serialize},DL={scheme:"urn",parse:TL,serialize:EL,skipNormalize:!0},OL={scheme:"urn:uuid",parse:IL,serialize:RL,skipNormalize:!0},Xu={http:g0,https:AL,ws:Yu,wss:CL,urn:DL,"urn:uuid":OL};Object.setPrototypeOf(Xu,null);function Tm(t){return t&&(Xu[t]||Xu[t.toLowerCase()])||void 0}y0.exports={wsIsSecure:km,SCHEMES:Xu,isValidSchemeName:xL,getSchemeHandler:Tm}});var Im=S((q7,el)=>{"use strict";var{normalizeIPv6:ML,removeDotSegments:va,recomposeAuthority:zL,normalizeComponentEncoding:Qu,isIPv4:jL,nonSimpleDomain:NL}=Pm(),{SCHEMES:LL,getSchemeHandler:_0}=v0();function FL(t,e){return typeof t=="string"?t=Pr(Wr(t,e),e):typeof t=="object"&&(t=Wr(Pr(t,e),e)),t}function qL(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=b0(Wr(t,n),Wr(e,n),n,!0);return n.skipEscape=!0,Pr(s,n)}function b0(t,e,r,n){let s={};return n||(t=Wr(Pr(t,r),r),e=Wr(Pr(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=va(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=va(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=va(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=va(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 UL(t,e,r){return typeof t=="string"?(t=unescape(t),t=Pr(Qu(Wr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Pr(Qu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Pr(Qu(Wr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Pr(Qu(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Pr(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=_0(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=zL(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=va(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 ZL=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Wr(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(ZL);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(jL(n.host)===!1){let c=ML(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=_0(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&NL(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 Em={SCHEMES:LL,normalize:FL,resolve:qL,resolveComponent:b0,equal:UL,serialize:Pr,parse:Wr};el.exports=Em;el.exports.default=Em;el.exports.fastUri=Em});var S0=S(Rm=>{"use strict";Object.defineProperty(Rm,"__esModule",{value:!0});var w0=Im();w0.code='require("ajv/dist/runtime/uri").default';Rm.default=w0});var R0=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 VL=ga();Object.defineProperty(Xe,"KeywordCxt",{enumerable:!0,get:function(){return VL.KeywordCxt}});var Eo=te();Object.defineProperty(Xe,"_",{enumerable:!0,get:function(){return Eo._}});Object.defineProperty(Xe,"str",{enumerable:!0,get:function(){return Eo.str}});Object.defineProperty(Xe,"stringify",{enumerable:!0,get:function(){return Eo.stringify}});Object.defineProperty(Xe,"nil",{enumerable:!0,get:function(){return Eo.nil}});Object.defineProperty(Xe,"Name",{enumerable:!0,get:function(){return Eo.Name}});Object.defineProperty(Xe,"CodeGen",{enumerable:!0,get:function(){return Eo.CodeGen}});var BL=Ku(),T0=ya(),HL=om(),_a=Gu(),WL=te(),ba=fa(),tl=da(),Cm=le(),$0=u0(),KL=S0(),E0=(t,e)=>new RegExp(t,e);E0.code="new RegExp";var JL=["removeAdditional","useDefaults","coerceTypes"],GL=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),YL={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."},XL={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},x0=200;function QL(t){var e,r,n,s,o,i,a,c,u,l,d,p,f,m,h,y,v,_,b,P,x,N,k,O,L;let F=t.strict,xe=(e=t.code)===null||e===void 0?void 0:e.optimize,We=xe===!0||xe===void 0?1:xe||0,Ct=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:E0,Nt=(s=t.uriResolver)!==null&&s!==void 0?s:KL.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:F)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:F)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:F)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:F)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:F)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:We,regExp:Ct}:{optimize:We,regExp:Ct},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:x0,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:x0,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(P=t.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(x=t.addUsedSchema)!==null&&x!==void 0?x:!0,validateSchema:(N=t.validateSchema)!==null&&N!==void 0?N:!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:Nt}}var wa=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,...QL(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new WL.ValueScope({scope:{},prefixes:GL,es5:r,lines:n}),this.logger=oF(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,HL.getRules)(),P0.call(this,YL,e,"NOT SUPPORTED"),P0.call(this,XL,e,"DEPRECATED","warn"),this._metaOpts=nF.call(this),e.formats&&tF.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&rF.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),eF.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=$0;n==="id"&&(s={...$0},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 T0.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,ba.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=k0.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new _a.SchemaEnv({schema:{},schemaId:n});if(r=_a.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=k0.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,ba.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(aF.call(this,n,r),!r)return(0,Cm.eachItem)(n,o=>Am.call(this,o)),this;uF.call(this,r);let s={...r,type:(0,tl.getJSONTypes)(r.type),schemaType:(0,tl.getJSONTypes)(r.schemaType)};return(0,Cm.eachItem)(n,s.type.length===0?o=>Am.call(this,o,s):o=>s.type.forEach(i=>Am.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]=I0(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,ba.normalizeId)(i||n);let u=ba.getSchemaRefs.call(this,e,n);return c=new _a.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):_a.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{_a.compileSchema.call(this,e)}finally{this.opts=r}}};wa.ValidationError=BL.default;wa.MissingRefError=T0.default;Xe.default=wa;function P0(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 k0(t){return t=(0,ba.normalizeId)(t),this.schemas[t]||this.refs[t]}function eF(){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 tF(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function rF(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 nF(){let t={...this.opts};for(let e of JL)delete t[e];return t}var sF={log(){},warn(){},error(){}};function oF(t){if(t===!1)return sF;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 iF=/^[a-z_$][a-z0-9_$:-]*$/i;function aF(t,e){let{RULES:r}=this;if((0,Cm.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!iF.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 Am(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,tl.getJSONTypes)(e.type),schemaType:(0,tl.getJSONTypes)(e.schemaType)}};e.before?cF.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 cF(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 uF(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=I0(e)),t.validateSchema=this.compile(e,!0))}var lF={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function I0(t){return{anyOf:[t,lF]}}});var A0=S(Dm=>{"use strict";Object.defineProperty(Dm,"__esModule",{value:!0});var dF={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Dm.default=dF});var M0=S(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.callRef=fs.getValidate=void 0;var pF=ya(),C0=Kt(),kt=te(),Io=Br(),D0=Gu(),rl=le(),fF={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=D0.resolveRef.call(c,u,s,r);if(l===void 0)throw new pF.default(n.opts.uriResolver,s,r);if(l instanceof D0.SchemaEnv)return p(l);return f(l);function d(){if(o===u)return nl(t,i,o,o.$async);let m=e.scopeValue("root",{ref:u});return nl(t,(0,kt._)`${m}.validate`,u,u.$async)}function p(m){let h=O0(t,m);nl(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 O0(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,kt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}fs.getValidate=O0;function nl(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?Io.default.this:kt.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,kt._)`await ${(0,C0.callValidateCode)(t,e,u)}`),f(e),i||s.assign(m,!0)},h=>{s.if((0,kt._)`!(${h} instanceof ${o.ValidationError})`,()=>s.throw(h)),p(h),i||s.assign(m,!1)}),t.ok(m)}function d(){t.result((0,C0.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,kt._)`${m}.errors`;s.assign(Io.default.vErrors,(0,kt._)`${Io.default.vErrors} === null ? ${h} : ${Io.default.vErrors}.concat(${h})`),s.assign(Io.default.errors,(0,kt._)`${Io.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(o.props=rl.mergeEvaluated.props(s,y.props,o.props));else{let v=s.var("props",(0,kt._)`${m}.evaluated.props`);o.props=rl.mergeEvaluated.props(s,v,o.props,kt.Name)}if(o.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(o.items=rl.mergeEvaluated.items(s,y.items,o.items));else{let v=s.var("items",(0,kt._)`${m}.evaluated.items`);o.items=rl.mergeEvaluated.items(s,v,o.items,kt.Name)}}}fs.callRef=nl;fs.default=fF});var z0=S(Om=>{"use strict";Object.defineProperty(Om,"__esModule",{value:!0});var mF=A0(),hF=M0(),gF=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",mF.default,hF.default];Om.default=gF});var j0=S(Mm=>{"use strict";Object.defineProperty(Mm,"__esModule",{value:!0});var sl=te(),_n=sl.operators,ol={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}},yF={message:({keyword:t,schemaCode:e})=>(0,sl.str)`must be ${ol[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,sl._)`{comparison: ${ol[t].okStr}, limit: ${e}}`},vF={keyword:Object.keys(ol),type:"number",schemaType:"number",$data:!0,error:yF,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,sl._)`${r} ${ol[e].fail} ${n} || isNaN(${r})`)}};Mm.default=vF});var N0=S(zm=>{"use strict";Object.defineProperty(zm,"__esModule",{value:!0});var Sa=te(),_F={message:({schemaCode:t})=>(0,Sa.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Sa._)`{multipleOf: ${t}}`},bF={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:_F,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Sa._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Sa._)`${i} !== parseInt(${i})`;t.fail$data((0,Sa._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};zm.default=bF});var F0=S(jm=>{"use strict";Object.defineProperty(jm,"__esModule",{value:!0});function L0(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}jm.default=L0;L0.code='require("ajv/dist/runtime/ucs2length").default'});var q0=S(Nm=>{"use strict";Object.defineProperty(Nm,"__esModule",{value:!0});var ms=te(),wF=le(),SF=F0(),$F={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,ms.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,ms._)`{limit: ${t}}`},xF={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:$F,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?ms.operators.GT:ms.operators.LT,i=s.opts.unicode===!1?(0,ms._)`${r}.length`:(0,ms._)`${(0,wF.useFunc)(t.gen,SF.default)}(${r})`;t.fail$data((0,ms._)`${i} ${o} ${n}`)}};Nm.default=xF});var U0=S(Lm=>{"use strict";Object.defineProperty(Lm,"__esModule",{value:!0});var PF=Kt(),kF=le(),Ro=te(),TF={message:({schemaCode:t})=>(0,Ro.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Ro._)`{pattern: ${t}}`},EF={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:TF,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,Ro._)`new RegExp`:(0,kF.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Ro._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Ro._)`!${l}`)}else{let c=(0,PF.usePattern)(t,s);t.fail$data((0,Ro._)`!${c}.test(${r})`)}}};Lm.default=EF});var Z0=S(Fm=>{"use strict";Object.defineProperty(Fm,"__esModule",{value:!0});var $a=te(),IF={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,$a.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,$a._)`{limit: ${t}}`},RF={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:IF,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?$a.operators.GT:$a.operators.LT;t.fail$data((0,$a._)`Object.keys(${r}).length ${s} ${n}`)}};Fm.default=RF});var V0=S(qm=>{"use strict";Object.defineProperty(qm,"__esModule",{value:!0});var xa=Kt(),Pa=te(),AF=le(),CF={message:({params:{missingProperty:t}})=>(0,Pa.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Pa._)`{missingProperty: ${t}}`},DF={keyword:"required",type:"object",schemaType:"array",$data:!0,error:CF,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 y=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,AF.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(Pa.nil,d);else for(let f of r)(0,xa.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,xa.checkMissingProp)(t,r,f)),(0,xa.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,xa.noPropertyInData)(e,s,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,xa.propertyInData)(e,s,f,a.ownProperties)),e.if((0,Pa.not)(m),()=>{t.error(),e.break()})},Pa.nil)}}};qm.default=DF});var B0=S(Um=>{"use strict";Object.defineProperty(Um,"__esModule",{value:!0});var ka=te(),OF={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ka.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ka._)`{limit: ${t}}`},MF={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:OF,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?ka.operators.GT:ka.operators.LT;t.fail$data((0,ka._)`${r}.length ${s} ${n}`)}};Um.default=MF});var il=S(Zm=>{"use strict";Object.defineProperty(Zm,"__esModule",{value:!0});var H0=pa();H0.code='require("ajv/dist/runtime/equal").default';Zm.default=H0});var W0=S(Bm=>{"use strict";Object.defineProperty(Bm,"__esModule",{value:!0});var Vm=da(),Qe=te(),zF=le(),jF=il(),NF={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}}`},LF={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:NF,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,Vm.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 y=e.name("item"),v=(0,Vm.checkDataTypes)(u,y,a.opts.strictNumbers,Vm.DataType.Wrong),_=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 ${_}[${y}] == "number"`,()=>{e.assign(h,(0,Qe._)`${_}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,Qe._)`${_}[${y}] = ${m}`)})}function f(m,h){let y=(0,zF.useFunc)(e,jF.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)})))}}};Bm.default=LF});var K0=S(Wm=>{"use strict";Object.defineProperty(Wm,"__esModule",{value:!0});var Hm=te(),FF=le(),qF=il(),UF={message:"must be equal to constant",params:({schemaCode:t})=>(0,Hm._)`{allowedValue: ${t}}`},ZF={keyword:"const",$data:!0,error:UF,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,Hm._)`!${(0,FF.useFunc)(e,qF.default)}(${r}, ${s})`):t.fail((0,Hm._)`${o} !== ${r}`)}};Wm.default=ZF});var J0=S(Km=>{"use strict";Object.defineProperty(Km,"__esModule",{value:!0});var Ta=te(),VF=le(),BF=il(),HF={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ta._)`{allowedValues: ${t}}`},WF={keyword:"enum",schemaType:"array",$data:!0,error:HF,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,VF.useFunc)(e,BF.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,Ta.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,Ta._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let h=s[m];return typeof h=="object"&&h!==null?(0,Ta._)`${u()}(${r}, ${f}[${m}])`:(0,Ta._)`${r} === ${h}`}}};Km.default=WF});var G0=S(Jm=>{"use strict";Object.defineProperty(Jm,"__esModule",{value:!0});var KF=j0(),JF=N0(),GF=q0(),YF=U0(),XF=Z0(),QF=V0(),eq=B0(),tq=W0(),rq=K0(),nq=J0(),sq=[KF.default,JF.default,GF.default,YF.default,XF.default,QF.default,eq.default,tq.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},rq.default,nq.default];Jm.default=sq});var Ym=S(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.validateAdditionalItems=void 0;var hs=te(),Gm=le(),oq={message:({params:{len:t}})=>(0,hs.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,hs._)`{limit: ${t}}`},iq={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:oq,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Gm.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Y0(t,n)}};function Y0(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,hs._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,hs._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Gm.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,hs._)`${a} <= ${e.length}`);r.if((0,hs.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:o,dataProp:l,dataPropType:Gm.Type.Num},u),i.allErrors||r.if((0,hs.not)(u),()=>r.break())})}}Ea.validateAdditionalItems=Y0;Ea.default=iq});var Xm=S(Ia=>{"use strict";Object.defineProperty(Ia,"__esModule",{value:!0});Ia.validateTuple=void 0;var X0=te(),al=le(),aq=Kt(),cq={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Q0(t,"additionalItems",e);r.items=!0,!(0,al.alwaysValidSchema)(r,e)&&t.ok((0,aq.validateArray)(t))}};function Q0(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=al.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,X0._)`${o}.length`);r.forEach((d,p)=>{(0,al.alwaysValidSchema)(a,d)||(n.if((0,X0._)`${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,al.checkStrictMode)(a,y,p.strictTuples)}}}Ia.validateTuple=Q0;Ia.default=cq});var eP=S(Qm=>{"use strict";Object.defineProperty(Qm,"__esModule",{value:!0});var uq=Xm(),lq={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,uq.validateTuple)(t,"items")};Qm.default=lq});var rP=S(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});var tP=te(),dq=le(),pq=Kt(),fq=Ym(),mq={message:({params:{len:t}})=>(0,tP.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,tP._)`{limit: ${t}}`},hq={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,fq.validateAdditionalItems)(t,s):t.ok((0,pq.validateArray)(t)))}};eh.default=hq});var nP=S(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var Gt=te(),cl=le(),gq={message:({params:{min:t,max:e}})=>e===void 0?(0,Gt.str)`must contain at least ${t} valid item(s)`:(0,Gt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Gt._)`{minContains: ${t}}`:(0,Gt._)`{minContains: ${t}, maxContains: ${e}}`},yq={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:gq,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,Gt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,cl.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,cl.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,cl.alwaysValidSchema)(o,r)){let h=(0,Gt._)`${l} >= ${i}`;a!==void 0&&(h=(0,Gt._)`${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,Gt._)`${s}.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:cl.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,Gt._)`${h}++`),a===void 0?e.if((0,Gt._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Gt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Gt._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};th.default=yq});var iP=S(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.validateSchemaDeps=kr.validatePropertyDeps=kr.error=void 0;var rh=te(),vq=le(),Ra=Kt();kr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,rh.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,rh._)`{property: ${t},
|
|
10
|
+
missingProperty: ${n},
|
|
11
|
+
depsCount: ${e},
|
|
12
|
+
deps: ${r}}`};var _q={keyword:"dependencies",type:"object",schemaType:"object",error:kr.error,code(t){let[e,r]=bq(t);sP(t,e),oP(t,r)}};function bq({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 sP(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,Ra.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,Ra.checkReportMissingProp)(t,u)}):(r.if((0,rh._)`${c} && (${(0,Ra.checkMissingProp)(t,a,o)})`),(0,Ra.reportMissingProp)(t,o),r.else())}}kr.validatePropertyDeps=sP;function oP(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,vq.alwaysValidSchema)(o,e[a])||(r.if((0,Ra.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))}kr.validateSchemaDeps=oP;kr.default=_q});var cP=S(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});var aP=te(),wq=le(),Sq={message:"property name must be valid",params:({params:t})=>(0,aP._)`{propertyName: ${t.propertyName}}`},$q={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Sq,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,wq.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,aP.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};nh.default=$q});var oh=S(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var ul=Kt(),ur=te(),xq=Br(),ll=le(),Pq={message:"must NOT have additional properties",params:({params:t})=>(0,ur._)`{additionalProperty: ${t.additionalProperty}}`},kq={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Pq,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,ll.alwaysValidSchema)(i,r))return;let u=(0,ul.allSchemaProperties)(n.properties),l=(0,ul.allSchemaProperties)(n.patternProperties);d(),t.ok((0,ur._)`${o} === ${xq.default.errors}`);function d(){e.forIn("key",s,y=>{!u.length&&!l.length?m(y):e.if(p(y),()=>m(y))})}function p(y){let v;if(u.length>8){let _=(0,ll.schemaRefOrVal)(i,n.properties,"properties");v=(0,ul.isOwnProperty)(e,_,y)}else u.length?v=(0,ur.or)(...u.map(_=>(0,ur._)`${y} === ${_}`)):v=ur.nil;return l.length&&(v=(0,ur.or)(v,...l.map(_=>(0,ur._)`${(0,ul.usePattern)(t,_)}.test(${y})`))),(0,ur.not)(v)}function f(y){e.code((0,ur._)`delete ${s}[${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,ll.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(h(y,v,!1),e.if((0,ur.not)(v),()=>{t.reset(),f(y)})):(h(y,v),a||e.if((0,ur.not)(v),()=>e.break()))}}function h(y,v,_){let b={keyword:"additionalProperties",dataProp:y,dataPropType:ll.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,v)}}};sh.default=kq});var dP=S(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var Tq=ga(),uP=Kt(),ih=le(),lP=oh(),Eq={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&&lP.default.code(new Tq.KeywordCxt(o,lP.default,"additionalProperties"));let i=(0,uP.allSchemaProperties)(r);for(let d of i)o.definedProperties.add(d);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=ih.mergeEvaluated.props(e,(0,ih.toHash)(i),o.props));let a=i.filter(d=>!(0,ih.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,uP.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)}}};ah.default=Eq});var hP=S(ch=>{"use strict";Object.defineProperty(ch,"__esModule",{value:!0});var pP=Kt(),dl=te(),fP=le(),mP=le(),Iq={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,pP.allSchemaProperties)(r),c=a.filter(h=>(0,fP.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 dl.Name)&&(o.props=(0,mP.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 y in u)new RegExp(h).test(y)&&(0,fP.checkStrictMode)(o,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,dl._)`${(0,pP.usePattern)(t,h)}.test(${y})`,()=>{let v=c.includes(h);v||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:mP.Type.Str},l),o.opts.unevaluated&&d!==!0?e.assign((0,dl._)`${d}[${y}]`,!0):!v&&!o.allErrors&&e.if((0,dl.not)(l),()=>e.break())})})}}};ch.default=Iq});var gP=S(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var Rq=le(),Aq={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Rq.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"}};uh.default=Aq});var yP=S(lh=>{"use strict";Object.defineProperty(lh,"__esModule",{value:!0});var Cq=Kt(),Dq={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Cq.validateUnion,error:{message:"must match a schema in anyOf"}};lh.default=Dq});var vP=S(dh=>{"use strict";Object.defineProperty(dh,"__esModule",{value:!0});var pl=te(),Oq=le(),Mq={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,pl._)`{passingSchemas: ${t.passing}}`},zq={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Mq,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,Oq.alwaysValidSchema)(s,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,pl._)`${c} && ${i}`).assign(i,!1).assign(a,(0,pl._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,pl.Name)})})}}};dh.default=zq});var _P=S(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var jq=le(),Nq={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,jq.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};ph.default=Nq});var SP=S(fh=>{"use strict";Object.defineProperty(fh,"__esModule",{value:!0});var fl=te(),wP=le(),Lq={message:({params:t})=>(0,fl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,fl._)`{failingKeyword: ${t.ifClause}}`},Fq={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Lq,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,wP.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=bP(n,"then"),o=bP(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,fl.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,fl._)`${l}`):t.setParams({ifClause:l})}}}};function bP(t,e){let r=t.schema[e];return r!==void 0&&!(0,wP.alwaysValidSchema)(t,r)}fh.default=Fq});var $P=S(mh=>{"use strict";Object.defineProperty(mh,"__esModule",{value:!0});var qq=le(),Uq={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,qq.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};mh.default=Uq});var xP=S(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var Zq=Ym(),Vq=eP(),Bq=Xm(),Hq=rP(),Wq=nP(),Kq=iP(),Jq=cP(),Gq=oh(),Yq=dP(),Xq=hP(),Qq=gP(),eU=yP(),tU=vP(),rU=_P(),nU=SP(),sU=$P();function oU(t=!1){let e=[Qq.default,eU.default,tU.default,rU.default,nU.default,sU.default,Jq.default,Gq.default,Kq.default,Yq.default,Xq.default];return t?e.push(Vq.default,Hq.default):e.push(Zq.default,Bq.default),e.push(Wq.default),e}hh.default=oU});var PP=S(gh=>{"use strict";Object.defineProperty(gh,"__esModule",{value:!0});var qe=te(),iU={message:({schemaCode:t})=>(0,qe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,qe._)`{format: ${t}}`},aU={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:iU,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,qe._)`${m}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,qe._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,qe._)`${h}.type || "string"`).assign(v,(0,qe._)`${h}.validate`),()=>r.assign(y,(0,qe._)`"string"`).assign(v,h)),t.fail$data((0,qe.or)(_(),b()));function _(){return c.strictSchema===!1?qe.nil:(0,qe._)`${i} && !${v}`}function b(){let P=l.$async?(0,qe._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,qe._)`${v}(${n})`,x=(0,qe._)`(typeof ${v} == "function" ? ${P} : ${v}.test(${n}))`;return(0,qe._)`${v} && ${v} !== true && ${y} === ${e} && !${x}`}}function f(){let m=d.formats[o];if(!m){_();return}if(m===!0)return;let[h,y,v]=b(m);h===e&&t.pass(P());function _(){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 b(x){let N=x instanceof RegExp?(0,qe.regexpCode)(x):c.code.formats?(0,qe._)`${c.code.formats}${(0,qe.getProperty)(o)}`:void 0,k=r.scopeValue("formats",{key:o,ref:x,code:N});return typeof x=="object"&&!(x instanceof RegExp)?[x.type||"string",x.validate,(0,qe._)`${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,qe._)`await ${v}(${n})`}return typeof y=="function"?(0,qe._)`${v}(${n})`:(0,qe._)`${v}.test(${n})`}}}};gh.default=aU});var kP=S(yh=>{"use strict";Object.defineProperty(yh,"__esModule",{value:!0});var cU=PP(),uU=[cU.default];yh.default=uU});var TP=S(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.contentVocabulary=Ao.metadataVocabulary=void 0;Ao.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ao.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var IP=S(vh=>{"use strict";Object.defineProperty(vh,"__esModule",{value:!0});var lU=z0(),dU=G0(),pU=xP(),fU=kP(),EP=TP(),mU=[lU.default,dU.default,(0,pU.default)(),fU.default,EP.metadataVocabulary,EP.contentVocabulary];vh.default=mU});var AP=S(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});ml.DiscrError=void 0;var RP;(function(t){t.Tag="tag",t.Mapping="mapping"})(RP||(ml.DiscrError=RP={}))});var DP=S(bh=>{"use strict";Object.defineProperty(bh,"__esModule",{value:!0});var Co=te(),_h=AP(),CP=Gu(),hU=ya(),gU=le(),yU={message:({params:{discrError:t,tagName:e}})=>t===_h.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Co._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},vU={keyword:"discriminator",type:"object",schemaType:"object",error:yU,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,Co._)`${r}${(0,Co.getProperty)(a)}`);e.if((0,Co._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:_h.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,Co._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:_h.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,Co.Name),m}function p(){var f;let m={},h=v(s),y=!0;for(let P=0;P<i.length;P++){let x=i[P];if(x?.$ref&&!(0,gU.schemaHasRulesButRef)(x,o.self.RULES)){let k=x.$ref;if(x=CP.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,k),x instanceof CP.SchemaEnv&&(x=x.schema),x===void 0)throw new hU.default(o.opts.uriResolver,o.baseId,k)}let N=(f=x?.properties)===null||f===void 0?void 0:f[a];if(typeof N!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||v(x)),_(N,P)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function v({required:P}){return Array.isArray(P)&&P.includes(a)}function _(P,x){if(P.const)b(P.const,x);else if(P.enum)for(let N of P.enum)b(N,x);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(P,x){if(typeof P!="string"||P in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[P]=x}}}};bh.default=vU});var OP=S((Iee,_U)=>{_U.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 zP=S((Ae,wh)=>{"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 bU=R0(),wU=IP(),SU=DP(),MP=OP(),$U=["/properties"],hl="http://json-schema.org/draft-07/schema",Do=class extends bU.default{_addVocabularies(){super._addVocabularies(),wU.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(SU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(MP,$U):MP;this.addMetaSchema(e,hl,!1),this.refs["http://json-schema.org/schema"]=hl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(hl)?hl:void 0)}};Ae.Ajv=Do;wh.exports=Ae=Do;wh.exports.Ajv=Do;Object.defineProperty(Ae,"__esModule",{value:!0});Ae.default=Do;var xU=ga();Object.defineProperty(Ae,"KeywordCxt",{enumerable:!0,get:function(){return xU.KeywordCxt}});var Oo=te();Object.defineProperty(Ae,"_",{enumerable:!0,get:function(){return Oo._}});Object.defineProperty(Ae,"str",{enumerable:!0,get:function(){return Oo.str}});Object.defineProperty(Ae,"stringify",{enumerable:!0,get:function(){return Oo.stringify}});Object.defineProperty(Ae,"nil",{enumerable:!0,get:function(){return Oo.nil}});Object.defineProperty(Ae,"Name",{enumerable:!0,get:function(){return Oo.Name}});Object.defineProperty(Ae,"CodeGen",{enumerable:!0,get:function(){return Oo.CodeGen}});var PU=Ku();Object.defineProperty(Ae,"ValidationError",{enumerable:!0,get:function(){return PU.default}});var kU=ya();Object.defineProperty(Ae,"MissingRefError",{enumerable:!0,get:function(){return kU.default}})});var VP=S(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.formatNames=Er.fastFormats=Er.fullFormats=void 0;function Tr(t,e){return{validate:t,compare:e}}Er.fullFormats={date:Tr(FP,Ph),time:Tr($h(!0),kh),"date-time":Tr(jP(!0),UP),"iso-time":Tr($h(),qP),"iso-date-time":Tr(jP(),ZP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:CU,"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:LU,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:DU,int32:{type:"number",validate:zU},int64:{type:"number",validate:jU},float:{type:"number",validate:LP},double:{type:"number",validate:LP},password:!0,binary:!0};Er.fastFormats={...Er.fullFormats,date:Tr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Ph),time:Tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,kh),"date-time":Tr(/^\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,UP),"iso-time":Tr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,qP),"iso-date-time":Tr(/^\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,ZP),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};Er.formatNames=Object.keys(Er.fullFormats);function TU(t){return t%4===0&&(t%100!==0||t%400===0)}var EU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,IU=[0,31,28,31,30,31,30,31,31,30,31,30,31];function FP(t){let e=EU.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&&TU(r)?29:IU[n])}function Ph(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Sh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function $h(t){return function(r){let n=Sh.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 kh(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 qP(t,e){if(!(t&&e))return;let r=Sh.exec(t),n=Sh.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 xh=/t|\s/i;function jP(t){let e=$h(t);return function(n){let s=n.split(xh);return s.length===2&&FP(s[0])&&e(s[1])}}function UP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function ZP(t,e){if(!(t&&e))return;let[r,n]=t.split(xh),[s,o]=e.split(xh),i=Ph(r,s);if(i!==void 0)return i||kh(n,o)}var RU=/\/|:/,AU=/^(?:[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 CU(t){return RU.test(t)&&AU.test(t)}var NP=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function DU(t){return NP.lastIndex=0,NP.test(t)}var OU=-(2**31),MU=2**31-1;function zU(t){return Number.isInteger(t)&&t<=MU&&t>=OU}function jU(t){return Number.isInteger(t)}function LP(){return!0}var NU=/[^\\]\\Z/;function LU(t){if(NU.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Da=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 Aa=class{};he._CodeOrName=Aa;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var gs=class extends Aa{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=gs;var Yt=class extends Aa{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 gs&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=Yt;he.nil=new Yt("");function BP(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Eh(r,e[n]),r.push(t[++n]);return new Yt(r)}he._=BP;var Th=new Yt("+");function HP(t,...e){let r=[Ca(t[0])],n=0;for(;n<e.length;)r.push(Th),Eh(r,e[n]),r.push(Th,Ca(t[++n]));return FU(r),new Yt(r)}he.str=HP;function Eh(t,e){e instanceof Yt?t.push(...e._items):e instanceof gs?t.push(e):t.push(ZU(e))}he.addCodeArg=Eh;function FU(t){let e=1;for(;e<t.length-1;){if(t[e]===Th){let r=qU(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function qU(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof gs||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 gs))return`"${t}${e.slice(1)}`}function UU(t,e){return e.emptyStr()?t:t.emptyStr()?e:HP`${t}${e}`}he.strConcat=UU;function ZU(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ca(Array.isArray(t)?t.join(","):t)}function VU(t){return new Yt(Ca(t))}he.stringify=VU;function Ca(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Ca;function BU(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new Yt(`.${t}`):BP`[${t}]`}he.getProperty=BU;function HU(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new Yt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=HU;function WU(t){return new Yt(t.toString())}he.regexpCode=WU});var Ah=S(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.ValueScope=Et.ValueScopeName=Et.Scope=Et.varKinds=Et.UsedValueState=void 0;var Tt=Da(),Ih=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},gl;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(gl||(Et.UsedValueState=gl={}));Et.varKinds={const:new Tt.Name("const"),let:new Tt.Name("let"),var:new Tt.Name("var")};var yl=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Tt.Name?e:this.name(e)}name(e){return new Tt.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=yl;var vl=class extends Tt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Tt._)`.${new Tt.Name(r)}[${n}]`}};Et.ValueScopeName=vl;var KU=(0,Tt._)`\n`,Rh=class extends yl{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?KU:Tt.nil}}get(){return this._scope}name(e){return new vl(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,Tt._)`${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=Tt.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,gl.Started);let l=r(u);if(l){let d=this.opts.es5?Et.varKinds.var:Et.varKinds.const;o=(0,Tt._)`${o}${d} ${u} = ${l};${this.opts._n}`}else if(l=s?.(u))o=(0,Tt._)`${o}${l}${this.opts._n}`;else throw new Ih(u);c.set(u,gl.Completed)})}return o}};Et.ValueScope=Rh});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=Da(),lr=Ah(),bn=Da();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return bn._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return bn.str}});Object.defineProperty(ee,"strConcat",{enumerable:!0,get:function(){return bn.strConcat}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return bn.nil}});Object.defineProperty(ee,"getProperty",{enumerable:!0,get:function(){return bn.getProperty}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return bn.stringify}});Object.defineProperty(ee,"regexpCode",{enumerable:!0,get:function(){return bn.regexpCode}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return bn.Name}});var Sl=Ah();Object.defineProperty(ee,"Scope",{enumerable:!0,get:function(){return Sl.Scope}});Object.defineProperty(ee,"ValueScope",{enumerable:!0,get:function(){return Sl.ValueScope}});Object.defineProperty(ee,"ValueScopeName",{enumerable:!0,get:function(){return Sl.ValueScopeName}});Object.defineProperty(ee,"varKinds",{enumerable:!0,get:function(){return Sl.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 Kr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Ch=class extends Kr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?lr.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=zo(this.rhs,e,r)),this}get names(){return this.rhs instanceof ue._CodeOrName?this.rhs.names:{}}},_l=class extends Kr{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=zo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ue.Name?{}:{...this.lhs.names};return wl(e,this.rhs)}},Dh=class extends _l{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Oh=class extends Kr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Mh=class extends Kr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},zh=class extends Kr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},jh=class extends Kr{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=zo(this.code,e,r),this}get names(){return this.code instanceof ue._CodeOrName?this.code.names:{}}},Oa=class extends Kr{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)||(JU(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>_s(e,r.names),{})}},Jr=class extends Oa{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Nh=class extends Oa{},Mo=class extends Jr{};Mo.kind="else";var ys=class t extends Jr{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 Mo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(WP(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=zo(this.condition,e,r),this}get names(){let e=super.names;return wl(e,this.condition),this.else&&_s(e,this.else.names),e}};ys.kind="if";var vs=class extends Jr{};vs.kind="for";var Lh=class extends vs{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=zo(this.iteration,e,r),this}get names(){return _s(super.names,this.iteration.names)}},Fh=class extends vs{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?lr.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=wl(super.names,this.from);return wl(e,this.to)}},bl=class extends vs{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=zo(this.iterable,e,r),this}get names(){return _s(super.names,this.iterable.names)}},Ma=class extends Jr{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)}};Ma.kind="func";var za=class extends Oa{render(e){return"return "+super.render(e)}};za.kind="return";var qh=class extends Jr{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&&_s(e,this.catch.names),this.finally&&_s(e,this.finally.names),e}},ja=class extends Jr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ja.kind="catch";var Na=class extends Jr{render(e){return"finally"+super.render(e)}};Na.kind="finally";var Uh=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
13
|
+
`:""},this._extScope=e,this._scope=new lr.Scope({parent:e}),this._nodes=[new Nh]}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 Ch(e,o,n)),o}const(e,r,n){return this._def(lr.varKinds.const,e,r,n)}let(e,r,n){return this._def(lr.varKinds.let,e,r,n)}var(e,r,n){return this._def(lr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new _l(e,r,n))}add(e,r){return this._leafNode(new Dh(e,ee.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ue.nil&&this._leafNode(new jh(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 ys(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 ys(e))}else(){return this._elseNode(new Mo)}endIf(){return this._endBlockNode(ys,Mo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Lh(e),r)}forRange(e,r,n,s,o=this.opts.es5?lr.varKinds.var:lr.varKinds.let){let i=this._scope.toName(e);return this._for(new Fh(o,i,r,n),()=>s(i))}forOf(e,r,n,s=lr.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 bl("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?lr.varKinds.var:lr.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 bl("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(vs)}label(e){return this._leafNode(new Oh(e))}break(e){return this._leafNode(new Mh(e))}return(e){let r=new za;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(za)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new qh;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new ja(o),r(o)}return n&&(this._currNode=s.finally=new Na,this.code(n)),this._endBlockNode(ja,Na)}throw(e){return this._leafNode(new zh(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 Ma(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Ma)}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 ys))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=Uh;function _s(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function wl(t,e){return e instanceof ue._CodeOrName?_s(t,e.names):t}function zo(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 JU(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function WP(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ue._)`!${Zh(t)}`}ee.not=WP;var GU=KP(ee.operators.AND);function YU(...t){return t.reduce(GU)}ee.and=YU;var XU=KP(ee.operators.OR);function QU(...t){return t.reduce(XU)}ee.or=QU;function KP(t){return(e,r)=>e===ue.nil?r:r===ue.nil?e:(0,ue._)`${Zh(e)} ${t} ${Zh(r)}`}function Zh(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 $e=X(),eZ=Da();function tZ(t){let e={};for(let r of t)e[r]=!0;return e}ne.toHash=tZ;function rZ(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(YP(t,e),!XP(e,t.self.RULES.all))}ne.alwaysValidSchema=rZ;function YP(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]||tk(t,`unknown keyword: "${o}"`)}ne.checkUnknownRules=YP;function XP(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ne.schemaHasRules=XP;function nZ(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=nZ;function sZ({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){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=sZ;function oZ(t){return QP(decodeURIComponent(t))}ne.unescapeFragment=oZ;function iZ(t){return encodeURIComponent(Bh(t))}ne.escapeFragment=iZ;function Bh(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ne.escapeJsonPointer=Bh;function QP(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ne.unescapeJsonPointer=QP;function aZ(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ne.eachItem=aZ;function JP({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof $e.Name?(o instanceof $e.Name?t(s,o,i):e(s,o,i),i):o instanceof $e.Name?(e(s,i,o),o):r(o,i);return a===$e.Name&&!(c instanceof $e.Name)?n(s,c):c}}ne.mergeEvaluated={props:JP({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} || {}`),Hh(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:ek}),items:JP({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 ek(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,$e._)`{}`);return e!==void 0&&Hh(t,r,e),r}ne.evaluatedPropsToName=ek;function Hh(t,e,r){Object.keys(r).forEach(n=>t.assign((0,$e._)`${e}${(0,$e.getProperty)(n)}`,!0))}ne.setEvaluated=Hh;var GP={};function cZ(t,e){return t.scopeValue("func",{ref:e,code:GP[e.code]||(GP[e.code]=new eZ._Code(e.code))})}ne.useFunc=cZ;var Vh;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Vh||(ne.Type=Vh={}));function uZ(t,e,r){if(t instanceof $e.Name){let n=e===Vh.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():"/"+Bh(t)}ne.getErrorPath=uZ;function tk(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=tk});var Gr=S(Wh=>{"use strict";Object.defineProperty(Wh,"__esModule",{value:!0});var ct=X(),lZ={data:new ct.Name("data"),valCxt:new ct.Name("valCxt"),instancePath:new ct.Name("instancePath"),parentData:new ct.Name("parentData"),parentDataProperty:new ct.Name("parentDataProperty"),rootData:new ct.Name("rootData"),dynamicAnchors:new ct.Name("dynamicAnchors"),vErrors:new ct.Name("vErrors"),errors:new ct.Name("errors"),this:new ct.Name("this"),self:new ct.Name("self"),scope:new ct.Name("scope"),json:new ct.Name("json"),jsonPos:new ct.Name("jsonPos"),jsonLen:new ct.Name("jsonLen"),jsonPart:new ct.Name("jsonPart")};Wh.default=lZ});var La=S(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.extendErrors=ut.resetErrorsCount=ut.reportExtraError=ut.reportError=ut.keyword$DataError=ut.keywordError=void 0;var fe=X(),$l=pe(),gt=Gr();ut.keywordError={message:({keyword:t})=>(0,fe.str)`must pass "${t}" keyword validation`};ut.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 dZ(t,e=ut.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=sk(t,e,r);n??(i||a)?rk(o,c):nk(s,(0,fe._)`[${c}]`)}ut.reportError=dZ;function pZ(t,e=ut.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=sk(t,e,r);rk(s,a),o||i||nk(n,gt.default.vErrors)}ut.reportExtraError=pZ;function fZ(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)))}ut.resetErrorsCount=fZ;function mZ({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))})}ut.extendErrors=mZ;function rk(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 nk(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 bs={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 sk(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,fe._)`{}`:hZ(t,e,r)}function hZ(t,e,r={}){let{gen:n,it:s}=t,o=[gZ(s,r),yZ(t,r)];return vZ(t,e,o),n.object(...o)}function gZ({errorPath:t},{instancePath:e}){let r=e?(0,fe.str)`${t}${(0,$l.getErrorPath)(e,$l.Type.Str)}`:t;return[gt.default.instancePath,(0,fe.strConcat)(gt.default.instancePath,r)]}function yZ({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,$l.getErrorPath)(r,$l.Type.Str)}`),[bs.schemaPath,s]}function vZ(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([bs.keyword,s],[bs.params,typeof e=="function"?e(t):e||(0,fe._)`{}`]),c.messages&&n.push([bs.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([bs.schema,i],[bs.parentSchema,(0,fe._)`${l}${d}`],[gt.default.data,o]),u&&n.push([bs.propertyName,u])}});var ik=S(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.boolOrEmptySchema=jo.topBoolOrEmptySchema=void 0;var _Z=La(),bZ=X(),wZ=Gr(),SZ={message:"boolean schema is false"};function $Z(t){let{gen:e,schema:r,validateName:n}=t;r===!1?ok(t,!1):typeof r=="object"&&r.$async===!0?e.return(wZ.default.data):(e.assign((0,bZ._)`${n}.errors`,null),e.return(!0))}jo.topBoolOrEmptySchema=$Z;function xZ(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),ok(t)):r.var(e,!0)}jo.boolOrEmptySchema=xZ;function ok(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,_Z.reportError)(s,SZ,void 0,e)}});var Kh=S(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.getRules=No.isJSONType=void 0;var PZ=["string","number","integer","boolean","null","object","array"],kZ=new Set(PZ);function TZ(t){return typeof t=="string"&&kZ.has(t)}No.isJSONType=TZ;function EZ(){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:{}}}No.getRules=EZ});var Jh=S(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.shouldUseRule=wn.shouldUseGroup=wn.schemaHasRulesForType=void 0;function IZ({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&ak(t,n)}wn.schemaHasRulesForType=IZ;function ak(t,e){return e.rules.some(r=>ck(t,r))}wn.shouldUseGroup=ak;function ck(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))}wn.shouldUseRule=ck});var Fa=S(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.reportTypeError=lt.checkDataTypes=lt.checkDataType=lt.coerceAndCheckDataType=lt.getJSONTypes=lt.getSchemaTypes=lt.DataType=void 0;var RZ=Kh(),AZ=Jh(),CZ=La(),G=X(),uk=pe(),Lo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Lo||(lt.DataType=Lo={}));function DZ(t){let e=lk(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}lt.getSchemaTypes=DZ;function lk(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(RZ.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}lt.getJSONTypes=lk;function OZ(t,e){let{gen:r,data:n,opts:s}=t,o=MZ(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,AZ.schemaHasRulesForType)(t,e[0]));if(i){let a=Yh(e,n,s.strictNumbers,Lo.Wrong);r.if(a,()=>{o.length?zZ(t,e,o):Xh(t)})}return i}lt.coerceAndCheckDataType=OZ;var dk=new Set(["string","number","integer","boolean","null"]);function MZ(t,e){return e?t.filter(r=>dk.has(r)||e==="array"&&r==="array"):[]}function zZ(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,G._)`typeof ${s}`),a=n.let("coerced",(0,G._)`undefined`);o.coerceTypes==="array"&&n.if((0,G._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,G._)`${s}[0]`).assign(i,(0,G._)`typeof ${s}`).if(Yh(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,G._)`${a} !== undefined`);for(let u of r)(dk.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),Xh(t),n.endIf(),n.if((0,G._)`${a} !== undefined`,()=>{n.assign(s,a),jZ(t,a)});function c(u){switch(u){case"string":n.elseIf((0,G._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,G._)`"" + ${s}`).elseIf((0,G._)`${s} === null`).assign(a,(0,G._)`""`);return;case"number":n.elseIf((0,G._)`${i} == "boolean" || ${s} === null
|
|
14
|
+
|| (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,G._)`+${s}`);return;case"integer":n.elseIf((0,G._)`${i} === "boolean" || ${s} === null
|
|
15
|
+
|| (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,G._)`+${s}`);return;case"boolean":n.elseIf((0,G._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,G._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,G._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,G._)`${i} === "string" || ${i} === "number"
|
|
16
|
+
|| ${i} === "boolean" || ${s} === null`).assign(a,(0,G._)`[${s}]`)}}}function jZ({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,G._)`${e} !== undefined`,()=>t.assign((0,G._)`${e}[${r}]`,n))}function Gh(t,e,r,n=Lo.Correct){let s=n===Lo.Correct?G.operators.EQ:G.operators.NEQ,o;switch(t){case"null":return(0,G._)`${e} ${s} null`;case"array":o=(0,G._)`Array.isArray(${e})`;break;case"object":o=(0,G._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,G._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,G._)`typeof ${e} ${s} ${t}`}return n===Lo.Correct?o:(0,G.not)(o);function i(a=G.nil){return(0,G.and)((0,G._)`typeof ${e} == "number"`,a,r?(0,G._)`isFinite(${e})`:G.nil)}}lt.checkDataType=Gh;function Yh(t,e,r,n){if(t.length===1)return Gh(t[0],e,r,n);let s,o=(0,uk.toHash)(t);if(o.array&&o.object){let i=(0,G._)`typeof ${e} != "object"`;s=o.null?i:(0,G._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=G.nil;o.number&&delete o.integer;for(let i in o)s=(0,G.and)(s,Gh(i,e,r,n));return s}lt.checkDataTypes=Yh;var NZ={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,G._)`{type: ${t}}`:(0,G._)`{type: ${e}}`};function Xh(t){let e=LZ(t);(0,CZ.reportError)(e,NZ)}lt.reportTypeError=Xh;function LZ(t){let{gen:e,data:r,schema:n}=t,s=(0,uk.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var fk=S(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});xl.assignDefaults=void 0;var Fo=X(),FZ=pe();function qZ(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)pk(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>pk(t,o,s.default))}xl.assignDefaults=qZ;function pk(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,Fo._)`${o}${(0,Fo.getProperty)(e)}`;if(s){(0,FZ.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Fo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Fo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Fo._)`${a} = ${(0,Fo.stringify)(r)}`)}});var Xt=S(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.validateUnion=we.validateArray=we.usePattern=we.callValidateCode=we.schemaProperties=we.allSchemaProperties=we.noPropertyInData=we.propertyInData=we.isOwnProperty=we.hasPropFunc=we.reportMissingProp=we.checkMissingProp=we.checkReportMissingProp=void 0;var Ce=X(),Qh=pe(),Sn=Gr(),UZ=pe();function ZZ(t,e){let{gen:r,data:n,it:s}=t;r.if(tg(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ce._)`${e}`},!0),t.error()})}we.checkReportMissingProp=ZZ;function VZ({gen:t,data:e,it:{opts:r}},n,s){return(0,Ce.or)(...n.map(o=>(0,Ce.and)(tg(t,e,o,r.ownProperties),(0,Ce._)`${s} = ${o}`)))}we.checkMissingProp=VZ;function BZ(t,e){t.setParams({missingProperty:e},!0),t.error()}we.reportMissingProp=BZ;function mk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ce._)`Object.prototype.hasOwnProperty`})}we.hasPropFunc=mk;function eg(t,e,r){return(0,Ce._)`${mk(t)}.call(${e}, ${r})`}we.isOwnProperty=eg;function HZ(t,e,r,n){let s=(0,Ce._)`${e}${(0,Ce.getProperty)(r)} !== undefined`;return n?(0,Ce._)`${s} && ${eg(t,e,r)}`:s}we.propertyInData=HZ;function tg(t,e,r,n){let s=(0,Ce._)`${e}${(0,Ce.getProperty)(r)} === undefined`;return n?(0,Ce.or)(s,(0,Ce.not)(eg(t,e,r))):s}we.noPropertyInData=tg;function hk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}we.allSchemaProperties=hk;function WZ(t,e){return hk(e).filter(r=>!(0,Qh.alwaysValidSchema)(t,e[r]))}we.schemaProperties=WZ;function KZ({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=[[Sn.default.instancePath,(0,Ce.strConcat)(Sn.default.instancePath,o)],[Sn.default.parentData,i.parentData],[Sn.default.parentDataProperty,i.parentDataProperty],[Sn.default.rootData,Sn.default.rootData]];i.opts.dynamicRef&&d.push([Sn.default.dynamicAnchors,Sn.default.dynamicAnchors]);let p=(0,Ce._)`${l}, ${r.object(...d)}`;return c!==Ce.nil?(0,Ce._)`${a}.call(${c}, ${p})`:(0,Ce._)`${a}(${p})`}we.callValidateCode=KZ;var JZ=(0,Ce._)`new RegExp`;function GZ({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"?JZ:(0,UZ.useFunc)(t,s)}(${r}, ${n})`})}we.usePattern=GZ;function YZ(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:Qh.Type.Num},o),e.if((0,Ce.not)(o),a)})}}we.validateArray=YZ;function XZ(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,Qh.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))}we.validateUnion=XZ});var vk=S(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateKeywordUsage=Ir.validSchemaType=Ir.funcKeywordCode=Ir.macroKeywordCode=void 0;var yt=X(),ws=Gr(),QZ=Xt(),eV=La();function tV(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=yk(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))}Ir.macroKeywordCode=tV;function rV(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;sV(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,l=yk(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&&gk(t),y(()=>t.error());else{let v=e.async?f():m();e.modifying&&gk(t),y(()=>nV(t,v))}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>h((0,yt._)`await `),_=>n.assign(d,!1).if((0,yt._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,yt._)`${_}.errors`),()=>n.throw(_))),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 _=c.opts.passContext?ws.default.this:ws.default.self,b=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,yt._)`${v}${(0,QZ.callValidateCode)(t,l,_,b)}`,e.modifying)}function y(v){var _;n.if((0,yt.not)((_=e.valid)!==null&&_!==void 0?_:d),v)}}Ir.funcKeywordCode=rV;function gk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,yt._)`${n.parentData}[${n.parentDataProperty}]`))}function nV(t,e){let{gen:r}=t;r.if((0,yt._)`Array.isArray(${e})`,()=>{r.assign(ws.default.vErrors,(0,yt._)`${ws.default.vErrors} === null ? ${e} : ${ws.default.vErrors}.concat(${e})`).assign(ws.default.errors,(0,yt._)`${ws.default.vErrors}.length`),(0,eV.extendErrors)(t)},()=>t.error())}function sV({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function yk(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 oV(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")}Ir.validSchemaType=oV;function iV({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)}}Ir.validateKeywordUsage=iV});var bk=S($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.extendSubschemaMode=$n.extendSubschemaData=$n.getSubschema=void 0;var Rr=X(),_k=pe();function aV(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,Rr._)`${t.schemaPath}${(0,Rr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Rr._)`${t.schemaPath}${(0,Rr.getProperty)(e)}${(0,Rr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,_k.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')}$n.getSubschema=aV;function cV(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,Rr._)`${e.data}${(0,Rr.getProperty)(r)}`,!0);c(p),t.errorPath=(0,Rr.str)`${u}${(0,_k.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Rr._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Rr.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]}}$n.extendSubschemaData=cV;function uV(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}$n.extendSubschemaMode=uV});var Sk=S((Bee,wk)=>{"use strict";var xn=wk.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(){};Pl(e,n,s,t,"",t)};xn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};xn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};xn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};xn.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 Pl(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 xn.arrayKeywords)for(var p=0;p<d.length;p++)Pl(t,e,r,d[p],s+"/"+l+"/"+p,o,s,l,n,p)}else if(l in xn.propsKeywords){if(d&&typeof d=="object")for(var f in d)Pl(t,e,r,d[f],s+"/"+l+"/"+lV(f),o,s,l,n,f)}else(l in xn.keywords||t.allKeys&&!(l in xn.skipKeywords))&&Pl(t,e,r,d,s+"/"+l,o,s,l,n)}r(n,s,o,i,a,c,u)}}function lV(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var qa=S(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.getSchemaRefs=It.resolveUrl=It.normalizeId=It._getFullPath=It.getFullPath=It.inlineRef=void 0;var dV=pe(),pV=pa(),fV=Sk(),mV=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function hV(t,e=!0){return typeof t=="boolean"?!0:e===!0?!rg(t):e?$k(t)<=e:!1}It.inlineRef=hV;var gV=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function rg(t){for(let e in t){if(gV.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(rg)||typeof r=="object"&&rg(r))return!0}return!1}function $k(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!mV.has(r)&&(typeof t[r]=="object"&&(0,dV.eachItem)(t[r],n=>e+=$k(n)),e===1/0))return 1/0}return e}function xk(t,e="",r){r!==!1&&(e=qo(e));let n=t.parse(e);return Pk(t,n)}It.getFullPath=xk;function Pk(t,e){return t.serialize(e).split("#")[0]+"#"}It._getFullPath=Pk;var yV=/#\/?$/;function qo(t){return t?t.replace(yV,""):""}It.normalizeId=qo;function vV(t,e,r){return r=qo(r),t.resolve(e,r)}It.resolveUrl=vV;var _V=/^[a-z_][-a-z0-9._]*$/i;function bV(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=qo(t[r]||e),o={"":s},i=xk(n,s,!1),a={},c=new Set;return fV(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=i+p,y=o[m];typeof d[r]=="string"&&(y=v.call(this,d[r])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),o[p]=y;function v(b){let P=this.opts.uriResolver.resolve;if(b=qo(y?P(y,b):b),c.has(b))throw l(b);c.add(b);let x=this.refs[b];return typeof x=="string"&&(x=this.refs[x]),typeof x=="object"?u(d,x.schema,b):b!==qo(h)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=h),b}function _(b){if(typeof b=="string"){if(!_V.test(b))throw new Error(`invalid anchor "${b}"`);v.call(this,`#${b}`)}}}),a;function u(d,p,f){if(p!==void 0&&!pV(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}It.getSchemaRefs=bV});var Va=S(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.getData=Pn.KeywordCxt=Pn.validateFunctionCode=void 0;var Rk=ik(),kk=Fa(),sg=Jh(),kl=Fa(),wV=fk(),Za=vk(),ng=bk(),j=X(),B=Gr(),SV=qa(),Yr=pe(),Ua=La();function $V(t){if(Dk(t)&&(Ok(t),Ck(t))){kV(t);return}Ak(t,()=>(0,Rk.topBoolOrEmptySchema)(t))}Pn.validateFunctionCode=$V;function Ak({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,j._)`${B.default.data}, ${B.default.valCxt}`,n.$async,()=>{t.code((0,j._)`"use strict"; ${Tk(r,s)}`),PV(t,s),t.code(o)}):t.func(e,(0,j._)`${B.default.data}, ${xV(s)}`,n.$async,()=>t.code(Tk(r,s)).code(o))}function xV(t){return(0,j._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${t.dynamicRef?(0,j._)`, ${B.default.dynamicAnchors}={}`:j.nil}}={}`}function PV(t,e){t.if(B.default.valCxt,()=>{t.var(B.default.instancePath,(0,j._)`${B.default.valCxt}.${B.default.instancePath}`),t.var(B.default.parentData,(0,j._)`${B.default.valCxt}.${B.default.parentData}`),t.var(B.default.parentDataProperty,(0,j._)`${B.default.valCxt}.${B.default.parentDataProperty}`),t.var(B.default.rootData,(0,j._)`${B.default.valCxt}.${B.default.rootData}`),e.dynamicRef&&t.var(B.default.dynamicAnchors,(0,j._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{t.var(B.default.instancePath,(0,j._)`""`),t.var(B.default.parentData,(0,j._)`undefined`),t.var(B.default.parentDataProperty,(0,j._)`undefined`),t.var(B.default.rootData,B.default.data),e.dynamicRef&&t.var(B.default.dynamicAnchors,(0,j._)`{}`)})}function kV(t){let{schema:e,opts:r,gen:n}=t;Ak(t,()=>{r.$comment&&e.$comment&&zk(t),AV(t),n.let(B.default.vErrors,null),n.let(B.default.errors,0),r.unevaluated&&TV(t),Mk(t),OV(t)})}function TV(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,j._)`${r}.evaluated`),e.if((0,j._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,j._)`${t.evaluated}.props`,(0,j._)`undefined`)),e.if((0,j._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,j._)`${t.evaluated}.items`,(0,j._)`undefined`))}function Tk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,j._)`/*# sourceURL=${r} */`:j.nil}function EV(t,e){if(Dk(t)&&(Ok(t),Ck(t))){IV(t,e);return}(0,Rk.boolOrEmptySchema)(t,e)}function Ck({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 Dk(t){return typeof t.schema!="boolean"}function IV(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&zk(t),CV(t),DV(t);let o=n.const("_errs",B.default.errors);Mk(t,o),n.var(e,(0,j._)`${o} === ${B.default.errors}`)}function Ok(t){(0,Yr.checkUnknownRules)(t),RV(t)}function Mk(t,e){if(t.opts.jtd)return Ek(t,[],!1,e);let r=(0,kk.getSchemaTypes)(t.schema),n=(0,kk.coerceAndCheckDataType)(t,r);Ek(t,r,!n,e)}function RV(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Yr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function AV(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Yr.checkStrictMode)(t,"default is ignored in the schema root")}function CV(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,SV.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function DV(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function zk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,j._)`${B.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,j.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,j._)`${B.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function OV(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,j._)`${B.default.errors} === 0`,()=>e.return(B.default.data),()=>e.throw((0,j._)`new ${s}(${B.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,B.default.vErrors),o.unevaluated&&MV(t),e.return((0,j._)`${B.default.errors} === 0`))}function MV({gen:t,evaluated:e,props:r,items:n}){r instanceof j.Name&&t.assign((0,j._)`${e}.props`,r),n instanceof j.Name&&t.assign((0,j._)`${e}.items`,n)}function Ek(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,Yr.schemaHasRulesButRef)(o,l))){s.block(()=>Nk(t,"$ref",l.all.$ref.definition));return}c.jtd||zV(t,e),s.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,sg.shouldUseGroup)(o,p)&&(p.type?(s.if((0,kl.checkDataType)(p.type,i,c.strictNumbers)),Ik(t,p),e.length===1&&e[0]===p.type&&r&&(s.else(),(0,kl.reportTypeError)(t)),s.endIf()):Ik(t,p),a||s.if((0,j._)`${B.default.errors} === ${n||0}`))}}function Ik(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,wV.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,sg.shouldUseRule)(n,o)&&Nk(t,o.keyword,o.definition,e.type)})}function zV(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(jV(t,e),t.opts.allowUnionTypes||NV(t,e),LV(t,t.dataTypes))}function jV(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{jk(t.dataTypes,r)||og(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),qV(t,e)}}function NV(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&og(t,"use allowUnionTypes to allow union type keyword")}function LV(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,sg.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>FV(e,i))&&og(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function FV(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function jk(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function qV(t,e){let r=[];for(let n of t.dataTypes)jk(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function og(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Yr.checkStrictMode)(t,e,t.opts.strictTypes)}var Tl=class{constructor(e,r,n){if((0,Za.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,Yr.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",Lk(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Za.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,j.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,j.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,j._)`${r} !== undefined && (${(0,j.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?Ua.reportExtraError:Ua.reportError)(this,this.def.error,r)}$dataError(){(0,Ua.reportError)(this,this.def.$dataError||Ua.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ua.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=j.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=j.nil,r=j.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,j.or)((0,j._)`${s} === undefined`,r)),e!==j.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==j.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,j.or)(i(),a());function i(){if(n.length){if(!(r instanceof j.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,j._)`${(0,kl.checkDataTypes)(c,r,o.opts.strictNumbers,kl.DataType.Wrong)}`}return j.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,j._)`!${c}(${r})`}return j.nil}}subschema(e,r){let n=(0,ng.getSubschema)(this.it,e);(0,ng.extendSubschemaData)(n,this.it,e),(0,ng.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return EV(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Yr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Yr.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,j.Name)),!0}};Pn.KeywordCxt=Tl;function Nk(t,e,r,n){let s=new Tl(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Za.funcKeywordCode)(s,r):"macro"in r?(0,Za.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Za.funcKeywordCode)(s,r)}var UV=/^\/(?:[^~]|~0|~1)*$/,ZV=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Lk(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return B.default.rootData;if(t[0]==="/"){if(!UV.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=B.default.rootData}else{let u=ZV.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,j._)`${o}${(0,j.getProperty)((0,Yr.unescapeJsonPointer)(u))}`,i=(0,j._)`${i} && ${o}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Pn.getData=Lk});var El=S(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});var ig=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};ag.default=ig});var Ba=S(lg=>{"use strict";Object.defineProperty(lg,"__esModule",{value:!0});var cg=qa(),ug=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,cg.resolveUrl)(e,r,n),this.missingSchema=(0,cg.normalizeId)((0,cg.getFullPath)(e,this.missingRef))}};lg.default=ug});var Rl=S(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.resolveSchema=Qt.getCompilingSchema=Qt.resolveRef=Qt.compileSchema=Qt.SchemaEnv=void 0;var dr=X(),VV=El(),Ss=Gr(),pr=qa(),Fk=pe(),BV=Va(),Uo=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,pr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Qt.SchemaEnv=Uo;function pg(t){let e=qk.call(this,t);if(e)return e;let r=(0,pr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new dr.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:VV.default,code:(0,dr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Ss.default.data,parentData:Ss.default.parentData,parentDataProperty:Ss.default.parentDataProperty,dataNames:[Ss.default.data],dataPathArr:[dr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,dr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:dr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,dr._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,BV.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Ss.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${Ss.default.self}`,`${Ss.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 dr.Name?void 0:m,items:h instanceof dr.Name?void 0:h,dynamicProps:m instanceof dr.Name,dynamicItems:h instanceof dr.Name},f.source&&(f.source.evaluated=(0,dr.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)}}Qt.compileSchema=pg;function HV(t,e,r){var n;r=(0,pr.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=JV.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 Uo({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=WV.call(this,o)}Qt.resolveRef=HV;function WV(t){return(0,pr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:pg.call(this,t)}function qk(t){for(let e of this._compilations)if(KV(e,t))return e}Qt.getCompilingSchema=qk;function KV(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function JV(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Il.call(this,t,e)}function Il(t,e){let r=this.opts.uriResolver.parse(e),n=(0,pr._getFullPath)(this.opts.uriResolver,r),s=(0,pr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return dg.call(this,r,t);let o=(0,pr.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Il.call(this,t,i);return typeof a?.schema!="object"?void 0:dg.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||pg.call(this,i),o===(0,pr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,pr.resolveUrl)(this.opts.uriResolver,s,u)),new Uo({schema:a,schemaId:c,root:t,baseId:s})}return dg.call(this,r,i)}}Qt.resolveSchema=Il;var GV=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function dg(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,Fk.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!GV.has(a)&&u&&(e=(0,pr.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,Fk.schemaHasRulesButRef)(r,this.RULES)){let a=(0,pr.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Il.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new Uo({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var Uk=S((Yee,YV)=>{YV.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 Vk=S(fg=>{"use strict";Object.defineProperty(fg,"__esModule",{value:!0});var Zk=Im();Zk.code='require("ajv/dist/runtime/uri").default';fg.default=Zk});var Xk=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 XV=Va();Object.defineProperty(et,"KeywordCxt",{enumerable:!0,get:function(){return XV.KeywordCxt}});var Zo=X();Object.defineProperty(et,"_",{enumerable:!0,get:function(){return Zo._}});Object.defineProperty(et,"str",{enumerable:!0,get:function(){return Zo.str}});Object.defineProperty(et,"stringify",{enumerable:!0,get:function(){return Zo.stringify}});Object.defineProperty(et,"nil",{enumerable:!0,get:function(){return Zo.nil}});Object.defineProperty(et,"Name",{enumerable:!0,get:function(){return Zo.Name}});Object.defineProperty(et,"CodeGen",{enumerable:!0,get:function(){return Zo.CodeGen}});var QV=El(),Jk=Ba(),eB=Kh(),Ha=Rl(),tB=X(),Wa=qa(),Al=Fa(),hg=pe(),Bk=Uk(),rB=Vk(),Gk=(t,e)=>new RegExp(t,e);Gk.code="new RegExp";var nB=["removeAdditional","useDefaults","coerceTypes"],sB=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),oB={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."},iB={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Hk=200;function aB(t){var e,r,n,s,o,i,a,c,u,l,d,p,f,m,h,y,v,_,b,P,x,N,k,O,L;let F=t.strict,xe=(e=t.code)===null||e===void 0?void 0:e.optimize,We=xe===!0||xe===void 0?1:xe||0,Ct=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Gk,Nt=(s=t.uriResolver)!==null&&s!==void 0?s:rB.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:F)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:F)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:F)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:F)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:F)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:We,regExp:Ct}:{optimize:We,regExp:Ct},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Hk,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:Hk,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(P=t.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(x=t.addUsedSchema)!==null&&x!==void 0?x:!0,validateSchema:(N=t.validateSchema)!==null&&N!==void 0?N:!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:Nt}}var Ka=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,...aB(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new tB.ValueScope({scope:{},prefixes:sB,es5:r,lines:n}),this.logger=fB(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,eB.getRules)(),Wk.call(this,oB,e,"NOT SUPPORTED"),Wk.call(this,iB,e,"DEPRECATED","warn"),this._metaOpts=dB.call(this),e.formats&&uB.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&lB.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),cB.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 Jk.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,Wa.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=Kk.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Ha.SchemaEnv({schema:{},schemaId:n});if(r=Ha.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=Kk.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,Wa.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(hB.call(this,n,r),!r)return(0,hg.eachItem)(n,o=>mg.call(this,o)),this;yB.call(this,r);let s={...r,type:(0,Al.getJSONTypes)(r.type),schemaType:(0,Al.getJSONTypes)(r.schemaType)};return(0,hg.eachItem)(n,s.type.length===0?o=>mg.call(this,o,s):o=>s.type.forEach(i=>mg.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]=Yk(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,Wa.normalizeId)(i||n);let u=Wa.getSchemaRefs.call(this,e,n);return c=new Ha.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):Ha.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{Ha.compileSchema.call(this,e)}finally{this.opts=r}}};Ka.ValidationError=QV.default;Ka.MissingRefError=Jk.default;et.default=Ka;function Wk(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 Kk(t){return t=(0,Wa.normalizeId)(t),this.schemas[t]||this.refs[t]}function cB(){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 uB(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function lB(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 dB(){let t={...this.opts};for(let e of nB)delete t[e];return t}var pB={log(){},warn(){},error(){}};function fB(t){if(t===!1)return pB;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 mB=/^[a-z_$][a-z0-9_$:-]*$/i;function hB(t,e){let{RULES:r}=this;if((0,hg.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!mB.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 mg(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,Al.getJSONTypes)(e.type),schemaType:(0,Al.getJSONTypes)(e.schemaType)}};e.before?gB.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 gB(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 yB(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Yk(e)),t.validateSchema=this.compile(e,!0))}var vB={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Yk(t){return{anyOf:[t,vB]}}});var Qk=S(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var _B={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};gg.default=_B});var nT=S($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.callRef=$s.getValidate=void 0;var bB=Ba(),eT=Xt(),Rt=X(),Vo=Gr(),tT=Rl(),Cl=pe(),wB={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=tT.resolveRef.call(c,u,s,r);if(l===void 0)throw new bB.default(n.opts.uriResolver,s,r);if(l instanceof tT.SchemaEnv)return p(l);return f(l);function d(){if(o===u)return Dl(t,i,o,o.$async);let m=e.scopeValue("root",{ref:u});return Dl(t,(0,Rt._)`${m}.validate`,u,u.$async)}function p(m){let h=rT(t,m);Dl(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 rT(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Rt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}$s.getValidate=rT;function Dl(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?Vo.default.this:Rt.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,Rt._)`await ${(0,eT.callValidateCode)(t,e,u)}`),f(e),i||s.assign(m,!0)},h=>{s.if((0,Rt._)`!(${h} instanceof ${o.ValidationError})`,()=>s.throw(h)),p(h),i||s.assign(m,!1)}),t.ok(m)}function d(){t.result((0,eT.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,Rt._)`${m}.errors`;s.assign(Vo.default.vErrors,(0,Rt._)`${Vo.default.vErrors} === null ? ${h} : ${Vo.default.vErrors}.concat(${h})`),s.assign(Vo.default.errors,(0,Rt._)`${Vo.default.vErrors}.length`)}function f(m){var h;if(!o.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(o.props=Cl.mergeEvaluated.props(s,y.props,o.props));else{let v=s.var("props",(0,Rt._)`${m}.evaluated.props`);o.props=Cl.mergeEvaluated.props(s,v,o.props,Rt.Name)}if(o.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(o.items=Cl.mergeEvaluated.items(s,y.items,o.items));else{let v=s.var("items",(0,Rt._)`${m}.evaluated.items`);o.items=Cl.mergeEvaluated.items(s,v,o.items,Rt.Name)}}}$s.callRef=Dl;$s.default=wB});var sT=S(yg=>{"use strict";Object.defineProperty(yg,"__esModule",{value:!0});var SB=Qk(),$B=nT(),xB=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",SB.default,$B.default];yg.default=xB});var oT=S(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});var Ol=X(),kn=Ol.operators,Ml={maximum:{okStr:"<=",ok:kn.LTE,fail:kn.GT},minimum:{okStr:">=",ok:kn.GTE,fail:kn.LT},exclusiveMaximum:{okStr:"<",ok:kn.LT,fail:kn.GTE},exclusiveMinimum:{okStr:">",ok:kn.GT,fail:kn.LTE}},PB={message:({keyword:t,schemaCode:e})=>(0,Ol.str)`must be ${Ml[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ol._)`{comparison: ${Ml[t].okStr}, limit: ${e}}`},kB={keyword:Object.keys(Ml),type:"number",schemaType:"number",$data:!0,error:PB,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Ol._)`${r} ${Ml[e].fail} ${n} || isNaN(${r})`)}};vg.default=kB});var iT=S(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});var Ja=X(),TB={message:({schemaCode:t})=>(0,Ja.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ja._)`{multipleOf: ${t}}`},EB={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:TB,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Ja._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Ja._)`${i} !== parseInt(${i})`;t.fail$data((0,Ja._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};_g.default=EB});var cT=S(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});function aT(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}bg.default=aT;aT.code='require("ajv/dist/runtime/ucs2length").default'});var uT=S(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});var xs=X(),IB=pe(),RB=cT(),AB={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,xs.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,xs._)`{limit: ${t}}`},CB={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:AB,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?xs.operators.GT:xs.operators.LT,i=s.opts.unicode===!1?(0,xs._)`${r}.length`:(0,xs._)`${(0,IB.useFunc)(t.gen,RB.default)}(${r})`;t.fail$data((0,xs._)`${i} ${o} ${n}`)}};wg.default=CB});var lT=S(Sg=>{"use strict";Object.defineProperty(Sg,"__esModule",{value:!0});var DB=Xt(),OB=pe(),Bo=X(),MB={message:({schemaCode:t})=>(0,Bo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Bo._)`{pattern: ${t}}`},zB={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:MB,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,Bo._)`new RegExp`:(0,OB.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Bo._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Bo._)`!${l}`)}else{let c=(0,DB.usePattern)(t,s);t.fail$data((0,Bo._)`!${c}.test(${r})`)}}};Sg.default=zB});var dT=S($g=>{"use strict";Object.defineProperty($g,"__esModule",{value:!0});var Ga=X(),jB={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}}`},NB={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:jB,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}`)}};$g.default=NB});var pT=S(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var Ya=Xt(),Xa=X(),LB=pe(),FB={message:({params:{missingProperty:t}})=>(0,Xa.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Xa._)`{missingProperty: ${t}}`},qB={keyword:"required",type:"object",schemaType:"array",$data:!0,error:FB,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 y=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,LB.checkStrictMode)(i,v,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(Xa.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,Xa.not)(m),()=>{t.error(),e.break()})},Xa.nil)}}};xg.default=qB});var fT=S(Pg=>{"use strict";Object.defineProperty(Pg,"__esModule",{value:!0});var Qa=X(),UB={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Qa.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Qa._)`{limit: ${t}}`},ZB={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:UB,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Qa.operators.GT:Qa.operators.LT;t.fail$data((0,Qa._)`${r}.length ${s} ${n}`)}};Pg.default=ZB});var zl=S(kg=>{"use strict";Object.defineProperty(kg,"__esModule",{value:!0});var mT=pa();mT.code='require("ajv/dist/runtime/equal").default';kg.default=mT});var hT=S(Eg=>{"use strict";Object.defineProperty(Eg,"__esModule",{value:!0});var Tg=Fa(),tt=X(),VB=pe(),BB=zl(),HB={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}}`},WB={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:HB,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,Tg.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 y=e.name("item"),v=(0,Tg.checkDataTypes)(u,y,a.opts.strictNumbers,Tg.DataType.Wrong),_=e.const("indices",(0,tt._)`{}`);e.for((0,tt._)`;${m}--;`,()=>{e.let(y,(0,tt._)`${r}[${m}]`),e.if(v,(0,tt._)`continue`),u.length>1&&e.if((0,tt._)`typeof ${y} == "string"`,(0,tt._)`${y} += "_"`),e.if((0,tt._)`typeof ${_}[${y}] == "number"`,()=>{e.assign(h,(0,tt._)`${_}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,tt._)`${_}[${y}] = ${m}`)})}function f(m,h){let y=(0,VB.useFunc)(e,BB.default),v=e.name("outer");e.label(v).for((0,tt._)`;${m}--;`,()=>e.for((0,tt._)`${h} = ${m}; ${h}--;`,()=>e.if((0,tt._)`${y}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};Eg.default=WB});var gT=S(Rg=>{"use strict";Object.defineProperty(Rg,"__esModule",{value:!0});var Ig=X(),KB=pe(),JB=zl(),GB={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ig._)`{allowedValue: ${t}}`},YB={keyword:"const",$data:!0,error:GB,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,Ig._)`!${(0,KB.useFunc)(e,JB.default)}(${r}, ${s})`):t.fail((0,Ig._)`${o} !== ${r}`)}};Rg.default=YB});var yT=S(Ag=>{"use strict";Object.defineProperty(Ag,"__esModule",{value:!0});var ec=X(),XB=pe(),QB=zl(),e9={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ec._)`{allowedValues: ${t}}`},t9={keyword:"enum",schemaType:"array",$data:!0,error:e9,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,XB.useFunc)(e,QB.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,ec.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,ec._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let h=s[m];return typeof h=="object"&&h!==null?(0,ec._)`${u()}(${r}, ${f}[${m}])`:(0,ec._)`${r} === ${h}`}}};Ag.default=t9});var vT=S(Cg=>{"use strict";Object.defineProperty(Cg,"__esModule",{value:!0});var r9=oT(),n9=iT(),s9=uT(),o9=lT(),i9=dT(),a9=pT(),c9=fT(),u9=hT(),l9=gT(),d9=yT(),p9=[r9.default,n9.default,s9.default,o9.default,i9.default,a9.default,c9.default,u9.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},l9.default,d9.default];Cg.default=p9});var Og=S(tc=>{"use strict";Object.defineProperty(tc,"__esModule",{value:!0});tc.validateAdditionalItems=void 0;var Ps=X(),Dg=pe(),f9={message:({params:{len:t}})=>(0,Ps.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ps._)`{limit: ${t}}`},m9={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:f9,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Dg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}_T(t,n)}};function _T(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,Ps._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Ps._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Dg.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Ps._)`${a} <= ${e.length}`);r.if((0,Ps.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:o,dataProp:l,dataPropType:Dg.Type.Num},u),i.allErrors||r.if((0,Ps.not)(u),()=>r.break())})}}tc.validateAdditionalItems=_T;tc.default=m9});var Mg=S(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});rc.validateTuple=void 0;var bT=X(),jl=pe(),h9=Xt(),g9={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return wT(t,"additionalItems",e);r.items=!0,!(0,jl.alwaysValidSchema)(r,e)&&t.ok((0,h9.validateArray)(t))}};function wT(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=jl.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,bT._)`${o}.length`);r.forEach((d,p)=>{(0,jl.alwaysValidSchema)(a,d)||(n.if((0,bT._)`${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,jl.checkStrictMode)(a,y,p.strictTuples)}}}rc.validateTuple=wT;rc.default=g9});var ST=S(zg=>{"use strict";Object.defineProperty(zg,"__esModule",{value:!0});var y9=Mg(),v9={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,y9.validateTuple)(t,"items")};zg.default=v9});var xT=S(jg=>{"use strict";Object.defineProperty(jg,"__esModule",{value:!0});var $T=X(),_9=pe(),b9=Xt(),w9=Og(),S9={message:({params:{len:t}})=>(0,$T.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,$T._)`{limit: ${t}}`},$9={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:S9,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,_9.alwaysValidSchema)(n,e)&&(s?(0,w9.validateAdditionalItems)(t,s):t.ok((0,b9.validateArray)(t)))}};jg.default=$9});var PT=S(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});var er=X(),Nl=pe(),x9={message:({params:{min:t,max:e}})=>e===void 0?(0,er.str)`must contain at least ${t} valid item(s)`:(0,er.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,er._)`{minContains: ${t}}`:(0,er._)`{minContains: ${t}, maxContains: ${e}}`},P9={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:x9,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,er._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Nl.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Nl.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Nl.alwaysValidSchema)(o,r)){let h=(0,er._)`${l} >= ${i}`;a!==void 0&&(h=(0,er._)`${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,er._)`${s}.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:Nl.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,er._)`${h}++`),a===void 0?e.if((0,er._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,er._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,er._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};Ng.default=P9});var ET=S(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.validateSchemaDeps=Ar.validatePropertyDeps=Ar.error=void 0;var Lg=X(),k9=pe(),nc=Xt();Ar.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Lg.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Lg._)`{property: ${t},
|
|
17
17
|
missingProperty: ${n},
|
|
18
18
|
depsCount: ${e},
|
|
19
|
-
deps: ${r}}`};var y9={keyword:"dependencies",type:"object",schemaType:"object",error:Ir.error,code(t){let[e,r]=v9(t);mE(t,e),hE(t,r)}};function v9({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 mE(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,Xa.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,Xa.checkReportMissingProp)(t,u)}):(r.if((0,Dg._)`${c} && (${(0,Xa.checkMissingProp)(t,a,o)})`),(0,Xa.reportMissingProp)(t,o),r.else())}}Ir.validatePropertyDeps=mE;function hE(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,g9.alwaysValidSchema)(o,e[a])||(r.if((0,Xa.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=hE;Ir.default=y9});var vE=S(Og=>{"use strict";Object.defineProperty(Og,"__esModule",{value:!0});var yE=X(),_9=pe(),b9={message:"property name must be valid",params:({params:t})=>(0,yE._)`{propertyName: ${t.propertyName}}`},w9={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:b9,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,_9.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,yE.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Og.default=w9});var zg=S(Mg=>{"use strict";Object.defineProperty(Mg,"__esModule",{value:!0});var Cl=Gt(),dr=X(),S9=Kr(),Dl=pe(),$9={message:"must NOT have additional properties",params:({params:t})=>(0,dr._)`{additionalProperty: ${t.additionalProperty}}`},x9={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:$9,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,Dl.alwaysValidSchema)(i,r))return;let u=(0,Cl.allSchemaProperties)(n.properties),l=(0,Cl.allSchemaProperties)(n.patternProperties);d(),t.ok((0,dr._)`${o} === ${S9.default.errors}`);function d(){e.forIn("key",s,y=>{!u.length&&!l.length?m(y):e.if(p(y),()=>m(y))})}function p(y){let g;if(u.length>8){let b=(0,Dl.schemaRefOrVal)(i,n.properties,"properties");g=(0,Cl.isOwnProperty)(e,b,y)}else u.length?g=(0,dr.or)(...u.map(b=>(0,dr._)`${y} === ${b}`)):g=dr.nil;return l.length&&(g=(0,dr.or)(g,...l.map(b=>(0,dr._)`${(0,Cl.usePattern)(t,b)}.test(${y})`))),(0,dr.not)(g)}function f(y){e.code((0,dr._)`delete ${s}[${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,Dl.alwaysValidSchema)(i,r)){let g=e.name("valid");c.removeAdditional==="failing"?(h(y,g,!1),e.if((0,dr.not)(g),()=>{t.reset(),f(y)})):(h(y,g),a||e.if((0,dr.not)(g),()=>e.break()))}}function h(y,g,b){let _={keyword:"additionalProperties",dataProp:y,dataPropType:Dl.Type.Str};b===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,g)}}};Mg.default=x9});var wE=S(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});var P9=La(),_E=Gt(),jg=pe(),bE=zg(),k9={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&&bE.default.code(new P9.KeywordCxt(o,bE.default,"additionalProperties"));let i=(0,_E.allSchemaProperties)(r);for(let d of i)o.definedProperties.add(d);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=jg.mergeEvaluated.props(e,(0,jg.toHash)(i),o.props));let a=i.filter(d=>!(0,jg.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,_E.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)}}};Ng.default=k9});var PE=S(Lg=>{"use strict";Object.defineProperty(Lg,"__esModule",{value:!0});var SE=Gt(),Ol=X(),$E=pe(),xE=pe(),E9={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,SE.allSchemaProperties)(r),c=a.filter(h=>(0,$E.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 Ol.Name)&&(o.props=(0,xE.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 y in u)new RegExp(h).test(y)&&(0,$E.checkStrictMode)(o,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,Ol._)`${(0,SE.usePattern)(t,h)}.test(${y})`,()=>{let g=c.includes(h);g||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:xE.Type.Str},l),o.opts.unevaluated&&d!==!0?e.assign((0,Ol._)`${d}[${y}]`,!0):!g&&!o.allErrors&&e.if((0,Ol.not)(l),()=>e.break())})})}}};Lg.default=E9});var kE=S(qg=>{"use strict";Object.defineProperty(qg,"__esModule",{value:!0});var T9=pe(),I9={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,T9.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"}};qg.default=I9});var EE=S(Fg=>{"use strict";Object.defineProperty(Fg,"__esModule",{value:!0});var R9=Gt(),A9={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:R9.validateUnion,error:{message:"must match a schema in anyOf"}};Fg.default=A9});var TE=S(Ug=>{"use strict";Object.defineProperty(Ug,"__esModule",{value:!0});var Ml=X(),C9=pe(),D9={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ml._)`{passingSchemas: ${t.passing}}`},O9={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,C9.alwaysValidSchema)(s,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Ml._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ml._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Ml.Name)})})}}};Ug.default=O9});var IE=S(Zg=>{"use strict";Object.defineProperty(Zg,"__esModule",{value:!0});var M9=pe(),z9={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,M9.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Zg.default=z9});var CE=S(Vg=>{"use strict";Object.defineProperty(Vg,"__esModule",{value:!0});var zl=X(),AE=pe(),j9={message:({params:t})=>(0,zl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,zl._)`{failingKeyword: ${t.ifClause}}`},N9={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:j9,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,AE.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=RE(n,"then"),o=RE(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,zl.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,zl._)`${l}`):t.setParams({ifClause:l})}}}};function RE(t,e){let r=t.schema[e];return r!==void 0&&!(0,AE.alwaysValidSchema)(t,r)}Vg.default=N9});var DE=S(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});var L9=pe(),q9={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,L9.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Bg.default=q9});var OE=S(Hg=>{"use strict";Object.defineProperty(Hg,"__esModule",{value:!0});var F9=Tg(),U9=lE(),Z9=Ig(),V9=pE(),B9=fE(),H9=gE(),W9=vE(),K9=zg(),J9=wE(),G9=PE(),Y9=kE(),X9=EE(),Q9=TE(),e2=IE(),t2=CE(),r2=DE();function n2(t=!1){let e=[Y9.default,X9.default,Q9.default,e2.default,t2.default,r2.default,W9.default,K9.default,H9.default,J9.default,G9.default];return t?e.push(U9.default,V9.default):e.push(F9.default,Z9.default),e.push(B9.default),e}Hg.default=n2});var ME=S(Wg=>{"use strict";Object.defineProperty(Wg,"__esModule",{value:!0});var Ue=X(),s2={message:({schemaCode:t})=>(0,Ue.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ue._)`{format: ${t}}`},o2={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:s2,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}]`),y=r.let("fType"),g=r.let("format");r.if((0,Ue._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,Ue._)`${h}.type || "string"`).assign(g,(0,Ue._)`${h}.validate`),()=>r.assign(y,(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 && ${y} === ${e} && !${x}`}}function f(){let m=d.formats[o];if(!m){b();return}if(m===!0)return;let[h,y,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 N=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:N});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 y=="function"?(0,Ue._)`${g}(${n})`:(0,Ue._)`${g}.test(${n})`}}}};Wg.default=o2});var zE=S(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});var i2=ME(),a2=[i2.default];Kg.default=a2});var jE=S(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.contentVocabulary=Fo.metadataVocabulary=void 0;Fo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Fo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var LE=S(Jg=>{"use strict";Object.defineProperty(Jg,"__esModule",{value:!0});var c2=Hk(),u2=iE(),l2=OE(),d2=zE(),NE=jE(),p2=[c2.default,u2.default,(0,l2.default)(),d2.default,NE.metadataVocabulary,NE.contentVocabulary];Jg.default=p2});var FE=S(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});jl.DiscrError=void 0;var qE;(function(t){t.Tag="tag",t.Mapping="mapping"})(qE||(jl.DiscrError=qE={}))});var ZE=S(Yg=>{"use strict";Object.defineProperty(Yg,"__esModule",{value:!0});var Uo=X(),Gg=FE(),UE=$l(),f2=qa(),m2=pe(),h2={message:({params:{discrError:t,tagName:e}})=>t===Gg.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Uo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},g2={keyword:"discriminator",type:"object",schemaType:"object",error:h2,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,Uo._)`${r}${(0,Uo.getProperty)(a)}`);e.if((0,Uo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Gg.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,Uo._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:Gg.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,Uo.Name),m}function p(){var f;let m={},h=g(s),y=!0;for(let P=0;P<i.length;P++){let x=i[P];if(x?.$ref&&!(0,m2.schemaHasRulesButRef)(x,o.self.RULES)){let k=x.$ref;if(x=UE.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,k),x instanceof UE.SchemaEnv&&(x=x.schema),x===void 0)throw new f2.default(o.opts.uriResolver,o.baseId,k)}let N=(f=x?.properties)===null||f===void 0?void 0:f[a];if(typeof N!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||g(x)),b(N,P)}if(!y)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 N of P.enum)_(N,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}}}};Yg.default=g2});var VE=S((kte,y2)=>{y2.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 HE=S((De,Xg)=>{"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 v2=qk(),_2=LE(),b2=ZE(),BE=VE(),w2=["/properties"],Nl="http://json-schema.org/draft-07/schema",Zo=class extends v2.default{_addVocabularies(){super._addVocabularies(),_2.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(b2.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(BE,w2):BE;this.addMetaSchema(e,Nl,!1),this.refs["http://json-schema.org/schema"]=Nl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Nl)?Nl:void 0)}};De.Ajv=Zo;Xg.exports=De=Zo;Xg.exports.Ajv=Zo;Object.defineProperty(De,"__esModule",{value:!0});De.default=Zo;var S2=La();Object.defineProperty(De,"KeywordCxt",{enumerable:!0,get:function(){return S2.KeywordCxt}});var Vo=X();Object.defineProperty(De,"_",{enumerable:!0,get:function(){return Vo._}});Object.defineProperty(De,"str",{enumerable:!0,get:function(){return Vo.str}});Object.defineProperty(De,"stringify",{enumerable:!0,get:function(){return Vo.stringify}});Object.defineProperty(De,"nil",{enumerable:!0,get:function(){return Vo.nil}});Object.defineProperty(De,"Name",{enumerable:!0,get:function(){return Vo.Name}});Object.defineProperty(De,"CodeGen",{enumerable:!0,get:function(){return Vo.CodeGen}});var $2=wl();Object.defineProperty(De,"ValidationError",{enumerable:!0,get:function(){return $2.default}});var x2=qa();Object.defineProperty(De,"MissingRefError",{enumerable:!0,get:function(){return x2.default}})});var WE=S(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.formatLimitDefinition=void 0;var P2=HE(),pr=X(),Pn=pr.operators,Ll={formatMaximum:{okStr:"<=",ok:Pn.LTE,fail:Pn.GT},formatMinimum:{okStr:">=",ok:Pn.GTE,fail:Pn.LT},formatExclusiveMaximum:{okStr:"<",ok:Pn.LT,fail:Pn.GTE},formatExclusiveMinimum:{okStr:">",ok:Pn.GT,fail:Pn.LTE}},k2={message:({keyword:t,schemaCode:e})=>(0,pr.str)`should be ${Ll[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,pr._)`{comparison: ${Ll[t].okStr}, limit: ${e}}`};Bo.formatLimitDefinition={keyword:Object.keys(Ll),type:"string",schemaType:"string",$data:!0,error:k2,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 P2.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}) ${Ll[s].fail} 0`}},dependencies:["format"]};var E2=t=>(t.addKeyword(Bo.formatLimitDefinition),t);Bo.default=E2});var YE=S((Qa,GE)=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});var Ho=CP(),T2=WE(),Qg=X(),KE=new Qg.Name("fullFormats"),I2=new Qg.Name("fastFormats"),ey=(t,e={keywords:!0})=>{if(Array.isArray(e))return JE(t,e,Ho.fullFormats,KE),t;let[r,n]=e.mode==="fast"?[Ho.fastFormats,I2]:[Ho.fullFormats,KE],s=e.formats||Ho.formatNames;return JE(t,s,r,n),e.keywords&&(0,T2.default)(t),t};ey.get=(t,e="full")=>{let n=(e==="fast"?Ho.fastFormats:Ho.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function JE(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Qg._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}GE.exports=Qa=ey;Object.defineProperty(Qa,"__esModule",{value:!0});Qa.default=ey});import{readFileSync as hK}from"fs";import{join as Ky}from"path";import{fileURLToPath as gK}from"url";var Is=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},oc=class extends Is{code="PROVIDER_NOT_FOUND";retryable=!1;constructor(e){super(e,`Provider not found: ${e}`)}},xe=class extends Is{code="PROVIDER_UNAVAILABLE";retryable=!1;constructor(e,r){super(e,`Provider unavailable: ${r||"not installed or not running"}`)}};var Rs=class extends Is{timeoutMs;code="PROVIDER_TIMEOUT";retryable=!0;constructor(e,r){super(e,`Timeout after ${r}ms`),this.timeoutMs=r}},dt=class extends Is{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(e,r){super(e,`Execution error: ${r}`)}};var hv={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"}},ZR={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 jd(t){return t<3?"simple":t<8?"moderate":t<=20?"complex":"advanced"}function cc(t,e,r,n=t){let s=hv[n]??hv[t]??{},o=s.maxComplexity??"simple";return n==="ollama"&&r!==void 0&&(o=jd(r)),{providerId:t,tier:s.tier??"tool",strengths:s.strengths??e.strengths,maxComplexity:o}}function Xr(t,e){let r=ZR[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 uc={low:0,medium:.5,high:.7},VR={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 gv(t,e){return e?.[t]??VR[t]??"low"}function lc(t,e,r=uc){return t>=r[e]}var dc=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 oc(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 cc(r.id,r.getCapabilities(),void 0,r.type)}getDescriptor(e){let r=this.get(e);return r.getDescriptor?.()??Xr(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??gv(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 lc(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 v={};rt(v,{BRAND:()=>gA,DIRTY:()=>Cn,EMPTY_PATH:()=>KR,INVALID:()=>F,NEVER:()=>eC,OK:()=>nt,ParseStatus:()=>Ke,Schema:()=>Y,ZodAny:()=>tn,ZodArray:()=>zr,ZodBigInt:()=>On,ZodBoolean:()=>Mn,ZodBranded:()=>ci,ZodCatch:()=>Hn,ZodDate:()=>zn,ZodDefault:()=>Bn,ZodDiscriminatedUnion:()=>mc,ZodEffects:()=>qt,ZodEnum:()=>Zn,ZodError:()=>_t,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>gc,ZodIntersection:()=>qn,ZodIssueCode:()=>E,ZodLazy:()=>Fn,ZodLiteral:()=>Un,ZodMap:()=>Fs,ZodNaN:()=>Zs,ZodNativeEnum:()=>Vn,ZodNever:()=>er,ZodNull:()=>Nn,ZodNullable:()=>yr,ZodNumber:()=>Dn,ZodObject:()=>bt,ZodOptional:()=>Nt,ZodParsedType:()=>R,ZodPipeline:()=>ui,ZodPromise:()=>rn,ZodReadonly:()=>Wn,ZodRecord:()=>hc,ZodSchema:()=>Y,ZodSet:()=>Us,ZodString:()=>en,ZodSymbol:()=>Ls,ZodTransformer:()=>qt,ZodTuple:()=>gr,ZodType:()=>Y,ZodUndefined:()=>jn,ZodUnion:()=>Ln,ZodUnknown:()=>Mr,ZodVoid:()=>qs,addIssueToContext:()=>I,any:()=>PA,array:()=>IA,bigint:()=>bA,boolean:()=>Ev,coerce:()=>QA,custom:()=>xv,date:()=>wA,datetimeRegex:()=>Sv,defaultErrorMap:()=>Dr,discriminatedUnion:()=>DA,effect:()=>BA,enum:()=>UA,function:()=>LA,getErrorMap:()=>zs,getParsedType:()=>hr,instanceof:()=>vA,intersection:()=>OA,isAborted:()=>pc,isAsync:()=>js,isDirty:()=>fc,isValid:()=>Qr,late:()=>yA,lazy:()=>qA,literal:()=>FA,makeIssue:()=>ai,map:()=>jA,nan:()=>_A,nativeEnum:()=>ZA,never:()=>EA,null:()=>xA,nullable:()=>WA,number:()=>kv,object:()=>RA,objectUtil:()=>Nd,oboolean:()=>XA,onumber:()=>YA,optional:()=>HA,ostring:()=>GA,pipeline:()=>JA,preprocess:()=>KA,promise:()=>VA,quotelessJson:()=>BR,record:()=>zA,set:()=>NA,setErrorMap:()=>WR,strictObject:()=>AA,string:()=>Pv,symbol:()=>SA,transformer:()=>BA,tuple:()=>MA,undefined:()=>$A,union:()=>CA,unknown:()=>kA,util:()=>se,void:()=>TA});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 Nd;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Nd||(Nd={}));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"]),BR=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 HR=(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}},Dr=HR;var yv=Dr;function WR(t){yv=t}function zs(){return yv}var ai=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}},KR=[];function I(t,e){let r=zs(),n=ai({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Dr?void 0:Dr].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"}),Cn=t=>({status:"dirty",value:t}),nt=t=>({status:"valid",value:t}),pc=t=>t.status==="aborted",fc=t=>t.status==="dirty",Qr=t=>t.status==="valid",js=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}},vv=(t,e)=>{if(Qr(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 H(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(js(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 vv(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 Qr(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=>Qr(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(js(s)?s:Promise.resolve(s));return vv(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 Nt.create(this,this._def)}nullable(){return yr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return zr.create(this)}promise(){return rn.create(this,this._def)}or(e){return Ln.create([this,e],this._def)}and(e){return qn.create(this,e,this._def)}transform(e){return new qt({...H(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Bn({...H(this._def),innerType:this,defaultValue:r,typeName:T.ZodDefault})}brand(){return new ci({typeName:T.ZodBranded,type:this,...H(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Hn({...H(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 ui.create(this,e)}readonly(){return Wn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},JR=/^c[^\s-]{8,}$/i,GR=/^[0-9a-z]+$/,YR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,XR=/^[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,QR=/^[a-z0-9_-]{21}$/i,eA=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tA=/^[-+]?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)?)??$/,rA=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,nA="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ld,sA=/^(?:(?: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])$/,oA=/^(?:(?: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])$/,iA=/^(([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]))$/,aA=/^(([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])$/,cA=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,uA=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,bv="((\\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])))",lA=new RegExp(`^${bv}$`);function wv(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 dA(t){return new RegExp(`^${wv(t)}$`)}function Sv(t){let e=`${bv}T${wv(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 pA(t,e){return!!((e==="v4"||!e)&&sA.test(t)||(e==="v6"||!e)&&iA.test(t))}function fA(t,e){if(!eA.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 mA(t,e){return!!((e==="v4"||!e)&&oA.test(t)||(e==="v6"||!e)&&aA.test(t))}var en=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")rA.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")Ld||(Ld=new RegExp(nA,"u")),Ld.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")XR.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")QR.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")JR.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")GR.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")YR.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"?Sv(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"?lA.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{code:E.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?dA(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"?tA.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"duration",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?pA(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"?fA(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"?mA(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"?cA.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"base64",code:E.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?uA.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}};en.create=t=>new en({checks:[],typeName:T.ZodString,coerce:t?.coerce??!1,...H(t)});function hA(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 Dn=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"?hA(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)}};Dn.create=t=>new Dn({checks:[],typeName:T.ZodNumber,coerce:t?.coerce||!1,...H(t)});var On=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}};On.create=t=>new On({checks:[],typeName:T.ZodBigInt,coerce:t?.coerce??!1,...H(t)});var Mn=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 nt(e.data)}};Mn.create=t=>new Mn({typeName:T.ZodBoolean,coerce:t?.coerce||!1,...H(t)});var zn=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}};zn.create=t=>new zn({checks:[],coerce:t?.coerce||!1,typeName:T.ZodDate,...H(t)});var Ls=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 nt(e.data)}};Ls.create=t=>new Ls({typeName:T.ZodSymbol,...H(t)});var jn=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 nt(e.data)}};jn.create=t=>new jn({typeName:T.ZodUndefined,...H(t)});var Nn=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 nt(e.data)}};Nn.create=t=>new Nn({typeName:T.ZodNull,...H(t)});var tn=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return nt(e.data)}};tn.create=t=>new tn({typeName:T.ZodAny,...H(t)});var Mr=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return nt(e.data)}};Mr.create=t=>new Mr({typeName:T.ZodUnknown,...H(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,...H(t)});var qs=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 nt(e.data)}};qs.create=t=>new qs({typeName:T.ZodVoid,...H(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,...H(e)});function Ns(t){if(t instanceof bt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Nt.create(Ns(n))}return new bt({...t._def,shape:()=>e})}else return t instanceof zr?new zr({...t._def,type:Ns(t.element)}):t instanceof Nt?Nt.create(Ns(t.unwrap())):t instanceof yr?yr.create(Ns(t.unwrap())):t instanceof gr?gr.create(t.items.map(e=>Ns(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 Ns(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 Nt;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return $v(se.objectKeys(this.shape))}};bt.create=(t,e)=>new bt({shape:()=>t,unknownKeys:"strip",catchall:er.create(),typeName:T.ZodObject,...H(e)});bt.strictCreate=(t,e)=>new bt({shape:()=>t,unknownKeys:"strict",catchall:er.create(),typeName:T.ZodObject,...H(e)});bt.lazycreate=(t,e)=>new bt({shape:t,unknownKeys:"strip",catchall:er.create(),typeName:T.ZodObject,...H(e)});var Ln=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}};Ln.create=(t,e)=>new Ln({options:t,typeName:T.ZodUnion,...H(e)});var Or=t=>t instanceof Fn?Or(t.schema):t instanceof qt?Or(t.innerType()):t instanceof Un?[t.value]:t instanceof Zn?t.options:t instanceof Vn?se.objectValues(t.enum):t instanceof Bn?Or(t._def.innerType):t instanceof jn?[void 0]:t instanceof Nn?[null]:t instanceof Nt?[void 0,...Or(t.unwrap())]:t instanceof yr?[null,...Or(t.unwrap())]:t instanceof ci||t instanceof Wn?Or(t.unwrap()):t instanceof Hn?Or(t._def.innerType):[],mc=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=Or(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,...H(n)})}};function qd(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=qd(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=qd(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 qn=class extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(pc(o)||pc(i))return F;let a=qd(o.value,i.value);return a.valid?((fc(o)||fc(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}))}};qn.create=(t,e,r)=>new qn({left:t,right:e,typeName:T.ZodIntersection,...H(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,...H(e)})};var hc=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,...H(n)}):new t({keyType:en.create(),valueType:e,typeName:T.ZodRecord,...H(r)})}},Fs=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}}}};Fs.create=(t,e,r)=>new Fs({valueType:e,keyType:t,typeName:T.ZodMap,...H(r)});var Us=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)}};Us.create=(t,e)=>new Us({valueType:t,minSize:null,maxSize:null,typeName:T.ZodSet,...H(e)});var gc=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 ai({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,zs(),Dr].filter(u=>!!u),issueData:{code:E.invalid_arguments,argumentsError:c}})}function s(a,c){return ai({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,zs(),Dr].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 rn){let a=this;return nt(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 nt(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(Mr.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(Mr.create()),returns:r||Mr.create(),typeName:T.ZodFunction,...H(n)})}},Fn=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})}};Fn.create=(t,e)=>new Fn({getter:t,typeName:T.ZodLazy,...H(e)});var Un=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}};Un.create=(t,e)=>new Un({value:t,typeName:T.ZodLiteral,...H(e)});function $v(t,e){return new Zn({values:t,typeName:T.ZodEnum,...H(e)})}var Zn=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 nt(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})}};Zn.create=$v;var Vn=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 nt(e.data)}get enum(){return this._def.values}};Vn.create=(t,e)=>new Vn({values:t,typeName:T.ZodNativeEnum,...H(e)});var rn=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 nt(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};rn.create=(t,e)=>new rn({type:t,typeName:T.ZodPromise,...H(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"?Cn(c.value):r.value==="dirty"?Cn(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"?Cn(a.value):r.value==="dirty"?Cn(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(!Qr(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=>Qr(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,...H(r)});qt.createWithPreprocess=(t,e,r)=>new qt({schema:e,effect:{type:"preprocess",transform:t},typeName:T.ZodEffects,...H(r)});var Nt=class extends Y{_parse(e){return this._getType(e)===R.undefined?nt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Nt.create=(t,e)=>new Nt({innerType:t,typeName:T.ZodOptional,...H(e)});var yr=class extends Y{_parse(e){return this._getType(e)===R.null?nt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};yr.create=(t,e)=>new yr({innerType:t,typeName:T.ZodNullable,...H(e)});var Bn=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}};Bn.create=(t,e)=>new Bn({innerType:t,typeName:T.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});var Hn=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 js(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}};Hn.create=(t,e)=>new Hn({innerType:t,typeName:T.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});var Zs=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}}};Zs.create=t=>new Zs({typeName:T.ZodNaN,...H(t)});var gA=Symbol("zod_brand"),ci=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}},ui=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(),Cn(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})}},Wn=class extends Y{_parse(e){let r=this._def.innerType._parse(e),n=s=>(Qr(s)&&(s.value=Object.freeze(s.value)),s);return js(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Wn.create=(t,e)=>new Wn({innerType:t,typeName:T.ZodReadonly,...H(e)});function _v(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function xv(t,e={},r){return t?tn.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=_v(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=_v(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):tn.create()}var yA={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 vA=(t,e={message:`Input not instance of ${t.name}`})=>xv(r=>r instanceof t,e),Pv=en.create,kv=Dn.create,_A=Zs.create,bA=On.create,Ev=Mn.create,wA=zn.create,SA=Ls.create,$A=jn.create,xA=Nn.create,PA=tn.create,kA=Mr.create,EA=er.create,TA=qs.create,IA=zr.create,RA=bt.create,AA=bt.strictCreate,CA=Ln.create,DA=mc.create,OA=qn.create,MA=gr.create,zA=hc.create,jA=Fs.create,NA=Us.create,LA=gc.create,qA=Fn.create,FA=Un.create,UA=Zn.create,ZA=Vn.create,VA=rn.create,BA=qt.create,HA=Nt.create,WA=yr.create,KA=qt.createWithPreprocess,JA=ui.create,GA=()=>Pv().optional(),YA=()=>kv().optional(),XA=()=>Ev().optional(),QA={string:(t=>en.create({...t,coerce:!0})),number:(t=>Dn.create({...t,coerce:!0})),boolean:(t=>Mn.create({...t,coerce:!0})),bigint:(t=>On.create({...t,coerce:!0})),date:(t=>zn.create({...t,coerce:!0}))};var eC=F;Cr();var tC=v.enum(["read-only","workspace-write","full-auto"]),rC=tC.default("read-only"),nC=v.object({id:v.string(),type:v.string(),enabled:v.boolean().default(!0),executionPolicy:rC,config:v.record(v.unknown()).default({})}),sC=v.enum(["default-only","auto"]).default("default-only"),oC=v.object({selectionPolicy:sC,locale:v.string().optional(),providers:v.array(nC).min(1,"At least one provider required")});function jr(t){switch(t){case"ollama":case"gemini-cli":case"codex-cli":case"claude-cli":return"workspace-write";default:return"read-only"}}function yc(t){return t==="workspace-write"||t==="full-auto"}function iC(t){return ic.includes(t)}function aC(t){if(t!==void 0)return iC(t)?t:(console.warn(`[config] unknown locale '${t}', falling back to ${Rn}`),Rn)}function Tv(t){let e=oC.parse(t);return{selectionPolicy:e.selectionPolicy,locale:aC(e.locale),providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}import{existsSync as Iv,mkdirSync as cC}from"fs";import{homedir as uC}from"os";import{dirname as lC,join as Rv}from"path";var Av="providers.config.json";function li(){let t=process.env.AGESTRA_CONFIG_PATH;if(t&&t.length>0)return t;let e=Rv(uC(),".agestra",Av);if(Iv(e))return e;let r=process.env.CLAUDE_PLUGIN_ROOT,n=r&&r.length>0?Rv(r,Av):void 0;return n&&Iv(n)?n:e}function Cv(t){cC(lC(t),{recursive:!0})}nn();bc();Vs();Os();import{mkdirSync as t_,readFileSync as vr,readdirSync as r_,existsSync as Dt}from"fs";import{join as Le}from"path";import{spawn as YC}from"child_process";import{randomUUID as XC}from"crypto";nn();Gd();fi();import{readFileSync as Wv}from"fs";import{join as $c}from"path";function xc(t){Promise.resolve().then(()=>(Hv(),Bv)).then(async({resolveCliConfig:e})=>{let r;try{r=JSON.parse(Wv($c(t,"job.json"),"utf-8"))}catch{return}let n=e(r);if(!n){Ve(t,{state:"missing_cli",completedAt:new Date().toISOString()}),ge($c(t,"error.txt"),`No CLI mapping for provider: ${r.provider}`);return}let{command:s,buildArgs:o}=n,i=Wv($c(t,"prompt.txt"),"utf-8"),a=o(i);Ve(t,{state:"running",startedAt:new Date().toISOString()}),await Sc({jobDir:t,command:s,args:a,cwd:r.cwd||void 0,timeoutMs:r.timeout,recordPid:!0})}).catch(()=>{try{Ve(t,{state:"error",completedAt:new Date().toISOString()}),ge($c(t,"error.txt"),"Failed to load job worker module")}catch{}})}import{existsSync as Kv,readFileSync as Jv,readdirSync as Gv,unlinkSync as ZC,rmdirSync as VC}from"fs";import{join as Pc}from"path";var BC=["completed","error","timed_out","cancelled","missing_cli"];function Yv(t){let{jobsDir:e,maxJobs:r,maxAgeDays:n,statusCache:s,clearDeferredSaveTimer:o}=t;if(!Kv(e))return 0;let i;try{i=Gv(e,{withFileTypes:!0}).filter(f=>f.isDirectory())}catch{return 0}let a=[];for(let f of i)try{let m=Pc(e,f.name,"status.json"),h=Pc(e,f.name,"job.json");if(!Kv(m))continue;let y=JSON.parse(Jv(m,"utf-8")),g=null;try{g=JSON.parse(Jv(h,"utf-8"))}catch{}a.push({name:f.name,status:y,descriptor:g})}catch{}let c=a.filter(f=>BC.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 g=Pc(e,f.name);try{let b=Gv(g);for(let _ of b)ZC(Pc(g,_));VC(g),s.delete(f.name),o(f.name),u++}catch{}}return u}nn();bc();Vs();import{existsSync as HC,readFileSync as Yd,readdirSync as WC}from"fs";import{join as Xd}from"path";function Xv(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=Xd(t,e,"job.json");try{let s=JSON.parse(Yd(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 e_(t){let{jobsDir:e,statusCache:r}=t,n=0,s;try{s=WC(e)}catch{return 0}for(let o of s){if(!Nr(o))continue;let i=Xd(e,o,"status.json");if(!HC(i))continue;let a;try{a=JSON.parse(Yd(i,"utf-8"))}catch{continue}if(a.state!=="running"||a.pid!==void 0&&Xv(a.pid))continue;let c=`${i}.lock`;try{let u=Kn(c,()=>{let l=JSON.parse(Yd(i,"utf-8"));if(l.state!=="running"||l.pid!==void 0&&Xv(l.pid))return null;let d={...l,state:"error",completedAt:new Date().toISOString()};return Ze(i,d),d});if(!u)continue;ge(Xd(e,o,"error.txt"),"orphaned (worker process died before completion)"),r.set(o,u),n++}catch{}}return n}fi();Cr();var QC=5e3,Qd=["completed","error","timed_out","cancelled","missing_cli"],kc=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,Qy),t_(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 r_(this.jobsDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).length}catch{return 0}}reconcileOrphans(){return e_({jobsDir:this.jobsDir,statusCache:this.statusCache})}submit(e){let r=`${e.provider}-${Date.now()}-${XC().slice(0,6)}`,n=Le(this.jobsDir,r);t_(n,{recursive:!0});let s=e.timeout??6e5,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+QC);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&&Qd.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=Kn(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),Qd.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,provider:r.provider,startedAt:r.startedAt,completedAt:r.completedAt,exitCode:r.exitCode,savedDocumentId:r.savedDocumentId,saveError:r.saveError,activity:r.activity},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(!Qd.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,provider:o.provider,startedAt:o.startedAt,completedAt:o.completedAt,exitCode:o.exitCode,activity:o.activity},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};Ve(r,d),this.statusCache.set(e,{...o,...d})}else{let d={saveError:`skipped (state=${o.state})`};Ve(r,d),this.statusCache.set(e,{...o,...d})}}catch(l){let p={saveError:l instanceof Error?l.message:String(l)};try{Ve(r,p),this.statusCache.set(e,{...o,...p})}catch{}}}listJobs(){if(!Dt(this.jobsDir))return[];let e;try{e=r_(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&&Ds(r.pid);let n=Le(this.jobsDir,e),s=Le(n,"status.json"),o=`${s}.lock`;try{let i=Kn(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 Yv({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=YC(process.execPath,[r,e],{detached:!0,stdio:"ignore",cwd:this.workspaceDir}),s=typeof n.pid=="number"&&n.pid>0;if(s)try{Ve(e,{pid:n.pid})}catch{}n.on("error",o=>{if(s)return;o.code==="ENOENT"?xc(e):xc(e)}),n.unref()}else xc(e)}};nn();Cr();import{mkdirSync as eD,readdirSync as n_,readFileSync as tD,unlinkSync as rD}from"fs";import{join as mi}from"path";function s_(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 nD(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function sD(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var Ec=class{tracesDir;writer;constructor(e,r){this.tracesDir=mi(e,ev),eD(this.tracesDir,{recursive:!0}),this.writer=new vc(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=s_(new Date(r.timestamp)),s=mi(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=
|
|
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 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=
|
|
23
|
-
`),r=[];for(let n=0;n<e.length;n++){let s=e[n];for(let o of
|
|
24
|
-
`);for(let r=0;r<e.length;r++){let n=e[r];for(let s of
|
|
25
|
-
`)}
|
|
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&&(
|
|
27
|
-
`)}function
|
|
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>
|
|
29
|
-
`)}var
|
|
19
|
+
deps: ${r}}`};var T9={keyword:"dependencies",type:"object",schemaType:"object",error:Ar.error,code(t){let[e,r]=E9(t);kT(t,e),TT(t,r)}};function E9({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 kT(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,nc.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,nc.checkReportMissingProp)(t,u)}):(r.if((0,Lg._)`${c} && (${(0,nc.checkMissingProp)(t,a,o)})`),(0,nc.reportMissingProp)(t,o),r.else())}}Ar.validatePropertyDeps=kT;function TT(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,k9.alwaysValidSchema)(o,e[a])||(r.if((0,nc.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))}Ar.validateSchemaDeps=TT;Ar.default=T9});var RT=S(Fg=>{"use strict";Object.defineProperty(Fg,"__esModule",{value:!0});var IT=X(),I9=pe(),R9={message:"property name must be valid",params:({params:t})=>(0,IT._)`{propertyName: ${t.propertyName}}`},A9={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:R9,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,I9.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,IT.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Fg.default=A9});var Ug=S(qg=>{"use strict";Object.defineProperty(qg,"__esModule",{value:!0});var Ll=Xt(),fr=X(),C9=Gr(),Fl=pe(),D9={message:"must NOT have additional properties",params:({params:t})=>(0,fr._)`{additionalProperty: ${t.additionalProperty}}`},O9={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:D9,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,Fl.alwaysValidSchema)(i,r))return;let u=(0,Ll.allSchemaProperties)(n.properties),l=(0,Ll.allSchemaProperties)(n.patternProperties);d(),t.ok((0,fr._)`${o} === ${C9.default.errors}`);function d(){e.forIn("key",s,y=>{!u.length&&!l.length?m(y):e.if(p(y),()=>m(y))})}function p(y){let v;if(u.length>8){let _=(0,Fl.schemaRefOrVal)(i,n.properties,"properties");v=(0,Ll.isOwnProperty)(e,_,y)}else u.length?v=(0,fr.or)(...u.map(_=>(0,fr._)`${y} === ${_}`)):v=fr.nil;return l.length&&(v=(0,fr.or)(v,...l.map(_=>(0,fr._)`${(0,Ll.usePattern)(t,_)}.test(${y})`))),(0,fr.not)(v)}function f(y){e.code((0,fr._)`delete ${s}[${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,Fl.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(h(y,v,!1),e.if((0,fr.not)(v),()=>{t.reset(),f(y)})):(h(y,v),a||e.if((0,fr.not)(v),()=>e.break()))}}function h(y,v,_){let b={keyword:"additionalProperties",dataProp:y,dataPropType:Fl.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,v)}}};qg.default=O9});var DT=S(Vg=>{"use strict";Object.defineProperty(Vg,"__esModule",{value:!0});var M9=Va(),AT=Xt(),Zg=pe(),CT=Ug(),z9={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&&CT.default.code(new M9.KeywordCxt(o,CT.default,"additionalProperties"));let i=(0,AT.allSchemaProperties)(r);for(let d of i)o.definedProperties.add(d);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Zg.mergeEvaluated.props(e,(0,Zg.toHash)(i),o.props));let a=i.filter(d=>!(0,Zg.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,AT.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)}}};Vg.default=z9});var jT=S(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});var OT=Xt(),ql=X(),MT=pe(),zT=pe(),j9={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,OT.allSchemaProperties)(r),c=a.filter(h=>(0,MT.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 ql.Name)&&(o.props=(0,zT.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 y in u)new RegExp(h).test(y)&&(0,MT.checkStrictMode)(o,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,ql._)`${(0,OT.usePattern)(t,h)}.test(${y})`,()=>{let v=c.includes(h);v||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:zT.Type.Str},l),o.opts.unevaluated&&d!==!0?e.assign((0,ql._)`${d}[${y}]`,!0):!v&&!o.allErrors&&e.if((0,ql.not)(l),()=>e.break())})})}}};Bg.default=j9});var NT=S(Hg=>{"use strict";Object.defineProperty(Hg,"__esModule",{value:!0});var N9=pe(),L9={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,N9.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"}};Hg.default=L9});var LT=S(Wg=>{"use strict";Object.defineProperty(Wg,"__esModule",{value:!0});var F9=Xt(),q9={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:F9.validateUnion,error:{message:"must match a schema in anyOf"}};Wg.default=q9});var FT=S(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});var Ul=X(),U9=pe(),Z9={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ul._)`{passingSchemas: ${t.passing}}`},V9={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Z9,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,U9.alwaysValidSchema)(s,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Ul._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ul._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Ul.Name)})})}}};Kg.default=V9});var qT=S(Jg=>{"use strict";Object.defineProperty(Jg,"__esModule",{value:!0});var B9=pe(),H9={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,B9.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Jg.default=H9});var VT=S(Gg=>{"use strict";Object.defineProperty(Gg,"__esModule",{value:!0});var Zl=X(),ZT=pe(),W9={message:({params:t})=>(0,Zl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Zl._)`{failingKeyword: ${t.ifClause}}`},K9={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:W9,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,ZT.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=UT(n,"then"),o=UT(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,Zl.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,Zl._)`${l}`):t.setParams({ifClause:l})}}}};function UT(t,e){let r=t.schema[e];return r!==void 0&&!(0,ZT.alwaysValidSchema)(t,r)}Gg.default=K9});var BT=S(Yg=>{"use strict";Object.defineProperty(Yg,"__esModule",{value:!0});var J9=pe(),G9={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,J9.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Yg.default=G9});var HT=S(Xg=>{"use strict";Object.defineProperty(Xg,"__esModule",{value:!0});var Y9=Og(),X9=ST(),Q9=Mg(),e2=xT(),t2=PT(),r2=ET(),n2=RT(),s2=Ug(),o2=DT(),i2=jT(),a2=NT(),c2=LT(),u2=FT(),l2=qT(),d2=VT(),p2=BT();function f2(t=!1){let e=[a2.default,c2.default,u2.default,l2.default,d2.default,p2.default,n2.default,s2.default,r2.default,o2.default,i2.default];return t?e.push(X9.default,e2.default):e.push(Y9.default,Q9.default),e.push(t2.default),e}Xg.default=f2});var WT=S(Qg=>{"use strict";Object.defineProperty(Qg,"__esModule",{value:!0});var Ue=X(),m2={message:({schemaCode:t})=>(0,Ue.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ue._)`{format: ${t}}`},h2={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:m2,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}]`),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 _(){return c.strictSchema===!1?Ue.nil:(0,Ue._)`${i} && !${v}`}function b(){let P=l.$async?(0,Ue._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,Ue._)`${v}(${n})`,x=(0,Ue._)`(typeof ${v} == "function" ? ${P} : ${v}.test(${n}))`;return(0,Ue._)`${v} && ${v} !== true && ${y} === ${e} && !${x}`}}function f(){let m=d.formats[o];if(!m){_();return}if(m===!0)return;let[h,y,v]=b(m);h===e&&t.pass(P());function _(){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 b(x){let N=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:N});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 ${v}(${n})`}return typeof y=="function"?(0,Ue._)`${v}(${n})`:(0,Ue._)`${v}.test(${n})`}}}};Qg.default=h2});var KT=S(ey=>{"use strict";Object.defineProperty(ey,"__esModule",{value:!0});var g2=WT(),y2=[g2.default];ey.default=y2});var JT=S(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.contentVocabulary=Ho.metadataVocabulary=void 0;Ho.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ho.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var YT=S(ty=>{"use strict";Object.defineProperty(ty,"__esModule",{value:!0});var v2=sT(),_2=vT(),b2=HT(),w2=KT(),GT=JT(),S2=[v2.default,_2.default,(0,b2.default)(),w2.default,GT.metadataVocabulary,GT.contentVocabulary];ty.default=S2});var QT=S(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});Vl.DiscrError=void 0;var XT;(function(t){t.Tag="tag",t.Mapping="mapping"})(XT||(Vl.DiscrError=XT={}))});var tE=S(ny=>{"use strict";Object.defineProperty(ny,"__esModule",{value:!0});var Wo=X(),ry=QT(),eE=Rl(),$2=Ba(),x2=pe(),P2={message:({params:{discrError:t,tagName:e}})=>t===ry.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Wo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},k2={keyword:"discriminator",type:"object",schemaType:"object",error:P2,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,Wo._)`${r}${(0,Wo.getProperty)(a)}`);e.if((0,Wo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:ry.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,Wo._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:ry.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,Wo.Name),m}function p(){var f;let m={},h=v(s),y=!0;for(let P=0;P<i.length;P++){let x=i[P];if(x?.$ref&&!(0,x2.schemaHasRulesButRef)(x,o.self.RULES)){let k=x.$ref;if(x=eE.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,k),x instanceof eE.SchemaEnv&&(x=x.schema),x===void 0)throw new $2.default(o.opts.uriResolver,o.baseId,k)}let N=(f=x?.properties)===null||f===void 0?void 0:f[a];if(typeof N!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||v(x)),_(N,P)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return m;function v({required:P}){return Array.isArray(P)&&P.includes(a)}function _(P,x){if(P.const)b(P.const,x);else if(P.enum)for(let N of P.enum)b(N,x);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(P,x){if(typeof P!="string"||P in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[P]=x}}}};ny.default=k2});var rE=S((Lte,T2)=>{T2.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 sE=S((De,sy)=>{"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 E2=Xk(),I2=YT(),R2=tE(),nE=rE(),A2=["/properties"],Bl="http://json-schema.org/draft-07/schema",Ko=class extends E2.default{_addVocabularies(){super._addVocabularies(),I2.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(R2.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(nE,A2):nE;this.addMetaSchema(e,Bl,!1),this.refs["http://json-schema.org/schema"]=Bl}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Bl)?Bl:void 0)}};De.Ajv=Ko;sy.exports=De=Ko;sy.exports.Ajv=Ko;Object.defineProperty(De,"__esModule",{value:!0});De.default=Ko;var C2=Va();Object.defineProperty(De,"KeywordCxt",{enumerable:!0,get:function(){return C2.KeywordCxt}});var Jo=X();Object.defineProperty(De,"_",{enumerable:!0,get:function(){return Jo._}});Object.defineProperty(De,"str",{enumerable:!0,get:function(){return Jo.str}});Object.defineProperty(De,"stringify",{enumerable:!0,get:function(){return Jo.stringify}});Object.defineProperty(De,"nil",{enumerable:!0,get:function(){return Jo.nil}});Object.defineProperty(De,"Name",{enumerable:!0,get:function(){return Jo.Name}});Object.defineProperty(De,"CodeGen",{enumerable:!0,get:function(){return Jo.CodeGen}});var D2=El();Object.defineProperty(De,"ValidationError",{enumerable:!0,get:function(){return D2.default}});var O2=Ba();Object.defineProperty(De,"MissingRefError",{enumerable:!0,get:function(){return O2.default}})});var oE=S(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.formatLimitDefinition=void 0;var M2=sE(),mr=X(),Tn=mr.operators,Hl={formatMaximum:{okStr:"<=",ok:Tn.LTE,fail:Tn.GT},formatMinimum:{okStr:">=",ok:Tn.GTE,fail:Tn.LT},formatExclusiveMaximum:{okStr:"<",ok:Tn.LT,fail:Tn.GTE},formatExclusiveMinimum:{okStr:">",ok:Tn.GT,fail:Tn.LTE}},z2={message:({keyword:t,schemaCode:e})=>(0,mr.str)`should be ${Hl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,mr._)`{comparison: ${Hl[t].okStr}, limit: ${e}}`};Go.formatLimitDefinition={keyword:Object.keys(Hl),type:"string",schemaType:"string",$data:!0,error:z2,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 M2.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,mr._)`${p}[${c.schemaCode}]`);t.fail$data((0,mr.or)((0,mr._)`typeof ${f} != "object"`,(0,mr._)`${f} instanceof RegExp`,(0,mr._)`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,mr._)`${i.code.formats}${(0,mr.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,mr._)`${p}.compare(${r}, ${n}) ${Hl[s].fail} 0`}},dependencies:["format"]};var j2=t=>(t.addKeyword(Go.formatLimitDefinition),t);Go.default=j2});var uE=S((sc,cE)=>{"use strict";Object.defineProperty(sc,"__esModule",{value:!0});var Yo=VP(),N2=oE(),oy=X(),iE=new oy.Name("fullFormats"),L2=new oy.Name("fastFormats"),iy=(t,e={keywords:!0})=>{if(Array.isArray(e))return aE(t,e,Yo.fullFormats,iE),t;let[r,n]=e.mode==="fast"?[Yo.fastFormats,L2]:[Yo.fullFormats,iE],s=e.formats||Yo.formatNames;return aE(t,s,r,n),e.keywords&&(0,N2.default)(t),t};iy.get=(t,e="full")=>{let n=(e==="fast"?Yo.fastFormats:Yo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function aE(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,oy._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}cE.exports=sc=iy;Object.defineProperty(sc,"__esModule",{value:!0});sc.default=iy});import{readFileSync as EK}from"fs";import{join as iv}from"path";import{fileURLToPath as IK}from"url";var Cs=class extends Error{providerId;constructor(e,r){super(`[${e}] ${r}`),this.providerId=e,this.name=this.constructor.name}},mc=class extends Cs{code="PROVIDER_NOT_FOUND";retryable=!1;constructor(e){super(e,`Provider not found: ${e}`)}},_e=class extends Cs{code="PROVIDER_UNAVAILABLE";retryable=!1;constructor(e,r){super(e,`Provider unavailable: ${r||"not installed or not running"}`)}};var Ds=class extends Cs{timeoutMs;code="PROVIDER_TIMEOUT";retryable=!0;constructor(e,r){super(e,`Timeout after ${r}ms`),this.timeoutMs=r}},dt=class extends Cs{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(e,r){super(e,`Execution error: ${r}`)}};var Tv={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"}},eA={ollama:{invocation:"http",roles:["participant","tool","worker"],supportsAutonomousExecution:!0,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 Vd(t){return t<3?"simple":t<8?"moderate":t<=20?"complex":"advanced"}function yc(t,e,r,n=t){let s=Tv[n]??Tv[t]??{},o=s.maxComplexity??"simple";return n==="ollama"&&r!==void 0&&(o=Vd(r)),{providerId:t,tier:s.tier??"tool",strengths:s.strengths??e.strengths,maxComplexity:o}}function Qr(t,e){let r=eA[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 vc={low:0,medium:.5,high:.7},tA={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 Ev(t,e){return e?.[t]??tA[t]??"low"}function _c(t,e,r=vc){return t>=r[e]}var bc=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 mc(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 yc(r.id,r.getCapabilities(),void 0,r.type)}getDescriptor(e){let r=this.get(e);return r.getDescriptor?.()??Qr(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??Ev(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 _c(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 g={};rt(g,{BRAND:()=>TA,DIRTY:()=>On,EMPTY_PATH:()=>oA,INVALID:()=>q,NEVER:()=>dC,OK:()=>nt,ParseStatus:()=>Ke,Schema:()=>Y,ZodAny:()=>rn,ZodArray:()=>Lr,ZodBigInt:()=>zn,ZodBoolean:()=>jn,ZodBranded:()=>pi,ZodCatch:()=>Kn,ZodDate:()=>Nn,ZodDefault:()=>Wn,ZodDiscriminatedUnion:()=>$c,ZodEffects:()=>Ut,ZodEnum:()=>Bn,ZodError:()=>bt,ZodFirstPartyTypeKind:()=>E,ZodFunction:()=>Pc,ZodIntersection:()=>Un,ZodIssueCode:()=>T,ZodLazy:()=>Zn,ZodLiteral:()=>Vn,ZodMap:()=>Vs,ZodNaN:()=>Hs,ZodNativeEnum:()=>Hn,ZodNever:()=>rr,ZodNull:()=>Fn,ZodNullable:()=>_r,ZodNumber:()=>Mn,ZodObject:()=>wt,ZodOptional:()=>Ft,ZodParsedType:()=>R,ZodPipeline:()=>fi,ZodPromise:()=>nn,ZodReadonly:()=>Jn,ZodRecord:()=>xc,ZodSchema:()=>Y,ZodSet:()=>Bs,ZodString:()=>tn,ZodSymbol:()=>Us,ZodTransformer:()=>Ut,ZodTuple:()=>vr,ZodType:()=>Y,ZodUndefined:()=>Ln,ZodUnion:()=>qn,ZodUnknown:()=>Nr,ZodVoid:()=>Zs,addIssueToContext:()=>I,any:()=>zA,array:()=>FA,bigint:()=>AA,boolean:()=>Lv,coerce:()=>lC,custom:()=>zv,date:()=>CA,datetimeRegex:()=>Ov,defaultErrorMap:()=>zr,discriminatedUnion:()=>VA,effect:()=>rC,enum:()=>QA,function:()=>GA,getErrorMap:()=>Ls,getParsedType:()=>yr,instanceof:()=>IA,intersection:()=>BA,isAborted:()=>wc,isAsync:()=>Fs,isDirty:()=>Sc,isValid:()=>en,late:()=>EA,lazy:()=>YA,literal:()=>XA,makeIssue:()=>di,map:()=>KA,nan:()=>RA,nativeEnum:()=>eC,never:()=>NA,null:()=>MA,nullable:()=>sC,number:()=>Nv,object:()=>qA,objectUtil:()=>Bd,oboolean:()=>uC,onumber:()=>cC,optional:()=>nC,ostring:()=>aC,pipeline:()=>iC,preprocess:()=>oC,promise:()=>tC,quotelessJson:()=>rA,record:()=>WA,set:()=>JA,setErrorMap:()=>sA,strictObject:()=>UA,string:()=>jv,symbol:()=>DA,transformer:()=>rC,tuple:()=>HA,undefined:()=>OA,union:()=>ZA,unknown:()=>jA,util:()=>se,void:()=>LA});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 Bd;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Bd||(Bd={}));var R=se.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yr=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 T=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"]),rA=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),bt=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()}};bt.create=t=>new bt(t);var nA=(t,e)=>{let r;switch(t.code){case T.invalid_type:t.received===R.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case T.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,se.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:r=`Unrecognized key(s) in object: ${se.joinValues(t.keys,", ")}`;break;case T.invalid_union:r="Invalid input";break;case T.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${se.joinValues(t.options)}`;break;case T.invalid_enum_value:r=`Invalid enum value. Expected ${se.joinValues(t.options)}, received '${t.received}'`;break;case T.invalid_arguments:r="Invalid function arguments";break;case T.invalid_return_type:r="Invalid function return type";break;case T.invalid_date:r="Invalid date";break;case T.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 T.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 T.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 T.custom:r="Invalid input";break;case T.invalid_intersection_types:r="Intersection results could not be merged";break;case T.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case T.not_finite:r="Number must be finite";break;default:r=e.defaultError,se.assertNever(t)}return{message:r}},zr=nA;var Iv=zr;function sA(t){Iv=t}function Ls(){return Iv}var di=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}},oA=[];function I(t,e){let r=Ls(),n=di({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===zr?void 0:zr].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 q;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 q;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}}},q=Object.freeze({status:"aborted"}),On=t=>({status:"dirty",value:t}),nt=t=>({status:"valid",value:t}),wc=t=>t.status==="aborted",Sc=t=>t.status==="dirty",en=t=>t.status==="valid",Fs=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 qt=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}},Rv=(t,e)=>{if(en(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 bt(t.common.issues);return this._error=r,this._error}}};function H(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 yr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:yr(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:yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Fs(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:yr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return Rv(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return en(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=>en(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:yr(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(Fs(s)?s:Promise.resolve(s));return Rv(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:T.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 Ut({schema:this,typeName:E.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 Ft.create(this,this._def)}nullable(){return _r.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Lr.create(this)}promise(){return nn.create(this,this._def)}or(e){return qn.create([this,e],this._def)}and(e){return Un.create(this,e,this._def)}transform(e){return new Ut({...H(this._def),schema:this,typeName:E.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Wn({...H(this._def),innerType:this,defaultValue:r,typeName:E.ZodDefault})}brand(){return new pi({typeName:E.ZodBranded,type:this,...H(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Kn({...H(this._def),innerType:this,catchValue:r,typeName:E.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return fi.create(this,e)}readonly(){return Jn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},iA=/^c[^\s-]{8,}$/i,aA=/^[0-9a-z]+$/,cA=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uA=/^[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,lA=/^[a-z0-9_-]{21}$/i,dA=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pA=/^[-+]?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)?)??$/,fA=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,mA="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Hd,hA=/^(?:(?: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])$/,gA=/^(?:(?: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])$/,yA=/^(([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]))$/,vA=/^(([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])$/,_A=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,bA=/^([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])))",wA=new RegExp(`^${Cv}$`);function Dv(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 SA(t){return new RegExp(`^${Dv(t)}$`)}function Ov(t){let e=`${Cv}T${Dv(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 $A(t,e){return!!((e==="v4"||!e)&&hA.test(t)||(e==="v6"||!e)&&yA.test(t))}function xA(t,e){if(!dA.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 PA(t,e){return!!((e==="v4"||!e)&&gA.test(t)||(e==="v6"||!e)&&vA.test(t))}var tn=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:T.invalid_type,expected:R.string,received:o.parsedType}),q}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:T.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:T.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:T.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&I(s,{code:T.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")fA.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"email",code:T.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")Hd||(Hd=new RegExp(mA,"u")),Hd.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"emoji",code:T.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")uA.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"uuid",code:T.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")lA.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"nanoid",code:T.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")iA.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"cuid",code:T.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")aA.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"cuid2",code:T.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")cA.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"ulid",code:T.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:T.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:T.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:T.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:T.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:T.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?Ov(o).test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{code:T.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?wA.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{code:T.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?SA(o).test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{code:T.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?pA.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"duration",code:T.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?$A(e.data,o.version)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"ip",code:T.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?xA(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"jwt",code:T.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?PA(e.data,o.version)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"cidr",code:T.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?_A.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"base64",code:T.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?bA.test(e.data)||(s=this._getOrReturnCtx(e,s),I(s,{validation:"base64url",code:T.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:T.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}};tn.create=t=>new tn({checks:[],typeName:E.ZodString,coerce:t?.coerce??!1,...H(t)});function kA(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 Mn=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:T.invalid_type,expected:R.number,received:o.parsedType}),q}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:T.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:T.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:T.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?kA(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),I(n,{code:T.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:T.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)}};Mn.create=t=>new Mn({checks:[],typeName:E.ZodNumber,coerce:t?.coerce||!1,...H(t)});var zn=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:T.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:T.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:T.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:T.invalid_type,expected:R.bigint,received:r.parsedType}),q}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}};zn.create=t=>new zn({checks:[],typeName:E.ZodBigInt,coerce:t?.coerce??!1,...H(t)});var jn=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:T.invalid_type,expected:R.boolean,received:n.parsedType}),q}return nt(e.data)}};jn.create=t=>new jn({typeName:E.ZodBoolean,coerce:t?.coerce||!1,...H(t)});var Nn=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:T.invalid_type,expected:R.date,received:o.parsedType}),q}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return I(o,{code:T.invalid_date}),q}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:T.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:T.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}};Nn.create=t=>new Nn({checks:[],coerce:t?.coerce||!1,typeName:E.ZodDate,...H(t)});var Us=class extends Y{_parse(e){if(this._getType(e)!==R.symbol){let n=this._getOrReturnCtx(e);return I(n,{code:T.invalid_type,expected:R.symbol,received:n.parsedType}),q}return nt(e.data)}};Us.create=t=>new Us({typeName:E.ZodSymbol,...H(t)});var Ln=class extends Y{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return I(n,{code:T.invalid_type,expected:R.undefined,received:n.parsedType}),q}return nt(e.data)}};Ln.create=t=>new Ln({typeName:E.ZodUndefined,...H(t)});var Fn=class extends Y{_parse(e){if(this._getType(e)!==R.null){let n=this._getOrReturnCtx(e);return I(n,{code:T.invalid_type,expected:R.null,received:n.parsedType}),q}return nt(e.data)}};Fn.create=t=>new Fn({typeName:E.ZodNull,...H(t)});var rn=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return nt(e.data)}};rn.create=t=>new rn({typeName:E.ZodAny,...H(t)});var Nr=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return nt(e.data)}};Nr.create=t=>new Nr({typeName:E.ZodUnknown,...H(t)});var rr=class extends Y{_parse(e){let r=this._getOrReturnCtx(e);return I(r,{code:T.invalid_type,expected:R.never,received:r.parsedType}),q}};rr.create=t=>new rr({typeName:E.ZodNever,...H(t)});var Zs=class extends Y{_parse(e){if(this._getType(e)!==R.undefined){let n=this._getOrReturnCtx(e);return I(n,{code:T.invalid_type,expected:R.void,received:n.parsedType}),q}return nt(e.data)}};Zs.create=t=>new Zs({typeName:E.ZodVoid,...H(t)});var Lr=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:T.invalid_type,expected:R.array,received:r.parsedType}),q;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?T.too_big:T.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:T.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:T.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 qt(r,i,r.path,a)))).then(i=>Ke.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new qt(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)}};Lr.create=(t,e)=>new Lr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:E.ZodArray,...H(e)});function qs(t){if(t instanceof wt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ft.create(qs(n))}return new wt({...t._def,shape:()=>e})}else return t instanceof Lr?new Lr({...t._def,type:qs(t.element)}):t instanceof Ft?Ft.create(qs(t.unwrap())):t instanceof _r?_r.create(qs(t.unwrap())):t instanceof vr?vr.create(t.items.map(e=>qs(e))):t}var wt=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:T.invalid_type,expected:R.object,received:u.parsedType}),q}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof rr&&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 qt(s,d,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof rr){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:T.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 qt(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:E.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 qs(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 Ft;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return Mv(se.objectKeys(this.shape))}};wt.create=(t,e)=>new wt({shape:()=>t,unknownKeys:"strip",catchall:rr.create(),typeName:E.ZodObject,...H(e)});wt.strictCreate=(t,e)=>new wt({shape:()=>t,unknownKeys:"strict",catchall:rr.create(),typeName:E.ZodObject,...H(e)});wt.lazycreate=(t,e)=>new wt({shape:t,unknownKeys:"strip",catchall:rr.create(),typeName:E.ZodObject,...H(e)});var qn=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 bt(a.ctx.common.issues));return I(r,{code:T.invalid_union,unionErrors:i}),q}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 bt(c));return I(r,{code:T.invalid_union,unionErrors:a}),q}}get options(){return this._def.options}};qn.create=(t,e)=>new qn({options:t,typeName:E.ZodUnion,...H(e)});var jr=t=>t instanceof Zn?jr(t.schema):t instanceof Ut?jr(t.innerType()):t instanceof Vn?[t.value]:t instanceof Bn?t.options:t instanceof Hn?se.objectValues(t.enum):t instanceof Wn?jr(t._def.innerType):t instanceof Ln?[void 0]:t instanceof Fn?[null]:t instanceof Ft?[void 0,...jr(t.unwrap())]:t instanceof _r?[null,...jr(t.unwrap())]:t instanceof pi||t instanceof Jn?jr(t.unwrap()):t instanceof Kn?jr(t._def.innerType):[],$c=class t extends Y{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==R.object)return I(r,{code:T.invalid_type,expected:R.object,received:r.parsedType}),q;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:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),q)}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=jr(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:E.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...H(n)})}};function Wd(t,e){let r=yr(t),n=yr(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=Wd(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=Wd(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 Un=class extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(wc(o)||wc(i))return q;let a=Wd(o.value,i.value);return a.valid?((Sc(o)||Sc(i))&&r.dirty(),{status:r.value,value:a.data}):(I(n,{code:T.invalid_intersection_types}),q)};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}))}};Un.create=(t,e,r)=>new Un({left:t,right:e,typeName:E.ZodIntersection,...H(r)});var vr=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.array)return I(n,{code:T.invalid_type,expected:R.array,received:n.parsedType}),q;if(n.data.length<this._def.items.length)return I(n,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),q;!this._def.rest&&n.data.length>this._def.items.length&&(I(n,{code:T.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 qt(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})}};vr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new vr({items:t,typeName:E.ZodTuple,rest:null,...H(e)})};var xc=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:T.invalid_type,expected:R.object,received:n.parsedType}),q;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new qt(n,a,n.path,a)),value:i._parse(new qt(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:E.ZodRecord,...H(n)}):new t({keyType:tn.create(),valueType:e,typeName:E.ZodRecord,...H(r)})}},Vs=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:T.invalid_type,expected:R.map,received:n.parsedType}),q;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new qt(n,a,n.path,[u,"key"])),value:o._parse(new qt(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 q;(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 q;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};Vs.create=(t,e,r)=>new Vs({valueType:e,keyType:t,typeName:E.ZodMap,...H(r)});var Bs=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==R.set)return I(n,{code:T.invalid_type,expected:R.set,received:n.parsedType}),q;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(I(n,{code:T.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:T.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 q;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 qt(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)}};Bs.create=(t,e)=>new Bs({valueType:t,minSize:null,maxSize:null,typeName:E.ZodSet,...H(e)});var Pc=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:T.invalid_type,expected:R.function,received:r.parsedType}),q;function n(a,c){return di({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ls(),zr].filter(u=>!!u),issueData:{code:T.invalid_arguments,argumentsError:c}})}function s(a,c){return di({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ls(),zr].filter(u=>!!u),issueData:{code:T.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof nn){let a=this;return nt(async function(...c){let u=new bt([]),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 nt(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new bt([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,o);if(!d.success)throw new bt([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:vr.create(e).rest(Nr.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||vr.create([]).rest(Nr.create()),returns:r||Nr.create(),typeName:E.ZodFunction,...H(n)})}},Zn=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})}};Zn.create=(t,e)=>new Zn({getter:t,typeName:E.ZodLazy,...H(e)});var Vn=class extends Y{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return I(r,{received:r.data,code:T.invalid_literal,expected:this._def.value}),q}return{status:"valid",value:e.data}}get value(){return this._def.value}};Vn.create=(t,e)=>new Vn({value:t,typeName:E.ZodLiteral,...H(e)});function Mv(t,e){return new Bn({values:t,typeName:E.ZodEnum,...H(e)})}var Bn=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:T.invalid_type}),q}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:T.invalid_enum_value,options:n}),q}return nt(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})}};Bn.create=Mv;var Hn=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:T.invalid_type}),q}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:T.invalid_enum_value,options:s}),q}return nt(e.data)}get enum(){return this._def.values}};Hn.create=(t,e)=>new Hn({values:t,typeName:E.ZodNativeEnum,...H(e)});var nn=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:T.invalid_type,expected:R.promise,received:r.parsedType}),q;let n=r.parsedType===R.promise?r.data:Promise.resolve(r.data);return nt(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};nn.create=(t,e)=>new nn({type:t,typeName:E.ZodPromise,...H(e)});var Ut=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===E.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 q;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?q:c.status==="dirty"?On(c.value):r.value==="dirty"?On(c.value):c});{if(r.value==="aborted")return q;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?q:a.status==="dirty"?On(a.value):r.value==="dirty"?On(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"?q:(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"?q:(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(!en(i))return q;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=>en(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):q);se.assertNever(s)}};Ut.create=(t,e,r)=>new Ut({schema:t,typeName:E.ZodEffects,effect:e,...H(r)});Ut.createWithPreprocess=(t,e,r)=>new Ut({schema:e,effect:{type:"preprocess",transform:t},typeName:E.ZodEffects,...H(r)});var Ft=class extends Y{_parse(e){return this._getType(e)===R.undefined?nt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ft.create=(t,e)=>new Ft({innerType:t,typeName:E.ZodOptional,...H(e)});var _r=class extends Y{_parse(e){return this._getType(e)===R.null?nt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_r.create=(t,e)=>new _r({innerType:t,typeName:E.ZodNullable,...H(e)});var Wn=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}};Wn.create=(t,e)=>new Wn({innerType:t,typeName:E.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});var Kn=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 Fs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new bt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new bt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Kn.create=(t,e)=>new Kn({innerType:t,typeName:E.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});var Hs=class extends Y{_parse(e){if(this._getType(e)!==R.nan){let n=this._getOrReturnCtx(e);return I(n,{code:T.invalid_type,expected:R.nan,received:n.parsedType}),q}return{status:"valid",value:e.data}}};Hs.create=t=>new Hs({typeName:E.ZodNaN,...H(t)});var TA=Symbol("zod_brand"),pi=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}},fi=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"?q:o.status==="dirty"?(r.dirty(),On(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"?q: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:E.ZodPipeline})}},Jn=class extends Y{_parse(e){let r=this._def.innerType._parse(e),n=s=>(en(s)&&(s.value=Object.freeze(s.value)),s);return Fs(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Jn.create=(t,e)=>new Jn({innerType:t,typeName:E.ZodReadonly,...H(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 zv(t,e={},r){return t?rn.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})}}):rn.create()}var EA={object:wt.lazycreate},E;(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"})(E||(E={}));var IA=(t,e={message:`Input not instance of ${t.name}`})=>zv(r=>r instanceof t,e),jv=tn.create,Nv=Mn.create,RA=Hs.create,AA=zn.create,Lv=jn.create,CA=Nn.create,DA=Us.create,OA=Ln.create,MA=Fn.create,zA=rn.create,jA=Nr.create,NA=rr.create,LA=Zs.create,FA=Lr.create,qA=wt.create,UA=wt.strictCreate,ZA=qn.create,VA=$c.create,BA=Un.create,HA=vr.create,WA=xc.create,KA=Vs.create,JA=Bs.create,GA=Pc.create,YA=Zn.create,XA=Vn.create,QA=Bn.create,eC=Hn.create,tC=nn.create,rC=Ut.create,nC=Ft.create,sC=_r.create,oC=Ut.createWithPreprocess,iC=fi.create,aC=()=>jv().optional(),cC=()=>Nv().optional(),uC=()=>Lv().optional(),lC={string:(t=>tn.create({...t,coerce:!0})),number:(t=>Mn.create({...t,coerce:!0})),boolean:(t=>jn.create({...t,coerce:!0})),bigint:(t=>zn.create({...t,coerce:!0})),date:(t=>Nn.create({...t,coerce:!0}))};var dC=q;Mr();var pC=g.enum(["read-only","workspace-write","full-auto"]),fC=pC.default("read-only"),mC=g.object({id:g.string(),type:g.string(),enabled:g.boolean().default(!0),executionPolicy:fC,config:g.record(g.unknown()).default({})}),hC=g.enum(["default-only","auto"]).default("default-only"),gC=g.object({selectionPolicy:hC,locale:g.string().optional(),providers:g.array(mC).min(1,"At least one provider required")});function Ot(t){switch(t){case"ollama":case"gemini-cli":case"codex-cli":case"claude-cli":return"workspace-write";default:return"read-only"}}function Ws(t){return t==="workspace-write"||t==="full-auto"}function yC(t){return hc.includes(t)}function vC(t){if(t!==void 0)return yC(t)?t:(console.warn(`[config] unknown locale '${t}', falling back to ${Cn}`),Cn)}function Fv(t){let e=gC.parse(t);return{selectionPolicy:e.selectionPolicy,locale:vC(e.locale),providers:e.providers,enabledProviders:e.providers.filter(r=>r.enabled)}}import{existsSync as qv,mkdirSync as _C}from"fs";import{homedir as bC}from"os";import{dirname as wC,join as Uv}from"path";var Zv="providers.config.json";function mi(){let t=process.env.AGESTRA_CONFIG_PATH;if(t&&t.length>0)return t;let e=Uv(bC(),".agestra",Zv);if(qv(e))return e;let r=process.env.CLAUDE_PLUGIN_ROOT,n=r&&r.length>0?Uv(r,Zv):void 0;return n&&qv(n)?n:e}function Vv(t){_C(wC(t),{recursive:!0})}sn();Ec();Ks();js();import{mkdirSync as f_,readFileSync as br,readdirSync as m_,existsSync as zt}from"fs";import{join as Le}from"path";import{spawn as aD}from"child_process";import{randomUUID as cD}from"crypto";sn();np();yi();import{readFileSync as o_}from"fs";import{join as Ac}from"path";function Cc(t){Promise.resolve().then(()=>(s_(),n_)).then(async({resolveCliConfig:e})=>{let r;try{r=JSON.parse(o_(Ac(t,"job.json"),"utf-8"))}catch{return}let n=e(r);if(!n){Ve(t,{state:"missing_cli",completedAt:new Date().toISOString()}),ge(Ac(t,"error.txt"),`No CLI mapping for provider: ${r.provider}`);return}let{command:s,buildArgs:o}=n,i=o_(Ac(t,"prompt.txt"),"utf-8"),a=o(i);Ve(t,{state:"running",startedAt:new Date().toISOString()}),await Rc({jobDir:t,command:s,args:a,cwd:r.cwd||void 0,timeoutMs:r.timeout,recordPid:!0})}).catch(()=>{try{Ve(t,{state:"error",completedAt:new Date().toISOString()}),ge(Ac(t,"error.txt"),"Failed to load job worker module")}catch{}})}import{existsSync as i_,readFileSync as a_,readdirSync as c_,unlinkSync as QC,rmdirSync as eD}from"fs";import{join as Dc}from"path";var tD=["completed","error","timed_out","cancelled","missing_cli"];function u_(t){let{jobsDir:e,maxJobs:r,maxAgeDays:n,statusCache:s,clearDeferredSaveTimer:o}=t;if(!i_(e))return 0;let i;try{i=c_(e,{withFileTypes:!0}).filter(f=>f.isDirectory())}catch{return 0}let a=[];for(let f of i)try{let m=Dc(e,f.name,"status.json"),h=Dc(e,f.name,"job.json");if(!i_(m))continue;let y=JSON.parse(a_(m,"utf-8")),v=null;try{v=JSON.parse(a_(h,"utf-8"))}catch{}a.push({name:f.name,status:y,descriptor:v})}catch{}let c=a.filter(f=>tD.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=Dc(e,f.name);try{let _=c_(v);for(let b of _)QC(Dc(v,b));eD(v),s.delete(f.name),o(f.name),u++}catch{}}return u}sn();Ec();Ks();import{existsSync as rD,readFileSync as sp,readdirSync as nD}from"fs";import{join as op}from"path";function l_(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function d_(t,e){let r=op(t,e,"job.json");try{let s=JSON.parse(sp(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 p_(t){let{jobsDir:e,statusCache:r}=t,n=0,s;try{s=nD(e)}catch{return 0}for(let o of s){if(!Fr(o))continue;let i=op(e,o,"status.json");if(!rD(i))continue;let a;try{a=JSON.parse(sp(i,"utf-8"))}catch{continue}if(a.state!=="running"||a.pid!==void 0&&l_(a.pid))continue;let c=`${i}.lock`;try{let u=Gn(c,()=>{let l=JSON.parse(sp(i,"utf-8"));if(l.state!=="running"||l.pid!==void 0&&l_(l.pid))return null;let d={...l,state:"error",completedAt:new Date().toISOString()};return Ze(i,d),d});if(!u)continue;ge(op(e,o,"error.txt"),"orphaned (worker process died before completion)"),r.set(o,u),n++}catch{}}return n}yi();Mr();var uD=5e3,ip=["completed","error","timed_out","cancelled","missing_cli"],Oc=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,dv),f_(this.jobsDir,{recursive:!0}),this.maxJobs=r?.maxJobs??100,this.maxAgeDays=r?.maxAgeDays??7,this.completionHandler=r?.completionHandler,this.submitCount=this.countExistingJobs()}countExistingJobs(){if(!zt(this.jobsDir))return 0;try{return m_(this.jobsDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).length}catch{return 0}}reconcileOrphans(){return p_({jobsDir:this.jobsDir,statusCache:this.statusCache})}submit(e){let r=`${e.provider}-${Date.now()}-${cD().slice(0,6)}`,n=Le(this.jobsDir,r);f_(n,{recursive:!0});let s=e.timeout??6e5,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+uD);a.unref?.(),this.deferredSaveTimers.set(r,a)}return this.submitCount++,this.submitCount%10===0&&this.cleanup(),r}getStatus(e){if(!Fr(e))return null;let r=this.statusCache.get(e);if(r&&ip.includes(r.state)&&((r.savedDocumentId?!0:r.saveError!==void 0)||!this.completionHandler))return r;let n=Le(this.jobsDir,e,"status.json");if(!zt(n))return null;let s=JSON.parse(br(n,"utf-8"));if(s.state==="queued"){let o=d_(this.jobsDir,e);if(o!==null&&Date.now()-o>6e4){let a=`${n}.lock`;try{let c=Gn(a,()=>{let u=JSON.parse(br(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),ip.includes(s.state)&&!s.savedDocumentId&&!s.saveError&&this.completionHandler&&this.maybeTriggerCompletionSave(e).catch(()=>{}),s}getResult(e){if(!Fr(e))return null;let r=this.getStatus(e);if(!r)return null;let n=Le(this.jobsDir,e),s={id:e,state:r.state,provider:r.provider,startedAt:r.startedAt,completedAt:r.completedAt,exitCode:r.exitCode,savedDocumentId:r.savedDocumentId,saveError:r.saveError,activity:r.activity},o=Le(n,"output.txt");zt(o)&&(s.output=br(o,"utf-8"));let i=Le(n,"error.txt");return zt(i)&&(s.error=br(i,"utf-8")),s}async getResultAwaited(e){return Fr(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(!zt(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||!Fr(e))return;let r=Le(this.jobsDir,e);if(!zt(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||!Fr(e))return;let r=Le(this.jobsDir,e),n=Le(r,"status.json"),s=Le(r,"job.json");if(!zt(n)||!zt(s))return;let o=JSON.parse(br(n,"utf-8"));if(!ip.includes(o.state)||o.savedDocumentId||o.saveError)return;let i=JSON.parse(br(s,"utf-8"));if(!i.saveAsDocument)return;let a={id:e,state:o.state,provider:o.provider,startedAt:o.startedAt,completedAt:o.completedAt,exitCode:o.exitCode,activity:o.activity},c=Le(r,"output.txt");zt(c)&&(a.output=br(c,"utf-8"));let u=Le(r,"error.txt");zt(u)&&(a.error=br(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};Ve(r,d),this.statusCache.set(e,{...o,...d})}else{let d={saveError:`skipped (state=${o.state})`};Ve(r,d),this.statusCache.set(e,{...o,...d})}}catch(l){let p={saveError:l instanceof Error?l.message:String(l)};try{Ve(r,p),this.statusCache.set(e,{...o,...p})}catch{}}}listJobs(){if(!zt(this.jobsDir))return[];let e;try{e=m_(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");zt(s)&&r.push(JSON.parse(br(s,"utf-8")))}catch{}return r}cancel(e){if(!Fr(e))return!1;let r=this.getStatus(e);if(!r||r.state!=="queued"&&r.state!=="running")return!1;r.pid&&zs(r.pid);let n=Le(this.jobsDir,e),s=Le(n,"status.json"),o=`${s}.lock`;try{let i=Gn(o,()=>{let a=JSON.parse(br(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 u_({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(zt(r)){let n=aD(process.execPath,[r,e],{detached:!0,stdio:"ignore",cwd:this.workspaceDir}),s=typeof n.pid=="number"&&n.pid>0;if(s)try{Ve(e,{pid:n.pid})}catch{}n.on("error",o=>{if(s)return;o.code==="ENOENT"?Cc(e):Cc(e)}),n.unref()}else Cc(e)}};sn();Mr();import{mkdirSync as lD,readdirSync as h_,readFileSync as dD,unlinkSync as pD}from"fs";import{join as vi}from"path";function g_(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 fD(t){return typeof t=="object"&&t!==null&&"traceId"in t&&"action"in t&&!("type"in t&&t.type==="quality_update")}function mD(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="quality_update"}var Mc=class{tracesDir;writer;constructor(e,r){this.tracesDir=vi(e,pv),lD(this.tracesDir,{recursive:!0}),this.writer=new kc(r)}write(e){let r={...e,timestamp:e.timestamp??new Date().toISOString()},n=g_(new Date(r.timestamp)),s=vi(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=dD(i,"utf-8").split(`
|
|
21
|
+
`).filter(Boolean);for(let c of a)try{let u=JSON.parse(c);mD(u)?s.push(u):fD(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=g_(s),a=vi(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=h_(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&&(pD(vi(this.tracesDir,o)),n++)}return n}listFiles(e){let r;try{r=h_(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=>vi(this.tracesDir,n))}};var hD=/[;|&`$(){}!><\n\r\\]/,zc=new Set(["ls","cat","head","tail","wc","diff","find","grep","sort","uniq"]),gD=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 y_(t){if(hD.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(!zc.has(r))return{valid:!1,error:`Command '${r}' is not allowed. Allowed: ${[...zc].join(", ")}`};for(let n of e){let s=n.replace(/^.*\//,"");if(gD.has(s))return{valid:!1,error:`Command contains blocked token '${s}'`}}return{valid:!0}}Mr();var v_=[{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"}],__=[/\$[A-Z_]+/,/\$\{[A-Z_]+\}/,/process\.env\.\w+/,/<YOUR_[A-Z_]+>/];function b_(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 v_){let i=o.regex.exec(s);if(!i)continue;let a=i[0];if(!__.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 Js(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 v_){let o=new RegExp(s.regex.source,s.regex.flags.includes("g")?s.regex.flags:s.regex.flags+"g");n=n.replace(o,i=>__.some(a=>a.test(i))?i:xv)}e[r]=n}return e.join(`
|
|
25
|
+
`)}Mr();import{execFileSync as yD}from"child_process";import{existsSync as w_,rmSync as vD,mkdirSync as _D}from"fs";import{join as S_}from"path";var jc=class{baseDir;worktrees=new Map;worktreeBaseDir;constructor(e){this.baseDir=e,this.worktreeBaseDir=S_(e,fv)}create(e){let r=e.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,60),n=`agestra-worker/${r}`,s=S_(this.worktreeBaseDir,r);_D(this.worktreeBaseDir,{recursive:!0}),w_(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&&(w_(e)&&vD(e,{recursive:!0,force:!0}),this.gitSafe(["worktree","prune"]))}git(e){return yD("git",e,{cwd:this.baseDir,encoding:"utf-8",stdio:"pipe",timeout:3e4}).trim()}gitSafe(e){try{return this.git(e)}catch{return null}}};var bD=["npm","node","git","tsc"];function $_(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:[...bD]},timeout_minutes:t.timeoutMinutes??10}}function x_(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 Fe;(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"})(Fe||(Fe={}));var Nc=10,up=2e4;import{spawn as kD}from"child_process";import{writeFileSync as dp,mkdirSync as TD,readFileSync as E_,existsSync as I_}from"fs";import{isAbsolute as R_,join as _i,resolve as A_}from"path";import{randomBytes as ED}from"crypto";import{execFileSync as ID}from"child_process";Mr();li();js();Ks();Ks();import{readFileSync as P_}from"fs";var lp=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 wD(t,e,r){let n=k_(t,e,r);return{command:"codex",args:["exec","--skip-git-repo-check","--full-auto","--ephemeral","-C",e,"-"],stdin:n}}function SD(t,e,r){return{command:"gemini",args:["--approval-mode","yolo","-p",k_(t,e,r)]}}function k_(t,e,r){let n=P_(t,"utf-8"),s=$D(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 T_(){let t=new lp;return t.register("codex",wD),t.register("gemini",SD),t}function $D(t,e){if(!t||t.length===0)return"";let r=t.filter(s=>!tp(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,Nc))try{let o=P_(s,"utf-8"),i=o.length>up?`${o.slice(0,up)}
|
|
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>Nc&&(n.push(`...[${r.length-Nc} additional read-only files omitted]`),n.push("")),n.join(`
|
|
29
|
+
`)}var bi=class t{baseDir;workers=new Map;workersBaseDir;worktreeManager;providerPolicies;cliBuilderRegistry;constructor(e,r={}){this.baseDir=e,this.workersBaseDir=_i(e,vv),this.worktreeManager=new jc(e),this.providerPolicies=r.providerPolicies??new Map,this.cliBuilderRegistry=r.cliBuilderRegistry??T_()}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===Fe.RUNNING||n===Fe.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=b_(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=ED(3).toString("hex"),c=`${e.provider}-${Date.now()}-${a}`,u=_i(this.workersBaseDir,c);TD(u,{recursive:!0});let l=$_({taskDescription:e.taskDescription,workingDir:r,filesToRead:n,filesToModify:s,constraints:e.constraints,successCriteria:e.successCriteria,timeoutMinutes:e.timeoutMinutes}),d=x_(l);if(!d.valid)throw new Error(`Invalid task manifest: ${d.errors.join(", ")}`);let p=_i(u,"task-manifest.json");dp(p,JSON.stringify(l,null,2),"utf-8");let f=e.useWorktree!==!1?this.tryCreateWorktree(c):null,m=_i(u,"stdout.log"),h=_i(u,"stderr.log"),y=f?.path??r,v=this.cliBuilderRegistry.build(e.provider,p,y,n),_=Dn(v.command,v.args),b=kD(_.command,_.args,{cwd:y,env:t.buildWorkerEnv(),detached:!0,stdio:[v.stdin?"pipe":"ignore","pipe","pipe"]}),P=[],x=[];b.stdout?.on("data",O=>P.push(O)),b.stderr?.on("data",O=>x.push(O)),v.stdin!==void 0&&b.stdin?.end(v.stdin),b.unref();let N={workerId:c,provider:e.provider,state:Fe.RUNNING,pid:b.pid??null,worktreePath:f?.path??null,worktreeBranch:f?.branch??null,startedAt:Date.now(),retryCount:0,exitCode:null,error:null},k={info:N,process:b,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===Fe.RUNNING&&k.process===b){k.info.state=Fe.TIMEOUT,k.info.error=`Worker timed out after ${e.timeoutMinutes} minutes`;let F=b.pid;F&&zs(F)}},O);L.unref(),k.timeoutTimer=L}return b.on("close",O=>{k.timeoutTimer&&(clearTimeout(k.timeoutTimer),k.timeoutTimer=void 0),k.info.exitCode=O;try{dp(m,Buffer.concat(P).toString("utf-8")),dp(h,Buffer.concat(x).toString("utf-8"))}catch{}k.info.state===Fe.CANCELLING?k.info.state=Fe.CANCELLED:O===0?k.info.state=Fe.COLLECTING:(k.info.state=Fe.FAILED,k.info.error=`Process exited with code ${O}`)}),N}getStatus(e){let r=this.workers.get(e);if(!r)return;let n=Math.floor((Date.now()-r.info.startedAt)/1e3),s="";try{I_(r.outputPath)&&(s=E_(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",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
|
|
33
|
-
`).map(n=>n.trim().slice(3)).filter(Boolean):[]}static buildWorkerEnv(){let e={};for(let r of
|
|
31
|
+
`))}catch{}return{workerId:r.info.workerId,provider:r.info.provider,state:r.info.state,elapsedSeconds:n,pid:r.info.pid,outputTail:Js(s),worktreeBranch:r.info.worktreeBranch,retryCount:r.info.retryCount}}collect(e){let r=this.workers.get(e);if(!r)return;let n="";try{I_(r.outputPath)&&(n=E_(r.outputPath,"utf-8"))}catch{}n=Js(n);let s=null;try{r.info.worktreePath&&(s=this.reviewChanges(r.info.workerId))}catch{s=null}return r.info.state===Fe.COLLECTING&&(r.info.state=Fe.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!==Fe.RUNNING)return;r.info.state=Fe.CANCELLING;let n=r.process.pid;if(n)zs(n);else try{r.process.kill("SIGTERM")}catch{}setTimeout(()=>{if(r.info.state===Fe.CANCELLING){try{r.process?.kill("SIGKILL")}catch{}r.info.state=Fe.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 ID("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 _v){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(!Ws(r))throw new Error(`Execution policy blocks autonomous worker for provider "${e}" (policy: ${r})`)}validateWorkingDirectory(e){return Zt(e,this.baseDir)}normalizeReadablePaths(e,r){return e?.map(n=>{let s=R_(n)?n:A_(r,n);return on(s,this.baseDir)})}normalizeWritablePaths(e,r){return e?.map(n=>{let s=R_(n)?n:A_(r,n);return Zt(s,this.baseDir)})}};var Fc=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 Gs=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()}}};li();Mr();js();import{spawn as RD}from"child_process";var AD=3e5,CD=3,DD=15e3,C_=10*1024*1024,OD=6e5,qc=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??AD,this.maxConsecutiveFailures=e.maxConsecutiveFailures??CD,this.startupTimeoutMs=e.startupTimeoutMs??DD}async request(e,r,n){if(this.state==="shutdown")throw new Error("CodexAppServer is shutting down");if(n?.aborted)throw new Lt(n.reason);if((this.state==="idle"||this.state==="error")&&await this.start(),this.state==="starting"&&await this.waitForReady(),n?.aborted)throw new Lt(n.reason);if(this.state!=="ready"&&this.state!=="busy")throw new Error(`CodexAppServer in unexpected state: ${this.state}`);return this.sendRequest(e,r??OD,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>wv?(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,tr(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=Dn(this.command,e),n=RD(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>C_){if(process.stderr.write(`[codex-app-server] stdoutBuffer exceeded ${C_} bytes \u2014 dropping and restarting
|
|
34
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
|
|
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
|
|
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
|
|
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 Lt(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 Ys(t,e,r="... [truncated]"){return t.length<=e?t:t.slice(0,e)+r}li();async function Xs(t,e){try{if((await _t({command:t,args:["--version"],timeout:1e4})).exitCode===0)return{available:!0,cliPath:t}}catch{}try{if((await _t({command:"npx",args:[e,"--version"],timeout:3e4})).exitCode===0)return{available:!0,cliPath:"npx"}}catch{}return{available:!1,cliPath:null}}async function Qs(t,e,r,n){if(!t)return{status:"error",message:`${n} CLI not installed`};try{let i=await _t({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 wi(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 eo(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 _e(r,`Rate limited: ${n}`);throw o.markUnavailable=!0,o}throw s.includes("auth")||s.includes("credential")||s.includes("login")||s.includes("api key")?new _e(r,`Authentication issue: ${n}`):s.includes("workspace trust")||s.includes("trusted folder")||s.includes("trustedfolders")||s.includes("not trusted")?new _e(r,`Workspace trust issue: ${n}`):new dt(r,n)}function D_(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 _e(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 _e(t,`Authentication issue (detected in stream): ${n.trim().slice(0,200)}`)):s.includes("workspace trust")||s.includes("trusted folder")||s.includes("trustedfolders")||s.includes("not trusted")?(r=!0,new _e(t,`Workspace trust issue (detected in stream): ${n.trim().slice(0,200)}`)):null},drain(){return e}}}function Xn(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 to(t,e){return!!t.files?.length||e.length>4e3}function pp(t){let e=0;return t.replace(/^### File: .+$/gm,()=>(e+=1,`### File ${e}`))}function ro(t,e,r,n){return t==="npx"?{command:"npx",cliArgs:[r,...n]}:{command:e,cliArgs:n}}function no(t,e,r){if(t instanceof _e||t instanceof dt||t instanceof Lt)throw t;let n=t?.message??"";throw n.startsWith("CLI timeout after ")?new Ds(e,r):new dt(e,n)}function zD(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 ED(t,e){let r=e?.model;return typeof r=="string"&&r.length>0?r:t}var on=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 Xr(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=kD(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:ED(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 TD={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"]}]},Oc=class extends on{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:TD,modelName:e.modelName??"claude-host"})}};var ID={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"]}]},Mc=class extends on{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:ID,modelName:e.modelName??"codex-host"})}};var RD={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"]}]},zc=class extends on{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:RD,modelName:e.modelName??"gemini-host"})}};Cr();var S_={"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 $_={"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 x_={"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 k_=Object.freeze({en:S_,ko:$_,ja:x_,zh:P_});function MD(t){return typeof t=="string"&&ic.includes(t)}function ip(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 cp(t){return t===void 0?ap(Rn):MD(t)?ap(t):(console.warn(`[i18n] unknown locale '${t}', falling back to ${Rn}`),ap(Rn))}function zD(t,e,r){let n=new Set;return{locale:t,t(s,o){let i=e[s];if(i!==void 0)return ip(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 ${zd}`)),ip(a,o)):(n.has(s)||(n.add(s),console.warn(`[i18n] missing key '${s}' in all bundles; returning raw key`)),ip(s,o))}}}function ap(t){return zD(t,k_[t],k_[zd])}async function E_(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:jD(n.name||"")}))}function jD(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 qD(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 Yn=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=qD(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 E_(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 Rs(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 ${Xy})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var FD=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function T_(t){return t.split(`
|
|
52
|
-
`).filter(n=>{let s=n.trim();return s?!
|
|
53
|
-
`).trim()}function
|
|
51
|
+
\`\`\``);return e}function jD(t,e){let r=e?.model;return typeof r=="string"&&r.length>0?r:t}var an=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 Qr(this,this.getCapabilities())}isAvailable(){return this.bridge.isAvailable()}async chat(e){if(!this.isAvailable())throw new _e(this.id,`${this.displayName} host bridge is not available`);try{let r=zD(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:jD(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 _e(this.id,n):new dt(this.id,n)}}};var ND={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"]}]},Uc=class extends an{constructor(e){super({...e,type:"claude-host",displayName:"Claude",capabilities:ND,modelName:e.modelName??"claude-host"})}};var LD={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"]}]},Zc=class extends an{constructor(e){super({...e,type:"codex-host",displayName:"Codex",capabilities:LD,modelName:e.modelName??"codex-host"})}};var FD={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"]}]},Vc=class extends an{constructor(e){super({...e,type:"gemini-host",displayName:"Gemini",capabilities:FD,modelName:e.modelName??"gemini-host"})}};Mr();var O_={"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 M_={"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 z_={"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 j_={"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 N_=Object.freeze({en:O_,ko:M_,ja:z_,zh:j_});function BD(t){return typeof t=="string"&&hc.includes(t)}function fp(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 hp(t){return t===void 0?mp(Cn):BD(t)?mp(t):(console.warn(`[i18n] unknown locale '${t}', falling back to ${Cn}`),mp(Cn))}function HD(t,e,r){let n=new Set;return{locale:t,t(s,o){let i=e[s];if(i!==void 0)return fp(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 ${Zd}`)),fp(a,o)):(n.has(s)||(n.add(s),console.warn(`[i18n] missing key '${s}' in all bundles; returning raw key`)),fp(s,o))}}}function mp(t){return HD(t,N_[t],N_[Zd])}async function L_(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:WD(n.name||"")}))}function WD(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 JD=new Set(["http:","https:"]);function GD(t){let e;try{e=new URL(t)}catch{throw new Error(`Invalid Ollama host: not a valid URL (${t})`)}if(!JD.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 Qn=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=GD(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 L_(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 _e(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 _e(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 Ds(this.id,this.timeouts.generate):a instanceof dt||a instanceof _e?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 _e(this.id,`No models detected. Install a model first (ollama pull ${lv})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var YD=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function F_(t){return t.split(`
|
|
52
|
+
`).filter(n=>{let s=n.trim();return s?!YD.some(o=>o.test(s)):!1}).join(`
|
|
53
|
+
`).trim()}function q_(t){let e=wi(t);return e&&typeof e.response=="string"?e.response:null}var gp="gemini",yp="@google/gemini-cli",es=class{id;type="gemini-cli";timeout;available=!1;cliPath=null;defaultCwd;limiter=new Gs(bv);constructor(e){this.id=e.id,this.timeout=e.timeout??18e4,this.defaultCwd=e.workspaceBaseDir??process.cwd()}async initialize(){let e=await Xs(gp,yp);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){return Qs(this.cliPath,gp,yp,"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 _e(this.id,"Gemini CLI not installed");let r=Xn(e),n=to(e,r),o=["-p",n?"Use the full instructions and file contents provided on stdin.":r,"-o","json"],{command:i,cliArgs:a}=ro(this.cliPath,gp,yp,o),c=D_(this.id),u=e.timeoutMs??this.timeout;try{let l=await _t({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{eo(l.exitCode,l.stderr,this.id)}catch(f){throw f.markUnavailable&&(this.available=!1),f}let d=q_(l.stdout);if(d!==null){let f=XD(l.stdout);return{text:d,model:f,provider:this.id}}return{text:F_(l.stdout),model:"gemini",provider:this.id}}catch(l){if(l instanceof _e)throw l.markUnavailable&&(this.available=!1),l;no(l,this.id,u)}}};function XD(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 QD}from"crypto";function vp(t){let e=t.trim().split(`
|
|
54
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
|
|
56
|
-
`).trim();try{
|
|
55
|
+
`)||t.trim()}var Bc="codex",Hc="@openai/codex";function eO(t){return["-C",t]}function tO(t,e,r){return["exec","--skip-git-repo-check","-C",r,"--full-auto","--ephemeral","--json","--",e?"-":t]}function U_(t,e){try{t.activity?.(e)}catch{}}var ts=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 Xs(Bc,Hc);this.available=e.available,this.cliPath=e.cliPath,this.available&&this.cliPath&&(this.appServer=new qc({command:this.cliPath==="npx"?"npx":Bc,commandPrefix:this.cliPath==="npx"?[Hc]:void 0,commandArgs:eO(this.defaultCwd)}))}async healthCheck(){return Qs(this.cliPath,Bc,Hc,"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 _e(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 Lt||e instanceof _e||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:pp(Xn(e)),fullAuto:!0,ephemeral:!0},id:QD()};U_(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{U_(e,{type:"close",at:new Date().toISOString(),command:"codex-app-server"})}})();if(s.error)throw new dt(this.id,s.error.message);return{text:vp(JSON.stringify(s.result)),model:"codex",provider:this.id}}async chatViaCli(e){let r=pp(Xn(e)),n=process.platform==="win32"||to(e,r),s=e.workspaceBaseDir??this.defaultCwd,o=tO(r,n,s),{command:i,cliArgs:a}=ro(this.cliPath,Bc,Hc,o),c=e.timeoutMs??this.timeout;try{let u=await _t({command:i,args:a,stdin:n?r:void 0,timeout:c,onActivity:e.activity,signal:e.signal});if(u.exitCode!==0)try{eo(u.exitCode,u.stderr,this.id)}catch(d){throw d.markUnavailable&&(this.available=!1),d}return{text:vp(u.stdout),model:"codex",provider:this.id}}catch(u){no(u,this.id,c)}}};function Z_(t){let e=wi(t);return e?typeof e.result=="string"?e.result:typeof e.response=="string"?e.response:null:null}function V_(t){let e=wi(t);return typeof e?.model=="string"?e.model:"claude"}var rO=1,_p="claude",bp="@anthropic-ai/claude-code",rs=class{id;type="claude-cli";timeout;available=!1;cliPath=null;defaultCwd;limiter=new Gs(rO);constructor(e){this.id=e.id,this.timeout=e.timeout??18e4,this.defaultCwd=e.workspaceBaseDir??process.cwd()}async initialize(){let e=await Xs(_p,bp);this.available=e.available,this.cliPath=e.cliPath}async healthCheck(){return Qs(this.cliPath,_p,bp,"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 _e(this.id,"Claude CLI not installed");let r=Xn(e),n=process.platform==="win32"||to(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}=ro(this.cliPath,_p,bp,o),c=e.timeoutMs??this.timeout;try{let u=await _t({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{eo(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:Z_(u.stdout)??u.stdout.trim(),model:V_(u.stdout),provider:this.id}}catch(u){no(u,this.id,c)}}};import{randomUUID as nO}from"crypto";var sO=7200*1e3,Si=class{debates=new Map;create(e){this.purgeStaleDebates();let r=nO(),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
57
|
`;if(n.goal&&(s+=`Goal: ${n.goal}
|
|
58
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>An){let u=i-An,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(-An),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>
|
|
66
|
+
`;if(c.length+l.length>Fd){c+=`[... history truncated at ${Fd} characters]
|
|
67
67
|
|
|
68
68
|
`;break}c+=l}s+=c,s+=`===
|
|
69
69
|
|
|
@@ -99,32 +99,33 @@ Evaluation goal: ${n.goal}
|
|
|
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 s=new Date(n.createdAt).getTime();e-s>
|
|
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>sO&&this.debates.delete(r)}}};import{mkdirSync as oO,readFileSync as B_,readdirSync as wp,existsSync as Wc,renameSync as iO,rmdirSync as aO}from"fs";import{join as cO}from"path";import{randomUUID as uO}from"crypto";function Sp(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 H_=new Set(["completed","completed_with_errors","failed"]);function W_(t,e){return H_.has(t)?!1:!!(t==="pending"&&e==="in_progress"||t==="in_progress"&&H_.has(e)||t==="in_progress"&&e==="in_progress")}function K_(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 $i=class{sessionDir;sessions;fullyLoaded=!1;constructor(e){this.sessionDir=e,oO(this.sessionDir,{recursive:!0}),this.migrateLegacyNestedSessions(),this.sessions=new Map}migrateLegacyNestedSessions(){let e=cO(this.sessionDir,"sessions");if(!Wc(e))return;let r;try{r=wp(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(Wc(i)){console.warn(`[SessionManager] migration skipped ${s}: destination already exists at ${i}`);continue}try{iO(o,i)}catch(a){console.warn(`[SessionManager] migration failed for ${s}: ${String(a)}`)}}try{wp(e).length===0&&aO(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:uO(),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(Wc(n))try{let s=B_(n,"utf-8"),o=JSON.parse(s);return K_(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(!W_(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(!W_(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(!Wc(this.sessionDir)){this.fullyLoaded=!0;return}let e=wp(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(!K_(i))continue;this.sessions.set(i.id,i)}catch{}}this.fullyLoaded=!0}};function so(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 J_(t,e,r){try{let n=so(t);if(n&&typeof n=="object")return e(n)}catch{}return r(t)}var xi=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
103
|
Additional criteria: ${n}`:"",o=[`You are a cross-validator reviewing work from provider "${e.providerId}".`,`Task: ${e.task}`,`Content to review:
|
|
104
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
|
|
105
|
+
`),i=await this.chatWith(r,{prompt:o});return this.parseReview(e.providerId,r.id,i.text)}parseReview(e,r,n){return J_(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 X_,readdirSync as Q_,statSync as Jc}from"fs";import{join as eb,relative as pO}from"path";var G_=50*1024,Kc=500,Y_=100;function fO(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}function mO(t,e){let r=[],n=s=>{let o=Jc(s);if(o.isFile()){r.push(s);return}if(o.isDirectory())for(let i of Q_(s)){let a=eb(s,i),c=Jc(a);c.isFile()?r.push(a):e&&c.isDirectory()&&n(a)}};return n(t),r}function hO(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 tb={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=on(String(t.path??""),e),n=X_(r,"utf-8");if(t.offset!==void 0||t.limit!==void 0){let s=n.split(`
|
|
106
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")>
|
|
108
|
-
... [truncated]`)),n}},
|
|
109
|
-
... [truncated at ${
|
|
110
|
-
`)+i}},
|
|
107
|
+
`)}return Buffer.byteLength(n,"utf-8")>G_&&(n=Ys(n,G_,`
|
|
108
|
+
... [truncated]`)),n}},gO={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=Zt(String(t.path??""),e),n=String(t.content??"");return ge(r,n),`File written: ${t.path} (${Buffer.byteLength(n,"utf-8")} bytes)`}},rb={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=on(String(t.path??"."),e),n=!!t.recursive,s=[];function o(a,c){if(s.length>=Kc)return;let u=Q_(a);for(let l of u){if(s.length>=Kc)break;let d=eb(a,l),p=c?`${c}/${l}`:l;try{let f=Jc(d);s.push(f.isDirectory()?`${p}/`:p),n&&f.isDirectory()&&o(d,p)}catch{}}}o(r,"");let i=s.length>=Kc?`
|
|
109
|
+
... [truncated at ${Kc} entries]`:"";return s.join(`
|
|
110
|
+
`)+i}},nb={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=on(String(t.path??"."),e),s=t.glob?fO(String(t.glob)):null,o=Jc(n).isDirectory(),i=mO(n,o);try{let a=new RegExp(r),c=[];for(let u of i){let l=pO(e,u).replace(/\\/g,"/");if(s&&!s.test(l.split("/").pop()??l))continue;let d;try{d=X_(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>=Y_))return c.join(`
|
|
111
111
|
`)+`
|
|
112
|
-
... [truncated at ${
|
|
113
|
-
`)||"No matches found."}catch{return"No matches found."}}},
|
|
112
|
+
... [truncated at ${Y_} matches]`}return c.join(`
|
|
113
|
+
`)||"No matches found."}catch{return"No matches found."}}},yO={name:"shell_exec",description:`Execute a shell command. Only safe, read-oriented commands are allowed (${[...zc].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=y_(r);if(!n.valid)return`Error: ${n.error}`;let s=r.split(/\s+/).filter(Boolean),o=s[0],i=s.slice(1),a=hO(o,i);try{let c=await _t({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: ${D(c)}`}}};function
|
|
116
|
+
... [output truncated]`),u||"(no output)"}catch(c){return`Error: ${D(c)}`}}};function Pi(){return[tb,gO,rb,nb,yO]}function oo(){return[tb,rb,nb]}function $p(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 vO=15,_O=30,bO=3e5,wO=2e3,SO=`You are a coding assistant with access to the workspace tools provided by the runtime. Use those 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
|
-
-
|
|
122
|
-
-
|
|
123
|
-
|
|
121
|
+
- If file_write is available and you use it, write complete file contents rather than diffs.
|
|
122
|
+
- If write tools are not available, do not claim to have edited files; provide analysis, a patch plan, or a candidate diff instead.
|
|
123
|
+
- Provide a clear summary of what you did when finished.`,Gc=class{host;model;baseDir;maxIterations;timeoutMs;systemPrompt;tools;toolDefs;toolMap;signal;constructor(e){this.host=e.providerHost.replace(/\/$/,""),this.model=e.model,this.baseDir=e.baseDir,this.maxIterations=Math.min(e.maxIterations??vO,_O),this.timeoutMs=e.timeoutMs??bO,this.systemPrompt=e.systemPrompt??SO,this.tools=e.tools??Pi(),this.toolDefs=$p(this.tools),this.toolMap=new Map(this.tools.map(r=>[r.name,r])),this.signal=e.signal}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(io(this.signal),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),io(this.signal)}catch(u){io(this.signal);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}
|
|
124
|
+
${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 y=so(d);p=y&&typeof y=="object"&&!Array.isArray(y)?y:{}}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{io(this.signal),h=await f.execute(p,this.baseDir),io(this.signal)}catch(y){io(this.signal),h=`Error: ${D(y)}`}n.push({iteration:i,toolName:l,arguments:p,result:Ys(h,wO,"... [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>An){let n=r[r.length-An];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=()=>{s.abort(this.signal?.reason)};this.signal?.aborted?o():this.signal?.addEventListener("abort",o,{once:!0});let i=setTimeout(()=>s.abort(),this.timeoutMs);try{let a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:s.signal});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`HTTP ${a.status}: ${c.slice(0,200)}`)}return await a.json()}finally{clearTimeout(i),this.signal?.removeEventListener("abort",o)}}};function io(t){if(!t?.aborted)return;let e=t.reason;throw e instanceof Error?e:new Error(typeof e=="string"?e:"Agent loop aborted")}function sb(t){if(t.type!=="ollama")return null;let e=t;return typeof e.getConnectionInfo=="function"?e.getConnectionInfo():null}var cn=class{tools;baseDir;constructor(e){this.tools=e.tools,this.baseDir=e.baseDir}async chat(e,r){if(yc(e.id,e.getCapabilities(),void 0,e.type).tier!=="tool")return e.chat(r);let s=sb(e);if(!s)return e.chat(r);let o=r.model??s.model,a=await new Gc({providerHost:s.host,model:o,baseDir:this.baseDir,tools:this.tools,...r.timeoutMs!==void 0?{timeoutMs:r.timeoutMs}:{},...r.system!==void 0?{systemPrompt:r.system}:{},...r.signal!==void 0?{signal:r.signal}:{}}).run(r.prompt);if(r.signal?.aborted){let c=r.signal.reason;throw c instanceof Error?c:new Error(typeof c=="string"?c:"Agent loop aborted")}return{text:a.output,model:o,provider:e.id}}};import{existsSync as ki,readFileSync as PO,readdirSync as kO}from"fs";import{join as ao}from"path";var Ti=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
125
|
${u.join(`
|
|
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=
|
|
126
|
-
${n.stderr}`.trim(),o=
|
|
127
|
-
... [truncated]`);return{exitCode:n.exitCode,output:o}}catch(n){return{exitCode:1,output:n.message??"AutoQA run failed"}}}};var
|
|
126
|
+
`)}`;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=Ms[e];return r?{name:r.name,command:r.command,args:r.args}:null}detectBuildProfile(){if(ki(ao(this.baseDir,"tsconfig.json")))return Ms.tsc;if(ki(ao(this.baseDir,"vitest.config.ts"))||ki(ao(this.baseDir,"vitest.config.js")))return Ms.vitest;let e=this.getPackageScripts();return e?.build?Ms["npm-build"]:e?.test&&e.test!=='echo "Error: no test specified" && exit 1'?Ms["npm-test"]:null}detectDesignDoc(){let e=ao(this.baseDir,"docs","plans");if(!ki(e))return null;try{let r=kO(e).filter(n=>n.endsWith(".md")).sort().reverse();if(r.length>0)return ao("docs","plans",r[0])}catch{}return null}getPackageScripts(){let e=ao(this.baseDir,"package.json");if(!ki(e))return null;try{return JSON.parse(PO(e,"utf-8")).scripts??null}catch{return null}}async runProfile(e,r){try{Ic(e.command,e.args)}catch(n){return{exitCode:1,output:n instanceof Mt?n.message:`Profile ${e.name} rejected: ${n.message}`}}try{let n=await _t({command:e.command,args:[...e.args],cwd:this.baseDir,timeout:r,maxBuffer:10485760}),s=n.exitCode===0?n.stdout:`${n.stdout}
|
|
127
|
+
${n.stderr}`.trim(),o=Ys(s,1e4,`
|
|
128
|
+
... [truncated]`);return{exitCode:n.exitCode,output:o}}catch(n){return{exitCode:1,output:n.message??"AutoQA run failed"}}}};var TO=new Set(["","hello","hi","thanks","thank you","sure","okay","i agree","great question"]),EO=/[\w./\\]+\.[a-z]{1,4}/gi,IO=/\b\d+\.?\d*\b/g,RO=/`[^`\n]+`/g,AO=/https?:\/\/\S+/g,CO=/\b[a-z][a-zA-Z]*[A-Z][a-zA-Z]*\b|\b[a-z]+(?:_[a-z]+)+\b/g;function Yc(t){return Math.max(0,Math.min(1,t))}function qr(t,e){return t.match(e)?.length??0}function DO(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 OO(t){let e=t.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim();return TO.has(e)?!0:e.replace(/\s+/g,"").length<5}function MO(t){let e=DO(t);if(e.length===0)return .1;let r=e.filter(OO).length,n=(e.length-r)/e.length;return Math.max(.1,Yc(n))}function zO(t){let e=qr(t,/^\s*#\s+/gm),r=qr(t,/^\s*(?:[-*]|\d+\.)\s+/gm),n=Math.ceil(qr(t,/^\s*```/gm)/2),s=qr(t,/^\s*.*\|.*\s*$/gm),o=e+r+n+s;return Yc(o/3)}function jO(t){let e=qr(t,EO)+qr(t,IO)+qr(t,RO)+qr(t,AO)+qr(t,CO);return Yc(e/3)}function ob(t){let e=t.toLowerCase().match(/\b[\w-]+\b/g)??[];return new Set(e.filter(r=>r.length>=4))}function NO(t,e){if(e.length===0)return .5;let r=new Set;for(let i of e)for(let a of ob(i.content))r.add(a);if(r.size===0)return 0;let n=ob(t),s=0;for(let i of r)n.has(i)&&(s+=1);let o=Math.max(1,r.size*.3);return Yc(s/o)}function Ei(t,e,r){let n={substanceRatio:MO(t),structureScore:zO(t),specificityScore:jO(t),engagementScore:NO(t,e)};return{score:(n.substanceRatio+n.structureScore+n.specificityScore+n.engagementScore)/4,breakdown:n}}import{mkdirSync as Xc,readFileSync as FO,readdirSync as xp,existsSync as co,statSync as ib,unlinkSync as qO}from"fs";import{basename as ab,join as Ii,relative as cb,sep as ub}from"path";import{randomUUID as UO}from"crypto";var ZO="reviews";function uo(t){return t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,40)||"untitled"}function VO(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"anonymous"}function lo(){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 lb(t){return ub==="/"?t:t.split(ub).join("/")}var Ri=class{reviewDir;individualDir;debateDir;synthesisDir;constructor(e){this.reviewDir=Ii(e,ZO),this.individualDir=Ii(e,hv),this.debateDir=Ii(e,Os),this.synthesisDir=Ii(e,gv),Xc(this.reviewDir,{recursive:!0}),Xc(this.individualDir,{recursive:!0}),Xc(this.debateDir,{recursive:!0}),Xc(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(!co(s))continue;let o;try{o=xp(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(co(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=lo(),n=e.topic?uo(e.topic):UO().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
129
|
|
|
129
130
|
`;a+=`**Date:** ${new Date().toISOString().slice(0,10)}
|
|
130
131
|
`,e.provider&&(a+=`**Provider:** ${e.provider}
|
|
@@ -139,7 +140,7 @@ ${n.stderr}`.trim(),o=Ws(s,1e4,`
|
|
|
139
140
|
`}return a+=`
|
|
140
141
|
---
|
|
141
142
|
|
|
142
|
-
`,ge(i,a),{id:o,content:a,path:i}}async createDebateDocument(e){let r=
|
|
143
|
+
`,ge(i,a),{id:o,content:a,path:i}}async createDebateDocument(e){let r=lo(),n=uo(e.topic),s=this.nextSequenceGlobal(r),o=`${n}_${r}_${s}`,i=Je(`${o}.md`,this.debateDir),a=`# Debate: ${e.topic}
|
|
143
144
|
|
|
144
145
|
`;return a+=`**Date:** ${new Date().toISOString().slice(0,10)}
|
|
145
146
|
`,a+=`**Participants:** ${e.providers.join(", ")}
|
|
@@ -147,7 +148,7 @@ ${n.stderr}`.trim(),o=Ws(s,1e4,`
|
|
|
147
148
|
`),a+=`
|
|
148
149
|
---
|
|
149
150
|
|
|
150
|
-
`,ge(i,a),{id:o,content:a,path:i}}async createIndividualReview(e){let r=
|
|
151
|
+
`,ge(i,a),{id:o,content:a,path:i}}async createIndividualReview(e){let r=lo(),n=VO(e.participantId),s=uo(e.topic),o=this.nextSequenceGlobal(r),i=`${n}_${s}_${r}_${o}`,a=Je(`${i}.md`,this.individualDir),c=`# ${e.topic} \u2014 ${e.participantId}
|
|
151
152
|
|
|
152
153
|
`;if(c+=`**Date:** ${new Date().toISOString().slice(0,10)}
|
|
153
154
|
`,c+=`**Participant:** ${e.participantId}
|
|
@@ -162,7 +163,7 @@ ${n.stderr}`.trim(),o=Ws(s,1e4,`
|
|
|
162
163
|
`,c+=e.content,c+=`
|
|
163
164
|
|
|
164
165
|
---
|
|
165
|
-
`,ge(a,c),{id:i,content:c,path:a}}async createIssueDocument(e){let r=
|
|
166
|
+
`,ge(a,c),{id:i,content:c,path:a}}async createIssueDocument(e){let r=lo(),n=e.sessionId.slice(0,8),s=this.nextSequenceGlobal(r),o=`${yv}_${n}_${r}_${s}`,i=Je(`${o}.md`,this.individualDir),a=`# Rejection Issue Report \u2014 ${e.topic}
|
|
166
167
|
|
|
167
168
|
`;if(a+=`**Session:** ${e.sessionId}
|
|
168
169
|
`,a+=`**Rejected at:** ${new Date().toISOString()}
|
|
@@ -181,7 +182,7 @@ ${n.stderr}`.trim(),o=Ws(s,1e4,`
|
|
|
181
182
|
`}a+=`
|
|
182
183
|
`}return a+=`
|
|
183
184
|
---
|
|
184
|
-
`,ge(i,a),{id:o,content:a,path:i}}buildSynthesisContent(e,r){let n=
|
|
185
|
+
`,ge(i,a),{id:o,content:a,path:i}}buildSynthesisContent(e,r){let n=lb(cb(r,e.debatePath)),s=e.individualPaths.map(i=>lb(cb(r,i))),o=`# Synthesis: ${e.topic}
|
|
185
186
|
|
|
186
187
|
`;if(o+=`**Date:** ${new Date().toISOString().slice(0,10)}
|
|
187
188
|
`,o+=`**Status:** ${e.status}
|
|
@@ -192,16 +193,16 @@ ${n.stderr}`.trim(),o=Ws(s,1e4,`
|
|
|
192
193
|
`;if(o+=`
|
|
193
194
|
## Sources
|
|
194
195
|
|
|
195
|
-
`,o+=`- Debate transcript: [${
|
|
196
|
+
`,o+=`- Debate transcript: [${ab(e.debatePath)}](${n})
|
|
196
197
|
`,e.individualPaths.length>0){o+=`- Individual reviews:
|
|
197
|
-
`;for(let i=0;i<e.individualPaths.length;i++){let a=e.individualPaths[i];o+=` - [${
|
|
198
|
+
`;for(let i=0;i<e.individualPaths.length;i++){let a=e.individualPaths[i];o+=` - [${ab(a)}](${s[i]})
|
|
198
199
|
`}}return o+=`
|
|
199
200
|
---
|
|
200
201
|
|
|
201
202
|
`,o+=e.body,o+=`
|
|
202
203
|
|
|
203
204
|
---
|
|
204
|
-
`,o}async createSynthesis(e){let r=
|
|
205
|
+
`,o}async createSynthesis(e){let r=lo(),n=uo(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(!co(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(!co(n))throw new Error(`Synthesis document not found: ${e}`);Tc(n,`
|
|
205
206
|
${r}
|
|
206
207
|
`)}async addComment(e,r){let n=this.resolveDocPath(e),s=`
|
|
207
208
|
## Comment by ${r.author}
|
|
@@ -209,69 +210,71 @@ ${r}
|
|
|
209
210
|
${r.content}
|
|
210
211
|
|
|
211
212
|
---
|
|
212
|
-
`;
|
|
213
|
+
`;Tc(n,s)}async replaceDocumentContent(e,r){let n=this.resolveDocPath(e);ge(n,r)}async read(e){let r=this.resolveDocPath(e),n=FO(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=lo(),o=e.topic?uo(e.topic):uo(e.title),i=this.nextSequenceGlobal(s),a=`${o}_${s}_${i}`,c=Je(`${a}.md`,n),u=`# ${e.title}
|
|
213
214
|
|
|
214
215
|
`;if(e.metadata){for(let[l,d]of Object.entries(e.metadata))u+=`**${l}:** ${d}
|
|
215
216
|
`;u+=`
|
|
216
217
|
`}return u+=e.content,u+=`
|
|
217
218
|
|
|
218
219
|
---
|
|
219
|
-
`,ge(c,u),{id:a,content:u,path:c}}async list(){let e=[];for(let r of this.allDirs){if(!no(r))continue;let n=vp(r).filter(s=>s.endsWith(".md"));for(let s of n){let o=s.replace(".md",""),i=Je(s,r),a=K_(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(!no(a))continue;let c=vp(a).filter(u=>u.endsWith(".md")).map(u=>{let l=xi(a,u),d=K_(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{AO(c[u].path),i++}catch{}}}return{removed:i}}};var i5=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 qr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Hc={};function Ut(t){return t&&Object.assign(Hc,t),Hc}var ye={};rt(ye,{BIGINT_FORMAT_RANGES:()=>eb,Class:()=>bp,NUMBER_FORMAT_RANGES:()=>Tp,aborted:()=>rs,allowsEval:()=>Pp,assert:()=>LO,assertEqual:()=>MO,assertIs:()=>jO,assertNever:()=>NO,assertNotEqual:()=>zO,assignProp:()=>xp,cached:()=>Ei,captureStackTrace:()=>Kc,cleanEnum:()=>XO,cleanRegex:()=>Ii,clone:()=>_r,createTransparentProxy:()=>BO,defineLazy:()=>Pe,esc:()=>ts,escapeRegex:()=>an,extend:()=>KO,finalizeIssue:()=>tr,floatSafeRemainder:()=>$p,getElementAtPath:()=>qO,getEnumValues:()=>wp,getLengthableOrigin:()=>Ri,getParsedType:()=>VO,getSizableOrigin:()=>tb,isObject:()=>io,isPlainObject:()=>ao,issue:()=>Ip,joinValues:()=>Wc,jsonStringifyReplacer:()=>Sp,merge:()=>JO,normalizeParams:()=>U,nullish:()=>Ti,numKeys:()=>ZO,omit:()=>WO,optionalKeys:()=>Ep,partial:()=>GO,pick:()=>HO,prefixIssues:()=>br,primitiveTypes:()=>Q_,promiseAllObject:()=>FO,propertyKeyTypes:()=>kp,randomString:()=>UO,required:()=>YO,stringifyPrimitive:()=>Jc,unwrapMessage:()=>ki});function MO(t){return t}function zO(t){return t}function jO(t){}function NO(t){throw new Error}function LO(t){}function wp(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 Wc(t,e="|"){return t.map(r=>Jc(r)).join(e)}function Sp(t,e){return typeof e=="bigint"?e.toString():e}function Ei(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ti(t){return t==null}function Ii(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function $p(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 xp(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function qO(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function FO(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 UO(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function ts(t){return JSON.stringify(t)}var Kc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function io(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Pp=Ei(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function ao(t){if(io(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(io(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function ZO(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var VO=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}`)}},kp=new Set(["string","number","symbol"]),Q_=new Set(["string","number","bigint","boolean","symbol","undefined"]);function an(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 BO(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 Jc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Ep(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Tp={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]},eb={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function HO(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 WO(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(!ao(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 xp(this,"shape",n),n},checks:[]};return _r(t,r)}function JO(t,e){return _r(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return xp(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function GO(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 YO(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 rs(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 ki(t){return typeof t=="string"?t:t?.message}function tr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let s=ki(t.inst?._zod.def?.error?.(t))??ki(e?.error?.(t))??ki(r.customError?.(t))??ki(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function tb(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ri(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ip(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function XO(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var bp=class{constructor(...e){}};var rb=(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,Sp,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Gc=$("$ZodError",rb),Rp=$("$ZodError",rb,{Parent:Error});function nb(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 sb(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 ob=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 qr;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>tr(c,o,Ut())));throw Kc(a,s?.callee),a}return i.value};var ib=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 Kc(a,s?.callee),a}return i.value};var Ap=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 qr;return o.issues.length?{success:!1,error:new(t??Gc)(o.issues.map(i=>tr(i,s,Ut())))}:{success:!0,data:o.value}},Ai=Ap(Rp),Cp=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}},Yc=Cp(Rp);var ab=/^[cC][^\s-]{8,}$/,cb=/^[0-9a-z]+$/,ub=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,lb=/^[0-9a-vA-V]{20}$/,db=/^[A-Za-z0-9]{27}$/,pb=/^[a-zA-Z0-9_-]{21}$/,fb=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var mb=/^([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})$/,Dp=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 hb=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var eM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function gb(){return new RegExp(eM,"u")}var yb=/^(?:(?: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])$/,vb=/^(([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})$/,_b=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,bb=/^(([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])$/,wb=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Op=/^[A-Za-z0-9_-]*$/,Sb=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var $b=/^\+(?:[0-9]){6,14}[0-9]$/,xb="(?:(?:\\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(`^${xb}$`);function kb(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 Eb(t){return new RegExp(`^${kb(t)}$`)}function Tb(t){let e=kb({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(`^${xb}T(?:${n})$`)}var Ib=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Rb=/^\d+$/,Ab=/^-?\d+(?:\.\d+)?/i,Cb=/true|false/i,Db=/null/i;var Ob=/^[^A-Z]*$/,Mb=/^[^a-z]*$/;var st=$("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),zb={number:"number",bigint:"bigint",object:"date"},zp=$("$ZodCheckLessThan",(t,e)=>{st.init(t,e);let r=zb[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})}}),jp=$("$ZodCheckGreaterThan",(t,e)=>{st.init(t,e);let r=zb[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})}}),jb=$("$ZodCheckMultipleOf",(t,e)=>{st.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):$p(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})}}),Nb=$("$ZodCheckNumberFormat",(t,e)=>{st.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[s,o]=Tp[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=Rb)}),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 Lb=$("$ZodCheckMaxLength",(t,e)=>{var r;st.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Ti(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=Ri(s);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),qb=$("$ZodCheckMinLength",(t,e)=>{var r;st.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Ti(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=Ri(s);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Fb=$("$ZodCheckLengthEquals",(t,e)=>{var r;st.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Ti(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=Ri(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})}}),Ci=$("$ZodCheckStringFormat",(t,e)=>{var r,n;st.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=()=>{})}),Ub=$("$ZodCheckRegex",(t,e)=>{Ci.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})}}),Zb=$("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Ob),Ci.init(t,e)}),Vb=$("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Mb),Ci.init(t,e)}),Bb=$("$ZodCheckIncludes",(t,e)=>{st.init(t,e);let r=an(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})}}),Hb=$("$ZodCheckStartsWith",(t,e)=>{st.init(t,e);let r=new RegExp(`^${an(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})}}),Wb=$("$ZodCheckEndsWith",(t,e)=>{st.init(t,e);let r=new RegExp(`.*${an(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 Kb=$("$ZodCheckOverwrite",(t,e)=>{st.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Xc=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
|
+
`,ge(c,u),{id:a,content:u,path:c}}async list(){let e=[];for(let r of this.allDirs){if(!co(r))continue;let n=xp(r).filter(s=>s.endsWith(".md"));for(let s of n){let o=s.replace(".md",""),i=Je(s,r),a=ib(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(!co(a))continue;let c=xp(a).filter(u=>u.endsWith(".md")).map(u=>{let l=Ii(a,u),d=ib(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{qO(c[u].path),i++}catch{}}}return{removed:i}}};var _5=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 Ur=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Qc={};function Vt(t){return t&&Object.assign(Qc,t),Qc}var ye={};rt(ye,{BIGINT_FORMAT_RANGES:()=>pb,Class:()=>kp,NUMBER_FORMAT_RANGES:()=>Op,aborted:()=>ss,allowsEval:()=>Ap,assert:()=>JO,assertEqual:()=>BO,assertIs:()=>WO,assertNever:()=>KO,assertNotEqual:()=>HO,assignProp:()=>Rp,cached:()=>Ci,captureStackTrace:()=>tu,cleanEnum:()=>cM,cleanRegex:()=>Oi,clone:()=>wr,createTransparentProxy:()=>tM,defineLazy:()=>Pe,esc:()=>ns,escapeRegex:()=>un,extend:()=>sM,finalizeIssue:()=>nr,floatSafeRemainder:()=>Ip,getElementAtPath:()=>GO,getEnumValues:()=>Tp,getLengthableOrigin:()=>Mi,getParsedType:()=>eM,getSizableOrigin:()=>fb,isObject:()=>po,isPlainObject:()=>fo,issue:()=>Mp,joinValues:()=>eu,jsonStringifyReplacer:()=>Ep,merge:()=>oM,normalizeParams:()=>U,nullish:()=>Di,numKeys:()=>QO,omit:()=>nM,optionalKeys:()=>Dp,partial:()=>iM,pick:()=>rM,prefixIssues:()=>Sr,primitiveTypes:()=>db,promiseAllObject:()=>YO,propertyKeyTypes:()=>Cp,randomString:()=>XO,required:()=>aM,stringifyPrimitive:()=>ru,unwrapMessage:()=>Ai});function BO(t){return t}function HO(t){return t}function WO(t){}function KO(t){throw new Error}function JO(t){}function Tp(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 eu(t,e="|"){return t.map(r=>ru(r)).join(e)}function Ep(t,e){return typeof e=="bigint"?e.toString():e}function Ci(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Di(t){return t==null}function Oi(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Ip(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 Rp(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function GO(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function YO(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 XO(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function ns(t){return JSON.stringify(t)}var tu=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function po(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Ap=Ci(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function fo(t){if(po(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(po(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function QO(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var eM=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}`)}},Cp=new Set(["string","number","symbol"]),db=new Set(["string","number","bigint","boolean","symbol","undefined"]);function un(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wr(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 tM(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 ru(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Dp(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Op={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]},pb={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function rM(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 wr(t,{...t._zod.def,shape:r,checks:[]})}function nM(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 wr(t,{...t._zod.def,shape:r,checks:[]})}function sM(t,e){if(!fo(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 Rp(this,"shape",n),n},checks:[]};return wr(t,r)}function oM(t,e){return wr(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Rp(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function iM(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 wr(e,{...e._zod.def,shape:s,checks:[]})}function aM(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 wr(e,{...e._zod.def,shape:s,checks:[]})}function ss(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Sr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ai(t){return typeof t=="string"?t:t?.message}function nr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let s=Ai(t.inst?._zod.def?.error?.(t))??Ai(e?.error?.(t))??Ai(r.customError?.(t))??Ai(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function fb(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Mi(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Mp(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function cM(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var kp=class{constructor(...e){}};var mb=(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,Ep,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},nu=$("$ZodError",mb),zp=$("$ZodError",mb,{Parent:Error});function hb(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 gb(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 yb=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 Ur;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>nr(c,o,Vt())));throw tu(a,s?.callee),a}return i.value};var vb=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=>nr(c,o,Vt())));throw tu(a,s?.callee),a}return i.value};var jp=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 Ur;return o.issues.length?{success:!1,error:new(t??nu)(o.issues.map(i=>nr(i,s,Vt())))}:{success:!0,data:o.value}},zi=jp(zp),Np=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=>nr(i,s,Vt())))}:{success:!0,data:o.value}},su=Np(zp);var _b=/^[cC][^\s-]{8,}$/,bb=/^[0-9a-z]+$/,wb=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Sb=/^[0-9a-vA-V]{20}$/,$b=/^[A-Za-z0-9]{27}$/,xb=/^[a-zA-Z0-9_-]{21}$/,Pb=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var kb=/^([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})$/,Lp=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 Tb=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var lM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Eb(){return new RegExp(lM,"u")}var 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])$/,Rb=/^(([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})$/,Ab=/^((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])$/,Cb=/^(([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])$/,Db=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Fp=/^[A-Za-z0-9_-]*$/,Ob=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Mb=/^\+(?:[0-9]){6,14}[0-9]$/,zb="(?:(?:\\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])))",jb=new RegExp(`^${zb}$`);function Nb(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 Lb(t){return new RegExp(`^${Nb(t)}$`)}function Fb(t){let e=Nb({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(`^${zb}T(?:${n})$`)}var qb=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Ub=/^\d+$/,Zb=/^-?\d+(?:\.\d+)?/i,Vb=/true|false/i,Bb=/null/i;var Hb=/^[^A-Z]*$/,Wb=/^[^a-z]*$/;var st=$("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Kb={number:"number",bigint:"bigint",object:"date"},Up=$("$ZodCheckLessThan",(t,e)=>{st.init(t,e);let r=Kb[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})}}),Zp=$("$ZodCheckGreaterThan",(t,e)=>{st.init(t,e);let r=Kb[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})}}),Jb=$("$ZodCheckMultipleOf",(t,e)=>{st.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):Ip(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})}}),Gb=$("$ZodCheckNumberFormat",(t,e)=>{st.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[s,o]=Op[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=Ub)}),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 Yb=$("$ZodCheckMaxLength",(t,e)=>{var r;st.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Di(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=Mi(s);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Xb=$("$ZodCheckMinLength",(t,e)=>{var r;st.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Di(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=Mi(s);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Qb=$("$ZodCheckLengthEquals",(t,e)=>{var r;st.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Di(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=Mi(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})}}),ji=$("$ZodCheckStringFormat",(t,e)=>{var r,n;st.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=()=>{})}),ew=$("$ZodCheckRegex",(t,e)=>{ji.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})}}),tw=$("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Hb),ji.init(t,e)}),rw=$("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Wb),ji.init(t,e)}),nw=$("$ZodCheckIncludes",(t,e)=>{st.init(t,e);let r=un(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})}}),sw=$("$ZodCheckStartsWith",(t,e)=>{st.init(t,e);let r=new RegExp(`^${un(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})}}),ow=$("$ZodCheckEndsWith",(t,e)=>{st.init(t,e);let r=new RegExp(`.*${un(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 iw=$("$ZodCheckOverwrite",(t,e)=>{st.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var ou=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
221
|
`).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
|
|
222
|
-
if (${
|
|
222
|
+
`))}};var cw={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=cw;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=ss(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 Ur;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,o.issues.length!==d&&(c||(c=ss(o,d)))});else{if(o.issues.length===d)continue;c||(c=ss(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 Ur;return a.then(c=>s(c,n,i))}return s(a,n,i)}}t["~standard"]={validate:s=>{try{let o=zi(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return su(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),au=$("$ZodString",(t,e)=>{ke.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??qb(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}}),Ee=$("$ZodStringFormat",(t,e)=>{ji.init(t,e),au.init(t,e)}),vw=$("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=kb),Ee.init(t,e)}),_w=$("$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=Lp(n))}else e.pattern??(e.pattern=Lp());Ee.init(t,e)}),bw=$("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Tb),Ee.init(t,e)}),ww=$("$ZodURL",(t,e)=>{Ee.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:Ob.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})}}}),Sw=$("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Eb()),Ee.init(t,e)}),$w=$("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=xb),Ee.init(t,e)}),xw=$("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=_b),Ee.init(t,e)}),Pw=$("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=bb),Ee.init(t,e)}),kw=$("$ZodULID",(t,e)=>{e.pattern??(e.pattern=wb),Ee.init(t,e)}),Tw=$("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Sb),Ee.init(t,e)}),Ew=$("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=$b),Ee.init(t,e)}),Iw=$("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Fb(e)),Ee.init(t,e)}),Rw=$("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=jb),Ee.init(t,e)}),Aw=$("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Lb(e)),Ee.init(t,e)}),Cw=$("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Pb),Ee.init(t,e)}),Dw=$("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Ib),Ee.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Ow=$("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Rb),Ee.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})}}}),Mw=$("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Ab),Ee.init(t,e)}),zw=$("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Cb),Ee.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 jw(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Nw=$("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Db),Ee.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{jw(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function dM(t){if(!Fp.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return jw(r)}var Lw=$("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Fp),Ee.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{dM(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Fw=$("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Mb),Ee.init(t,e)});function pM(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 qw=$("$ZodJWT",(t,e)=>{Ee.init(t,e),t._zod.check=r=>{pM(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var Bp=$("$ZodNumber",(t,e)=>{ke.init(t,e),t._zod.pattern=t._zod.bag.pattern??Zb,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}}),Uw=$("$ZodNumber",(t,e)=>{Gb.init(t,e),Bp.init(t,e)}),Zw=$("$ZodBoolean",(t,e)=>{ke.init(t,e),t._zod.pattern=Vb,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 Vw=$("$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}),Hw=$("$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 uw(t,e,r){t.issues.length&&e.issues.push(...Sr(r,t.issues)),e.value[r]=t.value}var Ww=$("$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=>uw(u,r,i))):uw(c,r,i)}return o.length?Promise.all(o).then(()=>r):r}});function iu(t,e,r){t.issues.length&&e.issues.push(...Sr(r,t.issues)),e.value[r]=t.value}function lw(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(...Sr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var Kw=$("$ZodObject",(t,e)=>{ke.init(t,e);let r=Ci(()=>{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=Dp(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 ou(["shape","payload","ctx"]),f=r.value,m=_=>{let b=ns(_);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),y=0;for(let _ of f.keys)h[_]=`key_${y++}`;p.write("const newResult = {}");for(let _ of f.keys)if(f.optionalKeys.has(_)){let b=h[_];p.write(`const ${b} = ${m(_)};`);let P=ns(_);p.write(`
|
|
223
|
+
if (${b}.issues.length) {
|
|
223
224
|
if (input[${P}] === undefined) {
|
|
224
225
|
if (${P} in input) {
|
|
225
226
|
newResult[${P}] = undefined;
|
|
226
227
|
}
|
|
227
228
|
} else {
|
|
228
229
|
payload.issues = payload.issues.concat(
|
|
229
|
-
${
|
|
230
|
+
${b}.issues.map((iss) => ({
|
|
230
231
|
...iss,
|
|
231
232
|
path: iss.path ? [${P}, ...iss.path] : [${P}],
|
|
232
233
|
}))
|
|
233
234
|
);
|
|
234
235
|
}
|
|
235
|
-
} else if (${
|
|
236
|
+
} else if (${b}.value === undefined) {
|
|
236
237
|
if (${P} in input) newResult[${P}] = undefined;
|
|
237
238
|
} else {
|
|
238
|
-
newResult[${P}] = ${
|
|
239
|
+
newResult[${P}] = ${b}.value;
|
|
239
240
|
}
|
|
240
|
-
`)}else{let
|
|
241
|
-
if (${
|
|
241
|
+
`)}else{let b=h[_];p.write(`const ${b} = ${m(_)};`),p.write(`
|
|
242
|
+
if (${b}.issues.length) payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
|
|
242
243
|
...iss,
|
|
243
|
-
path: iss.path ? [${
|
|
244
|
-
})));`),p.write(`newResult[${ts(b)}] = ${_}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let g=p.compile();return(b,_)=>g(d,b,_)},s,o=io,i=!Hc.jitless,c=i&&Pp.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],N=x._zod.run({value:f[P],issues:[]},p),k=x._zod.optin==="optional"&&x._zod.optout==="optional";N instanceof Promise?m.push(N.then(O=>k?Xb(O,d,P,f):Qc(O,d,P))):k?Xb(N,d,P,f):Qc(N,d,P)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let h=[],y=l.keySet,g=u._zod,b=g.def.type;for(let _ of Object.keys(f)){if(y.has(_))continue;if(b==="never"){h.push(_);continue}let P=g.run({value:f[_],issues:[]},p);P instanceof Promise?m.push(P.then(x=>Qc(x,d,_))):Qc(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 qp=$("$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=>Ii(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)}}),jw=$("$ZodDiscriminatedUnion",(t,e)=>{qp.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=Ei(()=>{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(!io(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)}}),Nw=$("$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])=>ew(r,c,u)):ew(r,o,i)}});function Np(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(ao(t)&&ao(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=Np(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=Np(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 ew(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),rs(t))return t;let n=Np(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 Lw=$("$ZodRecord",(t,e)=>{ke.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!ao(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 qw=$("$ZodEnum",(t,e)=>{ke.init(t,e);let r=wp(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>kp.has(typeof n)).map(n=>typeof n=="string"?an(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}}),Fw=$("$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"?an(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 Uw=$("$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 qr;return r.value=s,r}}),Zw=$("$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(`^(${Ii(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)}),Vw=$("$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(`^(${Ii(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)}),Bw=$("$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=>tw(o,e)):tw(s,e)}});function tw(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Hw=$("$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))}),Ww=$("$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=>rw(o,t)):rw(s,t)}});function rw(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 Kw=$("$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 Jw=$("$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=>nw(o,e,n)):nw(s,e,n)}});function nw(t,e,r){return rs(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Gw=$("$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(sw):sw(s)}});function sw(t){return t.value=Object.freeze(t.value),t}var Yw=$("$ZodCustom",(t,e)=>{st.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=>ow(o,r,n,t));ow(s,r,n,t)}});function ow(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(Ip(s))}}var nM=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},sM=()=>{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 ${nM(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Jc(n.values[0])}`:`Invalid option: expected one of ${Wc(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":""}: ${Wc(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 Xw(){return{localeError:sM()}}var Fp=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 oM(){return new Fp}var Di=oM();function Qw(t,e){return new t({type:"string",...U(e)})}function eS(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...U(e)})}function Up(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...U(e)})}function tS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...U(e)})}function rS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...U(e)})}function nS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...U(e)})}function sS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...U(e)})}function oS(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...U(e)})}function iS(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...U(e)})}function aS(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...U(e)})}function cS(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...U(e)})}function uS(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...U(e)})}function lS(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...U(e)})}function dS(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...U(e)})}function pS(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...U(e)})}function fS(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...U(e)})}function mS(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...U(e)})}function hS(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...U(e)})}function gS(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...U(e)})}function yS(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...U(e)})}function vS(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...U(e)})}function _S(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...U(e)})}function bS(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...U(e)})}function wS(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...U(e)})}function SS(t,e){return new t({type:"string",format:"date",check:"string_format",...U(e)})}function $S(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...U(e)})}function xS(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 kS(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...U(e)})}function ES(t,e){return new t({type:"boolean",...U(e)})}function TS(t,e){return new t({type:"null",...U(e)})}function IS(t){return new t({type:"unknown"})}function RS(t,e){return new t({type:"never",...U(e)})}function tu(t,e){return new zp({check:"less_than",...U(e),value:t,inclusive:!1})}function Oi(t,e){return new zp({check:"less_than",...U(e),value:t,inclusive:!0})}function ru(t,e){return new jp({check:"greater_than",...U(e),value:t,inclusive:!1})}function Mi(t,e){return new jp({check:"greater_than",...U(e),value:t,inclusive:!0})}function nu(t,e){return new jb({check:"multiple_of",...U(e),value:t})}function su(t,e){return new Lb({check:"max_length",...U(e),maximum:t})}function co(t,e){return new qb({check:"min_length",...U(e),minimum:t})}function ou(t,e){return new Fb({check:"length_equals",...U(e),length:t})}function Zp(t,e){return new Ub({check:"string_format",format:"regex",...U(e),pattern:t})}function Vp(t){return new Zb({check:"string_format",format:"lowercase",...U(t)})}function Bp(t){return new Vb({check:"string_format",format:"uppercase",...U(t)})}function Hp(t,e){return new Bb({check:"string_format",format:"includes",...U(e),includes:t})}function Wp(t,e){return new Hb({check:"string_format",format:"starts_with",...U(e),prefix:t})}function Kp(t,e){return new Wb({check:"string_format",format:"ends_with",...U(e),suffix:t})}function ns(t){return new Kb({check:"overwrite",tx:t})}function Jp(t){return ns(e=>e.normalize(t))}function Gp(){return ns(t=>t.trim())}function Yp(){return ns(t=>t.toLowerCase())}function Xp(){return ns(t=>t.toUpperCase())}function AS(t,e,r){return new t({type:"array",element:e,...U(r)})}function CS(t,e,r){let n=U(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function DS(t,e,r){return new t({type:"custom",check:"custom",fn:e,...U(r)})}function uo(t){return!!t._zod}function cn(t,e){return uo(t)?Ai(t,e):t.safeParse(e)}function iu(t){if(!t)return;let e;if(uo(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function OS(t){if(uo(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 ji={};rt(ji,{ZodISODate:()=>zS,ZodISODateTime:()=>MS,ZodISODuration:()=>NS,ZodISOTime:()=>jS,date:()=>ef,datetime:()=>Qp,duration:()=>rf,time:()=>tf});var MS=$("ZodISODateTime",(t,e)=>{yw.init(t,e),Oe.init(t,e)});function Qp(t){return wS(MS,t)}var zS=$("ZodISODate",(t,e)=>{vw.init(t,e),Oe.init(t,e)});function ef(t){return SS(zS,t)}var jS=$("ZodISOTime",(t,e)=>{_w.init(t,e),Oe.init(t,e)});function tf(t){return $S(jS,t)}var NS=$("ZodISODuration",(t,e)=>{bw.init(t,e),Oe.init(t,e)});function rf(t){return xS(NS,t)}var LS=(t,e)=>{Gc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>sb(t,r)},flatten:{value:r=>nb(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},Q5=$("ZodError",LS),Ni=$("ZodError",LS,{Parent:Error});var qS=ob(Ni),FS=ib(Ni),US=Ap(Ni),ZS=Cp(Ni);var Ne=$("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)=>qS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>US(t,r,n),t.parseAsync=async(r,n)=>FS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>ZS(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(rz(r,n)),t.superRefine=r=>t.check(nz(r)),t.overwrite=r=>t.check(ns(r)),t.optional=()=>ze(t),t.nullable=()=>HS(t),t.nullish=()=>ze(HS(t)),t.nonoptional=r=>JM(t,r),t.array=()=>ie(t),t.or=r=>Ie([t,r]),t.and=r=>cu(t,r),t.transform=r=>sf(t,XS(r)),t.default=r=>HM(t,r),t.prefault=r=>KM(t,r),t.catch=r=>YM(t,r),t.pipe=r=>sf(t,r),t.readonly=()=>ez(t),t.describe=r=>{let n=t.clone();return Di.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Di.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Di.get(t);let n=t.clone();return Di.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),WS=$("_ZodString",(t,e)=>{eu.init(t,e),Ne.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(Zp(...n)),t.includes=(...n)=>t.check(Hp(...n)),t.startsWith=(...n)=>t.check(Wp(...n)),t.endsWith=(...n)=>t.check(Kp(...n)),t.min=(...n)=>t.check(co(...n)),t.max=(...n)=>t.check(su(...n)),t.length=(...n)=>t.check(ou(...n)),t.nonempty=(...n)=>t.check(co(1,...n)),t.lowercase=n=>t.check(Vp(n)),t.uppercase=n=>t.check(Bp(n)),t.trim=()=>t.check(Gp()),t.normalize=(...n)=>t.check(Jp(...n)),t.toLowerCase=()=>t.check(Yp()),t.toUpperCase=()=>t.check(Xp())}),mM=$("ZodString",(t,e)=>{eu.init(t,e),WS.init(t,e),t.email=r=>t.check(eS(hM,r)),t.url=r=>t.check(oS(gM,r)),t.jwt=r=>t.check(bS(AM,r)),t.emoji=r=>t.check(iS(yM,r)),t.guid=r=>t.check(Up(VS,r)),t.uuid=r=>t.check(tS(au,r)),t.uuidv4=r=>t.check(rS(au,r)),t.uuidv6=r=>t.check(nS(au,r)),t.uuidv7=r=>t.check(sS(au,r)),t.nanoid=r=>t.check(aS(vM,r)),t.guid=r=>t.check(Up(VS,r)),t.cuid=r=>t.check(cS(_M,r)),t.cuid2=r=>t.check(uS(bM,r)),t.ulid=r=>t.check(lS(wM,r)),t.base64=r=>t.check(yS(TM,r)),t.base64url=r=>t.check(vS(IM,r)),t.xid=r=>t.check(dS(SM,r)),t.ksuid=r=>t.check(pS($M,r)),t.ipv4=r=>t.check(fS(xM,r)),t.ipv6=r=>t.check(mS(PM,r)),t.cidrv4=r=>t.check(hS(kM,r)),t.cidrv6=r=>t.check(gS(EM,r)),t.e164=r=>t.check(_S(RM,r)),t.datetime=r=>t.check(Qp(r)),t.date=r=>t.check(ef(r)),t.time=r=>t.check(tf(r)),t.duration=r=>t.check(rf(r))});function w(t){return Qw(mM,t)}var Oe=$("ZodStringFormat",(t,e)=>{Te.init(t,e),WS.init(t,e)}),hM=$("ZodEmail",(t,e)=>{cw.init(t,e),Oe.init(t,e)});var VS=$("ZodGUID",(t,e)=>{iw.init(t,e),Oe.init(t,e)});var au=$("ZodUUID",(t,e)=>{aw.init(t,e),Oe.init(t,e)});var gM=$("ZodURL",(t,e)=>{uw.init(t,e),Oe.init(t,e)});var yM=$("ZodEmoji",(t,e)=>{lw.init(t,e),Oe.init(t,e)});var vM=$("ZodNanoID",(t,e)=>{dw.init(t,e),Oe.init(t,e)});var _M=$("ZodCUID",(t,e)=>{pw.init(t,e),Oe.init(t,e)});var bM=$("ZodCUID2",(t,e)=>{fw.init(t,e),Oe.init(t,e)});var wM=$("ZodULID",(t,e)=>{mw.init(t,e),Oe.init(t,e)});var SM=$("ZodXID",(t,e)=>{hw.init(t,e),Oe.init(t,e)});var $M=$("ZodKSUID",(t,e)=>{gw.init(t,e),Oe.init(t,e)});var xM=$("ZodIPv4",(t,e)=>{ww.init(t,e),Oe.init(t,e)});var PM=$("ZodIPv6",(t,e)=>{Sw.init(t,e),Oe.init(t,e)});var kM=$("ZodCIDRv4",(t,e)=>{$w.init(t,e),Oe.init(t,e)});var EM=$("ZodCIDRv6",(t,e)=>{xw.init(t,e),Oe.init(t,e)});var TM=$("ZodBase64",(t,e)=>{kw.init(t,e),Oe.init(t,e)});var IM=$("ZodBase64URL",(t,e)=>{Ew.init(t,e),Oe.init(t,e)});var RM=$("ZodE164",(t,e)=>{Tw.init(t,e),Oe.init(t,e)});var AM=$("ZodJWT",(t,e)=>{Iw.init(t,e),Oe.init(t,e)});var KS=$("ZodNumber",(t,e)=>{Lp.init(t,e),Ne.init(t,e),t.gt=(n,s)=>t.check(ru(n,s)),t.gte=(n,s)=>t.check(Mi(n,s)),t.min=(n,s)=>t.check(Mi(n,s)),t.lt=(n,s)=>t.check(tu(n,s)),t.lte=(n,s)=>t.check(Oi(n,s)),t.max=(n,s)=>t.check(Oi(n,s)),t.int=n=>t.check(BS(n)),t.safe=n=>t.check(BS(n)),t.positive=n=>t.check(ru(0,n)),t.nonnegative=n=>t.check(Mi(0,n)),t.negative=n=>t.check(tu(0,n)),t.nonpositive=n=>t.check(Oi(0,n)),t.multipleOf=(n,s)=>t.check(nu(n,s)),t.step=(n,s)=>t.check(nu(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(KS,t)}var CM=$("ZodNumberFormat",(t,e)=>{Rw.init(t,e),KS.init(t,e)});function BS(t){return kS(CM,t)}var DM=$("ZodBoolean",(t,e)=>{Aw.init(t,e),Ne.init(t,e)});function He(t){return ES(DM,t)}var OM=$("ZodNull",(t,e)=>{Cw.init(t,e),Ne.init(t,e)});function JS(t){return TS(OM,t)}var MM=$("ZodUnknown",(t,e)=>{Dw.init(t,e),Ne.init(t,e)});function Me(){return IS(MM)}var zM=$("ZodNever",(t,e)=>{Ow.init(t,e),Ne.init(t,e)});function jM(t){return RS(zM,t)}var NM=$("ZodArray",(t,e)=>{Mw.init(t,e),Ne.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(co(r,n)),t.nonempty=r=>t.check(co(1,r)),t.max=(r,n)=>t.check(su(r,n)),t.length=(r,n)=>t.check(ou(r,n)),t.unwrap=()=>t.element});function ie(t,e){return AS(NM,t,e)}var GS=$("ZodObject",(t,e)=>{zw.init(t,e),Ne.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:Me()}),t.loose=()=>t.clone({...t._zod.def,catchall:Me()}),t.strict=()=>t.clone({...t._zod.def,catchall:jM()}),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(e$,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 GS(r)}function pt(t,e){return new GS({type:"object",get shape(){return ye.assignProp(this,"shape",{...t}),this.shape},catchall:Me(),...ye.normalizeParams(e)})}var YS=$("ZodUnion",(t,e)=>{qp.init(t,e),Ne.init(t,e),t.options=e.options});function Ie(t,e){return new YS({type:"union",options:t,...ye.normalizeParams(e)})}var LM=$("ZodDiscriminatedUnion",(t,e)=>{YS.init(t,e),jw.init(t,e)});function of(t,e,r){return new LM({type:"union",options:e,discriminator:t,...ye.normalizeParams(r)})}var qM=$("ZodIntersection",(t,e)=>{Nw.init(t,e),Ne.init(t,e)});function cu(t,e){return new qM({type:"intersection",left:t,right:e})}var FM=$("ZodRecord",(t,e)=>{Lw.init(t,e),Ne.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Ee(t,e,r){return new FM({type:"record",keyType:t,valueType:e,...ye.normalizeParams(r)})}var nf=$("ZodEnum",(t,e)=>{qw.init(t,e),Ne.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 nf({...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 nf({...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 nf({type:"enum",entries:r,...ye.normalizeParams(e)})}var UM=$("ZodLiteral",(t,e)=>{Fw.init(t,e),Ne.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 M(t,e){return new UM({type:"literal",values:Array.isArray(t)?t:[t],...ye.normalizeParams(e)})}var ZM=$("ZodTransform",(t,e)=>{Uw.init(t,e),Ne.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 XS(t){return new ZM({type:"transform",transform:t})}var QS=$("ZodOptional",(t,e)=>{Zw.init(t,e),Ne.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ze(t){return new QS({type:"optional",innerType:t})}var VM=$("ZodNullable",(t,e)=>{Vw.init(t,e),Ne.init(t,e),t.unwrap=()=>t._zod.def.innerType});function HS(t){return new VM({type:"nullable",innerType:t})}var BM=$("ZodDefault",(t,e)=>{Bw.init(t,e),Ne.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function HM(t,e){return new BM({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var WM=$("ZodPrefault",(t,e)=>{Hw.init(t,e),Ne.init(t,e),t.unwrap=()=>t._zod.def.innerType});function KM(t,e){return new WM({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var e$=$("ZodNonOptional",(t,e)=>{Ww.init(t,e),Ne.init(t,e),t.unwrap=()=>t._zod.def.innerType});function JM(t,e){return new e$({type:"nonoptional",innerType:t,...ye.normalizeParams(e)})}var GM=$("ZodCatch",(t,e)=>{Kw.init(t,e),Ne.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function YM(t,e){return new GM({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var XM=$("ZodPipe",(t,e)=>{Jw.init(t,e),Ne.init(t,e),t.in=e.in,t.out=e.out});function sf(t,e){return new XM({type:"pipe",in:t,out:e})}var QM=$("ZodReadonly",(t,e)=>{Gw.init(t,e),Ne.init(t,e)});function ez(t){return new QM({type:"readonly",innerType:t})}var t$=$("ZodCustom",(t,e)=>{Yw.init(t,e),Ne.init(t,e)});function tz(t){let e=new st({check:"custom"});return e._zod.check=t,e}function r$(t,e){return CS(t$,t??(()=>!0),e)}function rz(t,e={}){return DS(t$,t,e)}function nz(t){let e=tz(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 af(t,e){return sf(XS(t),e)}Ut(Xw());var uf="2025-11-25";var n$=[uf,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],un="io.modelcontextprotocol/related-task",lu="2.0",Be=r$(t=>t!==null&&(typeof t=="object"||typeof t=="function")),s$=Ie([w(),ve().int()]),o$=w(),H8=pt({ttl:ve().optional(),pollInterval:ve().optional()}),sz=A({ttl:ve().optional()}),oz=A({taskId:w()}),lf=pt({progressToken:s$.optional(),[un]:oz.optional()}),Ot=A({_meta:lf.optional()}),Li=Ot.extend({task:sz.optional()}),i$=t=>Li.safeParse(t).success,Ge=A({method:w(),params:Ot.loose().optional()}),Zt=A({_meta:lf.optional()}),Vt=A({method:w(),params:Zt.loose().optional()}),Ye=pt({_meta:lf.optional()}),du=Ie([w(),ve().int()]),a$=A({jsonrpc:M(lu),id:du,...Ge.shape}).strict(),df=t=>a$.safeParse(t).success,c$=A({jsonrpc:M(lu),...Vt.shape}).strict(),u$=t=>c$.safeParse(t).success,pf=A({jsonrpc:M(lu),id:du,result:Ye}).strict(),qi=t=>pf.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 ff=A({jsonrpc:M(lu),id:du.optional(),error:A({code:ve().int(),message:w(),data:Me().optional()})}).strict();var l$=t=>ff.safeParse(t).success;var d$=Ie([a$,c$,pf,ff]),W8=Ie([pf,ff]),pu=Ye.strict(),iz=Zt.extend({requestId:du.optional(),reason:w().optional()}),fu=Vt.extend({method:M("notifications/cancelled"),params:iz}),az=A({src:w(),mimeType:w().optional(),sizes:ie(w()).optional(),theme:wt(["light","dark"]).optional()}),Fi=A({icons:ie(az).optional()}),lo=A({name:w(),title:w().optional()}),p$=lo.extend({...lo.shape,...Fi.shape,version:w(),websiteUrl:w().optional(),description:w().optional()}),cz=cu(A({applyDefaults:He().optional()}),Ee(w(),Me())),uz=af(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,cu(A({form:cz.optional(),url:Be.optional()}),Ee(w(),Me()).optional())),lz=pt({list:Be.optional(),cancel:Be.optional(),requests:pt({sampling:pt({createMessage:Be.optional()}).optional(),elicitation:pt({create:Be.optional()}).optional()}).optional()}),dz=pt({list:Be.optional(),cancel:Be.optional(),requests:pt({tools:pt({call:Be.optional()}).optional()}).optional()}),pz=A({experimental:Ee(w(),Be).optional(),sampling:A({context:Be.optional(),tools:Be.optional()}).optional(),elicitation:uz.optional(),roots:A({listChanged:He().optional()}).optional(),tasks:lz.optional(),extensions:Ee(w(),Be).optional()}),fz=Ot.extend({protocolVersion:w(),capabilities:pz,clientInfo:p$}),mf=Ge.extend({method:M("initialize"),params:fz});var mz=A({experimental:Ee(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:dz.optional(),extensions:Ee(w(),Be).optional()}),hz=Ye.extend({protocolVersion:w(),capabilities:mz,serverInfo:p$,instructions:w().optional()}),hf=Vt.extend({method:M("notifications/initialized"),params:Zt.optional()});var mu=Ge.extend({method:M("ping"),params:Ot.optional()}),gz=A({progress:ve(),total:ze(ve()),message:ze(w())}),yz=A({...Zt.shape,...gz.shape,progressToken:s$}),hu=Vt.extend({method:M("notifications/progress"),params:yz}),vz=Ot.extend({cursor:o$.optional()}),Ui=Ge.extend({params:vz.optional()}),Zi=Ye.extend({nextCursor:o$.optional()}),_z=wt(["working","input_required","completed","failed","cancelled"]),Vi=A({taskId:w(),status:_z,ttl:Ie([ve(),JS()]),createdAt:w(),lastUpdatedAt:w(),pollInterval:ze(ve()),statusMessage:ze(w())}),po=Ye.extend({task:Vi}),bz=Zt.merge(Vi),Bi=Vt.extend({method:M("notifications/tasks/status"),params:bz}),gu=Ge.extend({method:M("tasks/get"),params:Ot.extend({taskId:w()})}),yu=Ye.merge(Vi),vu=Ge.extend({method:M("tasks/result"),params:Ot.extend({taskId:w()})}),K8=Ye.loose(),_u=Ui.extend({method:M("tasks/list")}),bu=Zi.extend({tasks:ie(Vi)}),wu=Ge.extend({method:M("tasks/cancel"),params:Ot.extend({taskId:w()})}),f$=Ye.merge(Vi),m$=A({uri:w(),mimeType:ze(w()),_meta:Ee(w(),Me()).optional()}),h$=m$.extend({text:w()}),gf=w().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),g$=m$.extend({blob:gf}),Hi=wt(["user","assistant"]),fo=A({audience:ie(Hi).optional(),priority:ve().min(0).max(1).optional(),lastModified:ji.datetime({offset:!0}).optional()}),y$=A({...lo.shape,...Fi.shape,uri:w(),description:ze(w()),mimeType:ze(w()),size:ze(ve()),annotations:fo.optional(),_meta:ze(pt({}))}),wz=A({...lo.shape,...Fi.shape,uriTemplate:w(),description:ze(w()),mimeType:ze(w()),annotations:fo.optional(),_meta:ze(pt({}))}),Sz=Ui.extend({method:M("resources/list")}),$z=Zi.extend({resources:ie(y$)}),xz=Ui.extend({method:M("resources/templates/list")}),Pz=Zi.extend({resourceTemplates:ie(wz)}),yf=Ot.extend({uri:w()}),kz=yf,Ez=Ge.extend({method:M("resources/read"),params:kz}),Tz=Ye.extend({contents:ie(Ie([h$,g$]))}),Iz=Vt.extend({method:M("notifications/resources/list_changed"),params:Zt.optional()}),Rz=yf,Az=Ge.extend({method:M("resources/subscribe"),params:Rz}),Cz=yf,Dz=Ge.extend({method:M("resources/unsubscribe"),params:Cz}),Oz=Zt.extend({uri:w()}),Mz=Vt.extend({method:M("notifications/resources/updated"),params:Oz}),zz=A({name:w(),description:ze(w()),required:ze(He())}),jz=A({...lo.shape,...Fi.shape,description:ze(w()),arguments:ze(ie(zz)),_meta:ze(pt({}))}),Nz=Ui.extend({method:M("prompts/list")}),Lz=Zi.extend({prompts:ie(jz)}),qz=Ot.extend({name:w(),arguments:Ee(w(),w()).optional()}),Fz=Ge.extend({method:M("prompts/get"),params:qz}),vf=A({type:M("text"),text:w(),annotations:fo.optional(),_meta:Ee(w(),Me()).optional()}),_f=A({type:M("image"),data:gf,mimeType:w(),annotations:fo.optional(),_meta:Ee(w(),Me()).optional()}),bf=A({type:M("audio"),data:gf,mimeType:w(),annotations:fo.optional(),_meta:Ee(w(),Me()).optional()}),Uz=A({type:M("tool_use"),name:w(),id:w(),input:Ee(w(),Me()),_meta:Ee(w(),Me()).optional()}),Zz=A({type:M("resource"),resource:Ie([h$,g$]),annotations:fo.optional(),_meta:Ee(w(),Me()).optional()}),Vz=y$.extend({type:M("resource_link")}),wf=Ie([vf,_f,bf,Vz,Zz]),Bz=A({role:Hi,content:wf}),Hz=Ye.extend({description:w().optional(),messages:ie(Bz)}),Wz=Vt.extend({method:M("notifications/prompts/list_changed"),params:Zt.optional()}),Kz=A({title:w().optional(),readOnlyHint:He().optional(),destructiveHint:He().optional(),idempotentHint:He().optional(),openWorldHint:He().optional()}),Jz=A({taskSupport:wt(["required","optional","forbidden"]).optional()}),v$=A({...lo.shape,...Fi.shape,description:w().optional(),inputSchema:A({type:M("object"),properties:Ee(w(),Be).optional(),required:ie(w()).optional()}).catchall(Me()),outputSchema:A({type:M("object"),properties:Ee(w(),Be).optional(),required:ie(w()).optional()}).catchall(Me()).optional(),annotations:Kz.optional(),execution:Jz.optional(),_meta:Ee(w(),Me()).optional()}),Sf=Ui.extend({method:M("tools/list")}),Gz=Zi.extend({tools:ie(v$)}),Su=Ye.extend({content:ie(wf).default([]),structuredContent:Ee(w(),Me()).optional(),isError:He().optional()}),J8=Su.or(Ye.extend({toolResult:Me()})),Yz=Li.extend({name:w(),arguments:Ee(w(),Me()).optional()}),Wi=Ge.extend({method:M("tools/call"),params:Yz}),Xz=Vt.extend({method:M("notifications/tools/list_changed"),params:Zt.optional()}),G8=A({autoRefresh:He().default(!0),debounceMs:ve().int().nonnegative().default(300)}),Ki=wt(["debug","info","notice","warning","error","critical","alert","emergency"]),Qz=Ot.extend({level:Ki}),$f=Ge.extend({method:M("logging/setLevel"),params:Qz}),ej=Zt.extend({level:Ki,logger:w().optional(),data:Me()}),tj=Vt.extend({method:M("notifications/message"),params:ej}),rj=A({name:w().optional()}),nj=A({hints:ie(rj).optional(),costPriority:ve().min(0).max(1).optional(),speedPriority:ve().min(0).max(1).optional(),intelligencePriority:ve().min(0).max(1).optional()}),sj=A({mode:wt(["auto","required","none"]).optional()}),oj=A({type:M("tool_result"),toolUseId:w().describe("The unique identifier for the corresponding tool call."),content:ie(wf).default([]),structuredContent:A({}).loose().optional(),isError:He().optional(),_meta:Ee(w(),Me()).optional()}),ij=of("type",[vf,_f,bf]),uu=of("type",[vf,_f,bf,Uz,oj]),aj=A({role:Hi,content:Ie([uu,ie(uu)]),_meta:Ee(w(),Me()).optional()}),cj=Li.extend({messages:ie(aj),modelPreferences:nj.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(v$).optional(),toolChoice:sj.optional()}),uj=Ge.extend({method:M("sampling/createMessage"),params:cj}),Ji=Ye.extend({model:w(),stopReason:ze(wt(["endTurn","stopSequence","maxTokens"]).or(w())),role:Hi,content:ij}),xf=Ye.extend({model:w(),stopReason:ze(wt(["endTurn","stopSequence","maxTokens","toolUse"]).or(w())),role:Hi,content:Ie([uu,ie(uu)])}),lj=A({type:M("boolean"),title:w().optional(),description:w().optional(),default:He().optional()}),dj=A({type:M("string"),title:w().optional(),description:w().optional(),minLength:ve().optional(),maxLength:ve().optional(),format:wt(["email","uri","date","date-time"]).optional(),default:w().optional()}),pj=A({type:wt(["number","integer"]),title:w().optional(),description:w().optional(),minimum:ve().optional(),maximum:ve().optional(),default:ve().optional()}),fj=A({type:M("string"),title:w().optional(),description:w().optional(),enum:ie(w()),default:w().optional()}),mj=A({type:M("string"),title:w().optional(),description:w().optional(),oneOf:ie(A({const:w(),title:w()})),default:w().optional()}),hj=A({type:M("string"),title:w().optional(),description:w().optional(),enum:ie(w()),enumNames:ie(w()).optional(),default:w().optional()}),gj=Ie([fj,mj]),yj=A({type:M("array"),title:w().optional(),description:w().optional(),minItems:ve().optional(),maxItems:ve().optional(),items:A({type:M("string"),enum:ie(w())}),default:ie(w()).optional()}),vj=A({type:M("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()}),_j=Ie([yj,vj]),bj=Ie([hj,gj,_j]),wj=Ie([bj,lj,dj,pj]),Sj=Li.extend({mode:M("form").optional(),message:w(),requestedSchema:A({type:M("object"),properties:Ee(w(),wj),required:ie(w()).optional()})}),$j=Li.extend({mode:M("url"),message:w(),elicitationId:w(),url:w().url()}),xj=Ie([Sj,$j]),Pj=Ge.extend({method:M("elicitation/create"),params:xj}),kj=Zt.extend({elicitationId:w()}),Ej=Vt.extend({method:M("notifications/elicitation/complete"),params:kj}),mo=Ye.extend({action:wt(["accept","decline","cancel"]),content:af(t=>t===null?void 0:t,Ee(w(),Ie([w(),ve(),He(),ie(w())])).optional())}),Tj=A({type:M("ref/resource"),uri:w()});var Ij=A({type:M("ref/prompt"),name:w()}),Rj=Ot.extend({ref:Ie([Ij,Tj]),argument:A({name:w(),value:w()}),context:A({arguments:Ee(w(),w()).optional()}).optional()}),Aj=Ge.extend({method:M("completion/complete"),params:Rj});var Cj=Ye.extend({completion:pt({values:ie(w()).max(100),total:ze(ve().int()),hasMore:ze(He())})}),Dj=A({uri:w().startsWith("file://"),name:w().optional(),_meta:Ee(w(),Me()).optional()}),Oj=Ge.extend({method:M("roots/list"),params:Ot.optional()}),Pf=Ye.extend({roots:ie(Dj)}),Mj=Vt.extend({method:M("notifications/roots/list_changed"),params:Zt.optional()}),Y8=Ie([mu,mf,Aj,$f,Fz,Nz,Sz,xz,Ez,Az,Dz,Wi,Sf,gu,vu,_u,wu]),X8=Ie([fu,hu,hf,Mj,Bi]),Q8=Ie([pu,Ji,xf,mo,Pf,yu,bu,po]),eY=Ie([mu,uj,Pj,Oj,gu,vu,_u,wu]),tY=Ie([fu,hu,tj,Mz,Iz,Xz,Wz,Bi,Ej]),rY=Ie([pu,hz,Cj,Hz,Lz,$z,Pz,Tz,Su,Gz,yu,bu,po]),W=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===oe.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new cf(s.elicitations,r)}return new t(e,r,n)}},cf=class extends W{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(oe.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ln(t){return t==="completed"||t==="failed"||t==="cancelled"}var b$=Symbol("Let zodToJsonSchema decide on which parser to use");var _$={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"},w$=t=>typeof t=="string"?{..._$,name:t}:{..._$,...t};var S$=t=>{let e=w$(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 kf(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ae(t,e,r,n,s){t[e]=r,kf(t,e,n,s)}var $u=(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"?$u(e,t.currentPath):e.join("/")}}function $$(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 x$(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 xu(t,e){return Z(t.type._def,e)}var k$=(t,e)=>Z(t.innerType._def,e);function Ef(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Ef(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 zj(t,e)}}var zj=(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 E$(t,e){return{...Z(t.innerType._def,e),default:t.defaultValue()}}function T$(t,e){return e.effectStrategy==="input"?Z(t.schema._def,e):je(e)}function I$(t){return{type:"string",enum:Array.from(t.values)}}var jj=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function R$(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(jj(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 A$(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 Tf,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:()=>(Tf===void 0&&(Tf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Tf),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 Pu(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(`^${If(n.value,e)}`),n.message,e);break;case"endsWith":ft(r,RegExp(`${If(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(If(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 If(t,e){return e.patternStrategy==="escape"?Lj(t):t}var Nj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Lj(t){let e="";for(let r=0;r<t.length;r++)Nj.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:C$(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ae(t,"pattern",C$(e,n),r,n)}function C$(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
|
|
244
|
+
path: iss.path ? [${ns(_)}, ...iss.path] : [${ns(_)}]
|
|
245
|
+
})));`),p.write(`newResult[${ns(_)}] = ${b}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let v=p.compile();return(_,b)=>v(d,_,b)},s,o=po,i=!Qc.jitless,c=i&&Ap.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 b=l.shape;for(let P of l.keys){let x=b[P],N=x._zod.run({value:f[P],issues:[]},p),k=x._zod.optin==="optional"&&x._zod.optout==="optional";N instanceof Promise?m.push(N.then(O=>k?lw(O,d,P,f):iu(O,d,P))):k?lw(N,d,P,f):iu(N,d,P)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let h=[],y=l.keySet,v=u._zod,_=v.def.type;for(let b of Object.keys(f)){if(y.has(b))continue;if(_==="never"){h.push(b);continue}let P=v.run({value:f[b],issues:[]},p);P instanceof Promise?m.push(P.then(x=>iu(x,d,b))):iu(P,d,b)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function dw(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=>nr(o,n,Vt())))}),e}var Hp=$("$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=>Oi(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=>dw(i,r,t,n)):dw(o,r,t,n)}}),Jw=$("$ZodDiscriminatedUnion",(t,e)=>{Hp.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=Ci(()=>{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(!po(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)}}),Gw=$("$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])=>pw(r,c,u)):pw(r,o,i)}});function Vp(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(fo(t)&&fo(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=Vp(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=Vp(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 pw(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),ss(t))return t;let n=Vp(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 Yw=$("$ZodRecord",(t,e)=>{ke.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!fo(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(...Sr(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Sr(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=>nr(u,n,Vt())),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(...Sr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Sr(i,c.issues)),r.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}});var Xw=$("$ZodEnum",(t,e)=>{ke.init(t,e);let r=Tp(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Cp.has(typeof n)).map(n=>typeof n=="string"?un(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}}),Qw=$("$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"?un(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 eS=$("$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 Ur;return r.value=s,r}}),tS=$("$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(`^(${Oi(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)}),rS=$("$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(`^(${Oi(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)}),nS=$("$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=>fw(o,e)):fw(s,e)}});function fw(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var sS=$("$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))}),oS=$("$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=>mw(o,t)):mw(s,t)}});function mw(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 iS=$("$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=>nr(i,n,Vt()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>nr(o,n,Vt()))},input:r.value}),r.issues=[]),r)}});var aS=$("$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=>hw(o,e,n)):hw(s,e,n)}});function hw(t,e,r){return ss(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var cS=$("$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(gw):gw(s)}});function gw(t){return t.value=Object.freeze(t.value),t}var uS=$("$ZodCustom",(t,e)=>{st.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=>yw(o,r,n,t));yw(s,r,n,t)}});function yw(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(Mp(s))}}var fM=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},mM=()=>{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 ${fM(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${ru(n.values[0])}`:`Invalid option: expected one of ${eu(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":""}: ${eu(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 lS(){return{localeError:mM()}}var Wp=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 hM(){return new Wp}var Ni=hM();function dS(t,e){return new t({type:"string",...U(e)})}function pS(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...U(e)})}function Kp(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...U(e)})}function fS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...U(e)})}function mS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...U(e)})}function hS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...U(e)})}function gS(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...U(e)})}function yS(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...U(e)})}function vS(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...U(e)})}function _S(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...U(e)})}function bS(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...U(e)})}function wS(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...U(e)})}function SS(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...U(e)})}function $S(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...U(e)})}function xS(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...U(e)})}function PS(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...U(e)})}function kS(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...U(e)})}function TS(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...U(e)})}function ES(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...U(e)})}function IS(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...U(e)})}function RS(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...U(e)})}function AS(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...U(e)})}function CS(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...U(e)})}function DS(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...U(e)})}function OS(t,e){return new t({type:"string",format:"date",check:"string_format",...U(e)})}function MS(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...U(e)})}function zS(t,e){return new t({type:"string",format:"duration",check:"string_format",...U(e)})}function jS(t,e){return new t({type:"number",checks:[],...U(e)})}function NS(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...U(e)})}function LS(t,e){return new t({type:"boolean",...U(e)})}function FS(t,e){return new t({type:"null",...U(e)})}function qS(t){return new t({type:"unknown"})}function US(t,e){return new t({type:"never",...U(e)})}function cu(t,e){return new Up({check:"less_than",...U(e),value:t,inclusive:!1})}function Li(t,e){return new Up({check:"less_than",...U(e),value:t,inclusive:!0})}function uu(t,e){return new Zp({check:"greater_than",...U(e),value:t,inclusive:!1})}function Fi(t,e){return new Zp({check:"greater_than",...U(e),value:t,inclusive:!0})}function lu(t,e){return new Jb({check:"multiple_of",...U(e),value:t})}function du(t,e){return new Yb({check:"max_length",...U(e),maximum:t})}function mo(t,e){return new Xb({check:"min_length",...U(e),minimum:t})}function pu(t,e){return new Qb({check:"length_equals",...U(e),length:t})}function Jp(t,e){return new ew({check:"string_format",format:"regex",...U(e),pattern:t})}function Gp(t){return new tw({check:"string_format",format:"lowercase",...U(t)})}function Yp(t){return new rw({check:"string_format",format:"uppercase",...U(t)})}function Xp(t,e){return new nw({check:"string_format",format:"includes",...U(e),includes:t})}function Qp(t,e){return new sw({check:"string_format",format:"starts_with",...U(e),prefix:t})}function ef(t,e){return new ow({check:"string_format",format:"ends_with",...U(e),suffix:t})}function os(t){return new iw({check:"overwrite",tx:t})}function tf(t){return os(e=>e.normalize(t))}function rf(){return os(t=>t.trim())}function nf(){return os(t=>t.toLowerCase())}function sf(){return os(t=>t.toUpperCase())}function ZS(t,e,r){return new t({type:"array",element:e,...U(r)})}function VS(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 ho(t){return!!t._zod}function ln(t,e){return ho(t)?zi(t,e):t.safeParse(e)}function fu(t){if(!t)return;let e;if(ho(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function HS(t){if(ho(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 Ui={};rt(Ui,{ZodISODate:()=>KS,ZodISODateTime:()=>WS,ZodISODuration:()=>GS,ZodISOTime:()=>JS,date:()=>af,datetime:()=>of,duration:()=>uf,time:()=>cf});var WS=$("ZodISODateTime",(t,e)=>{Iw.init(t,e),Oe.init(t,e)});function of(t){return DS(WS,t)}var KS=$("ZodISODate",(t,e)=>{Rw.init(t,e),Oe.init(t,e)});function af(t){return OS(KS,t)}var JS=$("ZodISOTime",(t,e)=>{Aw.init(t,e),Oe.init(t,e)});function cf(t){return MS(JS,t)}var GS=$("ZodISODuration",(t,e)=>{Cw.init(t,e),Oe.init(t,e)});function uf(t){return zS(GS,t)}var YS=(t,e)=>{nu.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>gb(t,r)},flatten:{value:r=>hb(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},p8=$("ZodError",YS),Zi=$("ZodError",YS,{Parent:Error});var XS=yb(Zi),QS=vb(Zi),e$=jp(Zi),t$=Np(Zi);var Ne=$("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)=>wr(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>XS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>e$(t,r,n),t.parseAsync=async(r,n)=>QS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>t$(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(pz(r,n)),t.superRefine=r=>t.check(fz(r)),t.overwrite=r=>t.check(os(r)),t.optional=()=>ze(t),t.nullable=()=>s$(t),t.nullish=()=>ze(s$(t)),t.nonoptional=r=>oz(t,r),t.array=()=>ie(t),t.or=r=>Ie([t,r]),t.and=r=>hu(t,r),t.transform=r=>df(t,l$(r)),t.default=r=>rz(t,r),t.prefault=r=>sz(t,r),t.catch=r=>az(t,r),t.pipe=r=>df(t,r),t.readonly=()=>lz(t),t.describe=r=>{let n=t.clone();return Ni.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Ni.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Ni.get(t);let n=t.clone();return Ni.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),o$=$("_ZodString",(t,e)=>{au.init(t,e),Ne.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(Jp(...n)),t.includes=(...n)=>t.check(Xp(...n)),t.startsWith=(...n)=>t.check(Qp(...n)),t.endsWith=(...n)=>t.check(ef(...n)),t.min=(...n)=>t.check(mo(...n)),t.max=(...n)=>t.check(du(...n)),t.length=(...n)=>t.check(pu(...n)),t.nonempty=(...n)=>t.check(mo(1,...n)),t.lowercase=n=>t.check(Gp(n)),t.uppercase=n=>t.check(Yp(n)),t.trim=()=>t.check(rf()),t.normalize=(...n)=>t.check(tf(...n)),t.toLowerCase=()=>t.check(nf()),t.toUpperCase=()=>t.check(sf())}),xM=$("ZodString",(t,e)=>{au.init(t,e),o$.init(t,e),t.email=r=>t.check(pS(PM,r)),t.url=r=>t.check(yS(kM,r)),t.jwt=r=>t.check(CS(qM,r)),t.emoji=r=>t.check(vS(TM,r)),t.guid=r=>t.check(Kp(r$,r)),t.uuid=r=>t.check(fS(mu,r)),t.uuidv4=r=>t.check(mS(mu,r)),t.uuidv6=r=>t.check(hS(mu,r)),t.uuidv7=r=>t.check(gS(mu,r)),t.nanoid=r=>t.check(_S(EM,r)),t.guid=r=>t.check(Kp(r$,r)),t.cuid=r=>t.check(bS(IM,r)),t.cuid2=r=>t.check(wS(RM,r)),t.ulid=r=>t.check(SS(AM,r)),t.base64=r=>t.check(IS(NM,r)),t.base64url=r=>t.check(RS(LM,r)),t.xid=r=>t.check($S(CM,r)),t.ksuid=r=>t.check(xS(DM,r)),t.ipv4=r=>t.check(PS(OM,r)),t.ipv6=r=>t.check(kS(MM,r)),t.cidrv4=r=>t.check(TS(zM,r)),t.cidrv6=r=>t.check(ES(jM,r)),t.e164=r=>t.check(AS(FM,r)),t.datetime=r=>t.check(of(r)),t.date=r=>t.check(af(r)),t.time=r=>t.check(cf(r)),t.duration=r=>t.check(uf(r))});function w(t){return dS(xM,t)}var Oe=$("ZodStringFormat",(t,e)=>{Ee.init(t,e),o$.init(t,e)}),PM=$("ZodEmail",(t,e)=>{bw.init(t,e),Oe.init(t,e)});var r$=$("ZodGUID",(t,e)=>{vw.init(t,e),Oe.init(t,e)});var mu=$("ZodUUID",(t,e)=>{_w.init(t,e),Oe.init(t,e)});var kM=$("ZodURL",(t,e)=>{ww.init(t,e),Oe.init(t,e)});var TM=$("ZodEmoji",(t,e)=>{Sw.init(t,e),Oe.init(t,e)});var EM=$("ZodNanoID",(t,e)=>{$w.init(t,e),Oe.init(t,e)});var IM=$("ZodCUID",(t,e)=>{xw.init(t,e),Oe.init(t,e)});var RM=$("ZodCUID2",(t,e)=>{Pw.init(t,e),Oe.init(t,e)});var AM=$("ZodULID",(t,e)=>{kw.init(t,e),Oe.init(t,e)});var CM=$("ZodXID",(t,e)=>{Tw.init(t,e),Oe.init(t,e)});var DM=$("ZodKSUID",(t,e)=>{Ew.init(t,e),Oe.init(t,e)});var OM=$("ZodIPv4",(t,e)=>{Dw.init(t,e),Oe.init(t,e)});var MM=$("ZodIPv6",(t,e)=>{Ow.init(t,e),Oe.init(t,e)});var zM=$("ZodCIDRv4",(t,e)=>{Mw.init(t,e),Oe.init(t,e)});var jM=$("ZodCIDRv6",(t,e)=>{zw.init(t,e),Oe.init(t,e)});var NM=$("ZodBase64",(t,e)=>{Nw.init(t,e),Oe.init(t,e)});var LM=$("ZodBase64URL",(t,e)=>{Lw.init(t,e),Oe.init(t,e)});var FM=$("ZodE164",(t,e)=>{Fw.init(t,e),Oe.init(t,e)});var qM=$("ZodJWT",(t,e)=>{qw.init(t,e),Oe.init(t,e)});var i$=$("ZodNumber",(t,e)=>{Bp.init(t,e),Ne.init(t,e),t.gt=(n,s)=>t.check(uu(n,s)),t.gte=(n,s)=>t.check(Fi(n,s)),t.min=(n,s)=>t.check(Fi(n,s)),t.lt=(n,s)=>t.check(cu(n,s)),t.lte=(n,s)=>t.check(Li(n,s)),t.max=(n,s)=>t.check(Li(n,s)),t.int=n=>t.check(n$(n)),t.safe=n=>t.check(n$(n)),t.positive=n=>t.check(uu(0,n)),t.nonnegative=n=>t.check(Fi(0,n)),t.negative=n=>t.check(cu(0,n)),t.nonpositive=n=>t.check(Li(0,n)),t.multipleOf=(n,s)=>t.check(lu(n,s)),t.step=(n,s)=>t.check(lu(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 jS(i$,t)}var UM=$("ZodNumberFormat",(t,e)=>{Uw.init(t,e),i$.init(t,e)});function n$(t){return NS(UM,t)}var ZM=$("ZodBoolean",(t,e)=>{Zw.init(t,e),Ne.init(t,e)});function He(t){return LS(ZM,t)}var VM=$("ZodNull",(t,e)=>{Vw.init(t,e),Ne.init(t,e)});function a$(t){return FS(VM,t)}var BM=$("ZodUnknown",(t,e)=>{Bw.init(t,e),Ne.init(t,e)});function Me(){return qS(BM)}var HM=$("ZodNever",(t,e)=>{Hw.init(t,e),Ne.init(t,e)});function WM(t){return US(HM,t)}var KM=$("ZodArray",(t,e)=>{Ww.init(t,e),Ne.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(mo(r,n)),t.nonempty=r=>t.check(mo(1,r)),t.max=(r,n)=>t.check(du(r,n)),t.length=(r,n)=>t.check(pu(r,n)),t.unwrap=()=>t.element});function ie(t,e){return ZS(KM,t,e)}var c$=$("ZodObject",(t,e)=>{Kw.init(t,e),Ne.init(t,e),ye.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>St(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Me()}),t.loose=()=>t.clone({...t._zod.def,catchall:Me()}),t.strict=()=>t.clone({...t._zod.def,catchall:WM()}),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(d$,t,r[0]),t.required=(...r)=>ye.required(p$,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 c$(r)}function pt(t,e){return new c$({type:"object",get shape(){return ye.assignProp(this,"shape",{...t}),this.shape},catchall:Me(),...ye.normalizeParams(e)})}var u$=$("ZodUnion",(t,e)=>{Hp.init(t,e),Ne.init(t,e),t.options=e.options});function Ie(t,e){return new u$({type:"union",options:t,...ye.normalizeParams(e)})}var JM=$("ZodDiscriminatedUnion",(t,e)=>{u$.init(t,e),Jw.init(t,e)});function pf(t,e,r){return new JM({type:"union",options:e,discriminator:t,...ye.normalizeParams(r)})}var GM=$("ZodIntersection",(t,e)=>{Gw.init(t,e),Ne.init(t,e)});function hu(t,e){return new GM({type:"intersection",left:t,right:e})}var YM=$("ZodRecord",(t,e)=>{Yw.init(t,e),Ne.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Te(t,e,r){return new YM({type:"record",keyType:t,valueType:e,...ye.normalizeParams(r)})}var lf=$("ZodEnum",(t,e)=>{Xw.init(t,e),Ne.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 lf({...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 lf({...e,checks:[],...ye.normalizeParams(s),entries:o})}});function St(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new lf({type:"enum",entries:r,...ye.normalizeParams(e)})}var XM=$("ZodLiteral",(t,e)=>{Qw.init(t,e),Ne.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 M(t,e){return new XM({type:"literal",values:Array.isArray(t)?t:[t],...ye.normalizeParams(e)})}var QM=$("ZodTransform",(t,e)=>{eS.init(t,e),Ne.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 l$(t){return new QM({type:"transform",transform:t})}var d$=$("ZodOptional",(t,e)=>{tS.init(t,e),Ne.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ze(t){return new d$({type:"optional",innerType:t})}var ez=$("ZodNullable",(t,e)=>{rS.init(t,e),Ne.init(t,e),t.unwrap=()=>t._zod.def.innerType});function s$(t){return new ez({type:"nullable",innerType:t})}var tz=$("ZodDefault",(t,e)=>{nS.init(t,e),Ne.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function rz(t,e){return new tz({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var nz=$("ZodPrefault",(t,e)=>{sS.init(t,e),Ne.init(t,e),t.unwrap=()=>t._zod.def.innerType});function sz(t,e){return new nz({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var p$=$("ZodNonOptional",(t,e)=>{oS.init(t,e),Ne.init(t,e),t.unwrap=()=>t._zod.def.innerType});function oz(t,e){return new p$({type:"nonoptional",innerType:t,...ye.normalizeParams(e)})}var iz=$("ZodCatch",(t,e)=>{iS.init(t,e),Ne.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function az(t,e){return new iz({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var cz=$("ZodPipe",(t,e)=>{aS.init(t,e),Ne.init(t,e),t.in=e.in,t.out=e.out});function df(t,e){return new cz({type:"pipe",in:t,out:e})}var uz=$("ZodReadonly",(t,e)=>{cS.init(t,e),Ne.init(t,e)});function lz(t){return new uz({type:"readonly",innerType:t})}var f$=$("ZodCustom",(t,e)=>{uS.init(t,e),Ne.init(t,e)});function dz(t){let e=new st({check:"custom"});return e._zod.check=t,e}function m$(t,e){return VS(f$,t??(()=>!0),e)}function pz(t,e={}){return BS(f$,t,e)}function fz(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 ff(t,e){return df(l$(t),e)}Vt(lS());var hf="2025-11-25";var h$=[hf,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],dn="io.modelcontextprotocol/related-task",yu="2.0",Be=m$(t=>t!==null&&(typeof t=="object"||typeof t=="function")),g$=Ie([w(),ve().int()]),y$=w(),oY=pt({ttl:ve().optional(),pollInterval:ve().optional()}),mz=A({ttl:ve().optional()}),hz=A({taskId:w()}),gf=pt({progressToken:g$.optional(),[dn]:hz.optional()}),jt=A({_meta:gf.optional()}),Vi=jt.extend({task:mz.optional()}),v$=t=>Vi.safeParse(t).success,Ge=A({method:w(),params:jt.loose().optional()}),Bt=A({_meta:gf.optional()}),Ht=A({method:w(),params:Bt.loose().optional()}),Ye=pt({_meta:gf.optional()}),vu=Ie([w(),ve().int()]),_$=A({jsonrpc:M(yu),id:vu,...Ge.shape}).strict(),yf=t=>_$.safeParse(t).success,b$=A({jsonrpc:M(yu),...Ht.shape}).strict(),w$=t=>b$.safeParse(t).success,vf=A({jsonrpc:M(yu),id:vu,result:Ye}).strict(),Bi=t=>vf.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 _f=A({jsonrpc:M(yu),id:vu.optional(),error:A({code:ve().int(),message:w(),data:Me().optional()})}).strict();var S$=t=>_f.safeParse(t).success;var $$=Ie([_$,b$,vf,_f]),iY=Ie([vf,_f]),_u=Ye.strict(),gz=Bt.extend({requestId:vu.optional(),reason:w().optional()}),bu=Ht.extend({method:M("notifications/cancelled"),params:gz}),yz=A({src:w(),mimeType:w().optional(),sizes:ie(w()).optional(),theme:St(["light","dark"]).optional()}),Hi=A({icons:ie(yz).optional()}),go=A({name:w(),title:w().optional()}),x$=go.extend({...go.shape,...Hi.shape,version:w(),websiteUrl:w().optional(),description:w().optional()}),vz=hu(A({applyDefaults:He().optional()}),Te(w(),Me())),_z=ff(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,hu(A({form:vz.optional(),url:Be.optional()}),Te(w(),Me()).optional())),bz=pt({list:Be.optional(),cancel:Be.optional(),requests:pt({sampling:pt({createMessage:Be.optional()}).optional(),elicitation:pt({create:Be.optional()}).optional()}).optional()}),wz=pt({list:Be.optional(),cancel:Be.optional(),requests:pt({tools:pt({call:Be.optional()}).optional()}).optional()}),Sz=A({experimental:Te(w(),Be).optional(),sampling:A({context:Be.optional(),tools:Be.optional()}).optional(),elicitation:_z.optional(),roots:A({listChanged:He().optional()}).optional(),tasks:bz.optional(),extensions:Te(w(),Be).optional()}),$z=jt.extend({protocolVersion:w(),capabilities:Sz,clientInfo:x$}),bf=Ge.extend({method:M("initialize"),params:$z});var xz=A({experimental:Te(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:wz.optional(),extensions:Te(w(),Be).optional()}),Pz=Ye.extend({protocolVersion:w(),capabilities:xz,serverInfo:x$,instructions:w().optional()}),wf=Ht.extend({method:M("notifications/initialized"),params:Bt.optional()});var wu=Ge.extend({method:M("ping"),params:jt.optional()}),kz=A({progress:ve(),total:ze(ve()),message:ze(w())}),Tz=A({...Bt.shape,...kz.shape,progressToken:g$}),Su=Ht.extend({method:M("notifications/progress"),params:Tz}),Ez=jt.extend({cursor:y$.optional()}),Wi=Ge.extend({params:Ez.optional()}),Ki=Ye.extend({nextCursor:y$.optional()}),Iz=St(["working","input_required","completed","failed","cancelled"]),Ji=A({taskId:w(),status:Iz,ttl:Ie([ve(),a$()]),createdAt:w(),lastUpdatedAt:w(),pollInterval:ze(ve()),statusMessage:ze(w())}),yo=Ye.extend({task:Ji}),Rz=Bt.merge(Ji),Gi=Ht.extend({method:M("notifications/tasks/status"),params:Rz}),$u=Ge.extend({method:M("tasks/get"),params:jt.extend({taskId:w()})}),xu=Ye.merge(Ji),Pu=Ge.extend({method:M("tasks/result"),params:jt.extend({taskId:w()})}),aY=Ye.loose(),ku=Wi.extend({method:M("tasks/list")}),Tu=Ki.extend({tasks:ie(Ji)}),Eu=Ge.extend({method:M("tasks/cancel"),params:jt.extend({taskId:w()})}),P$=Ye.merge(Ji),k$=A({uri:w(),mimeType:ze(w()),_meta:Te(w(),Me()).optional()}),T$=k$.extend({text:w()}),Sf=w().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),E$=k$.extend({blob:Sf}),Yi=St(["user","assistant"]),vo=A({audience:ie(Yi).optional(),priority:ve().min(0).max(1).optional(),lastModified:Ui.datetime({offset:!0}).optional()}),I$=A({...go.shape,...Hi.shape,uri:w(),description:ze(w()),mimeType:ze(w()),size:ze(ve()),annotations:vo.optional(),_meta:ze(pt({}))}),Az=A({...go.shape,...Hi.shape,uriTemplate:w(),description:ze(w()),mimeType:ze(w()),annotations:vo.optional(),_meta:ze(pt({}))}),Cz=Wi.extend({method:M("resources/list")}),Dz=Ki.extend({resources:ie(I$)}),Oz=Wi.extend({method:M("resources/templates/list")}),Mz=Ki.extend({resourceTemplates:ie(Az)}),$f=jt.extend({uri:w()}),zz=$f,jz=Ge.extend({method:M("resources/read"),params:zz}),Nz=Ye.extend({contents:ie(Ie([T$,E$]))}),Lz=Ht.extend({method:M("notifications/resources/list_changed"),params:Bt.optional()}),Fz=$f,qz=Ge.extend({method:M("resources/subscribe"),params:Fz}),Uz=$f,Zz=Ge.extend({method:M("resources/unsubscribe"),params:Uz}),Vz=Bt.extend({uri:w()}),Bz=Ht.extend({method:M("notifications/resources/updated"),params:Vz}),Hz=A({name:w(),description:ze(w()),required:ze(He())}),Wz=A({...go.shape,...Hi.shape,description:ze(w()),arguments:ze(ie(Hz)),_meta:ze(pt({}))}),Kz=Wi.extend({method:M("prompts/list")}),Jz=Ki.extend({prompts:ie(Wz)}),Gz=jt.extend({name:w(),arguments:Te(w(),w()).optional()}),Yz=Ge.extend({method:M("prompts/get"),params:Gz}),xf=A({type:M("text"),text:w(),annotations:vo.optional(),_meta:Te(w(),Me()).optional()}),Pf=A({type:M("image"),data:Sf,mimeType:w(),annotations:vo.optional(),_meta:Te(w(),Me()).optional()}),kf=A({type:M("audio"),data:Sf,mimeType:w(),annotations:vo.optional(),_meta:Te(w(),Me()).optional()}),Xz=A({type:M("tool_use"),name:w(),id:w(),input:Te(w(),Me()),_meta:Te(w(),Me()).optional()}),Qz=A({type:M("resource"),resource:Ie([T$,E$]),annotations:vo.optional(),_meta:Te(w(),Me()).optional()}),ej=I$.extend({type:M("resource_link")}),Tf=Ie([xf,Pf,kf,ej,Qz]),tj=A({role:Yi,content:Tf}),rj=Ye.extend({description:w().optional(),messages:ie(tj)}),nj=Ht.extend({method:M("notifications/prompts/list_changed"),params:Bt.optional()}),sj=A({title:w().optional(),readOnlyHint:He().optional(),destructiveHint:He().optional(),idempotentHint:He().optional(),openWorldHint:He().optional()}),oj=A({taskSupport:St(["required","optional","forbidden"]).optional()}),R$=A({...go.shape,...Hi.shape,description:w().optional(),inputSchema:A({type:M("object"),properties:Te(w(),Be).optional(),required:ie(w()).optional()}).catchall(Me()),outputSchema:A({type:M("object"),properties:Te(w(),Be).optional(),required:ie(w()).optional()}).catchall(Me()).optional(),annotations:sj.optional(),execution:oj.optional(),_meta:Te(w(),Me()).optional()}),Ef=Wi.extend({method:M("tools/list")}),ij=Ki.extend({tools:ie(R$)}),Iu=Ye.extend({content:ie(Tf).default([]),structuredContent:Te(w(),Me()).optional(),isError:He().optional()}),cY=Iu.or(Ye.extend({toolResult:Me()})),aj=Vi.extend({name:w(),arguments:Te(w(),Me()).optional()}),Xi=Ge.extend({method:M("tools/call"),params:aj}),cj=Ht.extend({method:M("notifications/tools/list_changed"),params:Bt.optional()}),uY=A({autoRefresh:He().default(!0),debounceMs:ve().int().nonnegative().default(300)}),Qi=St(["debug","info","notice","warning","error","critical","alert","emergency"]),uj=jt.extend({level:Qi}),If=Ge.extend({method:M("logging/setLevel"),params:uj}),lj=Bt.extend({level:Qi,logger:w().optional(),data:Me()}),dj=Ht.extend({method:M("notifications/message"),params:lj}),pj=A({name:w().optional()}),fj=A({hints:ie(pj).optional(),costPriority:ve().min(0).max(1).optional(),speedPriority:ve().min(0).max(1).optional(),intelligencePriority:ve().min(0).max(1).optional()}),mj=A({mode:St(["auto","required","none"]).optional()}),hj=A({type:M("tool_result"),toolUseId:w().describe("The unique identifier for the corresponding tool call."),content:ie(Tf).default([]),structuredContent:A({}).loose().optional(),isError:He().optional(),_meta:Te(w(),Me()).optional()}),gj=pf("type",[xf,Pf,kf]),gu=pf("type",[xf,Pf,kf,Xz,hj]),yj=A({role:Yi,content:Ie([gu,ie(gu)]),_meta:Te(w(),Me()).optional()}),vj=Vi.extend({messages:ie(yj),modelPreferences:fj.optional(),systemPrompt:w().optional(),includeContext:St(["none","thisServer","allServers"]).optional(),temperature:ve().optional(),maxTokens:ve().int(),stopSequences:ie(w()).optional(),metadata:Be.optional(),tools:ie(R$).optional(),toolChoice:mj.optional()}),_j=Ge.extend({method:M("sampling/createMessage"),params:vj}),ea=Ye.extend({model:w(),stopReason:ze(St(["endTurn","stopSequence","maxTokens"]).or(w())),role:Yi,content:gj}),Rf=Ye.extend({model:w(),stopReason:ze(St(["endTurn","stopSequence","maxTokens","toolUse"]).or(w())),role:Yi,content:Ie([gu,ie(gu)])}),bj=A({type:M("boolean"),title:w().optional(),description:w().optional(),default:He().optional()}),wj=A({type:M("string"),title:w().optional(),description:w().optional(),minLength:ve().optional(),maxLength:ve().optional(),format:St(["email","uri","date","date-time"]).optional(),default:w().optional()}),Sj=A({type:St(["number","integer"]),title:w().optional(),description:w().optional(),minimum:ve().optional(),maximum:ve().optional(),default:ve().optional()}),$j=A({type:M("string"),title:w().optional(),description:w().optional(),enum:ie(w()),default:w().optional()}),xj=A({type:M("string"),title:w().optional(),description:w().optional(),oneOf:ie(A({const:w(),title:w()})),default:w().optional()}),Pj=A({type:M("string"),title:w().optional(),description:w().optional(),enum:ie(w()),enumNames:ie(w()).optional(),default:w().optional()}),kj=Ie([$j,xj]),Tj=A({type:M("array"),title:w().optional(),description:w().optional(),minItems:ve().optional(),maxItems:ve().optional(),items:A({type:M("string"),enum:ie(w())}),default:ie(w()).optional()}),Ej=A({type:M("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()}),Ij=Ie([Tj,Ej]),Rj=Ie([Pj,kj,Ij]),Aj=Ie([Rj,bj,wj,Sj]),Cj=Vi.extend({mode:M("form").optional(),message:w(),requestedSchema:A({type:M("object"),properties:Te(w(),Aj),required:ie(w()).optional()})}),Dj=Vi.extend({mode:M("url"),message:w(),elicitationId:w(),url:w().url()}),Oj=Ie([Cj,Dj]),Mj=Ge.extend({method:M("elicitation/create"),params:Oj}),zj=Bt.extend({elicitationId:w()}),jj=Ht.extend({method:M("notifications/elicitation/complete"),params:zj}),_o=Ye.extend({action:St(["accept","decline","cancel"]),content:ff(t=>t===null?void 0:t,Te(w(),Ie([w(),ve(),He(),ie(w())])).optional())}),Nj=A({type:M("ref/resource"),uri:w()});var Lj=A({type:M("ref/prompt"),name:w()}),Fj=jt.extend({ref:Ie([Lj,Nj]),argument:A({name:w(),value:w()}),context:A({arguments:Te(w(),w()).optional()}).optional()}),qj=Ge.extend({method:M("completion/complete"),params:Fj});var Uj=Ye.extend({completion:pt({values:ie(w()).max(100),total:ze(ve().int()),hasMore:ze(He())})}),Zj=A({uri:w().startsWith("file://"),name:w().optional(),_meta:Te(w(),Me()).optional()}),Vj=Ge.extend({method:M("roots/list"),params:jt.optional()}),Af=Ye.extend({roots:ie(Zj)}),Bj=Ht.extend({method:M("notifications/roots/list_changed"),params:Bt.optional()}),lY=Ie([wu,bf,qj,If,Yz,Kz,Cz,Oz,jz,qz,Zz,Xi,Ef,$u,Pu,ku,Eu]),dY=Ie([bu,Su,wf,Bj,Gi]),pY=Ie([_u,ea,Rf,_o,Af,xu,Tu,yo]),fY=Ie([wu,_j,Mj,Vj,$u,Pu,ku,Eu]),mY=Ie([bu,Su,dj,Bz,Lz,cj,nj,Gi,jj]),hY=Ie([_u,Pz,Uj,rj,Jz,Dz,Mz,Nz,Iu,ij,xu,Tu,yo]),K=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 mf(s.elicitations,r)}return new t(e,r,n)}},mf=class extends K{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(oe.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function pn(t){return t==="completed"||t==="failed"||t==="cancelled"}var C$=Symbol("Let zodToJsonSchema decide on which parser to use");var A$={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"},D$=t=>typeof t=="string"?{...A$,name:t}:{...A$,...t};var O$=t=>{let e=D$(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 Cf(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ae(t,e,r,n,s){t[e]=r,Cf(t,e,n,s)}var Ru=(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"?Ru(e,t.currentPath):e.join("/")}}function M$(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==E.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 z$(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 j$(){return{type:"boolean"}}function Au(t,e){return Z(t.type._def,e)}var N$=(t,e)=>Z(t.innerType._def,e);function Df(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Df(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 Hj(t,e)}}var Hj=(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 L$(t,e){return{...Z(t.innerType._def,e),default:t.defaultValue()}}function F$(t,e){return e.effectStrategy==="input"?Z(t.schema._def,e):je(e)}function q$(t){return{type:"string",enum:Array.from(t.values)}}var Wj=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function U$(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(Wj(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 Z$(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 Of,sr={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:()=>(Of===void 0&&(Of=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Of),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 Cu(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":or(r,"email",n.message,e);break;case"format:idn-email":or(r,"idn-email",n.message,e);break;case"pattern:zod":ft(r,sr.email,n.message,e);break}break;case"url":or(r,"uri",n.message,e);break;case"uuid":or(r,"uuid",n.message,e);break;case"regex":ft(r,n.regex,n.message,e);break;case"cuid":ft(r,sr.cuid,n.message,e);break;case"cuid2":ft(r,sr.cuid2,n.message,e);break;case"startsWith":ft(r,RegExp(`^${Mf(n.value,e)}`),n.message,e);break;case"endsWith":ft(r,RegExp(`${Mf(n.value,e)}$`),n.message,e);break;case"datetime":or(r,"date-time",n.message,e);break;case"date":or(r,"date",n.message,e);break;case"time":or(r,"time",n.message,e);break;case"duration":or(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(Mf(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&or(r,"ipv4",n.message,e),n.version!=="v4"&&or(r,"ipv6",n.message,e);break}case"base64url":ft(r,sr.base64url,n.message,e);break;case"jwt":ft(r,sr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&ft(r,sr.ipv4Cidr,n.message,e),n.version!=="v4"&&ft(r,sr.ipv6Cidr,n.message,e);break}case"emoji":ft(r,sr.emoji(),n.message,e);break;case"ulid":{ft(r,sr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{or(r,"binary",n.message,e);break}case"contentEncoding:base64":{ae(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{ft(r,sr.base64,n.message,e);break}}break}case"nanoid":ft(r,sr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Mf(t,e){return e.patternStrategy==="escape"?Jj(t):t}var Kj=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Jj(t){let e="";for(let r=0;r<t.length;r++)Kj.has(t[r])||(e+="\\"),e+=t[r];return e}function or(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:V$(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ae(t,"pattern",V$(e,n),r,n)}function V$(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
246
|
]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
|
|
246
247
|
]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
|
|
247
248
|
`:`[${n[c]}\r
|
|
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 ku(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]})??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,...s}=Pu(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}=xu(t.keyType._def,e);return{...r,propertyNames:s}}}return r}function D$(t,e){if(e.mapStrategy==="record")return ku(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 O$(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 M$(t){return t.target==="openAi"?void 0:{not:je({...t,currentPath:[...t.currentPath,"not"]})}}function z$(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Gi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function N$(t,e){if(e.target==="openApi3")return j$(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Gi&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=Gi[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 j$(t,e)}var j$=(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 L$(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:Gi[t.innerType._def.typeName],nullable:!0}:{type:[Gi[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 q$(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",kf(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 F$(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=Fj(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=qj(t,e);return i!==void 0&&(n.additionalProperties=i),n}function qj(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 Fj(t){try{return t.isOptional()}catch{return!0}}var U$=(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 Z$=(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 V$(t,e){return Z(t.type._def,e)}function B$(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 H$(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 W$(t){return{not:je(t)}}function K$(t){return je(t)}var J$=(t,e)=>Z(t.innerType._def,e);var G$=(t,e,r)=>{switch(e){case T.ZodString:return Pu(t,r);case T.ZodNumber:return q$(t,r);case T.ZodObject:return F$(t,r);case T.ZodBigInt:return x$(t,r);case T.ZodBoolean:return P$();case T.ZodDate:return Ef(t,r);case T.ZodUndefined:return W$(r);case T.ZodNull:return z$(r);case T.ZodArray:return $$(t,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return N$(t,r);case T.ZodIntersection:return R$(t,r);case T.ZodTuple:return H$(t,r);case T.ZodRecord:return ku(t,r);case T.ZodLiteral:return A$(t,r);case T.ZodEnum:return I$(t);case T.ZodNativeEnum:return O$(t);case T.ZodNullable:return L$(t,r);case T.ZodOptional:return U$(t,r);case T.ZodMap:return D$(t,r);case T.ZodSet:return B$(t,r);case T.ZodLazy:return()=>t.getter()._def;case T.ZodPromise:return V$(t,r);case T.ZodNaN:case T.ZodNever:return M$(r);case T.ZodEffects:return T$(t,r);case T.ZodAny:return je(r);case T.ZodUnknown:return K$(r);case T.ZodDefault:return E$(t,r);case T.ZodBranded:return xu(t,r);case T.ZodReadonly:return J$(t,r);case T.ZodCatch:return k$(t,r);case T.ZodPipeline:return Z$(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!==b$)return a}if(n&&!r){let a=Uj(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=G$(t,t.typeName,e),i=typeof o=="function"?Z(o(),e):o;if(i&&Zj(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var Uj=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:$u(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}},Zj=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Eu=(t,e)=>{let r=S$(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,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)??je(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 Rf(t){let r=iu(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=OS(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Af(t,e){let r=cn(t,e);if(!r.success)throw r.error;return r.data}var Vj=6e4,Tu=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(fu,r=>{this._oncancel(r)}),this.setNotificationHandler(hu,r=>{this._onprogress(r)}),this.setRequestHandler(mu,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(gu,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new W(oe.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(vu,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 W(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new W(oe.InvalidParams,`Task not found: ${o}`);if(!ln(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(ln(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[un]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(_u,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 W(oe.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(wu,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new W(oe.InvalidParams,`Task not found: ${r.params.taskId}`);if(ln(s.status))throw new W(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 W(oe.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof W?s:new W(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),W.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),qi(o)||l$(o)?this._onresponse(o):df(o)?this._onrequest(o,i):u$(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=W.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?.[un]?.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=i$(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 W(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),qi(e))n(e);else{let i=new W(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(qi(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),qi(e))s(e);else{let i=W.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 W?i:new W(oe.InternalError,String(i))}}return}let o;try{let i=await this.request(e,po,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new W(oe.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},ln(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new W(oe.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new W(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 W?i:new W(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||{},[un]: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 W?b:new W(oe.RequestTimeout,String(b));l(_)};this._responseHandlers.set(p,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return l(b);try{let _=cn(r,b.result);_.success?u(_.data):l(_.error)}catch(_){l(_)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??Vj,y=()=>m(W.fromError(oe.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,y,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},yu,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},bu,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},f$,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||{},[un]: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||{},[un]: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||{},[un]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Rf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=Af(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=Rf(e);this._notificationHandlers.set(n,s=>{let o=Af(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"&&df(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new W(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 W(oe.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new W(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 W(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=Bi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),ln(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 W(oe.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(ln(a.status))throw new W(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=Bi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),ln(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function Y$(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function X$(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];Y$(i)&&Y$(o)?r[s]={...i,...o}:r[s]=o}return r}var XE=Gy(xP(),1),QE=Gy(YE(),1);function R2(){let t=new XE.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,QE.default)(t),t}var ql=class{constructor(e){this._ajv=e??R2()}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 Fl=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},Ji,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},mo,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 eT(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 tT(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 Ul=class extends Tu{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ki.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 ql,this.setRequestHandler(mf,n=>this._oninitialize(n)),this.setNotificationHandler(hf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler($f,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Ki.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Fl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=X$(this._capabilities,e)}setRequestHandler(e,r){let s=iu(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(uo(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=cn(Wi,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new W(oe.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=cn(po,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new W(oe.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=cn(Su,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new W(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){tT(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&eT(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:n$.includes(r)?r:uf,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"},pu)}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},xf,r):this.request({method:"sampling/createMessage",params:e},Ji,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},mo,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},mo,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new W(oe.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof W?i:new W(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},Pf,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 nT 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
|
|
249
|
+
]`;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 Du(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===E.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]})??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===E.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=Cu(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===E.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===E.ZodBranded&&t.keyType._def.type._def.typeName===E.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=Au(t.keyType._def,e);return{...r,propertyNames:s}}}return r}function B$(t,e){if(e.mapStrategy==="record")return Du(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 H$(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 W$(t){return t.target==="openAi"?void 0:{not:je({...t,currentPath:[...t.currentPath,"not"]})}}function K$(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ta={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function G$(t,e){if(e.target==="openApi3")return J$(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ta&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=ta[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 J$(t,e)}var J$=(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 Y$(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:ta[t.innerType._def.typeName],nullable:!0}:{type:[ta[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 X$(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",Cf(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 Q$(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=Yj(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=Gj(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Gj(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 Yj(t){try{return t.isOptional()}catch{return!0}}var ex=(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 tx=(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 rx(t,e){return Z(t.type._def,e)}function nx(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 sx(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 ox(t){return{not:je(t)}}function ix(t){return je(t)}var ax=(t,e)=>Z(t.innerType._def,e);var cx=(t,e,r)=>{switch(e){case E.ZodString:return Cu(t,r);case E.ZodNumber:return X$(t,r);case E.ZodObject:return Q$(t,r);case E.ZodBigInt:return z$(t,r);case E.ZodBoolean:return j$();case E.ZodDate:return Df(t,r);case E.ZodUndefined:return ox(r);case E.ZodNull:return K$(r);case E.ZodArray:return M$(t,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return G$(t,r);case E.ZodIntersection:return U$(t,r);case E.ZodTuple:return sx(t,r);case E.ZodRecord:return Du(t,r);case E.ZodLiteral:return Z$(t,r);case E.ZodEnum:return q$(t);case E.ZodNativeEnum:return H$(t);case E.ZodNullable:return Y$(t,r);case E.ZodOptional:return ex(t,r);case E.ZodMap:return B$(t,r);case E.ZodSet:return nx(t,r);case E.ZodLazy:return()=>t.getter()._def;case E.ZodPromise:return rx(t,r);case E.ZodNaN:case E.ZodNever:return W$(r);case E.ZodEffects:return F$(t,r);case E.ZodAny:return je(r);case E.ZodUnknown:return ix(r);case E.ZodDefault:return L$(t,r);case E.ZodBranded:return Au(t,r);case E.ZodReadonly:return ax(t,r);case E.ZodCatch:return N$(t,r);case E.ZodPipeline:return tx(t,r);case E.ZodFunction:case E.ZodVoid:case E.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!==C$)return a}if(n&&!r){let a=Xj(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=cx(t,t.typeName,e),i=typeof o=="function"?Z(o(),e):o;if(i&&Qj(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var Xj=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ru(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}},Qj=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Ou=(t,e)=>{let r=O$(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,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)??je(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 zf(t){let r=fu(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=HS(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function jf(t,e){let r=ln(t,e);if(!r.success)throw r.error;return r.data}var eN=6e4,Mu=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(bu,r=>{this._oncancel(r)}),this.setNotificationHandler(Su,r=>{this._onprogress(r)}),this.setRequestHandler(wu,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler($u,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new K(oe.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(Pu,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 K(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 K(oe.InvalidParams,`Task not found: ${o}`);if(!pn(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(pn(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[dn]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(ku,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 K(oe.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(Eu,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new K(oe.InvalidParams,`Task not found: ${r.params.taskId}`);if(pn(s.status))throw new K(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 K(oe.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof K?s:new K(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),K.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),Bi(o)||S$(o)?this._onresponse(o):yf(o)?this._onrequest(o,i):w$(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=K.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?.[dn]?.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=v$(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 K(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),Bi(e))n(e);else{let i=new K(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(Bi(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),Bi(e))s(e);else{let i=K.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 K?i:new K(oe.InternalError,String(i))}}return}let o;try{let i=await this.request(e,yo,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new K(oe.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},pn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new K(oe.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new K(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 K?i:new K(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=_=>{l(_)};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(_){d(_);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||{},[dn]:c}});let m=_=>{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(_)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(P=>this._onerror(new Error(`Failed to send cancellation: ${P}`)));let b=_ instanceof K?_:new K(oe.RequestTimeout,String(_));l(b)};this._responseHandlers.set(p,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return l(_);try{let b=ln(r,_.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??eN,y=()=>m(K.fromError(oe.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 P=this._responseHandlers.get(p);P?P(b):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(v,{type:"request",message:f,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(p),l(b)})}else this._transport.send(f,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(p),l(_)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},xu,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},Tu,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},P$,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||{},[dn]: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||{},[dn]: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||{},[dn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=zf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=jf(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=zf(e);this._notificationHandlers.set(n,s=>{let o=jf(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"&&yf(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new K(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 K(oe.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new K(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 K(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=Gi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),pn(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 K(oe.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(pn(a.status))throw new K(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=Gi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),pn(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}};function ux(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function lx(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];ux(i)&&ux(o)?r[s]={...i,...o}:r[s]=o}return r}var lE=cv(zP(),1),dE=cv(uE(),1);function F2(){let t=new lE.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,dE.default)(t),t}var Wl=class{constructor(e){this._ajv=e??F2()}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 Kl=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},ea,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},_o,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 pE(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 fE(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 Jl=class extends Mu{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Qi.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 Wl,this.setRequestHandler(bf,n=>this._oninitialize(n)),this.setNotificationHandler(wf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(If,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Qi.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Kl(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=lx(this._capabilities,e)}setRequestHandler(e,r){let s=fu(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(ho(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=ln(Xi,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new K(oe.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=ln(yo,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new K(oe.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=ln(Iu,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new K(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){fE(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&pE(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:h$.includes(r)?r:hf,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"},_u)}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},Rf,r):this.request({method:"sampling/createMessage",params:e},ea,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},_o,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},_o,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new K(oe.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof K?i:new K(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},Af,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 hE from"node:process";var Gl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
250
|
+
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),q2(r)}clear(){this._buffer=void 0}};function q2(t){return $$.parse(JSON.parse(t))}function mE(t){return JSON.stringify(t)+`
|
|
251
|
+
`}var Yl=class{constructor(e=hE.stdin,r=hE.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Gl,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=mE(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{fileURLToPath as aK}from"url";var uy={};rt(uy,{AI_CHAT_TIMEOUT_MS:()=>bE,AI_CONTEXT_BINARY_SAMPLE_BYTES:()=>wE,AI_CONTEXT_MAX_FILE_BYTES:()=>ay,AI_CONTEXT_MAX_TOTAL_BYTES:()=>cy,getTools:()=>J2,handleTool:()=>Q2});import{readFile as U2,stat as Z2}from"fs/promises";import{join as V2}from"path";import{randomUUID as gE}from"crypto";function W(t){let e=Ou(t,{target:"jsonSchema7"});return delete e.$schema,delete e.additionalProperties,e.type==="object"&&!e.required&&(e.required=[]),e}var B2=g.object({title:g.string().describe("Document title"),metadata:g.record(g.string()).optional().describe("Optional key-value metadata"),kind:g.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(),yE=g.object({provider:g.string().describe("Provider ID (e.g. 'ollama', 'gemini', 'codex', 'claude')"),prompt:g.string().describe("Chat prompt to send"),model:g.string().optional().describe("Model override"),system:g.string().optional().describe("System prompt"),files:g.array(g.string()).optional().describe("File paths to include as context"),allow_external_paths:g.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:B2.describe("If provided, automatically save the response as a workspace document with the given title and metadata. Returns document ID in the result.")}),vE=g.object({provider:g.string().describe("Provider ID"),file_paths:g.array(g.string()).min(1).describe("File paths to analyze"),question:g.string().describe("Question to ask about the files"),save_to_file:g.string().optional().describe("Path to save the analysis result"),allow_external_paths:g.boolean().optional().describe("Opt-in: allow absolute file paths outside the workspace base directory. Default false.")}),_E=g.object({providers:g.array(g.string()).min(1).describe("List of provider IDs to compare"),prompt:g.string().describe("Prompt to send to all providers"),aggregate_provider:g.string().optional().describe("Provider ID to synthesize all responses into a unified document. If omitted, returns raw comparisons only."),aggregate_prompt:g.string().optional().describe("Custom synthesis prompt. Default: synthesize and identify agreements/disagreements.")}),bE=18e4,ay=1e6,cy=4e6,wE=4096;function H2(t,e){return e?.get(t.id)??Ot(t.type)}function W2(t){return!t||t.length===0?"":["","Attached file context:",...t.map(e=>`--- ${e.path} ---
|
|
252
|
+
${e.content??""}`)].join(`
|
|
253
|
+
`)}async function K2(t,e,r){if(t.type!=="ollama")return t.chat(e);let n=H2(t,r.providerPolicies),s=new cn({baseDir:r.baseDir,tools:Ws(n)?Pi():oo()}),o=`${e.prompt}${W2(e.files)}`;return s.chat(t,{...e,prompt:o})}async function SE(t){let e=t.allowExternalPaths?Xv:on,r=[],n=0;for(let s of t.paths){let o=e(s,t.baseDir),i=await Z2(o);if(!i.isFile())throw new Error(`AI context path is not a file: ${o}`);if(i.size>ay)throw new Error(`File exceeds per-file AI context limit (${i.size} > ${ay} bytes): ${o}`);if(n+i.size>cy)throw new Error(`Total AI context size exceeds limit (${n+i.size} > ${cy} bytes).`);n+=i.size;let a=await U2(o),c=Buffer.isBuffer(a)?a:Buffer.from(a);if(c.subarray(0,wE).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 $E(t,e,r,n){if(t)try{t.write({traceId:gE(),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 xE(t,e,r){let n=`${r.tool}-${Date.now()}-${gE().slice(0,8)}`,s=V2(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
254
|
`);return ge(s,i+`
|
|
252
|
-
`+e.text),s}function
|
|
255
|
+
`+e.text),s}function J2(){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:W(yE)},{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:W(vE)},{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:W(_E)}]}async function G2(t,e){let r=yE.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&&$E(e.traceWriter,o.id,r.files,{tool:"ai_chat",promptSummary:r.prompt.slice(0,80)});let i=r.files?.length?await SE({paths:r.files,baseDir:n,allowExternalPaths:r.allow_external_paths}):void 0,a=e.aiChatTimeoutMs??bE,c=new AbortController,u=!1,l,d=K2(o,{prompt:r.prompt,model:r.model,system:r.system,workspaceBaseDir:n,timeoutMs:a,signal:c.signal,files:i},{baseDir:n,providerPolicies:e.providerPolicies});d.catch(()=>{});let p;try{p=await Promise.race([d,new Promise((h,y)=>{l=setTimeout(()=>{u=!0,c.abort(new Error("__AI_CHAT_TIMEOUT__")),y(new Error("__AI_CHAT_TIMEOUT__"))},a)})])}catch(h){if(u&&e.jobManager){let y=e.jobManager.submit({provider:r.provider,prompt:r.prompt,timeout:6e5,saveAsDocument:r.save_as_document}),v=r.save_as_document?`
|
|
253
256
|
**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
257
|
|
|
255
|
-
**Job ID:** ${y}${
|
|
258
|
+
**Job ID:** ${y}${v}
|
|
256
259
|
|
|
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 y=D(h);try{let
|
|
260
|
+
Use \`cli_job_status\` to check progress.`}]}}throw h}finally{l!==void 0&&clearTimeout(l)}r.allow_external_paths&&(p={...p,text:Js(p.text)});let f="",m=!1;if(r.save_as_document&&e.documentManager)try{f=`
|
|
261
|
+
**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 y=D(h);try{let v=xE(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
262
|
\u26A0 Document save failed: ${y}
|
|
260
|
-
**Pending save:** ${
|
|
263
|
+
**Pending save:** ${v}`}catch(v){f=`
|
|
261
264
|
\u26A0 Document save failed: ${y}
|
|
262
|
-
\u26A0 Pending-save dump also failed: ${D(
|
|
265
|
+
\u26A0 Pending-save dump also failed: ${D(v)}`}}return{content:[{type:"text",text:`**Provider:** ${p.provider}
|
|
263
266
|
**Model:** ${p.model}${f}
|
|
264
267
|
|
|
265
|
-
${p.text}`}],...m?{isError:!0}:{}}}async function
|
|
268
|
+
${p.text}`}],...m?{isError:!0}:{}}}async function Y2(t,e){let r=vE.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&&$E(e.traceWriter,o.id,r.file_paths,{tool:"ai_analyze_files",promptSummary:r.question.slice(0,80)});let c=`${(await SE({paths:r.file_paths,baseDir:n,allowExternalPaths:r.allow_external_paths})).map(({path:p,content:f})=>`--- ${p} ---
|
|
266
269
|
${f}`).join(`
|
|
267
270
|
|
|
268
271
|
`)}
|
|
269
272
|
|
|
270
273
|
---
|
|
271
274
|
|
|
272
|
-
Question: ${r.question}`,u=await o.chat({prompt:c,workspaceBaseDir:n});r.allow_external_paths&&(u={...u,text:
|
|
275
|
+
Question: ${r.question}`,u=await o.chat({prompt:c,workspaceBaseDir:n});r.allow_external_paths&&(u={...u,text:Js(u.text)});let l="",d=!1;if(r.save_to_file)try{let p=Zt(r.save_to_file,n);ge(p,u.text),l=`
|
|
273
276
|
|
|
274
|
-
_Result saved to: ${r.save_to_file}_`}catch(p){d=!0;let f=D(p);try{let m=
|
|
277
|
+
_Result saved to: ${r.save_to_file}_`}catch(p){d=!0;let f=D(p);try{let m=xE(n,u,{tool:"ai_analyze_files",originalTarget:r.save_to_file,extraMetadata:{question:r.question,file_paths:r.file_paths.join(", ")}});l=`
|
|
275
278
|
|
|
276
279
|
\u26A0 Save to ${r.save_to_file} failed: ${f}
|
|
277
280
|
**Pending save:** ${m}`}catch(m){l=`
|
|
@@ -280,7 +283,7 @@ _Result saved to: ${r.save_to_file}_`}catch(p){d=!0;let f=D(p);try{let m=pT(n,u,
|
|
|
280
283
|
\u26A0 Pending-save dump also failed: ${D(m)}`}}return{content:[{type:"text",text:`**Provider:** ${u.provider}
|
|
281
284
|
**Files analyzed:** ${r.file_paths.join(", ")}
|
|
282
285
|
|
|
283
|
-
${u.text}${l}`}],...d?{isError:!0}:{}}}async function
|
|
286
|
+
${u.text}${l}`}],...d?{isError:!0}:{}}}async function X2(t,e){let r=_E.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
287
|
|
|
285
288
|
**Prompt:** ${r.prompt}
|
|
286
289
|
|
|
@@ -299,47 +302,52 @@ ${o}`;try{i=(await c.chat({prompt:d})).text}catch(p){i=`[Aggregation failed: ${D
|
|
|
299
302
|
|
|
300
303
|
# Synthesis
|
|
301
304
|
|
|
302
|
-
${i}`),{content:[{type:"text",text:a}]}}async function
|
|
305
|
+
${i}`),{content:[{type:"text",text:a}]}}async function Q2(t,e,r){switch(t){case"ai_chat":return G2(e,r);case"ai_analyze_files":return Y2(e,r);case"ai_compare":return X2(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var My={};rt(My,{getTools:()=>ly,handleTool:()=>KI});var Xl=g.object({topic:g.string().describe("Topic for the debate"),providers:g.array(g.string()).min(1).describe("Provider IDs to participate"),max_rounds:g.number().int().positive().optional().default(3).describe("Maximum debate rounds"),goal:g.string().optional().describe("Quality goal for enhanced debate mode (enables quality validation loop)"),validator:g.string().optional().describe("Provider ID for quality validation (agent-tier recommended)"),min_rounds:g.number().int().positive().optional().default(2).describe("Minimum rounds before validation (default: 2)")}),Ql=g.object({items:g.array(g.object({provider:g.string().describe("Provider that produced the content"),content:g.string().describe("Content to validate"),task:g.string().describe("Original task description")})).min(1).describe("Items to cross-validate"),validators:g.array(g.string()).optional().describe("Provider IDs to use as validators (agent-tier only)"),criteria:g.string().optional().describe("Custom validation criteria")}),ed=g.object({session_id:g.string().describe("Session ID to check")}),td=g.object({topic:g.string().describe("Topic for the debate"),providers:g.array(g.string()).min(1).describe("Provider IDs to participate"),goal:g.string().optional().describe("Quality goal for the debate"),save_document:g.boolean().optional().default(!0).describe("Save debate as a workspace document (default: true)")}),rd=g.object({debate_id:g.string().describe("Debate session ID"),provider:g.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:g.string().optional().describe(`Claude's opinion. When provider is "claude", this becomes the turn content. Otherwise, injected before the provider responds.`),auto_specialist:g.boolean().optional().default(!1).describe("When true with provider 'claude', automatically select and record a specialist agent recommendation based on the debate topic.")}),nd=g.object({debate_id:g.string().describe("Debate session ID to conclude"),summary:g.string().optional().describe("Claude's final summary of the debate"),quality_scores:g.array(g.object({provider:g.string(),score:g.number().min(0).max(1),feedback:g.string()})).optional().describe("Quality assessment of each provider's contribution")}),sd=g.object({document:g.string().describe("Document content to review"),providers:g.array(g.string()).min(1).describe("Provider IDs to review the document"),review_prompt:g.string().optional().describe("Custom review instructions (default: agree/disagree with feedback)"),debate_id:g.string().optional().describe("Link reviews to an existing debate session's workspace document")}),od=g.object({task_id:g.string().describe("Task ID to review changes for")}),id=g.object({task_id:g.string().describe("Task ID whose changes to accept"),message:g.string().optional().describe("Commit message for the merge")}),ad=g.object({task_id:g.string().describe("Task ID whose changes to reject"),reason:g.string().optional().describe("Reason for rejection")}),PE=g.object({agrees:g.union([g.boolean(),g.enum(["true","false"])]).transform(t=>typeof t=="boolean"?t:t==="true"),feedback:g.string().optional().default(""),suggestions:g.string().optional()}),e4=g.object({document_id:g.string().min(1).describe("Workspace document id from workspace_create_document."),provider:g.string().min(1).describe("Provider that authored this individual document.")}),cd=g.object({mode:g.enum(["review","idea"]).optional().default("review").describe("Structured consensus mode. `review` reviews code/documents; `idea` explores improvement ideas."),topic:g.string().min(1).describe("Topic for the structured debate"),scope:g.string().optional().describe("What the leader wants debated (file list or task framing). Defaults to topic when omitted."),goal:g.string().optional().describe("Optional quality goal for the debate"),leader:g.string().optional().describe("Participant ID authorized to approve the final synthesis. Defaults to the session-context leader or the first participant."),participants:g.array(g.string()).min(1).describe("Participant IDs. When `auto_inject_specialists` is true (default), `claude-reviewer`, `claude-qa`, and/or `claude-security` may be added based on the topic."),exclude_participants:g.array(g.string()).optional().describe("Participant IDs to never inject/include. Applied regardless of `auto_inject_specialists`."),auto_inject_specialists:g.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:g.number().int().positive().max(50).optional().describe("Maximum number of rounds. Default: STRUCTURED_DEBATE_DEFAULT_MAX_ROUNDS."),participant_timeout_ms:g.number().int().positive().max(36e5).optional().describe("Optional per-participant inactivity timeout in milliseconds for structured debate provider turns."),individual_review_prompt:g.string().optional().describe("Override the system prompt used for individual-review fan-out."),source_documents:g.array(e4).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:g.array(g.string()).optional().describe("Optional list of files to pass to participants as context."),locale:g.enum(["ko","zh","ja","en"]).optional().describe("Override config locale for moderator text in this debate only.")}),ud=g.object({session_id:g.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),leader_note:g.string().optional().describe("Optional note appended to the synthesis footer under 'Leader approval notes'.")}),ld=g.object({session_id:g.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),additional_rounds:g.union([g.literal(3),g.literal(5),g.literal(10)]).describe("How many extra rounds to run beyond the current round count. Choose one of 3, 5, or 10.")}),dd=g.object({session_id:g.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured"),reason:g.string().optional().describe("Optional rejection reason, captured in the debate transcript footer."),spawn_issue:g.boolean().optional().default(!1).describe("If true, also write an issue_{sessionIdShort}_{YYYYMMDD}_{seq}.md under individual/ listing all non-accepted proposals (rejected/withdrawn/open/inconclusive/superseded). A rejected synthesis is always written.")}),pd=g.object({session_id:g.string().min(1).describe("Structured-debate session ID returned from agent_debate_structured."),participant_id:g.string().min(1).describe("Specialist participant id the host fulfilled (e.g. 'claude-reviewer'). Must match an entry under `pending_host_turns` in `agent_debate_status`."),content:g.string().min(1).describe("Verbatim text the host's native subagent produced. For individual-review handoffs, return the specialist's normal review/proposals text; for consensus-round handoffs, return the JSON contract used for CLI providers."),round:g.number().int().nonnegative().optional().describe("Round number from the matching pending host-turn entry. Individual-review handoffs use round 0. When supplied the moderator rejects mismatched submissions to catch late-arriving stale responses.")});var fd="agent_debate_structured",Xo="agent_debate_approve",Qo="agent_debate_continue",ei="agent_debate_reject",oc="agent_debate_submit_turn";function ic(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 kE(t,e){let r=ic(e);if(r)return r;let n;try{n=cd.parse(t)}catch(o){return At(`Invalid arguments: ${D(o)}`)}let s=t4(n.leader,n.participants,e);if(!s)return At("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(AE(o.sessionId,o.snapshot.status)),o.snapshot.status==="escalated"?i.push(DE(o.sessionId)):o.snapshot.status==="ready-for-approval"?i.push(CE(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
306
|
|
|
304
|
-
`)}],...o.snapshot.status==="error"?{isError:!0}:{}}}catch(o){return
|
|
307
|
+
`)}],...o.snapshot.status==="error"?{isError:!0}:{}}}catch(o){return At(`Failed to start structured debate: ${D(o)}`)}}async function TE(t,e){let r=ic(e);if(r)return r;let n;try{n=ud.parse(t)}catch(s){return At(`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
308
|
|
|
306
|
-
`)}]}}catch(s){return
|
|
309
|
+
`)}]}}catch(s){return At(`Approve failed: ${D(s)}`)}}async function EE(t,e){let r=ic(e);if(r)return r;let n;try{n=ld.parse(t)}catch(s){return At(`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(AE(n.session_id,s.snapshot.status)),s.snapshot.status==="escalated"?o.push(DE(n.session_id)):s.snapshot.status==="ready-for-approval"&&o.push(CE(n.session_id)),{content:[{type:"text",text:o.join(`
|
|
307
310
|
|
|
308
|
-
`)}]}}catch(s){return
|
|
309
|
-
`)}]}}catch(s){return
|
|
310
|
-
`)}function
|
|
311
|
-
`)}function
|
|
311
|
+
`)}]}}catch(s){return At(`Continue failed: ${D(s)}`)}}async function IE(t,e){let r=ic(e);if(r)return r;let n;try{n=pd.parse(t)}catch(s){return At(`Invalid arguments: ${D(s)}`)}try{let s=await e.moderatorEngine.submitHostTurn({sessionId:n.session_id,participantId:n.participant_id,content:n.content,...n.round!==void 0?{round:n.round}:{}});switch(s.outcome.kind){case"accepted":{let o=[`Host turn accepted for participant "${n.participant_id}".`,`Remaining pending host turns: ${s.outcome.remaining}`];return s.outcome.remaining===0?o.push("All pending host turns are in. The moderator round will resume shortly."):o.push(`Continue dispatching the remaining specialists, then call \`${oc}\` for each.`),{content:[{type:"text",text:o.join(`
|
|
312
|
+
`)}]}}case"duplicate":return At(`Host turn for participant "${n.participant_id}" was already submitted in this gate.`);case"round-mismatch":return At(`Round mismatch for participant "${n.participant_id}": expected round ${s.outcome.expectedRound}.`);case"no-pending":return At(`No pending host-turn request for participant "${n.participant_id}" in session "${n.session_id}". The round may have already resumed; check \`agent_debate_status\`.`)}}catch(s){return At(`Submit host turn failed: ${D(s)}`)}}async function RE(t,e){let r=ic(e);if(r)return r;let n;try{n=dd.parse(t)}catch(s){return At(`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}`),i.push(`Synthesis document: ${s.synthesisPath}`),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(`
|
|
313
|
+
`)}]}}catch(s){return At(`Reject failed: ${D(s)}`)}}function t4(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 AE(t,e){return`Session ID: ${t} \u2014 status: ${e}`}function CE(t){return["Next step \u2014 choose one:",`- Approve synthesis: call \`${Xo}\` with { session_id: "${t}" }`,`- Extend debate: call \`${Qo}\` with { session_id: "${t}", additional_rounds: 3 | 5 | 10 }`,`- Abandon session: call \`${ei}\` with { session_id: "${t}" }`].join(`
|
|
314
|
+
`)}function DE(t){return["Debate escalated \u2014 max rounds exhausted with open proposals.","The leader should choose one of:",`- \`${Qo}\` with additional_rounds = 3 | 5 | 10 to run more rounds.`,`- \`${Xo}\` to accept the current synthesis with open items captured.`,`- \`${ei}\` to abandon the session.`,`Session ID: ${t}`].join(`
|
|
315
|
+
`)}function At(t){return{content:[{type:"text",text:t}],isError:!0}}function ly(){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:W(Xl)},{name:"agent_debate_status",title:"Check Debate Status",description:"Check the status and result of a debate session.",inputSchema:W(ed)},{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:W(Ql)},{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:W(td)},{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:W(rd)},{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:W(nd)},{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:W(sd)},{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:W(od)},{name:"agent_changes_accept",title:"Accept File Changes",description:"Accept and merge file changes from an isolated worktree back to the main branch.",inputSchema:W(id)},{name:"agent_changes_reject",title:"Reject File Changes",description:"Reject file changes and clean up the isolated worktree.",inputSchema:W(ad)},{name:fd,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 the leader approves or rejects.",inputSchema:W(cd)},{name:Xo,title:"Approve Structured Debate",description:"Leader-approve a ready-for-approval structured-debate session. Writes the synthesis document and marks the session approved.",inputSchema:W(ud)},{name:Qo,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:W(ld)},{name:ei,title:"Reject Structured Debate",description:"Reject a ready-for-approval (or escalated/leader-timeout) structured-debate session. Writes a rejected synthesis, marks the transcript rejected, and optionally writes an issue document.",inputSchema:W(dd)},{name:oc,title:"Submit Host Turn",description:"Submit a specialist host-turn response. When `agent_debate_status` reports `phase: awaiting-host-turn`, the host runs each `pending_host_turns` entry through the matching native subagent (e.g. agestra-reviewer/qa/security) and posts the verbatim text back here. Round 0 entries are individual reviews; later rounds use the consensus JSON contract. Once every pending specialist has answered, the workflow resumes automatically.",inputSchema:W(pd)}]}import{join as RH}from"path";import{readFileSync as n4}from"fs";import{isAbsolute as s4,join as o4}from"path";function OE(t,e){let r=`${t} ${e??""}`.toLowerCase(),n=[{patterns:[/\bsecurity\b/,/\bvulnerab/,/\bsecret\b/,/\bauth\b/,/\bpermission/,/\bfile\s*access\b/,/보안/,/취약점/,/권한/,/セキュリティ/,/安全审计/],agent:"agestra-security"},{patterns:[/\breview\b/,/\bcode\s*quality\b/,/\bcritique\b/,/\bux\b/,/\bperformance\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 md="claude-reviewer",hd="claude-qa",gd="claude-security",r4={"agestra-reviewer":md,"agestra-qa":hd,"agestra-security":gd};function ME(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=OE(e,r),u=c!==null?r4[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 zE="claude",dy="claude-cli",fy=new Set([md,hd,gd]),ac=Object.freeze({[md]:"agestra-reviewer",[hd]:"agestra-qa",[gd]:"agestra-security"});function i4(t){if(!t.startsWith("---"))return t;let e=t.indexOf(`
|
|
312
316
|
`,3);if(e<0)return t;let r=t.indexOf(`
|
|
313
317
|
---`,e);if(r<0)return t;let n=t.indexOf(`
|
|
314
|
-
`,r+4);return n<0?"":t.slice(n+1)}function J2(t,e){return W2.has(t)?e==="claude-code"?{transport:"task-subagent",agentName:iy[t]}:{transport:"cli-bridge",providerId:oy,agentName:iy[t]}:t===$T?e==="claude-code"?{transport:"read-only-chat",providerId:$T}:{transport:"cli-bridge",providerId:oy}:{transport:"read-only-chat",providerId:t}}function G2(t){if(!(!t||t.length===0))return t.map(e=>({path:e}))}function Y2(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 xT(t,e,r,n,s){if(e.system!==void 0)return e.system;let o=iy[t];if(o===void 0)return;if(s.has(o))return s.get(o);let i=H2(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 ay=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(!B2(e.agentsDir))throw new Error(`ParticipantBridge: agentsDir must be absolute: ${e.agentsDir}`);this.agentsDir=e.agentsDir,this.readFile=e.agentsFileReader??(r=>V2(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??oy,i=this.lookupProviderOrNull(o);if(!i)return this.buildFailure(e,s,`CLI provider "${o}" not registered`);let a=xT(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?xT(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=Y2(e,n.timeoutMs);try{return await this.readOnlyAdapter.chat(r,{prompt:n.prompt,...s!==void 0?{system:s}:{},...n.files!==void 0?{files:G2(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 J2(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 ay(t)}function kT(t,e){return e(t)}var X2=/[.,!?;:]/g,Q2=/\s+/g;function ET(t){return t.toLowerCase().replace(X2," ").replace(Q2," ").trim()}function TT(t){return typeof t.location=="string"&&t.location.length>0}function IT(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 e4(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 t4(t,e){let r=t.proposerIds[0],n=e.proposerIds[0];if(r===n)return{kind:"unrelated"};let s=ET(t.title)===ET(e.title),o=t.severity===e.severity,a=TT(t)&&TT(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 kn=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=IT(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=r4(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(e4(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=IT(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 r4(t){return t.disagree>0||t.revise>0?"dissent":t.missing>0?"pending":t.agree>0?"consensus":"pending"}function RT(t){let e=new kn,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=t4(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 n4=/<proposals>([\s\S]*?)<\/proposals>/i,s4=/<item\b([^>]*)>([\s\S]*?)<\/item>/g,o4=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*"([^"]*)"/g;function cy(t){let e=n4.exec(t);if(!e)return[];let r=e[1],n=[],s,o=new RegExp(s4.source,"g");for(;(s=o.exec(r))!==null;){let i=s[1],a=s[2].trim(),c={},u=new RegExp(o4.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 i4=v.object({title:v.string().min(1),plainSummary:v.string().min(1),originalClaim:v.string().min(1)}),a4=v.object({id:v.string().min(1),stance:v.enum(["agree","disagree","opinion","revise"]),comment:v.string(),proposedItem:i4.optional()}),AT=v.object({provider:v.string().min(1),round:v.number().int().nonnegative(),items:v.array(a4)});function CT(t){return t.issues.map(e=>`${e.path.length>0?`${e.path.join(".")}: `:""}${e.message}`)}function c4(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 uy(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(c4(t),null,2)].join(`
|
|
315
|
-
`)}function
|
|
316
|
-
`)}function
|
|
317
|
-
`)}function
|
|
318
|
-
`)}function
|
|
319
|
-
`)}function
|
|
320
|
-
`)}function
|
|
321
|
-
`)}function
|
|
322
|
-
`)}function
|
|
323
|
-
`)}function KT(t){return t.currentStances.map(e=>`${e.provider} ${xs[e.stance]}${e.automatic?"(\uC790\uB3D9)":""}`).join(", ")}function Go(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} ${xs[r.stance]}`).join(", ")}`}function JT(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} ${xs[o.stance]}`).join(", ")||"-",s=t.conclusion?t.conclusion:Go(t);return`| ${t.id} | ${t.title} | ${t.displayStatus} | ${s} | ${t.proposer} | ${e} | ${r} | ${n} |`}function ly(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: ${m4(n)}`),t.push(`\uB3D9\uC758\uD55C AI: ${HT(n,"agree")}`),t.push(`\uBC18\uB300\uD55C AI: ${HT(n,"disagree")}`),t.push(`\uD604\uC7AC \uC785\uC7A5: ${h4(n)}`),t.push(`\uBCC0\uACBD \uC5EC\uBD80: ${g4(n)}`),t.push(`\uD1A0\uB860/\uADFC\uAC70 \uC704\uCE58: ${y4(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: ${v4(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}: ${xs[s.stance]} - ${s.comment}`)}}function m4(t){return t.conclusion?t.conclusion:Go(t)}function HT(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 h4(t){return t.currentStances.map(e=>`${e.provider} ${xs[e.stance]}${e.automatic?"(\uC790\uB3D9)":""}`).join(", ")}function g4(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 y4(t,e){return Array.from(new Set([e.documents.debate,...t.sourceRefs])).join(", ")}function v4(t){return t.comments.length>0?t.comments.slice(-3).map(e=>`${e.provider}: ${xs[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.":Go(t)}function _4(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 py(t,e){let r;try{r=JSON.parse(t)}catch{return{ok:!1,errors:["Response must be valid JSON."]}}let n=AT.safeParse(r);if(!n.success)return{ok:!1,errors:CT(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 b4,mkdirSync as w4,readFileSync as S4}from"fs";import{join as GT}from"path";var Mt=class{debatesDir;constructor(e){this.debatesDir=GT(e,As)}pathForSession(e){return GT(this.debatesDir,`${e}.consensus.json`)}async write(e){w4(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 b4(r)?JSON.parse(S4(r,"utf-8")):null}};async function fy(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=UT(t.consensusLedger,{provider:o,round:n,maxItems:10});if(a.assignedItems.length===0)continue;t.consensusLedger=ZT(t.consensusLedger,{round:n,provider:o,assignedItemIds:a.assignedItems.map(d=>d.id),totalActiveItems:i,maxItems:10,now:e.nowIso}),await Ps(t,e);let c={prompt:MT(a,t.legacyProposalIdMap),round:n,timeoutMs:t.participantTimeoutMs??24e4,...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){YT(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=dd(t.consensusLedger,{provider:o,round:n,assignedItemIds:a.assignedItems.map(d=>d.id),rawResponse:"",parsedItems:[],validationErrors:[u.failureReason?u.failureReason:"provider failed"]}),await Ps(t,e);continue}s.add(o),P4(t,o);let l=await $4(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=dd(t.consensusLedger,{provider:o,round:n,assignedItemIds:a.assignedItems.map(d=>d.id),rawResponse:l.rawResponse,parsedItems:l.items})):(YT(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=dd(t.consensusLedger,{provider:o,round:n,assignedItemIds:a.assignedItems.map(d=>d.id),rawResponse:l.rawResponse,parsedItems:[],validationErrors:l.errors})),x4(t),await Ps(t,e)}if(await e.setCurrentProvider?.(t,void 0),s.size===0)return}}async function $4(t,e,r,n,s,o){let i=e.assignedItems.map(l=>l.id),a=py(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:zT(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=py(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 Ps(t,e){let r=new Mt(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,pd(t.consensusLedger))}function x4(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 my(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 YT(t,e,r){let n=(t.consecutiveFailures.get(e)??0)+1;t.consecutiveFailures.set(e,n),n>=Md&&(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 P4(t,e){t.consecutiveFailures.delete(e)}function hy(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 XT(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 eI(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 tI(t,e){for(let[r,n]of t)if(n===e)return r;return e}function rI(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 gy(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 ec(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"<unstringifiable error>"}}function ks(t){let e=t.documentPaths.debate;return(e.split(/[\\/]/).pop()??e).replace(/\.md$/,"")}var k4=Object.freeze(["same","different","unsure"]),tc="alias-votes",E4=new Set(k4);function T4(t){return E4.has(t)}function I4(t){let e=`<${tc}>`,r=`</${tc}>`,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 R4(t){let e=`<${tc}>`;return t.includes(e)}var A4=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function C4(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 A4[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]=C4(u),n=s.index+s[0].length}return t.slice(n).trim().length>0?null:e}function nI(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}function yy(t,e){let r=I4(t);if(!r)return R4(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${tc}> without matching </${tc}>`}}:{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(!nI(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(!nI(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(!T4(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,g=typeof y=="string"&&y.length>0?y: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 O4="__";function M4(t){return`${t.proposalA}${O4}${t.proposalB}`}var z4=["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(" "),j4=["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(" "),N4=["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
|
-
`),
|
|
325
|
-
`)}async function
|
|
326
|
-
`)}function
|
|
327
|
-
`)}function
|
|
328
|
-
`)}function
|
|
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}}
|
|
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}:{}};wy(r,["ready-for-approval","escalated","leader-timeout"],"reject");let n=this.sessions.get(e.sessionId),s=n?.debateDocId??ks(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:fH(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=ks(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=cy(s.content);for(let i of o){let a=mI(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=DT(e.mode),s=OT({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??24e4,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=cy(u.text);for(let f of p){let m=mI(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 cI({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??24e4,...e.files.length>0?{files:e.files}:{}});return i.failed?{text:"",failed:!0}:{text:i.text}}}),n=LT(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])))}my(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:lH(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=kn.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:ks(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:ld({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 Mt(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 Mt(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 Mt(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:ks(e),debateDocPath:e.documentPaths.debate,individualPaths:{...e.documentPaths.individual},createdAt:e.createdAt,ledger:e.ledgerState?kn.fromJSON(e.ledgerState):new kn,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:NT(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=XT(r)?kT(s,uI):s,i=this.snapshotAggregatedVotes(e),a=dH(e.phase,r),c=pH(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:rI(o.stance),roundRecorded:o.round,...i?.comment?{reason:i.comment}:{}}}return{proposalId:tI(e.legacyProposalIdMap,n.id),title:n.title,severity:"MEDIUM",proposers:[n.proposer],status:eI(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," ")}`,"",WT({...e.consensusLedger,documents:{...e.consensusLedger.documents,...r.documentPaths.synthesis!==void 0?{synthesis:r.documentPaths.synthesis}:{}}})].join(`
|
|
331
|
-
|
|
318
|
+
`,r+4);return n<0?"":t.slice(n+1)}function a4(t,e){return fy.has(t)?e==="claude-code"?{transport:"task-subagent",agentName:ac[t]}:{transport:"cli-bridge",providerId:dy,agentName:ac[t]}:t===zE?e==="claude-code"?{transport:"read-only-chat",providerId:zE}:{transport:"cli-bridge",providerId:dy}:{transport:"read-only-chat",providerId:t}}function c4(t){if(!(!t||t.length===0))return t.map(e=>({path:e}))}function u4(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 jE(t,e,r,n,s){if(e.system!==void 0)return e.system;let o=ac[t];if(o===void 0)return;if(s.has(o))return s.get(o);let i=o4(r,`${o}.md`),a;try{a=n(i)}catch(u){throw new Error(`specialist prompt unavailable: ${i}: ${D(u)}`)}let c=i4(a).trim();if(c.length===0)throw new Error(`specialist prompt unavailable: ${i} is empty`);return s.set(o,c),c}var py=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(!s4(e.agentsDir))throw new Error(`ParticipantBridge: agentsDir must be absolute: ${e.agentsDir}`);this.agentsDir=e.agentsDir,this.readFile=e.agentsFileReader??(r=>n4(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,`specialist participant "${e}" must be supplied via source_documents on this host (subagent spawner not wired)`);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??dy,i=this.lookupProviderOrNull(o);if(!i)return this.buildFailure(e,s,`CLI provider "${o}" not registered`);let a=jE(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?jE(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=u4(e,n.timeoutMs);try{return await this.readOnlyAdapter.chat(r,{prompt:n.prompt,...s!==void 0?{system:s}:{},...n.files!==void 0?{files:c4(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 a4(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 NE(t){return new py(t)}function LE(t,e){return e(t)}var l4=/[.,!?;:]/g,d4=/\s+/g;function FE(t){return t.toLowerCase().replace(l4," ").replace(d4," ").trim()}function qE(t){return typeof t.location=="string"&&t.location.length>0}function UE(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 p4(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 f4(t,e){let r=t.proposerIds[0],n=e.proposerIds[0];if(r===n)return{kind:"unrelated"};let s=FE(t.title)===FE(e.title),o=t.severity===e.severity,a=qE(t)&&qE(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 En=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=UE(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=m4(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(p4(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=UE(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 m4(t){return t.disagree>0||t.revise>0?"dissent":t.missing>0?"pending":t.agree>0?"consensus":"pending"}function ZE(t){let e=new En,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=f4(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 h4=/<proposals>([\s\S]*?)<\/proposals>/i,g4=/<item\b([^>]*)>([\s\S]*?)<\/item>/g,y4=/([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*"([^"]*)"/g;function yd(t){let e=h4.exec(t);if(!e)return[];let r=e[1],n=[],s,o=new RegExp(g4.source,"g");for(;(s=o.exec(r))!==null;){let i=s[1],a=s[2].trim(),c={},u=new RegExp(y4.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 v4=g.object({title:g.string().min(1),plainSummary:g.string().min(1),originalClaim:g.string().min(1)}),_4=g.object({id:g.string().min(1),stance:g.enum(["agree","disagree","opinion","revise"]),comment:g.string(),proposedItem:v4.optional()}),VE=g.object({provider:g.string().min(1),round:g.number().int().nonnegative(),items:g.array(_4)});function BE(t){return t.issues.map(e=>`${e.path.length>0?`${e.path.join(".")}: `:""}${e.message}`)}function b4(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 my(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(b4(t),null,2)].join(`
|
|
319
|
+
`)}function HE(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(`
|
|
320
|
+
`)}function WE(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(`
|
|
321
|
+
`)}function hy(t,e=new Map){let r=JE(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),"```","",my(t)].join(`
|
|
322
|
+
`)}function KE(t,e,r=new Map){let n=JE(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),"```","",my(t)].join(`
|
|
323
|
+
`)}function JE(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 GE(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 YE(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(`
|
|
324
|
+
`)}function vd(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 w4(s,r,t.participants)}),turns:[],moderatorNotes:[],createdAt:e,updatedAt:e}}function w4(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 gy(t,e){let r=S4(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:QE(n)})),assignedItems:r.map(n=>({id:n.id,title:n.title,plainSummary:n.plainSummary,originalClaim:n.originalClaim,currentSummary:QE(n),recentComments:n.comments.slice(-4)})),responseContract:{allowedStances:["agree","disagree","opinion","revise"],mustAnswerEveryAssignedItem:!0,jsonOnly:!0}}}function S4(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 yy(t,e){let r=e.now?e.now():new Date().toISOString(),n=eI(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 ks(t,e){let r=e.now?e.now():new Date().toISOString(),n=eI(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)XE(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=tI(n,i.id);if(u.comments.push(c),XE(n,i.id,e.provider,i.stance,e.round,a),i.stance==="revise"&&i.proposedItem){let l=$4(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)x4(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 eI(t){return JSON.parse(JSON.stringify(t))}function tI(t,e){let r=t.items.find(n=>n.id===e);if(!r)throw new Error(`Unknown consensus item: ${e}`);return r}function XE(t,e,r,n,s,o){let i=tI(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 $4(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 x4(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 QE(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 Ts={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 _d(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} | ${sI(r)} | ${ti(r)} |`);for(let r of t.items)e.push(""),e.push(...P4(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(`
|
|
325
|
+
`)}function P4(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:** ${sI(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(ti(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: ${Ts[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 cc(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(oI(o));s.push(""),s.push("## \uD569\uC758\uB41C \uD56D\uBAA9"),vy(s,e,t),s.push(""),s.push("## \uC81C\uC678 \uD569\uC758 \uD56D\uBAA9"),vy(s,r,t),s.push(""),s.push("## \uBBF8\uD569\uC758 / \uC758\uACAC \uD544\uC694 \uD56D\uBAA9"),vy(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(A4(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(`
|
|
326
|
+
`)}function nI(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(oI(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(ti(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(`
|
|
327
|
+
`)}function sI(t){return t.currentStances.map(e=>`${e.provider} ${Ts[e.stance]}${e.automatic?"(\uC790\uB3D9)":""}`).join(", ")}function ti(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} ${Ts[r.stance]}`).join(", ")}`}function oI(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} ${Ts[o.stance]}`).join(", ")||"-",s=t.conclusion?t.conclusion:ti(t);return`| ${t.id} | ${t.title} | ${t.displayStatus} | ${s} | ${t.proposer} | ${e} | ${r} | ${n} |`}function vy(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: ${k4(n)}`),t.push(`\uB3D9\uC758\uD55C AI: ${rI(n,"agree")}`),t.push(`\uBC18\uB300\uD55C AI: ${rI(n,"disagree")}`),t.push(`\uD604\uC7AC \uC785\uC7A5: ${T4(n)}`),t.push(`\uBCC0\uACBD \uC5EC\uBD80: ${E4(n)}`),t.push(`\uD1A0\uB860/\uADFC\uAC70 \uC704\uCE58: ${I4(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: ${R4(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}: ${Ts[s.stance]} - ${s.comment}`)}}function k4(t){return t.conclusion?t.conclusion:ti(t)}function rI(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 T4(t){return t.currentStances.map(e=>`${e.provider} ${Ts[e.stance]}${e.automatic?"(\uC790\uB3D9)":""}`).join(", ")}function E4(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 I4(t,e){return Array.from(new Set([e.documents.debate,...t.sourceRefs])).join(", ")}function R4(t){return t.comments.length>0?t.comments.slice(-3).map(e=>`${e.provider}: ${Ts[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.":ti(t)}function A4(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 _y(t,e){let r;try{r=JSON.parse(t)}catch{return{ok:!1,errors:["Response must be valid JSON."]}}let n=VE.safeParse(r);if(!n.success)return{ok:!1,errors:BE(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 C4,mkdirSync as D4,readFileSync as O4}from"fs";import{join as iI}from"path";var vt=class{debatesDir;constructor(e){this.debatesDir=iI(e,Os)}pathForSession(e){return iI(this.debatesDir,`${e}.consensus.json`)}async write(e){D4(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 C4(r)?JSON.parse(O4(r,"utf-8")):null}};async function Sy(t,e){for(;t.rounds<t.maxRounds;){if(t.consensusLedger.items.filter(i=>i.status==="unresolved"||i.status==="needs_opinion").length===0)return;t.rounds+=1;let n=t.rounds;t.phase="consensus-round";let s=new Set,o=await z4(t,e,n);if(o.size>0){await j4(t,e,n,o);for(let i of t.hostTurnSubmissions.values())s.add(i.participantId);t.hostTurnSubmissions.clear()}for(let i of t.config.participants){if(t.unavailableParticipants.has(i)||t.sourceLoadedParticipants.has(i)||o.has(i))continue;let a=t.consensusLedger.items.filter(p=>p.status==="unresolved"||p.status==="needs_opinion").length,c=gy(t.consensusLedger,{provider:i,round:n,maxItems:10});if(c.assignedItems.length===0)continue;t.consensusLedger=yy(t.consensusLedger,{round:n,provider:i,assignedItemIds:c.assignedItems.map(p=>p.id),totalActiveItems:a,maxItems:10,now:e.nowIso}),await Cr(t,e);let u={prompt:hy(c,t.legacyProposalIdMap),round:n,timeoutMs:t.participantTimeoutMs??6e5,...e.createActivitySink!==void 0?{activity:e.createActivitySink(t,i,"consensus-round",n)}:{},...t.files.length>0?{files:t.files}:{}};await e.setCurrentProvider?.(t,i),await e.markParticipantProgress?.(t,i,{status:"running",phase:"consensus-round",round:n,startedAt:e.nowIso(),lastActivityAt:e.nowIso(),lastEvent:`round ${n} turn started`});let l=await e.bridge.requestTurn(i,u);if(l.failed){wy(t,i,e.nowIso),await e.markParticipantProgress?.(t,i,{status:"failed",phase:"consensus-round",round:n,completedAt:e.nowIso(),lastActivityAt:e.nowIso(),lastEvent:`round ${n} turn failed`,latencyMs:l.latencyMs,failureReason:l.failureReason??"provider failed"}),t.consensusLedger=ks(t.consensusLedger,{provider:i,round:n,assignedItemIds:c.assignedItems.map(p=>p.id),rawResponse:"",parsedItems:[],validationErrors:[l.failureReason?l.failureReason:"provider failed"]}),await Cr(t,e);continue}s.add(i),lI(t,i);let d=await uI(i,c,l.text,u,t.legacyProposalIdMap,e);d.ok?(await e.markParticipantProgress?.(t,i,{status:"completed",phase:"consensus-round",round:n,completedAt:e.nowIso(),lastActivityAt:e.nowIso(),lastEvent:`round ${n} turn accepted`,latencyMs:l.latencyMs}),t.consensusLedger=ks(t.consensusLedger,{provider:i,round:n,assignedItemIds:c.assignedItems.map(p=>p.id),rawResponse:d.rawResponse,parsedItems:d.items})):(wy(t,i,e.nowIso),await e.markParticipantProgress?.(t,i,{status:"format-error",phase:"consensus-round",round:n,completedAt:e.nowIso(),lastActivityAt:e.nowIso(),lastEvent:`round ${n} turn rejected by JSON contract`,latencyMs:l.latencyMs,failureReason:d.errors.join("; ")}),t.consensusLedger=ks(t.consensusLedger,{provider:i,round:n,assignedItemIds:c.assignedItems.map(p=>p.id),rawResponse:d.rawResponse,parsedItems:[],validationErrors:d.errors})),by(t),await Cr(t,e)}if(await e.setCurrentProvider?.(t,void 0),s.size===0)return}}async function z4(t,e,r){let n=new Map;for(let s of t.config.participants){if(!fy.has(s)||t.unavailableParticipants.has(s)||t.sourceLoadedParticipants.has(s))continue;let o=e.bridge.describe(s);if(o.transport!=="task-subagent")continue;let i=gy(t.consensusLedger,{provider:s,round:r,maxItems:10});if(i.assignedItems.length===0)continue;let a=t.consensusLedger.items.filter(l=>l.status==="unresolved"||l.status==="needs_opinion").length;t.consensusLedger=yy(t.consensusLedger,{round:r,provider:s,assignedItemIds:i.assignedItems.map(l=>l.id),totalActiveItems:a,maxItems:10,now:e.nowIso});let c=hy(i,t.legacyProposalIdMap),u=o.agentName??ac[s]??s;n.set(s,{participantId:s,agentName:u,round:r,prompt:c,packet:i,requestedAt:e.nowIso(),...t.files.length>0?{files:t.files}:{}})}return n.size>0&&await Cr(t,e),n}async function j4(t,e,r,n){t.pendingHostTurns=new Map(n),t.hostTurnSubmissions=new Map,t.phase="awaiting-host-turn";for(let s of n.values())await e.markParticipantProgress?.(t,s.participantId,{status:"running",phase:"awaiting-host-turn",round:r,startedAt:e.nowIso(),lastActivityAt:e.nowIso(),lastEvent:`round ${r} awaiting host-turn submission`});await e.setCurrentProvider?.(t,void 0),await Cr(t,e),await $y(t,e);for(let s of n.keys()){let o=n.get(s),i=t.hostTurnSubmissions.get(s);if(!i){await e.markParticipantProgress?.(t,s,{status:"failed",phase:"consensus-round",round:r,completedAt:e.nowIso(),lastActivityAt:e.nowIso(),lastEvent:`round ${r} host-turn timeout`,failureReason:"host-turn timeout"}),t.consensusLedger=ks(t.consensusLedger,{provider:s,round:r,assignedItemIds:o.packet.assignedItems.map(u=>u.id),rawResponse:"",parsedItems:[],validationErrors:["host-turn timeout \u2014 no submission received"]}),by(t);continue}let a={prompt:o.prompt,round:r,timeoutMs:t.participantTimeoutMs??6e5,...t.files.length>0?{files:t.files}:{}},c=await uI(s,o.packet,i.content,a,t.legacyProposalIdMap,e);c.ok?(lI(t,s),await e.markParticipantProgress?.(t,s,{status:"completed",phase:"consensus-round",round:r,completedAt:e.nowIso(),lastActivityAt:e.nowIso(),lastEvent:`round ${r} host-turn accepted`}),t.consensusLedger=ks(t.consensusLedger,{provider:s,round:r,assignedItemIds:o.packet.assignedItems.map(u=>u.id),rawResponse:c.rawResponse,parsedItems:c.items})):(wy(t,s,e.nowIso),await e.markParticipantProgress?.(t,s,{status:"format-error",phase:"consensus-round",round:r,completedAt:e.nowIso(),lastActivityAt:e.nowIso(),lastEvent:`round ${r} host-turn rejected by JSON contract`,failureReason:c.errors.join("; ")}),t.consensusLedger=ks(t.consensusLedger,{provider:s,round:r,assignedItemIds:o.packet.assignedItems.map(u=>u.id),rawResponse:c.rawResponse,parsedItems:[],validationErrors:c.errors})),by(t)}t.pendingHostTurns.clear(),t.phase="consensus-round",await Cr(t,e)}function $y(t,e){return new Promise(r=>{let n=!1,s=()=>{n||(n=!0,clearTimeout(i),t.hostTurnResolver===s&&delete t.hostTurnResolver,r())},o=t.hostTurnTimeoutMs??12e5,i=setTimeout(()=>{s()},o);i.unref?.(),t.hostTurnResolver=s,t.hostTurnSubmissions.size>=t.pendingHostTurns.size&&queueMicrotask(s)})}function aI(t,e,r,n){let s=t.pendingHostTurns.get(e);if(!s)return{kind:"no-pending"};if(n.round!==void 0&&n.round!==s.round)return{kind:"round-mismatch",expectedRound:s.round};if(t.hostTurnSubmissions.has(e))return{kind:"duplicate"};t.hostTurnSubmissions.set(e,{participantId:e,content:r,receivedAt:n.nowIso()});let o=t.pendingHostTurns.size-t.hostTurnSubmissions.size;if(o<=0&&t.hostTurnResolver){let i=t.hostTurnResolver;delete t.hostTurnResolver,i()}return{kind:"accepted",remaining:Math.max(0,o)}}function cI(t){return t.pendingHostTurns.size===0?[]:Array.from(t.pendingHostTurns.values()).map(e=>({participantId:e.participantId,agentName:e.agentName,round:e.round,prompt:e.prompt,requestedAt:e.requestedAt,...e.systemPrompt!==void 0?{systemPrompt:e.systemPrompt}:{},...e.files!==void 0?{files:e.files}:{}}))}async function uI(t,e,r,n,s,o){let i=e.assignedItems.map(l=>l.id),a=_y(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:KE(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=_y(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 Cr(t,e){let r=new vt(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,_d(t.consensusLedger))}function by(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 xy(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 wy(t,e,r){let n=(t.consecutiveFailures.get(e)??0)+1;t.consecutiveFailures.set(e,n),n>=Ud&&(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 lI(t,e){t.consecutiveFailures.delete(e)}function Py(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 dI(t){return t==="ready-for-approval"||t==="escalated"}function pI(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 fI(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 mI(t,e){for(let[r,n]of t)if(n===e)return r;return e}function hI(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 ky(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 uc(t){if(t instanceof Error)return t.message;try{return String(t)}catch{return"<unstringifiable error>"}}function Es(t){let e=t.documentPaths.debate;return(e.split(/[\\/]/).pop()??e).replace(/\.md$/,"")}var N4=Object.freeze(["same","different","unsure"]),lc="alias-votes",L4=new Set(N4);function F4(t){return L4.has(t)}function q4(t){let e=`<${lc}>`,r=`</${lc}>`,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 U4(t){let e=`<${lc}>`;return t.includes(e)}var Z4=Object.freeze({lt:"<",gt:">",amp:"&",quot:'"',apos:"'"});function V4(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 Z4[r]??e})}function B4(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]=V4(u),n=s.index+s[0].length}return t.slice(n).trim().length>0?null:e}function gI(t){return t.trim().length===0?!0:t.replace(/<!--[\s\S]*?-->/g,"").trim().length===0}function Ty(t,e){let r=q4(t);if(!r)return U4(t)?{ok:!1,error:{kind:"malformed-xml",details:`opening <${lc}> without matching </${lc}>`}}:{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(!gI(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(!gI(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=B4(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(!F4(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 _={pair:m,vote:h};v!==void 0&&(_.reason=v),u.push(_)}return{ok:!0,entries:u,entryErrors:l}}var H4="__";function W4(t){return`${t.proposalA}${H4}${t.proposalB}`}var K4=["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(" "),J4=["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(`
|
|
328
|
+
`),Y4="Candidate pairs:";function X4(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(`
|
|
329
|
+
`)}async function wI(t){let{ledger:e,participantIds:r,askParticipant:n}=t,s=e.aliasCandidates;if(s.length===0)return{mergesApplied:[],undecided:[],parseFailures:[]};let o=s.map(W4),i=new Map;for(let f=0;f<s.length;f+=1)i.set(o[f],s[f]);let a=Q4(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:bI(m.reason)}),bd(l,o);continue}let{response:y}=m.value;if(y.failed===!0){u.push({participantId:h,reason:"askParticipant reported failed=true"}),bd(l,o);continue}let v=Ty(y.text,o),_=new Set;if(!v.ok){let b=await n(h,X4(o,v.error.details!==void 0?`${v.error.kind}: ${v.error.details}`:v.error.kind)).catch(x=>({text:"",failed:!0,reason:bI(x)}));if(b.failed===!0){u.push({participantId:h,reason:"reason"in b&&typeof b.reason=="string"?b.reason:"retry failed"}),bd(l,o);continue}let P=Ty(b.text,o);if(!P.ok){u.push({participantId:h,reason:P.error.details!==void 0?`${P.error.kind}: ${P.error.details}`:P.error.kind}),bd(l,o);continue}for(let x of P.entries)_I(l,x),_.add(x.pair);for(let x of o)if(!_.has(x)){let N=l.get(x);N!==void 0&&(N.missing+=1)}continue}for(let b of v.entries)_I(l,b),_.add(b.pair);for(let b of o)if(!_.has(b)){let P=l.get(b);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 y=tH(h);if(y.kind==="merge"){let v=m.proposalA,_=m.proposalB;if(e.proposals.get(v)===void 0||e.proposals.get(_)===void 0)continue;e.applyAliasMerge(v,_),d.push({primary:v,alias:_,voteBreakdown:{...h}});continue}p.push({pair:m,voteBreakdown:{...h},reason:y.reason})}return{mergesApplied:d,undecided:p,parseFailures:u}}function Q4(t,e,r){let n=[];n.push(K4),n.push(""),n.push(J4),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:"),yI(n,a),n.push(" Proposal B:"),yI(n,c),n.push("")}return n.push(G4),n.join(`
|
|
330
|
+
`)}function yI(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=eH(e.description);t.push(` description: ${r}`)}}var vI=400;function eH(t){return t.length<=vI?t:`${t.slice(0,vI)}\u2026`}function _I(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 bd(t,e){for(let r of e){let n=t.get(r);n!==void 0&&(n.missing+=1)}}function tH(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 bI(t){if(t instanceof Error)return`askParticipant threw: ${t.message}`;try{return`askParticipant threw: ${String(t)}`}catch{return"askParticipant threw: <unstringifiable>"}}import{readdir as rH}from"fs/promises";import{readFileSync as nH,existsSync as wd,unlinkSync as sH,mkdirSync as oH}from"fs";import{join as Is}from"path";var Iy=".session.json",Sd=".approval.json";function Ey(t){return`${t}${Iy}`}function iH(t){return t.endsWith(Iy)?{sessionId:t.slice(0,t.length-Iy.length),legacy:!1}:t.endsWith(Sd)?{sessionId:t.slice(0,t.length-Sd.length),legacy:!0}:null}function SI(t){let e=Date.parse(t);if(Number.isNaN(e))throw new Error(`computeApprovalDeadline: invalid readyAt ISO string: ${t}`);return new Date(e+Sv).toISOString()}var ri=class{constructor(e){this.workspaceDir=e;if(!e||typeof e!="string")throw new Error("StructuredSessionRegistry: baseDir is required");this.debatesDir=Is(e,Os)}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}`);oH(this.debatesDir,{recursive:!0});let r=Is(this.debatesDir,Ey(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=Is(this.debatesDir,Ey(e));if(!wd(n)){let o=Is(this.debatesDir,`${e}${Sd}`);if(!wd(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[Is(this.debatesDir,Ey(e)),Is(this.debatesDir,`${e}${Sd}`)])if(wd(r))try{sH(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(),!wd(this.debatesDir)){this.hydrated=!0;return}let e;try{e=await rH(this.debatesDir)}catch(r){if(r.code==="ENOENT"){this.hydrated=!0;return}throw r}for(let r of e){let n=iH(r);if(!n)continue;let s=this.readSnapshotFile(Is(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=nH(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 aH(n)?n:cH(n)?uH(n):(console.warn(`[session-registry] skipping snapshot with unexpected shape: ${e}`),null)}};function aH(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 cH(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 uH(t){let e=t.config.participants,r=lH(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 lH(t){return t==="approved"||t==="rejected"||t==="leader-timeout"||t==="error"}function dH(t,e){let r=[];r.push(...mH(t,e)),r.push(""),r.push(...xI(t,e));let n=PI(t,e);return n.length>0&&(r.push(""),r.push(...n)),r.push(""),r.push(...kI(t,e)),r.push(""),r.push(...gH(t,e)),r.join(`
|
|
331
|
+
`)}function pH(t,e){let r=[];r.push(...xI(t,e));let n=yH(t,e);n.length>0&&(r.push(""),r.push(...n));let s=vH(t,e);s.length>0&&(r.push(""),r.push(...s));let o=_H(t,e);o.length>0&&(r.push(""),r.push(...o));let i=PI(t,e);return i.length>0&&(r.push(""),r.push(...i)),r.push(""),r.push(...kI(t,e)),r.join(`
|
|
332
|
+
`)}function $I(){return{renderTerminal:dH,renderSynthesis:pH}}var fH=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 mH(t,e){let r=e.t(fH[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 xI(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=hH(n);r.push(`| ${s} | ${n.title} | ${n.severity} | ${o} |`)}return r}function hH(t){let e=`${t.agreeCount}/${t.totalVoters}`;return t.accepted||t.dissentSummary===void 0||t.dissentSummary.length===0?e:`${e} (${t.dissentSummary})`}function PI(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(Ry(s))}return r}function Ry(t){let e=`- **${t.participantId}:** ${t.vote}`;return t.reason===void 0||t.reason.length===0?e:`${e} \u2014 ${t.reason}`}function kI(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 gH(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 yH(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 vH(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(Ry(o))}return n}function _H(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(Ry(o))}return n}var ni=class{deps;sessions=new Map;backgroundRuns=new Map;formatter=$I();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",uc(o))))}).finally(s)})}).finally(()=>{this.backgroundRuns.delete(e)});this.backgroundRuns.set(e,n)}async startDebate(e){let r=(this.deps.generateSessionId??wH)(),n=this.nowIso(),s=e.mode??"review",o=ME({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??qd,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 vt(this.deps.registry.getWorkspaceDir()).pathForSession(r),d=vd({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 En,rounds:0,maxRounds:a.maxRounds,consecutiveFailures:new Map,unavailableParticipants:new Set,sourceLoadedParticipants: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}:{},...e.hostTurnTimeoutMs!==void 0?{hostTurnTimeoutMs:e.hostTurnTimeoutMs}:{},pendingHostTurns:new Map,hostTurnSubmissions:new Map,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&&m.push(...await this.loadSourceDocumentPhase(p));let h=p.config.participants.filter(_=>!p.sourceLoadedParticipants.has(_));if(h.length>0&&m.push(...await this.runIndividualPhase(p,o,h)),p.consensusLedger=vd({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(_=>({title:_.title,proposer:_.proposerId,plainSummary:_.description??_.title,originalClaim:_.description??_.title,sourceRefs:[_.id,...p.individualPaths[_.proposerId]!==void 0?[p.individualPaths[_.proposerId]]:[],..._.location!==void 0?[_.location]:[]]}))}),p.legacyProposalIdMap=new Map(m.map((_,b)=>[_.id,p.consensusLedger.items[b]?.id??_.id])),await Cr(p,this.consensusFlowDeps()),m.length===0){let _="No proposals were extracted from individual source material.";await this.deps.documentManager.addComment(p.debateDocId,{author:"Moderator",content:_}),p.phase="terminal";let b=this.buildSnapshot(p,"error",_);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:_}}let{ledger:y}=ZE(m);p.ledger=y,p.nextProposalIndex=TH(m),xy(p),y.aliasCandidates.length>0&&await this.runAliasClarificationPhase(p),await Sy(p,this.consensusFlowDeps()),p.phase="approval-gate",delete p.currentProvider,p.consensusLedger=TI(p.consensusLedger),await Cr(p,this.consensusFlowDeps());let v=this.buildSnapshot(p,Py({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",uc(m));try{await this.deps.registry.persist(h)}catch{}return this.emitTrace(p,"debate_error",{error:uc(m)}),{sessionId:r,status:"error",snapshot:h,terminalReport:this.renderTerminal(p,h),errorMessage:uc(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(`
|
|
333
|
+
`)}}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}}Ay(r,["ready-for-approval","escalated"],"approve");let n=this.sessions.get(e.sessionId),s=n?.consensusLedger;!s&&r.documentPaths.consensusLedger&&(s=await new vt(this.deps.registry.getWorkspaceDir()).load(r.sessionId)??void 0);let o=s?cc({...s,documents:{...s.documents,...r.documentPaths.synthesis!==void 0?{synthesis:r.documentPaths.synthesis}:{}}}):this.formatter.renderSynthesis(n?this.buildReportData(n,r,e.leaderNote):Dy(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=cc(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 vt(this.deps.registry.getWorkspaceDir()).write(u),n&&(n.consensusLedger=u,n.consensusLedgerPath=u.documents.ledger),await this.deps.documentManager.replaceDocumentContent(n?.debateDocId??Es(r),_d(u))}else await this.deps.documentManager.addComment(n?.debateDocId??Es(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.`);Ay(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 Sy(n,this.consensusFlowDeps());let i=Py({consensusLedger:n.consensusLedger,ledger:n.ledger});n.phase="approval-gate",delete n.currentProvider,n.consensusLedger=TI(n.consensusLedger),await Cr(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(`
|
|
334
|
+
`)}}let o=await s();return{snapshot:o,terminalReport:this.renderTerminal(n,o)}}async submitHostTurn(e){let r=this.sessions.get(e.sessionId);if(!r)return{outcome:{kind:"no-pending"},snapshot:null};let n=aI(r,e.participantId,e.content,{...e.round!==void 0?{round:e.round}:{},nowIso:()=>this.nowIso()});return n.kind==="accepted"&&await this.markParticipantProgress(r,e.participantId,{status:"running",phase:"awaiting-host-turn",round:e.round??r.rounds,lastActivityAt:this.nowIso(),lastEvent:"host-turn submission received"}),{outcome:n,snapshot:this.buildSnapshot(r,$H(r))}}async reject(e){let r=await this.loadSnapshotOrThrow(e.sessionId);if(r.status==="rejected"&&r.documentPaths.synthesis)return{snapshot:r,synthesisPath:r.documentPaths.synthesis,idempotentReplay:!0,...r.documentPaths.issue!==void 0?{issuePath:r.documentPaths.issue}:{}};let n=r.status==="rejected";n||Ay(r,["ready-for-approval","escalated","leader-timeout"],"reject");let s=this.sessions.get(e.sessionId),o=s?.debateDocId??Es(r),i=e.reason??r.terminalNote;n||await this.deps.documentManager.addComment(o,{author:"moderator",content:this.formatRejectionFooter(i)});let a;e.spawnIssue===!0&&(a=(await this.deps.documentManager.createIssueDocument({sessionId:r.sessionId,topic:r.config.topic,...i!==void 0?{reason:i}:{},items:kH(r)})).path);let c={...r,status:"rejected",phase:"terminal",updatedAt:this.nowIso(),terminalNote:i??r.terminalNote,summary:{...r.summary,terminalNote:i??r.summary.terminalNote??r.terminalNote},documentPaths:{...r.documentPaths,...a!==void 0?{issue:a}:{}}},u=s?.consensusLedger;!u&&r.documentPaths.consensusLedger&&(u=await new vt(this.deps.registry.getWorkspaceDir()).load(r.sessionId)??void 0);let l=i!==void 0?{"Rejection Reason":i}:void 0,d=h=>i!==void 0?`## Leader rejection reason
|
|
335
|
+
|
|
336
|
+
${i}
|
|
337
|
+
|
|
338
|
+
${h}`:h,p=d(u?cc(u):this.formatter.renderSynthesis(s?this.buildReportData(s,c,e.reason):Dy(c,e.reason),this.deps.i18n)),f=await this.deps.documentManager.createSynthesis({sessionId:r.sessionId,topic:r.config.topic,status:"rejected",rounds:r.rounds,maxRounds:r.config.maxRounds,participantIds:r.config.participants,individualPaths:Object.values(r.documentPaths.individual),debatePath:r.documentPaths.debate,body:p,...l!==void 0?{metadata:l}:{}}),m={...c,documentPaths:{...c.documentPaths,synthesis:f.path}};if(u){let h={...u,documents:{...u.documents,synthesis:f.path}};await this.deps.documentManager.replaceSynthesis({synthesisId:f.id,sessionId:r.sessionId,topic:r.config.topic,status:"rejected",rounds:r.rounds,maxRounds:r.config.maxRounds,participantIds:r.config.participants,individualPaths:Object.values(r.documentPaths.individual),debatePath:r.documentPaths.debate,body:d(cc(h)),...l!==void 0?{metadata:l}:{}}),await new vt(this.deps.registry.getWorkspaceDir()).write(h),s&&(s.consensusLedger=h,s.consensusLedgerPath=h.documents.ledger)}return await this.deps.registry.persist(m),this.emitTrace(s??null,"debate_rejected",{sessionId:r.sessionId,synthesisPath:f.path,...a!==void 0?{issuePath:a}:{}}),{snapshot:m,synthesisPath:f.path,...a!==void 0?{issuePath:a}:{}}}async handleTimedOutSnapshots(e){for(let r of e){if(r.status!=="leader-timeout")continue;let n=Es(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,e.sourceLoadedParticipants.add(n.provider),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=yd(s.content);for(let i of o){let a=Cy(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,n){e.phase="individual-review",await this.persistRunningSnapshot(e);let s=HE(e.mode),o=WE({mode:e.mode,topic:e.config.topic,scope:e.config.scope,goal:e.goal,files:e.files,individualReviewPrompt:e.individualReviewPrompt}),i=n??e.config.participants,a=i.filter(d=>this.shouldUseHostTurnForParticipant(d)),c=i.filter(d=>!a.includes(d)),u=[];a.length>0&&u.push(...await this.runIndividualHostTurnPhase(e,a,o,s));let l=await Promise.allSettled(c.map(async d=>{await this.markParticipantProgress(e,d,{status:"running",phase:"individual-review",round:0,startedAt:this.nowIso(),lastActivityAt:this.nowIso(),lastEvent:"individual review started"});let p=await this.deps.bridge.requestTurn(d,{prompt:o,system:s,round:0,timeoutMs:e.participantTimeoutMs??6e5,activity:this.createParticipantActivitySink(e,d,"individual-review",0),...e.files.length>0?{files:e.files}:{}});return{participantId:d,resp:p}}));for(let d of l){if(d.status==="rejected")continue;let{participantId:p,resp:f}=d.value,m=f.failed?`(no response: ${f.failureReason??"unknown"})`:f.text,h=await this.deps.documentManager.createIndividualReview({participantId:p,topic:e.config.topic,content:m,...e.files.length>0?{files:e.files}:{}});if(e.individualPaths[p]=h.path,f.failed){await this.markParticipantProgress(e,p,{status:"failed",phase:"individual-review",round:0,completedAt:this.nowIso(),lastActivityAt:this.nowIso(),lastEvent:"individual review failed",latencyMs:f.latencyMs,failureReason:f.failureReason??"provider failed"});continue}await this.markParticipantProgress(e,p,{status:"completed",phase:"individual-review",round:0,completedAt:this.nowIso(),lastActivityAt:this.nowIso(),lastEvent:"individual review completed",latencyMs:f.latencyMs});let y=yd(f.text);for(let v of y){let _=Cy(e,v.id);u.push({id:_,proposerId:p,title:v.title,severity:v.severity,...v.location!==void 0?{location:v.location}:{},...v.description!==void 0?{description:v.description}:{},roundOpened:1})}}return u}shouldUseHostTurnForParticipant(e){return this.deps.bridge.describe(e).transport==="task-subagent"}async runIndividualHostTurnPhase(e,r,n,s){let o=new Map;for(let a of r){let c=this.deps.bridge.describe(a);o.set(a,{participantId:a,agentName:c.agentName??a,round:0,prompt:n,systemPrompt:s,requestedAt:this.nowIso(),...e.files.length>0?{files:e.files}:{}})}e.pendingHostTurns=o,e.hostTurnSubmissions=new Map,e.phase="awaiting-host-turn";for(let a of r)await this.markParticipantProgress(e,a,{status:"running",phase:"awaiting-host-turn",round:0,startedAt:this.nowIso(),lastActivityAt:this.nowIso(),lastEvent:"individual review awaiting host-turn submission"});await this.persistRunningSnapshot(e),await $y(e,this.consensusFlowDeps());let i=[];for(let a of r){let c=e.hostTurnSubmissions.get(a),u=c?c.content:"(no response: host-turn timeout)",l=await this.deps.documentManager.createIndividualReview({participantId:a,topic:e.config.topic,content:u,...e.files.length>0?{files:e.files}:{}});if(e.individualPaths[a]=l.path,!c){await this.markParticipantProgress(e,a,{status:"failed",phase:"individual-review",round:0,completedAt:this.nowIso(),lastActivityAt:this.nowIso(),lastEvent:"individual review host-turn timeout",failureReason:"host-turn timeout"});continue}await this.markParticipantProgress(e,a,{status:"completed",phase:"individual-review",round:0,completedAt:this.nowIso(),lastActivityAt:this.nowIso(),lastEvent:"individual review host-turn accepted"});let d=yd(c.content);for(let p of d){let f=Cy(e,p.id);i.push({id:f,proposerId:a,title:p.title,severity:p.severity,...p.location!==void 0?{location:p.location}:{},...p.description!==void 0?{description:p.description}:{},roundOpened:1})}}return e.pendingHostTurns.clear(),e.hostTurnSubmissions.clear(),e.phase="individual-review",await this.persistRunningSnapshot(e),i}async runAliasClarificationPhase(e){let r=await wI({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??6e5,...e.files.length>0?{files:e.files}:{}});return i.failed?{text:"",failed:!0}:{text:i.text}}}),n=YE(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])))}xy(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:SH(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=En.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:Es(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,sourceLoadedParticipants:new Set,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:o+1,consensusLedger:vd({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 vt(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 vt(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)),pendingHostTurns:new Map,hostTurnSubmissions:new Map,...e.progress.currentProvider!==void 0?{currentProvider:e.progress.currentProvider}:{}}}async rehydrateConsensusSessionContext(e){let r=new vt(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:Es(e),debateDocPath:e.documentPaths.debate,individualPaths:{...e.documentPaths.individual},createdAt:e.createdAt,ledger:e.ledgerState?En.fromJSON(e.ledgerState):new En,rounds:e.rounds,maxRounds:e.config.maxRounds,consecutiveFailures:o,unavailableParticipants:new Set(e.unavailableParticipants??[]),sourceLoadedParticipants:new Set,allAbstainCount:new Map,reviseSuccessors:new Map,pendingVoteWarnings:new Map,nextProposalIndex:1,consensusLedger:s,consensusLedgerPath:n,legacyProposalIdMap:GE(s),phase:e.phase,...e.config.participantTimeoutMs!==void 0?{participantTimeoutMs:e.config.participantTimeoutMs}:{},participantProgress:new Map(Object.entries(e.progress.participants)),pendingHostTurns:new Map,hostTurnSubmissions:new Map,...e.progress.currentProvider!==void 0?{currentProvider:e.progress.currentProvider}:{}}}buildSnapshot(e,r,n){let s=this.nowIso(),o=dI(r)?LE(s,SI):s,i=this.snapshotAggregatedVotes(e),a=xH(e.phase,r),c=PH(i,n),u={};for(let[p,f]of e.consecutiveFailures)f>0&&(u[p]=f);let l=cI(e);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)}:{},...l.length>0?{pendingHostTurns:l}:{},...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:hI(o.stance),roundRecorded:o.round,...i?.comment?{reason:i.comment}:{}}}return{proposalId:mI(e.legacyProposalIdMap,n.id),title:n.title,severity:"MEDIUM",proposers:[n.proposer],status:fI(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:pI(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," ")}`,"",nI({...e.consensusLedger,documents:{...e.consensusLedger.documents,...r.documentPaths.synthesis!==void 0?{synthesis:r.documentPaths.synthesis}:{}}})].join(`
|
|
339
|
+
`);let n=e?this.buildReportData(e,r):Dy(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=EH(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=IH(e);return{topic:e.config.topic,rounds:e.rounds,maxRounds:e.maxRounds,status:ky(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}
|
|
332
340
|
|
|
333
341
|
**${n}:** ${e}`}formatRejectionFooter(e){let r=this.deps.i18n.t("moderator.narration.rejected");return e?`${r}
|
|
334
342
|
|
|
335
343
|
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}
|
|
336
344
|
|
|
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
|
|
338
|
-
`)}function
|
|
339
|
-
`)}async function
|
|
345
|
+
${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 wH(){let t=Date.now().toString(36),e=Math.random().toString(36).slice(2,10);return`s-${t}-${e}`}function Ay(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 SH(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 $H(t){return t.phase==="terminal"?"error":(t.phase==="approval-gate","running")}function xH(t,e){return e==="approved"||e==="rejected"||e==="leader-timeout"||e==="error"?"terminal":e==="ready-for-approval"||e==="escalated"?"approval-gate":t}function PH(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 kH(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 TH(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 Cy(t,e){let r=`P${t.nextProposalIndex}`;return t.nextProposalIndex+=1,r}function TI(t){if(t.nextTurn===void 0)return t;let e={...t};return delete e.nextTurn,e}function EH(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 IH(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 Dy(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:ky(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 EI=6e5;function dc(t,e){return Promise.race([t,new Promise((r,n)=>setTimeout(()=>n(new Error(`Provider "${e}" stalled (no response after ${EI/1e3}s)`)),EI))])}function RI(t){return new cn({tools:oo(),baseDir:t})}var Oy;function AI(){return Oy||(Oy=new Si),Oy}var Rs;function $d(t,e,r){if(Rs&&Rs.hostKind!=="unknown"&&Rs.registry===t&&Rs.hostKind===e&&Rs.baseDir===r)return Rs.bridge;let n=new cn({tools:oo(),baseDir:r}),s=NE({registry:t,readOnlyAdapter:n,hostKind:e,agentsDir:RH(r,"agents")});return e!=="unknown"&&(Rs={bridge:s,registry:t,hostKind:e,baseDir:r}),s}var II=new Map;function CI(t){let e=II.get(t.workspaceBaseDir);if(e&&e.registry===t.structuredSessionRegistry&&e.documentManager===t.documentManager&&e.bridge===t.bridge)return e.engine;let r=new ni({bridge:t.bridge,documentManager:t.documentManager,registry:t.structuredSessionRegistry,i18n:t.i18n,...t.traceWriter!==void 0?{traceWriter:t.traceWriter}:{}});return II.set(t.workspaceBaseDir,{engine:r,registry:t.structuredSessionRegistry,documentManager:t.documentManager,bridge:t.bridge}),r}function DI(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=Ei(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 xd(t,e,r){r.alreadyConcluded||t.debateEngine.conclude(e);let n=t.debateEngine.buildTurnTranscript(e);return t.debateEngine.delete(e),n}function OI(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(", ")})`:""}`)}}if(t.pendingHostTurns&&t.pendingHostTurns.length>0){e.push("","## Pending Host Turns (awaiting subagent dispatch)"),e.push("Dispatch each entry through the matching native Task subagent and post","the verbatim text back via `agent_debate_submit_turn`. Round 0 entries","are individual reviews; later rounds use the consensus JSON contract.","The workflow resumes automatically once every entry is fulfilled.","");for(let n of t.pendingHostTurns)e.push(`### ${n.participantId} \u2192 ${n.agentName} (round ${n.round})`),e.push(`- Requested at: ${n.requestedAt}`),n.files&&n.files.length>0&&e.push(`- Files: ${n.files.join(", ")}`),e.push("- Prompt:","```",n.prompt,"```","")}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(`
|
|
346
|
+
`)}function MI(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(`
|
|
347
|
+
`)}async function zI(t,e){let r=Xl.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+=`
|
|
340
348
|
|
|
341
349
|
Validator feedback from previous round:
|
|
342
|
-
${l}`);let y=await
|
|
350
|
+
${l}`);let y=await dc(e.readOnlyAdapter.chat(m,{prompt:h}),f);o.addTurn(i.id,f,y.text)}if(a&&c&&p+1>=u){let f=o.buildTurnTranscript(i.id),m=`Evaluate this debate against the goal: "${r.goal}"
|
|
343
351
|
|
|
344
352
|
Current discussion:
|
|
345
353
|
${f}
|
|
@@ -351,12 +359,12 @@ Respond in JSON:
|
|
|
351
359
|
"accuracy": true/false,
|
|
352
360
|
"consistency": true/false,
|
|
353
361
|
"feedback": "..."
|
|
354
|
-
}`,h=await
|
|
362
|
+
}`,h=await dc(e.readOnlyAdapter.chat(c,{prompt:m}),c.id);try{let y=JSON.parse(h.text);if(y.goalAchievement&&y.completeness&&y.accuracy&&y.consistency)break;l=String(y.feedback??"")}catch{l=h.text}}}let d=xd(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
363
|
**Session ID:** ${s.id}
|
|
356
364
|
**Topic:** ${r.topic}
|
|
357
365
|
**Participants:** ${r.providers.join(", ")}
|
|
358
366
|
|
|
359
|
-
Use \`agent_debate_status\` to check progress.`}]}}async function
|
|
367
|
+
Use \`agent_debate_status\` to check progress.`}]}}async function jI(t,e){let r=ed.parse(t),n=await e.structuredSessionRegistry?.load(r.session_id);if(n)return{content:[{type:"text",text:OI(n)}]};if(e.structuredSessionRegistry){let i=await new vt(e.structuredSessionRegistry.getWorkspaceDir()).load(r.session_id);if(i)return{content:[{type:"text",text:MI(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
368
|
**Type:** ${s.type}
|
|
361
369
|
**Status:** ${s.status}
|
|
362
370
|
**Created:** ${s.createdAt}
|
|
@@ -366,7 +374,7 @@ Use \`agent_debate_status\` to check progress.`}]}}async function kI(t,e){let r=
|
|
|
366
374
|
|
|
367
375
|
---
|
|
368
376
|
|
|
369
|
-
${s.result}`),{content:[{type:"text",text:o}]}}async function
|
|
377
|
+
${s.result}`),{content:[{type:"text",text:o}]}}async function NI(t,e){let r=Ql.parse(t),n=new xi(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"}**
|
|
370
378
|
|
|
371
379
|
`;for(let i of s.reviews)o+=`### ${i.targetProvider} reviewed by ${i.reviewerProvider}
|
|
372
380
|
`,o+=`**Result:** ${i.passed?"PASS":"FAIL"}
|
|
@@ -376,13 +384,13 @@ ${s.result}`),{content:[{type:"text",text:o}]}}async function EI(t,e){let r=Hl.p
|
|
|
376
384
|
`;return s.conflicts.length>0&&(o+=`## Conflicts
|
|
377
385
|
${s.conflicts.map(i=>`- ${i}`).join(`
|
|
378
386
|
`)}
|
|
379
|
-
`),{content:[{type:"text",text:o}]}}catch(s){return{content:[{type:"text",text:`**Cross-validation failed:** ${D(s)}`}],isError:!0}}}async function
|
|
387
|
+
`),{content:[{type:"text",text:o}]}}catch(s){return{content:[{type:"text",text:`**Cross-validation failed:** ${D(s)}`}],isError:!0}}}async function LI(t,e){let r=td.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**
|
|
380
388
|
**Debate ID:** ${e.debateEngine.create({topic:r.topic,providerIds:r.providers,goal:r.goal,documentId:n}).id}
|
|
381
389
|
**Topic:** ${r.topic}
|
|
382
390
|
**Participants:** ${r.providers.join(", ")}${n?`
|
|
383
|
-
**Document ID:** ${n}`:""}`}]}}async function
|
|
391
|
+
**Document ID:** ${n}`:""}`}]}}async function FI(t,e){let r=rd.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=Ei(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}
|
|
384
392
|
|
|
385
|
-
_Quality: ${d.score.toFixed(2)}_`}]}}async function
|
|
393
|
+
_Quality: ${d.score.toFixed(2)}_`}]}}async function qI(t,e){let r=nd.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}=DI(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=xd(e,r.debate_id,{topic:n.topic,providerIds:n.providerIds,importance:.5+s*.5,confidence:s,alreadyConcluded:!0}),i=`**Debate concluded**
|
|
386
394
|
**Debate ID:** ${r.debate_id}
|
|
387
395
|
**Topic:** ${n.topic}
|
|
388
396
|
**Turns:** ${n.turns.length}`;return n.documentId&&(i+=`
|
|
@@ -390,13 +398,13 @@ _Quality: ${d.score.toFixed(2)}_`}]}}async function RI(t,e){let r=Gl.parse(t),n=
|
|
|
390
398
|
|
|
391
399
|
---
|
|
392
400
|
|
|
393
|
-
${o}`,{content:[{type:"text",text:i}]}}async function
|
|
401
|
+
${o}`,{content:[{type:"text",text:i}]}}async function UI(t,e,r,n){e&&await t.documentManager.addComment(e,{author:r,content:n})}function Pd(t){switch(t.kind){case"agree":return"AGREES";case"disagree":return"DISAGREES";case"parseError":return"PARSE_ERROR";case"unavailable":return"UNAVAILABLE"}}function kd(t){switch(t.kind){case"agree":case"disagree":{let e=t.suggestions?`
|
|
394
402
|
|
|
395
403
|
**Suggestions:** ${t.suggestions}`:"";return`${t.feedback}${e}`}case"parseError":return`[Parse error: ${t.reason}]
|
|
396
404
|
|
|
397
405
|
**Raw response:**
|
|
398
406
|
|
|
399
|
-
${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function
|
|
407
|
+
${t.rawResponse}`;case"unavailable":return`[Provider unavailable: ${t.reason}]`}}async function ZI(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
|
|
400
408
|
|
|
401
409
|
Parent document: ${e}${r?`
|
|
402
410
|
Debate ID: ${r}`:""}
|
|
@@ -407,27 +415,27 @@ ${n}`});let i=s.rawResponse?`
|
|
|
407
415
|
|
|
408
416
|
**Raw response:**
|
|
409
417
|
|
|
410
|
-
${s.rawResponse}`:"";return await t.documentManager.addComment(o.id,{author:`${s.provider} (independent review)`,content:`**${
|
|
418
|
+
${s.rawResponse}`:"";return await t.documentManager.addComment(o.id,{author:`${s.provider} (independent review)`,content:`**${Pd(s.outcome)}**
|
|
411
419
|
|
|
412
|
-
${
|
|
413
|
-
${
|
|
414
|
-
**Excluded Providers:** ${s.map(
|
|
420
|
+
${kd(s.outcome)}${i}`}),o.id}function AH(t){return`${t?.trim()??"Review the following document carefully and state whether you agree with its content."}
|
|
421
|
+
${Pv}`}function CH(t){let e=so(t);if(e===null||typeof e!="object")return{kind:"parseError",rawResponse:t,reason:"Response did not contain a parseable JSON object."};let r=PE.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 VI(t,e){let r=sd.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 v=new Set(e.debateEngine.getActiveProviders(r.debate_id)),_=[];for(let b of n)if(b==="claude"||v.has(b))_.push(b);else{let P=(o.unavailableProviders??[]).find(x=>x.providerId===b);s.push({id:b,reason:P?`Marked unavailable for this debate: ${P.reason}`:"Not currently active in this debate."})}n=_}let a=s.length===0?"":`
|
|
422
|
+
**Excluded Providers:** ${s.map(v=>`${v.id} (${v.reason})`).join(", ")}`;if(n.length===0)return{content:[{type:"text",text:`No review-capable providers remain after exclusions.${a}`}],isError:!0};let c=AH(r.review_prompt),u=[],l=n.map(async v=>{if(v==="claude")return null;let _=e.registry.get(v),b=`${c}
|
|
415
423
|
|
|
416
424
|
---
|
|
417
425
|
|
|
418
|
-
${r.document}`,P,x;try{let k=await
|
|
426
|
+
${r.document}`,P,x;try{let k=await dc(e.readOnlyAdapter.chat(_,{prompt:b}),v);P=k.text,x=CH(k.text)}catch(k){let O=D(k);if(x={kind:"unavailable",reason:O},r.debate_id&&o){let L=k instanceof _e?`Provider reported unavailable: ${O}`:`Chat failed: ${O}`;e.debateEngine.markProviderUnavailable(r.debate_id,v,L),o=e.debateEngine.getState(r.debate_id)}}let N={provider:v,outcome:x,rawResponse:P};if(N.linkedDocumentId=await ZI(e,i,r.debate_id,r.document,N),i){let k=kd(N.outcome),O=N.linkedDocumentId?`
|
|
419
427
|
|
|
420
|
-
**Independent review document:** ${N.linkedDocumentId}`:"";await e.documentManager.addComment(i,{author:`${
|
|
428
|
+
**Independent review document:** ${N.linkedDocumentId}`:"";await e.documentManager.addComment(i,{author:`${v} (review)`,content:`**${Pd(N.outcome)}**
|
|
421
429
|
|
|
422
|
-
${k}${O}`})}return N}),d=await Promise.all(l);for(let
|
|
430
|
+
${k}${O}`})}return N}),d=await Promise.all(l);for(let v of d)v&&u.push(v);let p=u.filter(v=>v.outcome.kind==="agree"||v.outcome.kind==="disagree"),f=u.length>0&&p.length===u.length&&p.every(v=>v.outcome.kind==="agree"),m=u.filter(v=>v.outcome.kind==="parseError"||v.outcome.kind==="unavailable"),y=`**Document Review** \u2014 ${f?"ALL AGREE \u2713":m.length>0&&p.length===0?"NO RESPONSES":"DISAGREEMENTS FOUND"}${a}
|
|
423
431
|
|
|
424
|
-
`;for(let
|
|
425
|
-
`,y+=`${
|
|
426
|
-
`,
|
|
432
|
+
`;for(let v of u)y+=`### ${v.provider}: ${Pd(v.outcome)}
|
|
433
|
+
`,y+=`${kd(v.outcome)}
|
|
434
|
+
`,v.linkedDocumentId&&(y+=`**Independent review document:** ${v.linkedDocumentId}
|
|
427
435
|
`),y+=`
|
|
428
|
-
`;if(!f){let
|
|
436
|
+
`;if(!f){let v=m.length>0?`Revise the document addressing the feedback above. Note: ${m.length} provider(s) did not return a definite agree/disagree (parseError or unavailable) \u2014 they are NOT counted as agreement. Call \`agent_debate_review\` again with an updated document or a narrower providers list.`:"Revise the document addressing the feedback above, then call `agent_debate_review` again to check for consensus.";y+=`---
|
|
429
437
|
|
|
430
|
-
**Next step:** ${
|
|
438
|
+
**Next step:** ${v}`}return await UI(e,i,"Moderator (Review Aggregation)",y),{content:[{type:"text",text:y}]}}async function BI(t,e){let r=od.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**
|
|
431
439
|
**Task ID:** ${r.task_id}
|
|
432
440
|
**Worktree:** ${n.worktreePath}
|
|
433
441
|
**Branch:** ${n.branch}
|
|
@@ -441,25 +449,25 @@ ${n.diffStat}
|
|
|
441
449
|
### Changes
|
|
442
450
|
\`\`\`diff
|
|
443
451
|
${n.fullDiff}
|
|
444
|
-
\`\`\``,{content:[{type:"text",text:s}]}}async function
|
|
452
|
+
\`\`\``,{content:[{type:"text",text:s}]}}async function HI(t,e){let r=id.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**
|
|
445
453
|
**Task ID:** ${r.task_id}
|
|
446
454
|
**Merged files:** ${n.merged.length}
|
|
447
455
|
|
|
448
456
|
${n.merged.map(s=>`- ${s}`).join(`
|
|
449
|
-
`)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${D(n)}`}],isError:!0}}}async function
|
|
457
|
+
`)||"(no files)"}`}]}}catch(n){return{content:[{type:"text",text:`**Accept failed:** ${D(n)}`}],isError:!0}}}async function WI(t,e){let r=ad.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**
|
|
450
458
|
**Task ID:** ${r.task_id}`;return r.reason&&(n+=`
|
|
451
|
-
**Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}import{join as
|
|
459
|
+
**Reason:** ${r.reason}`),{content:[{type:"text",text:n}]}}import{join as DH}from"path";var OH="unknown";async function KI(t,e,r){let n=r.workspaceBaseDir??process.cwd(),s=r.structuredSessionRegistry??new ri(DH(n,ui)),o=$d(r.registry,r.sessionContext?.hostKind??OH,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:RI(n),structuredSessionRegistry:s,moderatorEngine:i};switch(t){case"agent_debate_start":return zI(e,a);case"agent_debate_status":return jI(e,a);case"agent_cross_validate":return NI(e,a);case"agent_debate_create":return LI(e,a);case"agent_debate_turn":return FI(e,a);case"agent_debate_conclude":return qI(e,a);case"agent_debate_review":return VI(e,a);case"agent_changes_review":return BI(e,a);case"agent_changes_accept":return HI(e,a);case"agent_changes_reject":return WI(e,a);case fd:return kE(e,a);case Xo:return TE(e,a);case Qo:return EE(e,a);case ei:return RE(e,a);case oc:return IE(e,a);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var zy={};rt(zy,{getTools:()=>MH,handleTool:()=>ZH});var JI=g.object({files:g.array(g.string()).min(1).describe("File paths to include in the review"),rules:g.array(g.string()).describe("Review rules/guidelines to apply")}),GI=g.object({doc_id:g.string().describe("Document ID to request review for"),provider:g.union([g.string(),g.array(g.string()).min(1)]).describe("Provider ID(s) to perform the review")}),YI=g.object({session_id:g.string().describe("Session ID returned by workspace_request_review")}),XI=g.object({doc_id:g.string().describe("Document ID to comment on"),author:g.string().describe("Comment author name"),content:g.string().describe("Comment content")}),QI=g.object({doc_id:g.string().describe("Document ID to read")}),eR=g.object({title:g.string().describe("Document title"),content:g.string().describe("Document content (markdown)"),metadata:g.record(g.string()).optional().describe("Optional key-value metadata (e.g. Provider, Task, Mode)"),kind:g.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.")}),tR=g.object({});function MH(){return[{name:"workspace_create_review",title:"Create Code Review",description:"Create a code review document for the specified files with given review rules.",inputSchema:W(JI)},{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:W(GI)},{name:"workspace_review_status",title:"Check Review Status",description:"Check the status of an async review session started by workspace_request_review.",inputSchema:W(YI)},{name:"workspace_add_comment",title:"Add Review Comment",description:"Add a comment to an existing review document.",inputSchema:W(XI)},{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:W(eR)},{name:"workspace_read",title:"Read Document",description:"Read the contents of a workspace document.",inputSchema:W(QI)},{name:"workspace_list",title:"List Documents",description:"List all workspace documents.",inputSchema:W(tR)}]}async function zH(t,e){let r=JI.parse(t),n=await e.documentManager.createReview({files:r.files,rules:r.rules});return{content:[{type:"text",text:`**Review created**
|
|
452
460
|
**Document ID:** ${n.id}
|
|
453
461
|
**Path:** ${n.path}
|
|
454
462
|
**Files:** ${r.files.join(", ")}
|
|
455
|
-
**Rules:** ${r.rules.length}`}]}}async function
|
|
463
|
+
**Rules:** ${r.rules.length}`}]}}async function jH(t,e){let r=GI.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:
|
|
456
464
|
|
|
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=
|
|
465
|
+
${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=Sp({providers:n.length,failed:l.length});e.sessionManager.transitionSession(i.id,p,d)}catch{}}),{content:[{type:"text",text:`**Review started (async)**
|
|
458
466
|
**Session ID:** ${i.id}
|
|
459
467
|
**Document ID:** ${r.doc_id}
|
|
460
468
|
**Providers:** ${n.join(", ")}
|
|
461
469
|
|
|
462
|
-
Use \`workspace_review_status\` with session_id to check progress.`}]}}async function
|
|
470
|
+
Use \`workspace_review_status\` with session_id to check progress.`}]}}async function NH(t,e){let r=YI.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**
|
|
463
471
|
`;return c+=`**Session ID:** ${n.id}
|
|
464
472
|
`,c+=`**Status:** ${n.status}
|
|
465
473
|
`,c+=`**Document:** ${n.config.doc_id}
|
|
@@ -469,32 +477,33 @@ Use \`workspace_review_status\` with session_id to check progress.`}]}}async fun
|
|
|
469
477
|
`,c+=`- Failed: ${i.join(", ")||"none"}
|
|
470
478
|
`,c+=`- Pending: ${a.join(", ")||"none"}
|
|
471
479
|
`,n.result&&(c+=`
|
|
472
|
-
**Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function
|
|
480
|
+
**Result:** ${n.result}`),{content:[{type:"text",text:c}]}}async function LH(t,e){let r=XI.parse(t);return await e.documentManager.addComment(r.doc_id,{author:r.author,content:r.content}),{content:[{type:"text",text:`**Comment added**
|
|
473
481
|
**Document ID:** ${r.doc_id}
|
|
474
482
|
**Author:** ${r.author}
|
|
475
483
|
|
|
476
|
-
${r.content}`}]}}async function
|
|
484
|
+
${r.content}`}]}}async function FH(t,e){let r=eR.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**
|
|
477
485
|
**Document ID:** ${n.id}
|
|
478
486
|
**Path:** ${n.path}
|
|
479
|
-
**Title:** ${r.title}`}]}}async function
|
|
487
|
+
**Title:** ${r.title}`}]}}async function qH(t,e){let r=QI.parse(t),n=await e.documentManager.read(r.doc_id);return{content:[{type:"text",text:`**Document ID:** ${n.id}
|
|
480
488
|
**Path:** ${n.path}
|
|
481
489
|
|
|
482
|
-
${n.content}`}]}}async function
|
|
490
|
+
${n.content}`}]}}async function UH(t,e){tR.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
|
|
483
491
|
|
|
484
492
|
**Total:** ${r.length}
|
|
485
493
|
|
|
486
494
|
`;for(let s of r)n+=`- **${s.id}** \u2014 ${s.kind}, ${s.sizeBytes} bytes, ${s.modifiedAt}
|
|
487
495
|
`,n+=` Path: ${s.path}
|
|
488
|
-
`;return{content:[{type:"text",text:n}]}}async function
|
|
496
|
+
`;return{content:[{type:"text",text:n}]}}async function ZH(t,e,r){switch(t){case"workspace_create_review":return zH(e,r);case"workspace_request_review":return jH(e,r);case"workspace_review_status":return NH(e,r);case"workspace_add_comment":return LH(e,r);case"workspace_create_document":return FH(e,r);case"workspace_read":return qH(e,r);case"workspace_list":return UH(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var jy={};rt(jy,{getTools:()=>BH,handleTool:()=>KH});function Td(t,e){return t==="claude-only"&&e!=="claude-code"?"leader-only":t}var VH=g.object({provider:g.string().optional().describe("Provider ID to check (omit to check all)")});function BH(){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 HH(t){let e=t.registry.getAll();if(e.length===0)return{content:[{type:"text",text:"No providers registered."}]};let r=`# Registered Providers (${e.length})
|
|
489
497
|
|
|
490
498
|
`;t.sessionContext&&(r+=`## Host Session
|
|
491
499
|
`,r+=`- **Host:** ${t.sessionContext.hostId} (${t.sessionContext.hostKind})
|
|
492
500
|
`,r+=`- **Leader Provider:** ${t.sessionContext.leaderProviderId}
|
|
493
|
-
`,r+=`- **Execution Mode:** ${
|
|
501
|
+
`,r+=`- **Execution Mode:** ${Td(t.sessionContext.executionMode,t.sessionContext.hostKind)}
|
|
494
502
|
`,r+=`- **Participants:** ${t.sessionContext.participantProviderIds.join(", ")}
|
|
495
503
|
|
|
496
|
-
`);for(let n of e){let s=n.isAvailable(),o=n.getCapabilities(),i=typeof t.registry.getDescriptor=="function"?t.registry.getDescriptor(n.id):
|
|
504
|
+
`);for(let n of e){let s=n.isAvailable(),o=n.getCapabilities(),i=typeof t.registry.getDescriptor=="function"?t.registry.getDescriptor(n.id):Qr(n,o),a=s?"Available":"Unavailable",c=t.providerPolicies?.get(n.id)??Ot(n.type);r+=`## ${n.id} (${n.type})
|
|
497
505
|
`,r+=`- **Status:** ${a}
|
|
506
|
+
`,r+=`- **Execution Policy:** ${c}
|
|
498
507
|
`,r+=`- **Invocation:** ${i.invocation}
|
|
499
508
|
`,r+=`- **Roles:** ${i.roles.join(", ")}
|
|
500
509
|
`,r+=`- **Autonomous Execution:** ${i.supportsAutonomousExecution?"Yes":"No"}
|
|
@@ -506,46 +515,46 @@ ${n.content}`}]}}async function IH(t,e){VI.parse(t);let r=await e.documentManage
|
|
|
506
515
|
`,r+=`- **JSON Output:** ${o.supportsJsonOutput?"Yes":"No"}
|
|
507
516
|
`,r+=`- **Tool Use:** ${o.supportsToolUse?"Yes":"No"}
|
|
508
517
|
`,o.strengths.length>0&&(r+=`- **Strengths:** ${o.strengths.join(", ")}
|
|
509
|
-
`),o.models.length>0&&(r+=`- **Models:** ${o.models.map(
|
|
518
|
+
`),o.models.length>0&&(r+=`- **Models:** ${o.models.map(u=>u.name).join(", ")}
|
|
510
519
|
`),r+=`
|
|
511
|
-
`}return{content:[{type:"text",text:r}]}}async function
|
|
520
|
+
`}return{content:[{type:"text",text:r}]}}async function WH(t,e){let r=VH.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
521
|
|
|
513
522
|
`;for(let i of s){let a=i.status==="ok"?"OK":i.status==="degraded"?"DEGRADED":"ERROR";o+=`## ${i.id} (${i.type})
|
|
514
523
|
`,o+=`- **Status:** ${a}
|
|
515
524
|
`,i.message&&(o+=`- **Message:** ${i.message}
|
|
516
525
|
`),i.error&&(o+=`- **Error:** ${i.error}
|
|
517
526
|
`),o+=`
|
|
518
|
-
`}return{content:[{type:"text",text:o}]}}async function
|
|
519
|
-
`)}function
|
|
520
|
-
`))}async function
|
|
521
|
-
`),!0);let i=await(await
|
|
522
|
-
`))}async function
|
|
523
|
-
`))}async function
|
|
524
|
-
`)}]}}async function
|
|
525
|
-
`)}]}}async function
|
|
527
|
+
`}return{content:[{type:"text",text:o}]}}async function KH(t,e,r){switch(t){case"provider_list":return HH(r);case"provider_health":return WH(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var By={};rt(By,{getTools:()=>bW,handleTool:()=>$W});import{existsSync as fW,readFileSync as mW}from"fs";import{readFileSync as JH,existsSync as GH}from"fs";var YH={ollama:{executionPolicy:"workspace-write",config:{host:ci,defaultModel:"auto"}},"gemini-cli":{executionPolicy:Ot("gemini-cli"),config:{timeout:12e4}},"codex-cli":{executionPolicy:Ot("codex-cli"),config:{timeout:12e4}},"claude-cli":{executionPolicy:Ot("claude-cli"),config:{timeout:12e4}}};async function si(t){let e=t?.workspaceBaseDir,r=[{id:"ollama",type:"ollama",provider:new Qn({id:"ollama",host:ci})},{id:"gemini",type:"gemini-cli",provider:new es({id:"gemini"})},{id:"codex",type:"codex-cli",provider:new ts({id:"codex",workspaceBaseDir:e})},{id:"claude-cli",type:"claude-cli",provider:new rs({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 XH(t){if(!GH(t))return null;try{return JSON.parse(JH(t,"utf-8"))}catch{return null}}function QH(t){return t==="auto"?"auto":"default-only"}function rR(t,e,r){let n=XH(t),s=new Set(r.enabledIds??[]),o=new Map((n?.providers??[]).map(d=>[d.id,d])),i=e.map(d=>{let p=YH[d.type]||{executionPolicy:Ot(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:QH(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"&&(Vv(t),Ze(t,a)),{action:l,path:t,config:a}}function nR(t,e){Ny(t,e)}function Ny(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 Vy={};rt(Vy,{formatHostAssetsSetupSummary:()=>Zy,getTools:()=>cW,handleTool:()=>pW});import{existsSync as sR,readFileSync as eW}from"fs";import{readFile as tW}from"fs/promises";import Dr,{dirname as iR}from"path";import{fileURLToPath as rW,pathToFileURL as nW}from"url";var sW=Dr.join(".agestra","installs","host-assets.json"),Fy=g.object({host:g.enum(["auto","codex"]).optional().default("auto").describe("Host asset family to inspect. `auto` uses the connected MCP host."),scope:g.enum(["project","user"]).optional().default("project").describe("Install/check project-local or user-level host assets.")});function In(t,e){return{content:[{type:"text",text:t}],isError:e}}function oW(t){return Dr.join(t,sW)}function aR(t){if(!sR(Dr.join(t,"agents"))||!sR(Dr.join(t,"package.json")))return!1;try{return JSON.parse(eW(Dr.join(t,"package.json"),"utf8")).name==="agestra"}catch{return!1}}function oR(t){let e=Dr.resolve(t);for(;;){if(aR(e))return e;let r=iR(e);if(r===e)return null;e=r}}function cR(){let t=process.env.AGESTRA_BASE_DIR?.trim();if(t){let r=Dr.resolve(t);if(aR(r))return r}let e=iR(rW(import.meta.url));return oR(e)??oR(process.cwd())??process.cwd()}async function qy(t){let e=Dr.join(t,"scripts","host-assets","codex-assets.mjs");return import(nW(e).href)}function uR(t){return Dr.resolve(t.workspaceBaseDir??process.cwd())}async function Ed(t,e){let r=cR(),n=await qy(r),s=Dr.join(r,"agents"),o=n.resolveAgestraHome(),i=uR(e),a=await n.loadCodexRoleSpecsFromAgentsDir(s);if(a.length===0)throw new Error(`No Codex role prompts were found in ${s}.`);let c=n.buildCodexHostAssetFiles({roles:a,scope:t,homeDir:o,repoRoot:i}),u=[],l=[],d=[],p=[];for(let f of c){let m;try{m=await tW(f.path,"utf8")}catch(h){if(h?.code==="ENOENT"){l.push(f);continue}throw h}m===f.content?u.push(f):m.includes(n.MANAGED_HEADER)?d.push(f):p.push(f)}return{host:"codex",scope:t,sourceRoot:r,agentsDir:s,targetDir:n.resolveCodexAgentsDir({scope:t,homeDir:o,repoRoot:i}),manifestPath:oW(o),roles:a,files:c,current:u,missing:l,stale:d,conflicts:p}}function iW(t){return t?.toLowerCase().includes("codex")??!1}function Rd(t,e){return t==="codex"||iW(e.sessionContext?.hostKind)?"codex":null}function Uy(t){return["# Agestra Host Assets","",`Current host: ${t.sessionContext?.hostKind??"(unknown)"}`,"Status: unsupported","Automatic setup: not run","",'Agestra did not install anything automatically. Pass `host: "codex"` to inspect or install Codex assets explicitly.'].join(`
|
|
528
|
+
`)}function aW(t){return t.conflicts.length>0?"conflict":t.stale.length>0?"stale":t.missing.length===t.files.length?"not-installed":t.missing.length>0?"partial":"current"}function Ly(t,e){return e.length===0?[]:[`${t}:`,...e.map(r=>`- ${r.roleName}: ${r.path}`)]}function Id(t,e){let r=[`Host: ${t.host}`,`Scope: ${t.scope}`,`Status: ${aW(t)}`,`Installed/current: ${t.current.length}/${t.files.length}`,`Source: ${t.agentsDir}`,`Target: ${t.targetDir}`,`Manifest: ${t.manifestPath}`];return e?(r.push(""),t.conflicts.length>0?(r.push(...Ly("Unmanaged conflicts",t.conflicts)),r.push(""),r.push("Refusing to overwrite conflicts. Move or remove those files before installing."),r):(r.push(...Ly("Missing",t.missing)),t.missing.length>0&&t.stale.length>0&&r.push(""),r.push(...Ly("Stale",t.stale)),t.missing.length===0&&t.stale.length===0?r.push("No install action is needed."):r.push("Run `host_assets_install` to install or refresh these assets."),r)):r}async function Zy(t){if(Rd("auto",t)!=="codex")return[`- Current host: ${t.sessionContext?.hostKind??"(unknown)"}`,"- Host-native asset check: unavailable for this host","- Automatic setup: not run"];let r=await Ed("project",t);return Id(r,!1).map(n=>`- ${n}`)}function cW(){return[{name:"host_assets_status",title:"Read Host Asset Status",description:"Check whether host-native Agestra assets, currently Codex custom agents, are installed and current.",inputSchema:{type:"object",properties:{host:{type:"string",enum:["auto","codex"],description:"Host asset family to inspect."},scope:{type:"string",enum:["project","user"],description:"Project-local or user-level assets."}},required:[]}},{name:"host_assets_install",title:"Install Host Assets",description:"Explicitly install or refresh host-native Agestra assets. For Codex this writes managed custom agent TOML files.",inputSchema:{type:"object",properties:{host:{type:"string",enum:["auto","codex"],description:"Host asset family to install."},scope:{type:"string",enum:["project","user"],description:"Project-local or user-level assets."}},required:[]}},{name:"host_assets_uninstall",title:"Uninstall Host Assets",description:"Remove host-native Agestra assets that are tracked in the Agestra host asset manifest.",inputSchema:{type:"object",properties:{host:{type:"string",enum:["auto","codex"],description:"Host asset family to uninstall."},scope:{type:"string",enum:["project","user"],description:"Project-local or user-level assets."}},required:[]}}]}async function uW(t,e){let r=Fy.parse(t??{});if(Rd(r.host,e)!=="codex")return In(Uy(e));let s=await Ed(r.scope,e);return In(["# Agestra Host Assets","",...Id(s,!0)].join(`
|
|
529
|
+
`))}async function lW(t,e){let r=Fy.parse(t??{});if(Rd(r.host,e)!=="codex")return In(Uy(e),!0);let s=await Ed(r.scope,e);if(s.conflicts.length>0)return In(["# Agestra Host Assets Install","",...Id(s,!0)].join(`
|
|
530
|
+
`),!0);let i=await(await qy(s.sourceRoot)).installCodexHostAssets({scope:r.scope,repoRoot:uR(e),roles:s.roles}),a=await Ed(r.scope,e);return In(["# Agestra Host Assets Installed","",`Installed files: ${i.installed.length}`,`Manifest: ${i.manifestPath}`,"",...Id(a,!1)].join(`
|
|
531
|
+
`))}async function dW(t,e){let r=Fy.parse(t??{});if(Rd(r.host,e)!=="codex")return In(Uy(e),!0);let s=cR(),i=await(await qy(s)).uninstallCodexHostAssets({scope:r.scope}),a=["# Agestra Host Assets Uninstalled","",`Removed files: ${i.removed.length}`,`Left modified files: ${i.leftModified.length}`,`Manifest: ${i.manifestPath}`];return i.leftModified.length>0&&(a.push(""),a.push("Modified managed files were left in place:"),a.push(...i.leftModified.map(c=>`- ${c}`))),In(a.join(`
|
|
532
|
+
`))}async function pW(t,e,r){switch(t){case"host_assets_status":return uW(e,r);case"host_assets_install":return lW(e,r);case"host_assets_uninstall":return dW(e,r);default:return In(`Unknown tool: ${t}`,!0)}}var hW=g.object({}),gW=g.object({enabled_providers:g.array(g.string()).describe("Provider IDs to enable for Agestra workflows."),locale:g.enum(["ko","en","ja","zh"]).describe("UI language for moderator/setup-facing text."),selection_policy:g.enum(["default-only","auto"]).optional().default("default-only").describe("Provider selection policy stored in providers.config.json."),dry_run:g.boolean().optional().default(!1).describe("When true, compute the resulting config without writing it to disk.")});function yW(t){if(!fW(t))return null;try{return JSON.parse(mW(t,"utf-8"))}catch{return null}}function lR(t){return!t||!Array.isArray(t.providers)?[]:t.providers.filter(e=>e.enabled)}function vW(t){return lR(t).length===0}function _W(t,e){if(!t)return["Current config: not found",`Expected location: ${e}`];let r=lR(t);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 bW(){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 wW(t){let e=mi(),r=yW(e),{results:n}=await si(t.workspaceBaseDir!==void 0?{workspaceBaseDir:t.workspaceBaseDir}:void 0),s=["# Agestra Setup"];if(s.push(""),s.push(..._W(r,e)),vW(r)&&(s.push("Setup required: yes"),s.push("Recommended next action: ask the user for provider selection and locale, then call setup_apply.")),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"}`);s.push(""),s.push("Host assets:");try{s.push(...await Zy(t))}catch(o){let i=o instanceof Error?o.message:String(o);s.push(`- Host-native asset check failed: ${i}`),s.push("- Automatic setup: not run")}return{content:[{type:"text",text:s.join(`
|
|
533
|
+
`)}]}}async function SW(t,e){let r=gW.parse(t),n=mi(),{results:s}=await si(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=rR(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(`
|
|
534
|
+
`)}]}}async function $W(t,e,r){switch(t){case"setup_status":return hW.parse(e),wW(r);case"setup_apply":return SW(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Hy={};rt(Hy,{getTools:()=>PW,handleTool:()=>EW});var xW=g.object({model:g.string().describe("Model name to download (e.g. 'llama3', 'codellama')")});function PW(){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 dR(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 kW(t){let r=dR(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})
|
|
526
535
|
|
|
527
536
|
`;for(let s of r){let o=(s.size/1e9).toFixed(1);n+=`## ${s.name}
|
|
528
537
|
`,n+=`- **Size:** ${o} GB
|
|
529
538
|
`,s.strengths.length>0&&(n+=`- **Strengths:** ${s.strengths.join(", ")}
|
|
530
539
|
`),n+=`
|
|
531
|
-
`}return{content:[{type:"text",text:n}]}}async function
|
|
540
|
+
`}return{content:[{type:"text",text:n}]}}async function TW(t,e){let r=xW.parse(t),n=dR(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**
|
|
532
541
|
**Model:** ${r.model}
|
|
533
542
|
**Error:** HTTP ${o.status}: ${a}`}],isError:!0}}let i=await o.json();return{content:[{type:"text",text:`**Model pulled successfully**
|
|
534
543
|
**Model:** ${r.model}
|
|
535
544
|
**Status:** ${i.status||"success"}`}]}}catch(s){let o=D(s);return{content:[{type:"text",text:`**Pull failed**
|
|
536
545
|
**Model:** ${r.model}
|
|
537
|
-
**Error:** ${o}`}],isError:!0}}}async function
|
|
538
|
-
`)}function
|
|
546
|
+
**Error:** ${o}`}],isError:!0}}}async function EW(t,e,r){switch(t){case"ollama_models":return kW(r);case"ollama_pull":return TW(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Wy={};rt(Wy,{getTools:()=>CW,handleTool:()=>MW});var IW=g.object({title:g.string().describe("Document title"),metadata:g.record(g.string()).optional().describe("Optional key-value metadata"),kind:g.enum(["individual","debate","synthesis","general"]).optional().describe("Semantic placement: 'individual' / 'debate' / 'synthesis' / 'general' (default).")}).optional(),fR=g.object({provider:g.string().describe("Provider ID (e.g. 'gemini', 'codex')"),prompt:g.string().describe("Prompt to send to the provider CLI"),timeout:g.number().int().positive().optional().describe("Timeout in ms (default: 300000)"),save_as_document:IW.describe("If set, the job output will be saved as a workspace document on completion. Returned via cli_job_status once finalized.")}).strict(),mR=g.object({job_id:g.string().describe("Job ID returned by cli_job_submit")});function pR(t){if(!Number.isFinite(t)||t<0)return"0s";let e=Math.floor(t/1e3);if(e<60)return`${e}s`;let r=Math.floor(e/60),n=e%60;return n===0?`${r}m`:`${r}m ${n}s`}function RW(t){let e=[t.kind];return t.message&&e.push(t.message),e.join(" - ")}function AW(t){let e=t.activity;if(!e)return"";let r=[`- Last host observation: ${RW(e)}`];if(t.startedAt){let n=Date.now()-Date.parse(t.startedAt),s=e.timeoutMs?` / ${pR(e.timeoutMs)}`:"";r.push(`- Elapsed: ${pR(n)}${s}`)}return e.updatedAt&&r.push(`- Updated: ${e.updatedAt}`),e.command&&r.push(`- Command: ${e.command}`),e.lastStderrPreview&&r.push(`- Last stderr: ${e.lastStderrPreview}`),e.lastStdoutPreview&&r.push(`- Last stdout: ${e.lastStdoutPreview}`),(e.stdoutBytes||e.stderrBytes)&&r.push(`- Observed output: stdout ${e.stdoutBytes??0} bytes, stderr ${e.stderrBytes??0} bytes`),r.join(`
|
|
547
|
+
`)}function CW(){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:W(fR)},{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:W(mR)}]}async function DW(t,e){let r=fR.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?`
|
|
539
548
|
**Save on complete:** ${r.save_as_document.title}`:"";return{content:[{type:"text",text:`**Job submitted**
|
|
540
549
|
**Job ID:** ${n}
|
|
541
550
|
**Provider:** ${r.provider}${s}
|
|
542
551
|
|
|
543
|
-
Use \`cli_job_status\` with this job_id to check progress.`}]}}async function
|
|
552
|
+
Use \`cli_job_status\` with this job_id to check progress.`}]}}async function OW(t,e){let r=mR.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}
|
|
544
553
|
**State:** ${n.state}`;n.provider&&(s+=`
|
|
545
554
|
**Provider:** ${n.provider}`),n.exitCode!==void 0&&(s+=`
|
|
546
555
|
**Exit Code:** ${n.exitCode}`),n.savedDocumentId?s+=`
|
|
547
556
|
**Document ID:** ${n.savedDocumentId}`:n.saveError&&(s+=`
|
|
548
|
-
**Save error:** ${n.saveError}`);let o=
|
|
557
|
+
**Save error:** ${n.saveError}`);let o=AW(n);return o&&(s+=`
|
|
549
558
|
|
|
550
559
|
**Progress:**
|
|
551
560
|
${o}`),n.output&&(s+=`
|
|
@@ -556,10 +565,10 @@ ${o}`),n.output&&(s+=`
|
|
|
556
565
|
${n.output}`),n.error&&(s+=`
|
|
557
566
|
|
|
558
567
|
**Stderr:**
|
|
559
|
-
${n.error}`),{content:[{type:"text",text:s}],isError:n.state==="error"||n.state==="missing_cli"}}async function
|
|
568
|
+
${n.error}`),{content:[{type:"text",text:s}],isError:n.state==="error"||n.state==="missing_cli"}}async function MW(t,e,r){switch(t){case"cli_job_submit":return DW(e,r);case"cli_job_status":return OW(e,r);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}var Ky={};rt(Ky,{getTools:()=>zW,handleTool:()=>jW});var hR=g.object({provider_id:g.string().optional(),task:g.string().optional(),trace_id:g.string().optional(),days_back:g.number().optional().default(7),limit:g.number().optional().default(50)}),gR=g.object({days_back:g.number().optional().default(30)}),yR=g.object({trace_id:g.string()});function zW(){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:W(hR)},{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:W(gR)},{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:W(yR)}]}async function jW(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 NW(e,n);case"trace_summary":return LW(e,n);case"trace_visualize":return FW(e,n);default:return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}}function NW(t,e){let r=hR.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)
|
|
560
569
|
|
|
561
570
|
`;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+=`
|
|
562
|
-
`;return{content:[{type:"text",text:s}]}}function
|
|
571
|
+
`;return{content:[{type:"text",text:s}]}}function LW(t,e){let r=gR.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)
|
|
563
572
|
|
|
564
573
|
`;s+=`| Provider:Task | Avg Quality | Count | Avg Latency |
|
|
565
574
|
`,s+=`|---|---|---|---|
|
|
@@ -567,23 +576,23 @@ ${n.error}`),{content:[{type:"text",text:s}],isError:n.state==="error"||n.state=
|
|
|
567
576
|
`;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+=`
|
|
568
577
|
**Provider Difficulty Qualification**
|
|
569
578
|
|
|
570
|
-
`,s+=`| Provider | Overall Avg | Samples | Low | Medium (>=${
|
|
579
|
+
`,s+=`| Provider | Overall Avg | Samples | Low | Medium (>=${vc.medium}) | High (>=${vc.high}) |
|
|
571
580
|
`,s+=`|---|---|---|---|---|---|
|
|
572
|
-
`;for(let[a,c]of o){let u=c.totalScore/c.count,l=i.map(d=>
|
|
573
|
-
`}return{content:[{type:"text",text:s}]}}function
|
|
581
|
+
`;for(let[a,c]of o){let u=c.totalScore/c.count,l=i.map(d=>_c(u,d)?"YES":"no");s+=`| ${a} | ${u.toFixed(2)} | ${c.count} | ${l[0]} | ${l[1]} | ${l[2]} |
|
|
582
|
+
`}return{content:[{type:"text",text:s}]}}function FW(t,e){let r=yR.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}
|
|
574
583
|
`;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}]
|
|
575
584
|
`;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}]
|
|
576
585
|
`,a.quality&&(s+=` ${c}R --> ${c}Q[Quality: ${a.quality.score}]
|
|
577
586
|
`)}return s+="```",{content:[{type:"text",text:`**Trace Visualization: ${r.trace_id}**
|
|
578
587
|
|
|
579
|
-
${s}`}]}}var
|
|
588
|
+
${s}`}]}}var Gy={};rt(Gy,{getTools:()=>VW,handleTool:()=>WW,resetCache:()=>BW});import{execFile as qW}from"child_process";import{promisify as UW}from"util";var _R=UW(qW),bR=5e3;async function pc(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:r}=await _R(e,[t],{timeout:bR,encoding:"utf-8"});return r.split(/\r?\n/).map(s=>s.trim()).find(Boolean)||null}catch{return null}}async function ZW(){try{return await _R("git",["worktree","list"],{timeout:bR,encoding:"utf-8"}),!0}catch{return!1}}function VW(){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 Ad=null,Jy=null;function BW(){Ad=null,Jy=null}async function HW(t,e){let r=JSON.stringify(e.sessionContext??null);if(Ad&&Jy===r&&!t.force_refresh)return{content:[{type:"text",text:vR(Ad)}]};let n=typeof e.registry.getAvailable=="function"?e.registry.getAvailable():e.registry.getAll().filter(F=>F.isAvailable()),s=n.find(F=>F.type==="claude-cli"),o=n.find(F=>F.type==="claude-host"),i=n.find(F=>F.type==="codex-cli"),a=n.find(F=>F.type==="codex-host"),c=n.find(F=>F.type==="gemini-cli"),u=n.find(F=>F.type==="gemini-host"),[l,d,p,f,m,h]=await Promise.all([pc("claude"),pc("codex"),pc("gemini"),pc("tmux"),pc("git"),ZW()]),y=[],v=e.registry.getAll(),_=v.find(F=>F.id==="ollama");if(_?.isAvailable()){let F=_.getCapabilities();for(let xe of F.models){let We=xe.sizeGb??0;y.push({name:xe.name,size_gb:We,tier:Vd(We)})}}let b=i!==void 0||c!==void 0,P=f!==null,x=m!==null&&h,N=a!==void 0||u!==void 0||e.sessionContext?.hostKind==="codex-cli"||e.sessionContext?.hostKind==="gemini-cli",k=v.some(F=>F.isAvailable()&&!F.type.endsWith("-host")&&F.id!=="ollama"),O=[N?"leader_only":"claude_only"];(k||y.length>0)&&O.push("independent","debate"),b&&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:_?.isAvailable()??!1,models:y},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:b&&x,can_tmux_visible:P,can_parallel_workers:b&&x,max_parallel_workers:b?3:0,available_modes:O}};return Ad=L,Jy=r,{content:[{type:"text",text:vR(L)}]}}function vR(t){let e=`# Environment Check
|
|
580
589
|
|
|
581
590
|
`;t.host&&(e+=`## Host Session
|
|
582
591
|
|
|
583
592
|
`,e+=`- **Host:** ${t.host.id}
|
|
584
593
|
`,e+=`- **Kind:** ${t.host.kind}
|
|
585
594
|
`,e+=`- **Leader Provider:** ${t.host.leader_provider}
|
|
586
|
-
`,e+=`- **Execution Mode:** ${
|
|
595
|
+
`,e+=`- **Execution Mode:** ${Td(t.host.execution_mode,t.host.kind)}
|
|
587
596
|
`,e+=`- **Participants:** ${t.host.participant_providers.join(", ")}
|
|
588
597
|
|
|
589
598
|
`),e+=`## Providers
|
|
@@ -607,14 +616,14 @@ ${s}`}]}}var Ny={};rt(Ny,{getTools:()=>AW,handleTool:()=>OW,resetCache:()=>CW});
|
|
|
607
616
|
`,e+=`- **tmux visible:** ${t.capabilities.can_tmux_visible?"Yes":"No"}
|
|
608
617
|
`,e+=`- **Parallel workers:** ${t.capabilities.can_parallel_workers?`Yes (max ${t.capabilities.max_parallel_workers})`:"No"}
|
|
609
618
|
`,e+=`- **Available modes:** ${t.capabilities.available_modes.join(", ")}
|
|
610
|
-
`,e}async function
|
|
619
|
+
`,e}async function WW(t,e,r){return t==="environment_check"?HW(e??{},r):{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var Yy={};rt(Yy,{getTools:()=>KW,handleTool:()=>nK});var wR=g.object({provider:g.string().trim().min(1),task_description:g.string().trim().min(1),working_dir:g.string().trim().min(1),files_to_read:g.array(g.string().trim().min(1)).optional(),files_to_modify:g.array(g.string().trim().min(1)).optional(),constraints:g.string().optional(),success_criteria:g.array(g.string().trim().min(1)).optional(),timeout_minutes:g.number().positive().optional(),use_worktree:g.boolean().optional(),use_tmux:g.boolean().optional()}).strict(),SR=g.object({worker_id:g.string().trim().min(1).optional()}).strict(),$R=g.object({worker_id:g.string().trim().min(1)}).strict(),xR=g.object({worker_id:g.string().trim().min(1)}).strict();function KW(){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:W(wR)},{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:W(SR)},{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:W($R)},{name:"cli_worker_stop",title:"Stop CLI Worker",description:"Stop a running CLI worker. Sends SIGTERM, then SIGKILL after 5 seconds.",inputSchema:W(xR)}]}function Cd(t){if(!t.cliWorkerManager)throw new Error("CliWorkerManager not initialized \u2014 cli_worker tools are unavailable");return t.cliWorkerManager}function hr(t,e){return{content:[{type:"text",text:t}],...e?{isError:e}:{}}}function JW(t){let e=`# Worker Spawned
|
|
611
620
|
|
|
612
621
|
`;return e+=`- **Worker ID:** ${t.workerId}
|
|
613
622
|
`,e+=`- **Provider:** ${t.provider}
|
|
614
623
|
`,e+=`- **State:** ${t.state}
|
|
615
624
|
`,e+=`- **PID:** ${t.pid??"N/A"}
|
|
616
625
|
`,t.worktreeBranch&&(e+=`- **Worktree Branch:** ${t.worktreeBranch}
|
|
617
|
-
`),e}function
|
|
626
|
+
`),e}function GW(t){let e=`# Worker Status
|
|
618
627
|
|
|
619
628
|
`;return e+=`- **Worker ID:** ${t.workerId}
|
|
620
629
|
`,e+=`- **Provider:** ${t.provider}
|
|
@@ -623,18 +632,18 @@ ${s}`}]}}var Ny={};rt(Ny,{getTools:()=>AW,handleTool:()=>OW,resetCache:()=>CW});
|
|
|
623
632
|
`,e+=`- **PID:** ${t.pid??"N/A"}
|
|
624
633
|
`,e+=`- **Retry Count:** ${t.retryCount}
|
|
625
634
|
`,t.worktreeBranch&&(e+=`- **Worktree Branch:** ${t.worktreeBranch}
|
|
626
|
-
`),t.state===
|
|
635
|
+
`),t.state===Fe.COLLECTING&&(e+="- **Next Step:** Worker exited successfully and is ready for `cli_worker_collect`\n"),t.outputTail&&(e+=`
|
|
627
636
|
## Recent Output
|
|
628
637
|
|
|
629
638
|
\`\`\`
|
|
630
639
|
${t.outputTail}
|
|
631
640
|
\`\`\`
|
|
632
|
-
`),e}function
|
|
641
|
+
`),e}function YW(t){if(t.length===0)return`# Workers
|
|
633
642
|
|
|
634
643
|
No tracked workers.`;let e=`# Workers (${t.length})
|
|
635
644
|
|
|
636
645
|
`;for(let r of t)e+=`- **${r.workerId}** \u2014 ${r.provider} \u2014 ${r.state}`,r.pid&&(e+=` (PID ${r.pid})`),e+=`
|
|
637
|
-
`;return e}function
|
|
646
|
+
`;return e}function XW(t){let e=`# Worker Results
|
|
638
647
|
|
|
639
648
|
`;if(e+=`- **Worker ID:** ${t.workerId}
|
|
640
649
|
`,e+=`- **State:** ${t.state}
|
|
@@ -656,7 +665,7 @@ ${t.gitDiff}
|
|
|
656
665
|
\`\`\`
|
|
657
666
|
${t.outputFull}
|
|
658
667
|
\`\`\`
|
|
659
|
-
`),e}async function
|
|
668
|
+
`),e}async function QW(t,e){let r=Cd(e),n=wR.parse(t),s=r.knownProviders();if(!s.includes(n.provider))return hr(`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 hr(JW(i))}catch(i){let a=D(i);return hr(`Error spawning worker: ${a}`,!0)}}async function eK(t,e){let r=Cd(e),n=SR.parse(t);if(!n.worker_id){let o=r.listAll();return hr(YW(o))}let s=r.getStatus(n.worker_id);return s?hr(GW(s)):hr(`Worker not found: ${n.worker_id}`,!0)}async function tK(t,e){let r=Cd(e),n=$R.parse(t),s=r.collect(n.worker_id);return s?hr(XW(s)):hr(`Worker not found: ${n.worker_id}`,!0)}async function rK(t,e){let r=Cd(e),n=xR.parse(t);return r.stop(n.worker_id),hr(`Stop signal sent to worker: ${n.worker_id}`)}async function nK(t,e,r){try{switch(t){case"cli_worker_spawn":return await QW(e??{},r);case"cli_worker_status":return await eK(e??{},r);case"cli_worker_collect":return await tK(e??{},r);case"cli_worker_stop":return await rK(e??{},r);default:return hr(`Unknown tool: ${t}`,!0)}}catch(n){let s=D(n);return hr(`Error: ${s}`,!0)}}var Xy={};rt(Xy,{getTools:()=>sK,handleTool:()=>iK});var PR=g.object({design_doc:g.string().optional().describe("Optional design document path to verify against"),build_profile:g.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:g.number().int().positive().optional().describe("Timeout per command in milliseconds")}).strict();function sK(){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:W(PR)}]}function oK(t){let e=`# Workspace QA
|
|
660
669
|
|
|
661
670
|
${t.summary}
|
|
662
671
|
`;return t.designDoc&&(e+=`
|
|
@@ -673,12 +682,12 @@ ${t.buildOutput||"(no output)"}
|
|
|
673
682
|
\`\`\`
|
|
674
683
|
${t.testOutput||"(no output)"}
|
|
675
684
|
\`\`\`
|
|
676
|
-
`,e}async function
|
|
685
|
+
`,e}async function iK(t,e,r){if(t==="qa_run"){let n=PR.parse(e??{}),o=await new Ti(r?.workspaceBaseDir??process.cwd()).run({designDoc:n.design_doc,buildProfile:n.build_profile??"auto",timeoutMs:n.timeout_ms});return{content:[{type:"text",text:oK(o)}],isError:!(o.buildPassed&&o.testsPassed)}}else return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0}}var TR=[uy,My,zy,jy,By,Vy,Hy,Wy,Ky,Gy,Yy,Xy];function ER(){let t=[];for(let e of TR)t.push(...e.getTools());return t}var fc=new Map,cK=100;function uK(t,e){if(fc.set(t,e),fc.size>cK){let r=fc.keys().next().value;r!==void 0&&fc.delete(r)}}function lK(t){return t.sessionId??"__default__"}function dK(t){for(let e of t)if(!(typeof e.uri!="string"||!e.uri.startsWith("file://")))try{return aK(e.uri)}catch{}}async function pK(t,e,r){let n=lK(r);try{let s=await t.listRoots(void 0,{timeout:1500}),o=dK(s.roots);if(o)return uK(n,o),o}catch{}return fc.get(n)??e.workspaceBaseDir??process.cwd()}function fK(t,e){return t.filter(r=>IR(r.name,e))}function mK(t,e){let r=Qr(t);if(r.invocation!=="cli"||!r.roles.includes("worker"))return!1;let n=e?.get(t.id)??"workspace-write";return Ws(n)}function IR(t,e){let r=e.registry.getAvailable(),n=r.length>0,s=r.some(i=>i.type==="ollama"),o=r.some(i=>mK(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 hK(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 Qy=null;function gK(){if(Qy)return Qy;let t=new Map;for(let e of TR)for(let r of e.getTools())t.set(r.name,e);return Qy=t,t}function RR(t){let e=t.content.map(r=>r.type==="text"&&Buffer.byteLength(r.text,"utf-8")>51200?{type:"text",text:hK(r.text,51200)+`
|
|
677
686
|
|
|
678
|
-
... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function
|
|
687
|
+
... [Response truncated at 50KB]`}:r);return{...t,content:e}}async function AR(t,e,r){let s=gK().get(t);if(!s)return{content:[{type:"text",text:`Unknown tool: ${t}`}],isError:!0};if(await r.ensureRuntimeReady?.(),!IR(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,providerPolicies:r.providerPolicies,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 RR(i)}function ev(t){let e=new Jl({name:"agestra",version:uv},{capabilities:{tools:{}}});return e.setRequestHandler(Ef,async()=>(await t.ensureRuntimeReady?.(),{tools:fK(ER(),t)})),e.setRequestHandler(Xi,async(r,n)=>{let{name:s,arguments:o}=r.params;try{await t.ensureRuntimeReady?.();let i=await pK(e,t,n),a=await t.resolveWorkspaceServices?.(i)??{},c=await AR(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 tv(t){let e=new Yl;await t.connect(e)}function CR(t){return typeof t=="object"&&t!==null&&t.type==="text"&&typeof t.text=="string"}function yK(t){return Array.isArray(t)?t.filter(CR).map(e=>e.text).join(`
|
|
679
688
|
|
|
680
|
-
`).trim():
|
|
681
|
-
`),e=
|
|
682
|
-
`),process.exit(1)}),t(`Starting MCP server with ${s.getAll().length} provider(s)...`),await
|
|
683
|
-
`),process.exit(1)});export{
|
|
689
|
+
`).trim():CR(t)?t.text:""}function DR(t,e){let r=t?.[e];return typeof r=="number"&&Number.isFinite(r)?r:void 0}function OR(t,e){let r=t?.[e];return typeof r=="string"&&r.length>0?r:void 0}function oi(t){let e=t?.toLowerCase()??"";return e.includes("claude")?"claude-code":e.includes("codex")?"codex-cli":e.includes("gemini")?"gemini-cli":"unknown"}function rv(t,e,r){let n=()=>oi(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:DR(s.metadata,"maxTokens")??4096,temperature:DR(s.metadata,"temperature"),modelPreferences:OR(s.metadata,"model")?{hints:[{name:OR(s.metadata,"model")}]}:void 0,metadata:s.metadata}),i=yK(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 Dd(t,e="claude"){return rv(t,e,{expectedHostKind:"claude-code",displayName:"Claude",unavailableMessage:"Claude host bridge unavailable or client does not support sampling"})}function Od(t,e="codex-host"){return rv(t,e,{expectedHostKind:"codex-cli",displayName:"Codex",unavailableMessage:"Codex host bridge unavailable or client does not support sampling"})}function Md(t,e="gemini-host"){return rv(t,e,{expectedHostKind:"gemini-cli",displayName:"Gemini",unavailableMessage:"Gemini host bridge unavailable or client does not support sampling"})}var vK=[{type:"claude-host",defaultId:"claude",supportedHosts:["claude-code"],createProvider:(t,e)=>new Uc({id:e,bridge:Dd(t,e)})},{type:"codex-host",defaultId:"codex-host",supportedHosts:["codex-cli"],createProvider:(t,e)=>new Zc({id:e,bridge:Od(t,e)})},{type:"gemini-host",defaultId:"gemini-host",supportedHosts:["gemini-cli"],createProvider:(t,e)=>new Vc({id:e,bridge:Md(t,e)})}];function ii(t,e,r){return t?.providers.find(s=>s.type===e||s.id===r)?.id??r}function _K(t){switch(t){case"claude-code":return"claude-host";case"codex-cli":return"codex-host";case"gemini-cli":return"gemini-host";default:return}}function bK(t){switch(t){case"claude-code":return"claude-cli";case"codex-cli":return"codex-cli";case"gemini-cli":return"gemini-cli";default:return}}function wK(t,e){switch(t){case"claude-code":return ii(e,"claude-host","claude");case"codex-cli":return ii(e,"codex-host","codex-host");case"gemini-cli":return ii(e,"gemini-host","gemini-host");default:return}}function SK(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 nv(t,e){let r=()=>oi(t.getClientVersion()?.name),n=()=>_K(r()),s=()=>wK(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=ii(e,"claude-host","claude");return Dd(t,o)}case"codex-cli":{let o=ii(e,"codex-host","codex-host");return Od(t,o)}case"gemini-cli":{let o=ii(e,"gemini-host","gemini-host");return Md(t,o)}default:return null}},createHostProviders(){let o=r();return vK.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??Ot(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=bK(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:SK(i,u.id)}}}}async function sv(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 ov(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 MR}from"fs";import{dirname as jR,join as zd,resolve as NR,sep as $K}from"path";import{fileURLToPath as xK}from"url";var PK=[zd(".claude","plugins","cache"),zd(".claude","plugins","local")];function kK(t){let e=t.split(/[\\/]/).join($K);return PK.some(r=>e.includes(r))}function TK(t){return!(!MR(zd(t,"package.json"))||!MR(zd(t,"AGENTS.md"))||kK(t))}function zR(t){let e=NR(t);for(;;){if(TK(e))return e;let r=jR(e);if(r===e)return null;e=r}}function LR(){let t=process.env.AGESTRA_BASE_DIR?.trim();if(t)return NR(t);let e=jR(xK(import.meta.url));return zR(process.cwd())??zR(e)??process.cwd()}function RK(t){return{ollama:e=>new Qn({id:e.id,host:e.config?.host||ci}),"gemini-cli":e=>new es({id:e.id,timeout:e.config?.timeout,workspaceBaseDir:t}),"codex-cli":e=>new ts({id:e.id,timeout:e.config?.timeout,workspaceBaseDir:t}),"claude-cli":e=>new rs({id:e.id,timeout:e.config?.timeout,workspaceBaseDir:t})}}async function AK(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 si({workspaceBaseDir:e}),o=n.filter(i=>i.available);return o.length===0?(r("Auto-detect found no available providers."),{detected:0}):(nR(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 CK(t,e){return t===null&&e===0}async function DK(){let t=k=>process.stderr.write(`[mcp-server] ${k}
|
|
690
|
+
`),e=LR(),r=mi(),n;try{let k=EK(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 bc,o=null;if(n)try{o=Fv(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=RK(e);if(o){let k=o.enabledProviders.map(L=>{let F=i[L.type];if(!F)return t(`Unknown provider type: ${L.type} (id: ${L.id}), skipping`),null;let xe=F(L);return{pc:L,provider:xe}}).filter(L=>L!==null),O=await Promise.allSettled(k.map(async({pc:L,provider:F})=>(await F.initialize(),{pc:L,provider:F})));for(let L of O)if(L.status==="fulfilled"){let{pc:F,provider:xe}=L.value;s.register(xe),t(`Registered provider: ${F.id} (${F.type})`)}else t(`Failed to initialize provider: ${D(L.reason)}`)}if(CK(o,s.getAll().length)?await AK(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 si({workspaceBaseDir:e}),F=Ny(L,s,{excludeIds:k,excludeTypes:O});for(let xe of F)t(`Registered newly detected provider: ${xe.id} (${xe.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)??Ot(k.type)])),u;try{u=hp(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=hp(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!=="unknown"&&L.hostKind===O)return L;L.traceWriter.shutdown()}let F=new $i(iv(k,mv)),xe=new Ri(iv(k,ui)),We=new Oc(k,{completionHandler:async({descriptor:gr,result:jd,saveAsDocument:Nd})=>!jd.output||jd.output.trim().length===0?null:{documentId:(await xe.createDocument({title:Nd.title,content:jd.output,metadata:{...Nd.metadata,Provider:gr.provider,Model:gr.provider,JobId:gr.id},kind:Nd.kind})).id}});try{let gr=We.reconcileOrphans();gr>0&&t(`Reconciled ${gr} orphaned job(s) in ${k}`)}catch(gr){t(`Job orphan reconcile failed for ${k}: ${D(gr)}`)}let Ct=new Mc(k);Ct.cleanup(30);let Nt=new Fc(Ct,{ttlMs:6e4}),av=new bi(k,{providerPolicies:c}),As=new ri(iv(k,ui));try{await As.hydrateFromDisk()}catch(gr){t(`Structured session registry hydrate failed for ${k}: ${D(gr)}`)}let Dt=$d(s,O,k),Rn=new ni({bridge:Dt,documentManager:xe,registry:As,i18n:u,traceWriter:Ct}),ai={hostKind:O,sessionManager:F,documentManager:xe,jobManager:We,traceWriter:Ct,qualityStatsProvider:Nt,cliWorkerManager:av,structuredSessionRegistry:As,moderatorEngine:Rn};return O!=="unknown"&&l.set(k,ai),ai},m=await f(e),h={registry:s,...m,providerPolicies:c,workspaceBaseDir:e,ensureRuntimeReady:()=>p(),resolveWorkspaceServices:async k=>(await p(),f(k)),i18n:u},y=ev(h),v=nv(y,o);d=()=>oi(y.getClientVersion()?.name);let _,b=null;p=async()=>{let k=d();k==="unknown"||_===k||(b||(b=(async()=>{try{await sv(v,s,c,t),_=k}catch(O){t(`Host-backed provider registration failed (non-fatal): ${D(O)}`)}finally{b=null}})()),await b)},h.resolveSessionContext=()=>ov(v,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)}`)}})()},$v);P.unref?.();let x=!1,N=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",()=>{N().finally(()=>process.exit(0))}),process.on("SIGINT",()=>{N().finally(()=>process.exit(0))}),process.on("uncaughtException",k=>{for(let O of l.values())O.traceWriter.panicFlush();process.stderr.write(`[mcp-server] Uncaught: ${k}
|
|
691
|
+
`),process.exit(1)}),t(`Starting MCP server with ${s.getAll().length} provider(s)...`),await tv(y),t("MCP server connected via stdio.")}var OK=(()=>{if(typeof process>"u"||!process.argv[1])return!1;try{let t=IK(import.meta.url),e=process.argv[1];return e===t||e.endsWith("/dist/bundle.js")}catch{return!1}})();OK&&DK().catch(t=>{process.stderr.write(`[mcp-server] Fatal: ${t}
|
|
692
|
+
`),process.exit(1)});export{AK as autoDetectIfNeeded,ER as collectTools,tv as connectStdio,Dd as createClaudeLeaderBridge,Od as createCodexLeaderBridge,Md as createGeminiLeaderBridge,nv as createRuntimeHostAdapter,ev as createServer,AR as dispatch,oi as inferHostKindFromClientName,sv as registerHostBackedProviders,ov as resolveSessionContext,CK as shouldRunStartupAutoDetect,RR as truncateResponse};
|
|
684
693
|
//# sourceMappingURL=bundle.js.map
|