pando-ai 0.9.1 → 0.9.2

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/dist/cli.js CHANGED
@@ -20,7 +20,7 @@
20
20
  `);if(n<0)break;let r=this.buffer.slice(0,n).trim();if(this.buffer=this.buffer.slice(n+1),!r)continue;let s=null;try{s=JSON.parse(r)}catch{continue}let o=this.pending.get(s.id);o&&(this.pending.delete(s.id),s.ok?o.resolve(s):o.reject(new Error(s.error||"csharp server error")))}}async request(e,n=1){this.ensureProcess();let r=this.seq++;return new Promise((s,o)=>{let i={id:r,...e};this.pending.set(r,{resolve:s,reject:o});try{this.proc.stdin.write(`${JSON.stringify(i)}
21
21
  `)}catch(a){if(this.pending.delete(r),n>0){try{this.handleExit(a)}catch{}return this.request(e,n-1).then(s,o)}o(a)}})}async parseBatch(e){let n=await this.request({op:"parse",files:e});return"results"in n?n.results.map(r=>r.ok&&r.result?r.result:null):"result"in n?[n.result]:e.map(()=>null)}async resolve(e){let n=await this.request({op:"resolve",...e});return"result"in n&&n.result&&typeof n.result.start=="number"?n.result:null}async resolveReferences(e){let n=await this.request({op:"resolve-references",...e});return"result"in n&&n.result?n.result:null}close(){if(this.closed)return;this.closed=!0;for(let[,n]of this.pending)n.reject(new Error("csharp indexer client closed"));this.pending.clear();let e=this.proc;if(this.proc=null,!!e){try{e.stdin?.end()}catch{}try{e.kill()}catch{}}}},ES=class{constructor(e){this.client=e;this.queue=[];this.scheduled=!1}enqueue(e){return new Promise((n,r)=>{this.queue.push({input:e,resolve:n,reject:r,startedAt:Date.now()}),this.scheduled||(this.scheduled=!0,setImmediate(()=>this.flush()))})}async flush(){for(this.scheduled=!1;this.queue.length;){let e=[],n=0;for(;this.queue.length&&e.length<Vz;){let r=this.queue[0];if(e.length>0&&n+r.input.size>Jz)break;e.push(this.queue.shift()),n+=r.input.size}try{let r=await this.client.parseBatch(e.map(s=>({file:s.input.file,root:s.input.root,lang:s.input.lang,emitMode:s.input.emitMode})));for(let s=0;s<e.length;s+=1){let o=e[s],i=r[s]??null,a=Date.now()-o.startedAt;a>2e3&&$a(`[${new Date().toISOString()}] [CSharpCliAdapter] parse slow`,{file:o.input.file,ms:a,path:"custom",ok:!!i}),i||$a(`[${new Date().toISOString()}] [CSharpCliAdapter] parse failed`,{file:o.input.file,ms:a,path:"custom"}),o.resolve(i)}}catch(r){for(let s of e)s.reject(r)}}}},fl=new Map,TS=new Map});function hl(t){let e=[],n="",r=null,s=!1;for(let o=0;o<t.length;o+=1){let i=t[o];if(s){n+=i,s=!1;continue}if(i==="\\"){s=!0;continue}if(r){i===r?r=null:n+=i;continue}if(i==='"'||i==="'"){r=i;continue}if(i===" "||i===`
22
22
  `||i===" "||i==="\r"){n&&(e.push(n),n="");continue}n+=i}return n&&e.push(n),e}function eB(t,e){let n=[];for(let r=0;r<t.length;r+=1){let s=t[r];if(s==="-c")continue;if(s==="-o"){r+=1;continue}if(s===e)continue;let o=at.default.extname(s).toLowerCase();cP.has(o)||n.push(s)}return n}function uP(t,e){return at.default.isAbsolute(t)?at.default.resolve(t):e?at.default.resolve(e,t):at.default.resolve(t)}function tB(t){try{let e=Mr.default.readFileSync(t,"utf8"),n=JSON.parse(e),r=new Map,s=[];for(let o of n){let i=o.directory?at.default.resolve(o.directory):void 0,a=o.file?uP(o.file,i):null;if(!a)continue;let c=i??at.default.dirname(a),l=Array.isArray(o.arguments)?o.arguments:o.command?hl(o.command):[];if(l.length===0)continue;let d={args:eB(l.slice(1),a),cwd:c,file:a};r.set(a,d),s.push(d)}return{map:r,entries:s}}catch{return null}}function nB(t){try{let e=Mr.default.readFileSync(t,"utf8");return hl(e.replace(/\r/g,`
23
- `))}catch{return null}}function dP(t){let e=at.default.join(t,"compile_commands.json");if(Mr.default.existsSync(e))return e;for(let i of CS){let a=at.default.join(t,i,"compile_commands.json");if(Mr.default.existsSync(a))return a}let n=CS.map(i=>at.default.join(t,i)).filter(i=>Mr.default.existsSync(i));n.push(t);let r=10,s=new Set,o=(i,a)=>{if(a>r)return null;let c=at.default.resolve(i);if(s.has(c))return null;s.add(c);try{let l=Mr.default.readdirSync(i,{withFileTypes:!0});for(let u of l)if(u.isFile()&&u.name==="compile_commands.json")return at.default.join(i,u.name);for(let u of l){if(!u.isDirectory()||u.name==="node_modules"||u.name.startsWith("."))continue;let d=o(at.default.join(i,u.name),a+1);if(d)return d}}catch{}return null};for(let i of n){let a=o(i,0);if(a)return a}return null}function rB(t,e){let n=at.default.resolve(t),r=at.default.resolve(e);for(;;){let s=dP(n);if(s)return s;if(n===r)break;let o=at.default.dirname(n);if(o===n)break;n=o}return null}function pP(t){let e=at.default.join(t,"compile_flags.txt");if(Mr.default.existsSync(e))return e;for(let n of CS){let r=at.default.join(t,n,"compile_flags.txt");if(Mr.default.existsSync(r))return r}return null}function sB(t,e){let n=at.default.resolve(t),r=at.default.resolve(e);for(;;){let s=pP(n);if(s)return s;if(n===r)break;let o=at.default.dirname(n);if(o===n)break;n=o}return null}function pd(t){if(t)try{return Mr.default.statSync(t).mtimeMs}catch{return}}function oB(t){let e=[],n=new Set([".clangd","CMakeLists.txt","meson.build","meson_options.txt","Makefile","makefile","GNUmakefile","configure.ac","configure.in"]),r=5,s=200,o=(i,a)=>{if(a>r||e.length>=s)return;let c;try{c=Mr.default.readdirSync(i,{withFileTypes:!0})}catch{return}for(let l of c){if(e.length>=s)break;let u=at.default.join(i,l.name);l.isFile()&&(n.has(l.name)||l.name.endsWith(".cmake"))&&e.push(u)}for(let l of c){if(e.length>=s)break;l.isDirectory()&&(l.name==="node_modules"||l.name===".git"||l.name===".pando"||l.name.startsWith(".cache")||o(at.default.join(i,l.name),a+1))}};return o(t,0),e}function Ui(t,e,n){if(!n)return;let r=n.trim();!r||e.has(r)||(e.add(r),t.push(r))}function ml(t,e,n,r){let s=r.trim().replace(/^["']|["']$/g,"");if(!s||s.startsWith("$")||s.includes("${")||s.includes("<"))return;let o=at.default.isAbsolute(s)?s:at.default.resolve(n,s);Mr.default.existsSync(o)&&Ui(t,e,`-I${o}`)}function iP(t){let e=[],n=new Set,r;for(let s of oB(t)){let o=pd(s);o&&(!r||o>r)&&(r=o);let i="";try{i=Mr.default.readFileSync(s,"utf8")}catch{continue}let a=at.default.dirname(s),c=i.replace(/#[^\n]*/g," "),l=hl(c.replace(/[()[\]{},;]/g," "));for(let u=0;u<l.length;u+=1){let d=l[u];(d==="-I"||d==="-isystem"||d==="/I")&&l[u+1]?(ml(e,n,a,l[u+1]),u+=1):d.startsWith("-I")&&d.length>2||d.startsWith("/I")&&d.length>2?ml(e,n,a,d.slice(2)):d.startsWith("-isystem")&&d.length>8?ml(e,n,a,d.slice(8)):d.startsWith("-D")||d.startsWith("/D")?Ui(e,n,d.startsWith("/D")?`-D${d.slice(2)}`:d):d.startsWith("-std=")&&Ui(e,n,d)}for(let u of i.matchAll(/\b(?:target_)?include_directories\s*\(([^)]*)\)/gims))for(let d of hl(u[1].replace(/[()[\]{},;]/g," ")))/^(PRIVATE|PUBLIC|INTERFACE|SYSTEM|BEFORE|AFTER)$/i.test(d)||ml(e,n,a,d);for(let u of i.matchAll(/\b(?:add_compile_definitions|target_compile_definitions)\s*\(([^)]*)\)/gims))for(let d of hl(u[1].replace(/[()[\]{},;]/g," ")))/^(PRIVATE|PUBLIC|INTERFACE)$/i.test(d)||d.includes("$")||Ui(e,n,d.startsWith("-D")?d:`-D${d}`);for(let u of i.matchAll(/\binclude_directories\s*:\s*\[([^\]]*)\]/gims))for(let d of hl(u[1].replace(/,/g," ")))ml(e,n,a,d)}return{args:e,mtime:r}}function iB(t,e){let n=at.default.resolve(t).split(at.default.sep),r=at.default.resolve(e).split(at.default.sep),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s+=1;return s}function aB(t,e){if(!t||t.length===0)return null;let n=at.default.dirname(e),r=at.default.extname(e).toLowerCase(),s=at.default.basename(e,r),o=null;for(let i of t){let a=at.default.extname(i.file).toLowerCase();if(!cP.has(a))continue;let c=at.default.dirname(i.file),l=at.default.basename(i.file,a),u=iB(e,i.file);c===n&&(u+=100),l===s&&(u+=50),lP.has(r)&&(u+=20),(!o||u>o.score)&&(o={entry:i,score:u})}return o?.entry??null}function aP(t,e){let n=e?`${at.default.resolve(t)}::${at.default.resolve(e)}`:at.default.resolve(t),r=dd.get(n);if(r){let m=pd(r.commandsPath);if(r.commandsPath&&m&&r.commandsMtime&&m!==r.commandsMtime)dd.delete(n);else if(r.flagsPath){let h=pd(r.flagsPath);if(h&&r.flagsMtime&&h!==r.flagsMtime)dd.delete(n);else return r}else if(r.projectConfigFlags){let h=iP(e??t);if(r.projectConfigMtime&&h.mtime&&r.projectConfigMtime!==h.mtime)dd.delete(n);else return r}else return r}let s=e?rB(e,t):dP(t),o=s?tB(s)??void 0:void 0,i=o?.map,a=o?.entries,c=pd(s),l=i?null:e?sB(e,t):pP(t),u=l?nB(l)??void 0:void 0,d=pd(l),p=!i&&!u?iP(e??t):void 0,f={commands:i,commandEntries:a,flags:u,projectConfigFlags:p?.args,commandsPath:s,commandsMtime:c,flagsPath:l,flagsMtime:d,projectConfigMtime:p?.mtime};return dd.set(n,f),f}function AS(t,e,n){let r=at.default.dirname(e),s=aP(t);!s.commands&&!s.flags&&(!s.projectConfigFlags||s.projectConfigFlags.length===0)&&(s=aP(t,r));let o=uP(e);if(s.commands){let i=s.commands.get(o);if(i)return{args:i.args,cwd:i.cwd,source:"compile_commands"};let a=aB(s.commandEntries,o);if(a)return{args:a.args,cwd:a.cwd,source:"compile_commands"}}return s.flags?{args:s.flags,cwd:t,source:"compile_flags"}:s.projectConfigFlags&&s.projectConfigFlags.length>0?{args:fP(s.projectConfigFlags,t,n),cwd:t,source:"project_config"}:jm(t,n)}function cB(t){let e=[],n=new Set,r=a=>{let c=at.default.resolve(a);!n.has(c)&&Mr.default.existsSync(c)&&(n.add(c),e.push(c))};r(t);for(let a of Yz)r(at.default.join(t,a));let s=Number(process.env.PANDO_CLANG_FALLBACK_INCLUDE_DEPTH||"5"),o=Number(process.env.PANDO_CLANG_FALLBACK_INCLUDE_MAX_DIRS||"300"),i=(a,c)=>{if(c>s||e.length>=o)return;let l;try{l=Mr.default.readdirSync(a,{withFileTypes:!0})}catch{return}l.some(d=>d.isFile()&&lP.has(at.default.extname(d.name).toLowerCase()))&&r(a);for(let d of l){if(e.length>=o)break;d.isDirectory()&&(d.name==="node_modules"||d.name===".git"||d.name===".pando"||d.name.startsWith(".cache")||i(at.default.join(a,d.name),c+1))}};return i(t,0),e}function fP(t,e,n){let r=[...t],s=new Set(r);r.some(o=>o.startsWith("-std="))||Ui(r,s,"-std="+(n==="cpp"?"c++20":"c17"));for(let o of cB(e))Ui(r,s,`-I${o}`);for(let o of["-ferror-limit=0","-Wno-everything","-fparse-all-comments","-fms-extensions"])Ui(r,s,o);return n==="cpp"&&Ui(r,s,"-fdelayed-template-parsing"),r}function jm(t,e){return{args:fP([],t,e),cwd:t,source:"fallback"}}var Mr,at,dd,Yz,CS,cP,lP,mP=te(()=>{"use strict";Mr=B(require("fs")),at=B(require("path")),dd=new Map,Yz=["include","src","lib","libs","third_party","third-party","deps","vendor","build","build/src","build_pando","build_pando/src"],CS=["build","out","build-debug","build-release","cmake-build-debug","cmake-build-release","build_pando"],cP=new Set([".c",".cc",".cpp",".cxx",".c++",".cp",".m",".mm"]),lP=new Set([".h",".hh",".hpp",".hxx",".h++",".inl",".ipp",".tcc"])});function lB(t){let e=`PANDO_${t.toUpperCase()}_INDEXER_CMD`;return process.env[e]||(t==="cpp"?"clang++":"clang")}function uB(){let t=process.env.PANDO_CLANG_INDEXER_CMD;if(t&&t.trim())return t.trim();let e=Rr("clang-indexer/bin/pando-clang-indexer");if(e)return e;let n=[process.env.PANDO_TOOLS_ROOT?Lm.default.join(process.env.PANDO_TOOLS_ROOT,"clang-indexer","bin","pando-clang-indexer"):null,process.env.PANDO_RUNTIME_ROOT?Lm.default.join(process.env.PANDO_RUNTIME_ROOT,"tools","clang-indexer","bin","pando-clang-indexer"):null,typeof __dirname=="string"?Lm.default.resolve(__dirname,"..","..","..","..","..","tools","clang-indexer","bin","pando-clang-indexer"):null].filter(r=>!!r);for(let r of n)try{if(hP.default.existsSync(r))return r}catch{}return"pando-clang-indexer"}function gP(t,e,n){let r=lB(n),s=a=>{let c=[...a.args,"-fsyntax-only","-fno-color-diagnostics","-fno-diagnostics-color",...a.source==="fallback"?["-x",n==="cpp"?"c++":"c"]:[],e],l=(0,IS.spawnSync)(r,c,{encoding:"utf8",cwd:a.cwd});return l.status===0?{ok:!0}:{ok:!1,error:(l.stderr||l.stdout||"").trim()||"Clang syntax validation failed."}},o=AS(t,e,n),i=s(o);if(i.ok)return i;if(o.source!=="fallback"){let a=jm(t,n),c=s(a);return c.ok,c}return i}function dB(t){if(!t)return null;let e=t;(e.startsWith("SyntaxError:")||e.startsWith("CompileError:"))&&(e=e.substring(e.indexOf(":")+1)),e.includes("#")&&(e=e.split("#")[1]);let n=e.lastIndexOf(":"),r=n>=0?e.slice(0,n):e,[s,o]=r.split("-"),i=Number(s),a=Number(o);return!Number.isFinite(i)||!Number.isFinite(a)||a<i?null:{start:i,end:a}}function NS(t){return zo({id:t,extensions:[],parse:({absPath:e,relPath:n,content:r,projectRoot:s})=>{let o=AS(s,e,t),i=l=>["--file",e,"--project-root",s,"--lang",t,"--cwd",l.cwd,"--",...l.args,"-fsyntax-only","-fno-color-diagnostics","-fno-diagnostics-color",...l.source==="fallback"?["-x",t==="cpp"?"c++":"c"]:[]],a=l=>{let u=uB(),d=(0,IS.spawnSync)(u,i(l),{encoding:"utf8",cwd:l.cwd,maxBuffer:32*1024*1024});if(d.error){try{console.error(`[ClangAdapter] pando-clang-indexer spawn failed ${JSON.stringify({file:e,command:u,error:d.error.message})}`)}catch{}return null}if(d.status!==0){try{console.error(`[ClangAdapter] pando-clang-indexer failed ${JSON.stringify({file:e,status:d.status,stderr:(d.stderr||"").trim().slice(0,4e3)})}`)}catch{}return null}try{return JSON.parse(d.stdout||"{}")}catch(p){try{console.error(`[ClangAdapter] pando-clang-indexer emitted invalid JSON ${JSON.stringify({file:e,stdoutBytes:(d.stdout||"").length,stderr:(d.stderr||"").trim().slice(0,4e3),error:p instanceof Error?p.message:String(p)})}`)}catch{}return null}},c=a(o);return!c&&o.source!=="fallback"&&(c=a(jm(s,t))),!c||c.error?null:c},resolve:({absPath:e,nodePath:n,projectRoot:r})=>{try{let s=require("fs").readFileSync(e,"utf8"),o=dB(n);return o?{start:o.start,end:o.end,bodyStart:null,bodyEnd:null,text:s.slice(o.start,o.end)}:null}catch{return null}}})}var IS,hP,Lm,K3,DS=te(()=>{"use strict";IS=require("child_process"),hP=B(require("fs")),Lm=B(require("path"));ll();mP();kr();K3=(()=>{let t=Number(process.env.PANDO_CLANG_AST_MAX_BUFFER_BYTES||"");if(Number.isFinite(t)&&t>0)return Math.floor(t);let e=Number(process.env.PANDO_CLANG_AST_MAX_BUFFER_MB||"");return Number.isFinite(e)&&e>0?Math.floor(e*1024*1024):1536*1024*1024})()});function ja(...t){try{let e=t.map(n=>{if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}).join(" ");process.stderr.write(e+`
23
+ `))}catch{return null}}function dP(t){let e=at.default.join(t,"compile_commands.json");if(Mr.default.existsSync(e))return e;for(let i of CS){let a=at.default.join(t,i,"compile_commands.json");if(Mr.default.existsSync(a))return a}let n=CS.map(i=>at.default.join(t,i)).filter(i=>Mr.default.existsSync(i));n.push(t);let r=10,s=new Set,o=(i,a)=>{if(a>r)return null;let c=at.default.resolve(i);if(s.has(c))return null;s.add(c);try{let l=Mr.default.readdirSync(i,{withFileTypes:!0});for(let u of l)if(u.isFile()&&u.name==="compile_commands.json")return at.default.join(i,u.name);for(let u of l){if(!u.isDirectory()||u.name==="node_modules"||u.name.startsWith("."))continue;let d=o(at.default.join(i,u.name),a+1);if(d)return d}}catch{}return null};for(let i of n){let a=o(i,0);if(a)return a}return null}function rB(t,e){let n=at.default.resolve(t),r=at.default.resolve(e);for(;;){let s=dP(n);if(s)return s;if(n===r)break;let o=at.default.dirname(n);if(o===n)break;n=o}return null}function pP(t){let e=at.default.join(t,"compile_flags.txt");if(Mr.default.existsSync(e))return e;for(let n of CS){let r=at.default.join(t,n,"compile_flags.txt");if(Mr.default.existsSync(r))return r}return null}function sB(t,e){let n=at.default.resolve(t),r=at.default.resolve(e);for(;;){let s=pP(n);if(s)return s;if(n===r)break;let o=at.default.dirname(n);if(o===n)break;n=o}return null}function pd(t){if(t)try{return Mr.default.statSync(t).mtimeMs}catch{return}}function oB(t){let e=[],n=new Set([".clangd","CMakeLists.txt","meson.build","meson_options.txt","Makefile","makefile","GNUmakefile","configure.ac","configure.in"]),r=5,s=200,o=(i,a)=>{if(a>r||e.length>=s)return;let c;try{c=Mr.default.readdirSync(i,{withFileTypes:!0})}catch{return}for(let l of c){if(e.length>=s)break;let u=at.default.join(i,l.name);l.isFile()&&(n.has(l.name)||l.name.endsWith(".cmake"))&&e.push(u)}for(let l of c){if(e.length>=s)break;l.isDirectory()&&(l.name==="node_modules"||l.name===".git"||l.name===".pando"||l.name.startsWith(".cache")||o(at.default.join(i,l.name),a+1))}};return o(t,0),e}function Ui(t,e,n){if(!n)return;let r=n.trim();!r||e.has(r)||(e.add(r),t.push(r))}function ml(t,e,n,r){let s=r.trim().replace(/^["']|["']$/g,"");if(!s||s.startsWith("$")||s.includes("${")||s.includes("<"))return;let o=at.default.isAbsolute(s)?s:at.default.resolve(n,s);Mr.default.existsSync(o)&&Ui(t,e,`-I${o}`)}function iP(t){let e=[],n=new Set,r;for(let s of oB(t)){let o=pd(s);o&&(!r||o>r)&&(r=o);let i="";try{i=Mr.default.readFileSync(s,"utf8")}catch{continue}let a=at.default.dirname(s),c=i.replace(/#[^\n]*/g," "),l=hl(c.replace(/[()[\]{},;]/g," "));for(let u=0;u<l.length;u+=1){let d=l[u];(d==="-I"||d==="-isystem"||d==="/I")&&l[u+1]?(ml(e,n,a,l[u+1]),u+=1):d.startsWith("-I")&&d.length>2||d.startsWith("/I")&&d.length>2?ml(e,n,a,d.slice(2)):d.startsWith("-isystem")&&d.length>8?ml(e,n,a,d.slice(8)):d.startsWith("-D")||d.startsWith("/D")?Ui(e,n,d.startsWith("/D")?`-D${d.slice(2)}`:d):d.startsWith("-std=")&&Ui(e,n,d)}for(let u of i.matchAll(/\b(?:target_)?include_directories\s*\(([^)]*)\)/gims))for(let d of hl(u[1].replace(/[()[\]{},;]/g," ")))/^(PRIVATE|PUBLIC|INTERFACE|SYSTEM|BEFORE|AFTER)$/i.test(d)||ml(e,n,a,d);for(let u of i.matchAll(/\b(?:add_compile_definitions|target_compile_definitions)\s*\(([^)]*)\)/gims))for(let d of hl(u[1].replace(/[()[\]{},;]/g," ")))/^(PRIVATE|PUBLIC|INTERFACE)$/i.test(d)||d.includes("$")||Ui(e,n,d.startsWith("-D")?d:`-D${d}`);for(let u of i.matchAll(/\binclude_directories\s*:\s*\[([^\]]*)\]/gims))for(let d of hl(u[1].replace(/,/g," ")))ml(e,n,a,d)}return{args:e,mtime:r}}function iB(t,e){let n=at.default.resolve(t).split(at.default.sep),r=at.default.resolve(e).split(at.default.sep),s=0;for(;s<n.length&&s<r.length&&n[s]===r[s];)s+=1;return s}function aB(t,e){if(!t||t.length===0)return null;let n=at.default.dirname(e),r=at.default.extname(e).toLowerCase(),s=at.default.basename(e,r),o=null;for(let i of t){let a=at.default.extname(i.file).toLowerCase();if(!cP.has(a))continue;let c=at.default.dirname(i.file),l=at.default.basename(i.file,a),u=iB(e,i.file);c===n&&(u+=100),l===s&&(u+=50),lP.has(r)&&(u+=20),(!o||u>o.score)&&(o={entry:i,score:u})}return o?.entry??null}function aP(t,e){let n=e?`${at.default.resolve(t)}::${at.default.resolve(e)}`:at.default.resolve(t),r=dd.get(n);if(r){let m=pd(r.commandsPath);if(r.commandsPath&&m&&r.commandsMtime&&m!==r.commandsMtime)dd.delete(n);else if(r.flagsPath){let h=pd(r.flagsPath);if(h&&r.flagsMtime&&h!==r.flagsMtime)dd.delete(n);else return r}else if(r.projectConfigFlags){let h=iP(e??t);if(r.projectConfigMtime&&h.mtime&&r.projectConfigMtime!==h.mtime)dd.delete(n);else return r}else return r}let s=e?rB(e,t):dP(t),o=s?tB(s)??void 0:void 0,i=o?.map,a=o?.entries,c=pd(s),l=i?null:e?sB(e,t):pP(t),u=l?nB(l)??void 0:void 0,d=pd(l),p=!i&&!u?iP(e??t):void 0,f={commands:i,commandEntries:a,flags:u,projectConfigFlags:p?.args,commandsPath:s,commandsMtime:c,flagsPath:l,flagsMtime:d,projectConfigMtime:p?.mtime};return dd.set(n,f),f}function AS(t,e,n){let r=at.default.dirname(e),s=aP(t);!s.commands&&!s.flags&&(!s.projectConfigFlags||s.projectConfigFlags.length===0)&&(s=aP(t,r));let o=uP(e);if(s.commands){let i=s.commands.get(o);if(i)return{args:i.args,cwd:i.cwd,source:"compile_commands"};let a=aB(s.commandEntries,o);if(a)return{args:a.args,cwd:a.cwd,source:"compile_commands"}}return s.flags?{args:s.flags,cwd:t,source:"compile_flags"}:s.projectConfigFlags&&s.projectConfigFlags.length>0?{args:fP(s.projectConfigFlags,t,n),cwd:t,source:"project_config"}:jm(t,n)}function cB(t){let e=[],n=new Set,r=a=>{let c=at.default.resolve(a);!n.has(c)&&Mr.default.existsSync(c)&&(n.add(c),e.push(c))};r(t);for(let a of Yz)r(at.default.join(t,a));let s=Number(process.env.PANDO_CLANG_FALLBACK_INCLUDE_DEPTH||"5"),o=Number(process.env.PANDO_CLANG_FALLBACK_INCLUDE_MAX_DIRS||"300"),i=(a,c)=>{if(c>s||e.length>=o)return;let l;try{l=Mr.default.readdirSync(a,{withFileTypes:!0})}catch{return}l.some(d=>d.isFile()&&lP.has(at.default.extname(d.name).toLowerCase()))&&r(a);for(let d of l){if(e.length>=o)break;d.isDirectory()&&(d.name==="node_modules"||d.name===".git"||d.name===".pando"||d.name.startsWith(".cache")||i(at.default.join(a,d.name),c+1))}};return i(t,0),e}function fP(t,e,n){let r=[...t],s=new Set(r);r.some(o=>o.startsWith("-std="))||Ui(r,s,"-std="+(n==="cpp"?"c++20":"c17"));for(let o of cB(e))Ui(r,s,`-I${o}`);for(let o of["-ferror-limit=0","-Wno-everything","-fparse-all-comments","-fms-extensions"])Ui(r,s,o);return n==="cpp"&&Ui(r,s,"-fdelayed-template-parsing"),r}function jm(t,e){return{args:fP([],t,e),cwd:t,source:"fallback"}}var Mr,at,dd,Yz,CS,cP,lP,mP=te(()=>{"use strict";Mr=B(require("fs")),at=B(require("path")),dd=new Map,Yz=["include","src","lib","libs","third_party","third-party","deps","vendor","build","build/src","build_pando","build_pando/src"],CS=["build","out","build-debug","build-release","cmake-build-debug","cmake-build-release","build_pando"],cP=new Set([".c",".cc",".cpp",".cxx",".c++",".cp",".m",".mm"]),lP=new Set([".h",".hh",".hpp",".hxx",".h++",".inl",".ipp",".tcc"])});function lB(t){let e=`PANDO_${t.toUpperCase()}_INDEXER_CMD`;return process.env[e]||(t==="cpp"?"clang++":"clang")}function uB(){let t=process.env.PANDO_CLANG_INDEXER_CMD;if(t&&t.trim())return t.trim();let e=Rr("clang-indexer/bin/pando-clang-indexer");if(e)return e;let n=[process.env.PANDO_TOOLS_ROOT?Lm.default.join(process.env.PANDO_TOOLS_ROOT,"clang-indexer","bin","pando-clang-indexer"):null,process.env.PANDO_RUNTIME_ROOT?Lm.default.join(process.env.PANDO_RUNTIME_ROOT,"tools","clang-indexer","bin","pando-clang-indexer"):null,typeof __dirname=="string"?Lm.default.resolve(__dirname,"..","..","..","..","..","tools","clang-indexer","bin","pando-clang-indexer"):null].filter(r=>!!r);for(let r of n)try{if(hP.default.existsSync(r))return r}catch{}return"pando-clang-indexer"}function gP(t,e,n){let r=lB(n),s=a=>{let c=[...a.args,"-fsyntax-only","-fno-color-diagnostics","-fno-diagnostics-color",...a.source==="fallback"?["-x",n==="cpp"?"c++":"c"]:[],e],l=(0,IS.spawnSync)(r,c,{encoding:"utf8",cwd:a.cwd});return l.status===0?{ok:!0}:{ok:!1,error:(l.stderr||l.stdout||"").trim()||"Clang syntax validation failed."}},o=AS(t,e,n),i=s(o);if(i.ok)return i;if(o.source!=="fallback"){let a=jm(t,n),c=s(a);return c.ok,c}return i}function dB(t){if(!t)return null;let e=t;(e.startsWith("SyntaxError:")||e.startsWith("CompileError:"))&&(e=e.substring(e.indexOf(":")+1)),e.includes("#")&&(e=e.split("#")[1]);let n=e.lastIndexOf(":"),r=n>=0?e.slice(0,n):e,[s,o]=r.split("-"),i=Number(s),a=Number(o);return!Number.isFinite(i)||!Number.isFinite(a)||a<i?null:{start:i,end:a}}function NS(t){return zo({id:t,extensions:[],parse:({absPath:e,relPath:n,content:r,projectRoot:s})=>{let o=AS(s,e,t),i=l=>["--file",e,"--project-root",s,"--lang",t,"--cwd",l.cwd,"--",...l.args,"-fsyntax-only","-fno-color-diagnostics","-fno-diagnostics-color",...l.source==="fallback"?["-x",t==="cpp"?"c++":"c"]:[]],a=l=>{let u=uB(),d=(0,IS.spawnSync)(u,i(l),{encoding:"utf8",cwd:l.cwd,maxBuffer:32*1024*1024});if(d.error){try{console.error(`[ClangAdapter] pando-clang-indexer spawn failed ${JSON.stringify({file:e,command:u,error:d.error.message})}`)}catch{}return null}if(d.status!==0){try{console.error(`[ClangAdapter] pando-clang-indexer failed ${JSON.stringify({file:e,status:d.status,stderr:(d.stderr||"").trim().slice(0,4e3)})}`)}catch{}return null}try{return JSON.parse(d.stdout||"{}")}catch(p){try{console.error(`[ClangAdapter] pando-clang-indexer emitted invalid JSON ${JSON.stringify({file:e,stdoutBytes:(d.stdout||"").length,stderr:(d.stderr||"").trim().slice(0,4e3),error:p instanceof Error?p.message:String(p)})}`)}catch{}return null}},c=a(o);return!c&&o.source!=="fallback"&&(c=a(jm(s,t))),!c||c.error?null:c},resolve:({absPath:e,nodePath:n,projectRoot:r})=>{try{let s=require("fs").readFileSync(e,"utf8"),o=dB(n);return o?{start:o.start,end:o.end,bodyStart:null,bodyEnd:null,text:s.slice(o.start,o.end)}:null}catch{return null}}})}var IS,hP,Lm,Z3,DS=te(()=>{"use strict";IS=require("child_process"),hP=B(require("fs")),Lm=B(require("path"));ll();mP();kr();Z3=(()=>{let t=Number(process.env.PANDO_CLANG_AST_MAX_BUFFER_BYTES||"");if(Number.isFinite(t)&&t>0)return Math.floor(t);let e=Number(process.env.PANDO_CLANG_AST_MAX_BUFFER_MB||"");return Number.isFinite(e)&&e>0?Math.floor(e*1024*1024):1536*1024*1024})()});function ja(...t){try{let e=t.map(n=>{if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}).join(" ");process.stderr.write(e+`
24
24
  `)}catch{}}function yP(){for(let t of qm.values())try{t.close()}catch{}qm.clear(),FS.clear()}function bP(t){let e=process.platform==="win32"?".cmd":"",n=Rr(`dart-indexer/bin/pando-dart-indexer${e}`);if(n)return n;if(t){let o=Bm.default.resolve(t,"tools/dart-indexer/bin/pando-dart-indexer"+e);if(zm.default.existsSync(o))return o}let r=process.env.PANDO_EXTENSION_ROOT;if(r){let o=Bm.default.resolve(r,"tools/dart-indexer/bin/pando-dart-indexer"+e);if(zm.default.existsSync(o))return o}let s=Bm.default.resolve(process.cwd(),"tools/dart-indexer/bin/pando-dart-indexer"+e);return zm.default.existsSync(s)?s:null}function SP(t){let e=process.env.PANDO_DART_INDEXER_CMD||bP(t);if(!e)return null;let n=qm.get(e);n||(n=new OS(e),qm.set(e,n));let r=FS.get(e);return r||(r=new MS(n),FS.set(e,r)),{client:n,batcher:r}}async function mB(t,e,n){let r=SP(e);if(!r)return null;try{return await r.batcher.enqueue({file:t,root:e,lang:"dart",size:n})}catch(s){return ja(`[${new Date().toISOString()}] [DartCliAdapter] parse error`,{file:t,error:s?.message||s}),null}}function xP(t,e){let n=process.env.PANDO_DART_INDEXER_CMD||bP(t);if(!n)return{ok:!1,error:"Dart validator unavailable (missing indexer command)."};let r=(0,Hm.spawnSync)(n,["--validate","--file",e],{cwd:t,encoding:"utf8",env:{...process.env,PANDO_PROJECT_ROOT:t}});return r.status===0?{ok:!0}:{ok:!1,error:(r.stderr||r.stdout||"").trim()||"Dart syntax validation failed."}}function _P(){return zo({id:"dart",extensions:[".dart"],parse:async({absPath:t,projectRoot:e,content:n,meta:r})=>{let s=r?.size??Buffer.byteLength(n,"utf8");return mB(t,e,s)},resolve:({absPath:t,nodePath:e,projectRoot:n})=>{let r=Date.now(),s=SP(n);return s?s.client.resolve({file:t,root:n,lang:"dart",nodePath:e}).then(o=>{let i=Date.now()-r;return i>2e3&&ja(`[${new Date().toISOString()}] [DartCliAdapter] resolve slow`,{file:t,ms:i}),o||ja(`[${new Date().toISOString()}] [DartCliAdapter] resolve failed`,{file:t,ms:i,nodePath:e}),o}).catch(o=>{let i=Date.now()-r;return ja(`[${new Date().toISOString()}] [DartCliAdapter] resolve error`,{file:t,ms:i,nodePath:e,error:o?.message||o}),null}):null},exportKind:"dart"})}var zm,Bm,Hm,pB,fB,OS,MS,qm,FS,$S=te(()=>{"use strict";zm=B(require("fs")),Bm=B(require("path")),Hm=require("child_process");ll();kr();ld();pB=256e3,fB=32;OS=class{constructor(e){this.cmd=e;this.proc=null;this.buffer="";this.pending=new Map;this.seq=1;this.closed=!1;this.ensureProcess()}ensureProcess(){if(!(this.proc&&!this.closed)){if(this.closed=!1,this.proc=(0,Hm.spawn)(this.cmd,["--server"],{stdio:["pipe","pipe","pipe"]}),!this.proc.stdout||!this.proc.stderr||!this.proc.stdin)throw this.closed=!0,new Error("dart indexer stdio unavailable");this.proc.stdout.on("data",e=>this.onData(e)),this.proc.stderr.on("data",e=>{ja(`[DartIndexer] ${e.toString("utf8").trim()}`)}),this.proc.stdin.on("error",e=>this.handleExit(e)),this.proc.on("error",e=>this.handleExit(e)),this.proc.on("exit",e=>this.handleExit(new Error(`dart indexer exited with code ${e}`))),Wi(this.proc)}}handleExit(e){if(!this.closed){this.closed=!0;for(let[,n]of this.pending)n.reject(e);this.pending.clear()}}onData(e){for(this.buffer+=e.toString("utf8");;){let n=this.buffer.indexOf(`
25
25
  `);if(n<0)break;let r=this.buffer.slice(0,n).trim();if(this.buffer=this.buffer.slice(n+1),!r)continue;let s=null;try{s=JSON.parse(r)}catch{continue}let o=this.pending.get(s.id);o&&(this.pending.delete(s.id),s.ok?o.resolve(s):o.reject(new Error(s.error||"dart server error")))}}async request(e,n=1){this.ensureProcess();let r=this.seq++;return new Promise((s,o)=>{let i={id:r,...e};this.pending.set(r,{resolve:s,reject:o});try{this.proc.stdin.write(`${JSON.stringify(i)}
26
26
  `)}catch(a){if(this.pending.delete(r),n>0){try{this.handleExit(a)}catch{}return this.request(e,n-1).then(s,o)}o(a)}})}async parseBatch(e){let n=await this.request({op:"parse",files:e});return"results"in n&&Array.isArray(n.results)?n.results.map(r=>r.ok&&r.result?r.result:null):"result"in n&&n.result?[n.result]:e.map(()=>null)}async resolve(e){let n=await this.request({op:"resolve",...e});return"result"in n&&n.result&&typeof n.result.start=="number"?n.result:null}close(){if(this.closed)return;this.closed=!0;for(let[,n]of this.pending)n.reject(new Error("dart indexer client closed"));this.pending.clear();let e=this.proc;if(this.proc=null,!!e){try{e.stdin?.end()}catch{}try{e.kill()}catch{}}}},MS=class{constructor(e){this.client=e;this.queue=[];this.scheduled=!1}enqueue(e){return new Promise((n,r)=>{this.queue.push({input:e,resolve:n,reject:r,startedAt:Date.now()}),this.scheduled||(this.scheduled=!0,setImmediate(()=>this.flush()))})}async flush(){for(this.scheduled=!1;this.queue.length;){let e=[],n=0;for(;this.queue.length&&e.length<fB;){let r=this.queue[0];if(e.length>0&&n+r.input.size>pB)break;e.push(this.queue.shift()),n+=r.input.size}try{let r=await this.client.parseBatch(e.map(s=>({file:s.input.file,root:s.input.root,lang:s.input.lang})));for(let s=0;s<e.length;s+=1){let o=e[s],i=r[s]??null,a=Date.now()-o.startedAt;a>2e3&&ja(`[${new Date().toISOString()}] [DartCliAdapter] parse slow`,{file:o.input.file,ms:a,ok:!!i}),i||ja(`[${new Date().toISOString()}] [DartCliAdapter] parse failed`,{file:o.input.file,ms:a}),o.resolve(i)}}catch(r){for(let s of e)s.reject(r)}}}},qm=new Map,FS=new Map});function za(...t){try{let e=t.map(n=>{if(typeof n=="string")return n;try{return JSON.stringify(n)}catch{return String(n)}}).join(" ");process.stderr.write(e+`
@@ -599,7 +599,7 @@ Path: ${c}`)}Ye.debug("[resolvePathRef] Hash OK")}return u}static getNodePath(e,
599
599
  CASE WHEN n.is_exported = 1 THEN 0 ELSE 1 END ASC,
600
600
  s.text ASC,
601
601
  n.id ASC
602
- `).all(s,n,r);if(!a||a.length===0)continue;return a.map(c=>oA(c,{fileRel:s,start:n,end:r}))}finally{try{i.close()}catch{}}}catch{continue}return[]}function Tn(t,e,n,r,s){let o=bq(t,e,n,r);if(o.length===0)return null;if(o.length===1)return o[0];let i=typeof s?.expectedHash=="string"&&s.expectedHash.trim()?s.expectedHash.startsWith("@")?s.expectedHash:`@${s.expectedHash.trim()}`:null,a=typeof s?.plainPath=="string"&&s.plainPath.trim()?s.plainPath.trim():Tx(o[0]);if(i&&a){let c=typeof s?.content=="string"?s.content:Buffer.from(Fh.default.readFileSync(e,"utf8"),"utf8").slice(n,r).toString("utf8"),l=o.find(u=>Si(a,c,u)===i||Je(a,c)===i);return l||null}return o[0]}function xi(t,e,n,r,s){let o=s.expectedHash.startsWith("@")?s.expectedHash:`@${s.expectedHash.trim()}`,i=typeof s.content=="string"?s.content:Buffer.from(Fh.default.readFileSync(e,"utf8"),"utf8").slice(n,r).toString("utf8"),a=Tn(t,e,n,r,{plainPath:s.plainPath,expectedHash:o,content:i});if(!a)return{target:null,actualHash:null,comparison:null,expectedHash:o,content:i};let c=Si(s.plainPath,i,a),l=Je(s.plainPath,i),u=o===l?l:c;return{target:a,actualHash:u,comparison:mn(o,u),expectedHash:o,content:i}}var Fh,Jd,Gs=te(()=>{"use strict";Fh=B(require("fs")),Jd=B(require("path"));an();Qt();cr()});function Px(t){if(!t)return null;try{let e=typeof t=="string"?JSON.parse(t):t;return!e||typeof e!="object"?null:e}catch{return null}}function $h(t){let e=Px(t.metadata);return typeof e?.rewriteKind=="string"&&e.rewriteKind.length>0}function cA(t){return $h(t)?"call":typeof t.ref_kind=="string"&&t.ref_kind.trim()&&t.ref_kind!=="call"?t.ref_kind:"reference"}function aA(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function jh(t,e,n,r="head"){let s=Px(t.metadata),o=aA(r==="edit"?s?.callEditStart:s?.callHeadStart),i=aA(r==="edit"?s?.callEditEnd:s?.callHeadEnd);return o!=null&&i!=null&&i>=o?{start:o,end:i}:{start:e,end:n}}function Sq(t,e,n){let r=e.symbolKey||null;if(!(e.name||r?.split("/").pop()||null))return"missing-target-name";let o=new Set;r&&o.add(r);for(let c of n?.symbolKeys||[]){let l=String(c||"").trim();l&&o.add(l)}let i=new Set;for(let c of o){let l=c.lastIndexOf("/");l>0&&i.add(c.slice(0,l))}for(let c of n?.namespaces||[]){let l=String(c||"").trim();l&&i.add(l)}let a=Px(t.metadata);if(!$h(t))return"not-call-head";if(t.target_symbol_key&&o.has(t.target_symbol_key))return"exact-target-symbol-key";if(a?.targetIdentity&&o.size>0)return o.has(a.targetIdentity)?"metadata-target-identity":"no-match";if(a?.resolutionMode==="local")return a.localBindingKey&&o.has(a.localBindingKey)?"local-binding-key":"local-binding-mismatch";if(a?.resolutionMode==="refer-all"){let c=new Set((a.candidateNamespaces||[]).map(l=>String(l||"")).filter(Boolean));return a.sourceNamespace&&c.add(String(a.sourceNamespace)),Array.from(i).some(l=>c.has(l))?"refer-all-candidate-namespace":"refer-all-namespace-mismatch"}return"no-match"}function Lh(t,e,n){let r=Sq(t,e,n);return r==="exact-target-symbol-key"||r==="metadata-target-identity"||r==="local-binding-key"||r==="refer-all-candidate-namespace"}var zh=te(()=>{"use strict"});function _q(t,e){return`${t}::${e}`}function wq(t,e){if(!xq.test(e))return new Set;let n=_q(t,e),r;try{r=lA.default.statSync(t)}catch{return Bh.delete(n),new Set}let s=Bh.get(n);if(s&&s.mtimeMs===r.mtimeMs&&s.size===r.size)return s.columns;try{let o=new Dt(t,{readonly:!0});try{let i=o.prepare(`PRAGMA table_info(${e})`).all(),a=new Set(i.map(c=>String(c.name||"")).filter(Boolean));return Bh.set(n,{columns:a,mtimeMs:r.mtimeMs,size:r.size}),a}finally{try{o.close()}catch{}}}catch{return Bh.delete(n),new Set}}function uA(t,e,n){return wq(t,e).has(n)}var lA,Bh,xq,dA=te(()=>{"use strict";lA=B(require("fs"));an();Bh=new Map,xq=/^[A-Za-z_][A-Za-z0-9_]*$/});function vq(t){try{let e=t.getDecorators;if(typeof e!="function")return[];let n=new Set;for(let r of e.call(t)){let s;try{s=r.getName?.()}catch{s=void 0}if(!s)try{s=r.getExpression?.()?.getText?.()}catch{s=void 0}if(s){let o=String(s).trim();o&&n.add(o)}}return Array.from(n)}catch{return[]}}function Rq(t){try{if(!V.Node.isClassDeclaration(t))return[];let e=t.getImplements();if(!e||e.length===0)return[];let n=new Set;for(let r of e)try{let s=r.getExpression(),o=s?s.getText():r.getText();o&&n.add(o.trim())}catch{}return Array.from(n)}catch{return[]}}function kq(t){try{let e=new Set;if(V.Node.isClassDeclaration(t)){let n=t.getExtends();if(n)try{let r=n.getExpression(),s=r?r.getText():n.getText();s&&e.add(s.trim())}catch{}}else if(V.Node.isInterfaceDeclaration(t)){let n=t.getExtends();for(let r of n)try{let s=r.getText();s&&e.add(s.trim())}catch{}}return Array.from(e)}catch{return[]}}function pA(t){try{if("getReturnTypeNode"in t&&typeof t.getReturnTypeNode=="function"){let e=t.getReturnTypeNode();if(e)return e.getText()}if("getReturnType"in t&&typeof t.getReturnType=="function"){let e=t.getReturnType();if(e&&typeof e.getText=="function"){let n=e.getText();if(n)return String(n)}}return null}catch{return null}}function Eq(t){try{if(typeof t.getScope!="function")return null;let e=t.getScope();return e===V.Scope.Private||e===V.Scope.Protected||e===V.Scope.Public?e:null}catch{return null}}function fA(t){let e={kind:t.getKindName()},n=vq(t);if(n.length&&(e.decorators=n),gn(e,"flags",()=>t.getFlags()),(V.Node.isFunctionDeclaration(t)||V.Node.isMethodDeclaration(t)||V.Node.isFunctionExpression(t))&&(gn(e,"isAsync",()=>t.isAsync()),gn(e,"isGenerator",()=>t.isGenerator()),gn(e,"parameterCount",()=>t.getParameters().length),gn(e,"returnType",()=>pA(t)),V.Node.isFunctionDeclaration(t)&&gn(e,"isExported",()=>t.isExported())),V.Node.isClassDeclaration(t)){gn(e,"isAbstract",()=>t.isAbstract()),gn(e,"isExported",()=>t.isExported());let s=kq(t);s.length&&(e.extends=s);let o=Rq(t);o.length&&(e.implements=o)}if(V.Node.isVariableDeclaration(t)&&(gn(e,"declarationKind",()=>t.getVariableStatement()?.getDeclarationKind()),gn(e,"hasInitializer",()=>t.hasInitializer()),gn(e,"type",()=>t.getTypeNode()?.getText())),(V.Node.isPropertyDeclaration(t)||V.Node.isPropertySignature(t)||V.Node.isParameterDeclaration(t))&&(gn(e,"isStatic",()=>t.isStatic?.()),gn(e,"isReadonly",()=>t.isReadonly?.()),gn(e,"isOptional",()=>t.hasQuestionToken?.()),gn(e,"scope",()=>t.getScope?.())),(V.Node.isMethodDeclaration(t)||V.Node.isMethodSignature(t)||V.Node.isGetAccessorDeclaration(t)||V.Node.isSetAccessorDeclaration(t))&&(gn(e,"isStatic",()=>t.isStatic?.()),gn(e,"isAbstract",()=>t.isAbstract?.()),gn(e,"isAsync",()=>t.isAsync?.()),gn(e,"returnType",()=>pA(t)),gn(e,"scope",()=>t.getScope?.())),V.Node.isCallExpression(t)){let s=t.getExpression();if(V.Node.isPropertyAccessExpression(s)){e.propertyName=s.getName();let o=s.getExpression();V.Node.isIdentifier(o)&&(e.objectName=o.getText())}else V.Node.isIdentifier(s)&&(e.functionName=s.getText());e.argumentCount=t.getArguments().length,e.callExpression=s.getText()}let r=Eq(t);return r&&(e.visibility=r),e.isReadonly||gn(e,"isReadonly",()=>t.isReadonly?.()),V.Node.isImportDeclaration(t)&&(gn(e,"moduleSpecifier",()=>t.getModuleSpecifier()?.getLiteralText()),gn(e,"isTypeOnly",()=>t.isTypeOnly()),gn(e,"namedImports",()=>t.getNamedImports()?.map(s=>s.getName()).join(", ")),gn(e,"defaultImport",()=>t.getDefaultImport()?.getText())),Object.keys(e).forEach(s=>{e[s]===void 0&&delete e[s]}),e}function gn(t,e,n){try{let r=n();r!=null&&(t[e]=r)}catch{}}var V,dee,mA=te(()=>{"use strict";V=require("ts-morph");cr();bi();Tm();dee=new Set([V.SyntaxKind.ArrayLiteralExpression,V.SyntaxKind.ArrayType,V.SyntaxKind.ArrowFunction,V.SyntaxKind.AsExpression,V.SyntaxKind.AssertClause,V.SyntaxKind.AssertEntry,V.SyntaxKind.AwaitExpression,V.SyntaxKind.BigIntLiteral,V.SyntaxKind.BinaryExpression,V.SyntaxKind.BindingElement,V.SyntaxKind.Block,V.SyntaxKind.CallExpression,V.SyntaxKind.CallSignature,V.SyntaxKind.CaseClause,V.SyntaxKind.CatchClause,V.SyntaxKind.ClassDeclaration,V.SyntaxKind.ClassExpression,V.SyntaxKind.ClassStaticBlockDeclaration,V.SyntaxKind.ComputedPropertyName,V.SyntaxKind.ConditionalExpression,V.SyntaxKind.ConditionalType,V.SyntaxKind.ConstructSignature,V.SyntaxKind.Constructor,V.SyntaxKind.ConstructorType,V.SyntaxKind.Decorator,V.SyntaxKind.DefaultClause,V.SyntaxKind.DoStatement,V.SyntaxKind.ElementAccessExpression,V.SyntaxKind.EnumDeclaration,V.SyntaxKind.EnumMember,V.SyntaxKind.ExportAssignment,V.SyntaxKind.ExportDeclaration,V.SyntaxKind.ExportSpecifier,V.SyntaxKind.ExpressionStatement,V.SyntaxKind.ExpressionWithTypeArguments,V.SyntaxKind.FalseKeyword,V.SyntaxKind.ForInStatement,V.SyntaxKind.ForOfStatement,V.SyntaxKind.ForStatement,V.SyntaxKind.FunctionDeclaration,V.SyntaxKind.FunctionExpression,V.SyntaxKind.FunctionType,V.SyntaxKind.GetAccessor,V.SyntaxKind.Identifier,V.SyntaxKind.IfStatement,V.SyntaxKind.ImportAttribute,V.SyntaxKind.ImportAttributes,V.SyntaxKind.ImportClause,V.SyntaxKind.ImportDeclaration,V.SyntaxKind.ImportEqualsDeclaration,V.SyntaxKind.ImportSpecifier,V.SyntaxKind.ImportType,V.SyntaxKind.IndexSignature,V.SyntaxKind.IndexedAccessType,V.SyntaxKind.InferType,V.SyntaxKind.InterfaceDeclaration,V.SyntaxKind.IntersectionType,V.SyntaxKind.JsxAttribute,V.SyntaxKind.JsxClosingElement,V.SyntaxKind.JsxClosingFragment,V.SyntaxKind.JsxElement,V.SyntaxKind.JsxExpression,V.SyntaxKind.JsxFragment,V.SyntaxKind.JsxOpeningElement,V.SyntaxKind.JsxOpeningFragment,V.SyntaxKind.JsxSelfClosingElement,V.SyntaxKind.JsxSpreadAttribute,V.SyntaxKind.JsxText,V.SyntaxKind.LiteralType,V.SyntaxKind.MappedType,V.SyntaxKind.MetaProperty,V.SyntaxKind.MethodDeclaration,V.SyntaxKind.MethodSignature,V.SyntaxKind.ModuleDeclaration,V.SyntaxKind.NamedExports,V.SyntaxKind.NamedImports,V.SyntaxKind.NamedTupleMember,V.SyntaxKind.NamespaceExport,V.SyntaxKind.NamespaceExportDeclaration,V.SyntaxKind.NamespaceImport,V.SyntaxKind.NewExpression,V.SyntaxKind.NoSubstitutionTemplateLiteral,V.SyntaxKind.NonNullExpression,V.SyntaxKind.NullKeyword,V.SyntaxKind.NumericLiteral,V.SyntaxKind.ObjectLiteralExpression,V.SyntaxKind.OptionalType,V.SyntaxKind.Parameter,V.SyntaxKind.ParenthesizedType,V.SyntaxKind.PostfixUnaryExpression,V.SyntaxKind.PrefixUnaryExpression,V.SyntaxKind.PrivateIdentifier,V.SyntaxKind.PropertyAccessExpression,V.SyntaxKind.PropertyAssignment,V.SyntaxKind.PropertyDeclaration,V.SyntaxKind.PropertySignature,V.SyntaxKind.QualifiedName,V.SyntaxKind.RegularExpressionLiteral,V.SyntaxKind.RestType,V.SyntaxKind.ReturnStatement,V.SyntaxKind.SatisfiesExpression,V.SyntaxKind.SetAccessor,V.SyntaxKind.ShorthandPropertyAssignment,V.SyntaxKind.SourceFile,V.SyntaxKind.SpreadAssignment,V.SyntaxKind.SpreadElement,V.SyntaxKind.StringLiteral,V.SyntaxKind.SwitchStatement,V.SyntaxKind.TaggedTemplateExpression,V.SyntaxKind.TemplateExpression,V.SyntaxKind.TemplateLiteralType,V.SyntaxKind.ThisType,V.SyntaxKind.ThrowStatement,V.SyntaxKind.TrueKeyword,V.SyntaxKind.TryStatement,V.SyntaxKind.TupleType,V.SyntaxKind.TypeAliasDeclaration,V.SyntaxKind.TypeLiteral,V.SyntaxKind.TypeOfExpression,V.SyntaxKind.TypeOperator,V.SyntaxKind.TypeParameter,V.SyntaxKind.TypePredicate,V.SyntaxKind.TypeQuery,V.SyntaxKind.TypeReference,V.SyntaxKind.UnionType,V.SyntaxKind.VariableDeclaration,V.SyntaxKind.VariableStatement,V.SyntaxKind.WhileStatement,V.SyntaxKind.YieldExpression])});function Al(t){let e=ot(t);return{root:e,historyGit:Cx.join(e,"history.git"),workdir:Cx.join(e,"workdir")}}var Cx,qh=te(()=>{"use strict";Cx=B(require("path"));Qt()});var Yi={};Yt(Yi,{initSnapshotsSchema:()=>Ax,openSnapshotsDb:()=>_i});function Ax(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 10000");try{t.pragma("temp_store = MEMORY")}catch{}t.exec(`
602
+ `).all(s,n,r);if(!a||a.length===0)continue;return a.map(c=>oA(c,{fileRel:s,start:n,end:r}))}finally{try{i.close()}catch{}}}catch{continue}return[]}function Tn(t,e,n,r,s){let o=bq(t,e,n,r);if(o.length===0)return null;if(o.length===1)return o[0];let i=typeof s?.expectedHash=="string"&&s.expectedHash.trim()?s.expectedHash.startsWith("@")?s.expectedHash:`@${s.expectedHash.trim()}`:null,a=typeof s?.plainPath=="string"&&s.plainPath.trim()?s.plainPath.trim():Tx(o[0]);if(i&&a){let c=typeof s?.content=="string"?s.content:Buffer.from(Fh.default.readFileSync(e,"utf8"),"utf8").slice(n,r).toString("utf8"),l=o.find(u=>Si(a,c,u)===i||Je(a,c)===i);return l||null}return o[0]}function xi(t,e,n,r,s){let o=s.expectedHash.startsWith("@")?s.expectedHash:`@${s.expectedHash.trim()}`,i=typeof s.content=="string"?s.content:Buffer.from(Fh.default.readFileSync(e,"utf8"),"utf8").slice(n,r).toString("utf8"),a=Tn(t,e,n,r,{plainPath:s.plainPath,expectedHash:o,content:i});if(!a)return{target:null,actualHash:null,comparison:null,expectedHash:o,content:i};let c=Si(s.plainPath,i,a),l=Je(s.plainPath,i),u=o===l?l:c;return{target:a,actualHash:u,comparison:mn(o,u),expectedHash:o,content:i}}var Fh,Jd,Gs=te(()=>{"use strict";Fh=B(require("fs")),Jd=B(require("path"));an();Qt();cr()});function Px(t){if(!t)return null;try{let e=typeof t=="string"?JSON.parse(t):t;return!e||typeof e!="object"?null:e}catch{return null}}function $h(t){let e=Px(t.metadata);return typeof e?.rewriteKind=="string"&&e.rewriteKind.length>0}function cA(t){return $h(t)?"call":typeof t.ref_kind=="string"&&t.ref_kind.trim()&&t.ref_kind!=="call"?t.ref_kind:"reference"}function aA(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function jh(t,e,n,r="head"){let s=Px(t.metadata),o=aA(r==="edit"?s?.callEditStart:s?.callHeadStart),i=aA(r==="edit"?s?.callEditEnd:s?.callHeadEnd);return o!=null&&i!=null&&i>=o?{start:o,end:i}:{start:e,end:n}}function Sq(t,e,n){let r=e.symbolKey||null;if(!(e.name||r?.split("/").pop()||null))return"missing-target-name";let o=new Set;r&&o.add(r);for(let c of n?.symbolKeys||[]){let l=String(c||"").trim();l&&o.add(l)}let i=new Set;for(let c of o){let l=c.lastIndexOf("/");l>0&&i.add(c.slice(0,l))}for(let c of n?.namespaces||[]){let l=String(c||"").trim();l&&i.add(l)}let a=Px(t.metadata);if(!$h(t))return"not-call-head";if(t.target_symbol_key&&o.has(t.target_symbol_key))return"exact-target-symbol-key";if(a?.targetIdentity&&o.size>0)return o.has(a.targetIdentity)?"metadata-target-identity":"no-match";if(a?.resolutionMode==="local")return a.localBindingKey&&o.has(a.localBindingKey)?"local-binding-key":"local-binding-mismatch";if(a?.resolutionMode==="refer-all"){let c=new Set((a.candidateNamespaces||[]).map(l=>String(l||"")).filter(Boolean));return a.sourceNamespace&&c.add(String(a.sourceNamespace)),Array.from(i).some(l=>c.has(l))?"refer-all-candidate-namespace":"refer-all-namespace-mismatch"}return"no-match"}function Lh(t,e,n){let r=Sq(t,e,n);return r==="exact-target-symbol-key"||r==="metadata-target-identity"||r==="local-binding-key"||r==="refer-all-candidate-namespace"}var zh=te(()=>{"use strict"});function _q(t,e){return`${t}::${e}`}function wq(t,e){if(!xq.test(e))return new Set;let n=_q(t,e),r;try{r=lA.default.statSync(t)}catch{return Bh.delete(n),new Set}let s=Bh.get(n);if(s&&s.mtimeMs===r.mtimeMs&&s.size===r.size)return s.columns;try{let o=new Dt(t,{readonly:!0});try{let i=o.prepare(`PRAGMA table_info(${e})`).all(),a=new Set(i.map(c=>String(c.name||"")).filter(Boolean));return Bh.set(n,{columns:a,mtimeMs:r.mtimeMs,size:r.size}),a}finally{try{o.close()}catch{}}}catch{return Bh.delete(n),new Set}}function uA(t,e,n){return wq(t,e).has(n)}var lA,Bh,xq,dA=te(()=>{"use strict";lA=B(require("fs"));an();Bh=new Map,xq=/^[A-Za-z_][A-Za-z0-9_]*$/});function vq(t){try{let e=t.getDecorators;if(typeof e!="function")return[];let n=new Set;for(let r of e.call(t)){let s;try{s=r.getName?.()}catch{s=void 0}if(!s)try{s=r.getExpression?.()?.getText?.()}catch{s=void 0}if(s){let o=String(s).trim();o&&n.add(o)}}return Array.from(n)}catch{return[]}}function Rq(t){try{if(!V.Node.isClassDeclaration(t))return[];let e=t.getImplements();if(!e||e.length===0)return[];let n=new Set;for(let r of e)try{let s=r.getExpression(),o=s?s.getText():r.getText();o&&n.add(o.trim())}catch{}return Array.from(n)}catch{return[]}}function kq(t){try{let e=new Set;if(V.Node.isClassDeclaration(t)){let n=t.getExtends();if(n)try{let r=n.getExpression(),s=r?r.getText():n.getText();s&&e.add(s.trim())}catch{}}else if(V.Node.isInterfaceDeclaration(t)){let n=t.getExtends();for(let r of n)try{let s=r.getText();s&&e.add(s.trim())}catch{}}return Array.from(e)}catch{return[]}}function pA(t){try{if("getReturnTypeNode"in t&&typeof t.getReturnTypeNode=="function"){let e=t.getReturnTypeNode();if(e)return e.getText()}if("getReturnType"in t&&typeof t.getReturnType=="function"){let e=t.getReturnType();if(e&&typeof e.getText=="function"){let n=e.getText();if(n)return String(n)}}return null}catch{return null}}function Eq(t){try{if(typeof t.getScope!="function")return null;let e=t.getScope();return e===V.Scope.Private||e===V.Scope.Protected||e===V.Scope.Public?e:null}catch{return null}}function fA(t){let e={kind:t.getKindName()},n=vq(t);if(n.length&&(e.decorators=n),gn(e,"flags",()=>t.getFlags()),(V.Node.isFunctionDeclaration(t)||V.Node.isMethodDeclaration(t)||V.Node.isFunctionExpression(t))&&(gn(e,"isAsync",()=>t.isAsync()),gn(e,"isGenerator",()=>t.isGenerator()),gn(e,"parameterCount",()=>t.getParameters().length),gn(e,"returnType",()=>pA(t)),V.Node.isFunctionDeclaration(t)&&gn(e,"isExported",()=>t.isExported())),V.Node.isClassDeclaration(t)){gn(e,"isAbstract",()=>t.isAbstract()),gn(e,"isExported",()=>t.isExported());let s=kq(t);s.length&&(e.extends=s);let o=Rq(t);o.length&&(e.implements=o)}if(V.Node.isVariableDeclaration(t)&&(gn(e,"declarationKind",()=>t.getVariableStatement()?.getDeclarationKind()),gn(e,"hasInitializer",()=>t.hasInitializer()),gn(e,"type",()=>t.getTypeNode()?.getText())),(V.Node.isPropertyDeclaration(t)||V.Node.isPropertySignature(t)||V.Node.isParameterDeclaration(t))&&(gn(e,"isStatic",()=>t.isStatic?.()),gn(e,"isReadonly",()=>t.isReadonly?.()),gn(e,"isOptional",()=>t.hasQuestionToken?.()),gn(e,"scope",()=>t.getScope?.())),(V.Node.isMethodDeclaration(t)||V.Node.isMethodSignature(t)||V.Node.isGetAccessorDeclaration(t)||V.Node.isSetAccessorDeclaration(t))&&(gn(e,"isStatic",()=>t.isStatic?.()),gn(e,"isAbstract",()=>t.isAbstract?.()),gn(e,"isAsync",()=>t.isAsync?.()),gn(e,"returnType",()=>pA(t)),gn(e,"scope",()=>t.getScope?.())),V.Node.isCallExpression(t)){let s=t.getExpression();if(V.Node.isPropertyAccessExpression(s)){e.propertyName=s.getName();let o=s.getExpression();V.Node.isIdentifier(o)&&(e.objectName=o.getText())}else V.Node.isIdentifier(s)&&(e.functionName=s.getText());e.argumentCount=t.getArguments().length,e.callExpression=s.getText()}let r=Eq(t);return r&&(e.visibility=r),e.isReadonly||gn(e,"isReadonly",()=>t.isReadonly?.()),V.Node.isImportDeclaration(t)&&(gn(e,"moduleSpecifier",()=>t.getModuleSpecifier()?.getLiteralText()),gn(e,"isTypeOnly",()=>t.isTypeOnly()),gn(e,"namedImports",()=>t.getNamedImports()?.map(s=>s.getName()).join(", ")),gn(e,"defaultImport",()=>t.getDefaultImport()?.getText())),Object.keys(e).forEach(s=>{e[s]===void 0&&delete e[s]}),e}function gn(t,e,n){try{let r=n();r!=null&&(t[e]=r)}catch{}}var V,pee,mA=te(()=>{"use strict";V=require("ts-morph");cr();bi();Tm();pee=new Set([V.SyntaxKind.ArrayLiteralExpression,V.SyntaxKind.ArrayType,V.SyntaxKind.ArrowFunction,V.SyntaxKind.AsExpression,V.SyntaxKind.AssertClause,V.SyntaxKind.AssertEntry,V.SyntaxKind.AwaitExpression,V.SyntaxKind.BigIntLiteral,V.SyntaxKind.BinaryExpression,V.SyntaxKind.BindingElement,V.SyntaxKind.Block,V.SyntaxKind.CallExpression,V.SyntaxKind.CallSignature,V.SyntaxKind.CaseClause,V.SyntaxKind.CatchClause,V.SyntaxKind.ClassDeclaration,V.SyntaxKind.ClassExpression,V.SyntaxKind.ClassStaticBlockDeclaration,V.SyntaxKind.ComputedPropertyName,V.SyntaxKind.ConditionalExpression,V.SyntaxKind.ConditionalType,V.SyntaxKind.ConstructSignature,V.SyntaxKind.Constructor,V.SyntaxKind.ConstructorType,V.SyntaxKind.Decorator,V.SyntaxKind.DefaultClause,V.SyntaxKind.DoStatement,V.SyntaxKind.ElementAccessExpression,V.SyntaxKind.EnumDeclaration,V.SyntaxKind.EnumMember,V.SyntaxKind.ExportAssignment,V.SyntaxKind.ExportDeclaration,V.SyntaxKind.ExportSpecifier,V.SyntaxKind.ExpressionStatement,V.SyntaxKind.ExpressionWithTypeArguments,V.SyntaxKind.FalseKeyword,V.SyntaxKind.ForInStatement,V.SyntaxKind.ForOfStatement,V.SyntaxKind.ForStatement,V.SyntaxKind.FunctionDeclaration,V.SyntaxKind.FunctionExpression,V.SyntaxKind.FunctionType,V.SyntaxKind.GetAccessor,V.SyntaxKind.Identifier,V.SyntaxKind.IfStatement,V.SyntaxKind.ImportAttribute,V.SyntaxKind.ImportAttributes,V.SyntaxKind.ImportClause,V.SyntaxKind.ImportDeclaration,V.SyntaxKind.ImportEqualsDeclaration,V.SyntaxKind.ImportSpecifier,V.SyntaxKind.ImportType,V.SyntaxKind.IndexSignature,V.SyntaxKind.IndexedAccessType,V.SyntaxKind.InferType,V.SyntaxKind.InterfaceDeclaration,V.SyntaxKind.IntersectionType,V.SyntaxKind.JsxAttribute,V.SyntaxKind.JsxClosingElement,V.SyntaxKind.JsxClosingFragment,V.SyntaxKind.JsxElement,V.SyntaxKind.JsxExpression,V.SyntaxKind.JsxFragment,V.SyntaxKind.JsxOpeningElement,V.SyntaxKind.JsxOpeningFragment,V.SyntaxKind.JsxSelfClosingElement,V.SyntaxKind.JsxSpreadAttribute,V.SyntaxKind.JsxText,V.SyntaxKind.LiteralType,V.SyntaxKind.MappedType,V.SyntaxKind.MetaProperty,V.SyntaxKind.MethodDeclaration,V.SyntaxKind.MethodSignature,V.SyntaxKind.ModuleDeclaration,V.SyntaxKind.NamedExports,V.SyntaxKind.NamedImports,V.SyntaxKind.NamedTupleMember,V.SyntaxKind.NamespaceExport,V.SyntaxKind.NamespaceExportDeclaration,V.SyntaxKind.NamespaceImport,V.SyntaxKind.NewExpression,V.SyntaxKind.NoSubstitutionTemplateLiteral,V.SyntaxKind.NonNullExpression,V.SyntaxKind.NullKeyword,V.SyntaxKind.NumericLiteral,V.SyntaxKind.ObjectLiteralExpression,V.SyntaxKind.OptionalType,V.SyntaxKind.Parameter,V.SyntaxKind.ParenthesizedType,V.SyntaxKind.PostfixUnaryExpression,V.SyntaxKind.PrefixUnaryExpression,V.SyntaxKind.PrivateIdentifier,V.SyntaxKind.PropertyAccessExpression,V.SyntaxKind.PropertyAssignment,V.SyntaxKind.PropertyDeclaration,V.SyntaxKind.PropertySignature,V.SyntaxKind.QualifiedName,V.SyntaxKind.RegularExpressionLiteral,V.SyntaxKind.RestType,V.SyntaxKind.ReturnStatement,V.SyntaxKind.SatisfiesExpression,V.SyntaxKind.SetAccessor,V.SyntaxKind.ShorthandPropertyAssignment,V.SyntaxKind.SourceFile,V.SyntaxKind.SpreadAssignment,V.SyntaxKind.SpreadElement,V.SyntaxKind.StringLiteral,V.SyntaxKind.SwitchStatement,V.SyntaxKind.TaggedTemplateExpression,V.SyntaxKind.TemplateExpression,V.SyntaxKind.TemplateLiteralType,V.SyntaxKind.ThisType,V.SyntaxKind.ThrowStatement,V.SyntaxKind.TrueKeyword,V.SyntaxKind.TryStatement,V.SyntaxKind.TupleType,V.SyntaxKind.TypeAliasDeclaration,V.SyntaxKind.TypeLiteral,V.SyntaxKind.TypeOfExpression,V.SyntaxKind.TypeOperator,V.SyntaxKind.TypeParameter,V.SyntaxKind.TypePredicate,V.SyntaxKind.TypeQuery,V.SyntaxKind.TypeReference,V.SyntaxKind.UnionType,V.SyntaxKind.VariableDeclaration,V.SyntaxKind.VariableStatement,V.SyntaxKind.WhileStatement,V.SyntaxKind.YieldExpression])});function Al(t){let e=ot(t);return{root:e,historyGit:Cx.join(e,"history.git"),workdir:Cx.join(e,"workdir")}}var Cx,qh=te(()=>{"use strict";Cx=B(require("path"));Qt()});var Yi={};Yt(Yi,{initSnapshotsSchema:()=>Ax,openSnapshotsDb:()=>_i});function Ax(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL"),t.pragma("busy_timeout = 10000");try{t.pragma("temp_store = MEMORY")}catch{}t.exec(`
603
603
  CREATE TABLE IF NOT EXISTS objects (
604
604
  object_id TEXT PRIMARY KEY,
605
605
  kind TEXT DEFAULT 'blob',
@@ -891,7 +891,7 @@ ${r.join(`
891
891
  `)}function cU(t){try{let e=Ti.default.resolve(t);return yr.default.realpathSync.native?yr.default.realpathSync.native(e):yr.default.realpathSync(e)}catch{return null}}function lU(t){let e=new Set,n=[];for(let r of t){let s;try{if(s=yr.default.realpathSync.native?yr.default.realpathSync.native(r):yr.default.realpathSync(r),!yr.default.statSync(s).isDirectory())continue}catch{continue}e.has(s)||(e.add(s),n.push(s))}return n}function Cg(t){return JSON.stringify(t)}var Ng,yr,bN,Ti,Ys,iU,N_=te(()=>{"use strict";Ng=require("child_process"),yr=B(require("fs")),bN=B(require("os")),Ti=B(require("path"));zl();Ys="PANDO_AGENT_SANDBOX_CONTEXT";iU=["/Users","/private/var/log","/Volumes","/srv"]});var O_={};Yt(O_,{SnapshotService:()=>D_});var vN,RN,D_,M_=te(()=>{"use strict";vN=B(require("path")),RN=B(require("fs"));Ja();D_=class{static async takeSnapshotNow(e,n,r,s,o,i,a){ut(a,"Snapshot cancelled");let c=f=>f.replace(/^\.\//,"").replace(/\\/g,"/"),l=Array.from(new Set((n||[]).map(c))).filter(Boolean),u=[];for(let f=0;f<l.length;f++){f>0&&f%128===0&&await Hd(a),ut(a,"Snapshot cancelled");let m=l[f],h=vN.default.join(e,m);try{let g=RN.default.lstatSync(h);(g.isFile()||g.isSymbolicLink())&&u.push(m)}catch{}}let{openSnapshotsDb:d}=await Promise.resolve().then(()=>(Uo(),Yi)),p=d(e);try{ut(a,"Snapshot cancelled");let{SnapshotManager:f}=await Promise.resolve().then(()=>(_g(),xg)),m=new f(p,e),h={"AST-Op":r,"AST-Receipt":JSON.stringify(s||{})};if(o)for(let[b,S]of Object.entries(o))h[b]=S;let{snapshotId:g,parentId:y}=await m.createSnapshotFromFiles(u,{op:r,description:"apply",params:h,dbWrite:"immediate",deleted:Array.isArray(i)?i:void 0},a);ut(a,"Snapshot cancelled");try{await m.indexSnapshotBlobsNodes(p,g,y),console.info(`[SnapshotService] Blob node index updated snapshot=${g} parent=${y||"none"}`)}catch(b){console.log(`[SnapshotService] Blob node indexing failed snapshot=${g}: ${b?.message||b}`)}return{snapshotId:g,parentId:y}}finally{try{p.close()}catch{}}}}});var kN={};Yt(kN,{TypeInference:()=>F_});var rs,F_,EN=te(()=>{"use strict";rs=require("ts-morph"),F_=class{static{this.typeCache=new Map}static{this.MAX_CACHE_SIZE=1e3}static getCacheKey(e){let n=e.getSourceFile(),r=e.getStart(),s=e.getEnd();return`${n.getFilePath()}:${r}-${s}`}static clearCache(){this.typeCache.clear()}static addToCache(e,n){this.typeCache.size>=this.MAX_CACHE_SIZE&&Array.from(this.typeCache.keys()).slice(0,100).forEach(s=>this.typeCache.delete(s)),this.typeCache.set(e,n)}static inferIdentifierType(e){let n=this.getCacheKey(e),r=this.typeCache.get(n);if(r)return r;try{let s=e.getSymbol();if(s){let c=s.getTypeAtLocation(e),l=this.typeToString(c);return this.addToCache(n,l),l}let o=e.getDefinitions();if(o.length>0){let l=o[0].getDeclarationNode();if(l){if(rs.Node.isVariableDeclaration(l))return this.inferVariableType(l);if(rs.Node.isParameterDeclaration(l))return this.inferParameterType(l)}}let i=e.getParent();if(rs.Node.isPropertyAccessExpression(i))return this.inferPropertyAccessType(i);let a="any";return this.addToCache(n,a),a}catch{return this.addToCache(n,"any"),"any"}}static inferVariableType(e){let n=e.getTypeNode();if(n)return n.getText();let r=e.getInitializer();return r?this.inferExpressionType(r):"any"}static inferParameterType(e){let n=e.getTypeNode();if(n)return n.getText();let r=e.getInitializer();return r?this.inferExpressionType(r):"any"}static inferExpressionType(e){try{let n=e.getType();return this.typeToString(n)}catch{if(rs.Node.isStringLiteral(e))return"string";if(rs.Node.isNumericLiteral(e))return"number";if(rs.Node.isTrueLiteral(e)||rs.Node.isFalseLiteral(e))return"boolean";if(rs.Node.isArrayLiteralExpression(e)){let n=e.getElements();return n.length>0?`${this.inferExpressionType(n[0])}[]`:"any[]"}else{if(rs.Node.isObjectLiteralExpression(e))return this.inferObjectLiteralType(e);if(rs.Node.isCallExpression(e))return this.inferCallExpressionType(e)}return"any"}}static inferPropertyAccessType(e){try{let n=e.getType();return this.typeToString(n)}catch{let n=e.getName();return n==="length"?"number":n==="toString"?"() => string":n.startsWith("is")||n.startsWith("has")?"boolean":"any"}}static inferObjectLiteralType(e){let n=e.getProperties();if(n.length===0)return"{}";let r=[];for(let s of n.slice(0,3))if(rs.Node.isPropertyAssignment(s)){let o=s.getName(),i=s.getInitializer();if(i){let a=this.inferExpressionType(i);r.push(`${o}: ${a}`)}}return n.length>3&&r.push("..."),`{ ${r.join(", ")} }`}static inferCallExpressionType(e){try{let n=e.getReturnType();return this.typeToString(n)}catch{let n=e.getExpression().getText();return n.includes("fetch")?"Promise<Response>":n.includes("getElementById")?"HTMLElement | null":n.includes("querySelector")?"Element | null":n.includes("parseInt")?"number":n.includes("JSON.parse")?"any":n.includes("JSON.stringify")?"string":"any"}}static typeToString(e){if(!e)return"any";if(e.isLiteral()){if(e.isStringLiteral())return"string";if(e.isNumberLiteral())return"number";if(e.isBooleanLiteral())return"boolean"}let r=e.getText().replace(/import\([^)]*\)\./g,"").replace(/\n/g," ").replace(/\s+/g," ").trim();if(r.length>50){if(r.includes("Promise<")){let s=r.match(/Promise<([^>]+)>/);if(s)return`Promise<${this.simplifyType(s[1])}>`}if(e.isArray()){let s=e.getArrayElementType();if(s)return`${this.typeToString(s)}[]`}return"any"}return r}static simplifyType(e){return e=e.replace(/import\([^)]*\)\./g,""),e=e.replace(/\w+\./g,""),e.split("|").length>3?"any":e}static inferParameterTypes(e,n){let r=[];n.forEachDescendant(s=>{if(rs.Node.isIdentifier(s)){let o=s.getText();if(e.includes(o)&&!r.find(i=>i.name===o)){let i=this.inferIdentifierType(s);r.push({name:o,type:i})}}});for(let s of e)r.find(o=>o.name===s)||r.push({name:s,type:"any"});return r}static inferReturnType(e){for(let r of e){let s=[];if(r.forEachDescendant(o=>{rs.Node.isReturnStatement(o)&&s.push(o)}),s.length>0){let i=s[0].getExpression();if(i){let a=this.inferExpressionType(i);if(a!=="any")return a}}}let n=e.map(r=>r.getText()).join(`
892
892
  `);return n.includes("return results")||n.includes("return items")?"any[]":n.includes("return true")||n.includes("return false")?"boolean":n.includes("return")&&!n.includes("return;")?"any":"void"}}});var TN=te(()=>{"use strict"});var PN={};Yt(PN,{AtomicExecutor:()=>$_});var $_,CN=te(()=>{"use strict";nd();l_();hp();xp();bp();TN();$_=class{static async execute(e,n,r,s){let o=String(e.op||""),i=["find-nodes"],a=o==="add-code"?"insert":o==="replace-body"?"replace":o;if(a!=="find-nodes"){let d=!i.includes(a),p=a==="insert"&&e.createFileIfMissing===!0;if(d&&!p&&!("expectedHash"in e))return{success:!1,error:`Operation ${e.op} requires expectedHash field.`}}let c;switch(a){case"find-nodes":c=await hc.execute(e,n,r);break;case"insert":c=await ki.execute({...e,op:"insert"},n,r);break;case"replace":o==="replace-body"||e.scope==="body"?c=await yp.execute({...e,op:"replace",scope:"body"},n,r):c=await Sp.execute({...e,op:"replace"},n,r);break;default:c={success:!1,error:`Atomic operation ${e.op} not yet implemented`};break}let u=uo.getInstance(n.projectRoot).getStatus();if(u.isIndexing){c.indexingStatus=u;let d="Warning: Reindexing in progress, results might not be complete or up to date.";if(u.totalFiles&&u.filesProcessed!==void 0){let p=u.totalFiles-u.filesProcessed;if(d+=` ${p} files remaining`,u.estimatedSecondsRemaining)if(u.estimatedSecondsRemaining<60)d+=` (est. ${u.estimatedSecondsRemaining}s)`;else{let f=Math.ceil(u.estimatedSecondsRemaining/60);d+=` (est. ${f} minute${f>1?"s":""})`}}c.message?c.message+=" "+d:c.message=d}return c}}});function X(t,e){W("CodeEngine",t,e)}function Bn(...t){if(t.length===0)return;let[e,...n]=t;if(typeof e=="string"){if(n.length===0){W("CodeEngine",e);return}if(n.length===1){W("CodeEngine",e,n[0]);return}W("CodeEngine",e,n);return}W("CodeEngine","log",t)}function qn(t,e){if(!Vt())return;let n=e&&typeof e=="object"&&!Array.isArray(e)?{pid:process.pid,...e}:{pid:process.pid,details:e};W("CodeEngineReindex",t,n)}function uU(t){return t===void 0||t===0||t===1}function dU(t){let e=String(t??"").replace(/\s+/g," ").trim();return e?e.length>160?`${e.slice(0,157)}...`:e:"Unknown diagnostic"}function pU(t){let e=t.flatMap(r=>(r.topNewDiagnostics||[]).map(s=>`${r.path}:${s.line+1}:${s.column+1} ${s.message}`)).slice(0,3);return e.length>0?`Post-operation validation failed; changes rolled back. Top new diagnostics: ${e.join(" | ")}`:`Post-operation validation failed; changes rolled back. Changed files introduced diagnostics: ${t.slice(0,3).map(r=>{let s=Number(r.newDiagnostics||0);return`${r.path} (${r.errors} error(s)${s>0?`, ${s} new`:""})`}).join("; ")}`}function IN(t,e,n,r){if(t==null)return e;let s=typeof t=="number"||typeof t=="string"?Number(t):NaN;return Number.isFinite(s)?Math.max(n,Math.min(r,Math.floor(s))):e}function fU(t,e=500){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e)}...`}function mU(t){return Pi()?_N(t):xN(t)}function Ps(t){return require("path").resolve(t)}function hU(t){let e=t;if(typeof e.getNameNode=="function"){let n=e.getNameNode();if(n)return n.getStart()}if(typeof e.getName=="function"){let n=e.getName();if(n&&typeof n=="string"){let r=t.getFirstDescendant?.(s=>s.getText?.()===n);if(r&&typeof r.getStart=="function")return r.getStart()}}return null}var j_,L_,z_,AN,ed,uS=te(()=>{"use strict";j_=require("child_process"),L_=B(require("fs")),z_=B(require("path"));ST();Uu();wC();xx();VC();Wa();VS();nd();Qt();Yb();dt();Ja();Rd();Da();Ha();ah();ir();cr();p_();MI();XI();nN();vg();sN();Ss();pN();Ol();ic();kr();N_();AN="language_support_reconcile";ed=class t{constructor(e,n,r){this.operationCount=0;this.modifyingOpActive=!1;this.operationResetController=new AbortController;this.workspaceSyncController=new AbortController;this.refreshingInProgress=!1;this.refreshingFiles=[];this.pendingProjectSync=null;this.pendingLspWorkspaceSync=null;this.batchInProgress=!1;this.batchRunner=null;this.queuedBatch=null;this.indexExcludeDirs=[];this.pendingStatusReindex=[];this.indexingInProgress=!1;this.pendingFullReindex=!1;this.languageSupportReconcileTask=null;this.languageSupportReconcileQueued=!1;this.initialSnapshotTask=null;this.transientIndexers=new Set;let s=um("CodeEngineInit");s("start",{projectPath:e,hasTestProject:!!n}),this.testProject=n;let o=this.resolveInitialProjectPath(e);this.projectPath=o,s("projectPath.set",{projectPath:this.projectPath}),s("projectInit.start"),this.project=lo.initializeProject(this.projectPath,this.testProject),s("projectInit.complete",{sourceFiles:this.project.getSourceFiles().length}),this.snapshotter=new Ih(this.projectPath,()=>this.indexExcludeDirs.slice()),s("snapshotter.ready"),this.indexExcludeDirs=mo(this.projectPath),X("Loaded indexExcludeDirs",this.indexExcludeDirs),s("indexExcludes.loaded",{count:this.indexExcludeDirs.length}),this.languageSupport=r?.languageSupport,this.lspHost=r?.lspHost;try{X("constructor runtime wiring",{projectPath:this.projectPath,hasLanguageSupport:!!this.languageSupport,hasLspHost:!!this.lspHost})}catch{}s("initializeXXHash.start"),this.xxHashReady=(async()=>{try{await kx(),s("initializeXXHash.complete")}catch(i){throw Bn("FATAL: Failed to initialize xxHash:",i),i}})(),r?.enableASTStorage&&X("\u{1F4DD} Incremental AST indexing configured. Call startIndexing() when ready.")}static{this.DIAGNOSTIC_VALIDATION_TIMEOUT_MS=Math.max(500,Number(process.env.PANDO_DIAGNOSTIC_VALIDATION_TIMEOUT_MS||"3000"))}static{this.LARGE_INCREMENTAL_BATCH_FILES=Math.max(1e3,Number(process.env.PANDO_INCREMENTAL_FULL_REINDEX_FILE_THRESHOLD||"5000"))}static{this.LARGE_INCREMENTAL_BATCH_PERCENT=Math.max(1,Number(process.env.PANDO_INCREMENTAL_FULL_REINDEX_PERCENT_THRESHOLD||"15"))}static{this.PROJECT_SYNC_HEARTBEAT_MS=Math.max(1e3,Number(process.env.PANDO_PROJECT_SYNC_HEARTBEAT_MS||"5000"))}static{this.PROJECT_SYNC_SUPERSEDE_SETTLE_MS=Math.max(25,Number(process.env.PANDO_PROJECT_SYNC_SUPERSEDE_SETTLE_MS||"250"))}static{this.RESTORE_FAST_PATH_MAX_AGE_MS=Math.max(1e3,Number(process.env.PANDO_RESTORE_FAST_PATH_MAX_AGE_MS||"300000"))}static{this.WRITE_GATE_WAIT_MS=Math.max(0,Number(process.env.PANDO_WRITE_GATE_WAIT_MS||"0"))}cancelWorkspaceSync(e){let n=this.workspaceSyncController;if(this.workspaceSyncController=new AbortController,!n.signal.aborted)try{n.abort(ar(e,"Workspace sync cancelled"))}catch{try{n.abort()}catch{}}}clearPendingProjectSyncState(e){e&&this.pendingProjectSyncToken!==e||(this.pendingProjectSync=null,this.pendingProjectSyncToken=void 0,this.pendingProjectSyncId=void 0,this.pendingProjectSyncEnqueuedAt=void 0,this.pendingProjectSyncReason=void 0)}invalidateRestoreFastPathState(e,n){this.restoreFastPathState&&(X("[RestoreFastPath] invalidated",{reason:e,currentSnapshotId:this.restoreFastPathState.currentSnapshotId,sourceOp:this.restoreFastPathState.sourceOp??null,ageMs:Date.now()-this.restoreFastPathState.createdAt,...n||{}}),this.restoreFastPathState=void 0)}recordRestoreFastPathState(e,n){let r=typeof n?.snapshotAfter=="string"?String(n.snapshotAfter).trim():"";if(!r||r==="<none>"){this.invalidateRestoreFastPathState("missing-snapshot-after",{op:e??null,success:!!n?.success});return}this.restoreFastPathState={currentSnapshotId:r,sourceOp:e??null,createdAt:Date.now()},X("[RestoreFastPath] state.recorded",{currentSnapshotId:r,sourceOp:e??null})}installRestoreFastPathMetadata(e,n){let r=this.restoreFastPathState;if(!r){n.clearOperationMetadata(e,kp);return}let s=Date.now()-r.createdAt;if(s>t.RESTORE_FAST_PATH_MAX_AGE_MS){this.invalidateRestoreFastPathState("stale",{ageMs:s}),n.clearOperationMetadata(e,kp);return}n.setOperationMetadata(e,kp,r),X("[RestoreFastPath] metadata.installed",{currentSnapshotId:r.currentSnapshotId,sourceOp:r.sourceOp??null,ageMs:s})}async supersedePendingProjectSyncForRestore(e){let n=this.pendingProjectSync;if(!n)return;let r=Date.now();X("[ProjectSync] superseding for restore",{operation:e??null,syncId:this.pendingProjectSyncId??null,reason:this.pendingProjectSyncReason??null,queuedForMs:this.pendingProjectSyncEnqueuedAt?Date.now()-this.pendingProjectSyncEnqueuedAt:null,queuedBatch:this.describeQueuedBatch(),batchInProgress:this.batchInProgress,batchPhase:this.batchPhase??null}),this.queuedBatch=null,this.clearPendingProjectSyncState(),this.cancelWorkspaceSync(`${String(e||"restore-snapshot")} superseded pending project sync`);let s=t.PROJECT_SYNC_SUPERSEDE_SETTLE_MS,o,i=new Promise(a=>{o=setTimeout(()=>a("timeout"),s),o.unref?.()});try{let a=await Promise.race([n.then(()=>"settled").catch(c=>(hi(c)||X("[ProjectSync] supersede settle saw failure",{operation:e??null,message:c?.message||String(c)}),"settled")),i]);X("[ProjectSync] supersede settle complete",{operation:e??null,settled:a,settleTimeoutMs:s,durationMs:Date.now()-r})}finally{o&&clearTimeout(o)}}async collectDiagnostics(e,n){let r=Date.now();try{X("collectDiagnostics:start",{projectPath:this.projectPath,files:n,hasEngineLspHost:!!this.lspHost,hasContextLspHost:!!e.lsp})}catch{}if(!e.lsp)if(this.lspHost)e.setLspHost(this.lspHost);else try{let{CodeEngineFactory:u}=await Promise.resolve().then(()=>(Ls(),rl)),d=u.getEngineOptions(this.projectPath);d?.lspHost&&e.setLspHost(d.lspHost),X("collectDiagnostics:recoveredRuntimeOptions",{projectPath:this.projectPath,hasStoredLspHost:!!d?.lspHost})}catch{}let s=e.lsp;try{X("collectDiagnostics:resolvedHost",{projectPath:this.projectPath,hasLspHost:!!s})}catch{}let o=new Map,i=require("path"),a=require("fs"),{resolveLanguageIdForPath:c}=(ir(),ke(jP)),{getClojureDiagnostics:l}=(ho(),ke(lC));for(let u of n){let d=Date.now(),p=i.isAbsolute(u)?u:i.join(this.projectPath,u);if(!a.existsSync(p))continue;let f;try{f=c(p);let m;if(f==="clojure")m=l(this.projectPath,p);else{if(!s)continue;m=await Promise.race([s.diagnostics(p),new Promise((b,S)=>setTimeout(()=>S(new Error("__pando_diag_timeout__")),t.DIAGNOSTIC_VALIDATION_TIMEOUT_MS))])}let h=new Set,g=[],y=0;for(let b of m||[]){let S=b.severity;if(uU(S)){y+=1;let x=b.range,w=`${b.message??""}|${x?.start?.line??0}:${x?.start?.character??0}-${x?.end?.line??0}:${x?.end?.character??0}`;h.add(w),g.length<10&&g.push({signature:w,message:dU(b.message),line:Number(x?.start?.line??0),column:Number(x?.start?.character??0)})}}o.set(u,{errors:y,signatures:h,diagnostics:g})}catch(m){if(String(m?.message||m||"")==="__pando_diag_timeout__"){o.set(u,{errors:0,signatures:new Set,skipped:!0});continue}o.set(u,{errors:1,signatures:new Set(["diagnostics_error"])})}finally{let m=Date.now()-d;m>1e3&&X("collectDiagnostics:file.slow",{projectPath:this.projectPath,file:u,lang:f??null,durationMs:m})}}return X("collectDiagnostics:complete",{projectPath:this.projectPath,files:n.length,captured:o.size,durationMs:Date.now()-r}),o}async validateChangedFiles(e,n,r){try{X("validateChangedFiles:start",{projectPath:this.projectPath,changedFiles:n,hasEngineLspHost:!!this.lspHost,hasContextLspHost:!!e.lsp})}catch{}if(!e.lsp)if(this.lspHost)e.setLspHost(this.lspHost);else try{let{CodeEngineFactory:c}=(Ls(),ke(rl)),l=c.getEngineOptions(this.projectPath);l?.lspHost&&e.setLspHost(l.lspHost),X("validateChangedFiles:recoveredRuntimeOptions",{projectPath:this.projectPath,hasStoredLspHost:!!l?.lspHost})}catch{}let s=n.some(c=>{let l=z_.default.isAbsolute(c)?c:z_.default.join(this.projectPath,c);return Zt(l)!=="clojure"});if(!e.lsp&&s){try{X("validateChangedFiles:skippedNoHost",{projectPath:this.projectPath})}catch{}return{ok:!0,skipped:!0,warning:"Post-operation validation skipped: no active LSP host."}}let o=await this.collectDiagnostics(e,n),i=[],a=[];for(let c of n){let l=o.get(c);if(!l)continue;let u=r?.get(c);if(!u)continue;if(u.skipped||l.skipped){a.push(c);continue}let d=Array.from(l.signatures).filter(p=>!u.signatures.has(p)).length;if(l.errors>u.errors||d>0){let p=(l.diagnostics||[]).filter(f=>!u.signatures.has(f.signature)).slice(0,3).map(({signature:f,...m})=>m);i.push({path:c,errors:l.errors,newDiagnostics:d,topNewDiagnostics:p})}}if(i.length>0){let c=i.flatMap(l=>(l.topNewDiagnostics||[]).map(u=>`${l.path}:${u.line+1}:${u.column+1} ${u.message}`)).slice(0,3);return{ok:!1,errors:i,topDiagnostics:c,error:pU(i)}}return a.length>0?{ok:!0,skipped:!0,warning:`Post-operation validation skipped for ${a.length} file(s) because diagnostics did not respond within ${t.DIAGNOSTIC_VALIDATION_TIMEOUT_MS}ms.`}:{ok:!0}}extractTouchedFiles(e){let n=new Set,r=o=>{if(typeof o!="string"||!o.trim())return;let i=o.split("#")[0];i&&n.add(i)},s=o=>{if(typeof o=="string"){r(o);return}if(o&&typeof o=="object"){let i=o;r(i.before),r(i.after),r(i.start),r(i.end),r(i.bodyStartOf),r(i.bodyEndOf)}};if(r(e?.path),Array.isArray(e?.path))for(let o of e.path)r(o);if(r(e?.of),s(e?.to),Array.isArray(e?.files))for(let o of e.files)r(o);return Array.from(n)}async preflightExpectedHashCheck(e,n,r){let s=typeof e?.expectedHash=="string"?e.expectedHash.trim():"";if(!s||s.includes("@"))return{ok:!0};let o=Ux(e),i=typeof o=="string"&&/:FunctionArity(?:@|$)/.test(o);try{if(!i&&await Jo(n,e,r))return{ok:!0}}catch(a){return{ok:!1,error:a?.message||String(a)}}if(typeof o!="string"||!o.includes("#"))return{ok:!0};try{let a=await ns(this.projectPath,o);if(!a)return{ok:!0};let c=Je(o,a.text),l=s.startsWith("@")?s:`@${s}`,u=mn(l,c);if(u.type!=="MATCH")return{ok:!1,error:`Hash mismatch (${u.type}). Re-run find-nodes to refresh the target.`}}catch{return{ok:!0}}return{ok:!0}}get indexer(){return this._indexer||(this._indexer=new Qa(this.projectPath,void 0,{excludeDirs:this.indexExcludeDirs,languageSupport:this.languageSupport})),this._indexer}createTransientIndexer(e="transient"){let n=Bs(),r=qs("indexer-worker");X("[IndexerDiag] createTransientIndexer",{projectPath:this.projectPath,reason:e,activeTransientIndexers:this.transientIndexers.size,workerScript:r,workerScriptExists:r?L_.default.existsSync(r):!1,runtimePaths:n,env:{runtimeRoot:process.env.PANDO_RUNTIME_ROOT??null,workerRoot:process.env.PANDO_WORKER_SCRIPT_DIR??null}});let s=new Qa(this.projectPath,void 0,{excludeDirs:this.indexExcludeDirs,languageSupport:this.languageSupport});return this.transientIndexers.add(s),s}disposeTransientIndexer(e,n="transient indexer complete"){if(e){X("[IndexerDiag] disposeTransientIndexer",{projectPath:this.projectPath,reason:n,activeTransientIndexers:this.transientIndexers.size}),this.transientIndexers.delete(e);try{e.dispose(n)}catch{}}}async withTransientIndexer(e,n="transient run"){let r=this.createTransientIndexer(n);try{return await e(r)}finally{this.disposeTransientIndexer(r,n)}}cancelIndexing(e){if(this._indexer)try{this._indexer.cancelIndexing(e)}catch{}for(let n of Array.from(this.transientIndexers))try{n.cancelIndexing(e)}catch{}}cancelActiveOperations(e){let n=this.operationResetController;if(this.operationResetController=new AbortController,!n.signal.aborted)try{n.abort(ar(e,"Operation cancelled"))}catch{try{n.abort()}catch{}}}dispose(){this.cancelActiveOperations("engine dispose"),this.cancelWorkspaceSync("engine dispose"),this.cancelIndexing("dispose");try{uo.getInstance(this.projectPath).reset()}catch{}try{let{SnapshotStatusTracker:e}=(Za(),ke(Ka));e.getInstance(this.projectPath).complete()}catch{}try{let{FTSStatusTracker:e}=(Od(),ke(gh));e.getInstance(this.projectPath).complete()}catch{}if(this._indexer&&typeof this._indexer.dispose=="function")try{this._indexer.dispose("engine dispose")}catch{}this._indexer=void 0;for(let e of Array.from(this.transientIndexers))this.disposeTransientIndexer(e,"engine dispose");if(this.snapshotter){try{this.snapshotter.dispose()}catch{}this.snapshotter=void 0}}async drainPendingProjectSync(e="external wait"){let n=this.pendingProjectSync;n&&(X("[ProjectSync] drain requested",{reason:e,syncId:this.pendingProjectSyncId??null,pendingReason:this.pendingProjectSyncReason??null,queuedForMs:this.pendingProjectSyncEnqueuedAt?Date.now()-this.pendingProjectSyncEnqueuedAt:null,batchInProgress:this.batchInProgress,batchPhase:this.batchPhase??null}),await n,X("[ProjectSync] drain complete",{reason:e,syncId:this.pendingProjectSyncId??null,pendingReason:this.pendingProjectSyncReason??null}))}setRuntimeOptions(e){this.languageSupport=e?.languageSupport,this.lspHost=e?.lspHost;try{X("setRuntimeOptions",{projectPath:this.projectPath,hasLanguageSupport:!!this.languageSupport,hasLspHost:!!this.lspHost})}catch{}}getIndexingStore(){return this.indexingStore||(this.indexingStore=new gr(this.projectPath)),this.indexingStore}readLanguageSupportReconcileState(){try{let e=this.getIndexingStore().getIndexerMeta(AN);if(!e)return null;let n=JSON.parse(e);if(!n||typeof n!="object")return null;let r=n.state==="pending"||n.state==="applying"||n.state==="applied"?n.state:null;return r?{state:r,desiredEnabledLanguages:Array.isArray(n.desiredEnabledLanguages)?n.desiredEnabledLanguages.filter(s=>typeof s=="string"):[],appliedEnabledLanguages:Array.isArray(n.appliedEnabledLanguages)?n.appliedEnabledLanguages.filter(s=>typeof s=="string"):[],updatedAt:typeof n.updatedAt=="number"?n.updatedAt:Date.now(),message:typeof n.message=="string"?n.message:"",startedAt:typeof n.startedAt=="number"?n.startedAt:void 0,completedAt:typeof n.completedAt=="number"?n.completedAt:void 0,purgedIndexedFiles:typeof n.purgedIndexedFiles=="number"?n.purgedIndexedFiles:void 0,coldWorkspace:typeof n.coldWorkspace=="boolean"?n.coldWorkspace:void 0,pendingRestart:typeof n.pendingRestart=="boolean"?n.pendingRestart:void 0,lastError:typeof n.lastError=="string"?n.lastError:void 0}:null}catch{return null}}writeLanguageSupportReconcileState(e){this.getIndexingStore().setIndexerMeta(AN,`${JSON.stringify(e)}
893
893
  `)}hasCompletedIndexRun(){try{let e=this.getIndexingStore();if(e.getIndexingSession()?.run_state==="completed")return!0;let r=e.getIndexerMeta("indexing_session_stats");if(r)try{if(JSON.parse(r)?.runState==="completed")return!0}catch{}return!1}catch{return!1}}shouldScheduleBackgroundIndexing(){if(/^(1|true|yes)$/i.test(String(process.env.PANDO_FORCE_INITIAL_INDEXING||"")))return!0;try{let e=this.collectIndexedFileRels().length;if(e>0){let n=this.getIndexingStore(),r=n.getIndexingSession();return JS({projectRoot:this.projectPath,store:n,sessionData:r,pendingCount:Math.max(0,Number(n.getPendingStats?.()?.count||0)),overviewTotal:Math.max(0,Math.floor(Number(r?.total_files_estimate)||0)),overviewProcessed:e,indexingIsIndexing:!1,logScope:"CodeEngine"}),!1}}catch(e){try{W("CodeEngine","shouldScheduleBackgroundIndexing metadata check failed",{projectRoot:this.projectPath,error:e instanceof Error?e.message:String(e)})}catch{}}return!this.hasCompletedIndexRun()}async waitForIndexingToSettle(e=3e4){let n=Date.now()+Math.max(1e3,e);for(;this.indexingInProgress&&Date.now()<n;)await new Promise(r=>setTimeout(r,100));return!this.indexingInProgress}enqueueLanguageSupportReconcile(){if(this.languageSupportReconcileTask){this.languageSupportReconcileQueued=!0;return}this.languageSupportReconcileTask=(async()=>{do this.languageSupportReconcileQueued=!1,await this.runLanguageSupportReconcile();while(this.languageSupportReconcileQueued)})().catch(e=>{let n=Ia(this.projectPath).enabledLanguages;this.writeLanguageSupportReconcileState({state:"pending",desiredEnabledLanguages:n,appliedEnabledLanguages:this.readLanguageSupportReconcileState()?.appliedEnabledLanguages??n,updatedAt:Date.now(),message:"Language support reconcile failed; config is saved but not fully applied yet.",lastError:e instanceof Error?e.message:String(e)}),X("language support reconcile failed",{projectPath:this.projectPath,error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.languageSupportReconcileTask=null,this.languageSupportReconcileQueued&&this.enqueueLanguageSupportReconcile()})}async runLanguageSupportReconcile(){let e=Ia(this.projectPath).enabledLanguages,n=this.readLanguageSupportReconcileState();this.languageSupport=Na(this.projectPath);let r=Date.now();if(this.writeLanguageSupportReconcileState({state:"applying",desiredEnabledLanguages:e,appliedEnabledLanguages:n?.appliedEnabledLanguages??e,updatedAt:r,startedAt:r,message:"Applying language support configuration in the background."}),!this.hasCompletedIndexRun()){this.writeLanguageSupportReconcileState({state:"applied",desiredEnabledLanguages:e,appliedEnabledLanguages:e,updatedAt:Date.now(),startedAt:r,completedAt:Date.now(),coldWorkspace:!0,message:"Applied to future indexing; no completed index existed yet."});return}let s=Hs(this.languageSupport),o=this.collectIndexedFileRels().filter(l=>{let u=require("path").extname(l).toLowerCase();return!s.has(u)});if(this.cancelIndexing("language support changed"),this._indexer){try{this._indexer.dispose("language support changed")}catch{}this._indexer=void 0}for(let l of Array.from(this.transientIndexers))this.disposeTransientIndexer(l,"language support changed");let i=await this.waitForIndexingToSettle(),a=0;o.length>0&&(a=await this.withTransientIndexer(l=>l.purgeDeleted(o),"purge disabled language files"));let c=!1;i?await this.startIndexing():(c=!0,this.pendingFullReindex=!0),this.writeLanguageSupportReconcileState({state:"applied",desiredEnabledLanguages:e,appliedEnabledLanguages:e,updatedAt:Date.now(),startedAt:r,completedAt:Date.now(),purgedIndexedFiles:a,pendingRestart:c,message:c?"Applied config and purged disabled-language files; a restart of indexing is queued.":"Applied config and reconciled index state."})}computeIndexingEta(){try{let e=this.getIndexingStore(),n=e.getThroughput(),r=e.getPendingStats(),s=typeof n.avg_files_per_sec=="number"&&n.avg_files_per_sec>0?n.avg_files_per_sec:null;if(s&&r.count>0)return{seconds:Math.max(1,Math.ceil(r.count/s)),basis:"files"};let o=typeof n.avg_bytes_per_sec=="number"&&n.avg_bytes_per_sec>0?n.avg_bytes_per_sec:null;if(o&&r.known_bytes>0)return{seconds:Math.max(1,Math.ceil(r.known_bytes/o)),basis:"bytes"}}catch(e){try{W("CodeEngine","computeIndexingEta failed",{error:e?.message||e})}catch{}}return null}isPathExcludedForIndex(e){let n=Date.now(),r=VP(this.projectPath,this.indexExcludeDirs,e),s=Date.now()-n;return X("isPathExcludedForIndex result",{absPath:e,excluded:r,entries:this.indexExcludeDirs}),s>50&&X("[BatchQueue] isPathExcludedForIndex slow",{absPath:e,excluded:r,elapsedMs:s,entries:this.indexExcludeDirs}),r}finishBatch(e,n){let r=this.batchStartMs?Date.now()-this.batchStartMs:null;X("[BatchQueue] finishBatch",{reason:e,elapsedMs:r,phase:this.batchPhase??null,phaseElapsedMs:this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null,...n||{}}),this.batchInProgress=!1,this.batchStartMs=void 0,this.batchPhase=void 0,this.batchPhaseStartMs=void 0,this.batchWatchdogTimer&&(clearInterval(this.batchWatchdogTimer),this.batchWatchdogTimer=void 0),X("[BatchQueue] finishBatch complete",{batchInProgress:this.batchInProgress,indexingInProgress:this.indexingInProgress,refreshingInProgress:this.refreshingInProgress,queuedBatch:this.describeQueuedBatch(),pendingFullReindex:this.pendingFullReindex,pendingStatusReindex:this.pendingStatusReindex.length,watchdogActive:!!this.batchWatchdogTimer})}describeQueuedBatch(){return this.queuedBatch?{created:this.queuedBatch.created.size,modified:this.queuedBatch.modified.size,deleted:this.queuedBatch.deleted.size}:null}mergeQueuedBatch(e,n){this.queuedBatch?this.queuedBatch.source==="post-write-sync"&&n!=="post-write-sync"&&(this.queuedBatch.source=n):this.queuedBatch={created:new Set,modified:new Set,deleted:new Set,source:n};let r=this.queuedBatch,s=a=>{let c=Ps(a);r.deleted.delete(c),r.modified.delete(c),r.created.add(c)},o=a=>{let c=Ps(a);r.deleted.has(c)||r.created.has(c)||r.modified.add(c)},i=a=>{let c=Ps(a);r.created.delete(c),r.modified.delete(c),r.deleted.add(c)};for(let a of e.created)s(a);for(let a of e.modified)o(a);for(let a of e.deleted)i(a);return this.describeQueuedBatch()??{created:0,modified:0,deleted:0}}takeQueuedBatch(){if(!this.queuedBatch)return null;let e={created:Array.from(this.queuedBatch.created),modified:Array.from(this.queuedBatch.modified),deleted:Array.from(this.queuedBatch.deleted),source:this.queuedBatch.source};return this.queuedBatch=null,e.created.length+e.modified.length+e.deleted.length>0?e:null}shouldEscalateBatchToFullReindex(e){if(e>=t.LARGE_INCREMENTAL_BATCH_FILES)return{should:!0,reason:`file-count:${e}>=${t.LARGE_INCREMENTAL_BATCH_FILES}`};if(e<1e3)return{should:!1};try{let n=new gr(this.projectPath).getAllKnownFiles().size,r=Math.max(1,Math.ceil(n*t.LARGE_INCREMENTAL_BATCH_PERCENT/100));if(n>0&&e>=r)return{should:!0,reason:`file-percent:${e}/${n}>=${t.LARGE_INCREMENTAL_BATCH_PERCENT}%`,knownFiles:n}}catch{}return{should:!1}}ensureBatchRunner(){if(this.batchRunner)return this.batchRunner;if(this.indexingInProgress)return Promise.resolve();let e=this.runBatchRunnerLoop().catch(n=>{Bn("[BatchQueue] runner failed",n?.message||n)}).finally(()=>{this.batchRunner===e&&(this.batchRunner=null),this.queuedBatch&&!this.indexingInProgress&&this.ensureBatchRunner()});return this.batchRunner=e,e}async runBatchRunnerLoop(){for(;;){if(this.indexingInProgress)return;let e=this.takeQueuedBatch();if(!e)return;await this.processQueuedBatch(e,this.workspaceSyncController.signal)}}filterExcludedAbsolutePaths(e){if(!this.indexExcludeDirs.length)return e;X("filterExcludedAbsolutePaths input",{count:e.length,sample:e.slice(0,10)});let n=e.filter(r=>!this.isPathExcludedForIndex(r));return X("filterExcludedAbsolutePaths output",{count:n.length,excluded:e.length-n.length,sample:n.slice(0,10)}),n}async handleAddExcludeDir(e){let n=typeof e.directory=="string"?e.directory.trim():"";if(!n)return{success:!1,error:"Parameter 'directory' is required"};let r=ch(this.projectPath,[n]);if(r.length===0)return{success:!1,error:"Directory must be inside the workspace root",details:{directory:n}};let s=r[0];if(X("handleAddExcludeDir normalized entry",{dirInput:n,normalizedEntry:s}),this.indexExcludeDirs.includes(s))return{success:!0,details:{alreadyExcluded:!0,excludeDirs:this.indexExcludeDirs}};let o=[];try{o=(await this.withTransientIndexer(l=>l.scanFiles({relativeDirs:[s]}))).map(l=>l.relPath)}catch(c){return{success:!1,error:`Failed to scan target directory: ${c?.message||c}`}}let i=GP(this.projectPath,s,this.indexExcludeDirs);X("handleAddExcludeDir updated exclude list",i),KS(this.projectPath,i),this.indexExcludeDirs=mo(this.projectPath),X("handleAddExcludeDir reloaded exclude list",this.indexExcludeDirs);let a=0;if(o.length)try{a=await this.withTransientIndexer(c=>c.purgeDeleted(o))}catch(c){return{success:!1,error:`Failed to purge excluded files: ${c?.message||c}`}}return{success:!0,details:{excludeDirs:this.indexExcludeDirs,newlyExcluded:s,purged:a,candidatesRemoved:o.length}}}async handleRemoveExcludeDir(e){let n=typeof e.directory=="string"?e.directory.trim():"";if(!n)return{success:!1,error:"Parameter 'directory' is required"};let r=ch(this.projectPath,[n]);if(r.length===0)return{success:!1,error:"Directory must be inside the workspace root",details:{directory:n}};let s=r[0];if(X("handleRemoveExcludeDir normalized entry",{dirInput:n,normalizedEntry:s}),s===".clj-kondo")return{success:!0,details:{removed:!1,protectedDefault:!0,excludeDirs:this.indexExcludeDirs,message:".clj-kondo remains excluded from semantic indexing by default. .clj-kondo/.cache is always hard-ignored."}};if(!this.indexExcludeDirs.includes(s))return{success:!0,details:{removed:!1,excludeDirs:this.indexExcludeDirs}};let o=JP(this.projectPath,s,this.indexExcludeDirs);X("handleRemoveExcludeDir updated list",o),KS(this.projectPath,o),this.indexExcludeDirs=mo(this.projectPath),X("handleRemoveExcludeDir reloaded exclude list",this.indexExcludeDirs);let i=[];try{let c=await this.withTransientIndexer(l=>l.scanFiles({relativeDirs:[s]}));i=this.filterExcludedAbsolutePaths(c.map(l=>Ps(l.absPath)))}catch(c){return{success:!1,error:`Failed to scan newly included directory: ${c?.message||c}`}}let a=0;if(i.length){try{a=(await this.withTransientIndexer(l=>l.indexFiles(i.map(u=>Ps(u))))).processed}catch(c){return{success:!1,error:`Failed to index newly included files: ${c?.message||c}`}}try{await this.refreshFilesFromDisk(i)}catch(c){Bn("[ExcludeDirs] refresh failed",c?.message||c)}}return{success:!0,details:{excludeDirs:this.indexExcludeDirs,newlyIncluded:s,indexed:a,candidates:i.length}}}handleGetProjectRoot(){try{return{success:!0,details:{root:this.projectPath}}}catch(e){return{success:!1,error:`Failed to read project root: ${e?.message||e}`}}}collectIndexedFileRels(){let e=new Set,n=[];try{n=L_.default.readdirSync(ot(this.projectPath)).filter(s=>s.startsWith(".pando-index-chunk-")&&s.endsWith(".db")).map(s=>require("path").join(ot(this.projectPath),s)).sort((s,o)=>s.localeCompare(o))}catch{n=[]}if(n.length===0)return[];let{default:r}=(an(),ke(ps));for(let s of n){let o;try{o=new r(s,{readonly:!0,fileMustExist:!0});let i=o.prepare("SELECT df.path AS path FROM files f JOIN dict_files df ON f.file_id = df.id").all();for(let a of i)typeof a.path=="string"&&a.path.length>0&&e.add(a.path)}catch{}finally{try{o?.close?.()}catch{}}}return Array.from(e)}async handleSetEnabledLanguages(e){let n;try{n=Ia(this.projectPath)}catch(a){return{success:!1,error:`Failed to read enabled languages: ${a?.message||a}`}}if(!("languages"in e)||e.languages==null)return{success:!0,details:{...n,languageSupportChanged:!1}};if(!Array.isArray(e.languages))return{success:!0,details:{...n,valid:!1,error:"Parameter 'languages' must be an array when provided.",languageSupportChanged:!1}};let r=new Set(n.availableLanguages),s=e.languages.filter(a=>typeof a!="string"||!r.has(a));if(s.length>0)return{success:!0,details:{...n,valid:!1,error:"Invalid enabled language value.",invalidLanguages:s,languageSupportChanged:!1}};let o=gS(this.projectPath,e.languages),i=JSON.stringify(n.enabledLanguages)===JSON.stringify(o.enabledLanguages);return this.languageSupport=Na(this.projectPath),i?this.writeLanguageSupportReconcileState({state:"applied",desiredEnabledLanguages:o.enabledLanguages,appliedEnabledLanguages:o.enabledLanguages,updatedAt:Date.now(),completedAt:Date.now(),message:"Language support config already applied."}):(this.writeLanguageSupportReconcileState({state:"pending",desiredEnabledLanguages:o.enabledLanguages,appliedEnabledLanguages:this.readLanguageSupportReconcileState()?.appliedEnabledLanguages??n.enabledLanguages,updatedAt:Date.now(),message:"Language support config saved; reconcile is queued."}),this.enqueueLanguageSupportReconcile()),{success:!0,details:{...o,languageSupportChanged:!i,reconcileScheduled:!i,reconcileState:i?"applied":"pending"}}}async handleSnapshotWorktree(e,n){let r=typeof e.message=="string"?e.message.trim():"",s=e.trailers&&typeof e.trailers=="object"?e.trailers:{},o=null;try{let{SnapshotStatusTracker:c}=await Promise.resolve().then(()=>(Za(),Ka));o=c.getInstance(this.projectPath)}catch{o=null}if(o&&o.isSnapshotting)return{success:!1,error:"Snapshotting in progress; retry shortly."};let{openSnapshotsDb:i}=await Promise.resolve().then(()=>(Uo(),Yi)),a=i(this.projectPath);try{ut(n,"snapshot-worktree cancelled");let l=a.prepare("SELECT snapshot_id FROM snapshots ORDER BY timestamp DESC, rowid DESC LIMIT 1").get()?.snapshot_id,u=hs(this.projectPath,this.indexExcludeDirs),d=WP(this.projectPath,{shouldExclude:u??void 0,gitignoreRoot:this.projectPath}),p=require("path"),f=require("fs"),m=require("crypto"),h=d.map(P=>p.relative(this.projectPath,P).replace(/\\/g,"/")).filter(Boolean).sort((P,M)=>P.localeCompare(M));await Hd(n);let{computeEffectiveMap:g}=await Promise.resolve().then(()=>(xo(),vi)),y=l?g(a,l):new Map,b=P=>{let M=Buffer.from(`blob ${P.length}\0`,"utf8");return m.createHash("sha1").update(M).update(P).digest("hex")},S=P=>{let M=f.lstatSync(P);if(M.isSymbolicLink()){let O=f.readlinkSync(P);return["symlink","120000",b(Buffer.from(O,"utf8")),O].join("\0")}if(!M.isFile())return["other","","",""].join("\0");let N=f.readFileSync(P);return["file",M.mode&73?"100755":"100644",b(N),""].join("\0")},x=P=>{if(!P)return null;let M=P.entryKind==="symlink"?"symlink":"file";return[M,P.mode||(M==="symlink"?"120000":"100644"),P.oid,P.symlinkTarget||""].join("\0")},w=[],R=new Set;for(let P=0;P<h.length;P++){P>0&&P%64===0&&await Hd(n),ut(n,"snapshot-worktree cancelled");let M=h[P];R.add(M);let N=p.join(this.projectPath,M),O="";try{O=S(N)}catch{O=""}let A=x(y.get(M));(!l||A==null||A!==O)&&w.push(M)}ut(n,"snapshot-worktree cancelled");let E=ih(this.projectPath),_=P=>{let M=p.join(this.projectPath,P);return wd(M)||u?.(M)?!1:!E(M,!1)},v=l?Array.from(y.keys()).filter(P=>!R.has(P)&&_(P)).sort((P,M)=>P.localeCompare(M)):[],F={op:"snapshot-worktree",message:r||void 0,timestamp:Date.now(),scannedFilesCount:h.length,changedFilesCount:w.length,deletedFilesCount:v.length};if(w.length===0&&v.length===0){try{o?.complete()}catch{}return this.pendingShellCommandSnapshotFailure=void 0,{success:!0,snapshotBefore:l||"<none>",snapshotAfter:l||"<none>",details:{receipt:F,changedFiles:[],deletedFiles:[],snapshotSkipped:!0,message:"No changes detected since the latest Pando snapshot."}}}let{SnapshotService:D}=await Promise.resolve().then(()=>(M_(),O_)),I={};r&&(I["AST-Message"]=r);for(let[P,M]of Object.entries(s))M!=null&&(I[String(P)]=String(M));try{o?.start(w.length,v.length)}catch{}try{let{snapshotId:P,parentId:M}=await D.takeSnapshotNow(this.projectPath,w,"snapshot-worktree",F,I,v,n);try{o?.complete()}catch{}return this.pendingShellCommandSnapshotFailure=void 0,{success:!0,snapshotBefore:M||l||"<none>",snapshotAfter:P,details:{receipt:F,changedFiles:w,deletedFiles:v}}}catch(P){try{o?.complete()}catch{}throw P}}catch(c){try{o?.complete()}catch{}throw c}finally{try{a.close()}catch{}}}async handlePandoShellCommand(e,n){let r=typeof e.command=="string"?e.command:"",s=typeof e.reasonWhyNotUsingPandoNativeTools=="string"?e.reasonWhyNotUsingPandoNativeTools.trim():"",o=IN(e.timeoutMs,12e4,1e3,6e5),i=IN(e.maxOutputBytes,2e5,1024,1e6),a=typeof e.shell=="string"&&e.shell.trim()?e.shell.trim():void 0,c=Date.now(),l=await mU({command:r,cwd:this.projectPath,shell:a,timeoutMs:o,maxOutputBytes:i,signal:n}),u=`shell-command: ${s}`,d;try{d=await this.handleSnapshotWorktree({message:u,trailers:{"AST-Reason-Why-Not-Using-Pando-Native-Tools":s,"AST-Command":fU(r),"AST-Exit-Code":l.exitCode==null?"":String(l.exitCode),"AST-Timed-Out":String(l.timedOut)}})}catch(h){let g=h?.message||String(h);return this.pendingShellCommandSnapshotFailure={reason:s,command:r,error:g,failedAt:Date.now()},{success:!1,error:`Command completed but snapshot failed: ${g}`,details:{reasonWhyNotUsingPandoNativeTools:s,command:r,cwd:this.projectPath,shell:a??null,timeoutMs:o,maxOutputBytes:i,commandResult:l,snapshotFailed:!0}}}if(!d?.success){let h=d?.error||"Unknown snapshot failure";return this.pendingShellCommandSnapshotFailure={reason:s,command:r,error:h,failedAt:Date.now()},{success:!1,error:`Command completed but snapshot failed: ${h}`,snapshotBefore:d?.snapshotBefore,snapshotAfter:d?.snapshotAfter,details:{reasonWhyNotUsingPandoNativeTools:s,command:r,cwd:this.projectPath,shell:a??null,timeoutMs:o,maxOutputBytes:i,commandResult:l,snapshotResult:d,snapshotFailed:!0}}}let p=d?.details||{},f=l.exitCode===0&&!l.timedOut&&!l.error,m=f?void 0:l.timedOut?`Command timed out after ${o}ms`:l.error||(l.signal?`Command terminated by signal ${l.signal}`:`Command exited with code ${l.exitCode??"unknown"}`);return{success:f,...m?{error:m}:{},snapshotBefore:d.snapshotBefore,snapshotAfter:d.snapshotAfter,details:{reasonWhyNotUsingPandoNativeTools:s,command:r,cwd:this.projectPath,shell:a??null,timeoutMs:o,maxOutputBytes:i,commandResult:l,durationMs:Date.now()-c,receipt:p.receipt,changedFiles:(Array.isArray(p.changedFiles)?p.changedFiles:[]).slice(0,10),changedFilesTruncated:Array.isArray(p.changedFiles)&&p.changedFiles.length>10,deletedFiles:(Array.isArray(p.deletedFiles)?p.deletedFiles:[]).slice(0,10),deletedFilesTruncated:Array.isArray(p.deletedFiles)&&p.deletedFiles.length>10,snapshotSkipped:!!p.snapshotSkipped,snapshotMessage:u}}}getWorktreeChanges(e){try{let n=(0,j_.execFileSync)("git",["rev-parse","--show-prefix"],{cwd:e,encoding:"utf8"}).toString().replace(/\r?\n/g,""),s=(0,j_.execFileSync)("git",["status","--porcelain","-z"],{cwd:e,encoding:"utf8"}).toString().split("\0").filter(Boolean),o=new Set,i=new Set,a=l=>l.replace(/^\.\//,"").replace(/\\/g,"/"),c=l=>{if(!n)return a(l);let u=a(l);return u.startsWith(n)?u.slice(n.length):u};for(let l of s){if(l.length<3)continue;let u=l.slice(0,2),d=l.slice(3);if(!d)continue;let p=u.includes("D"),f=d.split(" -> "),m=c(f[f.length-1].trim());if(m&&(o.add(m),p&&i.add(m)),f.length>1){let h=c(f[0].trim());h&&i.add(h)}}return{ok:!0,changedFiles:Array.from(o),deletedFiles:Array.from(i)}}catch(n){return{ok:!1,error:`Failed to read git worktree status: ${n instanceof Error?n.message:String(n)}`}}}resolveInitialProjectPath(e){return e}evaluateIndexStatus(){let e=require("fs"),n=require("path");try{let{FileChunkMappingStore:r}=(Wa(),ke(GS)),o=new r(this.projectPath).all();if(!o||o.length===0)return{resetAll:!1,reindexAbs:[]};let i=/^\.pando-index-chunk-(\d+)\.db$/,a=e.readdirSync(ot(this.projectPath)),c=new Map;for(let m of a){let h=i.exec(m);if(!h)continue;let g=Number(h[1]);c.set(g,n.join(ot(this.projectPath),m))}if(c.size===0)return X("evaluateIndexStatus missing chunk databases",{mappingCount:o.length}),{resetAll:!0,reindexAbs:[]};let{default:l}=(an(),ke(ps)),u=new Map,d=new Set,p=0;for(let[m,h]of c){let g;try{Bn(`[IndexStatus] open chunk db :: ${h}`),g=new l(h);let y=g.prepare("SELECT COUNT(*) AS c FROM files").get();p+=Number(y?.c||0);let b=g.prepare("SELECT df.path AS file_path, f.status FROM files f JOIN dict_files df ON df.id = f.file_id").all();if(b&&b.length){let S=u.get(m);S||(S=new Set,u.set(m,S));for(let x of b){let w=String(x.file_path);d.add(w),(!x.status||String(x.status).toLowerCase()!=="completed")&&S.add(w)}S.size===0&&u.delete(m)}}catch(y){return Bn("[IndexStatus] failed to inspect chunk",h,y?.message||y),{resetAll:!0,reindexAbs:[]}}finally{if(g)try{g.close()}catch{}}}for(let m of o)if(!d.has(m.file_path)){let h=u.get(m.chunk_id);h||(h=new Set,u.set(m.chunk_id,h)),h.add(m.file_path)}let f=[];for(let[m,h]of u){let g=c.get(m);if(!g)return X("evaluateIndexStatus missing db path for chunk",{chunkId:m}),{resetAll:!0,reindexAbs:[]};let y=Array.from(h);if(y.length){try{this.purgeFilesFromChunk(g,y)}catch(b){return Bn("[IndexStatus] failed to purge chunk before reindex",g,b?.message||b),{resetAll:!0,reindexAbs:[]}}for(let b of y)f.push(n.join(this.projectPath,b))}}return p===0&&f.length===0?(X("evaluateIndexStatus empty index with no remediation",{mappingCount:o.length}),{resetAll:!0,reindexAbs:[]}):{resetAll:!1,reindexAbs:f}}catch(r){return Bn("[IndexStatus] unable to evaluate status table",r?.message||r),{resetAll:!0,reindexAbs:[]}}}purgeFilesFromChunk(e,n){if(!n||n.length===0)return;let{default:r}=(an(),ke(ps)),s=new r(e);try{s.transaction(a=>{let c=u=>{for(let d=0;d<a.length;d+=200){let p=a.slice(d,d+200);p.length!==0&&u(p)}},l=(u,d="file_id")=>{c(p=>{let f=p.map(h=>s.prepare("SELECT id FROM dict_files WHERE path = ?").get(h)).map(h=>h?.id).filter(h=>typeof h=="number");if(!f.length)return;let m=f.map(()=>"?").join(",");s.prepare(`DELETE FROM ${u} WHERE ${d} IN (${m})`).run(...f)})};l("nodes"),l("exports"),l("files"),l("file_imports"),l("file_import_bindings"),c(u=>{let d=u.map(f=>s.prepare("SELECT id FROM dict_files WHERE path = ?").get(f)).map(f=>f?.id).filter(f=>typeof f=="number");if(!d.length)return;let p=d.map(()=>"?").join(",");s.prepare(`DELETE FROM file_deps WHERE src_file_id IN (${p})`).run(...d)})})(n),X("purgeFilesFromChunk removed stale entries",{dbPath:e,count:n.length})}catch(o){throw Bn("[IndexStatus] failed to purge chunk entries",e,o?.message||o),o}finally{try{s.close()}catch{}}}prepareIndexingRun(){let e=require("fs");if(!(()=>{try{return e.existsSync(this.projectPath)}catch{return!1}})()){X("prepareIndexingRun skipped; project root missing",{projectPath:this.projectPath}),this.pendingStatusReindex=[];return}let r=ot(this.projectPath);X("prepareIndexingRun start",{dotPando:r});try{e.mkdirSync(r,{recursive:!0})}catch{}this.pendingStatusReindex=[]}async startIndexing(){let e=this.operationResetController.signal;X("[DEBUG] startIndexing ENTRY",{projectPath:this.projectPath,indexingInProgress:this.indexingInProgress}),X("\u{1F680} Starting AST indexing...");try{if(ut(e,"Indexing cancelled before start"),this.indexingInProgress){this.pendingFullReindex=!0,X("startIndexing skipped (already running)",{projectPath:this.projectPath}),X("[DEBUG] startIndexing EXIT (already in progress)");return}this.indexingInProgress=!0;let n=Math.random().toString(36).slice(2,8);X("startIndexing begin",{projectPath:this.projectPath,runId:n}),X("[DEBUG] startIndexing about to call initializeASTStorage"),await this.initializeASTStorage(e),ut(e,"Indexing cancelled"),this.scheduleInitialSnapshotAfterIndex("post-root-check",e),ut(e,"Indexing cancelled"),X("startIndexing end",{projectPath:this.projectPath,runId:n}),X("[DEBUG] startIndexing completed successfully"),X("\u2705 AST indexing completed successfully")}catch(n){if(hi(n))X("startIndexing aborted",{projectPath:this.projectPath,error:n instanceof Error?n.message:String(n)});else{let r=n instanceof Error?n.message:String(n);X("[DEBUG] startIndexing caught error",{error:r}),Bn("\u274C Failed to initialize AST storage:",n)}}finally{if(this.indexingInProgress=!1,X("INDEXING DONE",{projectPath:this.projectPath}),e.aborted&&(this.pendingFullReindex=!1),this.pendingFullReindex){this.pendingFullReindex=!1,X("queued full reindex starting",{projectPath:this.projectPath}),await this.startIndexing();return}this.queuedBatch&&!e.aborted&&this.ensureBatchRunner()}}readSnapshotCount(){try{let{openSnapshotsDb:e}=(Uo(),ke(Yi)),n=e(this.projectPath,{readonly:!0});try{return Number(n.prepare("SELECT COUNT(*) AS c FROM snapshots").get()?.c??0)}finally{try{n.close()}catch{}}}catch(e){return Bn("\u26A0\uFE0F Failed to inspect snapshot count",e?.message||e),null}}scheduleInitialSnapshotAfterIndex(e,n,r){let s=require("fs"),o=require("path");if(!s.existsSync(this.projectPath))return"unavailable";if(this.initialSnapshotTask)return X("initial snapshot already scheduled",{projectPath:this.projectPath,reason:e}),"inflight";let i=this.readSnapshotCount();if(i==null)return"unavailable";if(i>0)return"existing";let{SnapshotStatusTracker:a}=(Za(),ke(Ka)),c=a.getInstance(this.projectPath),l=ot(this.projectPath),u=o.join(l,"history"),d=Gn(this.projectPath,0);return c.start(0,0),this.initialSnapshotTask=(async()=>{let p=Date.now();try{ut(n,"Initial snapshot cancelled"),X("\u{1F504} Starting initial snapshot after indexing...",{projectPath:this.projectPath,reason:e}),X(`[SnapshotDiag] ${e==="full-index"?"fullIndex":"postIndex"}.preSnapshot`,{projectPath:this.projectPath,pandoDataDir:l,historyDir:u,historyExists:s.existsSync(u),dbPath:d});let f=typeof this.snapshotter.snapshotCompleteBaseline=="function"?await this.snapshotter.snapshotCompleteBaseline("ast: initial snapshot (complete pre-agent baseline)",n):await this.snapshotter.snapshotAll("ast: initial snapshot (serial)",n),m=Date.now()-p;X("\u2705 baseline snapshot complete",{elapsedMs:m}),X(`[SnapshotDiag] ${e==="full-index"?"fullIndex":"postIndex"}.postSnapshot`,{snapshotId:f?.snapshotId,parent:f?.parent,historyExists:s.existsSync(u)}),X("\u2705 Initial snapshot created and recorded",{snapshotId:f?.snapshotId})}catch(f){hi(f)?X("initial snapshot aborted",{projectPath:this.projectPath,reason:e,error:f instanceof Error?f.message:String(f)}):(Bn("\u26A0\uFE0F initial snapshot failed",f?.message,f?.stack),X("[SnapshotDiag] initialSnapshot.error",{projectPath:this.projectPath,reason:e,message:f?.message||String(f),stack:f?.stack,historyExists:s.existsSync(u),dbPath:d}))}finally{try{c.complete()}catch{}this.initialSnapshotTask=null}})(),this.initialSnapshotTask.catch(()=>{}),"scheduled"}async waitForInitialSnapshot(){let e=this.initialSnapshotTask;e&&await e}hasPendingInitialSnapshot(){return!!this.initialSnapshotTask}async processQueuedBatch(e,n){let r=Date.now(),s=`${ot(this.projectPath)}/`,o=b=>{let S=0,x=0,w=[],R=[];for(let E of b){if(E.startsWith(s)){S++,w.length<10&&w.push(E);continue}this.isPathExcludedForIndex(E)&&(x++,R.length<10&&R.push(E))}return{internal:S,excluded:x,internalSample:w,excludedSample:R}},i=o(e.created),a=o(e.modified),c=o(e.deleted);qn("code-engine.batch.start",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,createdSample:e.created.slice(0,20),modifiedSample:e.modified.slice(0,20),deletedSample:e.deleted.slice(0,20),internalCounts:{created:i.internal,modified:a.internal,deleted:c.internal},excludedCounts:{created:i.excluded,modified:a.excluded,deleted:c.excluded},internalSample:[...i.internalSample,...a.internalSample,...c.internalSample].slice(0,20),excludedSample:[...i.excludedSample,...a.excludedSample,...c.excludedSample].slice(0,20),queuedAfterTake:this.describeQueuedBatch()}),X("batch-change event",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length}),this.batchInProgress=!0,this.batchStartMs=Date.now(),this.batchPhase="start",this.batchPhaseStartMs=Date.now(),this.batchWatchdogTimer||(this.batchWatchdogTimer=setInterval(()=>{let b=this.batchStartMs?Date.now()-this.batchStartMs:null,S=this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null;X("[BatchQueue] watchdog",{batchInProgress:this.batchInProgress,batchStartMs:this.batchStartMs??null,elapsedMs:b,phase:this.batchPhase??null,phaseElapsedMs:S,queuedBatch:this.describeQueuedBatch()})},1e4));let l=()=>{let b=process.memoryUsage(),S=x=>Math.round(x/(1024*1024));return`rss=${S(b.rss)}MB heapUsed=${S(b.heapUsed)}MB heapTotal=${S(b.heapTotal)}MB ext=${S(b.external)}MB`};this.batchPhase="filtering",this.batchPhaseStartMs=Date.now(),X("[BatchQueue] filtering start",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});let u=(b,S)=>{let x=Date.now(),w=b.length,R=0,E=0,_=[];for(let F of b){if(F.startsWith(s)){R++;continue}if(this.isPathExcludedForIndex(F)){E++;continue}_.push(F)}let v=Date.now()-x;return X("[BatchQueue] filterList done",{label:S,input:w,output:_.length,internalSkipped:R,excludedSkipped:E,elapsedMs:v,sample:_.slice(0,10)}),_};e={created:u(e.created,"created"),modified:u(e.modified,"modified"),deleted:u(e.deleted,"deleted"),source:e.source},qn("code-engine.batch.afterFilter",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,createdSample:e.created.slice(0,20),modifiedSample:e.modified.slice(0,20),deletedSample:e.deleted.slice(0,20)});let d=e.created.length+e.modified.length+e.deleted.length;if(d===0){qn("code-engine.batch.filteredToZero",{projectRoot:this.projectPath,elapsedMs:Date.now()-r}),this.finishBatch("no-work-after-filtering");return}this.scheduleLspWorkspaceSync(e,"watcher-batch");let p=this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null;X("[BatchQueue] filtering complete",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:p});let f=this.shouldEscalateBatchToFullReindex(d);if(f.should){qn("code-engine.batch.fullReindexFallback",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,totalFiles:d,reason:f.reason,knownFiles:f.knownFiles??null}),X("[BatchQueue] large batch fallback",{totalFiles:d,reason:f.reason,knownFiles:f.knownFiles??null}),this.finishBatch("large-batch-full-reindex",{totalFiles:d,reason:f.reason,knownFiles:f.knownFiles??null}),await this.startIndexing();return}try{let b=S=>S.length<=10?S:[...S.slice(0,10),`... +${S.length-10} more`];X("batch-change filtered",{internalDbPrefix:s,created:b(e.created),modified:b(e.modified),deleted:b(e.deleted)}),qn("code-engine.batch.filtered",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,createdSample:e.created.slice(0,20),modifiedSample:e.modified.slice(0,20),deletedSample:e.deleted.slice(0,20)})}catch{}let m=Date.now();X("\u{1F680} Processing batch",{files:d,mem:l()});let h=b=>b.length<=20?b:[...b.slice(0,20),`... +${b.length-20} more`];e.created.length&&X("batch created",{files:h(e.created)}),e.modified.length&&X("batch modified",{files:h(e.modified)}),e.deleted.length&&X("batch deleted",{files:h(e.deleted)});for(let b of e.deleted){let S=this.project.getSourceFile(b);S&&this.project.removeSourceFile(S)}let g=[...e.created,...e.modified];g.length&&X("batch reindex targets",{files:h(g)});let y=!1;try{ut(n,"Batch indexing cancelled"),this.batchPhase="applyExplicitChanges",this.batchPhaseStartMs=Date.now(),X("[BatchQueue] applyExplicitChanges start",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});let b=this.createTransientIndexer(),S=Math.max(3e4,Number(process.env.PANDO_PROCESS_CHANGES_TIMEOUT_MS||18e4)),x=e.created.map(N=>Ps(N)),w=e.modified.map(N=>Ps(N)),R=e.deleted.map(N=>Ps(N));qn("code-engine.batch.applyExplicitChanges.invoke",{projectRoot:this.projectPath,created:x.length,modified:w.length,deleted:R.length,timeoutMs:S});let E,_=()=>{try{b.cancelIndexing("Batch indexing cancelled")}catch{}},v=n.aborted?(()=>{}):(n.addEventListener("abort",_,{once:!0}),()=>{try{n.removeEventListener("abort",_)}catch{}}),F=new Promise((N,O)=>{E=setTimeout(()=>{try{b.cancelIndexing(`applyExplicitChanges timeout after ${S}ms`)}catch{}qn("code-engine.batch.applyExplicitChanges.timeout",{projectRoot:this.projectPath,created:x.length,modified:w.length,deleted:R.length,timeoutMs:S}),O(new Error(`applyExplicitChanges timed out after ${S}ms`))},S),E.unref?.()}),D,I=ux(n,"Batch indexing cancelled",()=>{try{b.cancelIndexing("Batch indexing cancelled")}catch{}});try{D=await Promise.race([b.applyExplicitChanges({created:x.length?x:void 0,modified:w.length?w:void 0,deleted:R.length?R:void 0},{resetModifiedToLight:e.source!=="post-write-sync"}),I.promise,F])}finally{I.cleanup(),v(),E&&clearTimeout(E),this.disposeTransientIndexer(b,"batch applyExplicitChanges complete")}ut(n,"Batch indexing cancelled");let P=this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null;X("[BatchQueue] applyExplicitChanges done",{elapsedMs:P,indexed:D.indexed,purged:D.purged,needsFullReindex:D.needsFullReindex??!1}),qn("code-engine.batch.applyExplicitChanges.complete",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null,indexed:D.indexed,purged:D.purged,needsFullReindex:D.needsFullReindex??!1}),y=D.needsFullReindex===!0;let M=(Date.now()-m)/1e3;X("\u2705 Explicit batch applied",{durationSeconds:Number(M.toFixed(1)),mem:l()})}catch(b){if(hi(b)){this.finishBatch("batch-cancelled",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});return}qn("code-engine.batch.applyExplicitChanges.failed",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null,error:b?.message||String(b)});let S=this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null;X("[BatchQueue] applyExplicitChanges failed",{elapsedMs:S,error:b?.message||String(b)}),Bn("\u274C Failed to process queued batch:",b)}if(this.finishBatch(y?"apply-explicit-needs-full-reindex":"batch-complete",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length}),!y)try{g.length>0&&(this.batchPhase="refreshFiles",this.batchPhaseStartMs=Date.now(),await this.refreshFilesFromDisk(g,n),qn("code-engine.batch.refreshFiles.complete",{projectRoot:this.projectPath,files:g.length,elapsedMs:this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null,batchElapsedMs:Date.now()-r}),X("[Batch] Post-index refresh done",{files:g.length}))}catch(b){if(hi(b)){qn("code-engine.batch.refreshFiles.aborted",{projectRoot:this.projectPath,files:g.length,elapsedMs:this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null,batchElapsedMs:Date.now()-r}),X("[Batch] Post-index refresh aborted",{files:g.length});return}qn("code-engine.batch.refreshFiles.failed",{projectRoot:this.projectPath,error:b?.message||String(b),batchElapsedMs:Date.now()-r}),Bn("[Batch] Post-index refresh failed",b?.message||b)}qn("code-engine.batch.complete",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:Date.now()-r,fullReindexTriggered:y}),y&&(X("\u{1F504} Critical index files deleted, triggering full reindex..."),await this.startIndexing())}isIndexingInProgress(){return this.indexingInProgress}async initializeASTStorage(e){X("\u{1F504} Initializing AST storage (single-pass, incremental)..."),X("initializeASTStorage begin",{projectPath:this.projectPath}),X("initializeASTStorage start",{excludes:this.indexExcludeDirs});let n=require("fs"),r=require("path");if(ut(e,"Indexing cancelled"),!(()=>{try{return n.existsSync(this.projectPath)}catch{return!1}})()){X("initializeASTStorage skipped; project root missing",{projectPath:this.projectPath});return}this.prepareIndexingRun();let o=this.createTransientIndexer();try{let i=o.checkAndCleanupIfNeeded();X("initializeASTStorage integrity",{projectPath:this.projectPath,needsReindex:i});let a=Gn(this.projectPath,0),c=ot(this.projectPath),l=r.join(c,"history"),u=!i&&n.existsSync(a)&&n.statSync(a).size>0,d=null;X("initializeASTStorage DB status",{dbPath:a,dbExists:u}),X("initializeASTStorage dbStatus",{projectPath:this.projectPath,exists:u});try{let k={projectPath:this.projectPath,dbPath:a,pandoDataDir:c,historyDir:l,dbExists:u,needsReindex:i,historyExists:n.existsSync(l)};try{let{openSnapshotsDb:C}=(Uo(),ke(Yi)),T=C(this.projectPath,{readonly:!0});try{let j=Number(T.prepare("SELECT COUNT(*) AS c FROM snapshots").get()?.c??-1);d=j>=0?j:null,k.snapshots=j,k.snapshot_members=Number(T.prepare("SELECT COUNT(*) AS c FROM snapshot_members").get()?.c??-1),k.snapshot_meta=Number(T.prepare("SELECT COUNT(*) AS c FROM snapshot_meta").get()?.c??-1)}finally{try{T.close()}catch{}}}catch(C){k.snapshotCountReadError=C?.message||String(C)}X("[SnapshotDiag] initializeASTStorage.entry",k)}catch{}let p=u&&d===0;p&&X("[SnapshotDiag] missingInitialSnapshot forcing full index path",{projectPath:this.projectPath,dbPath:a,snapshots:d});let f=this.pendingStatusReindex.slice();if(this.pendingStatusReindex=[],!u||p){if(this.indexingInProgress&&this.pendingFullReindex){X("initializeASTStorage fullIndex skipped (reindex queued)",{projectPath:this.projectPath});return}X(`\u{1F4C0} ${i?"Index integrity repair":p?"Initial snapshot missing":"No existing DB detected"}. Running full index-all...`),X("initializeASTStorage fullIndex start",{projectPath:this.projectPath});let C=Date.now(),T=ux(e,"Indexing cancelled",()=>{try{o.cancelIndexing("Indexing cancelled")}catch{}}),j;try{j=await Promise.race([o.indexAll(void 0,{captureContents:!0}),T.promise])}finally{T.cleanup()}ut(e,"Indexing cancelled");let L=Date.now()-C;X("\u2705 indexAll complete",{elapsedMs:L}),X("initializeASTStorage fullIndex done",{projectPath:this.projectPath});let $=this.scheduleInitialSnapshotAfterIndex("full-index",e,Array.isArray(j?.captures)?j.captures:void 0);X("\u2705 Full indexing complete!",{dbPath:a,initialSnapshotState:$}),X("initializeASTStorage end",{projectPath:this.projectPath});return}X("\u{1F9EE} Existing DB found. Computing incremental changes...");try{let{default:k}=(an(),ke(ps)),C=new k(a,{readonly:!0}),T=Number(C.prepare("SELECT COUNT(*) AS c FROM snapshots").get()?.c??-1),j=Number(C.prepare("SELECT COUNT(*) AS c FROM snapshot_members").get()?.c??-1);C.close(),T===0&&X("[SnapshotDiag] incrementalPathWithNoSnapshots",{projectPath:this.projectPath,dbPath:a,snapshots:T,snapshot_members:j,historyExists:n.existsSync(l)})}catch(k){Bn("[SnapshotDiag] incrementalSnapshotCheck.error",k?.message||k)}X("initializeASTStorage incremental start",{projectPath:this.projectPath}),X("BUILD_STAMP incremental-logs-v1");let m=k=>r.relative(this.projectPath,k).replace(/\\/g,"/");X("workerScan:start",{projectPath:this.projectPath});let h=Date.now(),g=await this.withTransientIndexer(k=>k.scanFiles());X("workerScan:done",{count:g.length,elapsedMs:Date.now()-h,projectPath:this.projectPath});let y=new Set,b=new Map;for(let k of g){let C=k.relPath||m(k.absPath);!C||C.startsWith("..")||(y.add(C),b.set(C,{mtime:Math.floor(k.mtime),size:k.size}))}X("incremental diskMeta built",{projectPath:this.projectPath,count:b.size,source:"workerScan"});let{FileChunkMappingStore:S}=(Wa(),ke(GS)),x=new S(this.projectPath),w=[],R=process.env.REINDEX_ON_MTIME_DECREASE==="1",E=f.slice(),_={missingMapping:0,sizeChanged:0,mtimeIncreased:0,mtimeDecreased:0},v=[],F=Math.max(0,Math.min(100,Number(process.env.PANDO_INDEX_DIAG_LIMIT||"25"))),D=(k,C,T,j)=>{v.length>=F||v.push({rel:k,reason:C,disk:{mtime:T?.mtime??0,size:T?.size??0},chunk:j?{last_modified:j.last_modified??0,file_size:j.file_size??0}:void 0})};X("incremental map.all start",{projectPath:this.projectPath});let I=Date.now(),P=x.all(),M=P.length,N=new Map;for(let k of P)N.set(k.file_path,k);X("incremental map.all done",{projectPath:this.projectPath,elapsedMs:Date.now()-I,count:M}),X("incremental map lookup loop start",{projectPath:this.projectPath,count:b.size});let O=Date.now();for(let[k,C]of b){let T=N.get(k);if(!T){_.missingMapping++,D(k,"missingMapping",C),w.push(r.join(this.projectPath,k));continue}let j=(C.mtime||0)>(T.last_modified||0),L=(C.mtime||0)<(T.last_modified||0),$=(C.size||0)!==(T.file_size||0);$&&_.sizeChanged++,j&&_.mtimeIncreased++,L&&_.mtimeDecreased++,($||j||R&&L)&&(D(k,$?"sizeChanged":j?"mtimeIncreased":"mtimeDecreased",C,T),w.push(r.join(this.projectPath,k)))}if(X("incremental map lookup loop done",{projectPath:this.projectPath,elapsedMs:Date.now()-O,staleOrNew:w.length}),E.length){let k=new Set(w.map(T=>Ps(T))),C=0;for(let T of E){let j=Ps(T);if(!k.has(j)){let L=m(T),$=b.get(L)||{mtime:0,size:0};D(L,"status",$),w.push(T),k.add(j),C++}}C>0&&X("initializeASTStorage merged status-driven targets",{added:C,total:w.length})}let A=[];X("incremental deleted scan start",{projectPath:this.projectPath});for(let k of N.keys())y.has(k)||A.push(k);if(X("incremental deleted scan done",{projectPath:this.projectPath,deleted:A.length}),X("[IndexerDiag] re-index evaluation",{diskCount:b.size,mappingCount:M,staleOrNew:w.length,pendingStatus:E.length,counts:_,sample:v}),A.length>0&&X("[IndexerDiag] deleted candidates",{count:A.length,sample:A.slice(0,Math.max(0,Math.min(F,25)))}),X("\u{1F4CA} Incremental indexing",{staleOrNew:w.length,deleted:A.length}),A.length>0)for(let k of A)x.delete(k);w.length>0?(X("incremental indexFiles start",{count:w.length}),await this.withTransientIndexer(k=>k.indexFiles(w)),X("incremental indexFiles done",{count:w.length}),X("\u2705 Incremental indexing complete.")):(X("incremental no-op",{deleted:A.length}),X("\u2705 Everything up to date. No indexing needed."))}finally{this.disposeTransientIndexer(o,"initializeASTStorage complete")}}async forceSave(){await this.project.save()}getStats(){return{projectPath:this.projectPath,operationCount:this.operationCount,sourceFiles:this.project.getSourceFiles().length,projectStats:lo.getProjectStats(this.project),useASTStorage:!1}}refresh(){this.project.getSourceFiles().forEach(e=>e.refreshFromFileSystemSync())}async execute(e,n){this.operationCount++;let r=Date.now(),s=c=>{let l=Math.max(0,Date.now()-r),u=c??{success:!1},{success:d=!1,projectRoot:p,...f}=u;return{projectRoot:this.projectPath,success:d,elapsedMs:l,...f}},{signal:o,cleanup:i}=kC(n?.signal,this.operationResetController.signal);n?.clearTypeCache&&(EN(),ke(kN)).TypeInference.clearCache();let a=this.project;try{if(ut(o,"Operation cancelled before execution started"),!this.lspHost)try{let{CodeEngineFactory:u}=(Ls(),ke(rl)),d=u.getEngineOptions(this.projectPath);(d?.lspHost||d?.languageSupport)&&this.setRuntimeOptions(d)}catch{}let c=new xm(a,this.projectPath);if(this.lspHost&&c.setLspHost(this.lspHost),!Array.isArray(e)){let u=await this.executeSingle(e,c,o);return u.success&&u.changes?.count&&u.changes.count>0&&await this.project.save(),u}let l=[];for(let u of e){let d=await this.executeSingle(u,c,o);if(!d.success){if(n?.continueOnError){l.push(d);continue}throw new Error(`Operation failed: ${d.error}`)}l.push(d)}if(!n?.dryRun&&l.some(u=>u.success&&u.changes?.count&&u.changes.count>0)){let u=0;for(let d of l)d.success&&d.changes?.count&&(u+=d.changes.count);u>0&&await this.project.save()}return l}catch(c){let l=hi(c),u=l?c?.message||"Operation cancelled":c.message;return Array.isArray(e)?[s({success:!1,error:u,...l?{error_code:"cancelled"}:{}})]:s({success:!1,error:u,...l?{error_code:"cancelled"}:{}})}finally{i()}}async executeWithContext(e,n,r){if(!Array.isArray(e))return this.executeSingle(e,n,r?.signal);let s=[];for(let o of e){let i=await this.executeSingle(o,n,r?.signal);if(!i.success)throw new Error(`Operation failed: ${i.error}`);s.push(i)}return s}async executeSingle(e,n,r){ut(r);let s=e.op,o=s==="add-code"?"insert":s==="replace-body"?"replace":s,i=Pg(s),a=new Set(["rename","delete","insert","add-code","replace","replace-body","change-signature","filter-map-reduce","shell-command","move-clojure-namespace","rename-clojure-namespace","restore-snapshot","restore-files","add-exclude-dir","remove-exclude-dir"]),c=new Set(["get-project-root","read_this_first","list-snapshots","diff-snapshots","get-snapshot-trailers","get-db-schema","query-db"]),l=new Set(["restore-snapshot","restore-files","shell-command"]),u=new Set(["change-signature","restore-snapshot","restore-files","shell-command"]),d=typeof o=="string"&&a.has(o)||typeof s=="string"&&a.has(s),p=typeof o=="string"&&l.has(o),f=typeof o=="string"&&u.has(o),m=typeof o=="string"&&c.has(o);if(d&&this.pendingShellCommandSnapshotFailure){let A=this.pendingShellCommandSnapshotFailure,k=!1;for(let C=0;C<3&&!k;C++)try{(await this.handleSnapshotWorktree({message:`recover-shell-snapshot: ${A.reason}`},r))?.success&&(k=!0)}catch{}if(k)this.pendingShellCommandSnapshotFailure=void 0;else return{projectRoot:this.projectPath,success:!1,error:"A previous shell-command completed but its snapshot could not be captured after retries; the next modifying operation is blocked to avoid an un-snapshotted state.",details:{reason:"pending_shell_command_snapshot",failedCommand:A.command,failedReason:A.reason,snapshotError:A.error,failedAt:A.failedAt}}}let h=Date.now(),g=A=>{let k=Math.max(0,Date.now()-h),C=A??{success:!1},{success:T=!1,projectRoot:j,...L}=C;return{projectRoot:this.projectPath,success:T,elapsedMs:k,...L}};try{await this.xxHashReady}catch(A){return g({success:!1,error:`xxHash initialization failed: ${A?.message||String(A)}`})}let y=dN(e);if(!y.valid)return g({success:!1,error:y.error,error_code:"validation_failed",details:{operation:o??null,issues:y.issues}});if(i==="agent-sandbox"&&o!=="shell-command"&&!Pi())return g({success:!1,error:SN(typeof o=="string"?o:void 0),error_code:"agent_sandbox_required",details:{operation:o??null,requiredContext:"agent-sandbox",currentContext:"trusted-engine",env:Ys}});let b=o==="restore-snapshot";if(b&&(await this.supersedePendingProjectSyncForRestore(o),this.installRestoreFastPathMetadata(e,n)),!m)try{await this.awaitPendingProjectSync(o)}catch(A){return g({success:!1,error:`Project refresh failed after prior write: ${A?.message||String(A)}`,details:{reason:"project_refresh_failed",operation:o??null,pendingProjectSyncReason:this.pendingProjectSyncReason??null}})}let S=uo.getInstance(this.projectPath),x=(()=>{try{return(Od(),ke(gh)).FTSStatusTracker.getInstance(this.projectPath)}catch{return null}})(),w=(()=>{try{return(Za(),ke(Ka)).SnapshotStatusTracker.getInstance(this.projectPath)}catch{return null}})(),R=null,E=null,_=!1,v=!0,F="Ready for write operations",D=null;try{let A=this.getIndexingStore();R=A?.getIndexingSession?.()??null,E=Ga(this.projectPath,0);let k=Math.max(0,Math.floor(Number(E?.totalFiles)||0)),C=Math.max(0,Math.floor(Number(E?.filesProcessed)||0)),T=kd({projectRoot:this.projectPath,store:A,sessionData:R,pendingCount:Math.max(0,Number(A.getPendingStats?.()?.count||0)),overviewTotal:k,overviewProcessed:C,indexingIsIndexing:S.isIndexing(),snapshotIsSnapshotting:!!w?.isSnapshotting,snapshotFilesChanged:w?.status?.filesChanged,snapshotFilesDeleted:w?.status?.filesDeleted,logScope:"CodeEngine"});R=T.sessionData,_=T.indexingActive,v=T.writesPermitted,F=T.writeBlockMessage,D=T.writeBlockReason}catch{R=null}let I=!!(x&&x.isBuilding),P=!!(w&&w.isSnapshotting);if(b&&!v&&!P&&!_&&(v=!0,D="ready",F="Restore-snapshot allowed as a recovery operation while metadata indexing is idle."),d&&!v&&t.WRITE_GATE_WAIT_MS>0){let A=()=>{try{let C=this.getIndexingStore(),T=C?.getIndexingSession?.()??null,j=Ga(this.projectPath,0),L=kd({projectRoot:this.projectPath,store:C,sessionData:T,pendingCount:Math.max(0,Number(C.getPendingStats?.()?.count||0)),overviewTotal:Math.max(0,Math.floor(Number(j?.totalFiles)||0)),overviewProcessed:Math.max(0,Math.floor(Number(j?.filesProcessed)||0)),indexingIsIndexing:S.isIndexing(),snapshotIsSnapshotting:!!w?.isSnapshotting,snapshotFilesChanged:w?.status?.filesChanged,snapshotFilesDeleted:w?.status?.filesDeleted,logScope:"CodeEngine"});R=L.sessionData,_=L.indexingActive,v=L.writesPermitted,F=L.writeBlockMessage,D=L.writeBlockReason}catch{}},k=Date.now()+t.WRITE_GATE_WAIT_MS;for(;!v&&Date.now()<k;)await new Promise(C=>setTimeout(C,200)),ut(r,`${String(o||"operation")} cancelled while waiting for indexing to settle`),A(),b&&!v&&!(w&&w.isSnapshotting)&&!_&&(v=!0,D="ready")}if(d&&!v){let A=Ga(this.projectPath,0),k=this.computeIndexingEta()??(A?.estimatedSecondsRemaining!=null?{seconds:Math.max(1,Math.ceil(A.estimatedSecondsRemaining)),basis:"files"}:null),C={reason:D||"background_work_in_progress",operation:o??null},T=[`Operation '${String(o||"unknown")}' is temporarily blocked. ${F}`];if(A&&A.totalFiles!=null&&A.filesProcessed!=null){let L=Number(A.filesProcessed),$=Number(A.totalFiles),z=$>0?$:0,U=z>0?Math.round(L/z*100):void 0,G=z>0?Math.max(0,z-L):void 0;C.indexing={isIndexing:!0,filesIndexed:A.filesIndexed??void 0,filesSkipped:A.filesSkipped??void 0,filesFailed:A.filesFailed??void 0,filesProcessed:L,totalFiles:z,filesRemaining:G,percentComplete:U,estSecondsRemaining:A.estimatedSecondsRemaining??(k?k.seconds:void 0),statusMessage:A.message??void 0},T.push(`Progress: ${L}/${z} files${U!=null?` (${U}%)`:""}.`)}else if(R&&R.total_files_estimate!=null&&R.files_processed!=null){let L=Math.max(0,Math.floor(Number(R.files_processed)||0)),$=Math.max(0,Math.floor(Number(R.total_files_estimate)||0)),z=$>0?Math.round(L/$*100):void 0,U=$>0?Math.max(0,$-L):void 0;C.indexing={isIndexing:!0,filesProcessed:L,totalFiles:$,filesRemaining:U,percentComplete:z,statusMessage:R.run_state?`run_state=${R.run_state}`:void 0},T.push(`Progress: ${L}/${$} files${z!=null?` (${z}%)`:""}.`)}k?(T.push(`Estimated retry window: ~${k.seconds}s.`),C.retryAfterSeconds=k.seconds,C.retryAfterBasis=k.basis):T.push("Retry shortly."),C.message=T.join(" "),C.indexing&&k?(C.indexing.retryAfterSeconds=k.seconds,C.indexing.retryAfterBasis=k.basis):!C.indexing&&k&&(C.indexing={isIndexing:_,retryAfterSeconds:k.seconds,retryAfterBasis:k.basis}),I&&(C.fts={state:x?.status?.state,snapshotId:x?.status?.snapshotId,blocking:!1}),P&&(C.snapshot={state:"snapshotting"});let j=C.message||"BUSY_RETRY_LATER";return g({success:!1,error:j,hints:["Wait a few seconds and retry the same operation. The indexer is still processing files."],details:C})}if(this.refreshingInProgress&&!m){let A=this.refreshingFiles.length,k=Math.max(1,Math.ceil(A/50));return X("[OperationGate] blocked by refresh",{op:o??null,totalFiles:A,etaSeconds:k,sampleFiles:this.refreshingFiles.slice(0,10)}),g({success:!1,error:`Engine is reconciling in-memory state with disk changes. Refreshing ${A} files, rough ETA ~${k}s. Retry in ~${k} seconds.`,hints:[`Wait ~${k} seconds and retry the same operation.`],details:{reason:"refreshing_in_progress",operation:o??null,message:`Engine is reconciling in-memory state with disk changes. Refreshing ${A} files, progress 0/${A}, rough ETA ~${k}s.`,retryAfterSeconds:k,refresh:{filesProcessed:0,totalFiles:A,estSecondsRemaining:k,sampleFiles:this.refreshingFiles.slice(0,10)}}})}if(d){if(this.modifyingOpActive){X("[OperationGate] blocked by active modifying op",{op:o??null,activeOp:this.modifyingOpName||"unknown",pendingProjectSyncReason:this.pendingProjectSyncReason??null,batchInProgress:this.batchInProgress,batchPhase:this.batchPhase??null,batchPhaseAgeMs:this.batchPhaseStartMs?Date.now()-this.batchPhaseStartMs:null});let A={},k=[`Another modifying operation ('${this.modifyingOpName||"unknown"}') is in progress.`],C=this.computeIndexingEta(),T=S.getStatus?.(),j=null,L=null;try{let U=this.getIndexingStore();L=U?(()=>{let G=U.getThroughput();return{avg_files_per_sec:G.avg_files_per_sec??null,avg_bytes_per_sec:G.avg_bytes_per_sec??null}})():null,j=U?.getIndexerMeta("worker_concurrency_hint")??null}catch(U){try{W("CodeEngine","busyRetry indexing telemetry failed",{error:U?.message||U})}catch{}}!C&&T?.estimatedSecondsRemaining!=null&&(C={seconds:Math.max(1,Math.ceil(T.estimatedSecondsRemaining)),basis:"files"}),C?(k.push(`Estimated completion in ~${C.seconds}s (${C.basis}).`),A.retryAfterSeconds=C.seconds,A.retryAfterBasis=C.basis):k.push("Please retry shortly.");let $={};if(T&&(T.filesProcessed!=null&&($.filesProcessed=T.filesProcessed),T.totalFiles!=null&&($.totalFiles=T.totalFiles),T.estimatedSecondsRemaining!=null&&($.estSecondsRemaining=T.estimatedSecondsRemaining,A.retryAfterSeconds||(A.retryAfterSeconds=Math.max(1,Math.ceil(T.estimatedSecondsRemaining)),A.retryAfterBasis="files"))),C&&($.retryAfterSeconds=C.seconds,$.retryAfterBasis=C.basis),L&&(L.avg_files_per_sec!=null&&($.avgFilesPerSecond=L.avg_files_per_sec),L.avg_bytes_per_sec!=null&&($.avgBytesPerSecond=L.avg_bytes_per_sec)),j){let U=Number(j);$.workerConcurrencyHint=Number.isFinite(U)?U:j}if(Object.keys($).length>0&&(A.indexing=$),w&&w.isSnapshotting){let U=w.status;if(A.snapshot={state:U.state,startedAt:U.startedAt??void 0,filesChanged:U.filesChanged??void 0,filesDeleted:U.filesDeleted??void 0},!C&&U.startedAt){let G=Math.max(1,Math.floor((Date.now()-U.startedAt)/1e3));A.snapshot.elapsedSeconds=G}}A.message=k.join(" ");let z=A.message||"BUSY_RETRY_LATER";return g({success:!1,error:z,hints:["Wait a few seconds and retry the same operation."],details:A})}this.modifyingOpActive=!0,this.modifyingOpName=o,X("[OperationGate] acquired modifying op lock",{op:o??null,projectPath:this.projectPath})}let M=()=>{d&&(this.modifyingOpActive=!1,this.modifyingOpName=void 0)},N;try{let A=String(o||"").toLowerCase()==="delete"||!!e?.forceMayBreakSyntax;if(d&&!A&&!f){let k=await this.preflightExpectedHashCheck(e,n,o);if(!k.ok)return M(),g({success:!1,error:k.error});let C=this.extractTouchedFiles(e);C.length>0&&(N=await this.collectDiagnostics(n,C))}}catch{N=void 0}let O=A=>{let k=A??{success:!1};if(!d){let C=[],j=(()=>{let L=k?.indexing;if(L&&typeof L=="object")return L;let $=k?.data?.indexing;return $&&typeof $=="object"?$:null})()??Ga(this.projectPath,0);if(j.isIndexing){let L=Math.max(0,Math.floor(Number(j.filesProcessed)||0)),$=Math.max(0,Math.floor(Number(j.totalFiles)||0)),z=j.estimatedSecondsRemaining!=null?j.estimatedSecondsRemaining:this.computeIndexingEta()?.seconds??null;(z==null||!Number.isFinite(z))&&this.computeIndexingEta()?.seconds!=null&&(z=this.computeIndexingEta().seconds);let U=$>0?Math.round(L/$*100):void 0,G=[j.filesIndexed?`${j.filesIndexed} indexed`:null,j.filesSkipped?`${j.filesSkipped} skipped`:null,j.filesFailed?`${j.filesFailed} failed`:null].filter(Boolean).join(", ");C.push(`Indexing in progress: ${L||"?"} / ${$||"?"} files${U!=null?` (${U}%)`:""}${z!=null?`, est. ${z}s remaining`:""}${G?`; ${G}`:""}. Results may be incomplete.`)}x&&x.isBuilding&&C.push("FTS index building in background; text/FTS queries may be partial until ready."),w&&w.isSnapshotting&&C.push("Snapshotting in progress; results may lag until snapshot completes."),C.length&&(k.warnings=Array.isArray(k.warnings)?[...k.warnings,...C]:C)}return g(k)};try{let A=QI(e),{boundary:k}=A,{requireConfirmation:C,confirmed:T}=A,j=e.path||e.to||e.of||void 0;X("[OperationDispatch] begin",{op:o,rawOpName:s,isModifying:d,projectPath:this.projectPath,targetPath:j||null});let L=require("path"),$=require("fs"),z=j&&typeof j=="string"&&j.includes("#")?j.split("#")[0]:void 0,U=this.projectPath;if(z)U=L.isAbsolute(z)?z:L.join(this.projectPath,z);else if(e.scopeNode||e.scope){let q=e.scope,K=e.scopeNode?String(e.scopeNode):q?.node?.path||q?.files?.[0]||q?.dir||"";K.includes("#")&&(K=K.split("#")[0]);let ne=L.isAbsolute(K)?K:L.join(this.projectPath,K);try{$.existsSync(ne)&&$.statSync(ne).isDirectory()?U=L.join(ne,"__virtual__.ts"):U=ne}catch{U=ne}}let G=yc(U),J=new Set;e&&e.boundary==null&&!j&&!e.scopeNode&&!e.scope&&(k="workspace");try{$.existsSync(G)||(k="workspace")}catch{k="workspace"}if(k==="project")if(!j&&!e.scopeNode&&!e.scope){let q=v_(this.projectPath);if(q.length>0)for(let K of q)J.add(K);else J.add(G)}else J.add(G);else if(k==="reachable"){let q={maxDepth:e.reachabilityDepth,...e.reachabilityOptions||{}},K=YI(this.projectPath,G,q);for(let ne of K)J.add(ne)}let ee=new Rg(this.projectPath,{allowedTsconfigs:J,mode:k},n.ls.getForFile,async q=>{let K=String(q||"").replace(/\\/g,"/");if(!K)return!1;let ne=L.isAbsolute(K)?K:L.join(this.projectPath,K);try{if(!$.existsSync(ne)||!$.statSync(ne).isFile())return!1}catch{return!1}return(await this.withTransientIndexer(Re=>Re.indexFiles([ne],{emitMode:"full"}),"find-nodes full AST JIT")).processed>0});if(n.setQueryLayer(ee),String(o||"").toLowerCase()==="rename"&&k!=="project"&&C&&!T)try{if(j){let q=e.expectedHash?`${j}@${e.expectedHash}`:`${j}`,K=bs(q,this.project,this.projectPath);if(K){let ne=K.getSourceFile().getFilePath(),ce=hU(K);if(ce!=null){let Re=[],be=!!e.includeStrings,Ge=!!e.includeComments,Le=ee.findRenameLocations(ne,ce,be,Ge);Re=Array.from(new Set(Le.map(jt=>L.resolve(jt.fileName))));let rt=kg.build("rename",eN(q),this.projectPath,Re,{boundary:k,allowedTsconfigs:Array.from(J),referenceCount:Le.length,rename:{newName:e.newName,locations:Le,page:e.page}});return O({success:!1,error:"Cross-project rename requires explicit approval",crossProjectConfirmation:rt})}}}}catch{}let we=!!e?.dryRun,re=(()=>{try{let{openSnapshotsDb:q}=(Uo(),ke(Yi)),K=q(this.projectPath,{readonly:!0});try{return K.prepare("SELECT snapshot_id FROM snapshots ORDER BY timestamp DESC, rowid DESC LIMIT 1").get()?.snapshot_id}finally{try{K.close()}catch{}}}catch{return}})(),Ne=q=>q?!!(String(q.op||"").toLowerCase()==="delete"||q.forceMayBreakSyntax||q.forceInsertWillBreakSyntax===!0||q.forceReplaceWillBreakSyntax===!0||q.forceDeleteReferencesMayBreakSyntax===!0):!1,Z;switch(o){case"read_this_first":{let K=["Pando is an AST-aware code navigation and editing layer for large repos.","It keeps a light index of supported source files, uses that index to narrow candidate files, then parses exact AST details at query or edit time.","","Use Pando for source-code search, navigation, references, callers, exports, renames, inserts, replacements, and deletes.","Use shell/text tools for builds, tests, generated files, non-code files, and unsupported languages.",".clj-kondo is special: those files are intentionally excluded from semantic Clojure indexing to avoid indexing loops.","","Exposure tiers:","- Metadata tier: find-nodes without include, list-exports, analyze-imports, query-db, workspace-overview, and namespace graph tools return handles, hashes, counts, and structure without source text.","- Structure tier: add include.parents or include.self only with topN and maxChars when you need bounded syntax context.","- Source tier: add include.body only for a named node or a narrow scope.node query, always with maxChars.","- Raw file tier: unavailable to the agent. For historical code, restore the snapshot, inspect with Pando-native tools, then restore back.","","Edit workflow:","- First use find-nodes without include to get path/hash. Do not request include.self or include.body unless you need to inspect code before deciding the edit.","- Then use rename, replace, replace-body, insert, delete, change-signature, or filter-map-reduce. Re-run find-nodes after writes because hashes change.","","Anti-patterns and replacements:","- Need symbol location? Use find-nodes with no include.","- Need function body? Use find-nodes scoped to the file, predicate by node/name, include.body, and maxChars.","- Need statement inside function? Find the enclosing function first, then re-run find-nodes with scope.node.","- Need usages? Use find-references or find-callers.","- Need import/export shape? Use analyze-imports or list-exports.","- Need historical code? Restore the snapshot, use find-nodes and other Pando-native tools, then restore back.","","find-nodes recipes:",`- Symbol handle: scope:{files:["src/app.ts"]}, datalog query '[:find ?n :where [?n :node/name "foo"]]', no include.`,"- Bounded body: same query plus include:{body:true,topN:1,maxChars:2000}.","- Child statement: first find the function, then scope.node:{path,expectedHash} with predicates such as :node/kind, :node/text, :node/role, or :node/index-in-parent.","- Workspace candidate search: use prefilter.fts to narrow files before Datalog, then keep include omitted until source is required.","","Read next:","- workspace-overview: quick inventory of indexed files and symbols.","- find-nodes: search by language, scope, and Datalog. Omit include for edit targets; use include fields only as explicit exposure escalation.","- list-exports, find-references, and find-callers: follow symbols before changing them.","- Writers: rename, replace, replace-body, insert, delete, change-signature, filter-map-reduce, and shell-command.","","Unnamed nodes can and should still be edited with Pando.","Statements, returns, calls, arguments, branches, literals, and other unnamed syntax are normal AST nodes; find them by starting from a named entity or file, then narrowing by kind, text, role, parent, or child index.","","Examples:","- In one find-nodes call, search for a function by name within the workspace with no include to get the exact node path and hash.",'- To edit a statement inside a named function, find the function handle first, then call find-nodes again with scope.node set to { path, expectedHash } for that function. Use predicates such as :node/kind "ReturnStatement" or :node/text "oldValue", then pass the returned statement path and hash without @ to replace or insert; delete uses expectedHashes.',"- For scripts or top-level code, scope find-nodes to the file path instead of a named node, find the statement by kind/text/role/index, then edit that returned node with a writer.","- Insert code is literal: include the newline and indentation you want when inserting before or after a statement anchor."].join(`
894
- `);try{let ne=require("fs"),Re=require("path").resolve(__dirname,"..","..","mcp-pando-server","resources","messages.json");if(ne.existsSync(Re)){let Ge=JSON.parse(ne.readFileSync(Re,"utf8"))?.read_this_first;typeof Ge=="string"&&Ge.trim().length>0&&(K=Ge)}}catch{}Z={success:!0,help:{title:"read_this_first",body:K}};break}case"insert":{let{InsertCodeExecutor:q}=await Promise.resolve().then(()=>(hp(),TI)),K=s==="add-code"?{...e,op:"insert"}:e;Z=await q.execute(K,n,this.project);break}case"workspace-overview":Z=await Sh.execute(e,n,this.project);break;case"list-exports":Z=xh.execute(e,n,this.project);break;case"analyze-imports":Z=_h.execute(e,n,this.project);break;case"clojure-namespace-graph":Z=wh.execute(e,n,this.project);break;case"clojure-namespace-dependencies":Z=Fd.executeDependencies(e,n,this.project);break;case"clojure-namespace-dependents":Z=Fd.executeDependents(e,n,this.project);break;case"plan-clojure-namespace-move":Z=$d.executeMove(e,n,this.project);break;case"plan-clojure-namespace-rename":Z=$d.executeRename(e,n,this.project);break;case"move-clojure-namespace":Z=await jd.executeMove(e,n,this.project);break;case"rename-clojure-namespace":Z=await jd.executeRename(e,n,this.project);break;case"get-db-schema":Z=Ld.execute(e,n,this.project);break;case"query-db":Z=await vh.execute(e,n,this.project);break;case"delete":Z=await na.execute(e,n,this.project);break;case"find-references":Z=await cc.execute(e,n,this.project);break;case"find-callers":Z=await fp.execute(e,n,this.project);break;case"rename":Z=await sa.execute(e,n,this.project);break;case"filter-map-reduce":{let{FilterMapReduceExecutor:q}=await Promise.resolve().then(()=>(d_(),PI));Z=await q.execute(e,n,this.project);break}case"shell-command":Z=await this.handlePandoShellCommand(e,r);break;case"replace":{let q=s==="replace-body"?{...e,op:"replace",scope:"body"}:e;if(q.scope==="body"){let{ReplaceBodyExecutor:K}=await Promise.resolve().then(()=>(bp(),pg));Z=await K.execute(q,n,this.project)}else{let{ReplaceNodeExecutor:K}=await Promise.resolve().then(()=>(xp(),fg));Z=await K.execute(q,n,this.project)}break}case"add-exclude-dir":Z=await this.handleAddExcludeDir(e);break;case"remove-exclude-dir":Z=await this.handleRemoveExcludeDir(e);break;case"set-enabled-languages":Z=await this.handleSetEnabledLanguages(e);break;case"list-snapshots":Z=ko.listSnapshots(e,n,this.project);break;case"diff-snapshots":Z=ko.diffSnapshots(e,n,this.project);break;case"get-snapshot-trailers":Z=ko.getSnapshotTrailers(e,n,this.project);break;case"restore-snapshot":Z=await ko.restoreSnapshot(e,n,this.project);break;case"restore-files":Z=await ko.restoreFiles(e,n,this.project);break;case"change-signature":X("[OperationDispatch] entering ChangeSignatureExecutor",{op:o,targetPath:e?.path??null}),Z=await Sg.execute(e,n,this.project);break;case"get-project-root":Z=this.handleGetProjectRoot();break;default:try{let{AtomicExecutor:q}=await Promise.resolve().then(()=>(CN(),PN));Z=await q.execute(e,n,this.project,this)}catch{Z={success:!1,error:`Operation ${e.op} not implemented`}}}X("[OperationDispatch] executor returned",{op:o,success:!!Z?.success,error:Z?.error??null,errorCode:Z?.error_code??null,changedFiles:Array.isArray(Z?.details?.changedFiles)?Z.details.changedFiles.length:null,allChangedFiles:Array.isArray(Z?.details?.allChangedFiles)?Z.details.allChangedFiles.length:null});let ve=Date.now(),fe={executorMs:Math.max(0,ve-h)},ge=String(o||"").toLowerCase()==="delete"||!!e?.forceMayBreakSyntax;if(d&&Z&&!Z.success&&!we&&!Ne(e)){let q=Z.error_code;if((q==="would_introduce_syntax_error"||q==="validation_failed"||q==="io_write_failed")&&re){let ne=Array.isArray(Z.details?.changedFiles)?Z.details.changedFiles:[];if(ne.length>0)try{await ko.restoreSnapshot({op:"restore-snapshot",snapshotId:re,shouldCreateNewSnapshot:!1,restrictToPaths:ne},n,this.project),Z.details=Z.details||{},Z.details.rollbackAttempted=!0,Z.details.snapshotBefore=re}catch{}}}if(d&&Z&&Z.success&&!we&&!p){try{let q=Array.isArray(Z.details?.allChangedFiles)?Z.details.allChangedFiles:Array.isArray(Z.details?.changedFiles)?Z.details.changedFiles:[],K=Array.isArray(Z.details?.deletedFiles)?Z.details.deletedFiles:[];if((!q||q.length===0)&&(!K||K.length===0))return X("[OperationDispatch] skipping snapshot because no files changed",{op:o}),O(Z);let ne=Z.details?.receipt||{op:o,target:e.path||e.to||e.of,timestamp:Date.now(),changedFilesCount:q.length},{SnapshotService:ce}=await Promise.resolve().then(()=>(M_(),O_)),{SnapshotStatusTracker:Re}=await Promise.resolve().then(()=>(Za(),Ka)),be=Date.now();X("[SnapshotService] Starting snapshot",{files:q.length,deleted:K.length});try{Re.getInstance(this.projectPath).start(q.length,K.length)}catch{}let Ge=Z.details&&Z.details.trailers?Z.details.trailers:void 0,{snapshotId:Le,parentId:rt}=await ce.takeSnapshotNow(this.projectPath,q,o,ne,Ge,K,r);fe.snapshotMs=Date.now()-be,X("[SnapshotService] Snapshot finished",{durationMs:fe.snapshotMs,snapshotId:Le});try{Re.getInstance(this.projectPath).complete()}catch{}if(Z.snapshotBefore=rt||"<none>",Z.snapshotAfter=Le,Z.details||(Z.details={}),Z.details.receipt=ne,Z.details&&Z.details.trailers){let jt=Z.details.trailers,Oe={};for(let Be of Object.keys(jt)){let me=String(jt[Be]??"");Oe[Be]=me.length>200?me.slice(0,200):me}delete Z.details.trailers,Z.details.trailersPreview=Oe,Z.details.trailersNote="Trailers truncated to 200 chars. Use list-snapshots/get-snapshot-trailers to fetch full trailers."}}catch(q){return X("[OperationDispatch] snapshot finalization failed",{op:o,error:q?.message||String(q)}),O({success:!1,error:`Snapshot failure: ${q?.message||q}`})}if(!ge&&!f){let q=Array.isArray(Z.details?.allChangedFiles)?Z.details.allChangedFiles:Array.isArray(Z.details?.changedFiles)?Z.details.changedFiles:[];if(q.length>0){let K=Date.now(),ne=await this.validateChangedFiles(n,q,N);if(fe.validationMs=Date.now()-K,ne.skipped&&ne.warning&&(Z.warnings=Array.isArray(Z.warnings)?[...Z.warnings,ne.warning]:[ne.warning]),!ne.ok){let ce=Z.snapshotBefore,Re=Z.snapshotAfter;if(ce&&Re&&Re!=="<none>")try{await ko.restoreSnapshot({op:"restore-snapshot",snapshotId:ce,shouldCreateNewSnapshot:!1,deleteSnapshotId:Re,restrictToPaths:q},n,this.project)}catch{}return O({success:!1,error:ne.error||"Post-operation validation failed; changes rolled back.",details:{validation:ne,snapshotBefore:ce,snapshotAfter:Re,rollbackAttempted:!0}})}}}}d&&(Z?.success?this.recordRestoreFastPathState(o,Z):this.invalidateRestoreFastPathState("modifying-op-failed",{op:o??null,error:Z?.error??null}));try{if(d&&Z&&!we){let q=Date.now(),K=require("path"),ne=Array.isArray(Z.details?.allChangedFiles)?Z.details.allChangedFiles:Array.isArray(Z.details?.changedFiles)?Z.details.changedFiles:[],ce=Array.isArray(Z.details?.createdFiles)?Z.details.createdFiles:[],Re=Array.isArray(Z.details?.deletedFiles)?Z.details.deletedFiles:[],be=Be=>K.isAbsolute(Be)?Be:K.join(this.projectPath,Be),Ge=Be=>Array.from(new Set(Be.filter(Boolean))),Le=Ge(ce.map(be)),rt=new Set(Le),jt=Ge(ne.map(be)).filter(Be=>!rt.has(Be)),Oe=Ge(Re.map(be));(jt.length>0||Oe.length>0||Le.length>0)&&this.scheduleProjectSync({created:Le,modified:jt,deleted:Oe},`${String(o||s||"unknown")} post-write sync`).catch(Be=>{Bn("[RefreshFromDisk] post-op refresh failed",Be?.message||Be)}),fe.syncEnqueueMs=Date.now()-q}}catch(q){Bn("[RefreshFromDisk] post-op refresh failed",q?.message||q)}return X("[OperationDispatch] post-execution complete",{op:o,success:!!Z?.success,totalElapsedMs:Math.max(0,Date.now()-h),postExecutionMs:Math.max(0,Date.now()-ve),timings:fe,changedFiles:Array.isArray(Z?.details?.changedFiles)?Z.details.changedFiles.length:null,allChangedFiles:Array.isArray(Z?.details?.allChangedFiles)?Z.details.allChangedFiles.length:null}),O(Z)}finally{X("[OperationGate] releasing modifying op lock",{op:o??null,activeOp:this.modifyingOpName||null}),M()}}async refreshFilesFromDisk(e,n){let r=require("fs"),s=require("path"),o=a=>{try{return s.relative(this.projectPath,a).replace(/\\/g,"/")}catch{return a}};if(e=this.filterExcludedAbsolutePaths(e),!e.length)return;ut(n,"Workspace sync refresh cancelled"),this.refreshingInProgress=!0,this.refreshingFiles=e.map(o);let i=Date.now();try{for(let a of e){ut(n,"Workspace sync refresh cancelled");try{let c=r.existsSync(a),l=this.project.getSourceFile(a);if(!c){l&&this.project.removeSourceFile(l);continue}(l||this.project.addSourceFileAtPath(a)).refreshFromFileSystemSync()}catch(c){Bn("[RefreshFromDisk] Failed for",a,c?.message||c)}}}finally{let a=Date.now()-i;qn("code-engine.refreshFilesFromDisk.complete",{projectRoot:this.projectPath,files:e.length,sample:e.slice(0,20).map(o),elapsedMs:a}),X("[RefreshFromDisk] Completed",{files:e.length,ms:a}),this.refreshingInProgress=!1,this.refreshingFiles=[]}}scheduleProjectSync(e,n){let r=`project-sync:${Date.now().toString(36)}:${Math.random().toString(36).slice(2,8)}`,s=Date.now(),o=this.workspaceSyncController.signal;X("[ProjectSync] enqueue",{syncId:r,reason:n,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,hadPending:!!this.pendingProjectSync,pendingSyncId:this.pendingProjectSyncId??null,pendingReason:this.pendingProjectSyncReason??null});let i=async()=>{let l=Date.now();X("[ProjectSync] begin",{syncId:r,reason:n,queueWaitMs:l-s,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});try{if(await this.handleBatchFileChanges(e,{signal:o,source:"post-write-sync"}),o.aborted){X("[ProjectSync] superseded",{syncId:r,reason:n,durationMs:Date.now()-l,totalMs:Date.now()-s});return}X("[ProjectSync] complete",{syncId:r,reason:n,durationMs:Date.now()-l,totalMs:Date.now()-s})}catch(u){if(hi(u)||o.aborted){X("[ProjectSync] superseded",{syncId:r,reason:n,durationMs:Date.now()-l,totalMs:Date.now()-s,message:u?.message||String(u)});return}throw X("[ProjectSync] failed",{syncId:r,reason:n,durationMs:Date.now()-l,totalMs:Date.now()-s,message:u?.message||String(u)}),u}},a=(this.pendingProjectSync??Promise.resolve()).catch(l=>{if(hi(l)){X("[ProjectSync] previous queued refresh superseded",{syncId:r,reason:n,message:l?.message||String(l)});return}Bn("[ProjectSync] previous queued refresh failed",l?.message||l)}).then(i),c=Symbol(r);return this.pendingProjectSyncToken=c,this.pendingProjectSyncId=r,this.pendingProjectSyncEnqueuedAt=s,this.pendingProjectSyncReason=n,this.pendingProjectSync=a.finally(()=>{this.clearPendingProjectSyncState(c)}),this.pendingProjectSync}async awaitPendingProjectSync(e){let n=this.pendingProjectSync;if(!n)return;let r=Date.now();X("[ProjectSync] awaiting queued refresh before operation",{syncId:this.pendingProjectSyncId??null,operation:e??null,reason:this.pendingProjectSyncReason??null,queuedForMs:this.pendingProjectSyncEnqueuedAt?r-this.pendingProjectSyncEnqueuedAt:null});let s=setInterval(()=>{X("[ProjectSync] waiting",{syncId:this.pendingProjectSyncId??null,operation:e??null,reason:this.pendingProjectSyncReason??null,queuedForMs:this.pendingProjectSyncEnqueuedAt?Date.now()-this.pendingProjectSyncEnqueuedAt:null,waitedMs:Date.now()-r})},t.PROJECT_SYNC_HEARTBEAT_MS);s.unref?.();try{await n,X("[ProjectSync] awaited queued refresh complete",{syncId:this.pendingProjectSyncId??null,operation:e??null,reason:this.pendingProjectSyncReason??null,waitedMs:Date.now()-r})}finally{clearInterval(s)}}async awaitPostWriteWorkSettled(e="external"){let n=Date.now();X("[PostWriteDrain] begin",{reason:e,pendingProjectSync:!!this.pendingProjectSync,pendingProjectSyncId:this.pendingProjectSyncId??null,batchRunner:!!this.batchRunner,batchInProgress:this.batchInProgress,refreshingInProgress:this.refreshingInProgress});let r=setInterval(()=>{X("[PostWriteDrain] waiting",{reason:e,waitedMs:Date.now()-n,pendingProjectSync:!!this.pendingProjectSync,pendingProjectSyncId:this.pendingProjectSyncId??null,pendingProjectSyncReason:this.pendingProjectSyncReason??null,batchRunner:!!this.batchRunner,batchInProgress:this.batchInProgress,refreshingInProgress:this.refreshingInProgress,queuedBatch:this.describeQueuedBatch()})},t.PROJECT_SYNC_HEARTBEAT_MS);r.unref?.();try{for(;;){let s=this.pendingProjectSync;if(s){await s;continue}let o=this.batchRunner;if(o){await o;continue}if(!this.batchInProgress&&!this.refreshingInProgress&&!this.queuedBatch)break;await new Promise(i=>setTimeout(i,25))}}finally{clearInterval(r),X("[PostWriteDrain] complete",{reason:e,waitedMs:Date.now()-n,pendingProjectSync:!!this.pendingProjectSync,batchRunner:!!this.batchRunner,batchInProgress:this.batchInProgress,refreshingInProgress:this.refreshingInProgress})}}scheduleLspWorkspaceSync(e,n){let r=this.lspHost,s=r?.workspaceFilesChanged?.bind(r),o=e.created.length+e.modified.length+e.deleted.length;if(!s||o===0)return qn("code-engine.batch.workspaceFilesChanged.skipped",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,reason:s?"empty-batch":"no-lsp-host"}),Promise.resolve();qn("code-engine.batch.workspaceFilesChanged.scheduled",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,reason:n});let i=async()=>{let c=Date.now();qn("code-engine.batch.workspaceFilesChanged.start",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,createdSample:e.created.slice(0,20),modifiedSample:e.modified.slice(0,20),deletedSample:e.deleted.slice(0,20),reason:n});try{await s(e),qn("code-engine.batch.workspaceFilesChanged.complete",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:Date.now()-c,reason:n})}catch(l){qn("code-engine.batch.workspaceFilesChanged.failed",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:Date.now()-c,error:l?.message||String(l),reason:n}),Bn("[LspWorkspaceSync] workspaceFilesChanged failed",l?.message||l)}},a=(this.pendingLspWorkspaceSync??Promise.resolve()).catch(c=>{Bn("[LspWorkspaceSync] previous queued sync failed",c?.message||c)}).then(i);return this.pendingLspWorkspaceSync=a.finally(()=>{this.pendingLspWorkspaceSync===a&&(this.pendingLspWorkspaceSync=null)}),this.pendingLspWorkspaceSync}withSnapshotReceipt(e,n,r){return{...r}}async handleBatchFileChanges(e,n){let r=n?.source??"external",s=n?.signal??this.workspaceSyncController.signal;if(X("batch-change event",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,source:r,signalAborted:s.aborted}),e.created.length+e.modified.length+e.deleted.length===0)return;if(r!=="post-write-sync"&&this.invalidateRestoreFastPathState("batch-change",{source:r,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length}),s.aborted){X("[BatchQueue] skipped aborted batch",{source:r,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});return}let i={created:e.created.map(Ps),modified:e.modified.map(Ps),deleted:e.deleted.map(Ps)};qn("code-engine.batch.enqueue",{projectRoot:this.projectPath,created:i.created.length,modified:i.modified.length,deleted:i.deleted.length,createdSample:i.created.slice(0,20),modifiedSample:i.modified.slice(0,20),deletedSample:i.deleted.slice(0,20)});let a=`${ot(this.projectPath)}/`,c=i.deleted.find(u=>u.startsWith(a)&&u.endsWith(".db"));if(c&&!this.indexingInProgress){X("\u{1F504} Index DB deleted; triggering full reindex...",{file:c}),await this.startIndexing();return}let l=this.mergeQueuedBatch(i,r);X("[BatchQueue] enqueue",{incoming:{created:i.created.length,modified:i.modified.length,deleted:i.deleted.length},source:r,queued:l,indexingInProgress:this.indexingInProgress,batchInProgress:this.batchInProgress,runnerActive:!!this.batchRunner}),!this.indexingInProgress&&await this.ensureBatchRunner()}}});var si=B(require("path")),AL=B(require("os"));uS();Ls();dt();var Cp=class{constructor(e){this.options=e;this.workspaceRoots=new Set;this.explicitProjectRoot=null;this.registeredRoots=new Set}getWorkspaceRoots(){return Array.from(this.workspaceRoots).sort((e,n)=>e.localeCompare(n))}getExplicitProjectRoot(){return this.explicitProjectRoot}getRegisteredRoots(){return Array.from(this.registeredRoots).sort((e,n)=>e.localeCompare(n))}async setWorkspaceRoots(e,n){return this.workspaceRoots=new Set(e.map(r=>this.options.normalizeRoot(r)).filter(r=>!!r)),this.refreshEffectiveRoots(n)}async setProjectRoot(e,n){let r=Date.now();W("ProjectRootManager","setProjectRoot begin",{rootOrPath:e,currentExplicitRoot:this.explicitProjectRoot,opts:n});let s=this.options.normalizeRoot(e);if(!s)return W("ProjectRootManager","setProjectRoot normalized to null",{rootOrPath:e,elapsedMs:Date.now()-r}),null;let o=this.options.resolveIndexRoot(s);return o?this.explicitProjectRoot===o?(W("ProjectRootManager","setProjectRoot no-op",{rootOrPath:e,resolvedInput:s,targetDir:o,elapsedMs:Date.now()-r}),o):(this.explicitProjectRoot=o,await this.refreshEffectiveRoots(n),W("ProjectRootManager","setProjectRoot complete",{rootOrPath:e,resolvedInput:s,targetDir:o,registeredRoots:this.getRegisteredRoots(),elapsedMs:Date.now()-r}),o):(W("ProjectRootManager","setProjectRoot resolveIndexRoot returned null",{rootOrPath:e,resolvedInput:s,elapsedMs:Date.now()-r}),null)}async refreshEffectiveRoots(e){let n=Date.now(),r=this.explicitProjectRoot?new Set([this.explicitProjectRoot]):new Set(this.workspaceRoots),s=new Set(this.registeredRoots),o=[];W("ProjectRootManager","refreshEffectiveRoots begin",{effective:Array.from(r),registeredBefore:Array.from(s),opts:e});for(let i of r){if(this.registeredRoots.has(i))continue;let a=Date.now(),c=await this.options.registerRoot(i);W("ProjectRootManager","refreshEffectiveRoots registerRoot resolved",{requestedRoot:i,registered:c,elapsedMs:Date.now()-a}),c&&(this.registeredRoots.add(c),o.push(c))}for(let i of s)r.has(i)||(this.options.disposeRoot(i),this.registeredRoots.delete(i));if(e?.indexNewRoots&&this.options.startIndexingForRoot)for(let i of o)W("ProjectRootManager","refreshEffectiveRoots startIndexingForRoot dispatch",{root:i}),this.options.startIndexingForRoot(i);return W("ProjectRootManager","refreshEffectiveRoots complete",{newlyRegistered:o,finalRoots:this.getRegisteredRoots(),elapsedMs:Date.now()-n}),{newlyRegistered:o,finalRoots:this.getRegisteredRoots()}}};Ls();Da();var NN=B(require("os")),Qo=B(require("path"));ir();Rd();Ha();var B_=5e4,gU=1*1024*1024,Og="PANDO_ALLOW_BROAD_ROOT_INDEXING",yU=new Set(["applications","code","desktop","developer","documents","downloads","dropbox","github","google drive","icloud drive","library","movies","music","onedrive","pictures","projects","public","repos","repositories","src","videos","workspace","workspaces"]),bU=new Set(["code","developer","github","projects","repos","repositories","src","workspace","workspaces"]);function DN(t,e){let n=typeof e?.limit=="number"&&Number.isFinite(e.limit)?Math.max(1,Math.trunc(e.limit)):B_,r=SU(t,{env:e?.env,homeDir:e?.homeDir});if(r)return{root:t,candidateIndexableFiles:0,limit:n,exceeded:!0,reason:"broad-root",message:r};let s=e?.languageSupport,o=mo(t),i=bd(s),a=hs(t,o),c=KP(t,i,{shouldExclude:a,maxFileBytes:gU,limit:n});return{root:t,candidateIndexableFiles:c.count,limit:n,exceeded:c.limitExceeded,...c.limitExceeded?{reason:"file-count-limit"}:{}}}function ON(t){if(t.reason==="broad-root")return new Error(`Refusing to auto-index '${t.root}': ${t.message??"it is a broad filesystem location"}. Choose a narrower project folder, or set ${Og}=1 to override.`);let e=t.exceeded?"at least":"exactly";return new Error(`Refusing to index '${t.root}': candidate_indexable_files is ${e} ${t.candidateIndexableFiles}, above the limit of ${t.limit}. Choose a narrower root or add excludes before retrying.`)}function SU(t,e){let n=e?.env??process.env;if(/^(1|true|yes)$/i.test(n[Og]||""))return null;let r=Qo.default.resolve(t),s=Qo.default.parse(r);if(Dg(r)===Dg(s.root))return"it is the filesystem root";let o=Dg(Qo.default.resolve(e?.homeDir??NN.default.homedir())),i=Dg(r);if(i===o)return"it is the user home directory";let a=Qo.default.relative(o,i);if(!a||a.startsWith("..")||Qo.default.isAbsolute(a))return null;let c=a.split(Qo.default.sep).filter(Boolean);return c.length===1&&yU.has(c[0].toLowerCase())?`it is the broad home folder '${c[0]}'`:c.length===2&&c[0].toLowerCase()==="documents"&&bU.has(c[1].toLowerCase())?`it is the broad project collection folder '${c.join(Qo.default.sep)}'`:null}function Dg(t){let e=Qo.default.parse(t),n=Qo.default.resolve(t);for(;n.length>e.root.length&&/[\\/]$/.test(n);)n=n.slice(0,-1);return n}Qt();dt();var Ap=class t{constructor(e,n){this.options=n;this.indexingSuppressedRoots=new Set;this.indexingSuppressionReasons=new Map;this.rootManager=new Cp({normalizeRoot:r=>{let s=r.trim();return s?vt(s):null},resolveIndexRoot:r=>r,registerRoot:async r=>{let s=Date.now();W("DirectProjectRootManager","registerRoot begin",{root:r,hasOptions:!!this.options});let o=this.getOptionsForRoot(r);return o&&Dn.setEngineOptions(r,o),Dn.getEngine(r,o),W("DirectProjectRootManager","registerRoot complete",{root:r,elapsedMs:Date.now()-s}),r},disposeRoot:r=>{W("DirectProjectRootManager","disposeRoot",{root:r}),Dn.clearEngine(r)},startIndexingForRoot:async r=>{let s=Date.now();if(W("DirectProjectRootManager","startIndexingForRoot begin",{root:r}),this.indexingSuppressedRoots.has(vt(r))){W("DirectProjectRootManager","startIndexingForRoot skipped (root over indexing limit)",{root:r});return}let o=Dn.getEngine(r,this.getOptionsForRoot(r));typeof o?.startIndexing=="function"&&await o.startIndexing(),W("DirectProjectRootManager","startIndexingForRoot dispatched",{root:r,elapsedMs:Date.now()-s})}}),this.initialRoot=e}static async create(e,n){let r=new t(e,n);return await r.validateProjectRoot(e),await r.rootManager.setWorkspaceRoots([e]),r}getProjectRoot(){let e=this.rootManager.getExplicitProjectRoot();return e||(this.rootManager.getRegisteredRoots()[0]??null)}getEngine(){let e=this.getProjectRoot();if(!e)throw new Error("No project root configured.");return Dn.getEngine(e,this.getOptionsForRoot(e))}async validateProjectRoot(e){let n=e.trim();if(!n)return null;let r=vt(n),s=DN(r,{languageSupport:this.getOptionsForRoot(r)?.languageSupport,limit:this.indexingLimitOverride});if(s.exceeded){this.indexingSuppressedRoots.add(r);let o=ON(s).message;this.indexingSuppressionReasons.set(r,o),W("DirectProjectRootManager","validateProjectRoot indexing suppressed",{root:r,candidateIndexableFiles:s.candidateIndexableFiles,limit:s.limit,suppressionReason:s.reason??null,reason:o})}else this.indexingSuppressedRoots.delete(r),this.indexingSuppressionReasons.delete(r);return r}isIndexingSuppressed(e){return this.indexingSuppressedRoots.has(vt(e))}getIndexingSuppressionReason(e){return this.indexingSuppressionReasons.get(vt(e))}setIndexingLimitOverrideForTesting(e){this.indexingLimitOverride=e}async setProjectRoot(e){let n=Date.now();W("DirectProjectRootManager","setProjectRoot begin",{root:e}),await this.validateProjectRoot(e);let r=await this.rootManager.setProjectRoot(e,{indexNewRoots:!0});return W("DirectProjectRootManager","setProjectRoot complete",{root:e,resolved:r,elapsedMs:Date.now()-n}),r}updateRootOptions(e,n){let r=vt(e),s=n??this.getOptionsForRoot(r);s&&Dn.setEngineOptions(r,s)}getOptionsForRoot(e){let n=vt(e),r=this.options?.languageSupport??Na(n),s=this.options?.lspHost;if(!(!r&&!s))return{...r?{languageSupport:r}:{},...s?{lspHost:s}:{}}}};Go();Rh();Da();ir();ho();xo();var xU=B(require("fs")),_U=B(require("path"));Ph();var BN=require("events");Rh();Ph();ir();Da();Ls();Qt();var jN=require("child_process");Ls();kr();dt();var q_=require("child_process"),xc=null,Ip=null;async function FN(t){return xc||Ip||(Ip=Promise.resolve().then(()=>{let e=MN();if(e.available)return xc=e,e;let n=vU(),r=e.error;for(let s of n){t?.(`[NodeFileWatcher] watchman missing; trying install via ${s.label}`);let o=wU(s),i=MN();if(i.available)return xc={available:!0,version:i.version,installAttempted:!0,installSucceeded:!0,installMethod:s.label},xc;r=o.error??i.error??r}return xc={available:!1,installAttempted:n.length>0,installSucceeded:!1,error:r},xc}).finally(()=>{Ip=null}),Ip)}function MN(){let t=(0,q_.spawnSync)("watchman",["--version"],{encoding:"utf8",stdio:"pipe",shell:process.platform==="win32"});return t.status===0?{available:!0,version:`${t.stdout||t.stderr||""}`.trim()||void 0,installAttempted:!1,installSucceeded:!1}:{available:!1,installAttempted:!1,installSucceeded:!1,error:$N(t.error,t.stderr,t.stdout)}}function wU(t){for(let e of t.steps){let n=(0,q_.spawnSync)(e.cmd,e.args,{encoding:"utf8",stdio:"pipe",shell:process.platform==="win32"});if(n.status!==0)return{ok:!1,error:$N(n.error,n.stderr,n.stdout)}}return{ok:!0}}function vU(){let t=typeof process.getuid=="function"?process.getuid()===0:!1,e=(n,r)=>t?{cmd:n,args:r}:{cmd:"sudo",args:["-n",n,...r]};switch(process.platform){case"darwin":return[{label:"homebrew",steps:[{cmd:"brew",args:["install","watchman"]}]},{label:"macports",steps:[e("port",["install","watchman"])]}];case"linux":return[{label:"homebrew",steps:[{cmd:"brew",args:["install","watchman"]}]},{label:"apt",steps:[e("apt-get",["update"]),e("apt-get",["install","-y","watchman"])]},{label:"dnf",steps:[e("dnf",["install","-y","watchman"])]},{label:"pacman",steps:[e("pacman",["-S","--noconfirm","watchman"])]}];case"win32":return[{label:"chocolatey",steps:[{cmd:"choco",args:["install","watchman","-y"]}]},{label:"winget",steps:[{cmd:"winget",args:["install","--id","Facebook.Watchman","-e"]}]}];default:return[]}}function $N(t,e,n){if(t instanceof Error&&t.message)return t.message;let r=`${e??""}`.trim();return r||`${n??""}`.trim()||void 0}function Hn(t,e){if(!Vt())return;let n=e&&typeof e=="object"&&!Array.isArray(e)?{pid:process.pid,...e}:{pid:process.pid,details:e};W("WatcherTrace",t,n)}var Mg=class{constructor(e){this.log=e;this.projectRoot=null;this.languageSupport=null;this.watcherChild=null;this.watcherGeneration=0;this.shutdownGraceMs=1e3;this.switchChain=Promise.resolve()}async activate(e,n){this.languageSupport=n,await this.updateProjectRoot(e,n)}async updateProjectRoot(e,n){if(n&&(this.languageSupport=n),!e||!this.languageSupport||e===this.projectRoot&&!n)return;let r=this.languageSupport,s=this.switchChain.catch(()=>{}).then(async()=>{let o=this.projectRoot,i=this.watcherChild,a=this.watcherGeneration+1;this.log(`[NodeFileWatcher] updateProjectRoot begin from=${o??"null"} to=${e}`),Hn("node-watcher.updateProjectRoot.begin",{fromRoot:o,toRoot:e,previousGeneration:i?.generation??null,hasWatcher:!!i}),i&&(Hn("node-watcher.updateProjectRoot.await-previous-exit",{fromRoot:o,toRoot:e,previousGeneration:i.generation,childPid:i.process.pid??null}),await this.shutdownChild(i,"root-switch"));let c=await FN(this.log);Hn("node-watcher.watchman.status",{root:e,generation:a,available:c.available,version:c.version,installAttempted:c.installAttempted,installSucceeded:c.installSucceeded,installMethod:c.installMethod,error:c.error});let l=this.spawnWatcherChild(e,r,a,c);this.projectRoot=e,this.watcherChild=l,this.watcherGeneration=a,Hn("node-watcher.updateProjectRoot.complete",{fromRoot:o,toRoot:e,generation:a,childPid:l.process.pid??null,scriptPath:l.scriptPath})});this.switchChain=s,await s}async dispose(){let e=this.switchChain.catch(()=>{}).then(async()=>{let n=this.watcherChild,r=this.projectRoot,s=this.watcherGeneration;this.projectRoot=null,this.watcherChild=null,n&&(Hn("node-watcher.dispose",{root:r,generation:s,childPid:n.process.pid??null}),await this.shutdownChild(n,"dispose"))});this.switchChain=e,await e}spawnWatcherChild(e,n,r,s){let o=KT();if(!o)throw new Error("Could not resolve watcher child process script");this.log(`[NodeFileWatcher] activate root=${e}`),Hn("node-watcher.spawn.start",{root:e,generation:r,scriptPath:o});let i=(0,jN.fork)(o,[],{cwd:e,env:{...process.env,PANDO_WATCH_ROOT:e,PANDO_WATCH_GENERATION:String(r),PANDO_WATCH_LANGUAGE_SUPPORT_JSON:JSON.stringify(n),PANDO_WATCH_WATCHMAN_AVAILABLE:s.available?"1":"0",PANDO_WATCH_WATCHMAN_INSTALL_ATTEMPTED:s.installAttempted?"1":"0",PANDO_WATCH_WATCHMAN_INSTALL_SUCCEEDED:s.installSucceeded?"1":"0"},stdio:["ignore","inherit","inherit","ipc"]}),a=()=>{},c=new Promise(u=>{a=u}),l={process:i,root:e,generation:r,scriptPath:o,shutdownTimer:null,shuttingDown:!1,exitPromise:c,resolveExit:a};return i.on("message",u=>{this.handleChildMessage(l,u)}),i.on("exit",(u,d)=>{l.shutdownTimer&&(clearTimeout(l.shutdownTimer),l.shutdownTimer=null),Hn("node-watcher.child.exit",{root:l.root,generation:l.generation,childPid:i.pid??null,code:u,signal:d,shuttingDown:l.shuttingDown}),this.watcherChild===l&&(this.watcherChild=null),l.resolveExit()}),i.on("error",u=>{let d=u instanceof Error?u.message:String(u);this.log(`[NodeFileWatcher] watcher child error root=${e} error=${d}`),Hn("node-watcher.child.error",{root:e,generation:r,childPid:i.pid??null,error:d})}),Hn("node-watcher.spawn.complete",{root:e,generation:r,scriptPath:o,childPid:i.pid??null}),l}async handleChildMessage(e,n){if(!(!n||typeof n!="object"))switch(n.type){case"ready":this.handleReadyMessage(e,n);return;case"error":this.handleErrorMessage(e,n);return;case"batch":await this.handleBatchMessage(e,n);return;default:return}}handleReadyMessage(e,n){if(!this.isActiveChild(e)){Hn("node-watcher.ready.stale",{root:n.root,generation:n.generation,activeRoot:this.projectRoot,activeGeneration:this.watcherGeneration});return}this.log(`[NodeFileWatcher] ready root=${n.root} watchRoots=${n.watchRootCount??0} backend=${n.backendPreference??"native"}`),Hn("node-watcher.ready",{root:n.root,generation:n.generation,childPid:e.process.pid??null,watchRootCount:n.watchRootCount,backendPreference:n.backendPreference,watchmanAvailable:n.watchmanAvailable,watchmanInstallAttempted:n.watchmanInstallAttempted,watchmanInstallSucceeded:n.watchmanInstallSucceeded})}handleErrorMessage(e,n){let r=!this.isActiveChild(e);this.log(`[NodeFileWatcher] watch error path=${n.root} error=${n.error}`),Hn(r?"node-watcher.error.stale":"node-watcher.error",{root:n.root,generation:n.generation,childPid:e.process.pid??null,activeRoot:this.projectRoot,activeGeneration:this.watcherGeneration,error:n.error})}async handleBatchMessage(e,n){if(!this.isActiveChild(e)){Hn("node-watcher.batch.stale",{root:n.root,generation:n.generation,batchId:n.batchId,activeRoot:this.projectRoot,activeGeneration:this.watcherGeneration}),this.sendToChild(e,{type:"batch-ack",batchId:n.batchId,ok:!0});return}let r=Dn.getExistingEngine(n.root);if(Hn("node-watcher.batch.start",{root:n.root,generation:n.generation,batchId:n.batchId,childPid:e.process.pid??null,created:n.changes.created.length,modified:n.changes.modified.length,deleted:n.changes.deleted.length,hasEngine:!!r,hasBatchHandler:typeof r?.handleBatchFileChanges=="function"}),!r||typeof r.handleBatchFileChanges!="function"){this.sendToChild(e,{type:"batch-ack",batchId:n.batchId,ok:!1,error:`No batch handler available for root ${n.root}`});return}try{await r.handleBatchFileChanges(n.changes),Hn("node-watcher.batch.complete",{root:n.root,generation:n.generation,batchId:n.batchId,childPid:e.process.pid??null}),this.sendToChild(e,{type:"batch-ack",batchId:n.batchId,ok:!0})}catch(s){let o=s instanceof Error?s.message:String(s);Hn("node-watcher.batch.failed",{root:n.root,generation:n.generation,batchId:n.batchId,childPid:e.process.pid??null,error:o}),this.sendToChild(e,{type:"batch-ack",batchId:n.batchId,ok:!1,error:o})}}isActiveChild(e){return this.watcherChild===e&&this.projectRoot===e.root&&this.watcherGeneration===e.generation}sendToChild(e,n){try{e.process.send?.(n)}catch(r){Hn("node-watcher.child.send.failed",{root:e.root,generation:e.generation,childPid:e.process.pid??null,messageType:n.type,error:r instanceof Error?r.message:String(r)})}}async shutdownChild(e,n){if(e.shuttingDown){await e.exitPromise;return}e.shuttingDown=!0,Hn("node-watcher.child.shutdown.begin",{root:e.root,generation:e.generation,childPid:e.process.pid??null,reason:n}),this.sendToChild(e,{type:"shutdown",reason:n}),e.shutdownTimer=setTimeout(()=>{Hn("node-watcher.child.shutdown.force-kill",{root:e.root,generation:e.generation,childPid:e.process.pid??null,reason:n,graceMs:this.shutdownGraceMs});try{e.process.kill("SIGKILL")}catch(r){Hn("node-watcher.child.shutdown.force-kill.failed",{root:e.root,generation:e.generation,childPid:e.process.pid??null,reason:n,error:r instanceof Error?r.message:String(r)})}},this.shutdownGraceMs),await e.exitPromise}};var LN=zN();function zN(){return process.env.PANDO_RUNTIME_HOST==="vscode-extension"||process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK||process.env.VSCODE_CWD?"vscode-extension":process.env.PANDO_RUNTIME_HOST==="standalone-cli"?"standalone-cli":"unknown"}function H_(t){LN=t,process.env.PANDO_RUNTIME_HOST=t}function W_(){return LN==="vscode-extension"}kr();Ls();async function U_(t){let e=Dn.getEngine(t),n={root:t,isIndexing:typeof e?.isIndexingInProgress=="function"?!!e.isIndexingInProgress():!1};try{let r=await e.execute({op:"workspace-overview"});if(!r?.success)return n;let s=r.indexing??{};return{root:t,isIndexing:!!(s.isIndexing??n.isIndexing),progress:typeof s.progress=="number"?s.progress:void 0,totalFiles:typeof s.totalFiles=="number"?s.totalFiles:void 0,filesProcessed:typeof s.filesProcessed=="number"?s.filesProcessed:void 0,filesIndexed:typeof s.filesIndexed=="number"?s.filesIndexed:void 0,filesSkipped:typeof s.filesSkipped=="number"?s.filesSkipped:void 0,filesFailed:typeof s.filesFailed=="number"?s.filesFailed:void 0,message:typeof s.message=="string"?s.message:void 0}}catch{return n}}dt();var Np=class t extends BN.EventEmitter{constructor(n,r){super();this.rootManager=n;this.options=r;this.watcher=null}static async create(n){Bs()||Ma(process.cwd(),n.runtimePaths);let r=await Ap.create(n.initialRoot,{languageSupport:n.languageSupport,lspHost:n.lspHost}),s=new t(r,{...n});return s.warnIfIndexingSuppressed(r.getProjectRoot()),await s.configureWatcher(),s}warnIfIndexingSuppressed(n){if(!n||!this.rootManager.isIndexingSuppressed(n))return;let r=this.rootManager.getIndexingSuppressionReason(n)??`Refusing to auto-index '${n}': it has too many files to index safely.`;this.options.log?.(`indexing is OFF for '${n}': ${r} Pando is running but its code-graph tools will be empty here. Set the project root to a narrower folder, add excludes for large roots, or set ${Og}=1 before launch to override broad-root suppression. The file-count safety limit is ${B_.toLocaleString()} candidate files.`)}getProjectRoot(){return this.rootManager.getProjectRoot()}getRoots(){let n=this.getProjectRoot();return n?[n]:[]}getEngine(){return this.rootManager.getEngine()}async setProjectRoot(n){let r=this.getProjectRoot(),s=vt(n),o=Date.now();if(W("PandoRuntime","setProjectRoot begin",{requestedRoot:n,currentRoot:r,nextRoot:s}),await this.rootManager.validateProjectRoot(n),this.warnIfIndexingSuppressed(s),r===s)return W("PandoRuntime","setProjectRoot no-op",{requestedRoot:n,currentRoot:r,nextRoot:s,elapsedMs:Date.now()-o}),r;if(r&&r!==s){let c=Dn.getExistingEngine(r),l=`project root switching from ${r} to ${s}`,u=(p,f,m)=>{W("PandoRuntime",`setProjectRoot phase:${p}`,{requestedRoot:n,currentRoot:r,nextRoot:s,elapsedMs:Date.now()-f,...m})},d=Date.now();try{c?.cancelActiveOperations?.("project root switching")}catch{}u("cancelActiveOperations",d,{hasEngine:!!c}),d=Date.now();try{c?.cancelIndexing?.("project root switching")}catch{}u("cancelIndexing",d),d=Date.now();try{Dn.resetEngine(r)}catch{}u("resetEngine",d),d=Date.now(),Th(),u("shutdownActiveStreamingIndexers",d),d=Date.now(),await go.shutdownAllShared({force:!0,reason:l}).catch(()=>{}),u("shutdownAllShared(force)",d),d=Date.now(),Va(l),u("shutdownSharedWorkers",d)}let i=Date.now(),a=await this.rootManager.setProjectRoot(n);if(W("PandoRuntime","setProjectRoot rootManager resolved",{requestedRoot:n,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-i}),a){let c=Date.now();W("PandoRuntime","setProjectRoot watcher.updateProjectRoot begin",{requestedRoot:n,currentRoot:r,nextRoot:s,resolved:a,hasWatcher:!!this.watcher}),this.rootManager.isIndexingSuppressed(a)?W("PandoRuntime","setProjectRoot watcher skipped (root over indexing limit)",{requestedRoot:n,resolved:a}):await this.watcher?.updateProjectRoot(a,this.resolveLanguageSupport(a)),W("PandoRuntime","setProjectRoot watcher.updateProjectRoot complete",{requestedRoot:n,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-c});let l=Date.now();W("PandoRuntime","setProjectRoot emit rootChanged begin",{requestedRoot:n,currentRoot:r,nextRoot:s,resolved:a}),this.emit("rootChanged",a),W("PandoRuntime","setProjectRoot emit rootChanged complete",{requestedRoot:n,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-l})}return W("PandoRuntime","setProjectRoot complete",{requestedRoot:n,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-o}),a}async startIndexing(){let n=this.getProjectRoot();if(!n)return;if(this.rootManager.isIndexingSuppressed(n)){W("PandoRuntime","startIndexing skipped (root over indexing limit)",{root:n}),this.emit("indexing",{root:n,isIndexing:!1});return}let r=this.rootManager.getEngine();this.emit("indexing",{root:n,isIndexing:!0}),await r.startIndexing?.(),await r.waitForInitialSnapshot?.()}shouldScheduleBackgroundIndexing(){let n=this.getProjectRoot();if(!n||this.rootManager.isIndexingSuppressed(n))return!1;let r=this.rootManager.getEngine();return typeof r?.shouldScheduleBackgroundIndexing=="function"?!!r.shouldScheduleBackgroundIndexing():!0}async getIndexingStatus(){let n=this.getProjectRoot();return n?U_(n):null}async getWorkspaceOverview(){let n=this.getProjectRoot();if(!n)return null;let r=this.rootManager.getEngine();try{let s=await r.execute({op:"workspace-overview"});if(!s?.success)return null;let o=s.nodes??{},i=ss(o.functions),a=ss(o.classes),c=ss(o.interfaces),l=ss(o.types),u=ss(o.enums),d=ss(o.variables),p=[i,a,c,l,u,d].filter(f=>typeof f=="number").reduce((f,m)=>f+m,0);return{root:n,files:{total:ss(s.files?.total),testFiles:ss(s.files?.testFiles)},nodes:{total:p||void 0,functions:i,classes:a,interfaces:c,types:l,enums:u,variables:d},indexing:{root:n,isIndexing:!!s.indexing?.isIndexing,totalFiles:ss(s.indexing?.totalFiles),filesProcessed:ss(s.indexing?.filesProcessed),filesIndexed:ss(s.indexing?.filesIndexed),filesSkipped:ss(s.indexing?.filesSkipped),filesFailed:ss(s.indexing?.filesFailed),progress:ss(s.indexing?.progress),message:typeof s.indexing?.message=="string"?s.indexing.message:void 0},writes:{ready:!!s.writes?.ready,blocked:!!(s.writes?.blocked??!s.writes?.ready),reason:typeof s.writes?.reason=="string"?s.writes.reason:void 0,message:typeof s.writes?.message=="string"?s.writes.message:void 0,gates:{metadataIndexingComplete:!!s.writes?.gates?.metadataIndexingComplete,snapshotComplete:!!s.writes?.gates?.snapshotComplete,ftsRequired:!1}},lsp:s.lsp&&typeof s.lsp=="object"?s.lsp:void 0}}catch{return null}}async stop(){let n=this.getProjectRoot();await this.watcher?.dispose(),this.watcher=null;let r=n?vt(n):null,s=r?Dn.getExistingEngine(r):null;if(s?.hasPendingInitialSnapshot?.()){let o=Math.max(0,Number(process.env.PANDO_INITIAL_SNAPSHOT_DRAIN_MS||"300000"));W("PandoRuntime","stop draining pending initial snapshot",{root:n,timeoutMs:o});try{await Promise.race([s.waitForInitialSnapshot?.(),new Promise((i,a)=>setTimeout(()=>a(new Error(`initial snapshot drain timed out after ${o}ms`)),o))]),W("PandoRuntime","stop drained pending initial snapshot",{root:n})}catch(i){W("PandoRuntime","stop initial snapshot drain failed",{root:n,error:i instanceof Error?i.message:String(i)})}}try{s?.cancelActiveOperations?.("runtime stopped")}catch{}try{s?.cancelIndexing?.("runtime stopped")}catch{}if(Th(),await go.shutdownAllShared({force:!0,reason:"runtime stopped"}).catch(()=>{}),Va("runtime stopped"),qS(),!!r){try{s?.dispose?.()}catch{}Dn.clearEngine(r)}}reloadLanguageSupport(n){let r=vt(n),s=this.resolveLanguageSupport(r);this.rootManager.updateRootOptions(r,{languageSupport:s,lspHost:this.options.lspHost}),this.getProjectRoot()===r&&this.watcher?.updateProjectRoot(r,s)}async configureWatcher(){if(this.options.enableFileWatching===!1||W_())return;let n=this.getProjectRoot();if(n){if(this.rootManager.isIndexingSuppressed(n)){W("PandoRuntime","configureWatcher skipped (root over indexing limit)",{root:n});return}this.watcher=new Mg(r=>this.options.log?.(r)??void 0),await this.watcher.activate(n,this.resolveLanguageSupport(n))}}resolveLanguageSupport(n){return this.options.languageSupport??Na(n)}};function ss(t){return typeof t=="number"?t:void 0}kr();async function Fg(t,e={}){return e.hostKind&&H_(e.hostKind),e.runtimePaths&&Ma(e.runtimePaths.runtimeRoot??t,e.runtimePaths),Np.create({initialRoot:t,languageSupport:e.languageSupport,lspHost:e.lspHost,transportMode:e.transportMode,enableFileWatching:e.enableFileWatching,log:e.log,runtimePaths:e.runtimePaths})}kr();var Fp=B(require("path"));Ls();zl();Qt();Yc();var RU="Compared against a smart non-pando workflow that would only send targeted declaration/reference snippets and minimal surrounding context, not full files.";var _c={language:null,charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"heuristic"},kU={c:{language:"c",charsPerLine:40.09,charsPerToken:3.98,searchLines:5.91,confidence:"trace-high"},cpp:{language:"cpp",charsPerLine:42.56,charsPerToken:3.99,searchLines:6.89,confidence:"trace-high"},csharp:{language:"csharp",charsPerLine:38.55,charsPerToken:3.99,searchLines:3.76,confidence:"trace-low"},js:{language:"js",charsPerLine:39.75,charsPerToken:3.98,searchLines:6.02,confidence:"trace-high"},ts:{language:"ts",charsPerLine:37.3,charsPerToken:3.99,searchLines:7.67,confidence:"trace-high"},java:{language:"java",charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"trace-sparse"},clojure:{language:"clojure",charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"modeled-only"},dart:{language:"dart",charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"modeled-only"}};function aa(t){return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.floor(t))}function Mp(t){return Math.max(0,Math.floor(t))}function KN(t,e=_c){return Mp(Math.round(t*e.charsPerLine))}function jg(t,e=_c){return t<=0?0:Mp(Math.ceil(t/e.charsPerToken))}function EU(t){return Buffer.byteLength(t,"utf8")}function TU(t){let e=t[t.length-1],n=t[t.length-2],r=t[t.length-3];return e?e==="content"&&n==="body"||e==="content"&&n==="code"&&r==="self"||e==="content"&&n==="code"?!0:e==="source"||e==="sourceText"||e==="sourceCode"||e==="rawSource"||e==="excerpt"||e==="snippet"||e==="oldString"||e==="old_string"||e==="originalFile"||e==="gitDiff"||e==="diff"||e==="patch":!1}function ZN(t){let e=new Set,n=(r,s)=>{if(typeof r=="string")return TU(s)?EU(r):0;if(!r||typeof r!="object"||e.has(r))return 0;if(e.add(r),Array.isArray(r))return r.reduce((i,a,c)=>i+n(a,[...s,String(c)]),0);let o=0;for(let[i,a]of Object.entries(r))o+=n(a,[...s,i]);return o};return Mp(n(t,[]))}function J_(t){if(Array.isArray(t))return t.length===1?J_(t[0]):null;if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?e==="typescript"||e==="tsx"?"ts":e==="javascript"||e==="jsx"?"js":e==="c++"||e==="cc"||e==="cxx"?"cpp":e==="c#"||e==="cs"?"csharp":e==="clj"||e==="cljs"||e==="cljc"?"clojure":e:null}function tr(t){if(typeof t!="string")return null;let e=t.split("#",1)[0].split("?",1)[0].toLowerCase();return/\.(ts|tsx)$/.test(e)?"ts":/\.(js|jsx|mjs|cjs)$/.test(e)?"js":/\.(cc|cpp|cxx|c\+\+|hpp|hh|hxx)$/.test(e)?"cpp":/\.(c|h)$/.test(e)?"c":/\.cs$/.test(e)?"csharp":/\.java$/.test(e)?"java":/\.(clj|cljs|cljc|edn)$/.test(e)?"clojure":/\.dart$/.test(e)?"dart":null}function $g(t){let e=J_(t?.lang??t?.language);if(e)return e;let n=tr(t?.path)??tr(t?.file)??tr(t?.file_path)??tr(t?.newFile)??tr(t?.oldFile)??tr(t?.bodyEndOf)??tr(t?.bodyStartOf)??tr(t?.before)??tr(t?.after)??tr(t?.start)??tr(t?.end)??tr(t?.location?.file);return n||null}function PU(t,e){let n=J_(t.lang)??tr(t.path)??tr(t.to)??tr(t.of)??tr(t.file)??tr(t.newFile)??$g(t.to)??$g(t.scope)??tr(t.scope?.file)??(Array.isArray(t.scope?.files)?tr(t.scope.files[0]):null);if(n)return n;for(let r of[e.results,e.items,e.exports])if(Array.isArray(r))for(let s of r){let o=$g(s);if(o)return o}return $g(e)}function CU(t,e){let n=PU(t,e);return n?kU[n]??{..._c,language:n,confidence:"heuristic"}:_c}function AU(t,e){return e==="trace-high"?t:e==="trace-low"||e==="trace-sparse"||e==="modeled-only"?"low":t==="high"?"medium":t}function K_(t,e){let n=t.savedItems.map(s=>{let o=KN(s.estimatedLinesNotSent,e);return{...s,estimatedCharsNotSent:o,estimatedTokensNotSent:jg(o,e)}}),r=n.reduce((s,o)=>s+o.estimatedCharsNotSent,0);return{...t,confidence:AU(t.confidence,e.confidence),savedItems:n,language:e.language,calibrationConfidence:e.confidence,charsPerLine:e.charsPerLine,charsPerToken:e.charsPerToken,counterfactualTextToolChars:r,estimatedCharsNotSent:r,estimatedTokensNotSent:jg(r,e)}}function qN(t,e){return Math.max(1,Math.round(t.searchLines||e))}function jn(t,e,n,r,s){let o=aa(n),i=aa(r);if(o<=0||i<=0)return null;let a=o*i,c=KN(a),l=jg(c);return{key:t,label:e,count:o,linesPerUnit:i,estimatedLinesNotSent:a,estimatedCharsNotSent:c,estimatedTokensNotSent:l,note:s}}function HN(){return{version:1,calls:0,successfulCalls:0,callsWithSavings:0,estimatedLinesNotSent:0,counterfactualTextToolChars:0,pandoActualSourceChars:0,estimatedCharsNotSent:0,estimatedTokensNotSent:0,byOperation:{},lastUpdatedAt:null}}function os(t,e,n,r,s,o){let i=o.filter(d=>d!==null),a=i.reduce((d,p)=>d+p.estimatedLinesNotSent,0),c=i.reduce((d,p)=>d+p.estimatedCharsNotSent,0),l=c,u=i.reduce((d,p)=>d+p.estimatedTokensNotSent,0);return{version:1,op:t,success:e,method:n,confidence:r,comparisonBaseline:RU,rationale:s,savedItems:i,estimatedLinesNotSent:a,language:null,calibrationConfidence:_c.confidence,charsPerLine:_c.charsPerLine,charsPerToken:_c.charsPerToken,counterfactualTextToolChars:c,pandoActualSourceChars:0,estimatedCharsNotSent:l,estimatedTokensNotSent:u}}function Z_(t,e){let n=ZN(e);if(!t.success||t.counterfactualTextToolChars<=0)return{...t,pandoActualSourceChars:n};let r=Mp(t.counterfactualTextToolChars-n);return{...t,pandoActualSourceChars:n,estimatedCharsNotSent:r,estimatedTokensNotSent:jg(r,{language:t.language,charsPerLine:t.charsPerLine,charsPerToken:t.charsPerToken,searchLines:6,confidence:t.calibrationConfidence})}}function Dp(t,e,n){return os(t,e,"none","low",n,[])}function IU(t){switch(t.key){case"candidate-node-metadata":return"declaration snippets";case"candidate-node-self":return"extra declaration context";case"candidate-node-body":return"residual declaration context";case"reference-sites":return"reference snippets";case"caller-sites":return"caller snippets";case"export-result-contexts":return"export snippets";case"import-file-summaries":case"import-module-summaries":return"import snippets";case"namespace-graph-nodes":return"namespace declaration snippets";case"namespace-graph-edges":return"namespace dependency snippets";case"namespace-plan-edits":return"planned rewrite snippets";case"namespace-plan-declaration-context":return"namespace declaration context";case"reference-edit-contexts":return"reference edit snippets";case"declaration-context":return"declaration context";case"delete-target-context":return"delete target snippets";case"delete-reference-contexts":return"reference deletion snippets";case"signature-declaration-context":return"signature declaration context";case"signature-callsite-contexts":return"call-site rewrite snippets";case"fmr-match-contexts":return"matched code snippets";case"namespace-rewrite-files":return"namespace rewrite snippets";case"namespace-declaration-context":return"namespace declaration context";default:return t.label.replace(/\bthat did not need to be sent\b/gi,"").replace(/\bdid not need raw import snippets\b/gi,"").replace(/\s+/g," ").trim().replace(/[.;:]$/,"")}}function Lg(t){if(!t||t.estimatedTokensNotSent<=0&&t.pandoActualSourceChars<=0)return;let e=t.savedItems.filter(o=>o.estimatedTokensNotSent>0).map(o=>({label:IU(o),count:o.count,estimatedLines:o.estimatedLinesNotSent,estimatedChars:o.estimatedCharsNotSent,estimatedTokens:o.estimatedTokensNotSent})),n=e.reduce((o,i)=>o+i.count,0),r=n===1?"snippet":"snippets",s=`; Pando returned ${t.pandoActualSourceChars} chars of source`;return{version:1,op:t.op,summary:`Would have sent about ${t.estimatedCharsNotSent} chars / ${t.estimatedTokensNotSent} tokens across ${n} ${r}${s}.`,confidence:t.confidence,language:t.language,calibrationConfidence:t.calibrationConfidence,charsPerLine:t.charsPerLine,charsPerToken:t.charsPerToken,estimatedLines:t.estimatedLinesNotSent,counterfactualTextToolChars:t.counterfactualTextToolChars,pandoActualSourceChars:t.pandoActualSourceChars,estimatedChars:t.estimatedCharsNotSent,estimatedTokens:t.estimatedTokensNotSent,wouldSend:e}}function GN(t){return Array.isArray(t.results)?t.results:Array.isArray(t.items)?t.items:Array.isArray(t.exports)?t.exports:[]}function JN(t){let e=t.details;return typeof e?.changedFileCount=="number"?aa(e.changedFileCount):Array.isArray(e?.allChangedFiles)?e.allChangedFiles.length:Array.isArray(e?.changedFiles)?e.changedFiles.length:aa(t.changes?.count??0)}function wc(t){return Array.isArray(t)?t.length:0}function NU(t,e){let n=GN(e),r=0,s=0,o=0;for(let i of n){if(i?.body?.content){o+=1;continue}if(i?.self?.code?.content){s+=1;continue}r+=1}return os(t,e.success,"mixed","medium","Structured node discovery avoids sending most candidate snippets; when self/body is requested, the saved amount is reduced rather than treated as zero.",[jn("candidate-node-metadata","Candidate node snippets that did not need to be sent",r,4,"Metadata-only results usually avoid sending the declaration line plus minimal surrounding context for each candidate."),jn("candidate-node-self","Additional node context avoided even when self was requested",s,2,"Including the node itself still avoids some surrounding context a smart text workflow would usually inspect."),jn("candidate-node-body","Residual declaration context avoided when body content was requested",o,1,"Requesting body content removes most of the privacy advantage, so only a minimal declaration-context saving is counted.")])}function WN(t,e,n,r){let s=GN(e).length;return os(t,e.success,"exact-counts","high","Structured locations avoid sending per-location code snippets and nearby context.",[jn(n,n==="reference-sites"?"Reference-site snippets that did not need to be sent":"Caller-site snippets that did not need to be sent",s,r,"The comparison assumes a smart text workflow would only send a minimal location snippet for each result.")])}function DU(t,e){let n=wc(e.exports);return os(t,e.success,"exact-counts","medium","Structured export lookup answers declaration-discovery questions without sending export snippets or nearby code.",[jn("export-result-contexts","Export declaration snippets that did not need to be sent",n,2,"Only the returned export entries are counted, which keeps paginated list-exports calls conservative.")])}function OU(t,e){let n=e.imports,r=wc(n?.files),s=wc(n?.external),o=wc(n?.internal);return os(t,e.success,"exact-counts","medium","Import analysis returns grouped dependency structure without sending raw import blocks; only visible grouped entries are counted.",[jn("import-file-summaries","Per-file import summaries that did not need raw import snippets",r,2,"When grouped by file, the estimate counts one small import-summary snippet per returned file entry."),jn("import-module-summaries","Grouped import summaries that did not need raw import snippets",s+o,2,"When grouped by module, the estimate counts only the returned grouped entries rather than every underlying import usage.")])}function UN(t,e,n){let r=wc(e.namespaces),s=wc(e.edges);return os(t,e.success,"exact-counts","medium",n,[jn("namespace-graph-nodes","Namespace declaration snippets that did not need to be sent",r,1,"Each returned namespace usually corresponds to at least one small ns-form context in a text-based workflow."),jn("namespace-graph-edges","Namespace dependency snippets that did not need to be sent",s,2,"Each returned edge usually corresponds to one focused require/refer snippet in a text-based workflow.")])}function MU(t,e){let n=wc(e.namespaceEdits);return os(t,e.success,"exact-counts","medium","Namespace planning computes the affected declaration and dependent files without sending each candidate require/ns snippet to the provider.",[jn("namespace-plan-edits","Planned namespace rewrite snippets that did not need to be sent",n,4,"The estimate counts one small rewrite-planning snippet per planned file edit."),jn("namespace-plan-declaration-context","Namespace declaration context that only needed to be localized once",e.success?1:0,6,"The source namespace still needs one focused declaration context to build the plan.")])}function FU(t,e){let n=aa(e.details?.referencesRenamed);return os(t,e.success,"exact-counts","high","Rename uses exact reference counts already produced by the executor, then applies a conservative per-reference context window.",[jn("reference-edit-contexts","Reference edit contexts that did not need to be sent",n,3,"A smart non-pando workflow would still need to send each reference with a small amount of surrounding code before editing or approving it."),jn("declaration-context","Declaration context that only needed to be localized once",e.success?1:0,6,"The declaration still has to be identified, but pando does not require the model to receive surrounding code for every downstream edit.")])}function $U(t,e){let n=aa(e.details?.deletedCount),r=Array.isArray(e.details?.receipt?.appliedReferences)?e.details.receipt.appliedReferences.length:0;return os(t,e.success,r>0?"mixed":"heuristic",r>0?"high":"medium","Applied reference counts are exact when the executor exposes them; otherwise only the target-level deletion context is counted.",[jn("delete-target-context","Delete target contexts that did not need to be sent",n,6,"Each delete target typically needs declaration-level context in a text-based workflow."),jn("delete-reference-contexts","Reference deletion contexts that did not need to be sent",r,4,"When reference edits are applied automatically, pando avoids sending each reference and a small surrounding window.")])}function jU(t,e){let n=aa(e.details?.callSiteStats?.auto_rewritten??e.changes?.callSitesAutoRewritten??0);return os(t,e.success,"exact-counts","high","The executor already reports how many call sites were rewritten automatically, so the privacy estimate can stay count-exact while using conservative context windows.",[jn("signature-declaration-context","Function signature context that did not need to be sent repeatedly",e.success?1:0,6,"Only one declaration/signature context is counted for the target function."),jn("signature-callsite-contexts","Auto-rewritten call-site contexts that did not need to be sent",n,5,"The estimate only counts call sites pando rewrote automatically; manual-review sites are not claimed as privacy savings.")])}function LU(t,e,n){let r=aa(n.details?.receipt?.processedCount??n.details?.processedCount??n.details?.succeededCount??0),o=(Array.isArray(e.transforms)?e.transforms.length:0)>0?"filter-map-reduce localizes and rewrites matches without shipping matched code to the provider; the count is based on processed matches, not full-file size.":"filter-map-reduce localizes matches without shipping matched code to the provider.";return os(t,n.success,"exact-counts","high",o,[jn("fmr-match-contexts","Matched-node contexts that did not need to be sent",r,6,"The baseline assumes a smart text workflow would still need to send a small snippet for every matched location before applying or validating a transform.")])}function G_(t,e,n,r,s){let o=JN(e);return os(t,e.success,"heuristic","medium",s,[jn(`${t}-target-context`,r,o>0?1:0,n,"The estimate assumes one minimal target/anchor snippet would otherwise need to be sent for a single focused edit.")])}function zU(t,e){let n=JN(e);return os(t,e.success,"mixed","medium","Namespace rewrites typically require touching several import/require sites; the estimate stays conservative and file-based.",[jn("namespace-rewrite-files","Namespace/import rewrite snippets that did not need to be sent",n,4,"A smart text workflow would usually send at least one small require/import snippet per changed file."),jn("namespace-declaration-context","Namespace declaration context that only needed to be localized once",e.success?1:0,6,"The namespace declaration itself still needs one focused context window.")])}function VN(t,e,n){let r=!!n?.success,s=CU(e,n);if(!t)return Z_(K_(Dp("unknown",r,"Operation name unavailable; no privacy savings claimed."),s),n);if(!r)return Z_(K_(Dp(t,!1,"Operation did not succeed, so no privacy savings are claimed."),s),n);let o=(()=>{switch(t){case"find-nodes":return NU(t,n);case"find-references":return WN(t,n,"reference-sites",qN(s,6));case"find-callers":return WN(t,n,"caller-sites",qN(s,6));case"list-exports":return DU(t,n);case"analyze-imports":return OU(t,n);case"clojure-namespace-graph":return UN(t,n,"Namespace graph queries return cross-file dependency structure without sending the underlying ns/require snippets.");case"clojure-namespace-dependencies":case"clojure-namespace-dependents":return UN(t,n,"Namespace traversal returns dependency edges directly, avoiding per-edge code snippets in the provider request.");case"plan-clojure-namespace-move":case"plan-clojure-namespace-rename":return MU(t,n);case"rename":return FU(t,n);case"delete":return $U(t,n);case"change-signature":return jU(t,n);case"filter-map-reduce":return LU(t,e,n);case"replace":return G_(t,n,10,"Target replacement context that did not need to be sent","A focused replace still needs target localization in a text-based workflow; pando avoids sending that local code window.");case"replace-body":return G_(t,n,12,"Body replacement context that did not need to be sent","Body replacement typically requires a slightly larger context window than full-node replacement.");case"insert":case"add-code":return e?.createFileIfMissing?Dp(t,!0,"Insert created a new file, so no existing code context savings are claimed."):G_(t,n,8,"Insertion anchor context that did not need to be sent","A targeted insert usually needs local anchor context in a text-based workflow; pando keeps that out of the provider request.");case"rename-clojure-namespace":case"move-clojure-namespace":return zU(t,n);default:return Dp(t,!0,"Administrative or metadata-only operation; privacy savings are too small or too uncertain to claim conservatively.")}})();return Z_(K_(o,s),n)}function V_(t,e){if(e.length===0)return Dp(t,!0,"No underlying operation estimates were available.");let n=e.every(u=>u.success),r=e.every(u=>u.method==="exact-counts")?"exact-counts":e.some(u=>u.method==="none")?"mixed":e.every(u=>u.method==="heuristic")?"heuristic":"mixed",s=e.every(u=>u.confidence==="high")?"high":e.some(u=>u.confidence==="low")?"low":"medium",o=new Map;for(let u of e)for(let d of u.savedItems){let p=o.get(d.key);if(!p){o.set(d.key,{...d});continue}p.count+=d.count,p.estimatedLinesNotSent+=d.estimatedLinesNotSent,p.estimatedCharsNotSent+=d.estimatedCharsNotSent,p.estimatedTokensNotSent+=d.estimatedTokensNotSent}let i=os(t,n,r,s,"Combined from per-root operation estimates in the current dispatcher session.",Array.from(o.values())),a=e.reduce((u,d)=>u+d.pandoActualSourceChars,0),c=Mp(i.counterfactualTextToolChars-a),l=e.reduce((u,d)=>u+d.estimatedTokensNotSent,0);return{...i,language:e.every(u=>u.language===e[0]?.language)?e[0]?.language??null:null,calibrationConfidence:e.every(u=>u.calibrationConfidence==="trace-high")?"trace-high":e.some(u=>u.calibrationConfidence==="modeled-only")?"modeled-only":e.some(u=>u.calibrationConfidence==="trace-low")?"trace-low":e.some(u=>u.calibrationConfidence==="trace-sparse")?"trace-sparse":"heuristic",pandoActualSourceChars:a,estimatedCharsNotSent:c,estimatedTokensNotSent:l}}var Op=class{constructor(){this.summary=HN()}record(e,n,r){let s=VN(e,n,r),o=this.summary.byOperation[e]??{calls:0,successfulCalls:0,callsWithSavings:0,estimatedLinesNotSent:0,counterfactualTextToolChars:0,pandoActualSourceChars:0,estimatedCharsNotSent:0,estimatedTokensNotSent:0};return o.calls+=1,s.success&&(o.successfulCalls+=1),s.estimatedTokensNotSent>0&&(o.callsWithSavings+=1),o.estimatedLinesNotSent+=s.estimatedLinesNotSent,o.counterfactualTextToolChars+=s.counterfactualTextToolChars,o.pandoActualSourceChars+=s.pandoActualSourceChars,o.estimatedCharsNotSent+=s.estimatedCharsNotSent,o.estimatedTokensNotSent+=s.estimatedTokensNotSent,this.summary.byOperation[e]=o,this.summary.calls+=1,s.success&&(this.summary.successfulCalls+=1),s.estimatedTokensNotSent>0&&(this.summary.callsWithSavings+=1),this.summary.estimatedLinesNotSent+=s.estimatedLinesNotSent,this.summary.counterfactualTextToolChars+=s.counterfactualTextToolChars,this.summary.pandoActualSourceChars+=s.pandoActualSourceChars,this.summary.estimatedCharsNotSent+=s.estimatedCharsNotSent,this.summary.estimatedTokensNotSent+=s.estimatedTokensNotSent,this.summary.lastUpdatedAt=new Date().toISOString(),{operation:s,session:this.getSessionSummary()}}getSessionSummary(){let e={};for(let[n,r]of Object.entries(this.summary.byOperation))e[n]={...r};return{...this.summary,byOperation:e}}reset(){return this.summary=HN(),this.getSessionSummary()}};dt();function eo(t){let e=t.details;return e?typeof e.changedFileCount=="number"?e.changedFileCount:Array.isArray(e.allChangedFiles)?e.allChangedFiles.length:Array.isArray(e.changedFiles)?e.changedFiles.length:t.changes?.count??0:t.changes?.count??0}function zg(t){return t.page?.totalCount??t.totalCount??(Array.isArray(t.results)?t.results.length:0)}var BU={rename:t=>({primary:eo(t),secondary:t.details?.referencesRenamed??0}),delete:t=>({primary:eo(t),secondary:t.details?.deletedCount??0}),insert:t=>({primary:eo(t),secondary:t.created?1:0}),replace:t=>({primary:eo(t),secondary:0}),"replace-body":t=>({primary:eo(t),secondary:0}),"change-signature":t=>({primary:eo(t),secondary:t.changes?.callSitesAutoRewritten??0}),"filter-map-reduce":t=>({primary:eo(t),secondary:0}),"find-references":t=>({primary:zg(t),secondary:0}),"find-callers":t=>({primary:zg(t),secondary:0}),"find-nodes":t=>({primary:zg(t),secondary:0}),"workspace-overview":()=>({primary:0,secondary:0}),"list-exports":t=>({primary:t.page?.totalCount??(Array.isArray(t.exports)?t.exports.length:0),secondary:0}),"analyze-imports":t=>{let e=t.page;return{primary:e?.files?.totalCount??(e?.external?.totalCount??0)+(e?.internal?.totalCount??0),secondary:0}},"clojure-namespace-graph":t=>({primary:t.details?.namespaceCount??0,secondary:t.details?.edgeCount??0}),"clojure-namespace-dependencies":t=>({primary:t.namespacesPage?.totalCount??(Array.isArray(t.namespaces)?t.namespaces.length:0),secondary:t.edgesPage?.totalCount??(Array.isArray(t.edges)?t.edges.length:0)}),"clojure-namespace-dependents":t=>({primary:t.namespacesPage?.totalCount??(Array.isArray(t.namespaces)?t.namespaces.length:0),secondary:t.edgesPage?.totalCount??(Array.isArray(t.edges)?t.edges.length:0)}),"move-clojure-namespace":t=>({primary:eo(t),secondary:0}),"rename-clojure-namespace":t=>({primary:eo(t),secondary:0}),"restore-snapshot":t=>({primary:eo(t),secondary:0}),"restore-files":t=>({primary:eo(t),secondary:0})},qU=t=>({primary:eo(t),secondary:zg(t)});function HU(t,e){let n=BU[t]??qU;try{return n(e)}catch{return{primary:0,secondary:0}}}var WU=0;function X_(){return`${Date.now()}-${++WU}`}function XN(t,e,n,r){let s=HU(t,e);return{schema_version:1,call_id:r,op:t,success:e.success,duration_ms:Math.max(0,Math.round(n)),error_code:e.error_code??void 0,primary_count:s.primary,secondary_count:s.secondary,timestamp:new Date().toISOString()}}var QN="_privacyOperation";function t0(t){let e=t.trim();if(!e)return null;let n=e;return(e.startsWith("pando_")||e.startsWith("pando-"))&&(n=e.slice(6)),n?n.replace(/_/g,"-"):null}function n0(t,e){let n={...e};return delete n.root,n}var Bl=class{constructor(e){this.config=e;this.privacyCounter=new Op}async dispatch(e,n,r){let s=Date.now();W("PandoOp","op begin",{tool:e});let o;try{o=await this.dispatchInner(e,n,r)}catch(a){let c=a instanceof Error?a.message:String(a);throw W("PandoOp","op threw",{tool:e,error:c,elapsedMs:Date.now()-s}),a}let i=Date.now()-s;return o.success&&o.data&&typeof o.data=="object"&&!Array.isArray(o.data)&&o.data.elapsedMs===void 0&&(o.data.elapsedMs=i),W("PandoOp","op end",{tool:e,success:o.success,...o.success?{}:{error:o.error},elapsedMs:i}),o}async dispatchInner(e,n,r){let s=t0(e);if(!s)return{success:!1,error:`Unknown tool: ${e}`};let o=this.config.processRole??Xo();if(!Pp(o,s))return{success:!1,error:C_(o,s),data:{role:o,operation:s}};if(s==="add-root"){let f=typeof n.root=="string"?n.root.trim():"";if(!f)return{success:!1,error:"Missing required parameter: root"};if(YN(f))return{success:!1,error:"Filesystem root '/' cannot be used as a project root."};let m=$o(f);if(m)return{success:!1,error:`'${f}' cannot be added as a workspace root because it is, contains, or sits inside a protected location ('${m}'). Choose a project directory, not a system, credential, home, or external-disk path.`};if(!this.config.onRootAdded)return{success:!1,error:"add-root is not supported in this host."};let h=Date.now();W("PandoToolDispatcher","add-root begin",{toolName:e,requestedRoot:f});let g;try{g=await this.config.onRootAdded(f)}catch(S){let x=S instanceof Error?S.message:String(S);return W("PandoToolDispatcher","add-root rejected",{toolName:e,requestedRoot:f,error:x}),{success:!1,error:x}}if(!g.resolved)return{success:!1,error:`Unable to add root: ${f}`};W("PandoToolDispatcher","add-root complete",{toolName:e,requestedRoot:f,resolvedRoot:g.resolved,alreadyPersisted:g.alreadyPersisted,elapsedMs:Date.now()-h});let y=g.alreadyPersisted?`Root '${g.resolved}' is already registered. Restart Pando to use it if it isn't active yet.`:`Root '${g.resolved}' saved. Restart Pando to bind it into the sandbox; it will be available automatically on the next launch.`,b={root:g.resolved,alreadyPersisted:g.alreadyPersisted,requiresRestart:!g.alreadyPersisted,persistedRoots:g.persistedRoots,message:y};return{success:!0,data:this.attachPrivacyToData("add-root",n,b,{success:!0})}}if(s==="remove-root"){let f=typeof n.root=="string"?n.root.trim():"";if(!f)return{success:!1,error:"Missing required parameter: root"};if(YN(f))return{success:!1,error:"Filesystem root '/' cannot be removed as a project root."};if(!this.config.onRootRemoved)return{success:!1,error:"remove-root is not supported in this host."};let m=Date.now();W("PandoToolDispatcher","remove-root begin",{toolName:e,requestedRoot:f});let h;try{h=await this.config.onRootRemoved(f)}catch(b){let S=b instanceof Error?b.message:String(b);return W("PandoToolDispatcher","remove-root rejected",{toolName:e,requestedRoot:f,error:S}),{success:!1,error:S}}if(!h.resolved)return{success:!1,error:`Unable to remove root: ${f}`};W("PandoToolDispatcher","remove-root complete",{toolName:e,requestedRoot:f,resolvedRoot:h.resolved,removed:h.removed,elapsedMs:Date.now()-m});let g=h.removed?`Root '${h.resolved}' removed. Restart Pando to remove it from the sandbox bindings.`:`Root '${h.resolved}' was not registered. Restart Pando if it is still active from an older launch.`,y={root:h.resolved,removed:h.removed,requiresRestart:h.removed,persistedRoots:h.persistedRoots,message:g};return{success:!0,data:this.attachPrivacyToData("remove-root",n,y,{success:!0})}}let i=this.resolveToolRoots(n);if(!i.roots.length&&i.error)return{success:!1,error:i.error,data:i.availableRoots?{availableRoots:i.availableRoots}:void 0};let a=i.roots;if(s==="get-project-root")return a.length<=1?{success:!0,data:this.attachPrivacyToData("get-project-root",n,{projectRoot:a[0]??null},{success:!0})}:{success:!0,data:this.attachPrivacyToData("get-project-root",n,{projectRoots:a},{success:!0})};if(!a.length)return{success:!1,error:"No workspace root available."};if(s==="read-this-first")return{success:!0,data:this.attachPrivacyToData("read-this-first",n,{help:this.config.loadReadThisFirstMessage()},{success:!0})};let c=n0(s,n),l={op:s,...c},u=X_(),d=r?.telemetry;if(this.isReadOnlyTool(e,s))return this.dispatchReadOnly(a,l,r?.signal,u,d);if(a.length>1){let f=[];for(let h of a)f.push(await this.executeOne(h,l,r?.signal,u,d));await this.handlePostDispatchEffects(s,f);let m=this.buildAggregatePrivacy(s,f);return{success:!0,data:{perRoot:f,...m?{privacy:m}:{}}}}let p=await this.executeOne(a[0],l,r?.signal,u,d);if(!p.success){let f=p.error??"Operation failed",m=Array.isArray(p.result?.hints)?p.result.hints:void 0;return{success:!1,error:f,...m?{hints:m}:{},data:p.result??{success:!1,error:f}}}return await this.handlePostDispatchEffects(s,[p]),{success:!0,data:p.result}}getPrivacySummary(){return this.privacyCounter.getSessionSummary()}resetPrivacySummary(){return this.privacyCounter.reset()}resolveToolRoots(e){if(this.config.resolveRoots)return this.config.resolveRoots(e);let n=this.config.roots(),r=typeof e.root=="string"?e.root.trim():"";if(!r)return{roots:n};let s=vt(Fp.default.isAbsolute(r)?r:Fp.default.resolve(n[0]??process.cwd(),r)),o=n.map(i=>vt(i));return o.includes(s)?{roots:[s]}:{roots:[],error:`Requested root is not registered: ${r}`,availableRoots:o}}async dispatchReadOnly(e,n,r,s,o){if(e.length===1){let d=await this.executeOne(e[0],n,r,s,o);if(!d.success){let p=d.error??"Operation failed",f=Array.isArray(d.result?.hints)?d.result.hints:void 0;return{success:!1,error:p,...f?{hints:f}:{},data:d.result??{success:!1,error:p}}}return{success:!0,data:d.result}}let i=[],a=[],c=0,l=!1;for(let d of e){let p=await this.executeOne(d,n,r,s,o);if(i.push(p),!p.success||!p.result)continue;let f=Array.isArray(p.result.items)?p.result.items:Array.isArray(p.result.results)?p.result.results:null;if(!f)continue;for(let g of f)a.push({...g,root:d});let m=p.result.page,h=typeof m?.totalCount=="number"?m.totalCount:typeof p.result.totalCount=="number"?p.result.totalCount:f.length;c+=h,l=l||!!m?.hasMore||!!p.result.hasMore}let u=this.buildAggregatePrivacy(String(n.op||"unknown"),i);return{success:!0,data:{summary:KU(i,a.length?{shownCount:a.length,totalCount:c,hasMore:l}:void 0),results:a.length?a:void 0,totalCount:a.length?c:void 0,hasMore:a.length?l:void 0,perRoot:i,...u?{privacy:u}:{}}}}async executeOne(e,n,r,s,o){let i=typeof n.op=="string"?n.op:"unknown",a=Date.now();try{let l=await Dn.getEngine(e).execute(n,{signal:r}),u=this.attachPrivacyToResult(i,n,l);if(await this.emitTelemetry(i,l,Date.now()-a,e,s,o),!l.success){let d=e0(l.error||"Operation failed");return{root:e,success:!1,error:d,result:{...u,error:d}}}return{root:e,success:!0,result:u}}catch(c){let l={success:!1,error:c instanceof Error?c.message:String(c)},u=this.attachPrivacyToResult(i,n,l);await this.emitTelemetry(i,l,Date.now()-a,e,s,o);let d=e0(c instanceof Error?c.message:String(c));return{root:e,success:!1,error:d,result:{...u,error:d}}}}async emitTelemetry(e,n,r,s,o,i){try{let a=this.config.onTelemetry?.(XN(e,n,r,o??X_()),s,i);if(!a)return;let c=Promise.resolve(a);if(!this.config.awaitTelemetry){c.catch(()=>{});return}await UU(c,this.config.telemetryTimeoutMs??1e3)}catch{}}async handlePostDispatchEffects(e,n){if(e==="set-enabled-languages")for(let r of n)r.success&&r.result?.details?.languageSupportChanged===!0&&await this.config.onLanguageSupportChanged?.(r.root)}isReadOnlyTool(e,n){let r=n.replace(/-/g,"_");return this.config.readOnlyTools.has(e)||this.config.readOnlyTools.has(n)||this.config.readOnlyTools.has(r)||this.config.readOnlyTools.has(`pando_${r}`)||this.config.readOnlyTools.has(`pando-${n}`)}attachPrivacyToResult(e,n,r){let s=this.privacyCounter.record(e,n,r),o=Lg(s.operation),i={...r,...o?{privacy:o}:{}};return Object.defineProperty(i,QN,{value:s.operation,enumerable:!1,configurable:!0,writable:!1}),i}attachPrivacyToData(e,n,r,s){let o=Lg(this.privacyCounter.record(e,n,s).operation);return{...r,...o?{privacy:o}:{}}}buildAggregatePrivacy(e,n){let r=n.map(s=>s.result?.[QN]).filter(s=>!!s);return Lg(V_(e,r))}};function YN(t){let e=Fp.default.resolve(t);return Fp.default.parse(e).root===e}function e0(t){return t.length<=1e3?t:`${t.slice(0,1e3)}\u2026 [truncated]`}function UU(t,e){let n=Math.max(0,Math.trunc(e));return n===0?t:Promise.race([t,new Promise(r=>{setTimeout(r,n)})])}function KU(t,e){let n=t.length,r=t.filter(i=>i.success).length,s=n-r,o=t.map(i=>i.error??(typeof i.result?.error=="string"?i.result.error:void 0)).find(i=>typeof i=="string"&&i.trim().length>0);return{rootsTotal:n,rootsSucceeded:r,rootsFailed:s,shownCount:e?.shownCount,totalCount:e?.totalCount,hasMore:e?.hasMore,error:o}}var r0=B(require("fs")),ZU=["set-enabled-languages","add-root","remove-root","workspace-overview","get-db-schema","query-db","find-nodes","find-references","rename","replace","insert","delete","filter-map-reduce","shell-command"];function ql(t,e){let n=r0.default.readFileSync(t,"utf8"),r=JSON.parse(n),s=Array.isArray(r.tools)?r.tools:[],o=new Map(ZU.map((i,a)=>[i,a]));return s.filter(i=>typeof i?.name=="string").filter(i=>i.category!=="orchestrator").filter(i=>!(e?.excludeNames?.has(i.name)??!1)).sort((i,a)=>{let c=o.get(i.name),l=o.get(a.name);return c!=null&&l!=null?c-l:c!=null?-1:l!=null?1:i.name.localeCompare(a.name)})}var GU={"read-this-first":"Read this first","get-project-root":"Get project root","set-project-root":"Set project root","set-enabled-languages":"Set languages","find-nodes":"Find code","find-references":"Find references","find-callers":"Find callers","get-db-schema":"Index schema","query-db":"Query index","get-storage-content":"Read stored content","workspace-overview":"Workspace overview","list-exports":"List exports","analyze-imports":"Analyze imports","clojure-namespace-graph":"Namespace graph","clojure-namespace-dependencies":"Namespace deps","clojure-namespace-dependents":"Namespace dependents","plan-clojure-namespace-move":"Plan namespace move","plan-clojure-namespace-rename":"Plan namespace rename","move-clojure-namespace":"Move namespace","rename-clojure-namespace":"Rename namespace",rename:"Rename symbol",delete:"Delete code",insert:"Insert code",replace:"Replace code","replace-body":"Replace body","change-signature":"Change signature","filter-map-reduce":"Batch edit","shell-command":"Shell command","list-snapshots":"List snapshots","diff-snapshots":"Diff snapshots","get-snapshot-trailers":"Snapshot trailers","snapshot-worktree":"Create snapshot","restore-snapshot":"Restore snapshot","restore-files":"Restore files","repair-history":"Repair history","add-exclude-dir":"Exclude directory","remove-exclude-dir":"Include directory"},JU=new Set(["read-this-first","get-project-root","get-db-schema","get-storage-content","workspace-overview","find-nodes","find-references","find-callers","query-db","list-exports","analyze-imports","clojure-namespace-graph","clojure-namespace-dependencies","clojure-namespace-dependents","plan-clojure-namespace-move","plan-clojure-namespace-rename","list-snapshots","diff-snapshots","get-snapshot-trailers"]),VU=new Set(["set-project-root","set-enabled-languages","add-root","remove-root","rename","rename-clojure-namespace","move-clojure-namespace","delete","insert","replace","replace-body","change-signature","filter-map-reduce","shell-command","snapshot-worktree","restore-snapshot","restore-files","repair-history","add-exclude-dir","remove-exclude-dir"]),XU=new Set(["delete","shell-command","restore-snapshot","restore-files","repair-history","remove-root","remove-exclude-dir"]);function Q_(t){let e=t.parameters&&t.parameters.type==="object"?{...t.parameters,type:"object",properties:YU(t.parameters.properties)}:{type:"object",properties:{},required:[],additionalProperties:!1},n=GU[t.name],r=QU(t.name,n);return{name:t.name,...n?{title:n}:{},...r?{annotations:r}:{},description:t.description,inputSchema:e}}function QU(t,e){let n=JU.has(t),r=VU.has(t),s=XU.has(t);if(!(!e&&!n&&!r&&!s))return{...e?{title:e}:{},...n?{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}:{},...r?{readOnlyHint:!1,destructiveHint:s,idempotentHint:!1,openWorldHint:t==="shell-command"}:{}}}function Bg(t,e){return t.find(r=>r.name===e)?.description??""}function YU(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t))r&&typeof r=="object"&&(e[n]=r);return e}var Pt;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,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 r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=r,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(Pt||(Pt={}));var s0;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(s0||(s0={}));var Ee=Pt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ci=t=>{switch(typeof t){case"undefined":return Ee.undefined;case"string":return Ee.string;case"number":return Number.isNaN(t)?Ee.nan:Ee.number;case"boolean":return Ee.boolean;case"function":return Ee.function;case"bigint":return Ee.bigint;case"symbol":return Ee.symbol;case"object":return Array.isArray(t)?Ee.array:t===null?Ee.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Ee.promise:typeof Map<"u"&&t instanceof Map?Ee.map:typeof Set<"u"&&t instanceof Set?Ee.set:typeof Date<"u"&&t instanceof Date?Ee.date:Ee.object;default:return Ee.unknown}};var ie=Pt.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"]);var Cs=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(o){return o.message},r={_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)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),r}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,Pt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Cs.create=t=>new Cs(t);var eK=(t,e)=>{let n;switch(t.code){case ie.invalid_type:t.received===Ee.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case ie.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Pt.jsonStringifyReplacer)}`;break;case ie.unrecognized_keys:n=`Unrecognized key(s) in object: ${Pt.joinValues(t.keys,", ")}`;break;case ie.invalid_union:n="Invalid input";break;case ie.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Pt.joinValues(t.options)}`;break;case ie.invalid_enum_value:n=`Invalid enum value. Expected ${Pt.joinValues(t.options)}, received '${t.received}'`;break;case ie.invalid_arguments:n="Invalid function arguments";break;case ie.invalid_return_type:n="Invalid function return type";break;case ie.invalid_date:n="Invalid date";break;case ie.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Pt.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case ie.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case ie.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case ie.custom:n="Invalid input";break;case ie.invalid_intersection_types:n="Intersection results could not be merged";break;case ie.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case ie.not_finite:n="Number must be finite";break;default:n=e.defaultError,Pt.assertNever(t)}return{message:n}},ca=eK;var tK=ca;function $p(){return tK}var qg=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,o=[...n,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}};function _e(t,e){let n=$p(),r=qg({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===ca?void 0:ca].filter(s=>!!s)});t.common.issues.push(r)}var Ar=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return tt;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return tt;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:e.value,value:r}}},tt=Object.freeze({status:"aborted"}),Hl=t=>({status:"dirty",value:t}),qr=t=>({status:"valid",value:t}),Y_=t=>t.status==="aborted",ew=t=>t.status==="dirty",vc=t=>t.status==="valid",jp=t=>typeof Promise<"u"&&t instanceof Promise;var $e;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})($e||($e={}));var to=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,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}},o0=(t,e)=>{if(vc(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 n=new Cs(t.common.issues);return this._error=n,this._error}}};function mt(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))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??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:s}}var _t=class{get description(){return this._def.description}_getType(e){return Ci(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ci(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ar,ctx:{common:e.parent.common,data:e.data,parsedType:Ci(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(jp(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ci(e)},s=this._parseSync({data:e,path:r.path,parent:r});return o0(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ci(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return vc(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>vc(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ci(e)},s=this._parse({data:e,path:r.path,parent:r}),o=await(jp(s)?s:Promise.resolve(s));return o0(r,o)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:ie.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Co({schema:this,typeName:le.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:n=>this["~validate"](n)}}optional(){return As.create(this,this._def)}nullable(){return Ni.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ua.create(this)}promise(){return Rc.create(this,this._def)}or(e){return Gl.create([this,e],this._def)}and(e){return Jl.create(this,e,this._def)}transform(e){return new Co({...mt(this._def),schema:this,typeName:le.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new eu({...mt(this._def),innerType:this,defaultValue:n,typeName:le.ZodDefault})}brand(){return new Hg({typeName:le.ZodBranded,type:this,...mt(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new tu({...mt(this._def),innerType:this,catchValue:n,typeName:le.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Wg.create(this,e)}readonly(){return nu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},nK=/^c[^\s-]{8,}$/i,rK=/^[0-9a-z]+$/,sK=/^[0-9A-HJKMNP-TV-Z]{26}$/i,oK=/^[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,iK=/^[a-z0-9_-]{21}$/i,aK=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cK=/^[-+]?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)?)??$/,lK=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,uK="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",tw,dK=/^(?:(?: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])$/,pK=/^(?:(?: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])$/,fK=/^(([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]))$/,mK=/^(([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])$/,hK=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,gK=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,i0="((\\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])))",yK=new RegExp(`^${i0}$`);function a0(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function bK(t){return new RegExp(`^${a0(t)}$`)}function SK(t){let e=`${i0}T${a0(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function xK(t,e){return!!((e==="v4"||!e)&&dK.test(t)||(e==="v6"||!e)&&fK.test(t))}function _K(t,e){if(!aK.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function wK(t,e){return!!((e==="v4"||!e)&&pK.test(t)||(e==="v6"||!e)&&mK.test(t))}var Ul=class t extends _t{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Ee.string){let o=this._getOrReturnCtx(e);return _e(o,{code:ie.invalid_type,expected:Ee.string,received:o.parsedType}),tt}let r=new Ar,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.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?_e(s,{code:ie.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&_e(s,{code:ie.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")lK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"email",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")tw||(tw=new RegExp(uK,"u")),tw.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"emoji",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")oK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"uuid",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")iK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"nanoid",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")nK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"cuid",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")rK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"cuid2",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")sK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"ulid",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),_e(s,{validation:"url",code:ie.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"regex",code:ie.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.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),_e(s,{code:ie.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?SK(o).test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?yK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?bK(o).test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?cK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"duration",code:ie.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?xK(e.data,o.version)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"ip",code:ie.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?_K(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"jwt",code:ie.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?wK(e.data,o.version)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"cidr",code:ie.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?hK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"base64",code:ie.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?gK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"base64url",code:ie.invalid_string,message:o.message}),r.dirty()):Pt.assertNever(o);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:ie.invalid_string,...$e.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...$e.errToObj(e)})}url(e){return this._addCheck({kind:"url",...$e.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...$e.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...$e.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...$e.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...$e.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...$e.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...$e.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...$e.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...$e.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...$e.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...$e.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...$e.errToObj(e)})}datetime(e){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,...$e.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,...$e.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...$e.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...$e.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...$e.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...$e.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...$e.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...$e.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...$e.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...$e.errToObj(n)})}nonempty(e){return this.min(1,$e.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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Ul.create=t=>new Ul({checks:[],typeName:le.ZodString,coerce:t?.coerce??!1,...mt(t)});function vK(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}var Lp=class t extends _t{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)!==Ee.number){let o=this._getOrReturnCtx(e);return _e(o,{code:ie.invalid_type,expected:Ee.number,received:o.parsedType}),tt}let r,s=new Ar;for(let o of this._def.checks)o.kind==="int"?Pt.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.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)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?vK(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.not_finite,message:o.message}),s.dirty()):Pt.assertNever(o);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,$e.toString(n))}gt(e,n){return this.setLimit("min",e,!1,$e.toString(n))}lte(e,n){return this.setLimit("max",e,!0,$e.toString(n))}lt(e,n){return this.setLimit("max",e,!1,$e.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:$e.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:$e.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:$e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:$e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:$e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:$e.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:$e.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:$e.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:$e.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:$e.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Pt.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Lp.create=t=>new Lp({checks:[],typeName:le.ZodNumber,coerce:t?.coerce||!1,...mt(t)});var zp=class t extends _t{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)!==Ee.bigint)return this._getInvalidInput(e);let r,s=new Ar;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.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)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):Pt.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return _e(n,{code:ie.invalid_type,expected:Ee.bigint,received:n.parsedType}),tt}gte(e,n){return this.setLimit("min",e,!0,$e.toString(n))}gt(e,n){return this.setLimit("min",e,!1,$e.toString(n))}lte(e,n){return this.setLimit("max",e,!0,$e.toString(n))}lt(e,n){return this.setLimit("max",e,!1,$e.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:$e.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:$e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:$e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:$e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:$e.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:$e.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};zp.create=t=>new zp({checks:[],typeName:le.ZodBigInt,coerce:t?.coerce??!1,...mt(t)});var Bp=class extends _t{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Ee.boolean){let r=this._getOrReturnCtx(e);return _e(r,{code:ie.invalid_type,expected:Ee.boolean,received:r.parsedType}),tt}return qr(e.data)}};Bp.create=t=>new Bp({typeName:le.ZodBoolean,coerce:t?.coerce||!1,...mt(t)});var qp=class t extends _t{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Ee.date){let o=this._getOrReturnCtx(e);return _e(o,{code:ie.invalid_type,expected:Ee.date,received:o.parsedType}),tt}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return _e(o,{code:ie.invalid_date}),tt}let r=new Ar,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):Pt.assertNever(o);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:$e.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:$e.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};qp.create=t=>new qp({checks:[],coerce:t?.coerce||!1,typeName:le.ZodDate,...mt(t)});var Hp=class extends _t{_parse(e){if(this._getType(e)!==Ee.symbol){let r=this._getOrReturnCtx(e);return _e(r,{code:ie.invalid_type,expected:Ee.symbol,received:r.parsedType}),tt}return qr(e.data)}};Hp.create=t=>new Hp({typeName:le.ZodSymbol,...mt(t)});var Kl=class extends _t{_parse(e){if(this._getType(e)!==Ee.undefined){let r=this._getOrReturnCtx(e);return _e(r,{code:ie.invalid_type,expected:Ee.undefined,received:r.parsedType}),tt}return qr(e.data)}};Kl.create=t=>new Kl({typeName:le.ZodUndefined,...mt(t)});var Zl=class extends _t{_parse(e){if(this._getType(e)!==Ee.null){let r=this._getOrReturnCtx(e);return _e(r,{code:ie.invalid_type,expected:Ee.null,received:r.parsedType}),tt}return qr(e.data)}};Zl.create=t=>new Zl({typeName:le.ZodNull,...mt(t)});var Wp=class extends _t{constructor(){super(...arguments),this._any=!0}_parse(e){return qr(e.data)}};Wp.create=t=>new Wp({typeName:le.ZodAny,...mt(t)});var la=class extends _t{constructor(){super(...arguments),this._unknown=!0}_parse(e){return qr(e.data)}};la.create=t=>new la({typeName:le.ZodUnknown,...mt(t)});var Yo=class extends _t{_parse(e){let n=this._getOrReturnCtx(e);return _e(n,{code:ie.invalid_type,expected:Ee.never,received:n.parsedType}),tt}};Yo.create=t=>new Yo({typeName:le.ZodNever,...mt(t)});var Up=class extends _t{_parse(e){if(this._getType(e)!==Ee.undefined){let r=this._getOrReturnCtx(e);return _e(r,{code:ie.invalid_type,expected:Ee.void,received:r.parsedType}),tt}return qr(e.data)}};Up.create=t=>new Up({typeName:le.ZodVoid,...mt(t)});var ua=class t extends _t{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==Ee.array)return _e(n,{code:ie.invalid_type,expected:Ee.array,received:n.parsedType}),tt;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,a=n.data.length<s.exactLength.value;(i||a)&&(_e(n,{code:i?ie.too_big:ie.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}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(_e(n,{code:ie.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(_e(n,{code:ie.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new to(n,i,n.path,a)))).then(i=>Ar.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new to(n,i,n.path,a)));return Ar.mergeArray(r,o)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:$e.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:$e.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:$e.toString(n)}})}nonempty(e){return this.min(1,e)}};ua.create=(t,e)=>new ua({type:t,minLength:null,maxLength:null,exactLength:null,typeName:le.ZodArray,...mt(e)});function Wl(t){if(t instanceof Is){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=As.create(Wl(r))}return new Is({...t._def,shape:()=>e})}else return t instanceof ua?new ua({...t._def,type:Wl(t.element)}):t instanceof As?As.create(Wl(t.unwrap())):t instanceof Ni?Ni.create(Wl(t.unwrap())):t instanceof Ii?Ii.create(t.items.map(e=>Wl(e))):t}var Is=class t extends _t{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(),n=Pt.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==Ee.object){let l=this._getOrReturnCtx(e);return _e(l,{code:ie.invalid_type,expected:Ee.object,received:l.parsedType}),tt}let{status:r,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Yo&&this._def.unknownKeys==="strip"))for(let l in s.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=o[l],d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new to(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Yo){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")a.length>0&&(_e(s,{code:ie.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new to(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,p=await u.value;l.push({key:d,value:p,alwaysSet:u.alwaysSet})}return l}).then(l=>Ar.mergeObjectSync(r,l)):Ar.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return $e.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:$e.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:le.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of Pt.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of Pt.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Wl(this)}partial(e){let n={};for(let r of Pt.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of Pt.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof As;)o=o._def.innerType;n[r]=o}return new t({...this._def,shape:()=>n})}keyof(){return c0(Pt.objectKeys(this.shape))}};Is.create=(t,e)=>new Is({shape:()=>t,unknownKeys:"strip",catchall:Yo.create(),typeName:le.ZodObject,...mt(e)});Is.strictCreate=(t,e)=>new Is({shape:()=>t,unknownKeys:"strict",catchall:Yo.create(),typeName:le.ZodObject,...mt(e)});Is.lazycreate=(t,e)=>new Is({shape:t,unknownKeys:"strip",catchall:Yo.create(),typeName:le.ZodObject,...mt(e)});var Gl=class extends _t{_parse(e){let{ctx:n}=this._processInputParams(e),r=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 n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new Cs(a.ctx.common.issues));return _e(n,{code:ie.invalid_union,unionErrors:i}),tt}if(n.common.async)return Promise.all(r.map(async o=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of r){let l={...n,common:{...n.common,issues:[]},parent:null},u=c._parseSync({data:n.data,path:n.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new Cs(c));return _e(n,{code:ie.invalid_union,unionErrors:a}),tt}}get options(){return this._def.options}};Gl.create=(t,e)=>new Gl({options:t,typeName:le.ZodUnion,...mt(e)});var Ai=t=>t instanceof Vl?Ai(t.schema):t instanceof Co?Ai(t.innerType()):t instanceof Xl?[t.value]:t instanceof Ql?t.options:t instanceof Yl?Pt.objectValues(t.enum):t instanceof eu?Ai(t._def.innerType):t instanceof Kl?[void 0]:t instanceof Zl?[null]:t instanceof As?[void 0,...Ai(t.unwrap())]:t instanceof Ni?[null,...Ai(t.unwrap())]:t instanceof Hg||t instanceof nu?Ai(t.unwrap()):t instanceof tu?Ai(t._def.innerType):[],nw=class t extends _t{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ee.object)return _e(n,{code:ie.invalid_type,expected:Ee.object,received:n.parsedType}),tt;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(_e(n,{code:ie.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),tt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let o of n){let i=Ai(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:le.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...mt(r)})}};function rw(t,e){let n=Ci(t),r=Ci(e);if(t===e)return{valid:!0,data:t};if(n===Ee.object&&r===Ee.object){let s=Pt.objectKeys(e),o=Pt.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=rw(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===Ee.array&&r===Ee.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=rw(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===Ee.date&&r===Ee.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Jl=class extends _t{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(o,i)=>{if(Y_(o)||Y_(i))return tt;let a=rw(o.value,i.value);return a.valid?((ew(o)||ew(i))&&n.dirty(),{status:n.value,value:a.data}):(_e(r,{code:ie.invalid_intersection_types}),tt)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Jl.create=(t,e,n)=>new Jl({left:t,right:e,typeName:le.ZodIntersection,...mt(n)});var Ii=class t extends _t{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ee.array)return _e(r,{code:ie.invalid_type,expected:Ee.array,received:r.parsedType}),tt;if(r.data.length<this._def.items.length)return _e(r,{code:ie.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),tt;!this._def.rest&&r.data.length>this._def.items.length&&(_e(r,{code:ie.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new to(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>Ar.mergeArray(n,i)):Ar.mergeArray(n,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ii.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ii({items:t,typeName:le.ZodTuple,rest:null,...mt(e)})};var sw=class t extends _t{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ee.object)return _e(r,{code:ie.invalid_type,expected:Ee.object,received:r.parsedType}),tt;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new to(r,a,r.path,a)),value:i._parse(new to(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Ar.mergeObjectAsync(n,s):Ar.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof _t?new t({keyType:e,valueType:n,typeName:le.ZodRecord,...mt(r)}):new t({keyType:Ul.create(),valueType:e,typeName:le.ZodRecord,...mt(n)})}},Kp=class extends _t{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ee.map)return _e(r,{code:ie.invalid_type,expected:Ee.map,received:r.parsedType}),tt;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,c],l)=>({key:s._parse(new to(r,a,r.path,[l,"key"])),value:o._parse(new to(r,c,r.path,[l,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return tt;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return tt;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};Kp.create=(t,e,n)=>new Kp({valueType:e,keyType:t,typeName:le.ZodMap,...mt(n)});var Zp=class t extends _t{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ee.set)return _e(r,{code:ie.invalid_type,expected:Ee.set,received:r.parsedType}),tt;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(_e(r,{code:ie.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(_e(r,{code:ie.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return tt;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((c,l)=>o._parse(new to(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:$e.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:$e.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Zp.create=(t,e)=>new Zp({valueType:t,minSize:null,maxSize:null,typeName:le.ZodSet,...mt(e)});var ow=class t extends _t{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ee.function)return _e(n,{code:ie.invalid_type,expected:Ee.function,received:n.parsedType}),tt;function r(a,c){return qg({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,$p(),ca].filter(l=>!!l),issueData:{code:ie.invalid_arguments,argumentsError:c}})}function s(a,c){return qg({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,$p(),ca].filter(l=>!!l),issueData:{code:ie.invalid_return_type,returnTypeError:c}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Rc){let a=this;return qr(async function(...c){let l=new Cs([]),u=await a._def.args.parseAsync(c,o).catch(f=>{throw l.addIssue(r(c,f)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(f=>{throw l.addIssue(s(d,f)),l})})}else{let a=this;return qr(function(...c){let l=a._def.args.safeParse(c,o);if(!l.success)throw new Cs([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new Cs([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Ii.create(e).rest(la.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,n,r){return new t({args:e||Ii.create([]).rest(la.create()),returns:n||la.create(),typeName:le.ZodFunction,...mt(r)})}},Vl=class extends _t{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Vl.create=(t,e)=>new Vl({getter:t,typeName:le.ZodLazy,...mt(e)});var Xl=class extends _t{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return _e(n,{received:n.data,code:ie.invalid_literal,expected:this._def.value}),tt}return{status:"valid",value:e.data}}get value(){return this._def.value}};Xl.create=(t,e)=>new Xl({value:t,typeName:le.ZodLiteral,...mt(e)});function c0(t,e){return new Ql({values:t,typeName:le.ZodEnum,...mt(e)})}var Ql=class t extends _t{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return _e(n,{expected:Pt.joinValues(r),received:n.parsedType,code:ie.invalid_type}),tt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return _e(n,{received:n.data,code:ie.invalid_enum_value,options:r}),tt}return qr(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Ql.create=c0;var Yl=class extends _t{_parse(e){let n=Pt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Ee.string&&r.parsedType!==Ee.number){let s=Pt.objectValues(n);return _e(r,{expected:Pt.joinValues(s),received:r.parsedType,code:ie.invalid_type}),tt}if(this._cache||(this._cache=new Set(Pt.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=Pt.objectValues(n);return _e(r,{received:r.data,code:ie.invalid_enum_value,options:s}),tt}return qr(e.data)}get enum(){return this._def.values}};Yl.create=(t,e)=>new Yl({values:t,typeName:le.ZodNativeEnum,...mt(e)});var Rc=class extends _t{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ee.promise&&n.common.async===!1)return _e(n,{code:ie.invalid_type,expected:Ee.promise,received:n.parsedType}),tt;let r=n.parsedType===Ee.promise?n.data:Promise.resolve(n.data);return qr(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Rc.create=(t,e)=>new Rc({type:t,typeName:le.ZodPromise,...mt(e)});var Co=class extends _t{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===le.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{_e(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return tt;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?tt:c.status==="dirty"?Hl(c.value):n.value==="dirty"?Hl(c.value):c});{if(n.value==="aborted")return tt;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?tt:a.status==="dirty"?Hl(a.value):n.value==="dirty"?Hl(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(r.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(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?tt:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?tt:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!vc(i))return tt;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:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>vc(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):tt);Pt.assertNever(s)}};Co.create=(t,e,n)=>new Co({schema:t,typeName:le.ZodEffects,effect:e,...mt(n)});Co.createWithPreprocess=(t,e,n)=>new Co({schema:e,effect:{type:"preprocess",transform:t},typeName:le.ZodEffects,...mt(n)});var As=class extends _t{_parse(e){return this._getType(e)===Ee.undefined?qr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};As.create=(t,e)=>new As({innerType:t,typeName:le.ZodOptional,...mt(e)});var Ni=class extends _t{_parse(e){return this._getType(e)===Ee.null?qr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ni.create=(t,e)=>new Ni({innerType:t,typeName:le.ZodNullable,...mt(e)});var eu=class extends _t{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===Ee.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};eu.create=(t,e)=>new eu({innerType:t,typeName:le.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...mt(e)});var tu=class extends _t{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return jp(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Cs(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Cs(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};tu.create=(t,e)=>new tu({innerType:t,typeName:le.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...mt(e)});var Gp=class extends _t{_parse(e){if(this._getType(e)!==Ee.nan){let r=this._getOrReturnCtx(e);return _e(r,{code:ie.invalid_type,expected:Ee.nan,received:r.parsedType}),tt}return{status:"valid",value:e.data}}};Gp.create=t=>new Gp({typeName:le.ZodNaN,...mt(t)});var Hg=class extends _t{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Wg=class t extends _t{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?tt:o.status==="dirty"?(n.dirty(),Hl(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?tt:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:le.ZodPipeline})}},nu=class extends _t{_parse(e){let n=this._def.innerType._parse(e),r=s=>(vc(s)&&(s.value=Object.freeze(s.value)),s);return jp(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};nu.create=(t,e)=>new nu({innerType:t,typeName:le.ZodReadonly,...mt(e)});var Cae={object:Is.lazycreate},le;(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"})(le||(le={}));var Aae=Ul.create,Iae=Lp.create,Nae=Gp.create,Dae=zp.create,Oae=Bp.create,Mae=qp.create,Fae=Hp.create,$ae=Kl.create,jae=Zl.create,Lae=Wp.create,zae=la.create,Bae=Yo.create,qae=Up.create,Hae=ua.create,l0=Is.create,Wae=Is.strictCreate,Uae=Gl.create,Kae=nw.create,Zae=Jl.create,Gae=Ii.create,Jae=sw.create,Vae=Kp.create,Xae=Zp.create,Qae=ow.create,Yae=Vl.create,ece=Xl.create,tce=Ql.create,nce=Yl.create,rce=Rc.create,sce=Co.create,oce=As.create,ice=Ni.create,ace=Co.createWithPreprocess,cce=Wg.create;var RK=Object.freeze({status:"aborted"});function Y(t,e,n){function r(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(t),e(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let s=n?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function i(a){var c;let l=n?.Parent?new o:this;r(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Di=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ug={};function Ns(t){return t&&Object.assign(Ug,t),Ug}var Ct={};Yt(Ct,{BIGINT_FORMAT_RANGES:()=>d0,Class:()=>aw,NUMBER_FORMAT_RANGES:()=>mw,aborted:()=>Ec,allowsEval:()=>dw,assert:()=>CK,assertEqual:()=>kK,assertIs:()=>TK,assertNever:()=>PK,assertNotEqual:()=>EK,assignProp:()=>uw,cached:()=>Xp,captureStackTrace:()=>Zg,cleanEnum:()=>qK,cleanRegex:()=>Yp,clone:()=>Ds,createTransparentProxy:()=>MK,defineLazy:()=>ln,esc:()=>kc,escapeRegex:()=>da,extend:()=>jK,finalizeIssue:()=>Ao,floatSafeRemainder:()=>lw,getElementAtPath:()=>AK,getEnumValues:()=>Vp,getLengthableOrigin:()=>ef,getParsedType:()=>OK,getSizableOrigin:()=>p0,isObject:()=>ru,isPlainObject:()=>su,issue:()=>hw,joinValues:()=>Kg,jsonStringifyReplacer:()=>cw,merge:()=>LK,normalizeParams:()=>et,nullish:()=>Qp,numKeys:()=>DK,omit:()=>$K,optionalKeys:()=>fw,partial:()=>zK,pick:()=>FK,prefixIssues:()=>ei,primitiveTypes:()=>u0,promiseAllObject:()=>IK,propertyKeyTypes:()=>pw,randomString:()=>NK,required:()=>BK,stringifyPrimitive:()=>Gg,unwrapMessage:()=>Jp});function kK(t){return t}function EK(t){return t}function TK(t){}function PK(t){throw new Error}function CK(t){}function Vp(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function Kg(t,e="|"){return t.map(n=>Gg(n)).join(e)}function cw(t,e){return typeof e=="bigint"?e.toString():e}function Xp(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Qp(t){return t==null}function Yp(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function lw(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function ln(t,e,n){Object.defineProperty(t,e,{get(){{let s=n();return t[e]=s,s}throw new Error("cached value already set")},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function uw(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function AK(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function IK(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let s={};for(let o=0;o<e.length;o++)s[e[o]]=r[o];return s})}function NK(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function kc(t){return JSON.stringify(t)}var Zg=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function ru(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var dw=Xp(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function su(t){if(ru(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(ru(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function DK(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var OK=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}`)}},pw=new Set(["string","number","symbol"]),u0=new Set(["string","number","bigint","boolean","symbol","undefined"]);function da(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ds(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function et(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 MK(t){let e;return new Proxy({},{get(n,r,s){return e??(e=t()),Reflect.get(e,r,s)},set(n,r,s,o){return e??(e=t()),Reflect.set(e,r,s,o)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,s){return e??(e=t()),Reflect.defineProperty(e,r,s)}})}function Gg(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function fw(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var mw={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]},d0={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function FK(t,e){let n={},r=t._zod.def;for(let s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(n[s]=r.shape[s])}return Ds(t,{...t._zod.def,shape:n,checks:[]})}function $K(t,e){let n={...t._zod.def.shape},r=t._zod.def;for(let s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete n[s]}return Ds(t,{...t._zod.def,shape:n,checks:[]})}function jK(t,e){if(!su(e))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let r={...t._zod.def.shape,...e};return uw(this,"shape",r),r},checks:[]};return Ds(t,n)}function LK(t,e){return Ds(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return uw(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function zK(t,e,n){let r=e._zod.def.shape,s={...r};if(n)for(let o in n){if(!(o in r))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(s[o]=t?new t({type:"optional",innerType:r[o]}):r[o])}else for(let o in r)s[o]=t?new t({type:"optional",innerType:r[o]}):r[o];return Ds(e,{...e._zod.def,shape:s,checks:[]})}function BK(t,e,n){let r=e._zod.def.shape,s={...r};if(n)for(let o in n){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(s[o]=new t({type:"nonoptional",innerType:r[o]}))}else for(let o in r)s[o]=new t({type:"nonoptional",innerType:r[o]});return Ds(e,{...e._zod.def,shape:s,checks:[]})}function Ec(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function ei(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Jp(t){return typeof t=="string"?t:t?.message}function Ao(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let s=Jp(t.inst?._zod.def?.error?.(t))??Jp(e?.error?.(t))??Jp(n.customError?.(t))??Jp(n.localeError?.(t))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function p0(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ef(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function hw(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function qK(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var aw=class{constructor(...e){}};var f0=(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,cw,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Jg=Y("$ZodError",f0),tf=Y("$ZodError",f0,{Parent:Error});function gw(t,e=n=>n.message){let n={},r=[];for(let s of t.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}function yw(t,e){let n=e||function(o){return o.message},r={_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)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(t),r}var bw=t=>(e,n,r,s)=>{let o=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Di;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>Ao(c,o,Ns())));throw Zg(a,s?.callee),a}return i.value},Sw=bw(tf),xw=t=>async(e,n,r,s)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>Ao(c,o,Ns())));throw Zg(a,s?.callee),a}return i.value},_w=xw(tf),ww=t=>(e,n,r)=>{let s=r?{...r,async:!1}:{async:!1},o=e._zod.run({value:n,issues:[]},s);if(o instanceof Promise)throw new Di;return o.issues.length?{success:!1,error:new(t??Jg)(o.issues.map(i=>Ao(i,s,Ns())))}:{success:!0,data:o.value}},Tc=ww(tf),vw=t=>async(e,n,r)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},o=e._zod.run({value:n,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(i=>Ao(i,s,Ns())))}:{success:!0,data:o.value}},Pc=vw(tf);var m0=/^[cC][^\s-]{8,}$/,h0=/^[0-9a-z]+$/,g0=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,y0=/^[0-9a-vA-V]{20}$/,b0=/^[A-Za-z0-9]{27}$/,S0=/^[a-zA-Z0-9_-]{21}$/,x0=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var _0=/^([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})$/,Rw=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 w0=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var WK="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function v0(){return new RegExp(WK,"u")}var R0=/^(?:(?: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])$/,k0=/^(([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})$/,E0=/^((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])$/,T0=/^(([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])$/,P0=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kw=/^[A-Za-z0-9_-]*$/,C0=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var A0=/^\+(?:[0-9]){6,14}[0-9]$/,I0="(?:(?:\\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])))",N0=new RegExp(`^${I0}$`);function D0(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 O0(t){return new RegExp(`^${D0(t)}$`)}function M0(t){let e=D0({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${I0}T(?:${r})$`)}var F0=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var $0=/^\d+$/,j0=/^-?\d+(?:\.\d+)?/i,L0=/true|false/i,z0=/null/i;var B0=/^[^A-Z]*$/,q0=/^[^a-z]*$/;var br=Y("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),H0={number:"number",bigint:"bigint",object:"date"},Ew=Y("$ZodCheckLessThan",(t,e)=>{br.init(t,e);let n=H0[typeof e.value];t._zod.onattach.push(r=>{let s=r._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=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Tw=Y("$ZodCheckGreaterThan",(t,e)=>{br.init(t,e);let n=H0[typeof e.value];t._zod.onattach.push(r=>{let s=r._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=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),W0=Y("$ZodCheckMultipleOf",(t,e)=>{br.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):lw(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),U0=Y("$ZodCheckNumberFormat",(t,e)=>{br.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[s,o]=mw[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=s,a.maximum=o,n&&(a.pattern=$0)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,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:r,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:r,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 K0=Y("$ZodCheckMaxLength",(t,e)=>{var n;br.init(t,e),(n=t._zod.def).when??(n.when=r=>{let s=r.value;return!Qp(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{let s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let s=r.value;if(s.length<=e.maximum)return;let i=ef(s);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Z0=Y("$ZodCheckMinLength",(t,e)=>{var n;br.init(t,e),(n=t._zod.def).when??(n.when=r=>{let s=r.value;return!Qp(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{let s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let s=r.value;if(s.length>=e.minimum)return;let i=ef(s);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),G0=Y("$ZodCheckLengthEquals",(t,e)=>{var n;br.init(t,e),(n=t._zod.def).when??(n.when=r=>{let s=r.value;return!Qp(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{let s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=r=>{let s=r.value,o=s.length;if(o===e.length)return;let i=ef(s),a=o>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),nf=Y("$ZodCheckStringFormat",(t,e)=>{var n,r;br.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?(n=t._zod).check??(n.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})}):(r=t._zod).check??(r.check=()=>{})}),J0=Y("$ZodCheckRegex",(t,e)=>{nf.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),V0=Y("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=B0),nf.init(t,e)}),X0=Y("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=q0),nf.init(t,e)}),Q0=Y("$ZodCheckIncludes",(t,e)=>{br.init(t,e);let n=da(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(s=>{let o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),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})}}),Y0=Y("$ZodCheckStartsWith",(t,e)=>{br.init(t,e);let n=new RegExp(`^${da(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),eD=Y("$ZodCheckEndsWith",(t,e)=>{br.init(t,e);let n=new RegExp(`.*${da(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}});var tD=Y("$ZodCheckOverwrite",(t,e)=>{br.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var Xg=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 r=e.split(`
894
+ `);try{let ne=require("fs"),Re=require("path").resolve(__dirname,"..","..","mcp-pando-server","resources","messages.json");if(ne.existsSync(Re)){let Ge=JSON.parse(ne.readFileSync(Re,"utf8"))?.read_this_first;typeof Ge=="string"&&Ge.trim().length>0&&(K=Ge)}}catch{}Z={success:!0,help:{title:"read_this_first",body:K}};break}case"insert":{let{InsertCodeExecutor:q}=await Promise.resolve().then(()=>(hp(),TI)),K=s==="add-code"?{...e,op:"insert"}:e;Z=await q.execute(K,n,this.project);break}case"workspace-overview":Z=await Sh.execute(e,n,this.project);break;case"list-exports":Z=xh.execute(e,n,this.project);break;case"analyze-imports":Z=_h.execute(e,n,this.project);break;case"clojure-namespace-graph":Z=wh.execute(e,n,this.project);break;case"clojure-namespace-dependencies":Z=Fd.executeDependencies(e,n,this.project);break;case"clojure-namespace-dependents":Z=Fd.executeDependents(e,n,this.project);break;case"plan-clojure-namespace-move":Z=$d.executeMove(e,n,this.project);break;case"plan-clojure-namespace-rename":Z=$d.executeRename(e,n,this.project);break;case"move-clojure-namespace":Z=await jd.executeMove(e,n,this.project);break;case"rename-clojure-namespace":Z=await jd.executeRename(e,n,this.project);break;case"get-db-schema":Z=Ld.execute(e,n,this.project);break;case"query-db":Z=await vh.execute(e,n,this.project);break;case"delete":Z=await na.execute(e,n,this.project);break;case"find-references":Z=await cc.execute(e,n,this.project);break;case"find-callers":Z=await fp.execute(e,n,this.project);break;case"rename":Z=await sa.execute(e,n,this.project);break;case"filter-map-reduce":{let{FilterMapReduceExecutor:q}=await Promise.resolve().then(()=>(d_(),PI));Z=await q.execute(e,n,this.project);break}case"shell-command":Z=await this.handlePandoShellCommand(e,r);break;case"replace":{let q=s==="replace-body"?{...e,op:"replace",scope:"body"}:e;if(q.scope==="body"){let{ReplaceBodyExecutor:K}=await Promise.resolve().then(()=>(bp(),pg));Z=await K.execute(q,n,this.project)}else{let{ReplaceNodeExecutor:K}=await Promise.resolve().then(()=>(xp(),fg));Z=await K.execute(q,n,this.project)}break}case"add-exclude-dir":Z=await this.handleAddExcludeDir(e);break;case"remove-exclude-dir":Z=await this.handleRemoveExcludeDir(e);break;case"set-enabled-languages":Z=await this.handleSetEnabledLanguages(e);break;case"list-snapshots":Z=ko.listSnapshots(e,n,this.project);break;case"diff-snapshots":Z=ko.diffSnapshots(e,n,this.project);break;case"get-snapshot-trailers":Z=ko.getSnapshotTrailers(e,n,this.project);break;case"restore-snapshot":Z=await ko.restoreSnapshot(e,n,this.project);break;case"restore-files":Z=await ko.restoreFiles(e,n,this.project);break;case"change-signature":X("[OperationDispatch] entering ChangeSignatureExecutor",{op:o,targetPath:e?.path??null}),Z=await Sg.execute(e,n,this.project);break;case"get-project-root":Z=this.handleGetProjectRoot();break;default:try{let{AtomicExecutor:q}=await Promise.resolve().then(()=>(CN(),PN));Z=await q.execute(e,n,this.project,this)}catch{Z={success:!1,error:`Operation ${e.op} not implemented`}}}X("[OperationDispatch] executor returned",{op:o,success:!!Z?.success,error:Z?.error??null,errorCode:Z?.error_code??null,changedFiles:Array.isArray(Z?.details?.changedFiles)?Z.details.changedFiles.length:null,allChangedFiles:Array.isArray(Z?.details?.allChangedFiles)?Z.details.allChangedFiles.length:null});let ve=Date.now(),fe={executorMs:Math.max(0,ve-h)},ge=String(o||"").toLowerCase()==="delete"||!!e?.forceMayBreakSyntax;if(d&&Z&&!Z.success&&!we&&!Ne(e)){let q=Z.error_code;if((q==="would_introduce_syntax_error"||q==="validation_failed"||q==="io_write_failed")&&re){let ne=Array.isArray(Z.details?.changedFiles)?Z.details.changedFiles:[];if(ne.length>0)try{await ko.restoreSnapshot({op:"restore-snapshot",snapshotId:re,shouldCreateNewSnapshot:!1,restrictToPaths:ne},n,this.project),Z.details=Z.details||{},Z.details.rollbackAttempted=!0,Z.details.snapshotBefore=re}catch{}}}if(d&&Z&&Z.success&&!we&&!p){try{let q=Array.isArray(Z.details?.allChangedFiles)?Z.details.allChangedFiles:Array.isArray(Z.details?.changedFiles)?Z.details.changedFiles:[],K=Array.isArray(Z.details?.deletedFiles)?Z.details.deletedFiles:[];if((!q||q.length===0)&&(!K||K.length===0))return X("[OperationDispatch] skipping snapshot because no files changed",{op:o}),O(Z);let ne=Z.details?.receipt||{op:o,target:e.path||e.to||e.of,timestamp:Date.now(),changedFilesCount:q.length},{SnapshotService:ce}=await Promise.resolve().then(()=>(M_(),O_)),{SnapshotStatusTracker:Re}=await Promise.resolve().then(()=>(Za(),Ka)),be=Date.now();X("[SnapshotService] Starting snapshot",{files:q.length,deleted:K.length});try{Re.getInstance(this.projectPath).start(q.length,K.length)}catch{}let Ge=Z.details&&Z.details.trailers?Z.details.trailers:void 0,{snapshotId:Le,parentId:rt}=await ce.takeSnapshotNow(this.projectPath,q,o,ne,Ge,K,r);fe.snapshotMs=Date.now()-be,X("[SnapshotService] Snapshot finished",{durationMs:fe.snapshotMs,snapshotId:Le});try{Re.getInstance(this.projectPath).complete()}catch{}if(Z.snapshotBefore=rt||"<none>",Z.snapshotAfter=Le,Z.details||(Z.details={}),Z.details.receipt=ne,Z.details&&Z.details.trailers){let jt=Z.details.trailers,Oe={};for(let Be of Object.keys(jt)){let me=String(jt[Be]??"");Oe[Be]=me.length>200?me.slice(0,200):me}delete Z.details.trailers,Z.details.trailersPreview=Oe,Z.details.trailersNote="Trailers truncated to 200 chars. Use list-snapshots/get-snapshot-trailers to fetch full trailers."}}catch(q){return X("[OperationDispatch] snapshot finalization failed",{op:o,error:q?.message||String(q)}),O({success:!1,error:`Snapshot failure: ${q?.message||q}`})}if(!ge&&!f){let q=Array.isArray(Z.details?.allChangedFiles)?Z.details.allChangedFiles:Array.isArray(Z.details?.changedFiles)?Z.details.changedFiles:[];if(q.length>0){let K=Date.now(),ne=await this.validateChangedFiles(n,q,N);if(fe.validationMs=Date.now()-K,ne.skipped&&ne.warning&&(Z.warnings=Array.isArray(Z.warnings)?[...Z.warnings,ne.warning]:[ne.warning]),!ne.ok){let ce=Z.snapshotBefore,Re=Z.snapshotAfter;if(ce&&Re&&Re!=="<none>")try{await ko.restoreSnapshot({op:"restore-snapshot",snapshotId:ce,shouldCreateNewSnapshot:!1,deleteSnapshotId:Re,restrictToPaths:q},n,this.project)}catch{}return O({success:!1,error:ne.error||"Post-operation validation failed; changes rolled back.",details:{validation:ne,snapshotBefore:ce,snapshotAfter:Re,rollbackAttempted:!0}})}}}}d&&(Z?.success?this.recordRestoreFastPathState(o,Z):this.invalidateRestoreFastPathState("modifying-op-failed",{op:o??null,error:Z?.error??null}));try{if(d&&Z&&!we){let q=Date.now(),K=require("path"),ne=Array.isArray(Z.details?.allChangedFiles)?Z.details.allChangedFiles:Array.isArray(Z.details?.changedFiles)?Z.details.changedFiles:[],ce=Array.isArray(Z.details?.createdFiles)?Z.details.createdFiles:[],Re=Array.isArray(Z.details?.deletedFiles)?Z.details.deletedFiles:[],be=Be=>K.isAbsolute(Be)?Be:K.join(this.projectPath,Be),Ge=Be=>Array.from(new Set(Be.filter(Boolean))),Le=Ge(ce.map(be)),rt=new Set(Le),jt=Ge(ne.map(be)).filter(Be=>!rt.has(Be)),Oe=Ge(Re.map(be));(jt.length>0||Oe.length>0||Le.length>0)&&this.scheduleProjectSync({created:Le,modified:jt,deleted:Oe},`${String(o||s||"unknown")} post-write sync`).catch(Be=>{Bn("[RefreshFromDisk] post-op refresh failed",Be?.message||Be)}),fe.syncEnqueueMs=Date.now()-q}}catch(q){Bn("[RefreshFromDisk] post-op refresh failed",q?.message||q)}return X("[OperationDispatch] post-execution complete",{op:o,success:!!Z?.success,totalElapsedMs:Math.max(0,Date.now()-h),postExecutionMs:Math.max(0,Date.now()-ve),timings:fe,changedFiles:Array.isArray(Z?.details?.changedFiles)?Z.details.changedFiles.length:null,allChangedFiles:Array.isArray(Z?.details?.allChangedFiles)?Z.details.allChangedFiles.length:null}),O(Z)}finally{X("[OperationGate] releasing modifying op lock",{op:o??null,activeOp:this.modifyingOpName||null}),M()}}async refreshFilesFromDisk(e,n){let r=require("fs"),s=require("path"),o=a=>{try{return s.relative(this.projectPath,a).replace(/\\/g,"/")}catch{return a}};if(e=this.filterExcludedAbsolutePaths(e),!e.length)return;ut(n,"Workspace sync refresh cancelled"),this.refreshingInProgress=!0,this.refreshingFiles=e.map(o);let i=Date.now();try{for(let a of e){ut(n,"Workspace sync refresh cancelled");try{let c=r.existsSync(a),l=this.project.getSourceFile(a);if(!c){l&&this.project.removeSourceFile(l);continue}(l||this.project.addSourceFileAtPath(a)).refreshFromFileSystemSync()}catch(c){Bn("[RefreshFromDisk] Failed for",a,c?.message||c)}}}finally{let a=Date.now()-i;qn("code-engine.refreshFilesFromDisk.complete",{projectRoot:this.projectPath,files:e.length,sample:e.slice(0,20).map(o),elapsedMs:a}),X("[RefreshFromDisk] Completed",{files:e.length,ms:a}),this.refreshingInProgress=!1,this.refreshingFiles=[]}}scheduleProjectSync(e,n){let r=`project-sync:${Date.now().toString(36)}:${Math.random().toString(36).slice(2,8)}`,s=Date.now(),o=this.workspaceSyncController.signal;X("[ProjectSync] enqueue",{syncId:r,reason:n,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,hadPending:!!this.pendingProjectSync,pendingSyncId:this.pendingProjectSyncId??null,pendingReason:this.pendingProjectSyncReason??null});let i=async()=>{let l=Date.now();X("[ProjectSync] begin",{syncId:r,reason:n,queueWaitMs:l-s,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});try{if(await this.handleBatchFileChanges(e,{signal:o,source:"post-write-sync"}),o.aborted){X("[ProjectSync] superseded",{syncId:r,reason:n,durationMs:Date.now()-l,totalMs:Date.now()-s});return}X("[ProjectSync] complete",{syncId:r,reason:n,durationMs:Date.now()-l,totalMs:Date.now()-s})}catch(u){if(hi(u)||o.aborted){X("[ProjectSync] superseded",{syncId:r,reason:n,durationMs:Date.now()-l,totalMs:Date.now()-s,message:u?.message||String(u)});return}throw X("[ProjectSync] failed",{syncId:r,reason:n,durationMs:Date.now()-l,totalMs:Date.now()-s,message:u?.message||String(u)}),u}},a=(this.pendingProjectSync??Promise.resolve()).catch(l=>{if(hi(l)){X("[ProjectSync] previous queued refresh superseded",{syncId:r,reason:n,message:l?.message||String(l)});return}Bn("[ProjectSync] previous queued refresh failed",l?.message||l)}).then(i),c=Symbol(r);return this.pendingProjectSyncToken=c,this.pendingProjectSyncId=r,this.pendingProjectSyncEnqueuedAt=s,this.pendingProjectSyncReason=n,this.pendingProjectSync=a.finally(()=>{this.clearPendingProjectSyncState(c)}),this.pendingProjectSync}async awaitPendingProjectSync(e){let n=this.pendingProjectSync;if(!n)return;let r=Date.now();X("[ProjectSync] awaiting queued refresh before operation",{syncId:this.pendingProjectSyncId??null,operation:e??null,reason:this.pendingProjectSyncReason??null,queuedForMs:this.pendingProjectSyncEnqueuedAt?r-this.pendingProjectSyncEnqueuedAt:null});let s=setInterval(()=>{X("[ProjectSync] waiting",{syncId:this.pendingProjectSyncId??null,operation:e??null,reason:this.pendingProjectSyncReason??null,queuedForMs:this.pendingProjectSyncEnqueuedAt?Date.now()-this.pendingProjectSyncEnqueuedAt:null,waitedMs:Date.now()-r})},t.PROJECT_SYNC_HEARTBEAT_MS);s.unref?.();try{await n,X("[ProjectSync] awaited queued refresh complete",{syncId:this.pendingProjectSyncId??null,operation:e??null,reason:this.pendingProjectSyncReason??null,waitedMs:Date.now()-r})}finally{clearInterval(s)}}async awaitPostWriteWorkSettled(e="external"){let n=Date.now();X("[PostWriteDrain] begin",{reason:e,pendingProjectSync:!!this.pendingProjectSync,pendingProjectSyncId:this.pendingProjectSyncId??null,batchRunner:!!this.batchRunner,batchInProgress:this.batchInProgress,refreshingInProgress:this.refreshingInProgress});let r=setInterval(()=>{X("[PostWriteDrain] waiting",{reason:e,waitedMs:Date.now()-n,pendingProjectSync:!!this.pendingProjectSync,pendingProjectSyncId:this.pendingProjectSyncId??null,pendingProjectSyncReason:this.pendingProjectSyncReason??null,batchRunner:!!this.batchRunner,batchInProgress:this.batchInProgress,refreshingInProgress:this.refreshingInProgress,queuedBatch:this.describeQueuedBatch()})},t.PROJECT_SYNC_HEARTBEAT_MS);r.unref?.();try{for(;;){let s=this.pendingProjectSync;if(s){await s;continue}let o=this.batchRunner;if(o){await o;continue}if(!this.batchInProgress&&!this.refreshingInProgress&&!this.queuedBatch)break;await new Promise(i=>setTimeout(i,25))}}finally{clearInterval(r),X("[PostWriteDrain] complete",{reason:e,waitedMs:Date.now()-n,pendingProjectSync:!!this.pendingProjectSync,batchRunner:!!this.batchRunner,batchInProgress:this.batchInProgress,refreshingInProgress:this.refreshingInProgress})}}scheduleLspWorkspaceSync(e,n){let r=this.lspHost,s=r?.workspaceFilesChanged?.bind(r),o=e.created.length+e.modified.length+e.deleted.length;if(!s||o===0)return qn("code-engine.batch.workspaceFilesChanged.skipped",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,reason:s?"empty-batch":"no-lsp-host"}),Promise.resolve();qn("code-engine.batch.workspaceFilesChanged.scheduled",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,reason:n});let i=async()=>{let c=Date.now();qn("code-engine.batch.workspaceFilesChanged.start",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,createdSample:e.created.slice(0,20),modifiedSample:e.modified.slice(0,20),deletedSample:e.deleted.slice(0,20),reason:n});try{await s(e),qn("code-engine.batch.workspaceFilesChanged.complete",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:Date.now()-c,reason:n})}catch(l){qn("code-engine.batch.workspaceFilesChanged.failed",{projectRoot:this.projectPath,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,elapsedMs:Date.now()-c,error:l?.message||String(l),reason:n}),Bn("[LspWorkspaceSync] workspaceFilesChanged failed",l?.message||l)}},a=(this.pendingLspWorkspaceSync??Promise.resolve()).catch(c=>{Bn("[LspWorkspaceSync] previous queued sync failed",c?.message||c)}).then(i);return this.pendingLspWorkspaceSync=a.finally(()=>{this.pendingLspWorkspaceSync===a&&(this.pendingLspWorkspaceSync=null)}),this.pendingLspWorkspaceSync}withSnapshotReceipt(e,n,r){return{...r}}async handleBatchFileChanges(e,n){let r=n?.source??"external",s=n?.signal??this.workspaceSyncController.signal;if(X("batch-change event",{created:e.created.length,modified:e.modified.length,deleted:e.deleted.length,source:r,signalAborted:s.aborted}),e.created.length+e.modified.length+e.deleted.length===0)return;if(r!=="post-write-sync"&&this.invalidateRestoreFastPathState("batch-change",{source:r,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length}),s.aborted){X("[BatchQueue] skipped aborted batch",{source:r,created:e.created.length,modified:e.modified.length,deleted:e.deleted.length});return}let i={created:e.created.map(Ps),modified:e.modified.map(Ps),deleted:e.deleted.map(Ps)};qn("code-engine.batch.enqueue",{projectRoot:this.projectPath,created:i.created.length,modified:i.modified.length,deleted:i.deleted.length,createdSample:i.created.slice(0,20),modifiedSample:i.modified.slice(0,20),deletedSample:i.deleted.slice(0,20)});let a=`${ot(this.projectPath)}/`,c=i.deleted.find(u=>u.startsWith(a)&&u.endsWith(".db"));if(c&&!this.indexingInProgress){X("\u{1F504} Index DB deleted; triggering full reindex...",{file:c}),await this.startIndexing();return}let l=this.mergeQueuedBatch(i,r);X("[BatchQueue] enqueue",{incoming:{created:i.created.length,modified:i.modified.length,deleted:i.deleted.length},source:r,queued:l,indexingInProgress:this.indexingInProgress,batchInProgress:this.batchInProgress,runnerActive:!!this.batchRunner}),!this.indexingInProgress&&await this.ensureBatchRunner()}}});var si=B(require("path")),AL=B(require("os"));uS();Ls();dt();var Cp=class{constructor(e){this.options=e;this.workspaceRoots=new Set;this.explicitProjectRoot=null;this.registeredRoots=new Set}getWorkspaceRoots(){return Array.from(this.workspaceRoots).sort((e,n)=>e.localeCompare(n))}getExplicitProjectRoot(){return this.explicitProjectRoot}getRegisteredRoots(){return Array.from(this.registeredRoots).sort((e,n)=>e.localeCompare(n))}async setWorkspaceRoots(e,n){return this.workspaceRoots=new Set(e.map(r=>this.options.normalizeRoot(r)).filter(r=>!!r)),this.refreshEffectiveRoots(n)}async setProjectRoot(e,n){let r=Date.now();W("ProjectRootManager","setProjectRoot begin",{rootOrPath:e,currentExplicitRoot:this.explicitProjectRoot,opts:n});let s=this.options.normalizeRoot(e);if(!s)return W("ProjectRootManager","setProjectRoot normalized to null",{rootOrPath:e,elapsedMs:Date.now()-r}),null;let o=this.options.resolveIndexRoot(s);return o?this.explicitProjectRoot===o?(W("ProjectRootManager","setProjectRoot no-op",{rootOrPath:e,resolvedInput:s,targetDir:o,elapsedMs:Date.now()-r}),o):(this.explicitProjectRoot=o,await this.refreshEffectiveRoots(n),W("ProjectRootManager","setProjectRoot complete",{rootOrPath:e,resolvedInput:s,targetDir:o,registeredRoots:this.getRegisteredRoots(),elapsedMs:Date.now()-r}),o):(W("ProjectRootManager","setProjectRoot resolveIndexRoot returned null",{rootOrPath:e,resolvedInput:s,elapsedMs:Date.now()-r}),null)}async refreshEffectiveRoots(e){let n=Date.now(),r=this.explicitProjectRoot?new Set([this.explicitProjectRoot]):new Set(this.workspaceRoots),s=new Set(this.registeredRoots),o=[];W("ProjectRootManager","refreshEffectiveRoots begin",{effective:Array.from(r),registeredBefore:Array.from(s),opts:e});for(let i of r){if(this.registeredRoots.has(i))continue;let a=Date.now(),c=await this.options.registerRoot(i);W("ProjectRootManager","refreshEffectiveRoots registerRoot resolved",{requestedRoot:i,registered:c,elapsedMs:Date.now()-a}),c&&(this.registeredRoots.add(c),o.push(c))}for(let i of s)r.has(i)||(this.options.disposeRoot(i),this.registeredRoots.delete(i));if(e?.indexNewRoots&&this.options.startIndexingForRoot)for(let i of o)W("ProjectRootManager","refreshEffectiveRoots startIndexingForRoot dispatch",{root:i}),this.options.startIndexingForRoot(i);return W("ProjectRootManager","refreshEffectiveRoots complete",{newlyRegistered:o,finalRoots:this.getRegisteredRoots(),elapsedMs:Date.now()-n}),{newlyRegistered:o,finalRoots:this.getRegisteredRoots()}}};Ls();Da();var NN=B(require("os")),Qo=B(require("path"));ir();Rd();Ha();var B_=5e4,gU=1*1024*1024,Og="PANDO_ALLOW_BROAD_ROOT_INDEXING",yU=new Set(["applications","code","desktop","developer","documents","downloads","dropbox","github","google drive","icloud drive","library","movies","music","onedrive","pictures","projects","public","repos","repositories","src","videos","workspace","workspaces"]),bU=new Set(["code","developer","github","projects","repos","repositories","src","workspace","workspaces"]);function DN(t,e){let n=typeof e?.limit=="number"&&Number.isFinite(e.limit)?Math.max(1,Math.trunc(e.limit)):B_,r=SU(t,{env:e?.env,homeDir:e?.homeDir});if(r)return{root:t,candidateIndexableFiles:0,limit:n,exceeded:!0,reason:"broad-root",message:r};let s=e?.languageSupport,o=mo(t),i=bd(s),a=hs(t,o),c=KP(t,i,{shouldExclude:a,maxFileBytes:gU,limit:n});return{root:t,candidateIndexableFiles:c.count,limit:n,exceeded:c.limitExceeded,...c.limitExceeded?{reason:"file-count-limit"}:{}}}function ON(t){if(t.reason==="broad-root")return new Error(`Refusing to auto-index '${t.root}': ${t.message??"it is a broad filesystem location"}. Choose a narrower project folder, or set ${Og}=1 to override.`);let e=t.exceeded?"at least":"exactly";return new Error(`Refusing to index '${t.root}': candidate_indexable_files is ${e} ${t.candidateIndexableFiles}, above the limit of ${t.limit}. Choose a narrower root or add excludes before retrying.`)}function SU(t,e){let n=e?.env??process.env;if(/^(1|true|yes)$/i.test(n[Og]||""))return null;let r=Qo.default.resolve(t),s=Qo.default.parse(r);if(Dg(r)===Dg(s.root))return"it is the filesystem root";let o=Dg(Qo.default.resolve(e?.homeDir??NN.default.homedir())),i=Dg(r);if(i===o)return"it is the user home directory";let a=Qo.default.relative(o,i);if(!a||a.startsWith("..")||Qo.default.isAbsolute(a))return null;let c=a.split(Qo.default.sep).filter(Boolean);return c.length===1&&yU.has(c[0].toLowerCase())?`it is the broad home folder '${c[0]}'`:c.length===2&&c[0].toLowerCase()==="documents"&&bU.has(c[1].toLowerCase())?`it is the broad project collection folder '${c.join(Qo.default.sep)}'`:null}function Dg(t){let e=Qo.default.parse(t),n=Qo.default.resolve(t);for(;n.length>e.root.length&&/[\\/]$/.test(n);)n=n.slice(0,-1);return n}Qt();dt();var Ap=class t{constructor(e,n){this.options=n;this.indexingSuppressedRoots=new Set;this.indexingSuppressionReasons=new Map;this.rootManager=new Cp({normalizeRoot:r=>{let s=r.trim();return s?vt(s):null},resolveIndexRoot:r=>r,registerRoot:async r=>{let s=Date.now();W("DirectProjectRootManager","registerRoot begin",{root:r,hasOptions:!!this.options});let o=this.getOptionsForRoot(r);return o&&Dn.setEngineOptions(r,o),Dn.getEngine(r,o),W("DirectProjectRootManager","registerRoot complete",{root:r,elapsedMs:Date.now()-s}),r},disposeRoot:r=>{W("DirectProjectRootManager","disposeRoot",{root:r}),Dn.clearEngine(r)},startIndexingForRoot:async r=>{let s=Date.now();if(W("DirectProjectRootManager","startIndexingForRoot begin",{root:r}),this.indexingSuppressedRoots.has(vt(r))){W("DirectProjectRootManager","startIndexingForRoot skipped (root over indexing limit)",{root:r});return}let o=Dn.getEngine(r,this.getOptionsForRoot(r));typeof o?.startIndexing=="function"&&await o.startIndexing(),W("DirectProjectRootManager","startIndexingForRoot dispatched",{root:r,elapsedMs:Date.now()-s})}}),this.initialRoot=e}static async create(e,n){let r=new t(e,n);return await r.validateProjectRoot(e),await r.rootManager.setWorkspaceRoots([e]),r}getProjectRoot(){let e=this.rootManager.getExplicitProjectRoot();return e||(this.rootManager.getRegisteredRoots()[0]??null)}getEngine(){let e=this.getProjectRoot();if(!e)throw new Error("No project root configured.");return Dn.getEngine(e,this.getOptionsForRoot(e))}async validateProjectRoot(e){let n=e.trim();if(!n)return null;let r=vt(n),s=DN(r,{languageSupport:this.getOptionsForRoot(r)?.languageSupport,limit:this.indexingLimitOverride});if(s.exceeded){this.indexingSuppressedRoots.add(r);let o=ON(s).message;this.indexingSuppressionReasons.set(r,o),W("DirectProjectRootManager","validateProjectRoot indexing suppressed",{root:r,candidateIndexableFiles:s.candidateIndexableFiles,limit:s.limit,suppressionReason:s.reason??null,reason:o})}else this.indexingSuppressedRoots.delete(r),this.indexingSuppressionReasons.delete(r);return r}isIndexingSuppressed(e){return this.indexingSuppressedRoots.has(vt(e))}getIndexingSuppressionReason(e){return this.indexingSuppressionReasons.get(vt(e))}setIndexingLimitOverrideForTesting(e){this.indexingLimitOverride=e}async setProjectRoot(e){let n=Date.now();W("DirectProjectRootManager","setProjectRoot begin",{root:e}),await this.validateProjectRoot(e);let r=await this.rootManager.setProjectRoot(e,{indexNewRoots:!0});return W("DirectProjectRootManager","setProjectRoot complete",{root:e,resolved:r,elapsedMs:Date.now()-n}),r}updateRootOptions(e,n){let r=vt(e),s=n??this.getOptionsForRoot(r);s&&Dn.setEngineOptions(r,s)}getOptionsForRoot(e){let n=vt(e),r=this.options?.languageSupport??Na(n),s=this.options?.lspHost;if(!(!r&&!s))return{...r?{languageSupport:r}:{},...s?{lspHost:s}:{}}}};Go();Rh();Da();ir();ho();xo();var xU=B(require("fs")),_U=B(require("path"));Ph();var BN=require("events");Rh();Ph();ir();Da();Ls();Qt();var jN=require("child_process");Ls();kr();dt();var q_=require("child_process"),xc=null,Ip=null;async function FN(t){return xc||Ip||(Ip=Promise.resolve().then(()=>{let e=MN();if(e.available)return xc=e,e;let n=vU(),r=e.error;for(let s of n){t?.(`[NodeFileWatcher] watchman missing; trying install via ${s.label}`);let o=wU(s),i=MN();if(i.available)return xc={available:!0,version:i.version,installAttempted:!0,installSucceeded:!0,installMethod:s.label},xc;r=o.error??i.error??r}return xc={available:!1,installAttempted:n.length>0,installSucceeded:!1,error:r},xc}).finally(()=>{Ip=null}),Ip)}function MN(){let t=(0,q_.spawnSync)("watchman",["--version"],{encoding:"utf8",stdio:"pipe",shell:process.platform==="win32"});return t.status===0?{available:!0,version:`${t.stdout||t.stderr||""}`.trim()||void 0,installAttempted:!1,installSucceeded:!1}:{available:!1,installAttempted:!1,installSucceeded:!1,error:$N(t.error,t.stderr,t.stdout)}}function wU(t){for(let e of t.steps){let n=(0,q_.spawnSync)(e.cmd,e.args,{encoding:"utf8",stdio:"pipe",shell:process.platform==="win32"});if(n.status!==0)return{ok:!1,error:$N(n.error,n.stderr,n.stdout)}}return{ok:!0}}function vU(){let t=typeof process.getuid=="function"?process.getuid()===0:!1,e=(n,r)=>t?{cmd:n,args:r}:{cmd:"sudo",args:["-n",n,...r]};switch(process.platform){case"darwin":return[{label:"homebrew",steps:[{cmd:"brew",args:["install","watchman"]}]},{label:"macports",steps:[e("port",["install","watchman"])]}];case"linux":return[{label:"homebrew",steps:[{cmd:"brew",args:["install","watchman"]}]},{label:"apt",steps:[e("apt-get",["update"]),e("apt-get",["install","-y","watchman"])]},{label:"dnf",steps:[e("dnf",["install","-y","watchman"])]},{label:"pacman",steps:[e("pacman",["-S","--noconfirm","watchman"])]}];case"win32":return[{label:"chocolatey",steps:[{cmd:"choco",args:["install","watchman","-y"]}]},{label:"winget",steps:[{cmd:"winget",args:["install","--id","Facebook.Watchman","-e"]}]}];default:return[]}}function $N(t,e,n){if(t instanceof Error&&t.message)return t.message;let r=`${e??""}`.trim();return r||`${n??""}`.trim()||void 0}function Hn(t,e){if(!Vt())return;let n=e&&typeof e=="object"&&!Array.isArray(e)?{pid:process.pid,...e}:{pid:process.pid,details:e};W("WatcherTrace",t,n)}var Mg=class{constructor(e){this.log=e;this.projectRoot=null;this.languageSupport=null;this.watcherChild=null;this.watcherGeneration=0;this.shutdownGraceMs=1e3;this.switchChain=Promise.resolve()}async activate(e,n){this.languageSupport=n,await this.updateProjectRoot(e,n)}async updateProjectRoot(e,n){if(n&&(this.languageSupport=n),!e||!this.languageSupport||e===this.projectRoot&&!n)return;let r=this.languageSupport,s=this.switchChain.catch(()=>{}).then(async()=>{let o=this.projectRoot,i=this.watcherChild,a=this.watcherGeneration+1;this.log(`[NodeFileWatcher] updateProjectRoot begin from=${o??"null"} to=${e}`),Hn("node-watcher.updateProjectRoot.begin",{fromRoot:o,toRoot:e,previousGeneration:i?.generation??null,hasWatcher:!!i}),i&&(Hn("node-watcher.updateProjectRoot.await-previous-exit",{fromRoot:o,toRoot:e,previousGeneration:i.generation,childPid:i.process.pid??null}),await this.shutdownChild(i,"root-switch"));let c=await FN(this.log);Hn("node-watcher.watchman.status",{root:e,generation:a,available:c.available,version:c.version,installAttempted:c.installAttempted,installSucceeded:c.installSucceeded,installMethod:c.installMethod,error:c.error});let l=this.spawnWatcherChild(e,r,a,c);this.projectRoot=e,this.watcherChild=l,this.watcherGeneration=a,Hn("node-watcher.updateProjectRoot.complete",{fromRoot:o,toRoot:e,generation:a,childPid:l.process.pid??null,scriptPath:l.scriptPath})});this.switchChain=s,await s}async dispose(){let e=this.switchChain.catch(()=>{}).then(async()=>{let n=this.watcherChild,r=this.projectRoot,s=this.watcherGeneration;this.projectRoot=null,this.watcherChild=null,n&&(Hn("node-watcher.dispose",{root:r,generation:s,childPid:n.process.pid??null}),await this.shutdownChild(n,"dispose"))});this.switchChain=e,await e}spawnWatcherChild(e,n,r,s){let o=KT();if(!o)throw new Error("Could not resolve watcher child process script");this.log(`[NodeFileWatcher] activate root=${e}`),Hn("node-watcher.spawn.start",{root:e,generation:r,scriptPath:o});let i=(0,jN.fork)(o,[],{cwd:e,env:{...process.env,PANDO_WATCH_ROOT:e,PANDO_WATCH_GENERATION:String(r),PANDO_WATCH_LANGUAGE_SUPPORT_JSON:JSON.stringify(n),PANDO_WATCH_WATCHMAN_AVAILABLE:s.available?"1":"0",PANDO_WATCH_WATCHMAN_INSTALL_ATTEMPTED:s.installAttempted?"1":"0",PANDO_WATCH_WATCHMAN_INSTALL_SUCCEEDED:s.installSucceeded?"1":"0"},stdio:["ignore","inherit","inherit","ipc"]}),a=()=>{},c=new Promise(u=>{a=u}),l={process:i,root:e,generation:r,scriptPath:o,shutdownTimer:null,shuttingDown:!1,exitPromise:c,resolveExit:a};return i.on("message",u=>{this.handleChildMessage(l,u)}),i.on("exit",(u,d)=>{l.shutdownTimer&&(clearTimeout(l.shutdownTimer),l.shutdownTimer=null),Hn("node-watcher.child.exit",{root:l.root,generation:l.generation,childPid:i.pid??null,code:u,signal:d,shuttingDown:l.shuttingDown}),this.watcherChild===l&&(this.watcherChild=null),l.resolveExit()}),i.on("error",u=>{let d=u instanceof Error?u.message:String(u);this.log(`[NodeFileWatcher] watcher child error root=${e} error=${d}`),Hn("node-watcher.child.error",{root:e,generation:r,childPid:i.pid??null,error:d})}),Hn("node-watcher.spawn.complete",{root:e,generation:r,scriptPath:o,childPid:i.pid??null}),l}async handleChildMessage(e,n){if(!(!n||typeof n!="object"))switch(n.type){case"ready":this.handleReadyMessage(e,n);return;case"error":this.handleErrorMessage(e,n);return;case"batch":await this.handleBatchMessage(e,n);return;default:return}}handleReadyMessage(e,n){if(!this.isActiveChild(e)){Hn("node-watcher.ready.stale",{root:n.root,generation:n.generation,activeRoot:this.projectRoot,activeGeneration:this.watcherGeneration});return}this.log(`[NodeFileWatcher] ready root=${n.root} watchRoots=${n.watchRootCount??0} backend=${n.backendPreference??"native"}`),Hn("node-watcher.ready",{root:n.root,generation:n.generation,childPid:e.process.pid??null,watchRootCount:n.watchRootCount,backendPreference:n.backendPreference,watchmanAvailable:n.watchmanAvailable,watchmanInstallAttempted:n.watchmanInstallAttempted,watchmanInstallSucceeded:n.watchmanInstallSucceeded})}handleErrorMessage(e,n){let r=!this.isActiveChild(e);this.log(`[NodeFileWatcher] watch error path=${n.root} error=${n.error}`),Hn(r?"node-watcher.error.stale":"node-watcher.error",{root:n.root,generation:n.generation,childPid:e.process.pid??null,activeRoot:this.projectRoot,activeGeneration:this.watcherGeneration,error:n.error})}async handleBatchMessage(e,n){if(!this.isActiveChild(e)){Hn("node-watcher.batch.stale",{root:n.root,generation:n.generation,batchId:n.batchId,activeRoot:this.projectRoot,activeGeneration:this.watcherGeneration}),this.sendToChild(e,{type:"batch-ack",batchId:n.batchId,ok:!0});return}let r=Dn.getExistingEngine(n.root);if(Hn("node-watcher.batch.start",{root:n.root,generation:n.generation,batchId:n.batchId,childPid:e.process.pid??null,created:n.changes.created.length,modified:n.changes.modified.length,deleted:n.changes.deleted.length,hasEngine:!!r,hasBatchHandler:typeof r?.handleBatchFileChanges=="function"}),!r||typeof r.handleBatchFileChanges!="function"){this.sendToChild(e,{type:"batch-ack",batchId:n.batchId,ok:!1,error:`No batch handler available for root ${n.root}`});return}try{await r.handleBatchFileChanges(n.changes),Hn("node-watcher.batch.complete",{root:n.root,generation:n.generation,batchId:n.batchId,childPid:e.process.pid??null}),this.sendToChild(e,{type:"batch-ack",batchId:n.batchId,ok:!0})}catch(s){let o=s instanceof Error?s.message:String(s);Hn("node-watcher.batch.failed",{root:n.root,generation:n.generation,batchId:n.batchId,childPid:e.process.pid??null,error:o}),this.sendToChild(e,{type:"batch-ack",batchId:n.batchId,ok:!1,error:o})}}isActiveChild(e){return this.watcherChild===e&&this.projectRoot===e.root&&this.watcherGeneration===e.generation}sendToChild(e,n){try{e.process.send?.(n)}catch(r){Hn("node-watcher.child.send.failed",{root:e.root,generation:e.generation,childPid:e.process.pid??null,messageType:n.type,error:r instanceof Error?r.message:String(r)})}}async shutdownChild(e,n){if(e.shuttingDown){await e.exitPromise;return}e.shuttingDown=!0,Hn("node-watcher.child.shutdown.begin",{root:e.root,generation:e.generation,childPid:e.process.pid??null,reason:n}),this.sendToChild(e,{type:"shutdown",reason:n}),e.shutdownTimer=setTimeout(()=>{Hn("node-watcher.child.shutdown.force-kill",{root:e.root,generation:e.generation,childPid:e.process.pid??null,reason:n,graceMs:this.shutdownGraceMs});try{e.process.kill("SIGKILL")}catch(r){Hn("node-watcher.child.shutdown.force-kill.failed",{root:e.root,generation:e.generation,childPid:e.process.pid??null,reason:n,error:r instanceof Error?r.message:String(r)})}},this.shutdownGraceMs),await e.exitPromise}};var LN=zN();function zN(){return process.env.PANDO_RUNTIME_HOST==="vscode-extension"||process.env.VSCODE_PID||process.env.VSCODE_IPC_HOOK||process.env.VSCODE_CWD?"vscode-extension":process.env.PANDO_RUNTIME_HOST==="standalone-cli"?"standalone-cli":"unknown"}function H_(t){LN=t,process.env.PANDO_RUNTIME_HOST=t}function W_(){return LN==="vscode-extension"}kr();Ls();async function U_(t){let e=Dn.getEngine(t),n={root:t,isIndexing:typeof e?.isIndexingInProgress=="function"?!!e.isIndexingInProgress():!1};try{let r=await e.execute({op:"workspace-overview"});if(!r?.success)return n;let s=r.indexing??{};return{root:t,isIndexing:!!(s.isIndexing??n.isIndexing),progress:typeof s.progress=="number"?s.progress:void 0,totalFiles:typeof s.totalFiles=="number"?s.totalFiles:void 0,filesProcessed:typeof s.filesProcessed=="number"?s.filesProcessed:void 0,filesIndexed:typeof s.filesIndexed=="number"?s.filesIndexed:void 0,filesSkipped:typeof s.filesSkipped=="number"?s.filesSkipped:void 0,filesFailed:typeof s.filesFailed=="number"?s.filesFailed:void 0,message:typeof s.message=="string"?s.message:void 0}}catch{return n}}dt();var Np=class t extends BN.EventEmitter{constructor(n,r){super();this.rootManager=n;this.options=r;this.watcher=null}static async create(n){Bs()||Ma(process.cwd(),n.runtimePaths);let r=await Ap.create(n.initialRoot,{languageSupport:n.languageSupport,lspHost:n.lspHost}),s=new t(r,{...n});return s.warnIfIndexingSuppressed(r.getProjectRoot()),await s.configureWatcher(),s}warnIfIndexingSuppressed(n){if(!n||!this.rootManager.isIndexingSuppressed(n))return;let r=this.rootManager.getIndexingSuppressionReason(n)??`Refusing to auto-index '${n}': it has too many files to index safely.`;this.options.log?.(`indexing is OFF for '${n}': ${r} Pando is running but its code-graph tools will be empty here. Set the project root to a narrower folder, add excludes for large roots, or set ${Og}=1 before launch to override broad-root suppression. The file-count safety limit is ${B_.toLocaleString()} candidate files.`)}getProjectRoot(){return this.rootManager.getProjectRoot()}getRoots(){let n=this.getProjectRoot();return n?[n]:[]}getEngine(){return this.rootManager.getEngine()}async setProjectRoot(n){let r=this.getProjectRoot(),s=vt(n),o=Date.now();if(W("PandoRuntime","setProjectRoot begin",{requestedRoot:n,currentRoot:r,nextRoot:s}),await this.rootManager.validateProjectRoot(n),this.warnIfIndexingSuppressed(s),r===s)return W("PandoRuntime","setProjectRoot no-op",{requestedRoot:n,currentRoot:r,nextRoot:s,elapsedMs:Date.now()-o}),r;if(r&&r!==s){let c=Dn.getExistingEngine(r),l=`project root switching from ${r} to ${s}`,u=(p,f,m)=>{W("PandoRuntime",`setProjectRoot phase:${p}`,{requestedRoot:n,currentRoot:r,nextRoot:s,elapsedMs:Date.now()-f,...m})},d=Date.now();try{c?.cancelActiveOperations?.("project root switching")}catch{}u("cancelActiveOperations",d,{hasEngine:!!c}),d=Date.now();try{c?.cancelIndexing?.("project root switching")}catch{}u("cancelIndexing",d),d=Date.now();try{Dn.resetEngine(r)}catch{}u("resetEngine",d),d=Date.now(),Th(),u("shutdownActiveStreamingIndexers",d),d=Date.now(),await go.shutdownAllShared({force:!0,reason:l}).catch(()=>{}),u("shutdownAllShared(force)",d),d=Date.now(),Va(l),u("shutdownSharedWorkers",d)}let i=Date.now(),a=await this.rootManager.setProjectRoot(n);if(W("PandoRuntime","setProjectRoot rootManager resolved",{requestedRoot:n,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-i}),a){let c=Date.now();W("PandoRuntime","setProjectRoot watcher.updateProjectRoot begin",{requestedRoot:n,currentRoot:r,nextRoot:s,resolved:a,hasWatcher:!!this.watcher}),this.rootManager.isIndexingSuppressed(a)?W("PandoRuntime","setProjectRoot watcher skipped (root over indexing limit)",{requestedRoot:n,resolved:a}):await this.watcher?.updateProjectRoot(a,this.resolveLanguageSupport(a)),W("PandoRuntime","setProjectRoot watcher.updateProjectRoot complete",{requestedRoot:n,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-c});let l=Date.now();W("PandoRuntime","setProjectRoot emit rootChanged begin",{requestedRoot:n,currentRoot:r,nextRoot:s,resolved:a}),this.emit("rootChanged",a),W("PandoRuntime","setProjectRoot emit rootChanged complete",{requestedRoot:n,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-l})}return W("PandoRuntime","setProjectRoot complete",{requestedRoot:n,currentRoot:r,nextRoot:s,resolved:a,elapsedMs:Date.now()-o}),a}async startIndexing(){let n=this.getProjectRoot();if(!n)return;if(this.rootManager.isIndexingSuppressed(n)){W("PandoRuntime","startIndexing skipped (root over indexing limit)",{root:n}),this.emit("indexing",{root:n,isIndexing:!1});return}let r=this.rootManager.getEngine();this.emit("indexing",{root:n,isIndexing:!0}),await r.startIndexing?.(),await r.waitForInitialSnapshot?.()}shouldScheduleBackgroundIndexing(){let n=this.getProjectRoot();if(!n||this.rootManager.isIndexingSuppressed(n))return!1;let r=this.rootManager.getEngine();return typeof r?.shouldScheduleBackgroundIndexing=="function"?!!r.shouldScheduleBackgroundIndexing():!0}async getIndexingStatus(){let n=this.getProjectRoot();return n?U_(n):null}async getWorkspaceOverview(){let n=this.getProjectRoot();if(!n)return null;let r=this.rootManager.getEngine();try{let s=await r.execute({op:"workspace-overview"});if(!s?.success)return null;let o=s.nodes??{},i=ss(o.functions),a=ss(o.classes),c=ss(o.interfaces),l=ss(o.types),u=ss(o.enums),d=ss(o.variables),p=[i,a,c,l,u,d].filter(f=>typeof f=="number").reduce((f,m)=>f+m,0);return{root:n,files:{total:ss(s.files?.total),testFiles:ss(s.files?.testFiles)},nodes:{total:p||void 0,functions:i,classes:a,interfaces:c,types:l,enums:u,variables:d},indexing:{root:n,isIndexing:!!s.indexing?.isIndexing,totalFiles:ss(s.indexing?.totalFiles),filesProcessed:ss(s.indexing?.filesProcessed),filesIndexed:ss(s.indexing?.filesIndexed),filesSkipped:ss(s.indexing?.filesSkipped),filesFailed:ss(s.indexing?.filesFailed),progress:ss(s.indexing?.progress),message:typeof s.indexing?.message=="string"?s.indexing.message:void 0},writes:{ready:!!s.writes?.ready,blocked:!!(s.writes?.blocked??!s.writes?.ready),reason:typeof s.writes?.reason=="string"?s.writes.reason:void 0,message:typeof s.writes?.message=="string"?s.writes.message:void 0,gates:{metadataIndexingComplete:!!s.writes?.gates?.metadataIndexingComplete,snapshotComplete:!!s.writes?.gates?.snapshotComplete,ftsRequired:!1}},lsp:s.lsp&&typeof s.lsp=="object"?s.lsp:void 0}}catch{return null}}async stop(){let n=this.getProjectRoot();await this.watcher?.dispose(),this.watcher=null;let r=n?vt(n):null,s=r?Dn.getExistingEngine(r):null;if(s?.hasPendingInitialSnapshot?.()){let o=Math.max(0,Number(process.env.PANDO_INITIAL_SNAPSHOT_DRAIN_MS||"300000"));W("PandoRuntime","stop draining pending initial snapshot",{root:n,timeoutMs:o});try{await Promise.race([s.waitForInitialSnapshot?.(),new Promise((i,a)=>setTimeout(()=>a(new Error(`initial snapshot drain timed out after ${o}ms`)),o))]),W("PandoRuntime","stop drained pending initial snapshot",{root:n})}catch(i){W("PandoRuntime","stop initial snapshot drain failed",{root:n,error:i instanceof Error?i.message:String(i)})}}try{s?.cancelActiveOperations?.("runtime stopped")}catch{}try{s?.cancelIndexing?.("runtime stopped")}catch{}if(Th(),await go.shutdownAllShared({force:!0,reason:"runtime stopped"}).catch(()=>{}),Va("runtime stopped"),qS(),!!r){try{s?.dispose?.()}catch{}Dn.clearEngine(r)}}reloadLanguageSupport(n){let r=vt(n),s=this.resolveLanguageSupport(r);this.rootManager.updateRootOptions(r,{languageSupport:s,lspHost:this.options.lspHost}),this.getProjectRoot()===r&&this.watcher?.updateProjectRoot(r,s)}async configureWatcher(){if(this.options.enableFileWatching===!1||W_())return;let n=this.getProjectRoot();if(n){if(this.rootManager.isIndexingSuppressed(n)){W("PandoRuntime","configureWatcher skipped (root over indexing limit)",{root:n});return}this.watcher=new Mg(r=>this.options.log?.(r)??void 0),await this.watcher.activate(n,this.resolveLanguageSupport(n))}}resolveLanguageSupport(n){return this.options.languageSupport??Na(n)}};function ss(t){return typeof t=="number"?t:void 0}kr();async function Fg(t,e={}){return e.hostKind&&H_(e.hostKind),e.runtimePaths&&Ma(e.runtimePaths.runtimeRoot??t,e.runtimePaths),Np.create({initialRoot:t,languageSupport:e.languageSupport,lspHost:e.lspHost,transportMode:e.transportMode,enableFileWatching:e.enableFileWatching,log:e.log,runtimePaths:e.runtimePaths})}kr();var Fp=B(require("path"));Ls();zl();Qt();Yc();var RU="Compared against a smart non-pando workflow that would only send targeted declaration/reference snippets and minimal surrounding context, not full files.";var _c={language:null,charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"heuristic"},kU={c:{language:"c",charsPerLine:40.09,charsPerToken:3.98,searchLines:5.91,confidence:"trace-high"},cpp:{language:"cpp",charsPerLine:42.56,charsPerToken:3.99,searchLines:6.89,confidence:"trace-high"},csharp:{language:"csharp",charsPerLine:38.55,charsPerToken:3.99,searchLines:3.76,confidence:"trace-low"},js:{language:"js",charsPerLine:39.75,charsPerToken:3.98,searchLines:6.02,confidence:"trace-high"},ts:{language:"ts",charsPerLine:37.3,charsPerToken:3.99,searchLines:7.67,confidence:"trace-high"},java:{language:"java",charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"trace-sparse"},clojure:{language:"clojure",charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"modeled-only"},dart:{language:"dart",charsPerLine:40,charsPerToken:4,searchLines:6,confidence:"modeled-only"}};function aa(t){return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.floor(t))}function Mp(t){return Math.max(0,Math.floor(t))}function KN(t,e=_c){return Mp(Math.round(t*e.charsPerLine))}function jg(t,e=_c){return t<=0?0:Mp(Math.ceil(t/e.charsPerToken))}function EU(t){return Buffer.byteLength(t,"utf8")}function TU(t){let e=t[t.length-1],n=t[t.length-2],r=t[t.length-3];return e?e==="content"&&n==="body"||e==="content"&&n==="code"&&r==="self"||e==="content"&&n==="code"?!0:e==="source"||e==="sourceText"||e==="sourceCode"||e==="rawSource"||e==="excerpt"||e==="snippet"||e==="oldString"||e==="old_string"||e==="originalFile"||e==="gitDiff"||e==="diff"||e==="patch":!1}function ZN(t){let e=new Set,n=(r,s)=>{if(typeof r=="string")return TU(s)?EU(r):0;if(!r||typeof r!="object"||e.has(r))return 0;if(e.add(r),Array.isArray(r))return r.reduce((i,a,c)=>i+n(a,[...s,String(c)]),0);let o=0;for(let[i,a]of Object.entries(r))o+=n(a,[...s,i]);return o};return Mp(n(t,[]))}function J_(t){if(Array.isArray(t))return t.length===1?J_(t[0]):null;if(typeof t!="string")return null;let e=t.trim().toLowerCase();return e?e==="typescript"||e==="tsx"?"ts":e==="javascript"||e==="jsx"?"js":e==="c++"||e==="cc"||e==="cxx"?"cpp":e==="c#"||e==="cs"?"csharp":e==="clj"||e==="cljs"||e==="cljc"?"clojure":e:null}function tr(t){if(typeof t!="string")return null;let e=t.split("#",1)[0].split("?",1)[0].toLowerCase();return/\.(ts|tsx)$/.test(e)?"ts":/\.(js|jsx|mjs|cjs)$/.test(e)?"js":/\.(cc|cpp|cxx|c\+\+|hpp|hh|hxx)$/.test(e)?"cpp":/\.(c|h)$/.test(e)?"c":/\.cs$/.test(e)?"csharp":/\.java$/.test(e)?"java":/\.(clj|cljs|cljc|edn)$/.test(e)?"clojure":/\.dart$/.test(e)?"dart":null}function $g(t){let e=J_(t?.lang??t?.language);if(e)return e;let n=tr(t?.path)??tr(t?.file)??tr(t?.file_path)??tr(t?.newFile)??tr(t?.oldFile)??tr(t?.bodyEndOf)??tr(t?.bodyStartOf)??tr(t?.before)??tr(t?.after)??tr(t?.start)??tr(t?.end)??tr(t?.location?.file);return n||null}function PU(t,e){let n=J_(t.lang)??tr(t.path)??tr(t.to)??tr(t.of)??tr(t.file)??tr(t.newFile)??$g(t.to)??$g(t.scope)??tr(t.scope?.file)??(Array.isArray(t.scope?.files)?tr(t.scope.files[0]):null);if(n)return n;for(let r of[e.results,e.items,e.exports])if(Array.isArray(r))for(let s of r){let o=$g(s);if(o)return o}return $g(e)}function CU(t,e){let n=PU(t,e);return n?kU[n]??{..._c,language:n,confidence:"heuristic"}:_c}function AU(t,e){return e==="trace-high"?t:e==="trace-low"||e==="trace-sparse"||e==="modeled-only"?"low":t==="high"?"medium":t}function K_(t,e){let n=t.savedItems.map(s=>{let o=KN(s.estimatedLinesNotSent,e);return{...s,estimatedCharsNotSent:o,estimatedTokensNotSent:jg(o,e)}}),r=n.reduce((s,o)=>s+o.estimatedCharsNotSent,0);return{...t,confidence:AU(t.confidence,e.confidence),savedItems:n,language:e.language,calibrationConfidence:e.confidence,charsPerLine:e.charsPerLine,charsPerToken:e.charsPerToken,counterfactualTextToolChars:r,estimatedCharsNotSent:r,estimatedTokensNotSent:jg(r,e)}}function qN(t,e){return Math.max(1,Math.round(t.searchLines||e))}function jn(t,e,n,r,s){let o=aa(n),i=aa(r);if(o<=0||i<=0)return null;let a=o*i,c=KN(a),l=jg(c);return{key:t,label:e,count:o,linesPerUnit:i,estimatedLinesNotSent:a,estimatedCharsNotSent:c,estimatedTokensNotSent:l,note:s}}function HN(){return{version:1,calls:0,successfulCalls:0,callsWithSavings:0,estimatedLinesNotSent:0,counterfactualTextToolChars:0,pandoActualSourceChars:0,estimatedCharsNotSent:0,estimatedTokensNotSent:0,byOperation:{},lastUpdatedAt:null}}function os(t,e,n,r,s,o){let i=o.filter(d=>d!==null),a=i.reduce((d,p)=>d+p.estimatedLinesNotSent,0),c=i.reduce((d,p)=>d+p.estimatedCharsNotSent,0),l=c,u=i.reduce((d,p)=>d+p.estimatedTokensNotSent,0);return{version:1,op:t,success:e,method:n,confidence:r,comparisonBaseline:RU,rationale:s,savedItems:i,estimatedLinesNotSent:a,language:null,calibrationConfidence:_c.confidence,charsPerLine:_c.charsPerLine,charsPerToken:_c.charsPerToken,counterfactualTextToolChars:c,pandoActualSourceChars:0,estimatedCharsNotSent:l,estimatedTokensNotSent:u}}function Z_(t,e){let n=ZN(e);if(!t.success||t.counterfactualTextToolChars<=0)return{...t,pandoActualSourceChars:n};let r=Mp(t.counterfactualTextToolChars-n);return{...t,pandoActualSourceChars:n,estimatedCharsNotSent:r,estimatedTokensNotSent:jg(r,{language:t.language,charsPerLine:t.charsPerLine,charsPerToken:t.charsPerToken,searchLines:6,confidence:t.calibrationConfidence})}}function Dp(t,e,n){return os(t,e,"none","low",n,[])}function IU(t){switch(t.key){case"candidate-node-metadata":return"declaration snippets";case"candidate-node-self":return"extra declaration context";case"candidate-node-body":return"residual declaration context";case"reference-sites":return"reference snippets";case"caller-sites":return"caller snippets";case"export-result-contexts":return"export snippets";case"import-file-summaries":case"import-module-summaries":return"import snippets";case"namespace-graph-nodes":return"namespace declaration snippets";case"namespace-graph-edges":return"namespace dependency snippets";case"namespace-plan-edits":return"planned rewrite snippets";case"namespace-plan-declaration-context":return"namespace declaration context";case"reference-edit-contexts":return"reference edit snippets";case"declaration-context":return"declaration context";case"delete-target-context":return"delete target snippets";case"delete-reference-contexts":return"reference deletion snippets";case"signature-declaration-context":return"signature declaration context";case"signature-callsite-contexts":return"call-site rewrite snippets";case"fmr-match-contexts":return"matched code snippets";case"namespace-rewrite-files":return"namespace rewrite snippets";case"namespace-declaration-context":return"namespace declaration context";default:return t.label.replace(/\bthat did not need to be sent\b/gi,"").replace(/\bdid not need raw import snippets\b/gi,"").replace(/\s+/g," ").trim().replace(/[.;:]$/,"")}}function Lg(t){if(!t||t.estimatedTokensNotSent<=0&&t.pandoActualSourceChars<=0)return;let e=t.savedItems.filter(o=>o.estimatedTokensNotSent>0).map(o=>({label:IU(o),count:o.count,estimatedLines:o.estimatedLinesNotSent,estimatedChars:o.estimatedCharsNotSent,estimatedTokens:o.estimatedTokensNotSent})),n=e.reduce((o,i)=>o+i.count,0),r=n===1?"snippet":"snippets",s=`; Pando returned ${t.pandoActualSourceChars} chars of source`;return{version:1,op:t.op,summary:`Would have sent about ${t.estimatedCharsNotSent} chars / ${t.estimatedTokensNotSent} tokens across ${n} ${r}${s}.`,confidence:t.confidence,language:t.language,calibrationConfidence:t.calibrationConfidence,charsPerLine:t.charsPerLine,charsPerToken:t.charsPerToken,estimatedLines:t.estimatedLinesNotSent,counterfactualTextToolChars:t.counterfactualTextToolChars,pandoActualSourceChars:t.pandoActualSourceChars,estimatedChars:t.estimatedCharsNotSent,estimatedTokens:t.estimatedTokensNotSent,wouldSend:e}}function GN(t){return Array.isArray(t.results)?t.results:Array.isArray(t.items)?t.items:Array.isArray(t.exports)?t.exports:[]}function JN(t){let e=t.details;return typeof e?.changedFileCount=="number"?aa(e.changedFileCount):Array.isArray(e?.allChangedFiles)?e.allChangedFiles.length:Array.isArray(e?.changedFiles)?e.changedFiles.length:aa(t.changes?.count??0)}function wc(t){return Array.isArray(t)?t.length:0}function NU(t,e){let n=GN(e),r=0,s=0,o=0;for(let i of n){if(i?.body?.content){o+=1;continue}if(i?.self?.code?.content){s+=1;continue}r+=1}return os(t,e.success,"mixed","medium","Structured node discovery avoids sending most candidate snippets; when self/body is requested, the saved amount is reduced rather than treated as zero.",[jn("candidate-node-metadata","Candidate node snippets that did not need to be sent",r,4,"Metadata-only results usually avoid sending the declaration line plus minimal surrounding context for each candidate."),jn("candidate-node-self","Additional node context avoided even when self was requested",s,2,"Including the node itself still avoids some surrounding context a smart text workflow would usually inspect."),jn("candidate-node-body","Residual declaration context avoided when body content was requested",o,1,"Requesting body content removes most of the privacy advantage, so only a minimal declaration-context saving is counted.")])}function WN(t,e,n,r){let s=GN(e).length;return os(t,e.success,"exact-counts","high","Structured locations avoid sending per-location code snippets and nearby context.",[jn(n,n==="reference-sites"?"Reference-site snippets that did not need to be sent":"Caller-site snippets that did not need to be sent",s,r,"The comparison assumes a smart text workflow would only send a minimal location snippet for each result.")])}function DU(t,e){let n=wc(e.exports);return os(t,e.success,"exact-counts","medium","Structured export lookup answers declaration-discovery questions without sending export snippets or nearby code.",[jn("export-result-contexts","Export declaration snippets that did not need to be sent",n,2,"Only the returned export entries are counted, which keeps paginated list-exports calls conservative.")])}function OU(t,e){let n=e.imports,r=wc(n?.files),s=wc(n?.external),o=wc(n?.internal);return os(t,e.success,"exact-counts","medium","Import analysis returns grouped dependency structure without sending raw import blocks; only visible grouped entries are counted.",[jn("import-file-summaries","Per-file import summaries that did not need raw import snippets",r,2,"When grouped by file, the estimate counts one small import-summary snippet per returned file entry."),jn("import-module-summaries","Grouped import summaries that did not need raw import snippets",s+o,2,"When grouped by module, the estimate counts only the returned grouped entries rather than every underlying import usage.")])}function UN(t,e,n){let r=wc(e.namespaces),s=wc(e.edges);return os(t,e.success,"exact-counts","medium",n,[jn("namespace-graph-nodes","Namespace declaration snippets that did not need to be sent",r,1,"Each returned namespace usually corresponds to at least one small ns-form context in a text-based workflow."),jn("namespace-graph-edges","Namespace dependency snippets that did not need to be sent",s,2,"Each returned edge usually corresponds to one focused require/refer snippet in a text-based workflow.")])}function MU(t,e){let n=wc(e.namespaceEdits);return os(t,e.success,"exact-counts","medium","Namespace planning computes the affected declaration and dependent files without sending each candidate require/ns snippet to the provider.",[jn("namespace-plan-edits","Planned namespace rewrite snippets that did not need to be sent",n,4,"The estimate counts one small rewrite-planning snippet per planned file edit."),jn("namespace-plan-declaration-context","Namespace declaration context that only needed to be localized once",e.success?1:0,6,"The source namespace still needs one focused declaration context to build the plan.")])}function FU(t,e){let n=aa(e.details?.referencesRenamed);return os(t,e.success,"exact-counts","high","Rename uses exact reference counts already produced by the executor, then applies a conservative per-reference context window.",[jn("reference-edit-contexts","Reference edit contexts that did not need to be sent",n,3,"A smart non-pando workflow would still need to send each reference with a small amount of surrounding code before editing or approving it."),jn("declaration-context","Declaration context that only needed to be localized once",e.success?1:0,6,"The declaration still has to be identified, but pando does not require the model to receive surrounding code for every downstream edit.")])}function $U(t,e){let n=aa(e.details?.deletedCount),r=Array.isArray(e.details?.receipt?.appliedReferences)?e.details.receipt.appliedReferences.length:0;return os(t,e.success,r>0?"mixed":"heuristic",r>0?"high":"medium","Applied reference counts are exact when the executor exposes them; otherwise only the target-level deletion context is counted.",[jn("delete-target-context","Delete target contexts that did not need to be sent",n,6,"Each delete target typically needs declaration-level context in a text-based workflow."),jn("delete-reference-contexts","Reference deletion contexts that did not need to be sent",r,4,"When reference edits are applied automatically, pando avoids sending each reference and a small surrounding window.")])}function jU(t,e){let n=aa(e.details?.callSiteStats?.auto_rewritten??e.changes?.callSitesAutoRewritten??0);return os(t,e.success,"exact-counts","high","The executor already reports how many call sites were rewritten automatically, so the privacy estimate can stay count-exact while using conservative context windows.",[jn("signature-declaration-context","Function signature context that did not need to be sent repeatedly",e.success?1:0,6,"Only one declaration/signature context is counted for the target function."),jn("signature-callsite-contexts","Auto-rewritten call-site contexts that did not need to be sent",n,5,"The estimate only counts call sites pando rewrote automatically; manual-review sites are not claimed as privacy savings.")])}function LU(t,e,n){let r=aa(n.details?.receipt?.processedCount??n.details?.processedCount??n.details?.succeededCount??0),o=(Array.isArray(e.transforms)?e.transforms.length:0)>0?"filter-map-reduce localizes and rewrites matches without shipping matched code to the provider; the count is based on processed matches, not full-file size.":"filter-map-reduce localizes matches without shipping matched code to the provider.";return os(t,n.success,"exact-counts","high",o,[jn("fmr-match-contexts","Matched-node contexts that did not need to be sent",r,6,"The baseline assumes a smart text workflow would still need to send a small snippet for every matched location before applying or validating a transform.")])}function G_(t,e,n,r,s){let o=JN(e);return os(t,e.success,"heuristic","medium",s,[jn(`${t}-target-context`,r,o>0?1:0,n,"The estimate assumes one minimal target/anchor snippet would otherwise need to be sent for a single focused edit.")])}function zU(t,e){let n=JN(e);return os(t,e.success,"mixed","medium","Namespace rewrites typically require touching several import/require sites; the estimate stays conservative and file-based.",[jn("namespace-rewrite-files","Namespace/import rewrite snippets that did not need to be sent",n,4,"A smart text workflow would usually send at least one small require/import snippet per changed file."),jn("namespace-declaration-context","Namespace declaration context that only needed to be localized once",e.success?1:0,6,"The namespace declaration itself still needs one focused context window.")])}function VN(t,e,n){let r=!!n?.success,s=CU(e,n);if(!t)return Z_(K_(Dp("unknown",r,"Operation name unavailable; no privacy savings claimed."),s),n);if(!r)return Z_(K_(Dp(t,!1,"Operation did not succeed, so no privacy savings are claimed."),s),n);let o=(()=>{switch(t){case"find-nodes":return NU(t,n);case"find-references":return WN(t,n,"reference-sites",qN(s,6));case"find-callers":return WN(t,n,"caller-sites",qN(s,6));case"list-exports":return DU(t,n);case"analyze-imports":return OU(t,n);case"clojure-namespace-graph":return UN(t,n,"Namespace graph queries return cross-file dependency structure without sending the underlying ns/require snippets.");case"clojure-namespace-dependencies":case"clojure-namespace-dependents":return UN(t,n,"Namespace traversal returns dependency edges directly, avoiding per-edge code snippets in the provider request.");case"plan-clojure-namespace-move":case"plan-clojure-namespace-rename":return MU(t,n);case"rename":return FU(t,n);case"delete":return $U(t,n);case"change-signature":return jU(t,n);case"filter-map-reduce":return LU(t,e,n);case"replace":return G_(t,n,10,"Target replacement context that did not need to be sent","A focused replace still needs target localization in a text-based workflow; pando avoids sending that local code window.");case"replace-body":return G_(t,n,12,"Body replacement context that did not need to be sent","Body replacement typically requires a slightly larger context window than full-node replacement.");case"insert":case"add-code":return e?.createFileIfMissing?Dp(t,!0,"Insert created a new file, so no existing code context savings are claimed."):G_(t,n,8,"Insertion anchor context that did not need to be sent","A targeted insert usually needs local anchor context in a text-based workflow; pando keeps that out of the provider request.");case"rename-clojure-namespace":case"move-clojure-namespace":return zU(t,n);default:return Dp(t,!0,"Administrative or metadata-only operation; privacy savings are too small or too uncertain to claim conservatively.")}})();return Z_(K_(o,s),n)}function V_(t,e){if(e.length===0)return Dp(t,!0,"No underlying operation estimates were available.");let n=e.every(u=>u.success),r=e.every(u=>u.method==="exact-counts")?"exact-counts":e.some(u=>u.method==="none")?"mixed":e.every(u=>u.method==="heuristic")?"heuristic":"mixed",s=e.every(u=>u.confidence==="high")?"high":e.some(u=>u.confidence==="low")?"low":"medium",o=new Map;for(let u of e)for(let d of u.savedItems){let p=o.get(d.key);if(!p){o.set(d.key,{...d});continue}p.count+=d.count,p.estimatedLinesNotSent+=d.estimatedLinesNotSent,p.estimatedCharsNotSent+=d.estimatedCharsNotSent,p.estimatedTokensNotSent+=d.estimatedTokensNotSent}let i=os(t,n,r,s,"Combined from per-root operation estimates in the current dispatcher session.",Array.from(o.values())),a=e.reduce((u,d)=>u+d.pandoActualSourceChars,0),c=Mp(i.counterfactualTextToolChars-a),l=e.reduce((u,d)=>u+d.estimatedTokensNotSent,0);return{...i,language:e.every(u=>u.language===e[0]?.language)?e[0]?.language??null:null,calibrationConfidence:e.every(u=>u.calibrationConfidence==="trace-high")?"trace-high":e.some(u=>u.calibrationConfidence==="modeled-only")?"modeled-only":e.some(u=>u.calibrationConfidence==="trace-low")?"trace-low":e.some(u=>u.calibrationConfidence==="trace-sparse")?"trace-sparse":"heuristic",pandoActualSourceChars:a,estimatedCharsNotSent:c,estimatedTokensNotSent:l}}var Op=class{constructor(){this.summary=HN()}record(e,n,r){let s=VN(e,n,r),o=this.summary.byOperation[e]??{calls:0,successfulCalls:0,callsWithSavings:0,estimatedLinesNotSent:0,counterfactualTextToolChars:0,pandoActualSourceChars:0,estimatedCharsNotSent:0,estimatedTokensNotSent:0};return o.calls+=1,s.success&&(o.successfulCalls+=1),s.estimatedTokensNotSent>0&&(o.callsWithSavings+=1),o.estimatedLinesNotSent+=s.estimatedLinesNotSent,o.counterfactualTextToolChars+=s.counterfactualTextToolChars,o.pandoActualSourceChars+=s.pandoActualSourceChars,o.estimatedCharsNotSent+=s.estimatedCharsNotSent,o.estimatedTokensNotSent+=s.estimatedTokensNotSent,this.summary.byOperation[e]=o,this.summary.calls+=1,s.success&&(this.summary.successfulCalls+=1),s.estimatedTokensNotSent>0&&(this.summary.callsWithSavings+=1),this.summary.estimatedLinesNotSent+=s.estimatedLinesNotSent,this.summary.counterfactualTextToolChars+=s.counterfactualTextToolChars,this.summary.pandoActualSourceChars+=s.pandoActualSourceChars,this.summary.estimatedCharsNotSent+=s.estimatedCharsNotSent,this.summary.estimatedTokensNotSent+=s.estimatedTokensNotSent,this.summary.lastUpdatedAt=new Date().toISOString(),{operation:s,session:this.getSessionSummary()}}getSessionSummary(){let e={};for(let[n,r]of Object.entries(this.summary.byOperation))e[n]={...r};return{...this.summary,byOperation:e}}reset(){return this.summary=HN(),this.getSessionSummary()}};dt();function eo(t){let e=t.details;return e?typeof e.changedFileCount=="number"?e.changedFileCount:Array.isArray(e.allChangedFiles)?e.allChangedFiles.length:Array.isArray(e.changedFiles)?e.changedFiles.length:t.changes?.count??0:t.changes?.count??0}function zg(t){return t.page?.totalCount??t.totalCount??(Array.isArray(t.results)?t.results.length:0)}var BU={rename:t=>({primary:eo(t),secondary:t.details?.referencesRenamed??0}),delete:t=>({primary:eo(t),secondary:t.details?.deletedCount??0}),insert:t=>({primary:eo(t),secondary:t.created?1:0}),replace:t=>({primary:eo(t),secondary:0}),"replace-body":t=>({primary:eo(t),secondary:0}),"change-signature":t=>({primary:eo(t),secondary:t.changes?.callSitesAutoRewritten??0}),"filter-map-reduce":t=>({primary:eo(t),secondary:0}),"find-references":t=>({primary:zg(t),secondary:0}),"find-callers":t=>({primary:zg(t),secondary:0}),"find-nodes":t=>({primary:zg(t),secondary:0}),"workspace-overview":()=>({primary:0,secondary:0}),"list-exports":t=>({primary:t.page?.totalCount??(Array.isArray(t.exports)?t.exports.length:0),secondary:0}),"analyze-imports":t=>{let e=t.page;return{primary:e?.files?.totalCount??(e?.external?.totalCount??0)+(e?.internal?.totalCount??0),secondary:0}},"clojure-namespace-graph":t=>({primary:t.details?.namespaceCount??0,secondary:t.details?.edgeCount??0}),"clojure-namespace-dependencies":t=>({primary:t.namespacesPage?.totalCount??(Array.isArray(t.namespaces)?t.namespaces.length:0),secondary:t.edgesPage?.totalCount??(Array.isArray(t.edges)?t.edges.length:0)}),"clojure-namespace-dependents":t=>({primary:t.namespacesPage?.totalCount??(Array.isArray(t.namespaces)?t.namespaces.length:0),secondary:t.edgesPage?.totalCount??(Array.isArray(t.edges)?t.edges.length:0)}),"move-clojure-namespace":t=>({primary:eo(t),secondary:0}),"rename-clojure-namespace":t=>({primary:eo(t),secondary:0}),"restore-snapshot":t=>({primary:eo(t),secondary:0}),"restore-files":t=>({primary:eo(t),secondary:0})},qU=t=>({primary:eo(t),secondary:zg(t)});function HU(t,e){let n=BU[t]??qU;try{return n(e)}catch{return{primary:0,secondary:0}}}var WU=0;function X_(){return`${Date.now()}-${++WU}`}function XN(t,e,n,r){let s=HU(t,e);return{schema_version:1,call_id:r,op:t,success:e.success,duration_ms:Math.max(0,Math.round(n)),error_code:e.error_code??void 0,primary_count:s.primary,secondary_count:s.secondary,timestamp:new Date().toISOString()}}var QN="_privacyOperation";function t0(t){let e=t.trim();if(!e)return null;let n=e;return(e.startsWith("pando_")||e.startsWith("pando-"))&&(n=e.slice(6)),n?n.replace(/_/g,"-"):null}function n0(t,e){let n={...e};return delete n.root,n}var Bl=class{constructor(e){this.config=e;this.privacyCounter=new Op}async dispatch(e,n,r){let s=Date.now();W("PandoOp","op begin",{tool:e});let o;try{o=await this.dispatchInner(e,n,r)}catch(a){let c=a instanceof Error?a.message:String(a);throw W("PandoOp","op threw",{tool:e,error:c,elapsedMs:Date.now()-s}),a}let i=Date.now()-s;return o.success&&o.data&&typeof o.data=="object"&&!Array.isArray(o.data)&&o.data.elapsedMs===void 0&&(o.data.elapsedMs=i),W("PandoOp","op end",{tool:e,success:o.success,...o.success?{}:{error:o.error},elapsedMs:i}),o}async dispatchInner(e,n,r){let s=t0(e);if(!s)return{success:!1,error:`Unknown tool: ${e}`};let o=this.config.processRole??Xo();if(!Pp(o,s))return{success:!1,error:C_(o,s),data:{role:o,operation:s}};if(s==="add-root"){let f=typeof n.root=="string"?n.root.trim():"";if(!f)return{success:!1,error:"Missing required parameter: root"};if(YN(f))return{success:!1,error:"Filesystem root '/' cannot be used as a project root."};let m=$o(f);if(m)return{success:!1,error:`'${f}' cannot be added as a workspace root because it is, contains, or sits inside a protected location ('${m}'). Choose a project directory, not a system, credential, home, or external-disk path.`};if(!this.config.onRootAdded)return{success:!1,error:"add-root is not supported in this host."};let h=Date.now();W("PandoToolDispatcher","add-root begin",{toolName:e,requestedRoot:f});let g;try{g=await this.config.onRootAdded(f)}catch(S){let x=S instanceof Error?S.message:String(S);return W("PandoToolDispatcher","add-root rejected",{toolName:e,requestedRoot:f,error:x}),{success:!1,error:x}}if(!g.resolved)return{success:!1,error:`Unable to add root: ${f}`};W("PandoToolDispatcher","add-root complete",{toolName:e,requestedRoot:f,resolvedRoot:g.resolved,alreadyPersisted:g.alreadyPersisted,elapsedMs:Date.now()-h});let y=g.alreadyPersisted?`Root '${g.resolved}' is already registered. Restart Pando to use it if it isn't active yet.`:`Root '${g.resolved}' saved. Restart Pando to bind it into the sandbox; it will be available automatically on the next launch.`,b={root:g.resolved,alreadyPersisted:g.alreadyPersisted,requiresRestart:!g.alreadyPersisted,persistedRoots:g.persistedRoots,message:y};return{success:!0,data:this.attachPrivacyToData("add-root",n,b,{success:!0})}}if(s==="remove-root"){let f=typeof n.root=="string"?n.root.trim():"";if(!f)return{success:!1,error:"Missing required parameter: root"};if(YN(f))return{success:!1,error:"Filesystem root '/' cannot be removed as a project root."};if(!this.config.onRootRemoved)return{success:!1,error:"remove-root is not supported in this host."};let m=Date.now();W("PandoToolDispatcher","remove-root begin",{toolName:e,requestedRoot:f});let h;try{h=await this.config.onRootRemoved(f)}catch(b){let S=b instanceof Error?b.message:String(b);return W("PandoToolDispatcher","remove-root rejected",{toolName:e,requestedRoot:f,error:S}),{success:!1,error:S}}if(!h.resolved)return{success:!1,error:`Unable to remove root: ${f}`};W("PandoToolDispatcher","remove-root complete",{toolName:e,requestedRoot:f,resolvedRoot:h.resolved,removed:h.removed,elapsedMs:Date.now()-m});let g=h.removed?`Root '${h.resolved}' removed. Restart Pando to remove it from the sandbox bindings.`:`Root '${h.resolved}' was not registered. Restart Pando if it is still active from an older launch.`,y={root:h.resolved,removed:h.removed,requiresRestart:h.removed,persistedRoots:h.persistedRoots,message:g};return{success:!0,data:this.attachPrivacyToData("remove-root",n,y,{success:!0})}}let i=this.resolveToolRoots(n);if(!i.roots.length&&i.error)return{success:!1,error:i.error,data:i.availableRoots?{availableRoots:i.availableRoots}:void 0};let a=i.roots;if(s==="get-project-root")return a.length<=1?{success:!0,data:this.attachPrivacyToData("get-project-root",n,{projectRoot:a[0]??null},{success:!0})}:{success:!0,data:this.attachPrivacyToData("get-project-root",n,{projectRoots:a},{success:!0})};if(!a.length)return{success:!1,error:"No workspace root available."};if(s==="read-this-first")return{success:!0,data:this.attachPrivacyToData("read-this-first",n,{help:this.config.loadReadThisFirstMessage()},{success:!0})};let c=n0(s,n),l={op:s,...c},u=X_(),d=r?.telemetry;if(this.isReadOnlyTool(e,s))return this.dispatchReadOnly(a,l,r?.signal,u,d);if(a.length>1){let f=[];for(let h of a)f.push(await this.executeOne(h,l,r?.signal,u,d));await this.handlePostDispatchEffects(s,f);let m=this.buildAggregatePrivacy(s,f);return{success:!0,data:{perRoot:f,...m?{privacy:m}:{}}}}let p=await this.executeOne(a[0],l,r?.signal,u,d);if(!p.success){let f=p.error??"Operation failed",m=Array.isArray(p.result?.hints)?p.result.hints:void 0;return{success:!1,error:f,...m?{hints:m}:{},data:p.result??{success:!1,error:f}}}return await this.handlePostDispatchEffects(s,[p]),{success:!0,data:p.result}}getPrivacySummary(){return this.privacyCounter.getSessionSummary()}resetPrivacySummary(){return this.privacyCounter.reset()}resolveToolRoots(e){if(this.config.resolveRoots)return this.config.resolveRoots(e);let n=this.config.roots(),r=typeof e.root=="string"?e.root.trim():"";if(!r)return{roots:n};let s=vt(Fp.default.isAbsolute(r)?r:Fp.default.resolve(n[0]??process.cwd(),r)),o=n.map(i=>vt(i));return o.includes(s)?{roots:[s]}:{roots:[],error:`Requested root is not registered: ${r}`,availableRoots:o}}async dispatchReadOnly(e,n,r,s,o){if(e.length===1){let d=await this.executeOne(e[0],n,r,s,o);if(!d.success){let p=d.error??"Operation failed",f=Array.isArray(d.result?.hints)?d.result.hints:void 0;return{success:!1,error:p,...f?{hints:f}:{},data:d.result??{success:!1,error:p}}}return{success:!0,data:d.result}}let i=[],a=[],c=0,l=!1;for(let d of e){let p=await this.executeOne(d,n,r,s,o);if(i.push(p),!p.success||!p.result)continue;let f=Array.isArray(p.result.items)?p.result.items:Array.isArray(p.result.results)?p.result.results:null;if(!f)continue;for(let g of f)a.push({...g,root:d});let m=p.result.page,h=typeof m?.totalCount=="number"?m.totalCount:typeof p.result.totalCount=="number"?p.result.totalCount:f.length;c+=h,l=l||!!m?.hasMore||!!p.result.hasMore}let u=this.buildAggregatePrivacy(String(n.op||"unknown"),i);return{success:!0,data:{summary:KU(i,a.length?{shownCount:a.length,totalCount:c,hasMore:l}:void 0),results:a.length?a:void 0,totalCount:a.length?c:void 0,hasMore:a.length?l:void 0,perRoot:i,...u?{privacy:u}:{}}}}async executeOne(e,n,r,s,o){let i=typeof n.op=="string"?n.op:"unknown",a=Date.now();try{let l=await Dn.getEngine(e).execute(n,{signal:r}),u=this.attachPrivacyToResult(i,n,l);if(await this.emitTelemetry(i,l,Date.now()-a,e,s,o),!l.success){let d=e0(l.error||"Operation failed");return{root:e,success:!1,error:d,result:{...u,error:d}}}return{root:e,success:!0,result:u}}catch(c){let l={success:!1,error:c instanceof Error?c.message:String(c)},u=this.attachPrivacyToResult(i,n,l);await this.emitTelemetry(i,l,Date.now()-a,e,s,o);let d=e0(c instanceof Error?c.message:String(c));return{root:e,success:!1,error:d,result:{...u,error:d}}}}async emitTelemetry(e,n,r,s,o,i){try{let a=this.config.onTelemetry?.(XN(e,n,r,o??X_()),s,i);if(!a)return;let c=Promise.resolve(a);if(!this.config.awaitTelemetry){c.catch(()=>{});return}await UU(c,this.config.telemetryTimeoutMs??1e3)}catch{}}async handlePostDispatchEffects(e,n){if(e==="set-enabled-languages")for(let r of n)r.success&&r.result?.details?.languageSupportChanged===!0&&await this.config.onLanguageSupportChanged?.(r.root)}isReadOnlyTool(e,n){let r=n.replace(/-/g,"_");return this.config.readOnlyTools.has(e)||this.config.readOnlyTools.has(n)||this.config.readOnlyTools.has(r)||this.config.readOnlyTools.has(`pando_${r}`)||this.config.readOnlyTools.has(`pando-${n}`)}attachPrivacyToResult(e,n,r){let s=this.privacyCounter.record(e,n,r),o=Lg(s.operation),i={...r,...o?{privacy:o}:{}};return Object.defineProperty(i,QN,{value:s.operation,enumerable:!1,configurable:!0,writable:!1}),i}attachPrivacyToData(e,n,r,s){let o=Lg(this.privacyCounter.record(e,n,s).operation);return{...r,...o?{privacy:o}:{}}}buildAggregatePrivacy(e,n){let r=n.map(s=>s.result?.[QN]).filter(s=>!!s);return Lg(V_(e,r))}};function YN(t){let e=Fp.default.resolve(t);return Fp.default.parse(e).root===e}function e0(t){return t.length<=1e3?t:`${t.slice(0,1e3)}\u2026 [truncated]`}function UU(t,e){let n=Math.max(0,Math.trunc(e));return n===0?t:Promise.race([t,new Promise(r=>{setTimeout(r,n)})])}function KU(t,e){let n=t.length,r=t.filter(i=>i.success).length,s=n-r,o=t.map(i=>i.error??(typeof i.result?.error=="string"?i.result.error:void 0)).find(i=>typeof i=="string"&&i.trim().length>0);return{rootsTotal:n,rootsSucceeded:r,rootsFailed:s,shownCount:e?.shownCount,totalCount:e?.totalCount,hasMore:e?.hasMore,error:o}}var r0=B(require("fs")),ZU=["set-enabled-languages","add-root","remove-root","workspace-overview","get-db-schema","query-db","find-nodes","find-references","rename","replace","insert","delete","filter-map-reduce","shell-command"];function ql(t,e){let n=r0.default.readFileSync(t,"utf8"),r=JSON.parse(n),s=Array.isArray(r.tools)?r.tools:[],o=new Map(ZU.map((i,a)=>[i,a]));return s.filter(i=>typeof i?.name=="string").filter(i=>i.category!=="orchestrator").filter(i=>!(e?.excludeNames?.has(i.name)??!1)).sort((i,a)=>{let c=o.get(i.name),l=o.get(a.name);return c!=null&&l!=null?c-l:c!=null?-1:l!=null?1:i.name.localeCompare(a.name)})}var GU={"read-this-first":"Read this first","get-project-root":"Get project root","set-project-root":"Set project root","set-enabled-languages":"Set languages","find-nodes":"Find code","find-references":"Find references","find-callers":"Find callers","get-db-schema":"Index schema","query-db":"Query index","get-storage-content":"Read stored content","workspace-overview":"Workspace overview","list-exports":"List exports","analyze-imports":"Analyze imports","clojure-namespace-graph":"Namespace graph","clojure-namespace-dependencies":"Namespace deps","clojure-namespace-dependents":"Namespace dependents","plan-clojure-namespace-move":"Plan namespace move","plan-clojure-namespace-rename":"Plan namespace rename","move-clojure-namespace":"Move namespace","rename-clojure-namespace":"Rename namespace",rename:"Rename symbol",delete:"Delete code",insert:"Insert code",replace:"Replace code","replace-body":"Replace body","change-signature":"Change signature","filter-map-reduce":"Batch edit","shell-command":"Shell command","list-snapshots":"List snapshots","diff-snapshots":"Diff snapshots","get-snapshot-trailers":"Snapshot trailers","snapshot-worktree":"Create snapshot","restore-snapshot":"Restore snapshot","restore-files":"Restore files","repair-history":"Repair history","add-exclude-dir":"Exclude directory","remove-exclude-dir":"Include directory"},JU=new Set(["read-this-first","get-project-root","get-db-schema","get-storage-content","workspace-overview","find-nodes","find-references","find-callers","query-db","list-exports","analyze-imports","clojure-namespace-graph","clojure-namespace-dependencies","clojure-namespace-dependents","plan-clojure-namespace-move","plan-clojure-namespace-rename","list-snapshots","diff-snapshots","get-snapshot-trailers"]),VU=new Set(["set-project-root","set-enabled-languages","add-root","remove-root","rename","rename-clojure-namespace","move-clojure-namespace","delete","insert","replace","replace-body","change-signature","filter-map-reduce","shell-command","snapshot-worktree","restore-snapshot","restore-files","repair-history","add-exclude-dir","remove-exclude-dir"]),XU=new Set(["delete","shell-command","restore-snapshot","restore-files","repair-history","remove-root","remove-exclude-dir"]);function Q_(t){let e=t.parameters&&t.parameters.type==="object"?{...t.parameters,type:"object",properties:YU(t.parameters.properties)}:{type:"object",properties:{},required:[],additionalProperties:!1},n=GU[t.name],r=QU(t.name,n);return{name:t.name,...n?{title:n}:{},...r?{annotations:r}:{},description:t.description,inputSchema:e}}function QU(t,e){let n=JU.has(t),r=VU.has(t),s=XU.has(t);if(!(!e&&!n&&!r&&!s))return{...e?{title:e}:{},...n?{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}:{},...r?{readOnlyHint:!1,destructiveHint:s,idempotentHint:!1,openWorldHint:t==="shell-command"}:{}}}function Bg(t,e){return t.find(r=>r.name===e)?.description??""}function YU(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t))r&&typeof r=="object"&&(e[n]=r);return e}var Pt;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,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 r(s,o=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}t.joinValues=r,t.jsonStringifyReplacer=(s,o)=>typeof o=="bigint"?o.toString():o})(Pt||(Pt={}));var s0;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(s0||(s0={}));var Ee=Pt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ci=t=>{switch(typeof t){case"undefined":return Ee.undefined;case"string":return Ee.string;case"number":return Number.isNaN(t)?Ee.nan:Ee.number;case"boolean":return Ee.boolean;case"function":return Ee.function;case"bigint":return Ee.bigint;case"symbol":return Ee.symbol;case"object":return Array.isArray(t)?Ee.array:t===null?Ee.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Ee.promise:typeof Map<"u"&&t instanceof Map?Ee.map:typeof Set<"u"&&t instanceof Set?Ee.set:typeof Date<"u"&&t instanceof Date?Ee.date:Ee.object;default:return Ee.unknown}};var ie=Pt.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"]);var Cs=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(o){return o.message},r={_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)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(this),r}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,Pt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let s of this.issues)if(s.path.length>0){let o=s.path[0];n[o]=n[o]||[],n[o].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Cs.create=t=>new Cs(t);var eK=(t,e)=>{let n;switch(t.code){case ie.invalid_type:t.received===Ee.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case ie.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Pt.jsonStringifyReplacer)}`;break;case ie.unrecognized_keys:n=`Unrecognized key(s) in object: ${Pt.joinValues(t.keys,", ")}`;break;case ie.invalid_union:n="Invalid input";break;case ie.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Pt.joinValues(t.options)}`;break;case ie.invalid_enum_value:n=`Invalid enum value. Expected ${Pt.joinValues(t.options)}, received '${t.received}'`;break;case ie.invalid_arguments:n="Invalid function arguments";break;case ie.invalid_return_type:n="Invalid function return type";break;case ie.invalid_date:n="Invalid date";break;case ie.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Pt.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case ie.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case ie.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case ie.custom:n="Invalid input";break;case ie.invalid_intersection_types:n="Intersection results could not be merged";break;case ie.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case ie.not_finite:n="Number must be finite";break;default:n=e.defaultError,Pt.assertNever(t)}return{message:n}},ca=eK;var tK=ca;function $p(){return tK}var qg=t=>{let{data:e,path:n,errorMaps:r,issueData:s}=t,o=[...n,...s.path||[]],i={...s,path:o};if(s.message!==void 0)return{...s,path:o,message:s.message};let a="",c=r.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:e,defaultError:a}).message;return{...s,path:o,message:a}};function _e(t,e){let n=$p(),r=qg({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===ca?void 0:ca].filter(s=>!!s)});t.common.issues.push(r)}var Ar=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let s of n){if(s.status==="aborted")return tt;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let s of n){let o=await s.key,i=await s.value;r.push({key:o,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let s of n){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return tt;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[o.value]=i.value)}return{status:e.value,value:r}}},tt=Object.freeze({status:"aborted"}),Hl=t=>({status:"dirty",value:t}),qr=t=>({status:"valid",value:t}),Y_=t=>t.status==="aborted",ew=t=>t.status==="dirty",vc=t=>t.status==="valid",jp=t=>typeof Promise<"u"&&t instanceof Promise;var $e;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})($e||($e={}));var to=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,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}},o0=(t,e)=>{if(vc(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 n=new Cs(t.common.issues);return this._error=n,this._error}}};function mt(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))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??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:s}}var _t=class{get description(){return this._def.description}_getType(e){return Ci(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ci(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ar,ctx:{common:e.parent.common,data:e.data,parsedType:Ci(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(jp(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ci(e)},s=this._parseSync({data:e,path:r.path,parent:r});return o0(r,s)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ci(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return vc(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>vc(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ci(e)},s=this._parse({data:e,path:r.path,parent:r}),o=await(jp(s)?s:Promise.resolve(s));return o0(r,o)}refine(e,n){let r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,o)=>{let i=e(s),a=()=>o.addIssue({code:ie.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new Co({schema:this,typeName:le.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:n=>this["~validate"](n)}}optional(){return As.create(this,this._def)}nullable(){return Ni.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ua.create(this)}promise(){return Rc.create(this,this._def)}or(e){return Gl.create([this,e],this._def)}and(e){return Jl.create(this,e,this._def)}transform(e){return new Co({...mt(this._def),schema:this,typeName:le.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new eu({...mt(this._def),innerType:this,defaultValue:n,typeName:le.ZodDefault})}brand(){return new Hg({typeName:le.ZodBranded,type:this,...mt(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new tu({...mt(this._def),innerType:this,catchValue:n,typeName:le.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Wg.create(this,e)}readonly(){return nu.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},nK=/^c[^\s-]{8,}$/i,rK=/^[0-9a-z]+$/,sK=/^[0-9A-HJKMNP-TV-Z]{26}$/i,oK=/^[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,iK=/^[a-z0-9_-]{21}$/i,aK=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cK=/^[-+]?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)?)??$/,lK=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,uK="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",tw,dK=/^(?:(?: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])$/,pK=/^(?:(?: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])$/,fK=/^(([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]))$/,mK=/^(([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])$/,hK=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,gK=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,i0="((\\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])))",yK=new RegExp(`^${i0}$`);function a0(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function bK(t){return new RegExp(`^${a0(t)}$`)}function SK(t){let e=`${i0}T${a0(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function xK(t,e){return!!((e==="v4"||!e)&&dK.test(t)||(e==="v6"||!e)&&fK.test(t))}function _K(t,e){if(!aK.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function wK(t,e){return!!((e==="v4"||!e)&&pK.test(t)||(e==="v6"||!e)&&mK.test(t))}var Ul=class t extends _t{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Ee.string){let o=this._getOrReturnCtx(e);return _e(o,{code:ie.invalid_type,expected:Ee.string,received:o.parsedType}),tt}let r=new Ar,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")e.data.length>o.value&&(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.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?_e(s,{code:ie.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&_e(s,{code:ie.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")lK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"email",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")tw||(tw=new RegExp(uK,"u")),tw.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"emoji",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")oK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"uuid",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")iK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"nanoid",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")nK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"cuid",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")rK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"cuid2",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")sK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"ulid",code:ie.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),_e(s,{validation:"url",code:ie.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"regex",code:ie.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.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),_e(s,{code:ie.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?SK(o).test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?yK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?bK(o).test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?cK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"duration",code:ie.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?xK(e.data,o.version)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"ip",code:ie.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?_K(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"jwt",code:ie.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?wK(e.data,o.version)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"cidr",code:ie.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?hK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"base64",code:ie.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?gK.test(e.data)||(s=this._getOrReturnCtx(e,s),_e(s,{validation:"base64url",code:ie.invalid_string,message:o.message}),r.dirty()):Pt.assertNever(o);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:ie.invalid_string,...$e.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...$e.errToObj(e)})}url(e){return this._addCheck({kind:"url",...$e.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...$e.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...$e.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...$e.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...$e.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...$e.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...$e.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...$e.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...$e.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...$e.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...$e.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...$e.errToObj(e)})}datetime(e){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,...$e.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,...$e.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...$e.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...$e.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...$e.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...$e.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...$e.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...$e.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...$e.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...$e.errToObj(n)})}nonempty(e){return this.min(1,$e.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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Ul.create=t=>new Ul({checks:[],typeName:le.ZodString,coerce:t?.coerce??!1,...mt(t)});function vK(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}var Lp=class t extends _t{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)!==Ee.number){let o=this._getOrReturnCtx(e);return _e(o,{code:ie.invalid_type,expected:Ee.number,received:o.parsedType}),tt}let r,s=new Ar;for(let o of this._def.checks)o.kind==="int"?Pt.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.invalid_type,expected:"integer",received:"float",message:o.message}),s.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.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)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?vK(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.not_finite,message:o.message}),s.dirty()):Pt.assertNever(o);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,$e.toString(n))}gt(e,n){return this.setLimit("min",e,!1,$e.toString(n))}lte(e,n){return this.setLimit("max",e,!0,$e.toString(n))}lt(e,n){return this.setLimit("max",e,!1,$e.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:$e.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:$e.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:$e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:$e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:$e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:$e.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:$e.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:$e.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:$e.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:$e.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Pt.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Lp.create=t=>new Lp({checks:[],typeName:le.ZodNumber,coerce:t?.coerce||!1,...mt(t)});var zp=class t extends _t{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)!==Ee.bigint)return this._getInvalidInput(e);let r,s=new Ar;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.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)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),s.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),_e(r,{code:ie.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):Pt.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return _e(n,{code:ie.invalid_type,expected:Ee.bigint,received:n.parsedType}),tt}gte(e,n){return this.setLimit("min",e,!0,$e.toString(n))}gt(e,n){return this.setLimit("min",e,!1,$e.toString(n))}lte(e,n){return this.setLimit("max",e,!0,$e.toString(n))}lt(e,n){return this.setLimit("max",e,!1,$e.toString(n))}setLimit(e,n,r,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:$e.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:$e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:$e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:$e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:$e.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:$e.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};zp.create=t=>new zp({checks:[],typeName:le.ZodBigInt,coerce:t?.coerce??!1,...mt(t)});var Bp=class extends _t{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Ee.boolean){let r=this._getOrReturnCtx(e);return _e(r,{code:ie.invalid_type,expected:Ee.boolean,received:r.parsedType}),tt}return qr(e.data)}};Bp.create=t=>new Bp({typeName:le.ZodBoolean,coerce:t?.coerce||!1,...mt(t)});var qp=class t extends _t{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Ee.date){let o=this._getOrReturnCtx(e);return _e(o,{code:ie.invalid_type,expected:Ee.date,received:o.parsedType}),tt}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return _e(o,{code:ie.invalid_date}),tt}let r=new Ar,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(s=this._getOrReturnCtx(e,s),_e(s,{code:ie.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):Pt.assertNever(o);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:$e.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:$e.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};qp.create=t=>new qp({checks:[],coerce:t?.coerce||!1,typeName:le.ZodDate,...mt(t)});var Hp=class extends _t{_parse(e){if(this._getType(e)!==Ee.symbol){let r=this._getOrReturnCtx(e);return _e(r,{code:ie.invalid_type,expected:Ee.symbol,received:r.parsedType}),tt}return qr(e.data)}};Hp.create=t=>new Hp({typeName:le.ZodSymbol,...mt(t)});var Kl=class extends _t{_parse(e){if(this._getType(e)!==Ee.undefined){let r=this._getOrReturnCtx(e);return _e(r,{code:ie.invalid_type,expected:Ee.undefined,received:r.parsedType}),tt}return qr(e.data)}};Kl.create=t=>new Kl({typeName:le.ZodUndefined,...mt(t)});var Zl=class extends _t{_parse(e){if(this._getType(e)!==Ee.null){let r=this._getOrReturnCtx(e);return _e(r,{code:ie.invalid_type,expected:Ee.null,received:r.parsedType}),tt}return qr(e.data)}};Zl.create=t=>new Zl({typeName:le.ZodNull,...mt(t)});var Wp=class extends _t{constructor(){super(...arguments),this._any=!0}_parse(e){return qr(e.data)}};Wp.create=t=>new Wp({typeName:le.ZodAny,...mt(t)});var la=class extends _t{constructor(){super(...arguments),this._unknown=!0}_parse(e){return qr(e.data)}};la.create=t=>new la({typeName:le.ZodUnknown,...mt(t)});var Yo=class extends _t{_parse(e){let n=this._getOrReturnCtx(e);return _e(n,{code:ie.invalid_type,expected:Ee.never,received:n.parsedType}),tt}};Yo.create=t=>new Yo({typeName:le.ZodNever,...mt(t)});var Up=class extends _t{_parse(e){if(this._getType(e)!==Ee.undefined){let r=this._getOrReturnCtx(e);return _e(r,{code:ie.invalid_type,expected:Ee.void,received:r.parsedType}),tt}return qr(e.data)}};Up.create=t=>new Up({typeName:le.ZodVoid,...mt(t)});var ua=class t extends _t{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==Ee.array)return _e(n,{code:ie.invalid_type,expected:Ee.array,received:n.parsedType}),tt;if(s.exactLength!==null){let i=n.data.length>s.exactLength.value,a=n.data.length<s.exactLength.value;(i||a)&&(_e(n,{code:i?ie.too_big:ie.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}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(_e(n,{code:ie.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(_e(n,{code:ie.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>s.type._parseAsync(new to(n,i,n.path,a)))).then(i=>Ar.mergeArray(r,i));let o=[...n.data].map((i,a)=>s.type._parseSync(new to(n,i,n.path,a)));return Ar.mergeArray(r,o)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:$e.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:$e.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:$e.toString(n)}})}nonempty(e){return this.min(1,e)}};ua.create=(t,e)=>new ua({type:t,minLength:null,maxLength:null,exactLength:null,typeName:le.ZodArray,...mt(e)});function Wl(t){if(t instanceof Is){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=As.create(Wl(r))}return new Is({...t._def,shape:()=>e})}else return t instanceof ua?new ua({...t._def,type:Wl(t.element)}):t instanceof As?As.create(Wl(t.unwrap())):t instanceof Ni?Ni.create(Wl(t.unwrap())):t instanceof Ii?Ii.create(t.items.map(e=>Wl(e))):t}var Is=class t extends _t{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(),n=Pt.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==Ee.object){let l=this._getOrReturnCtx(e);return _e(l,{code:ie.invalid_type,expected:Ee.object,received:l.parsedType}),tt}let{status:r,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Yo&&this._def.unknownKeys==="strip"))for(let l in s.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=o[l],d=s.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new to(s,d,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof Yo){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(l==="strict")a.length>0&&(_e(s,{code:ie.unrecognized_keys,keys:a}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let d=s.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new to(s,d,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let d=await u.key,p=await u.value;l.push({key:d,value:p,alwaysSet:u.alwaysSet})}return l}).then(l=>Ar.mergeObjectSync(r,l)):Ar.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return $e.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:$e.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:le.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of Pt.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of Pt.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Wl(this)}partial(e){let n={};for(let r of Pt.objectKeys(this.shape)){let s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of Pt.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof As;)o=o._def.innerType;n[r]=o}return new t({...this._def,shape:()=>n})}keyof(){return c0(Pt.objectKeys(this.shape))}};Is.create=(t,e)=>new Is({shape:()=>t,unknownKeys:"strip",catchall:Yo.create(),typeName:le.ZodObject,...mt(e)});Is.strictCreate=(t,e)=>new Is({shape:()=>t,unknownKeys:"strict",catchall:Yo.create(),typeName:le.ZodObject,...mt(e)});Is.lazycreate=(t,e)=>new Is({shape:t,unknownKeys:"strip",catchall:Yo.create(),typeName:le.ZodObject,...mt(e)});var Gl=class extends _t{_parse(e){let{ctx:n}=this._processInputParams(e),r=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 n.common.issues.push(...a.ctx.common.issues),a.result;let i=o.map(a=>new Cs(a.ctx.common.issues));return _e(n,{code:ie.invalid_union,unionErrors:i}),tt}if(n.common.async)return Promise.all(r.map(async o=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of r){let l={...n,common:{...n.common,issues:[]},parent:null},u=c._parseSync({data:n.data,path:n.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new Cs(c));return _e(n,{code:ie.invalid_union,unionErrors:a}),tt}}get options(){return this._def.options}};Gl.create=(t,e)=>new Gl({options:t,typeName:le.ZodUnion,...mt(e)});var Ai=t=>t instanceof Vl?Ai(t.schema):t instanceof Co?Ai(t.innerType()):t instanceof Xl?[t.value]:t instanceof Ql?t.options:t instanceof Yl?Pt.objectValues(t.enum):t instanceof eu?Ai(t._def.innerType):t instanceof Kl?[void 0]:t instanceof Zl?[null]:t instanceof As?[void 0,...Ai(t.unwrap())]:t instanceof Ni?[null,...Ai(t.unwrap())]:t instanceof Hg||t instanceof nu?Ai(t.unwrap()):t instanceof tu?Ai(t._def.innerType):[],nw=class t extends _t{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ee.object)return _e(n,{code:ie.invalid_type,expected:Ee.object,received:n.parsedType}),tt;let r=this.discriminator,s=n.data[r],o=this.optionsMap.get(s);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(_e(n,{code:ie.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),tt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let s=new Map;for(let o of n){let i=Ai(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:le.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...mt(r)})}};function rw(t,e){let n=Ci(t),r=Ci(e);if(t===e)return{valid:!0,data:t};if(n===Ee.object&&r===Ee.object){let s=Pt.objectKeys(e),o=Pt.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=rw(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===Ee.array&&r===Ee.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=rw(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return n===Ee.date&&r===Ee.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Jl=class extends _t{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=(o,i)=>{if(Y_(o)||Y_(i))return tt;let a=rw(o.value,i.value);return a.valid?((ew(o)||ew(i))&&n.dirty(),{status:n.value,value:a.data}):(_e(r,{code:ie.invalid_intersection_types}),tt)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Jl.create=(t,e,n)=>new Jl({left:t,right:e,typeName:le.ZodIntersection,...mt(n)});var Ii=class t extends _t{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ee.array)return _e(r,{code:ie.invalid_type,expected:Ee.array,received:r.parsedType}),tt;if(r.data.length<this._def.items.length)return _e(r,{code:ie.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),tt;!this._def.rest&&r.data.length>this._def.items.length&&(_e(r,{code:ie.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new to(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(o).then(i=>Ar.mergeArray(n,i)):Ar.mergeArray(n,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Ii.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ii({items:t,typeName:le.ZodTuple,rest:null,...mt(e)})};var sw=class t extends _t{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ee.object)return _e(r,{code:ie.invalid_type,expected:Ee.object,received:r.parsedType}),tt;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in r.data)s.push({key:o._parse(new to(r,a,r.path,a)),value:i._parse(new to(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Ar.mergeObjectAsync(n,s):Ar.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof _t?new t({keyType:e,valueType:n,typeName:le.ZodRecord,...mt(r)}):new t({keyType:Ul.create(),valueType:e,typeName:le.ZodRecord,...mt(n)})}},Kp=class extends _t{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ee.map)return _e(r,{code:ie.invalid_type,expected:Ee.map,received:r.parsedType}),tt;let s=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map(([a,c],l)=>({key:s._parse(new to(r,a,r.path,[l,"key"])),value:o._parse(new to(r,c,r.path,[l,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return tt;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return tt;(l.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(l.value,u.value)}return{status:n.value,value:a}}}};Kp.create=(t,e,n)=>new Kp({valueType:e,keyType:t,typeName:le.ZodMap,...mt(n)});var Zp=class t extends _t{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ee.set)return _e(r,{code:ie.invalid_type,expected:Ee.set,received:r.parsedType}),tt;let s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(_e(r,{code:ie.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(_e(r,{code:ie.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());let o=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return tt;u.status==="dirty"&&n.dirty(),l.add(u.value)}return{status:n.value,value:l}}let a=[...r.data.values()].map((c,l)=>o._parse(new to(r,c,r.path,l)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:$e.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:$e.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Zp.create=(t,e)=>new Zp({valueType:t,minSize:null,maxSize:null,typeName:le.ZodSet,...mt(e)});var ow=class t extends _t{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ee.function)return _e(n,{code:ie.invalid_type,expected:Ee.function,received:n.parsedType}),tt;function r(a,c){return qg({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,$p(),ca].filter(l=>!!l),issueData:{code:ie.invalid_arguments,argumentsError:c}})}function s(a,c){return qg({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,$p(),ca].filter(l=>!!l),issueData:{code:ie.invalid_return_type,returnTypeError:c}})}let o={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Rc){let a=this;return qr(async function(...c){let l=new Cs([]),u=await a._def.args.parseAsync(c,o).catch(f=>{throw l.addIssue(r(c,f)),l}),d=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(d,o).catch(f=>{throw l.addIssue(s(d,f)),l})})}else{let a=this;return qr(function(...c){let l=a._def.args.safeParse(c,o);if(!l.success)throw new Cs([r(c,l.error)]);let u=Reflect.apply(i,this,l.data),d=a._def.returns.safeParse(u,o);if(!d.success)throw new Cs([s(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Ii.create(e).rest(la.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,n,r){return new t({args:e||Ii.create([]).rest(la.create()),returns:n||la.create(),typeName:le.ZodFunction,...mt(r)})}},Vl=class extends _t{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Vl.create=(t,e)=>new Vl({getter:t,typeName:le.ZodLazy,...mt(e)});var Xl=class extends _t{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return _e(n,{received:n.data,code:ie.invalid_literal,expected:this._def.value}),tt}return{status:"valid",value:e.data}}get value(){return this._def.value}};Xl.create=(t,e)=>new Xl({value:t,typeName:le.ZodLiteral,...mt(e)});function c0(t,e){return new Ql({values:t,typeName:le.ZodEnum,...mt(e)})}var Ql=class t extends _t{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return _e(n,{expected:Pt.joinValues(r),received:n.parsedType,code:ie.invalid_type}),tt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return _e(n,{received:n.data,code:ie.invalid_enum_value,options:r}),tt}return qr(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Ql.create=c0;var Yl=class extends _t{_parse(e){let n=Pt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Ee.string&&r.parsedType!==Ee.number){let s=Pt.objectValues(n);return _e(r,{expected:Pt.joinValues(s),received:r.parsedType,code:ie.invalid_type}),tt}if(this._cache||(this._cache=new Set(Pt.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=Pt.objectValues(n);return _e(r,{received:r.data,code:ie.invalid_enum_value,options:s}),tt}return qr(e.data)}get enum(){return this._def.values}};Yl.create=(t,e)=>new Yl({values:t,typeName:le.ZodNativeEnum,...mt(e)});var Rc=class extends _t{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ee.promise&&n.common.async===!1)return _e(n,{code:ie.invalid_type,expected:Ee.promise,received:n.parsedType}),tt;let r=n.parsedType===Ee.promise?n.data:Promise.resolve(n.data);return qr(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Rc.create=(t,e)=>new Rc({type:t,typeName:le.ZodPromise,...mt(e)});var Co=class extends _t{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===le.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:i=>{_e(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(r.data,o);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return tt;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?tt:c.status==="dirty"?Hl(c.value):n.value==="dirty"?Hl(c.value):c});{if(n.value==="aborted")return tt;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?tt:a.status==="dirty"?Hl(a.value):n.value==="dirty"?Hl(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(r.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(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?tt:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?tt:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(s.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!vc(i))return tt;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:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>vc(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:n.value,value:a})):tt);Pt.assertNever(s)}};Co.create=(t,e,n)=>new Co({schema:t,typeName:le.ZodEffects,effect:e,...mt(n)});Co.createWithPreprocess=(t,e,n)=>new Co({schema:e,effect:{type:"preprocess",transform:t},typeName:le.ZodEffects,...mt(n)});var As=class extends _t{_parse(e){return this._getType(e)===Ee.undefined?qr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};As.create=(t,e)=>new As({innerType:t,typeName:le.ZodOptional,...mt(e)});var Ni=class extends _t{_parse(e){return this._getType(e)===Ee.null?qr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ni.create=(t,e)=>new Ni({innerType:t,typeName:le.ZodNullable,...mt(e)});var eu=class extends _t{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===Ee.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};eu.create=(t,e)=>new eu({innerType:t,typeName:le.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...mt(e)});var tu=class extends _t{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return jp(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Cs(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Cs(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};tu.create=(t,e)=>new tu({innerType:t,typeName:le.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...mt(e)});var Gp=class extends _t{_parse(e){if(this._getType(e)!==Ee.nan){let r=this._getOrReturnCtx(e);return _e(r,{code:ie.invalid_type,expected:Ee.nan,received:r.parsedType}),tt}return{status:"valid",value:e.data}}};Gp.create=t=>new Gp({typeName:le.ZodNaN,...mt(t)});var Hg=class extends _t{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Wg=class t extends _t{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?tt:o.status==="dirty"?(n.dirty(),Hl(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?tt:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:le.ZodPipeline})}},nu=class extends _t{_parse(e){let n=this._def.innerType._parse(e),r=s=>(vc(s)&&(s.value=Object.freeze(s.value)),s);return jp(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};nu.create=(t,e)=>new nu({innerType:t,typeName:le.ZodReadonly,...mt(e)});var Aae={object:Is.lazycreate},le;(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"})(le||(le={}));var Iae=Ul.create,Nae=Lp.create,Dae=Gp.create,Oae=zp.create,Mae=Bp.create,Fae=qp.create,$ae=Hp.create,jae=Kl.create,Lae=Zl.create,zae=Wp.create,Bae=la.create,qae=Yo.create,Hae=Up.create,Wae=ua.create,l0=Is.create,Uae=Is.strictCreate,Kae=Gl.create,Zae=nw.create,Gae=Jl.create,Jae=Ii.create,Vae=sw.create,Xae=Kp.create,Qae=Zp.create,Yae=ow.create,ece=Vl.create,tce=Xl.create,nce=Ql.create,rce=Yl.create,sce=Rc.create,oce=Co.create,ice=As.create,ace=Ni.create,cce=Co.createWithPreprocess,lce=Wg.create;var RK=Object.freeze({status:"aborted"});function Y(t,e,n){function r(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(t),e(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let s=n?.Parent??Object;class o extends s{}Object.defineProperty(o,"name",{value:t});function i(a){var c;let l=n?.Parent?new o:this;r(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Di=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ug={};function Ns(t){return t&&Object.assign(Ug,t),Ug}var Ct={};Yt(Ct,{BIGINT_FORMAT_RANGES:()=>d0,Class:()=>aw,NUMBER_FORMAT_RANGES:()=>mw,aborted:()=>Ec,allowsEval:()=>dw,assert:()=>CK,assertEqual:()=>kK,assertIs:()=>TK,assertNever:()=>PK,assertNotEqual:()=>EK,assignProp:()=>uw,cached:()=>Xp,captureStackTrace:()=>Zg,cleanEnum:()=>qK,cleanRegex:()=>Yp,clone:()=>Ds,createTransparentProxy:()=>MK,defineLazy:()=>ln,esc:()=>kc,escapeRegex:()=>da,extend:()=>jK,finalizeIssue:()=>Ao,floatSafeRemainder:()=>lw,getElementAtPath:()=>AK,getEnumValues:()=>Vp,getLengthableOrigin:()=>ef,getParsedType:()=>OK,getSizableOrigin:()=>p0,isObject:()=>ru,isPlainObject:()=>su,issue:()=>hw,joinValues:()=>Kg,jsonStringifyReplacer:()=>cw,merge:()=>LK,normalizeParams:()=>et,nullish:()=>Qp,numKeys:()=>DK,omit:()=>$K,optionalKeys:()=>fw,partial:()=>zK,pick:()=>FK,prefixIssues:()=>ei,primitiveTypes:()=>u0,promiseAllObject:()=>IK,propertyKeyTypes:()=>pw,randomString:()=>NK,required:()=>BK,stringifyPrimitive:()=>Gg,unwrapMessage:()=>Jp});function kK(t){return t}function EK(t){return t}function TK(t){}function PK(t){throw new Error}function CK(t){}function Vp(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function Kg(t,e="|"){return t.map(n=>Gg(n)).join(e)}function cw(t,e){return typeof e=="bigint"?e.toString():e}function Xp(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Qp(t){return t==null}function Yp(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function lw(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function ln(t,e,n){Object.defineProperty(t,e,{get(){{let s=n();return t[e]=s,s}throw new Error("cached value already set")},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function uw(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function AK(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function IK(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let s={};for(let o=0;o<e.length;o++)s[e[o]]=r[o];return s})}function NK(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function kc(t){return JSON.stringify(t)}var Zg=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function ru(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var dw=Xp(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function su(t){if(ru(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(ru(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function DK(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var OK=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}`)}},pw=new Set(["string","number","symbol"]),u0=new Set(["string","number","bigint","boolean","symbol","undefined"]);function da(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ds(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function et(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 MK(t){let e;return new Proxy({},{get(n,r,s){return e??(e=t()),Reflect.get(e,r,s)},set(n,r,s,o){return e??(e=t()),Reflect.set(e,r,s,o)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,s){return e??(e=t()),Reflect.defineProperty(e,r,s)}})}function Gg(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function fw(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var mw={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]},d0={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function FK(t,e){let n={},r=t._zod.def;for(let s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&(n[s]=r.shape[s])}return Ds(t,{...t._zod.def,shape:n,checks:[]})}function $K(t,e){let n={...t._zod.def.shape},r=t._zod.def;for(let s in e){if(!(s in r.shape))throw new Error(`Unrecognized key: "${s}"`);e[s]&&delete n[s]}return Ds(t,{...t._zod.def,shape:n,checks:[]})}function jK(t,e){if(!su(e))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let r={...t._zod.def.shape,...e};return uw(this,"shape",r),r},checks:[]};return Ds(t,n)}function LK(t,e){return Ds(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return uw(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function zK(t,e,n){let r=e._zod.def.shape,s={...r};if(n)for(let o in n){if(!(o in r))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(s[o]=t?new t({type:"optional",innerType:r[o]}):r[o])}else for(let o in r)s[o]=t?new t({type:"optional",innerType:r[o]}):r[o];return Ds(e,{...e._zod.def,shape:s,checks:[]})}function BK(t,e,n){let r=e._zod.def.shape,s={...r};if(n)for(let o in n){if(!(o in s))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(s[o]=new t({type:"nonoptional",innerType:r[o]}))}else for(let o in r)s[o]=new t({type:"nonoptional",innerType:r[o]});return Ds(e,{...e._zod.def,shape:s,checks:[]})}function Ec(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function ei(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Jp(t){return typeof t=="string"?t:t?.message}function Ao(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let s=Jp(t.inst?._zod.def?.error?.(t))??Jp(e?.error?.(t))??Jp(n.customError?.(t))??Jp(n.localeError?.(t))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function p0(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ef(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function hw(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function qK(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var aw=class{constructor(...e){}};var f0=(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,cw,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Jg=Y("$ZodError",f0),tf=Y("$ZodError",f0,{Parent:Error});function gw(t,e=n=>n.message){let n={},r=[];for(let s of t.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}function yw(t,e){let n=e||function(o){return o.message},r={_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)r._errors.push(n(i));else{let a=r,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(n(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return s(t),r}var bw=t=>(e,n,r,s)=>{let o=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Di;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>Ao(c,o,Ns())));throw Zg(a,s?.callee),a}return i.value},Sw=bw(tf),xw=t=>async(e,n,r,s)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>Ao(c,o,Ns())));throw Zg(a,s?.callee),a}return i.value},_w=xw(tf),ww=t=>(e,n,r)=>{let s=r?{...r,async:!1}:{async:!1},o=e._zod.run({value:n,issues:[]},s);if(o instanceof Promise)throw new Di;return o.issues.length?{success:!1,error:new(t??Jg)(o.issues.map(i=>Ao(i,s,Ns())))}:{success:!0,data:o.value}},Tc=ww(tf),vw=t=>async(e,n,r)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},o=e._zod.run({value:n,issues:[]},s);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new t(o.issues.map(i=>Ao(i,s,Ns())))}:{success:!0,data:o.value}},Pc=vw(tf);var m0=/^[cC][^\s-]{8,}$/,h0=/^[0-9a-z]+$/,g0=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,y0=/^[0-9a-vA-V]{20}$/,b0=/^[A-Za-z0-9]{27}$/,S0=/^[a-zA-Z0-9_-]{21}$/,x0=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var _0=/^([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})$/,Rw=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 w0=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var WK="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function v0(){return new RegExp(WK,"u")}var R0=/^(?:(?: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])$/,k0=/^(([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})$/,E0=/^((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])$/,T0=/^(([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])$/,P0=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kw=/^[A-Za-z0-9_-]*$/,C0=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var A0=/^\+(?:[0-9]){6,14}[0-9]$/,I0="(?:(?:\\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])))",N0=new RegExp(`^${I0}$`);function D0(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 O0(t){return new RegExp(`^${D0(t)}$`)}function M0(t){let e=D0({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${I0}T(?:${r})$`)}var F0=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var $0=/^\d+$/,j0=/^-?\d+(?:\.\d+)?/i,L0=/true|false/i,z0=/null/i;var B0=/^[^A-Z]*$/,q0=/^[^a-z]*$/;var br=Y("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),H0={number:"number",bigint:"bigint",object:"date"},Ew=Y("$ZodCheckLessThan",(t,e)=>{br.init(t,e);let n=H0[typeof e.value];t._zod.onattach.push(r=>{let s=r._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=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Tw=Y("$ZodCheckGreaterThan",(t,e)=>{br.init(t,e);let n=H0[typeof e.value];t._zod.onattach.push(r=>{let s=r._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=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),W0=Y("$ZodCheckMultipleOf",(t,e)=>{br.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):lw(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),U0=Y("$ZodCheckNumberFormat",(t,e)=>{br.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[s,o]=mw[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=s,a.maximum=o,n&&(a.pattern=$0)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,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:r,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:r,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 K0=Y("$ZodCheckMaxLength",(t,e)=>{var n;br.init(t,e),(n=t._zod.def).when??(n.when=r=>{let s=r.value;return!Qp(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{let s=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<s&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let s=r.value;if(s.length<=e.maximum)return;let i=ef(s);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Z0=Y("$ZodCheckMinLength",(t,e)=>{var n;br.init(t,e),(n=t._zod.def).when??(n.when=r=>{let s=r.value;return!Qp(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{let s=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>s&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let s=r.value;if(s.length>=e.minimum)return;let i=ef(s);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),G0=Y("$ZodCheckLengthEquals",(t,e)=>{var n;br.init(t,e),(n=t._zod.def).when??(n.when=r=>{let s=r.value;return!Qp(s)&&s.length!==void 0}),t._zod.onattach.push(r=>{let s=r._zod.bag;s.minimum=e.length,s.maximum=e.length,s.length=e.length}),t._zod.check=r=>{let s=r.value,o=s.length;if(o===e.length)return;let i=ef(s),a=o>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),nf=Y("$ZodCheckStringFormat",(t,e)=>{var n,r;br.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?(n=t._zod).check??(n.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})}):(r=t._zod).check??(r.check=()=>{})}),J0=Y("$ZodCheckRegex",(t,e)=>{nf.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),V0=Y("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=B0),nf.init(t,e)}),X0=Y("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=q0),nf.init(t,e)}),Q0=Y("$ZodCheckIncludes",(t,e)=>{br.init(t,e);let n=da(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(s=>{let o=s._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),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})}}),Y0=Y("$ZodCheckStartsWith",(t,e)=>{br.init(t,e);let n=new RegExp(`^${da(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),eD=Y("$ZodCheckEndsWith",(t,e)=>{br.init(t,e);let n=new RegExp(`.*${da(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let s=r._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}});var tD=Y("$ZodCheckOverwrite",(t,e)=>{br.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var Xg=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 r=e.split(`
895
895
  `).filter(i=>i),s=Math.min(...r.map(i=>i.length-i.trimStart().length)),o=r.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,n=this?.args,s=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...n,s.join(`
896
896
  `))}};var rD={major:4,minor:0,patch:0};var en=Y("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=rD;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let s of r)for(let o of s._zod.onattach)o(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let s=(o,i,a)=>{let c=Ec(o),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(o))continue}else if(c)continue;let d=o.issues.length,p=u._zod.check(o);if(p instanceof Promise&&a?.async===!1)throw new Di;if(l||p instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await p,o.issues.length!==d&&(c||(c=Ec(o,d)))});else{if(o.issues.length===d)continue;c||(c=Ec(o,d))}}return l?l.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 Di;return a.then(c=>s(c,r,i))}return s(a,r,i)}}t["~standard"]={validate:s=>{try{let o=Tc(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Pc(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),rf=Y("$ZodString",(t,e)=>{en.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??F0(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),un=Y("$ZodStringFormat",(t,e)=>{nf.init(t,e),rf.init(t,e)}),Cw=Y("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=_0),un.init(t,e)}),Aw=Y("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Rw(r))}else e.pattern??(e.pattern=Rw());un.init(t,e)}),Iw=Y("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=w0),un.init(t,e)}),Nw=Y("$ZodURL",(t,e)=>{un.init(t,e),t._zod.check=n=>{try{let r=n.value,s=new URL(r),o=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:C0.source,input:n.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)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&o.endsWith("/")?n.value=o.slice(0,-1):n.value=o;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),Dw=Y("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=v0()),un.init(t,e)}),Ow=Y("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=S0),un.init(t,e)}),Mw=Y("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=m0),un.init(t,e)}),Fw=Y("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=h0),un.init(t,e)}),$w=Y("$ZodULID",(t,e)=>{e.pattern??(e.pattern=g0),un.init(t,e)}),jw=Y("$ZodXID",(t,e)=>{e.pattern??(e.pattern=y0),un.init(t,e)}),Lw=Y("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=b0),un.init(t,e)}),fD=Y("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=M0(e)),un.init(t,e)}),mD=Y("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=N0),un.init(t,e)}),hD=Y("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=O0(e)),un.init(t,e)}),gD=Y("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=x0),un.init(t,e)}),zw=Y("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=R0),un.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv4"})}),Bw=Y("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=k0),un.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),qw=Y("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=E0),un.init(t,e)}),Hw=Y("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=T0),un.init(t,e),t._zod.check=n=>{let[r,s]=n.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://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function yD(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var Ww=Y("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=P0),un.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{yD(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function UK(t){if(!kw.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return yD(n)}var Uw=Y("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=kw),un.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{UK(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Kw=Y("$ZodE164",(t,e)=>{e.pattern??(e.pattern=A0),un.init(t,e)});function KK(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let s=JSON.parse(atob(r));return!("typ"in s&&s?.typ!=="JWT"||!s.alg||e&&(!("alg"in s)||s.alg!==e))}catch{return!1}}var Zw=Y("$ZodJWT",(t,e)=>{un.init(t,e),t._zod.check=n=>{KK(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var Yg=Y("$ZodNumber",(t,e)=>{en.init(t,e),t._zod.pattern=t._zod.bag.pattern??j0,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let s=n.value;if(typeof s=="number"&&!Number.isNaN(s)&&Number.isFinite(s))return n;let o=typeof s=="number"?Number.isNaN(s)?"NaN":Number.isFinite(s)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:s,inst:t,...o?{received:o}:{}}),n}}),Gw=Y("$ZodNumber",(t,e)=>{U0.init(t,e),Yg.init(t,e)}),Jw=Y("$ZodBoolean",(t,e)=>{en.init(t,e),t._zod.pattern=L0,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let s=n.value;return typeof s=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:s,inst:t}),n}});var Vw=Y("$ZodNull",(t,e)=>{en.init(t,e),t._zod.pattern=z0,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let s=n.value;return s===null||n.issues.push({expected:"null",code:"invalid_type",input:s,inst:t}),n}});var Xw=Y("$ZodUnknown",(t,e)=>{en.init(t,e),t._zod.parse=n=>n}),Qw=Y("$ZodNever",(t,e)=>{en.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function sD(t,e,n){t.issues.length&&e.issues.push(...ei(n,t.issues)),e.value[n]=t.value}var Yw=Y("$ZodArray",(t,e)=>{en.init(t,e),t._zod.parse=(n,r)=>{let s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:t}),n;n.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:[]},r);c instanceof Promise?o.push(c.then(l=>sD(l,n,i))):sD(c,n,i)}return o.length?Promise.all(o).then(()=>n):n}});function Qg(t,e,n){t.issues.length&&e.issues.push(...ei(n,t.issues)),e.value[n]=t.value}function oD(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...ei(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}var ey=Y("$ZodObject",(t,e)=>{en.init(t,e);let n=Xp(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof en))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=fw(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});ln(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 r=d=>{let p=new Xg(["shape","payload","ctx"]),f=n.value,m=b=>{let S=kc(b);return`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),g=0;for(let b of f.keys)h[b]=`key_${g++}`;p.write("const newResult = {}");for(let b of f.keys)if(f.optionalKeys.has(b)){let S=h[b];p.write(`const ${S} = ${m(b)};`);let x=kc(b);p.write(`
897
897
  if (${S}.issues.length) {
@@ -918,7 +918,7 @@ ${r.join(`
918
918
  path: iss.path ? [${kc(b)}, ...iss.path] : [${kc(b)}]
919
919
  })));`),p.write(`newResult[${kc(b)}] = ${S}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let y=p.compile();return(b,S)=>y(d,b,S)},s,o=ru,i=!Ug.jitless,c=i&&dw.value,l=e.catchall,u;t._zod.parse=(d,p)=>{u??(u=n.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=r(e.shape)),d=s(d,p);else{d.value={};let S=u.shape;for(let x of u.keys){let w=S[x],R=w._zod.run({value:f[x],issues:[]},p),E=w._zod.optin==="optional"&&w._zod.optout==="optional";R instanceof Promise?m.push(R.then(_=>E?oD(_,d,x,f):Qg(_,d,x))):E?oD(R,d,x,f):Qg(R,d,x)}}if(!l)return m.length?Promise.all(m).then(()=>d):d;let h=[],g=u.keySet,y=l._zod,b=y.def.type;for(let S of Object.keys(f)){if(g.has(S))continue;if(b==="never"){h.push(S);continue}let x=y.run({value:f[S],issues:[]},p);x instanceof Promise?m.push(x.then(w=>Qg(w,d,S))):Qg(x,d,S)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});function iD(t,e,n,r){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:n,errors:t.map(s=>s.issues.map(o=>Ao(o,r,Ns())))}),e}var ty=Y("$ZodUnion",(t,e)=>{en.init(t,e),ln(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),ln(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),ln(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),ln(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>Yp(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let s=!1,o=[];for(let i of e.options){let a=i._zod.run({value:n.value,issues:[]},r);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=>iD(i,n,t,r)):iD(o,n,t,r)}}),ev=Y("$ZodDiscriminatedUnion",(t,e)=>{ty.init(t,e);let n=t._zod.parse;ln(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 l of c)s[a].add(l)}}return s});let r=Xp(()=>{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(!ru(i))return s.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),s;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(s,o):e.unionFallback?n(s,o):(s.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),s)}}),tv=Y("$ZodIntersection",(t,e)=>{en.init(t,e),t._zod.parse=(n,r)=>{let s=n.value,o=e.left._zod.run({value:s,issues:[]},r),i=e.right._zod.run({value:s,issues:[]},r);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([c,l])=>aD(n,c,l)):aD(n,o,i)}});function Pw(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(su(t)&&su(e)){let n=Object.keys(e),r=Object.keys(t).filter(o=>n.indexOf(o)!==-1),s={...t,...e};for(let o of r){let i=Pw(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 n=[];for(let r=0;r<t.length;r++){let s=t[r],o=e[r],i=Pw(s,o);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function aD(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),Ec(t))return t;let r=Pw(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}var nv=Y("$ZodRecord",(t,e)=>{en.init(t,e),t._zod.parse=(n,r)=>{let s=n.value;if(!su(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:t}),n;let o=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;n.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:s[c],issues:[]},r);l instanceof Promise?o.push(l.then(u=>{u.issues.length&&n.issues.push(...ei(c,u.issues)),n.value[c]=u.value})):(l.issues.length&&n.issues.push(...ei(c,l.issues)),n.value[c]=l.value)}let a;for(let c in s)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:t,keys:a})}else{n.value={};for(let i of Reflect.ownKeys(s)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>Ao(l,r,Ns())),input:i,path:[i],inst:t}),n.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:s[i],issues:[]},r);c instanceof Promise?o.push(c.then(l=>{l.issues.length&&n.issues.push(...ei(i,l.issues)),n.value[a.value]=l.value})):(c.issues.length&&n.issues.push(...ei(i,c.issues)),n.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>n):n}});var rv=Y("$ZodEnum",(t,e)=>{en.init(t,e);let n=Vp(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>pw.has(typeof r)).map(r=>typeof r=="string"?da(r):r.toString()).join("|")})$`),t._zod.parse=(r,s)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:n,input:o,inst:t}),r}}),sv=Y("$ZodLiteral",(t,e)=>{en.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?da(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),n}});var ov=Y("$ZodTransform",(t,e)=>{en.init(t,e),t._zod.parse=(n,r)=>{let s=e.transform(n.value,n);if(r.async)return(s instanceof Promise?s:Promise.resolve(s)).then(i=>(n.value=i,n));if(s instanceof Promise)throw new Di;return n.value=s,n}}),iv=Y("$ZodOptional",(t,e)=>{en.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ln(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ln(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${Yp(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),av=Y("$ZodNullable",(t,e)=>{en.init(t,e),ln(t._zod,"optin",()=>e.innerType._zod.optin),ln(t._zod,"optout",()=>e.innerType._zod.optout),ln(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${Yp(n.source)}|null)$`):void 0}),ln(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),cv=Y("$ZodDefault",(t,e)=>{en.init(t,e),t._zod.optin="optional",ln(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;let s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(o=>cD(o,e)):cD(s,e)}});function cD(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var lv=Y("$ZodPrefault",(t,e)=>{en.init(t,e),t._zod.optin="optional",ln(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),uv=Y("$ZodNonOptional",(t,e)=>{en.init(t,e),ln(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(o=>lD(o,t)):lD(s,t)}});function lD(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 dv=Y("$ZodCatch",(t,e)=>{en.init(t,e),t._zod.optin="optional",ln(t._zod,"optout",()=>e.innerType._zod.optout),ln(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{let s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(o=>(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(i=>Ao(i,r,Ns()))},input:n.value}),n.issues=[]),n)):(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(o=>Ao(o,r,Ns()))},input:n.value}),n.issues=[]),n)}});var pv=Y("$ZodPipe",(t,e)=>{en.init(t,e),ln(t._zod,"values",()=>e.in._zod.values),ln(t._zod,"optin",()=>e.in._zod.optin),ln(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{let s=e.in._zod.run(n,r);return s instanceof Promise?s.then(o=>uD(o,e,r)):uD(s,e,r)}});function uD(t,e,n){return Ec(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}var fv=Y("$ZodReadonly",(t,e)=>{en.init(t,e),ln(t._zod,"propValues",()=>e.innerType._zod.propValues),ln(t._zod,"values",()=>e.innerType._zod.values),ln(t._zod,"optin",()=>e.innerType._zod.optin),ln(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{let s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(dD):dD(s)}});function dD(t){return t.value=Object.freeze(t.value),t}var mv=Y("$ZodCustom",(t,e)=>{br.init(t,e),en.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,s=e.fn(r);if(s instanceof Promise)return s.then(o=>pD(o,n,r,t));pD(s,n,r,t)}});function pD(t,e,n,r){if(!t){let s={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(s.params=r._zod.def.params),e.issues.push(hw(s))}}var ZK=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},GK=()=>{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(r){return t[r]??null}let n={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 r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${ZK(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${Gg(r.values[0])}`:`Invalid option: expected one of ${Kg(r.values,"|")}`;case"too_big":{let s=r.inclusive?"<=":"<",o=e(r.origin);return o?`Too big: expected ${r.origin??"value"} to have ${s}${r.maximum.toString()} ${o.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${s}${r.maximum.toString()}`}case"too_small":{let s=r.inclusive?">=":">",o=e(r.origin);return o?`Too small: expected ${r.origin} to have ${s}${r.minimum.toString()} ${o.unit}`:`Too small: expected ${r.origin} to be ${s}${r.minimum.toString()}`}case"invalid_format":{let s=r;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 ${n[s.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${Kg(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function bD(){return{localeError:GK()}}var sf=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){let r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function SD(){return new sf}var pa=SD();function hv(t,e){return new t({type:"string",...et(e)})}function gv(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...et(e)})}function ny(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...et(e)})}function yv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...et(e)})}function bv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...et(e)})}function Sv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...et(e)})}function xv(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...et(e)})}function _v(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...et(e)})}function wv(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...et(e)})}function vv(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...et(e)})}function Rv(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...et(e)})}function kv(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...et(e)})}function Ev(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...et(e)})}function Tv(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...et(e)})}function Pv(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...et(e)})}function Cv(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...et(e)})}function Av(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...et(e)})}function Iv(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...et(e)})}function Nv(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...et(e)})}function Dv(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...et(e)})}function Ov(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...et(e)})}function Mv(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...et(e)})}function Fv(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...et(e)})}function xD(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...et(e)})}function _D(t,e){return new t({type:"string",format:"date",check:"string_format",...et(e)})}function wD(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...et(e)})}function vD(t,e){return new t({type:"string",format:"duration",check:"string_format",...et(e)})}function $v(t,e){return new t({type:"number",checks:[],...et(e)})}function jv(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...et(e)})}function Lv(t,e){return new t({type:"boolean",...et(e)})}function zv(t,e){return new t({type:"null",...et(e)})}function Bv(t){return new t({type:"unknown"})}function qv(t,e){return new t({type:"never",...et(e)})}function ry(t,e){return new Ew({check:"less_than",...et(e),value:t,inclusive:!1})}function of(t,e){return new Ew({check:"less_than",...et(e),value:t,inclusive:!0})}function sy(t,e){return new Tw({check:"greater_than",...et(e),value:t,inclusive:!1})}function af(t,e){return new Tw({check:"greater_than",...et(e),value:t,inclusive:!0})}function oy(t,e){return new W0({check:"multiple_of",...et(e),value:t})}function iy(t,e){return new K0({check:"max_length",...et(e),maximum:t})}function ou(t,e){return new Z0({check:"min_length",...et(e),minimum:t})}function ay(t,e){return new G0({check:"length_equals",...et(e),length:t})}function Hv(t,e){return new J0({check:"string_format",format:"regex",...et(e),pattern:t})}function Wv(t){return new V0({check:"string_format",format:"lowercase",...et(t)})}function Uv(t){return new X0({check:"string_format",format:"uppercase",...et(t)})}function Kv(t,e){return new Q0({check:"string_format",format:"includes",...et(e),includes:t})}function Zv(t,e){return new Y0({check:"string_format",format:"starts_with",...et(e),prefix:t})}function Gv(t,e){return new eD({check:"string_format",format:"ends_with",...et(e),suffix:t})}function Cc(t){return new tD({check:"overwrite",tx:t})}function Jv(t){return Cc(e=>e.normalize(t))}function Vv(){return Cc(t=>t.trim())}function Xv(){return Cc(t=>t.toLowerCase())}function Qv(){return Cc(t=>t.toUpperCase())}function RD(t,e,n){return new t({type:"array",element:e,...et(n)})}function Yv(t,e,n){let r=et(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function eR(t,e,n){return new t({type:"custom",check:"custom",fn:e,...et(n)})}var cy=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??pa,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,n={path:[],schemaPath:[]}){var r;let s=e._zod.def,o={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{let f=a.schema;switch(s.type){case"string":{let m=f;m.type="string";let{minimum:h,maximum:g,format:y,patterns:b,contentEncoding:S}=e._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof g=="number"&&(m.maxLength=g),y&&(m.format=o[y]??y,m.format===""&&delete m.format),S&&(m.contentEncoding=S),b&&b.size>0){let x=[...b];x.length===1?m.pattern=x[0].source:x.length>1&&(a.schema.allOf=[...x.map(w=>({...this.target==="draft-7"?{type:"string"}:{},pattern:w.source}))])}break}case"number":{let m=f,{minimum:h,maximum:g,format:y,multipleOf:b,exclusiveMaximum:S,exclusiveMinimum:x}=e._zod.bag;typeof y=="string"&&y.includes("int")?m.type="integer":m.type="number",typeof x=="number"&&(m.exclusiveMinimum=x),typeof h=="number"&&(m.minimum=h,typeof x=="number"&&(x>=h?delete m.minimum:delete m.exclusiveMinimum)),typeof S=="number"&&(m.exclusiveMaximum=S),typeof g=="number"&&(m.maximum=g,typeof S=="number"&&(S<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof b=="number"&&(m.multipleOf=b);break}case"boolean":{let m=f;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=f,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(m.minItems=h),typeof g=="number"&&(m.maxItems=g),m.type="array",m.items=this.process(s.element,{...d,path:[...d.path,"items"]});break}case"object":{let m=f;m.type="object",m.properties={};let h=s.shape;for(let b in h)m.properties[b]=this.process(h[b],{...d,path:[...d.path,"properties",b]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(b=>{let S=s.shape[b]._zod;return this.io==="input"?S.optin===void 0:S.optout===void 0}));y.size>0&&(m.required=Array.from(y)),s.catchall?._zod.def.type==="never"?m.additionalProperties=!1:s.catchall?s.catchall&&(m.additionalProperties=this.process(s.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=f;m.anyOf=s.options.map((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let m=f,h=this.process(s.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(s.right,{...d,path:[...d.path,"allOf",1]}),y=S=>"allOf"in S&&Object.keys(S).length===1,b=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];m.allOf=b;break}case"tuple":{let m=f;m.type="array";let h=s.items.map((b,S)=>this.process(b,{...d,path:[...d.path,"prefixItems",S]}));if(this.target==="draft-2020-12"?m.prefixItems=h:m.items=h,s.rest){let b=this.process(s.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?m.items=b:m.additionalItems=b}s.rest&&(m.items=this.process(s.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof y=="number"&&(m.maxItems=y);break}case"record":{let m=f;m.type="object",m.propertyNames=this.process(s.keyType,{...d,path:[...d.path,"propertyNames"]}),m.additionalProperties=this.process(s.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=f,h=Vp(s.entries);h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),m.enum=h;break}case"literal":{let m=f,h=[];for(let g of s.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];m.type=g===null?"null":typeof g,m.const=g}else h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),h.every(g=>typeof g=="boolean")&&(m.type="string"),h.every(g=>g===null)&&(m.type="null"),m.enum=h;break}case"file":{let m=f,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:b}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),b?b.length===1?(h.contentMediaType=b[0],Object.assign(m,h)):m.anyOf=b.map(S=>({...h,contentMediaType:S})):Object.assign(m,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(s.innerType,d);f.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,d),a.ref=s.innerType;break}case"success":{let m=f;m.type="boolean";break}case"default":{this.process(s.innerType,d),a.ref=s.innerType,f.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,d),a.ref=s.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,d),a.ref=s.innerType;let m;try{m=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=f,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=h.source;break}case"pipe":{let m=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(m,d),a.ref=m;break}case"readonly":{this.process(s.innerType,d),a.ref=s.innerType,f.readOnly=!0;break}case"promise":{this.process(s.innerType,d),a.ref=s.innerType;break}case"optional":{this.process(s.innerType,d),a.ref=s.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,d),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),this.io==="input"&&nr(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,n){let r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=u=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){let h=r.external.registry.get(u[0])?.id,g=r.external.uri??(b=>b);if(h)return{ref:g(h)};let y=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(u[1]===s)return{ref:"#"};let f=`#/${d}/`,m=u[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:f+m}},i=u=>{if(u[1].schema.$ref)return;let d=u[1],{ref:p,defId:f}=o(u);d.def={...d.schema},f&&(d.defId=f);let m=d.schema;for(let h in m)delete m[h];m.$ref=p};if(r.cycles==="throw")for(let u of this.seen.entries()){let d=u[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
920
920
 
921
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let d=u[1];if(e===u[0]){i(u);continue}if(r.external){let f=r.external.registry.get(u[0])?.id;if(e!==u[0]&&f){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(d.cycle){i(u);continue}if(d.count>1&&r.reused==="ref"){i(u);continue}}let a=(u,d)=>{let p=this.seen.get(u),f=p.def??p.schema,m={...f};if(p.ref===null)return;let h=p.ref;if(p.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,m))}p.isParent||this.override({zodSchema:u,jsonSchema:f,path:p.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){let u=r.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(u)}Object.assign(c,s.def);let l=r.external?.defs??{};for(let u of this.seen.entries()){let d=u[1];d.def&&d.defId&&(l[d.defId]=d.def)}r.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function tR(t,e){if(t instanceof sf){let r=new cy(e),s={};for(let a of t._idmap.entries()){let[c,l]=a;r.process(l)}let o={},i={registry:t,uri:e?.uri,defs:s};for(let a of t._idmap.entries()){let[c,l]=a;o[c]=r.emit(l,{...e,external:i})}if(Object.keys(s).length>0){let a=r.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[a]:s}}return{schemas:o}}let n=new cy(e);return n.process(t),n.emit(t,e)}function nr(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let s=t._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return nr(s.element,n);case"object":{for(let o in s.shape)if(nr(s.shape[o],n))return!0;return!1}case"union":{for(let o of s.options)if(nr(o,n))return!0;return!1}case"intersection":return nr(s.left,n)||nr(s.right,n);case"tuple":{for(let o of s.items)if(nr(o,n))return!0;return!!(s.rest&&nr(s.rest,n))}case"record":return nr(s.keyType,n)||nr(s.valueType,n);case"map":return nr(s.keyType,n)||nr(s.valueType,n);case"set":return nr(s.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return nr(s.innerType,n);case"lazy":return nr(s.getter(),n);case"default":return nr(s.innerType,n);case"prefault":return nr(s.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return nr(s.in,n)||nr(s.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${s.type}`)}var CZ=Y("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");en.init(t,e),t.def=e,t.parse=(n,r)=>Sw(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Tc(t,n,r),t.parseAsync=async(n,r)=>_w(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Pc(t,n,r),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Ds(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t))});var AZ=Y("ZodMiniObject",(t,e)=>{ey.init(t,e),CZ.init(t,e),Ct.defineLazy(t,"shape",()=>e.shape)});function nR(t,e){let n={type:"object",get shape(){return Ct.assignProp(this,"shape",{...t}),this.shape},...Ct.normalizeParams(e)};return new AZ(n)}function no(t){return!!t._zod}function Ic(t){let e=Object.values(t);if(e.length===0)return nR({});let n=e.every(no),r=e.every(s=>!no(s));if(n)return nR(t);if(r)return l0(t);throw new Error("Mixed Zod versions detected in object shape.")}function fa(t,e){return no(t)?Tc(t,e):t.safeParse(e)}async function ly(t,e){return no(t)?await Pc(t,e):await t.safeParseAsync(e)}function ma(t){if(!t)return;let e;if(no(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function iu(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let r=Object.values(t);if(r.length>0&&r.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return Ic(t)}}if(no(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function uy(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function ED(t){return t.description}function TD(t){if(no(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function dy(t){if(no(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 n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var cf={};Yt(cf,{ZodISODate:()=>CD,ZodISODateTime:()=>PD,ZodISODuration:()=>ID,ZodISOTime:()=>AD,date:()=>sR,datetime:()=>rR,duration:()=>iR,time:()=>oR});var PD=Y("ZodISODateTime",(t,e)=>{fD.init(t,e),Sn.init(t,e)});function rR(t){return xD(PD,t)}var CD=Y("ZodISODate",(t,e)=>{mD.init(t,e),Sn.init(t,e)});function sR(t){return _D(CD,t)}var AD=Y("ZodISOTime",(t,e)=>{hD.init(t,e),Sn.init(t,e)});function oR(t){return wD(AD,t)}var ID=Y("ZodISODuration",(t,e)=>{gD.init(t,e),Sn.init(t,e)});function iR(t){return vD(ID,t)}var ND=(t,e)=>{Jg.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>yw(t,n)},flatten:{value:n=>gw(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},yle=Y("ZodError",ND),lf=Y("ZodError",ND,{Parent:Error});var DD=bw(lf),OD=xw(lf),MD=ww(lf),FD=vw(lf);var Cn=Y("ZodType",(t,e)=>(en.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Ds(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>DD(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>MD(t,n,r),t.parseAsync=async(n,r)=>OD(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>FD(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(TG(n,r)),t.superRefine=n=>t.check(PG(n)),t.overwrite=n=>t.check(Cc(n)),t.optional=()=>_n(t),t.nullable=()=>LD(t),t.nullish=()=>_n(LD(t)),t.nonoptional=n=>xG(t,n),t.array=()=>At(t),t.or=n=>yn([t,n]),t.and=n=>fy(t,n),t.transform=n=>cR(t,UD(n)),t.default=n=>yG(t,n),t.prefault=n=>SG(t,n),t.catch=n=>wG(t,n),t.pipe=n=>cR(t,n),t.readonly=()=>kG(t),t.describe=n=>{let r=t.clone();return pa.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return pa.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return pa.get(t);let r=t.clone();return pa.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),zD=Y("_ZodString",(t,e)=>{rf.init(t,e),Cn.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(Hv(...r)),t.includes=(...r)=>t.check(Kv(...r)),t.startsWith=(...r)=>t.check(Zv(...r)),t.endsWith=(...r)=>t.check(Gv(...r)),t.min=(...r)=>t.check(ou(...r)),t.max=(...r)=>t.check(iy(...r)),t.length=(...r)=>t.check(ay(...r)),t.nonempty=(...r)=>t.check(ou(1,...r)),t.lowercase=r=>t.check(Wv(r)),t.uppercase=r=>t.check(Uv(r)),t.trim=()=>t.check(Vv()),t.normalize=(...r)=>t.check(Jv(...r)),t.toLowerCase=()=>t.check(Xv()),t.toUpperCase=()=>t.check(Qv())}),LZ=Y("ZodString",(t,e)=>{rf.init(t,e),zD.init(t,e),t.email=n=>t.check(gv(zZ,n)),t.url=n=>t.check(_v(BZ,n)),t.jwt=n=>t.check(Fv(nG,n)),t.emoji=n=>t.check(wv(qZ,n)),t.guid=n=>t.check(ny($D,n)),t.uuid=n=>t.check(yv(py,n)),t.uuidv4=n=>t.check(bv(py,n)),t.uuidv6=n=>t.check(Sv(py,n)),t.uuidv7=n=>t.check(xv(py,n)),t.nanoid=n=>t.check(vv(HZ,n)),t.guid=n=>t.check(ny($D,n)),t.cuid=n=>t.check(Rv(WZ,n)),t.cuid2=n=>t.check(kv(UZ,n)),t.ulid=n=>t.check(Ev(KZ,n)),t.base64=n=>t.check(Dv(YZ,n)),t.base64url=n=>t.check(Ov(eG,n)),t.xid=n=>t.check(Tv(ZZ,n)),t.ksuid=n=>t.check(Pv(GZ,n)),t.ipv4=n=>t.check(Cv(JZ,n)),t.ipv6=n=>t.check(Av(VZ,n)),t.cidrv4=n=>t.check(Iv(XZ,n)),t.cidrv6=n=>t.check(Nv(QZ,n)),t.e164=n=>t.check(Mv(tG,n)),t.datetime=n=>t.check(rR(n)),t.date=n=>t.check(sR(n)),t.time=n=>t.check(oR(n)),t.duration=n=>t.check(iR(n))});function Q(t){return hv(LZ,t)}var Sn=Y("ZodStringFormat",(t,e)=>{un.init(t,e),zD.init(t,e)}),zZ=Y("ZodEmail",(t,e)=>{Iw.init(t,e),Sn.init(t,e)});var $D=Y("ZodGUID",(t,e)=>{Cw.init(t,e),Sn.init(t,e)});var py=Y("ZodUUID",(t,e)=>{Aw.init(t,e),Sn.init(t,e)});var BZ=Y("ZodURL",(t,e)=>{Nw.init(t,e),Sn.init(t,e)});var qZ=Y("ZodEmoji",(t,e)=>{Dw.init(t,e),Sn.init(t,e)});var HZ=Y("ZodNanoID",(t,e)=>{Ow.init(t,e),Sn.init(t,e)});var WZ=Y("ZodCUID",(t,e)=>{Mw.init(t,e),Sn.init(t,e)});var UZ=Y("ZodCUID2",(t,e)=>{Fw.init(t,e),Sn.init(t,e)});var KZ=Y("ZodULID",(t,e)=>{$w.init(t,e),Sn.init(t,e)});var ZZ=Y("ZodXID",(t,e)=>{jw.init(t,e),Sn.init(t,e)});var GZ=Y("ZodKSUID",(t,e)=>{Lw.init(t,e),Sn.init(t,e)});var JZ=Y("ZodIPv4",(t,e)=>{zw.init(t,e),Sn.init(t,e)});var VZ=Y("ZodIPv6",(t,e)=>{Bw.init(t,e),Sn.init(t,e)});var XZ=Y("ZodCIDRv4",(t,e)=>{qw.init(t,e),Sn.init(t,e)});var QZ=Y("ZodCIDRv6",(t,e)=>{Hw.init(t,e),Sn.init(t,e)});var YZ=Y("ZodBase64",(t,e)=>{Ww.init(t,e),Sn.init(t,e)});var eG=Y("ZodBase64URL",(t,e)=>{Uw.init(t,e),Sn.init(t,e)});var tG=Y("ZodE164",(t,e)=>{Kw.init(t,e),Sn.init(t,e)});var nG=Y("ZodJWT",(t,e)=>{Zw.init(t,e),Sn.init(t,e)});var BD=Y("ZodNumber",(t,e)=>{Yg.init(t,e),Cn.init(t,e),t.gt=(r,s)=>t.check(sy(r,s)),t.gte=(r,s)=>t.check(af(r,s)),t.min=(r,s)=>t.check(af(r,s)),t.lt=(r,s)=>t.check(ry(r,s)),t.lte=(r,s)=>t.check(of(r,s)),t.max=(r,s)=>t.check(of(r,s)),t.int=r=>t.check(jD(r)),t.safe=r=>t.check(jD(r)),t.positive=r=>t.check(sy(0,r)),t.nonnegative=r=>t.check(af(0,r)),t.negative=r=>t.check(ry(0,r)),t.nonpositive=r=>t.check(of(0,r)),t.multipleOf=(r,s)=>t.check(oy(r,s)),t.step=(r,s)=>t.check(oy(r,s)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function Xt(t){return $v(BD,t)}var rG=Y("ZodNumberFormat",(t,e)=>{Gw.init(t,e),BD.init(t,e)});function jD(t){return jv(rG,t)}var sG=Y("ZodBoolean",(t,e)=>{Jw.init(t,e),Cn.init(t,e)});function pr(t){return Lv(sG,t)}var oG=Y("ZodNull",(t,e)=>{Vw.init(t,e),Cn.init(t,e)});function qD(t){return zv(oG,t)}var iG=Y("ZodUnknown",(t,e)=>{Xw.init(t,e),Cn.init(t,e)});function xn(){return Bv(iG)}var aG=Y("ZodNever",(t,e)=>{Qw.init(t,e),Cn.init(t,e)});function cG(t){return qv(aG,t)}var lG=Y("ZodArray",(t,e)=>{Yw.init(t,e),Cn.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(ou(n,r)),t.nonempty=n=>t.check(ou(1,n)),t.max=(n,r)=>t.check(iy(n,r)),t.length=(n,r)=>t.check(ay(n,r)),t.unwrap=()=>t.element});function At(t,e){return RD(lG,t,e)}var HD=Y("ZodObject",(t,e)=>{ey.init(t,e),Cn.init(t,e),Ct.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>is(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:xn()}),t.loose=()=>t.clone({...t._zod.def,catchall:xn()}),t.strict=()=>t.clone({...t._zod.def,catchall:cG()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Ct.extend(t,n),t.merge=n=>Ct.merge(t,n),t.pick=n=>Ct.pick(t,n),t.omit=n=>Ct.omit(t,n),t.partial=(...n)=>Ct.partial(KD,t,n[0]),t.required=(...n)=>Ct.required(ZD,t,n[0])});function Te(t,e){let n={type:"object",get shape(){return Ct.assignProp(this,"shape",{...t}),this.shape},...Ct.normalizeParams(e)};return new HD(n)}function Hr(t,e){return new HD({type:"object",get shape(){return Ct.assignProp(this,"shape",{...t}),this.shape},catchall:xn(),...Ct.normalizeParams(e)})}var WD=Y("ZodUnion",(t,e)=>{ty.init(t,e),Cn.init(t,e),t.options=e.options});function yn(t,e){return new WD({type:"union",options:t,...Ct.normalizeParams(e)})}var uG=Y("ZodDiscriminatedUnion",(t,e)=>{WD.init(t,e),ev.init(t,e)});function lR(t,e,n){return new uG({type:"union",options:e,discriminator:t,...Ct.normalizeParams(n)})}var dG=Y("ZodIntersection",(t,e)=>{tv.init(t,e),Cn.init(t,e)});function fy(t,e){return new dG({type:"intersection",left:t,right:e})}var pG=Y("ZodRecord",(t,e)=>{nv.init(t,e),Cn.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function dn(t,e,n){return new pG({type:"record",keyType:t,valueType:e,...Ct.normalizeParams(n)})}var aR=Y("ZodEnum",(t,e)=>{rv.init(t,e),Cn.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,s)=>{let o={};for(let i of r)if(n.has(i))o[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new aR({...e,checks:[],...Ct.normalizeParams(s),entries:o})},t.exclude=(r,s)=>{let o={...e.entries};for(let i of r)if(n.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new aR({...e,checks:[],...Ct.normalizeParams(s),entries:o})}});function is(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new aR({type:"enum",entries:n,...Ct.normalizeParams(e)})}var fG=Y("ZodLiteral",(t,e)=>{sv.init(t,e),Cn.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 ze(t,e){return new fG({type:"literal",values:Array.isArray(t)?t:[t],...Ct.normalizeParams(e)})}var mG=Y("ZodTransform",(t,e)=>{ov.init(t,e),Cn.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=o=>{if(typeof o=="string")n.issues.push(Ct.issue(o,n.value,e));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),n.issues.push(Ct.issue(i))}};let s=e.transform(n.value,n);return s instanceof Promise?s.then(o=>(n.value=o,n)):(n.value=s,n)}});function UD(t){return new mG({type:"transform",transform:t})}var KD=Y("ZodOptional",(t,e)=>{iv.init(t,e),Cn.init(t,e),t.unwrap=()=>t._zod.def.innerType});function _n(t){return new KD({type:"optional",innerType:t})}var hG=Y("ZodNullable",(t,e)=>{av.init(t,e),Cn.init(t,e),t.unwrap=()=>t._zod.def.innerType});function LD(t){return new hG({type:"nullable",innerType:t})}var gG=Y("ZodDefault",(t,e)=>{cv.init(t,e),Cn.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function yG(t,e){return new gG({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var bG=Y("ZodPrefault",(t,e)=>{lv.init(t,e),Cn.init(t,e),t.unwrap=()=>t._zod.def.innerType});function SG(t,e){return new bG({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var ZD=Y("ZodNonOptional",(t,e)=>{uv.init(t,e),Cn.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xG(t,e){return new ZD({type:"nonoptional",innerType:t,...Ct.normalizeParams(e)})}var _G=Y("ZodCatch",(t,e)=>{dv.init(t,e),Cn.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function wG(t,e){return new _G({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var vG=Y("ZodPipe",(t,e)=>{pv.init(t,e),Cn.init(t,e),t.in=e.in,t.out=e.out});function cR(t,e){return new vG({type:"pipe",in:t,out:e})}var RG=Y("ZodReadonly",(t,e)=>{fv.init(t,e),Cn.init(t,e)});function kG(t){return new RG({type:"readonly",innerType:t})}var GD=Y("ZodCustom",(t,e)=>{mv.init(t,e),Cn.init(t,e)});function EG(t){let e=new br({check:"custom"});return e._zod.check=t,e}function JD(t,e){return Yv(GD,t??(()=>!0),e)}function TG(t,e={}){return eR(GD,t,e)}function PG(t){let e=EG(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Ct.issue(r,n.value,e._zod.def));else{let s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),n.issues.push(Ct.issue(s))}},t(n.value,n)));return e}function uR(t,e){return cR(UD(t),e)}Ns(bD());var pR="2025-11-25",VD="2025-03-26",cu=[pR,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ha="io.modelcontextprotocol/related-task",hy="2.0",rr=JD(t=>t!==null&&(typeof t=="object"||typeof t=="function")),XD=yn([Q(),Xt().int()]),QD=Q(),Ile=Hr({ttl:Xt().optional(),pollInterval:Xt().optional()}),CG=Te({ttl:Xt().optional()}),AG=Te({taskId:Q()}),fR=Hr({progressToken:XD.optional(),[ha]:AG.optional()}),Os=Te({_meta:fR.optional()}),uf=Os.extend({task:CG.optional()}),YD=t=>uf.safeParse(t).success,Sr=Te({method:Q(),params:Os.loose().optional()}),ro=Te({_meta:fR.optional()}),so=Te({method:Q(),params:ro.loose().optional()}),xr=Hr({_meta:fR.optional()}),gy=yn([Q(),Xt().int()]),eO=Te({jsonrpc:ze(hy),id:gy,...Sr.shape}).strict(),ga=t=>eO.safeParse(t).success,tO=Te({jsonrpc:ze(hy),...so.shape}).strict(),nO=t=>tO.safeParse(t).success,mR=Te({jsonrpc:ze(hy),id:gy,result:xr}).strict(),Oi=t=>mR.safeParse(t).success;var Ze;(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"})(Ze||(Ze={}));var hR=Te({jsonrpc:ze(hy),id:gy.optional(),error:Te({code:Xt().int(),message:Q(),data:xn().optional()})}).strict();var lu=t=>hR.safeParse(t).success;var df=yn([eO,tO,mR,hR]),Nle=yn([mR,hR]),yy=xr.strict(),IG=ro.extend({requestId:gy.optional(),reason:Q().optional()}),by=so.extend({method:ze("notifications/cancelled"),params:IG}),NG=Te({src:Q(),mimeType:Q().optional(),sizes:At(Q()).optional(),theme:is(["light","dark"]).optional()}),pf=Te({icons:At(NG).optional()}),au=Te({name:Q(),title:Q().optional()}),rO=au.extend({...au.shape,...pf.shape,version:Q(),websiteUrl:Q().optional(),description:Q().optional()}),DG=fy(Te({applyDefaults:pr().optional()}),dn(Q(),xn())),OG=uR(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,fy(Te({form:DG.optional(),url:rr.optional()}),dn(Q(),xn()).optional())),MG=Hr({list:rr.optional(),cancel:rr.optional(),requests:Hr({sampling:Hr({createMessage:rr.optional()}).optional(),elicitation:Hr({create:rr.optional()}).optional()}).optional()}),FG=Hr({list:rr.optional(),cancel:rr.optional(),requests:Hr({tools:Hr({call:rr.optional()}).optional()}).optional()}),$G=Te({experimental:dn(Q(),rr).optional(),sampling:Te({context:rr.optional(),tools:rr.optional()}).optional(),elicitation:OG.optional(),roots:Te({listChanged:pr().optional()}).optional(),tasks:MG.optional(),extensions:dn(Q(),rr).optional()}),jG=Os.extend({protocolVersion:Q(),capabilities:$G,clientInfo:rO}),Sy=Sr.extend({method:ze("initialize"),params:jG}),gR=t=>Sy.safeParse(t).success,LG=Te({experimental:dn(Q(),rr).optional(),logging:rr.optional(),completions:rr.optional(),prompts:Te({listChanged:pr().optional()}).optional(),resources:Te({subscribe:pr().optional(),listChanged:pr().optional()}).optional(),tools:Te({listChanged:pr().optional()}).optional(),tasks:FG.optional(),extensions:dn(Q(),rr).optional()}),zG=xr.extend({protocolVersion:Q(),capabilities:LG,serverInfo:rO,instructions:Q().optional()}),yR=so.extend({method:ze("notifications/initialized"),params:ro.optional()});var xy=Sr.extend({method:ze("ping"),params:Os.optional()}),BG=Te({progress:Xt(),total:_n(Xt()),message:_n(Q())}),qG=Te({...ro.shape,...BG.shape,progressToken:XD}),_y=so.extend({method:ze("notifications/progress"),params:qG}),HG=Os.extend({cursor:QD.optional()}),ff=Sr.extend({params:HG.optional()}),mf=xr.extend({nextCursor:QD.optional()}),WG=is(["working","input_required","completed","failed","cancelled"]),hf=Te({taskId:Q(),status:WG,ttl:yn([Xt(),qD()]),createdAt:Q(),lastUpdatedAt:Q(),pollInterval:_n(Xt()),statusMessage:_n(Q())}),uu=xr.extend({task:hf}),UG=ro.merge(hf),gf=so.extend({method:ze("notifications/tasks/status"),params:UG}),wy=Sr.extend({method:ze("tasks/get"),params:Os.extend({taskId:Q()})}),vy=xr.merge(hf),Ry=Sr.extend({method:ze("tasks/result"),params:Os.extend({taskId:Q()})}),Dle=xr.loose(),ky=ff.extend({method:ze("tasks/list")}),Ey=mf.extend({tasks:At(hf)}),Ty=Sr.extend({method:ze("tasks/cancel"),params:Os.extend({taskId:Q()})}),sO=xr.merge(hf),oO=Te({uri:Q(),mimeType:_n(Q()),_meta:dn(Q(),xn()).optional()}),iO=oO.extend({text:Q()}),bR=Q().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),aO=oO.extend({blob:bR}),yf=is(["user","assistant"]),du=Te({audience:At(yf).optional(),priority:Xt().min(0).max(1).optional(),lastModified:cf.datetime({offset:!0}).optional()}),cO=Te({...au.shape,...pf.shape,uri:Q(),description:_n(Q()),mimeType:_n(Q()),size:_n(Xt()),annotations:du.optional(),_meta:_n(Hr({}))}),KG=Te({...au.shape,...pf.shape,uriTemplate:Q(),description:_n(Q()),mimeType:_n(Q()),annotations:du.optional(),_meta:_n(Hr({}))}),Py=ff.extend({method:ze("resources/list")}),ZG=mf.extend({resources:At(cO)}),Cy=ff.extend({method:ze("resources/templates/list")}),GG=mf.extend({resourceTemplates:At(KG)}),SR=Os.extend({uri:Q()}),JG=SR,Ay=Sr.extend({method:ze("resources/read"),params:JG}),VG=xr.extend({contents:At(yn([iO,aO]))}),XG=so.extend({method:ze("notifications/resources/list_changed"),params:ro.optional()}),QG=SR,YG=Sr.extend({method:ze("resources/subscribe"),params:QG}),e2=SR,t2=Sr.extend({method:ze("resources/unsubscribe"),params:e2}),n2=ro.extend({uri:Q()}),r2=so.extend({method:ze("notifications/resources/updated"),params:n2}),s2=Te({name:Q(),description:_n(Q()),required:_n(pr())}),o2=Te({...au.shape,...pf.shape,description:_n(Q()),arguments:_n(At(s2)),_meta:_n(Hr({}))}),pu=ff.extend({method:ze("prompts/list")}),i2=mf.extend({prompts:At(o2)}),a2=Os.extend({name:Q(),arguments:dn(Q(),Q()).optional()}),fu=Sr.extend({method:ze("prompts/get"),params:a2}),xR=Te({type:ze("text"),text:Q(),annotations:du.optional(),_meta:dn(Q(),xn()).optional()}),_R=Te({type:ze("image"),data:bR,mimeType:Q(),annotations:du.optional(),_meta:dn(Q(),xn()).optional()}),wR=Te({type:ze("audio"),data:bR,mimeType:Q(),annotations:du.optional(),_meta:dn(Q(),xn()).optional()}),c2=Te({type:ze("tool_use"),name:Q(),id:Q(),input:dn(Q(),xn()),_meta:dn(Q(),xn()).optional()}),l2=Te({type:ze("resource"),resource:yn([iO,aO]),annotations:du.optional(),_meta:dn(Q(),xn()).optional()}),u2=cO.extend({type:ze("resource_link")}),vR=yn([xR,_R,wR,u2,l2]),d2=Te({role:yf,content:vR}),p2=xr.extend({description:Q().optional(),messages:At(d2)}),f2=so.extend({method:ze("notifications/prompts/list_changed"),params:ro.optional()}),m2=Te({title:Q().optional(),readOnlyHint:pr().optional(),destructiveHint:pr().optional(),idempotentHint:pr().optional(),openWorldHint:pr().optional()}),h2=Te({taskSupport:is(["required","optional","forbidden"]).optional()}),lO=Te({...au.shape,...pf.shape,description:Q().optional(),inputSchema:Te({type:ze("object"),properties:dn(Q(),rr).optional(),required:At(Q()).optional()}).catchall(xn()),outputSchema:Te({type:ze("object"),properties:dn(Q(),rr).optional(),required:At(Q()).optional()}).catchall(xn()).optional(),annotations:m2.optional(),execution:h2.optional(),_meta:dn(Q(),xn()).optional()}),mu=ff.extend({method:ze("tools/list")}),g2=mf.extend({tools:At(lO)}),Iy=xr.extend({content:At(vR).default([]),structuredContent:dn(Q(),xn()).optional(),isError:pr().optional()}),Ole=Iy.or(xr.extend({toolResult:xn()})),y2=uf.extend({name:Q(),arguments:dn(Q(),xn()).optional()}),ya=Sr.extend({method:ze("tools/call"),params:y2}),b2=so.extend({method:ze("notifications/tools/list_changed"),params:ro.optional()}),Mle=Te({autoRefresh:pr().default(!0),debounceMs:Xt().int().nonnegative().default(300)}),bf=is(["debug","info","notice","warning","error","critical","alert","emergency"]),S2=Os.extend({level:bf}),RR=Sr.extend({method:ze("logging/setLevel"),params:S2}),x2=ro.extend({level:bf,logger:Q().optional(),data:xn()}),_2=so.extend({method:ze("notifications/message"),params:x2}),w2=Te({name:Q().optional()}),v2=Te({hints:At(w2).optional(),costPriority:Xt().min(0).max(1).optional(),speedPriority:Xt().min(0).max(1).optional(),intelligencePriority:Xt().min(0).max(1).optional()}),R2=Te({mode:is(["auto","required","none"]).optional()}),k2=Te({type:ze("tool_result"),toolUseId:Q().describe("The unique identifier for the corresponding tool call."),content:At(vR).default([]),structuredContent:Te({}).loose().optional(),isError:pr().optional(),_meta:dn(Q(),xn()).optional()}),E2=lR("type",[xR,_R,wR]),my=lR("type",[xR,_R,wR,c2,k2]),T2=Te({role:yf,content:yn([my,At(my)]),_meta:dn(Q(),xn()).optional()}),P2=uf.extend({messages:At(T2),modelPreferences:v2.optional(),systemPrompt:Q().optional(),includeContext:is(["none","thisServer","allServers"]).optional(),temperature:Xt().optional(),maxTokens:Xt().int(),stopSequences:At(Q()).optional(),metadata:rr.optional(),tools:At(lO).optional(),toolChoice:R2.optional()}),C2=Sr.extend({method:ze("sampling/createMessage"),params:P2}),Sf=xr.extend({model:Q(),stopReason:_n(is(["endTurn","stopSequence","maxTokens"]).or(Q())),role:yf,content:E2}),kR=xr.extend({model:Q(),stopReason:_n(is(["endTurn","stopSequence","maxTokens","toolUse"]).or(Q())),role:yf,content:yn([my,At(my)])}),A2=Te({type:ze("boolean"),title:Q().optional(),description:Q().optional(),default:pr().optional()}),I2=Te({type:ze("string"),title:Q().optional(),description:Q().optional(),minLength:Xt().optional(),maxLength:Xt().optional(),format:is(["email","uri","date","date-time"]).optional(),default:Q().optional()}),N2=Te({type:is(["number","integer"]),title:Q().optional(),description:Q().optional(),minimum:Xt().optional(),maximum:Xt().optional(),default:Xt().optional()}),D2=Te({type:ze("string"),title:Q().optional(),description:Q().optional(),enum:At(Q()),default:Q().optional()}),O2=Te({type:ze("string"),title:Q().optional(),description:Q().optional(),oneOf:At(Te({const:Q(),title:Q()})),default:Q().optional()}),M2=Te({type:ze("string"),title:Q().optional(),description:Q().optional(),enum:At(Q()),enumNames:At(Q()).optional(),default:Q().optional()}),F2=yn([D2,O2]),$2=Te({type:ze("array"),title:Q().optional(),description:Q().optional(),minItems:Xt().optional(),maxItems:Xt().optional(),items:Te({type:ze("string"),enum:At(Q())}),default:At(Q()).optional()}),j2=Te({type:ze("array"),title:Q().optional(),description:Q().optional(),minItems:Xt().optional(),maxItems:Xt().optional(),items:Te({anyOf:At(Te({const:Q(),title:Q()}))}),default:At(Q()).optional()}),L2=yn([$2,j2]),z2=yn([M2,F2,L2]),B2=yn([z2,A2,I2,N2]),q2=uf.extend({mode:ze("form").optional(),message:Q(),requestedSchema:Te({type:ze("object"),properties:dn(Q(),B2),required:At(Q()).optional()})}),H2=uf.extend({mode:ze("url"),message:Q(),elicitationId:Q(),url:Q().url()}),W2=yn([q2,H2]),U2=Sr.extend({method:ze("elicitation/create"),params:W2}),K2=ro.extend({elicitationId:Q()}),Z2=so.extend({method:ze("notifications/elicitation/complete"),params:K2}),hu=xr.extend({action:is(["accept","decline","cancel"]),content:uR(t=>t===null?void 0:t,dn(Q(),yn([Q(),Xt(),pr(),At(Q())])).optional())}),G2=Te({type:ze("ref/resource"),uri:Q()});var J2=Te({type:ze("ref/prompt"),name:Q()}),V2=Os.extend({ref:yn([J2,G2]),argument:Te({name:Q(),value:Q()}),context:Te({arguments:dn(Q(),Q()).optional()}).optional()}),Ny=Sr.extend({method:ze("completion/complete"),params:V2});function uO(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function dO(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var X2=xr.extend({completion:Hr({values:At(Q()).max(100),total:_n(Xt().int()),hasMore:_n(pr())})}),Q2=Te({uri:Q().startsWith("file://"),name:Q().optional(),_meta:dn(Q(),xn()).optional()}),Y2=Sr.extend({method:ze("roots/list"),params:Os.optional()}),ER=xr.extend({roots:At(Q2)}),eJ=so.extend({method:ze("notifications/roots/list_changed"),params:ro.optional()}),Fle=yn([xy,Sy,Ny,RR,fu,pu,Py,Cy,Ay,YG,t2,ya,mu,wy,Ry,ky,Ty]),$le=yn([by,_y,yR,eJ,gf]),jle=yn([yy,Sf,kR,hu,ER,vy,Ey,uu]),Lle=yn([xy,C2,U2,Y2,wy,Ry,ky,Ty]),zle=yn([by,_y,_2,r2,XG,b2,f2,gf,Z2]),Ble=yn([yy,zG,X2,p2,i2,ZG,GG,VG,Iy,g2,vy,Ey,uu]),je=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===Ze.UrlElicitationRequired&&r){let s=r;if(s.elicitations)return new dR(s.elicitations,n)}return new t(e,n,r)}},dR=class extends je{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(Ze.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ba(t){return t==="completed"||t==="failed"||t==="cancelled"}var fO=Symbol("Let zodToJsonSchema decide on which parser to use");var pO={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"},mO=t=>typeof t=="string"?{...pO,name:t}:{...pO,...t};var hO=t=>{let e=mO(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function TR(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function It(t,e,n,r,s){t[e]=n,TR(t,e,r,s)}var Dy=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")};function wn(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Dy(e,t.currentPath):e.join("/")}}function gO(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==le.ZodAny&&(n.items=nt(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&It(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&It(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(It(n,"minItems",t.exactLength.value,t.exactLength.message,e),It(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function yO(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?It(n,"minimum",r.value,r.message,e):It(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),It(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?It(n,"maximum",r.value,r.message,e):It(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),It(n,"maximum",r.value,r.message,e));break;case"multipleOf":It(n,"multipleOf",r.value,r.message,e);break}return n}function bO(){return{type:"boolean"}}function Oy(t,e){return nt(t.type._def,e)}var SO=(t,e)=>nt(t.innerType._def,e);function PR(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,o)=>PR(t,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return tJ(t,e)}}var tJ=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":It(n,"minimum",r.value,r.message,e);break;case"max":It(n,"maximum",r.value,r.message,e);break}return n};function xO(t,e){return{...nt(t.innerType._def,e),default:t.defaultValue()}}function _O(t,e){return e.effectStrategy==="input"?nt(t.schema._def,e):wn(e)}function wO(t){return{type:"string",enum:Array.from(t.values)}}var nJ=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function vO(t,e){let n=[nt(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),nt(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return n.forEach(o=>{if(nJ(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(r=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function RO(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var CR,Io={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:()=>(CR===void 0&&(CR=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),CR),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 My(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":It(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":It(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":No(n,"email",r.message,e);break;case"format:idn-email":No(n,"idn-email",r.message,e);break;case"pattern:zod":Wr(n,Io.email,r.message,e);break}break;case"url":No(n,"uri",r.message,e);break;case"uuid":No(n,"uuid",r.message,e);break;case"regex":Wr(n,r.regex,r.message,e);break;case"cuid":Wr(n,Io.cuid,r.message,e);break;case"cuid2":Wr(n,Io.cuid2,r.message,e);break;case"startsWith":Wr(n,RegExp(`^${AR(r.value,e)}`),r.message,e);break;case"endsWith":Wr(n,RegExp(`${AR(r.value,e)}$`),r.message,e);break;case"datetime":No(n,"date-time",r.message,e);break;case"date":No(n,"date",r.message,e);break;case"time":No(n,"time",r.message,e);break;case"duration":No(n,"duration",r.message,e);break;case"length":It(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),It(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Wr(n,RegExp(AR(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&No(n,"ipv4",r.message,e),r.version!=="v4"&&No(n,"ipv6",r.message,e);break}case"base64url":Wr(n,Io.base64url,r.message,e);break;case"jwt":Wr(n,Io.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&Wr(n,Io.ipv4Cidr,r.message,e),r.version!=="v4"&&Wr(n,Io.ipv6Cidr,r.message,e);break}case"emoji":Wr(n,Io.emoji(),r.message,e);break;case"ulid":{Wr(n,Io.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{No(n,"binary",r.message,e);break}case"contentEncoding:base64":{It(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Wr(n,Io.base64,r.message,e);break}}break}case"nanoid":Wr(n,Io.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function AR(t,e){return e.patternStrategy==="escape"?sJ(t):t}var rJ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function sJ(t){let e="";for(let n=0;n<t.length;n++)rJ.has(t[n])||(e+="\\"),e+=t[n];return e}function No(t,e,n,r){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.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,...n&&r.errorMessages&&{errorMessage:{format:n}}})):It(t,"format",e,n,r)}function Wr(t,e,n,r){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.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:kO(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):It(t,"pattern",kO(e,r),n,r)}function kO(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,s="",o=!1,i=!1,a=!1;for(let c=0;c<r.length;c++){if(o){s+=r[c],o=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){a?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),a=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],a=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){s+=`(^|(?<=[\r
921
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let d=u[1];if(e===u[0]){i(u);continue}if(r.external){let f=r.external.registry.get(u[0])?.id;if(e!==u[0]&&f){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(d.cycle){i(u);continue}if(d.count>1&&r.reused==="ref"){i(u);continue}}let a=(u,d)=>{let p=this.seen.get(u),f=p.def??p.schema,m={...f};if(p.ref===null)return;let h=p.ref;if(p.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,m))}p.isParent||this.override({zodSchema:u,jsonSchema:f,path:p.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){let u=r.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(u)}Object.assign(c,s.def);let l=r.external?.defs??{};for(let u of this.seen.entries()){let d=u[1];d.def&&d.defId&&(l[d.defId]=d.def)}r.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function tR(t,e){if(t instanceof sf){let r=new cy(e),s={};for(let a of t._idmap.entries()){let[c,l]=a;r.process(l)}let o={},i={registry:t,uri:e?.uri,defs:s};for(let a of t._idmap.entries()){let[c,l]=a;o[c]=r.emit(l,{...e,external:i})}if(Object.keys(s).length>0){let a=r.target==="draft-2020-12"?"$defs":"definitions";o.__shared={[a]:s}}return{schemas:o}}let n=new cy(e);return n.process(t),n.emit(t,e)}function nr(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let s=t._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return nr(s.element,n);case"object":{for(let o in s.shape)if(nr(s.shape[o],n))return!0;return!1}case"union":{for(let o of s.options)if(nr(o,n))return!0;return!1}case"intersection":return nr(s.left,n)||nr(s.right,n);case"tuple":{for(let o of s.items)if(nr(o,n))return!0;return!!(s.rest&&nr(s.rest,n))}case"record":return nr(s.keyType,n)||nr(s.valueType,n);case"map":return nr(s.keyType,n)||nr(s.valueType,n);case"set":return nr(s.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return nr(s.innerType,n);case"lazy":return nr(s.getter(),n);case"default":return nr(s.innerType,n);case"prefault":return nr(s.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return nr(s.in,n)||nr(s.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${s.type}`)}var CZ=Y("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");en.init(t,e),t.def=e,t.parse=(n,r)=>Sw(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Tc(t,n,r),t.parseAsync=async(n,r)=>_w(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Pc(t,n,r),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Ds(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t))});var AZ=Y("ZodMiniObject",(t,e)=>{ey.init(t,e),CZ.init(t,e),Ct.defineLazy(t,"shape",()=>e.shape)});function nR(t,e){let n={type:"object",get shape(){return Ct.assignProp(this,"shape",{...t}),this.shape},...Ct.normalizeParams(e)};return new AZ(n)}function no(t){return!!t._zod}function Ic(t){let e=Object.values(t);if(e.length===0)return nR({});let n=e.every(no),r=e.every(s=>!no(s));if(n)return nR(t);if(r)return l0(t);throw new Error("Mixed Zod versions detected in object shape.")}function fa(t,e){return no(t)?Tc(t,e):t.safeParse(e)}async function ly(t,e){return no(t)?await Pc(t,e):await t.safeParseAsync(e)}function ma(t){if(!t)return;let e;if(no(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function iu(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let r=Object.values(t);if(r.length>0&&r.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return Ic(t)}}if(no(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function uy(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function ED(t){return t.description}function TD(t){if(no(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function dy(t){if(no(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 n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var cf={};Yt(cf,{ZodISODate:()=>CD,ZodISODateTime:()=>PD,ZodISODuration:()=>ID,ZodISOTime:()=>AD,date:()=>sR,datetime:()=>rR,duration:()=>iR,time:()=>oR});var PD=Y("ZodISODateTime",(t,e)=>{fD.init(t,e),Sn.init(t,e)});function rR(t){return xD(PD,t)}var CD=Y("ZodISODate",(t,e)=>{mD.init(t,e),Sn.init(t,e)});function sR(t){return _D(CD,t)}var AD=Y("ZodISOTime",(t,e)=>{hD.init(t,e),Sn.init(t,e)});function oR(t){return wD(AD,t)}var ID=Y("ZodISODuration",(t,e)=>{gD.init(t,e),Sn.init(t,e)});function iR(t){return vD(ID,t)}var ND=(t,e)=>{Jg.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>yw(t,n)},flatten:{value:n=>gw(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},ble=Y("ZodError",ND),lf=Y("ZodError",ND,{Parent:Error});var DD=bw(lf),OD=xw(lf),MD=ww(lf),FD=vw(lf);var Cn=Y("ZodType",(t,e)=>(en.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>Ds(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>DD(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>MD(t,n,r),t.parseAsync=async(n,r)=>OD(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>FD(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(TG(n,r)),t.superRefine=n=>t.check(PG(n)),t.overwrite=n=>t.check(Cc(n)),t.optional=()=>_n(t),t.nullable=()=>LD(t),t.nullish=()=>_n(LD(t)),t.nonoptional=n=>xG(t,n),t.array=()=>At(t),t.or=n=>yn([t,n]),t.and=n=>fy(t,n),t.transform=n=>cR(t,UD(n)),t.default=n=>yG(t,n),t.prefault=n=>SG(t,n),t.catch=n=>wG(t,n),t.pipe=n=>cR(t,n),t.readonly=()=>kG(t),t.describe=n=>{let r=t.clone();return pa.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return pa.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return pa.get(t);let r=t.clone();return pa.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),zD=Y("_ZodString",(t,e)=>{rf.init(t,e),Cn.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(Hv(...r)),t.includes=(...r)=>t.check(Kv(...r)),t.startsWith=(...r)=>t.check(Zv(...r)),t.endsWith=(...r)=>t.check(Gv(...r)),t.min=(...r)=>t.check(ou(...r)),t.max=(...r)=>t.check(iy(...r)),t.length=(...r)=>t.check(ay(...r)),t.nonempty=(...r)=>t.check(ou(1,...r)),t.lowercase=r=>t.check(Wv(r)),t.uppercase=r=>t.check(Uv(r)),t.trim=()=>t.check(Vv()),t.normalize=(...r)=>t.check(Jv(...r)),t.toLowerCase=()=>t.check(Xv()),t.toUpperCase=()=>t.check(Qv())}),LZ=Y("ZodString",(t,e)=>{rf.init(t,e),zD.init(t,e),t.email=n=>t.check(gv(zZ,n)),t.url=n=>t.check(_v(BZ,n)),t.jwt=n=>t.check(Fv(nG,n)),t.emoji=n=>t.check(wv(qZ,n)),t.guid=n=>t.check(ny($D,n)),t.uuid=n=>t.check(yv(py,n)),t.uuidv4=n=>t.check(bv(py,n)),t.uuidv6=n=>t.check(Sv(py,n)),t.uuidv7=n=>t.check(xv(py,n)),t.nanoid=n=>t.check(vv(HZ,n)),t.guid=n=>t.check(ny($D,n)),t.cuid=n=>t.check(Rv(WZ,n)),t.cuid2=n=>t.check(kv(UZ,n)),t.ulid=n=>t.check(Ev(KZ,n)),t.base64=n=>t.check(Dv(YZ,n)),t.base64url=n=>t.check(Ov(eG,n)),t.xid=n=>t.check(Tv(ZZ,n)),t.ksuid=n=>t.check(Pv(GZ,n)),t.ipv4=n=>t.check(Cv(JZ,n)),t.ipv6=n=>t.check(Av(VZ,n)),t.cidrv4=n=>t.check(Iv(XZ,n)),t.cidrv6=n=>t.check(Nv(QZ,n)),t.e164=n=>t.check(Mv(tG,n)),t.datetime=n=>t.check(rR(n)),t.date=n=>t.check(sR(n)),t.time=n=>t.check(oR(n)),t.duration=n=>t.check(iR(n))});function Q(t){return hv(LZ,t)}var Sn=Y("ZodStringFormat",(t,e)=>{un.init(t,e),zD.init(t,e)}),zZ=Y("ZodEmail",(t,e)=>{Iw.init(t,e),Sn.init(t,e)});var $D=Y("ZodGUID",(t,e)=>{Cw.init(t,e),Sn.init(t,e)});var py=Y("ZodUUID",(t,e)=>{Aw.init(t,e),Sn.init(t,e)});var BZ=Y("ZodURL",(t,e)=>{Nw.init(t,e),Sn.init(t,e)});var qZ=Y("ZodEmoji",(t,e)=>{Dw.init(t,e),Sn.init(t,e)});var HZ=Y("ZodNanoID",(t,e)=>{Ow.init(t,e),Sn.init(t,e)});var WZ=Y("ZodCUID",(t,e)=>{Mw.init(t,e),Sn.init(t,e)});var UZ=Y("ZodCUID2",(t,e)=>{Fw.init(t,e),Sn.init(t,e)});var KZ=Y("ZodULID",(t,e)=>{$w.init(t,e),Sn.init(t,e)});var ZZ=Y("ZodXID",(t,e)=>{jw.init(t,e),Sn.init(t,e)});var GZ=Y("ZodKSUID",(t,e)=>{Lw.init(t,e),Sn.init(t,e)});var JZ=Y("ZodIPv4",(t,e)=>{zw.init(t,e),Sn.init(t,e)});var VZ=Y("ZodIPv6",(t,e)=>{Bw.init(t,e),Sn.init(t,e)});var XZ=Y("ZodCIDRv4",(t,e)=>{qw.init(t,e),Sn.init(t,e)});var QZ=Y("ZodCIDRv6",(t,e)=>{Hw.init(t,e),Sn.init(t,e)});var YZ=Y("ZodBase64",(t,e)=>{Ww.init(t,e),Sn.init(t,e)});var eG=Y("ZodBase64URL",(t,e)=>{Uw.init(t,e),Sn.init(t,e)});var tG=Y("ZodE164",(t,e)=>{Kw.init(t,e),Sn.init(t,e)});var nG=Y("ZodJWT",(t,e)=>{Zw.init(t,e),Sn.init(t,e)});var BD=Y("ZodNumber",(t,e)=>{Yg.init(t,e),Cn.init(t,e),t.gt=(r,s)=>t.check(sy(r,s)),t.gte=(r,s)=>t.check(af(r,s)),t.min=(r,s)=>t.check(af(r,s)),t.lt=(r,s)=>t.check(ry(r,s)),t.lte=(r,s)=>t.check(of(r,s)),t.max=(r,s)=>t.check(of(r,s)),t.int=r=>t.check(jD(r)),t.safe=r=>t.check(jD(r)),t.positive=r=>t.check(sy(0,r)),t.nonnegative=r=>t.check(af(0,r)),t.negative=r=>t.check(ry(0,r)),t.nonpositive=r=>t.check(of(0,r)),t.multipleOf=(r,s)=>t.check(oy(r,s)),t.step=(r,s)=>t.check(oy(r,s)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function Xt(t){return $v(BD,t)}var rG=Y("ZodNumberFormat",(t,e)=>{Gw.init(t,e),BD.init(t,e)});function jD(t){return jv(rG,t)}var sG=Y("ZodBoolean",(t,e)=>{Jw.init(t,e),Cn.init(t,e)});function pr(t){return Lv(sG,t)}var oG=Y("ZodNull",(t,e)=>{Vw.init(t,e),Cn.init(t,e)});function qD(t){return zv(oG,t)}var iG=Y("ZodUnknown",(t,e)=>{Xw.init(t,e),Cn.init(t,e)});function xn(){return Bv(iG)}var aG=Y("ZodNever",(t,e)=>{Qw.init(t,e),Cn.init(t,e)});function cG(t){return qv(aG,t)}var lG=Y("ZodArray",(t,e)=>{Yw.init(t,e),Cn.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(ou(n,r)),t.nonempty=n=>t.check(ou(1,n)),t.max=(n,r)=>t.check(iy(n,r)),t.length=(n,r)=>t.check(ay(n,r)),t.unwrap=()=>t.element});function At(t,e){return RD(lG,t,e)}var HD=Y("ZodObject",(t,e)=>{ey.init(t,e),Cn.init(t,e),Ct.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>is(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:xn()}),t.loose=()=>t.clone({...t._zod.def,catchall:xn()}),t.strict=()=>t.clone({...t._zod.def,catchall:cG()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Ct.extend(t,n),t.merge=n=>Ct.merge(t,n),t.pick=n=>Ct.pick(t,n),t.omit=n=>Ct.omit(t,n),t.partial=(...n)=>Ct.partial(KD,t,n[0]),t.required=(...n)=>Ct.required(ZD,t,n[0])});function Te(t,e){let n={type:"object",get shape(){return Ct.assignProp(this,"shape",{...t}),this.shape},...Ct.normalizeParams(e)};return new HD(n)}function Hr(t,e){return new HD({type:"object",get shape(){return Ct.assignProp(this,"shape",{...t}),this.shape},catchall:xn(),...Ct.normalizeParams(e)})}var WD=Y("ZodUnion",(t,e)=>{ty.init(t,e),Cn.init(t,e),t.options=e.options});function yn(t,e){return new WD({type:"union",options:t,...Ct.normalizeParams(e)})}var uG=Y("ZodDiscriminatedUnion",(t,e)=>{WD.init(t,e),ev.init(t,e)});function lR(t,e,n){return new uG({type:"union",options:e,discriminator:t,...Ct.normalizeParams(n)})}var dG=Y("ZodIntersection",(t,e)=>{tv.init(t,e),Cn.init(t,e)});function fy(t,e){return new dG({type:"intersection",left:t,right:e})}var pG=Y("ZodRecord",(t,e)=>{nv.init(t,e),Cn.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function dn(t,e,n){return new pG({type:"record",keyType:t,valueType:e,...Ct.normalizeParams(n)})}var aR=Y("ZodEnum",(t,e)=>{rv.init(t,e),Cn.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,s)=>{let o={};for(let i of r)if(n.has(i))o[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new aR({...e,checks:[],...Ct.normalizeParams(s),entries:o})},t.exclude=(r,s)=>{let o={...e.entries};for(let i of r)if(n.has(i))delete o[i];else throw new Error(`Key ${i} not found in enum`);return new aR({...e,checks:[],...Ct.normalizeParams(s),entries:o})}});function is(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new aR({type:"enum",entries:n,...Ct.normalizeParams(e)})}var fG=Y("ZodLiteral",(t,e)=>{sv.init(t,e),Cn.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 ze(t,e){return new fG({type:"literal",values:Array.isArray(t)?t:[t],...Ct.normalizeParams(e)})}var mG=Y("ZodTransform",(t,e)=>{ov.init(t,e),Cn.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=o=>{if(typeof o=="string")n.issues.push(Ct.issue(o,n.value,e));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),n.issues.push(Ct.issue(i))}};let s=e.transform(n.value,n);return s instanceof Promise?s.then(o=>(n.value=o,n)):(n.value=s,n)}});function UD(t){return new mG({type:"transform",transform:t})}var KD=Y("ZodOptional",(t,e)=>{iv.init(t,e),Cn.init(t,e),t.unwrap=()=>t._zod.def.innerType});function _n(t){return new KD({type:"optional",innerType:t})}var hG=Y("ZodNullable",(t,e)=>{av.init(t,e),Cn.init(t,e),t.unwrap=()=>t._zod.def.innerType});function LD(t){return new hG({type:"nullable",innerType:t})}var gG=Y("ZodDefault",(t,e)=>{cv.init(t,e),Cn.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function yG(t,e){return new gG({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var bG=Y("ZodPrefault",(t,e)=>{lv.init(t,e),Cn.init(t,e),t.unwrap=()=>t._zod.def.innerType});function SG(t,e){return new bG({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var ZD=Y("ZodNonOptional",(t,e)=>{uv.init(t,e),Cn.init(t,e),t.unwrap=()=>t._zod.def.innerType});function xG(t,e){return new ZD({type:"nonoptional",innerType:t,...Ct.normalizeParams(e)})}var _G=Y("ZodCatch",(t,e)=>{dv.init(t,e),Cn.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function wG(t,e){return new _G({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var vG=Y("ZodPipe",(t,e)=>{pv.init(t,e),Cn.init(t,e),t.in=e.in,t.out=e.out});function cR(t,e){return new vG({type:"pipe",in:t,out:e})}var RG=Y("ZodReadonly",(t,e)=>{fv.init(t,e),Cn.init(t,e)});function kG(t){return new RG({type:"readonly",innerType:t})}var GD=Y("ZodCustom",(t,e)=>{mv.init(t,e),Cn.init(t,e)});function EG(t){let e=new br({check:"custom"});return e._zod.check=t,e}function JD(t,e){return Yv(GD,t??(()=>!0),e)}function TG(t,e={}){return eR(GD,t,e)}function PG(t){let e=EG(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Ct.issue(r,n.value,e._zod.def));else{let s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=e),s.continue??(s.continue=!e._zod.def.abort),n.issues.push(Ct.issue(s))}},t(n.value,n)));return e}function uR(t,e){return cR(UD(t),e)}Ns(bD());var pR="2025-11-25",VD="2025-03-26",cu=[pR,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ha="io.modelcontextprotocol/related-task",hy="2.0",rr=JD(t=>t!==null&&(typeof t=="object"||typeof t=="function")),XD=yn([Q(),Xt().int()]),QD=Q(),Nle=Hr({ttl:Xt().optional(),pollInterval:Xt().optional()}),CG=Te({ttl:Xt().optional()}),AG=Te({taskId:Q()}),fR=Hr({progressToken:XD.optional(),[ha]:AG.optional()}),Os=Te({_meta:fR.optional()}),uf=Os.extend({task:CG.optional()}),YD=t=>uf.safeParse(t).success,Sr=Te({method:Q(),params:Os.loose().optional()}),ro=Te({_meta:fR.optional()}),so=Te({method:Q(),params:ro.loose().optional()}),xr=Hr({_meta:fR.optional()}),gy=yn([Q(),Xt().int()]),eO=Te({jsonrpc:ze(hy),id:gy,...Sr.shape}).strict(),ga=t=>eO.safeParse(t).success,tO=Te({jsonrpc:ze(hy),...so.shape}).strict(),nO=t=>tO.safeParse(t).success,mR=Te({jsonrpc:ze(hy),id:gy,result:xr}).strict(),Oi=t=>mR.safeParse(t).success;var Ze;(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"})(Ze||(Ze={}));var hR=Te({jsonrpc:ze(hy),id:gy.optional(),error:Te({code:Xt().int(),message:Q(),data:xn().optional()})}).strict();var lu=t=>hR.safeParse(t).success;var df=yn([eO,tO,mR,hR]),Dle=yn([mR,hR]),yy=xr.strict(),IG=ro.extend({requestId:gy.optional(),reason:Q().optional()}),by=so.extend({method:ze("notifications/cancelled"),params:IG}),NG=Te({src:Q(),mimeType:Q().optional(),sizes:At(Q()).optional(),theme:is(["light","dark"]).optional()}),pf=Te({icons:At(NG).optional()}),au=Te({name:Q(),title:Q().optional()}),rO=au.extend({...au.shape,...pf.shape,version:Q(),websiteUrl:Q().optional(),description:Q().optional()}),DG=fy(Te({applyDefaults:pr().optional()}),dn(Q(),xn())),OG=uR(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,fy(Te({form:DG.optional(),url:rr.optional()}),dn(Q(),xn()).optional())),MG=Hr({list:rr.optional(),cancel:rr.optional(),requests:Hr({sampling:Hr({createMessage:rr.optional()}).optional(),elicitation:Hr({create:rr.optional()}).optional()}).optional()}),FG=Hr({list:rr.optional(),cancel:rr.optional(),requests:Hr({tools:Hr({call:rr.optional()}).optional()}).optional()}),$G=Te({experimental:dn(Q(),rr).optional(),sampling:Te({context:rr.optional(),tools:rr.optional()}).optional(),elicitation:OG.optional(),roots:Te({listChanged:pr().optional()}).optional(),tasks:MG.optional(),extensions:dn(Q(),rr).optional()}),jG=Os.extend({protocolVersion:Q(),capabilities:$G,clientInfo:rO}),Sy=Sr.extend({method:ze("initialize"),params:jG}),gR=t=>Sy.safeParse(t).success,LG=Te({experimental:dn(Q(),rr).optional(),logging:rr.optional(),completions:rr.optional(),prompts:Te({listChanged:pr().optional()}).optional(),resources:Te({subscribe:pr().optional(),listChanged:pr().optional()}).optional(),tools:Te({listChanged:pr().optional()}).optional(),tasks:FG.optional(),extensions:dn(Q(),rr).optional()}),zG=xr.extend({protocolVersion:Q(),capabilities:LG,serverInfo:rO,instructions:Q().optional()}),yR=so.extend({method:ze("notifications/initialized"),params:ro.optional()});var xy=Sr.extend({method:ze("ping"),params:Os.optional()}),BG=Te({progress:Xt(),total:_n(Xt()),message:_n(Q())}),qG=Te({...ro.shape,...BG.shape,progressToken:XD}),_y=so.extend({method:ze("notifications/progress"),params:qG}),HG=Os.extend({cursor:QD.optional()}),ff=Sr.extend({params:HG.optional()}),mf=xr.extend({nextCursor:QD.optional()}),WG=is(["working","input_required","completed","failed","cancelled"]),hf=Te({taskId:Q(),status:WG,ttl:yn([Xt(),qD()]),createdAt:Q(),lastUpdatedAt:Q(),pollInterval:_n(Xt()),statusMessage:_n(Q())}),uu=xr.extend({task:hf}),UG=ro.merge(hf),gf=so.extend({method:ze("notifications/tasks/status"),params:UG}),wy=Sr.extend({method:ze("tasks/get"),params:Os.extend({taskId:Q()})}),vy=xr.merge(hf),Ry=Sr.extend({method:ze("tasks/result"),params:Os.extend({taskId:Q()})}),Ole=xr.loose(),ky=ff.extend({method:ze("tasks/list")}),Ey=mf.extend({tasks:At(hf)}),Ty=Sr.extend({method:ze("tasks/cancel"),params:Os.extend({taskId:Q()})}),sO=xr.merge(hf),oO=Te({uri:Q(),mimeType:_n(Q()),_meta:dn(Q(),xn()).optional()}),iO=oO.extend({text:Q()}),bR=Q().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),aO=oO.extend({blob:bR}),yf=is(["user","assistant"]),du=Te({audience:At(yf).optional(),priority:Xt().min(0).max(1).optional(),lastModified:cf.datetime({offset:!0}).optional()}),cO=Te({...au.shape,...pf.shape,uri:Q(),description:_n(Q()),mimeType:_n(Q()),size:_n(Xt()),annotations:du.optional(),_meta:_n(Hr({}))}),KG=Te({...au.shape,...pf.shape,uriTemplate:Q(),description:_n(Q()),mimeType:_n(Q()),annotations:du.optional(),_meta:_n(Hr({}))}),Py=ff.extend({method:ze("resources/list")}),ZG=mf.extend({resources:At(cO)}),Cy=ff.extend({method:ze("resources/templates/list")}),GG=mf.extend({resourceTemplates:At(KG)}),SR=Os.extend({uri:Q()}),JG=SR,Ay=Sr.extend({method:ze("resources/read"),params:JG}),VG=xr.extend({contents:At(yn([iO,aO]))}),XG=so.extend({method:ze("notifications/resources/list_changed"),params:ro.optional()}),QG=SR,YG=Sr.extend({method:ze("resources/subscribe"),params:QG}),e2=SR,t2=Sr.extend({method:ze("resources/unsubscribe"),params:e2}),n2=ro.extend({uri:Q()}),r2=so.extend({method:ze("notifications/resources/updated"),params:n2}),s2=Te({name:Q(),description:_n(Q()),required:_n(pr())}),o2=Te({...au.shape,...pf.shape,description:_n(Q()),arguments:_n(At(s2)),_meta:_n(Hr({}))}),pu=ff.extend({method:ze("prompts/list")}),i2=mf.extend({prompts:At(o2)}),a2=Os.extend({name:Q(),arguments:dn(Q(),Q()).optional()}),fu=Sr.extend({method:ze("prompts/get"),params:a2}),xR=Te({type:ze("text"),text:Q(),annotations:du.optional(),_meta:dn(Q(),xn()).optional()}),_R=Te({type:ze("image"),data:bR,mimeType:Q(),annotations:du.optional(),_meta:dn(Q(),xn()).optional()}),wR=Te({type:ze("audio"),data:bR,mimeType:Q(),annotations:du.optional(),_meta:dn(Q(),xn()).optional()}),c2=Te({type:ze("tool_use"),name:Q(),id:Q(),input:dn(Q(),xn()),_meta:dn(Q(),xn()).optional()}),l2=Te({type:ze("resource"),resource:yn([iO,aO]),annotations:du.optional(),_meta:dn(Q(),xn()).optional()}),u2=cO.extend({type:ze("resource_link")}),vR=yn([xR,_R,wR,u2,l2]),d2=Te({role:yf,content:vR}),p2=xr.extend({description:Q().optional(),messages:At(d2)}),f2=so.extend({method:ze("notifications/prompts/list_changed"),params:ro.optional()}),m2=Te({title:Q().optional(),readOnlyHint:pr().optional(),destructiveHint:pr().optional(),idempotentHint:pr().optional(),openWorldHint:pr().optional()}),h2=Te({taskSupport:is(["required","optional","forbidden"]).optional()}),lO=Te({...au.shape,...pf.shape,description:Q().optional(),inputSchema:Te({type:ze("object"),properties:dn(Q(),rr).optional(),required:At(Q()).optional()}).catchall(xn()),outputSchema:Te({type:ze("object"),properties:dn(Q(),rr).optional(),required:At(Q()).optional()}).catchall(xn()).optional(),annotations:m2.optional(),execution:h2.optional(),_meta:dn(Q(),xn()).optional()}),mu=ff.extend({method:ze("tools/list")}),g2=mf.extend({tools:At(lO)}),Iy=xr.extend({content:At(vR).default([]),structuredContent:dn(Q(),xn()).optional(),isError:pr().optional()}),Mle=Iy.or(xr.extend({toolResult:xn()})),y2=uf.extend({name:Q(),arguments:dn(Q(),xn()).optional()}),ya=Sr.extend({method:ze("tools/call"),params:y2}),b2=so.extend({method:ze("notifications/tools/list_changed"),params:ro.optional()}),Fle=Te({autoRefresh:pr().default(!0),debounceMs:Xt().int().nonnegative().default(300)}),bf=is(["debug","info","notice","warning","error","critical","alert","emergency"]),S2=Os.extend({level:bf}),RR=Sr.extend({method:ze("logging/setLevel"),params:S2}),x2=ro.extend({level:bf,logger:Q().optional(),data:xn()}),_2=so.extend({method:ze("notifications/message"),params:x2}),w2=Te({name:Q().optional()}),v2=Te({hints:At(w2).optional(),costPriority:Xt().min(0).max(1).optional(),speedPriority:Xt().min(0).max(1).optional(),intelligencePriority:Xt().min(0).max(1).optional()}),R2=Te({mode:is(["auto","required","none"]).optional()}),k2=Te({type:ze("tool_result"),toolUseId:Q().describe("The unique identifier for the corresponding tool call."),content:At(vR).default([]),structuredContent:Te({}).loose().optional(),isError:pr().optional(),_meta:dn(Q(),xn()).optional()}),E2=lR("type",[xR,_R,wR]),my=lR("type",[xR,_R,wR,c2,k2]),T2=Te({role:yf,content:yn([my,At(my)]),_meta:dn(Q(),xn()).optional()}),P2=uf.extend({messages:At(T2),modelPreferences:v2.optional(),systemPrompt:Q().optional(),includeContext:is(["none","thisServer","allServers"]).optional(),temperature:Xt().optional(),maxTokens:Xt().int(),stopSequences:At(Q()).optional(),metadata:rr.optional(),tools:At(lO).optional(),toolChoice:R2.optional()}),C2=Sr.extend({method:ze("sampling/createMessage"),params:P2}),Sf=xr.extend({model:Q(),stopReason:_n(is(["endTurn","stopSequence","maxTokens"]).or(Q())),role:yf,content:E2}),kR=xr.extend({model:Q(),stopReason:_n(is(["endTurn","stopSequence","maxTokens","toolUse"]).or(Q())),role:yf,content:yn([my,At(my)])}),A2=Te({type:ze("boolean"),title:Q().optional(),description:Q().optional(),default:pr().optional()}),I2=Te({type:ze("string"),title:Q().optional(),description:Q().optional(),minLength:Xt().optional(),maxLength:Xt().optional(),format:is(["email","uri","date","date-time"]).optional(),default:Q().optional()}),N2=Te({type:is(["number","integer"]),title:Q().optional(),description:Q().optional(),minimum:Xt().optional(),maximum:Xt().optional(),default:Xt().optional()}),D2=Te({type:ze("string"),title:Q().optional(),description:Q().optional(),enum:At(Q()),default:Q().optional()}),O2=Te({type:ze("string"),title:Q().optional(),description:Q().optional(),oneOf:At(Te({const:Q(),title:Q()})),default:Q().optional()}),M2=Te({type:ze("string"),title:Q().optional(),description:Q().optional(),enum:At(Q()),enumNames:At(Q()).optional(),default:Q().optional()}),F2=yn([D2,O2]),$2=Te({type:ze("array"),title:Q().optional(),description:Q().optional(),minItems:Xt().optional(),maxItems:Xt().optional(),items:Te({type:ze("string"),enum:At(Q())}),default:At(Q()).optional()}),j2=Te({type:ze("array"),title:Q().optional(),description:Q().optional(),minItems:Xt().optional(),maxItems:Xt().optional(),items:Te({anyOf:At(Te({const:Q(),title:Q()}))}),default:At(Q()).optional()}),L2=yn([$2,j2]),z2=yn([M2,F2,L2]),B2=yn([z2,A2,I2,N2]),q2=uf.extend({mode:ze("form").optional(),message:Q(),requestedSchema:Te({type:ze("object"),properties:dn(Q(),B2),required:At(Q()).optional()})}),H2=uf.extend({mode:ze("url"),message:Q(),elicitationId:Q(),url:Q().url()}),W2=yn([q2,H2]),U2=Sr.extend({method:ze("elicitation/create"),params:W2}),K2=ro.extend({elicitationId:Q()}),Z2=so.extend({method:ze("notifications/elicitation/complete"),params:K2}),hu=xr.extend({action:is(["accept","decline","cancel"]),content:uR(t=>t===null?void 0:t,dn(Q(),yn([Q(),Xt(),pr(),At(Q())])).optional())}),G2=Te({type:ze("ref/resource"),uri:Q()});var J2=Te({type:ze("ref/prompt"),name:Q()}),V2=Os.extend({ref:yn([J2,G2]),argument:Te({name:Q(),value:Q()}),context:Te({arguments:dn(Q(),Q()).optional()}).optional()}),Ny=Sr.extend({method:ze("completion/complete"),params:V2});function uO(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function dO(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var X2=xr.extend({completion:Hr({values:At(Q()).max(100),total:_n(Xt().int()),hasMore:_n(pr())})}),Q2=Te({uri:Q().startsWith("file://"),name:Q().optional(),_meta:dn(Q(),xn()).optional()}),Y2=Sr.extend({method:ze("roots/list"),params:Os.optional()}),ER=xr.extend({roots:At(Q2)}),eJ=so.extend({method:ze("notifications/roots/list_changed"),params:ro.optional()}),$le=yn([xy,Sy,Ny,RR,fu,pu,Py,Cy,Ay,YG,t2,ya,mu,wy,Ry,ky,Ty]),jle=yn([by,_y,yR,eJ,gf]),Lle=yn([yy,Sf,kR,hu,ER,vy,Ey,uu]),zle=yn([xy,C2,U2,Y2,wy,Ry,ky,Ty]),Ble=yn([by,_y,_2,r2,XG,b2,f2,gf,Z2]),qle=yn([yy,zG,X2,p2,i2,ZG,GG,VG,Iy,g2,vy,Ey,uu]),je=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===Ze.UrlElicitationRequired&&r){let s=r;if(s.elicitations)return new dR(s.elicitations,n)}return new t(e,n,r)}},dR=class extends je{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(Ze.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function ba(t){return t==="completed"||t==="failed"||t==="cancelled"}var fO=Symbol("Let zodToJsonSchema decide on which parser to use");var pO={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"},mO=t=>typeof t=="string"?{...pO,name:t}:{...pO,...t};var hO=t=>{let e=mO(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function TR(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function It(t,e,n,r,s){t[e]=n,TR(t,e,r,s)}var Dy=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")};function wn(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Dy(e,t.currentPath):e.join("/")}}function gO(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==le.ZodAny&&(n.items=nt(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&It(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&It(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(It(n,"minItems",t.exactLength.value,t.exactLength.message,e),It(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function yO(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?It(n,"minimum",r.value,r.message,e):It(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),It(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?It(n,"maximum",r.value,r.message,e):It(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),It(n,"maximum",r.value,r.message,e));break;case"multipleOf":It(n,"multipleOf",r.value,r.message,e);break}return n}function bO(){return{type:"boolean"}}function Oy(t,e){return nt(t.type._def,e)}var SO=(t,e)=>nt(t.innerType._def,e);function PR(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,o)=>PR(t,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return tJ(t,e)}}var tJ=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":It(n,"minimum",r.value,r.message,e);break;case"max":It(n,"maximum",r.value,r.message,e);break}return n};function xO(t,e){return{...nt(t.innerType._def,e),default:t.defaultValue()}}function _O(t,e){return e.effectStrategy==="input"?nt(t.schema._def,e):wn(e)}function wO(t){return{type:"string",enum:Array.from(t.values)}}var nJ=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function vO(t,e){let n=[nt(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),nt(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return n.forEach(o=>{if(nJ(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(r=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...c}=o;i=c}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function RO(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var CR,Io={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:()=>(CR===void 0&&(CR=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),CR),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 My(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":It(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":It(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":No(n,"email",r.message,e);break;case"format:idn-email":No(n,"idn-email",r.message,e);break;case"pattern:zod":Wr(n,Io.email,r.message,e);break}break;case"url":No(n,"uri",r.message,e);break;case"uuid":No(n,"uuid",r.message,e);break;case"regex":Wr(n,r.regex,r.message,e);break;case"cuid":Wr(n,Io.cuid,r.message,e);break;case"cuid2":Wr(n,Io.cuid2,r.message,e);break;case"startsWith":Wr(n,RegExp(`^${AR(r.value,e)}`),r.message,e);break;case"endsWith":Wr(n,RegExp(`${AR(r.value,e)}$`),r.message,e);break;case"datetime":No(n,"date-time",r.message,e);break;case"date":No(n,"date",r.message,e);break;case"time":No(n,"time",r.message,e);break;case"duration":No(n,"duration",r.message,e);break;case"length":It(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),It(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Wr(n,RegExp(AR(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&No(n,"ipv4",r.message,e),r.version!=="v4"&&No(n,"ipv6",r.message,e);break}case"base64url":Wr(n,Io.base64url,r.message,e);break;case"jwt":Wr(n,Io.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&Wr(n,Io.ipv4Cidr,r.message,e),r.version!=="v4"&&Wr(n,Io.ipv6Cidr,r.message,e);break}case"emoji":Wr(n,Io.emoji(),r.message,e);break;case"ulid":{Wr(n,Io.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{No(n,"binary",r.message,e);break}case"contentEncoding:base64":{It(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Wr(n,Io.base64,r.message,e);break}}break}case"nanoid":Wr(n,Io.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function AR(t,e){return e.patternStrategy==="escape"?sJ(t):t}var rJ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function sJ(t){let e="";for(let n=0;n<t.length;n++)rJ.has(t[n])||(e+="\\"),e+=t[n];return e}function No(t,e,n,r){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.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,...n&&r.errorMessages&&{errorMessage:{format:n}}})):It(t,"format",e,n,r)}function Wr(t,e,n,r){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.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:kO(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):It(t,"pattern",kO(e,r),n,r)}function kO(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,s="",o=!1,i=!1,a=!1;for(let c=0;c<r.length;c++){if(o){s+=r[c],o=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){a?(s+=r[c],s+=`${r[c-2]}-${r[c]}`.toUpperCase(),a=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(s+=r[c],a=!0):s+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){s+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){s+=`(^|(?<=[\r
922
922
  ]))`;continue}else if(r[c]==="$"){s+=`($|(?=[\r
923
923
  ]))`;continue}}if(n.s&&r[c]==="."){s+=i?`${r[c]}\r
924
924
  `:`[${r[c]}\r
@@ -1242,10 +1242,10 @@ RestartSec=1
1242
1242
  WantedBy=multi-user.target
1243
1243
  `}function Mb(t,e,n,r){let s=St.default.join(qu.default.tmpdir(),`pando-helper-${process.pid}-${St.default.basename(t)}`);if(r)return console.log(`install -o root -g ${process.platform==="darwin"?"wheel":"root"} -m ${n} <generated> ${t}`),{ok:!0};$s.default.writeFileSync(s,e,"utf8");let o=Nt("install",["-o","root","-g",process.platform==="darwin"?"wheel":"root","-m",n,s,t],!1);try{$s.default.rmSync(s,{force:!0})}catch{}return o}function o8(t,e,n){if(n)return console.log(`rm -rf ${e}`),console.log(`mkdir -p ${e}`),console.log(`ditto ${t} ${e}`),console.log(`chmod -R a+rX ${e}`),{ok:!0};let r=Nt("rm",["-rf",e],!1);return!r.ok||(r=Nt("mkdir",["-p",e],!1),!r.ok)||(r=Nt("ditto",[t,e],!1),!r.ok)||(r=Nt("chown",["-R","root:"+(process.platform==="darwin"?"wheel":"root"),e],!1),!r.ok)?r:Nt("chmod",["-R","a+rX",e],!1)}function i8(t,e){let n=n8(),r=["install","--omit=dev","--ignore-scripts","--no-audit","--no-fund","--prefix",t];if(e)return console.log([n,...r].join(" ")),console.log(`verify ${St.default.join(t,"node_modules","typescript","package.json")}`),console.log(`verify ${St.default.join(t,"node_modules","ts-morph","package.json")}`),{ok:!0};let s=Nt(n,r,!1);if(!s.ok)return s;let o=["typescript","ts-morph"].filter(i=>!$s.default.existsSync(St.default.join(t,"node_modules",i,"package.json")));return o.length>0?{ok:!1,error:`Root helper runtime dependency install completed but missing ${o.join(", ")} under ${t}. Run ${n} install --omit=dev --ignore-scripts --no-audit --no-fund --prefix ${t} and retry setup.`}:{ok:!0}}function a8(t,e){if(process.platform==="darwin"){let n=Lj,r=o8(t8(),n,t);if(!r.ok||(r=i8(n,t),!r.ok)||(r=Mb(Lb,$j({dataRoot:e,cliPath:St.default.join(n,"dist","cli.js"),daemonPath:St.default.join(n,"dist","security-daemon.js")}),"0755",t),!r.ok)||(r=Mb(Bu,r8(),"0644",t),!r.ok))return r;let s=Nt("launchctl",["bootout","system",Bu],t);return!s.ok&&!/No such process|not found|does not exist|Boot-out failed:\s*5|Input\/output error/i.test(s.error)?s:Nt("launchctl",["bootstrap","system",Bu],t)}if(process.platform==="linux"){let n=Nt("mkdir",["-p",St.default.dirname(Xf)],t);return!n.ok||(n=Mb(Xf,$j({dataRoot:e}),"0755",t),!n.ok)||(n=Mb(vE,s8(),"0644",t),!n.ok)||(n=Nt("systemctl",["daemon-reload"],t),!n.ok)?n:Nt("systemctl",["enable","--now","pando-security-helper.service"],t)}return{ok:!1,error:`Pando security helper daemon is not implemented on ${process.platform}`}}function c8(t){if(process.platform==="darwin"){let e=Nt("launchctl",["bootout","system",Bu],t);if(!e.ok&&!/No such process|not found|does not exist|Boot-out failed:\s*5|Input\/output error/i.test(e.error))return e;let n=Nt("rm",["-f",Bu],t);return!n.ok||(n=Nt("rm",["-f",Lb],t),!n.ok)||(n=Nt("rm",["-rf",Lj],t),!n.ok)||(n=Nt("rm",["-f",Lc],t),!n.ok)?n:Nt("rm",["-f",zj],t)}if(process.platform==="linux"){let e=Nt("systemctl",["disable","--now","pando-security-helper.service"],t);if(!e.ok&&!/not loaded|not found|does not exist/i.test(e.error))return e;let n=Nt("rm",["-f",vE],t);return!n.ok||(n=Nt("rm",["-f",Xf],t),!n.ok)?n:Nt("systemctl",["daemon-reload"],t)}return{ok:!0}}function Gj(t,e){let n=[{target:t,user:Uc,kind:"write",recursive:!0},{target:t,user:Kc,kind:"write",recursive:!0}];return e&&n.unshift({target:e,user:Uc,kind:"write",recursive:!0},{target:e,user:Kc,kind:"read",recursive:!0}),n}function l8(t,e){let n=Gj(t,e),r=new Set;for(let{target:o,user:i}of n)for(let a of Zj(o))r.add(`${a}\0${i}`);let s=[];for(let o of r){let[i,a]=o.split("\0"),c="traverse";s.push({platform:process.platform,target:St.default.resolve(i),user:a,kind:c,recursive:!1,acl:process.platform==="darwin"?_E(a,c):wE(a,c)})}for(let o of n)s.push({platform:process.platform,target:St.default.resolve(o.target),user:o.user,kind:o.kind,recursive:o.recursive,acl:process.platform==="darwin"?_E(o.user,o.kind):wE(o.user,o.kind)});return s}function u8(t,e){return t.platform===e.platform&&t.target===e.target&&t.user===e.user&&t.kind===e.kind&&t.recursive===e.recursive&&t.acl===e.acl}function Jj(t,e){let n=St.default.resolve(t),r=St.default.resolve(e);if($o(r))return!1;let o=TE(n);return l8(n,r).every(i=>o.some(a=>u8(a,i)))}function Qf(t){let e=!!t.dryRun,n=St.default.resolve(t.dataRoot),r=t.realRoot?St.default.resolve(t.realRoot):null;if(r){let a=$o(r);if(a)return{ok:!1,message:`Refusing to configure Pando security for project root '${r}' (matches protected path '${a}'). Run pando-ai from a real project folder, not your home directory, /Users, a system directory, or a credential/config directory.`}}GQ(n);for(let a of[Uc,Kc]){t.onProgress?.(`ensuring dedicated user ${a}`);let c=ZQ(a,e);if(!c.ok)return{ok:!1,message:c.error}}let s=Gj(n,r),o=new Set;for(let{target:a,user:c}of s)for(let l of Zj(a))o.add(`${l}\0${c}`);for(let a of o){let[c,l]=a.split("\0");t.onProgress?.(`granting ${l} traverse access to ${c}`);let u=Fj({dataRoot:n,target:c,user:l,kind:"traverse",recursive:!1,dryRun:e});if(!u.ok)return{ok:!1,message:u.error}}for(let a of s){t.onProgress?.(`granting ${a.user} ${a.kind} access to ${a.target}`);let c=Fj({dataRoot:n,...a,dryRun:e});if(!c.ok)return{ok:!1,message:c.error}}t.onProgress?.("installing privileged helper daemon");let i=a8(e,n);return i.ok?{ok:!0,message:r?`Pando dedicated users, repo ACLs, and helper daemon configured: ${Uc}, ${Kc}`:`Pando dedicated users, data ACLs, and helper daemon configured: ${Uc}, ${Kc}`}:{ok:!1,message:i.error}}function d8(t,e){return qb(t)?kE(t)?process.platform==="darwin"?Nt("dscl",[".","-delete",`/Users/${t}`],e):process.platform==="linux"?Nt("userdel",[t],e):{ok:!1,error:`Dedicated Pando user removal is not implemented on ${process.platform}`}:{ok:!0}:{ok:!0}}function p8(t){return process.platform!=="darwin"||!RE(ri)?{ok:!0}:Wj(ri)?Nt("dscl",[".","-delete",`/Groups/${ri}`],t):{ok:!0}}function f8(t,e){let n=TE(t).filter(r=>r.platform===process.platform);for(let r of[...n].reverse()){let s=Kj(r,e,!0);if(!s.ok)return s}if(e)return console.log(`rm -f ${$b(t)}`),{ok:!0};try{$s.default.rmSync($b(t),{force:!0})}catch{}return{ok:!0}}function PE(t={}){let e=!!t.dryRun,n=St.default.resolve(t.dataRoot||St.default.join(qu.default.homedir(),".pando-data")),r=c8(e);if(!r.ok)return{ok:!1,message:r.error};let s=f8(n,e);if(!s.ok)return{ok:!1,message:s.error};for(let i of[Uc,Kc]){let a=d8(i,e);if(!a.ok)return{ok:!1,message:a.error}}let o=p8(e);return o.ok?{ok:!0,message:"Pando dedicated users removed"}:{ok:!1,message:o.error}}async function Vj(t){let e=t[0];if(e!=="setup-users"&&e!=="uninstall-users"&&e!=="launch"&&e!=="daemon")return console.error("Usage: pando-ai security setup-users [--data-root <path>] [--real-root <path>] [--dry-run]"),console.error(" pando-ai security uninstall-users [--data-root <path>] [--dry-run]"),console.error(" pando-ai security launch --role <core|workspace> --project-root <path> --stdio"),console.error(" pando-ai security daemon [--socket <path>] (internal root-owned helper)"),1;let n=t.includes("--dry-run");if(e==="daemon")return xF(t.slice(1));if(e==="launch")return SF(t.slice(1));if(e==="uninstall-users"){let i=xE(t,"--data-root"),a=PE({dataRoot:i??void 0,dryRun:n});return a.ok?(console.log(a.message),0):(console.error(a.message),1)}let r=xE(t,"--data-root")||St.default.join(qu.default.homedir(),".pando-data"),s=xE(t,"--real-root");s&&await XQ(s,n);let o=Qf({dataRoot:r,realRoot:s??void 0,dryRun:n});return o.ok?(console.log(o.message),0):(console.error(o.message),1)}dt();var CE="PANDO_PROCESS_ROLE",Hb="PANDO_BROKERED_AUTH";function AE(){let t=process.env.PANDO_SECURITY_HELPER_SOCKET||Lc,e=zb(),n=!1;try{n=Yf.default.existsSync(t)}catch{n=!1}return{securityInstalled:e,daemonAvailable:n,socketPath:t}}var eL="pando_core",tL="pando_workspace",IE=[eL,tL];function Xj(t,e){let n=e??"core",r=AE(),s=kk("security",["launch","--role",n,"--project-root",t,"--stdio"]),o={[CE]:n};(n==="workspace"||/^(1|true|yes)$/i.test(process.env[Hb]||""))&&(o[Hb]="1");let i={...s,env:o};return W("PandoMcpConfig","server spec generated",{projectRoot:t,role:e??null,effectiveRole:n,command:i.command,args:i.args,env:{PANDO_PROCESS_ROLE:i.env?.[CE],PANDO_BROKERED_AUTH:i.env?.[Hb]},security:r,envKeys:Object.keys(i.env||{}).sort()}),i}function nL(t){return{[eL]:Xj(t,"core"),[tL]:Xj(t,"workspace")}}function m8(t){return{command:t.command,args:t.args,env:{...t.env??{},PANDO_MCP_OUTPUT:process.env.PANDO_MCP_OUTPUT??"markdown",PANDO_MCP_CLIENT:"claude"}}}function rL(t,e=null){let n=h8(t,e),r=Object.fromEntries(Object.entries(nL(t)).map(([s,o])=>[s,m8(o)]));return{mcpServers:{...n,...r}}}function sL(t,e=null){return JSON.stringify(rL(t,e))}function oL(t,e=null){let n=rL(t,e),r=Pa.default.join(Ms(),"mcp");Yf.default.mkdirSync(r,{recursive:!0});let s=Pa.default.join(r,"claude-mcp-config.json");return Yf.default.writeFileSync(s,`${JSON.stringify(n,null,2)}
1244
1244
  `),s}function h8(t,e){let n=e===null?null:new Set(e.map(Qj).filter(Boolean));if(n&&n.size===0)return{};let r={};for(let s of g8(t)){let o;try{o=JSON.parse(Yf.default.readFileSync(s,"utf8"))}catch{continue}let i=y8(o);for(let[a,c]of Object.entries(i))(n===null||n.has(Qj(a)))&&!(a in r)&&(r[a]=c)}return r}function g8(t){let e=process.env.PANDO_CLAUDE_MCP_CONFIG?[process.env.PANDO_CLAUDE_MCP_CONFIG]:[],n=Yj.default.homedir();return[...e,Pa.default.join(t,".mcp.json"),Pa.default.join(process.cwd(),".mcp.json"),Pa.default.join(n,".mcp.json"),Pa.default.join(n,".claude","mcp.json"),Pa.default.join(n,".config","claude","mcp.json")]}function y8(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e=t,n=e.mcpServers??e.mcp_servers;return!n||typeof n!="object"||Array.isArray(n)?{}:n}function Qj(t){return t.replace(/^mcp__/,"").replace(/__.*$/,"").trim()}function iL(t){let e=[],n={};for(let[r,s]of Object.entries(nL(t))){n[r]={command:s.command,args:s.args,env:{PANDO_PROCESS_ROLE:s.env?.[CE],PANDO_BROKERED_AUTH:s.env?.[Hb]},envKeys:Object.keys(s.env||{}).sort()};let o=`mcp_servers.${r}`;e.push("-c",`${o}.command=${JSON.stringify(s.command)}`,"-c",`${o}.args=${JSON.stringify(s.args)}`,"-c",`${o}.required=true`,"-c",`${o}.enabled=true`,"-c",`${o}.default_tools_approval_mode="approve"`);for(let[i,a]of Object.entries(s.env||{}))e.push("-c",`${o}.env.${i}=${JSON.stringify(a)}`);e.push("-c",`${o}.env.PANDO_MCP_CLIENT=${JSON.stringify("codex")}`)}return W("PandoMcpConfig","codex MCP args generated",{projectRoot:t,serverCount:Object.keys(n).length,servers:n}),e}var NE=B(require("fs")),DE=B(require("path"));var b8=["mcp__computer-use","mcp__computer-use__*"],OE=["SessionStart","Setup","InstructionsLoaded","UserPromptSubmit","UserPromptExpansion","MessageDisplay","PreToolUse","PermissionRequest","PostToolUse","PostToolUseFailure","PostToolBatch","PermissionDenied","Notification","SubagentStart","SubagentStop","TaskCreated","TaskCompleted","Stop","StopFailure","TeammateIdle","ConfigChange","CwdChanged","WorktreeCreate","WorktreeRemove","PreCompact","PostCompact","SessionEnd","Elicitation","ElicitationResult"];function aL(){return JSON.stringify(lL())}function cL(){let t=DE.default.join(Ms(),"claude");NE.default.mkdirSync(t,{recursive:!0});let e=DE.default.join(t,"hook-settings.json");return NE.default.writeFileSync(e,`${JSON.stringify(lL(),null,2)}
1245
- `),e}function lL(){let t=S8(),e={};for(let n of OE)e[n]=[{hooks:[t]}];return{hooks:e,permissions:{deny:[...b8]}}}function S8(){return{type:"command",command:qF("claude-hook")}}zl();function uL(t,e={}){let n=[],r={ENABLE_CLAUDEAI_MCP_SERVERS:"false"},s=[];t.nativeTools==="deny"&&s.push("native tools denied by Claude hooks; Pando MCP explicitly allowed via --allowedTools"),s.push("Claude.ai MCP/connectors disabled (ENABLE_CLAUDEAI_MCP_SERVERS=false)");let o=e.supportedFlags;o?.disableSlashCommands&&s.push("Claude slash commands/skills left enabled (not disabled)"),o?.bare&&s.push("Claude bare mode left OFF (preserves subscription/OAuth auth and hooks)"),o?.noChrome&&(n.push("--no-chrome"),s.push("Claude Chrome/browser tool surface disabled"));let i=yE(),a=_8(t);switch(oL(i,a),n.push("--mcp-config",sL(i,a),"--strict-mcp-config"),s.push(`pand\u014D MCP dynamically injected via --mcp-config/--strict-mcp-config, root-scoped to ${i}; on-disk Claude config left untouched`),n.push(`--allowedTools=${x8().join(",")}`),s.push('snapshots on \u2014 every edit is checkpointed and undoable. In chat, type "pando, undo" to revert the last change, or "pando, history" to see every checkpoint and pick one to roll back to.'),(e.hooksEnabled??!0)&&(cL(),n.push("--settings",aL()),s.push("Claude hooks installed for tool call/result enforcement and transcript audit")),t.otherMcp.mode){case"deny_all":s.push("other MCP servers blocked (strict: pand\u014D only)");break;case"allow_list":t.otherMcp.tools.length>0&&n.push(`--allowedTools=${t.otherMcp.tools.join(",")}`),s.push(`other MCP restricted to allow-list (${t.otherMcp.servers.join(", ")||"none"}); strict config in effect`);break;case"deny_list":if(t.otherMcp.tools.length>0||t.otherMcp.servers.length>0){let c=[...t.otherMcp.tools,...t.otherMcp.servers.map(l=>`mcp__${l}`)];n.push(`--disallowedTools=${c.join(",")}`),s.push(`other MCP deny-list removed from Claude context (${c.join(", ")})`)}break;default:s.push("other MCP servers preserved in strict generated config");break}return{extraArgs:n,env:r,notes:s}}function x8(){let[t,e]=IE;return[...P_("core").map(n=>`mcp__${t}__${n}`),...P_("workspace").map(n=>`mcp__${e}__${n}`)]}function _8(t){switch(t.otherMcp.mode){case"deny_all":return[];case"allow_list":return t.otherMcp.servers;default:return null}}function dL(t){let e=[],n={},r=[];t.nativeTools==="deny"&&(e.push("-c",'sandbox_mode="read-only"'),e.push("-c",'web_search="disabled"'),r.push("native tools restricted (read-only sandbox, web search disabled, best-effort); tool traffic is enforced at the gateway"));let s=yE();switch(e.push(...iL(s)),r.push(`pand\u014D MCP (${IE.join(", ")}) dynamically injected via Codex -c overrides, root-scoped to ${s}; user MCP files are not modified`),r.push('snapshots on \u2014 every edit is checkpointed and undoable. In chat, type "pando, undo" to revert the last change, or "pando, history" to see every checkpoint and pick one to roll back to.'),t.otherMcp.mode){case"deny_all":case"allow_list":case"deny_list":r.push(`other MCP policy "${t.otherMcp.mode}" is best-effort for Codex (no strict-MCP flag); enforced at the gateway, not via config`);break;default:r.push("other MCP servers allowed");break}return{extraArgs:e,env:n,notes:r}}var pL=new Set(["-c","--config","--enable","--disable","--remote","--remote-auth-token-env","-i","--image","-m","--model","--local-provider","-p","--profile","-s","--sandbox","-a","--ask-for-approval","-C","--cd","--add-dir"]);function fL(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="--")return null;if(!w8(n)){if(pL.has(n)){e+=1;continue}if(!n.startsWith("-"))return{name:n,index:e}}}return null}function w8(t){let[e,n]=t.split("=",2);return n!==void 0&&pL.has(e)}var mL="pando-proxy";function v8(t){let e=`model_providers.${mL}`;return["-c",`model_provider="${mL}"`,"-c",`model_auto_compact_token_limit=${t.codexAutoCompactTokenLimit}`,"-c",`${e}.name="Pando Firewall"`,"-c",`${e}.base_url="http://${t.host}:${t.port}/v1"`,"-c",`${e}.wire_api="responses"`,"-c",`${e}.transport="responses_http"`,"-c",`${e}.requires_openai_auth=true`]}function hL(t,e){let n=v8(e),r=fL(t);return r?[...t.slice(0,r.index+1),...n,...t.slice(r.index+1)]:[...n,...t]}dt();Qt();Yc();var R8=28e4,gL="x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles";function An(t){console.error(`[pand\u014D] ${t}`)}function k8(t){let e=ot(t);process.env.PANDO_LOG_DIR||(process.env.PANDO_LOG_DIR=e),process.env.PANDO_GATEWAY_LOG_FILE||(process.env.PANDO_GATEWAY_LOG_FILE=Zc.default.join(e,"gateway-debug.jsonl"))}function E8(){return process.env.PANDO_DATA_DIR||Zc.default.join(process.env.PANDO_HOME_OVERRIDE||ME.default.homedir(),".pando-data")}function T8(t){if(process.platform!=="darwin")return;let e=EE(t);if(e){An(`macOS privacy warning: project root is inside ~/${e.label}. macOS may block the privileged helper even after Unix ACL setup succeeds.`),An("opening macOS Full Disk Access settings so you can grant access to the Pando helper/runtime.");try{(0,em.spawnSync)("open",[gL],{stdio:"ignore"})}catch{An(`could not open Full Disk Access settings automatically: ${gL}`)}}}function P8(t,e){let n=AE(),r=E8(),s=Jj(r,e);if(T8(e),n.daemonAvailable&&s)return!0;let o=[n.daemonAvailable?null:`helper daemon socket missing at ${n.socketPath}`,s?null:"repo ACLs not configured"].filter(Boolean).join("; ");An(`configuring Pando security for ${t}: ${o}`);let i=Qf({dataRoot:r,realRoot:e,onProgress:a=>An(`security setup: ${a}`)});return i.ok?(An(`security setup complete: ${i.message}`),!0):(An(`refusing to launch ${t}: security setup failed: ${i.message}`),!1)}async function Wb(t,e){let n=process.cwd();k8(n);let r=Ca();Rt("session.start",{actor:"pando.launcher",channel:"session",tool:t,projectRoot:n,originalArgs:e});let s=$o(n);if(s)return An(`refusing to launch ${t}: project root '${n}' is not allowed (matches protected path '${s}'). Start ${t} from a real project folder inside your home directory, not directly from /Users, your home directory, a system directory, or a credential/config directory.`),Rt("session.end",{actor:"pando.launcher",channel:"session",tool:t,sessionId:r,exitCode:78,reason:"forbidden_project_root",projectRoot:n,forbiddenRoot:s}),78;let o=FF(t);if(!o)return An(`could not find the real \`${t}\` binary. Is it installed and on PATH (outside ~/.pando/bin)?`),Rt("session.end",{actor:"pando.launcher",channel:"session",tool:t,sessionId:r,exitCode:127,reason:"real_binary_not_found"}),127;let i=Kr();if(t==="claude"){let y=N8();if(y)return An(`refusing to launch claude: Claude hooks are disabled by ${y}. pand\u014D requires hooks for subscription-mode tool/result enforcement.`),Rt("session.end",{actor:"pando.launcher",channel:"session",tool:t,sessionId:r,exitCode:78,reason:"claude_hooks_disabled",disabledBy:y}),78}if(!P8(t,n))return W("Launch","security setup failed",{tool:t,projectRoot:n}),Rt("session.end",{actor:"pando.launcher",channel:"session",tool:t,sessionId:r,exitCode:78,reason:"security_setup_failed"}),78;let a=Eu({memoryEnabled:i.memory}),c=i.proxy[t]==="enforce",l=t==="claude"?C8():!1,u=c&&(t==="codex"||l),d=/^(1|true|yes)$/i.test(process.env.PANDO_ALLOW_UNSUPERVISED||""),p=null;if(u)try{p=await zu(a,y=>{W("Gateway","runtime log",{message:y})})}catch(y){let b=y instanceof Error?y.message:String(y);if(!d)return An(`refusing to launch ${t}: the pand\u014D gateway could not start (${b}). Fix the problem, or set PANDO_ALLOW_UNSUPERVISED=1 to run ${t} without wire interception (NOT recommended \u2014 the firewall will be off).`),Rt("session.end",{actor:"pando.launcher",channel:"session",tool:t,sessionId:r,exitCode:78,reason:"gateway_start_failed",error:b}),78;An(`gateway failed to start (${b}); PANDO_ALLOW_UNSUPERVISED is set, so launching ${t} WITHOUT wire interception.`)}let f=t==="claude"&&!p;c?f&&!l?An("Claude gateway auth not configured; using Claude hooks-only fallback for tool call/result firewalling."):f&&An("Claude gateway unavailable; using Claude hooks-only fallback for tool call/result firewalling."):An(`${t} provider proxy disabled by policy; ${t==="claude"?"using Claude hooks only":"Codex provider-bound gateway enforcement is off"}.`);let{childArgs:m,childEnv:h}=B8(t,e,i,p,o);/^(1|true|yes)$/i.test(process.env.PANDO_DEBUG_LAUNCH_ARGS||"")&&(An(`debug launch args: ${JSON.stringify(m)}`),An(`debug launch env: ANTHROPIC_BASE_URL=${h.ANTHROPIC_BASE_URL?"set":"unset"} PANDO_ALLOW_UNSUPERVISED=${h.PANDO_ALLOW_UNSUPERVISED?"set":"unset"} PANDO_GATEWAY_MEMORY=${h.PANDO_GATEWAY_MEMORY?"set":"unset"}`)),An(`supervising ${t}: gateway=${p?"on":"off"} ${t==="claude"?"hooks=on ":""}pando_mcp=on policy native_tools=${i.nativeTools} other_mcp=${i.otherMcp.mode}`),W("Launch","supervised run start",{sessionId:r,tool:t,gateway:p?"on":"off",memory:i.memory,nativeTools:i.nativeTools,otherMcp:i.otherMcp.mode}),await W8(t);let g=await U8(o,m,h);return p&&await p.close().catch(()=>{}),W("Launch","supervised run end",{tool:t,exitCode:g}),Rt("session.end",{actor:"pando.launcher",channel:"session",tool:t,sessionId:r,exitCode:g}),g}function C8(){return!!(process.env.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||A8())}function A8(){for(let t of xL()){let e=_L(t);if(!e)continue;if(typeof e.apiKeyHelper=="string"&&e.apiKeyHelper.trim())return!0;let n=e.env;if(n&&typeof n=="object"&&!Array.isArray(n)&&(yL(n.ANTHROPIC_API_KEY)||yL(n.ANTHROPIC_AUTH_TOKEN)))return!0}return!1}function xL(){let t=I8(),e=process.env.CLAUDE_CONFIG_DIR||Zc.default.join(t,".claude"),n=process.cwd();return[...process.platform==="darwin"?[...process.env.PANDO_CLAUDE_MANAGED_SETTINGS?[process.env.PANDO_CLAUDE_MANAGED_SETTINGS]:[],"/Library/Application Support/ClaudeCode/managed-settings.json"]:process.platform==="win32"?process.env.PANDO_CLAUDE_MANAGED_SETTINGS?[process.env.PANDO_CLAUDE_MANAGED_SETTINGS]:[]:[...process.env.PANDO_CLAUDE_MANAGED_SETTINGS?[process.env.PANDO_CLAUDE_MANAGED_SETTINGS]:[],"/etc/claude-code/managed-settings.json"],Zc.default.join(n,".claude","settings.json"),Zc.default.join(n,".claude","settings.local.json"),Zc.default.join(e,"settings.json")]}function I8(){return process.env.PANDO_CLAUDE_HOME_OVERRIDE||process.env.PANDO_HOME_OVERRIDE||process.env.HOME||ME.default.homedir()}function N8(){for(let t of xL()){let e=_L(t);if(e&&D8(e.disableAllHooks))return t}return null}function D8(t){return typeof t=="boolean"?t:typeof t!="string"?!1:/^(1|true|yes|on)$/i.test(t.trim())}function _L(t){try{let e=JSON.parse(SL.default.readFileSync(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function yL(t){return typeof t=="string"&&t.trim().length>0}var O8=new Set(["--add-dir","--agents","--agent","--allowed-tools","--allowedTools","--append-system-prompt","--betas","--disallowed-tools","--disallowedTools","--fallback-model","--input-format","--json-schema","--mcp-config","--model","--output-format","--permission-mode","--plugin-dir","--session-id","--setting-sources","--settings","--system-prompt","--tools"]),M8=new Set(["--add-dir","--agent","--agents","--allowed-tools","--allowedTools","--disallowed-tools","--disallowedTools","--mcp-config","--permission-mode","--plugin-dir","--setting-sources","--settings","--tools"]),F8=new Set(["--allow-dangerously-skip-permissions","--dangerously-load-development-channels","--dangerously-skip-permissions","--ide"]);function $8(t,e){let n=j8(t),r=z8(n.args);return r===null?{args:[...n.args,...e],removed:n.removed}:{args:[...n.args.slice(0,r),...e,...n.args.slice(r)],removed:n.removed}}function j8(t){let e=[],n=[];for(let r=0;r<t.length;r+=1){let s=t[r];if(!s.startsWith("--")){e.push(s);continue}let[o,i]=L8(s);if(F8.has(o)){n.push(o);continue}if(M8.has(o)){if(n.push(o),i!==void 0)continue;for(;r+1<t.length&&!t[r+1].startsWith("-");)r+=1;continue}e.push(s)}return{args:e,removed:n}}function L8(t){let e=t.indexOf("=");return e===-1?[t,void 0]:[t.slice(0,e),t.slice(e+1)]}function z8(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="--")return e;if(n.startsWith("--")){let[r,s]=n.split("=",2);s===void 0&&O8.has(r)&&(e+=1);continue}if(!n.startsWith("-"))return e}return null}function B8(t,e,n,r,s){let o={...process.env};H8(o);let i,a;if(t==="codex")a=dL(n),r?i=hL(e,{host:r.host,port:r.port,codexAutoCompactTokenLimit:R8}):i=[...e],i=[...i,...a.extraArgs];else{a=uL(n,{supportedFlags:q8(s)});let c=$8(e,a.extraArgs);i=c.args,c.removed.length>0&&An(`policy: stripped Claude flags that can bypass pand\u014D enforcement (${[...new Set(c.removed)].join(", ")})`),r&&(o.ANTHROPIC_BASE_URL=r.anthropicBaseUrl)}for(let[c,l]of Object.entries(a.env))o[c]=l;for(let c of a.notes)An(`policy: ${c}`);return{childArgs:i,childEnv:o}}var bL=new Map;function q8(t){let e=bL.get(t);if(e)return e;let n=(0,em.spawnSync)(t,["--help"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:5e3}),r=`${n.stdout||""}
1246
- ${n.stderr||""}`,s={bare:r.includes("--bare"),noChrome:r.includes("--no-chrome"),disableSlashCommands:r.includes("--disable-slash-commands")};return bL.set(t,s),s}function H8(t){for(let e of["PANDO_ALLOW_UNSUPERVISED","PANDO_DEBUG","PANDO_DEBUG_LAUNCH_ARGS","PANDO_GATEWAY_ANTHROPIC_BASE_URL","PANDO_GATEWAY_HOST","PANDO_GATEWAY_LOG_FILE","PANDO_GATEWAY_MEMORY","PANDO_GATEWAY_OPENAI_BASE_URL","PANDO_GATEWAY_PORT","PANDO_GATEWAY_STATE_DIR"])delete t[e]}async function W8(t){An(`${Jt} ${wa}`);for(let e of[3,2,1])An(`starting ${t} in ${e}...`),await new Promise(n=>setTimeout(n,1e3))}function U8(t,e,n){return new Promise(r=>{let s=(0,em.spawn)(t,e,{stdio:"inherit",env:n}),o=c=>{try{s.kill(c)}catch{}},i=()=>o("SIGINT"),a=()=>o("SIGTERM");process.on("SIGINT",i),process.on("SIGTERM",a),s.on("error",c=>{An(`failed to launch: ${c instanceof Error?c.message:String(c)}`),process.off("SIGINT",i),process.off("SIGTERM",a),r(127)}),s.on("exit",(c,l)=>{if(process.off("SIGINT",i),process.off("SIGTERM",a),l){r(128+({SIGINT:2,SIGTERM:15}[l]??0));return}r(c??0)})})}var Li=B(require("fs")),js=B(require("path")),$E=require("child_process");var FE=B(require("fs")),Ub=B(require("path"));Qt();function K8(){let t=process.env.PANDO_GATEWAY_LOG_FILE;return t?t.startsWith("~/")?Ub.default.join(ds(),t.slice(2)):t:Tu(process.env.PANDO_DEBUG)===!1?null:Ub.default.join(ds(),Af)}function Gr(t,e={}){let n=K8();if(n)try{let r=JSON.stringify({ts:new Date().toISOString(),event:`installer_${t}`,...e});FE.default.mkdirSync(Ub.default.dirname(n),{recursive:!0}),FE.default.appendFileSync(n,`${r}
1247
- `,"utf8")}catch{}}var Z8=["codex","claude"],G8=[".pando",".pando-ai",".pando-data"];function vr(t){return t?"\u2713":"\u2717"}function J8(){try{Li.default.readdirSync(sr()).length===0&&Li.default.rmdirSync(sr())}catch{}}function V8(t){let e=js.default.resolve(_a()),n=js.default.resolve(t);return n===e||n===js.default.parse(n).root||js.default.dirname(n)!==e?!1:G8.includes(js.default.basename(n))}function X8(t){if(!Li.default.existsSync(t))return{status:"not_present",target:t};if(!V8(t))return{status:"failed",target:t,message:"refusing to remove unexpected path"};try{return Li.default.rmSync(t,{recursive:!0,force:!0}),Li.default.existsSync(t)?{status:"failed",target:t,message:"path still exists after removal"}:{status:"removed",target:t}}catch(e){return{status:"failed",target:t,message:e instanceof Error?e.message:String(e)}}}function Q8(){let t=_a();return[Ms(),js.default.join(t,".pando-ai"),js.default.join(t,".pando-data")].map(X8)}function wL(t){try{return Li.default.realpathSync.native(t)}catch{return js.default.resolve(t)}}function Y8(t){let e=js.default.resolve(t);for(;;){let n=js.default.join(e,"package.json");try{if(JSON.parse(Li.default.readFileSync(n,"utf8"))?.name===Jt)return e}catch{}let r=js.default.dirname(e);if(r===e)return null;e=r}}function vL(){let t=process.env.npm_execpath;return t&&Li.default.existsSync(t)?{command:process.execPath,args:[t]}:{command:"npm",args:[]}}function e5(){let t=vL(),e=(0,$E.spawnSync)(t.command,[...t.args,"root","-g"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(e.status!==0)return null;let n=e.stdout.trim();return n||null}function t5(){let t=Y8(__dirname),e=e5();if(!t||!e)return{status:"not_global"};let n=wL(js.default.join(e,Jt)),r=wL(t);if(r!==n)return{status:"not_global"};let s=vL(),o=(0,$E.spawnSync)(s.command,[...s.args,"uninstall","-g",Jt],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return o.status===0?{status:"removed_global",packageRoot:r}:{status:"failed",message:(o.stderr||o.stdout||`exit ${o.status}`).trim()}}function Kb(){if(console.log(""),console.log(" pand\u014D uninstall"),console.log(""),zb()){let o=Bb("remove the privileged Pando security helper");if(!o.ok)return Gr("uninstall_blocked",{reason:"sudo_failed",message:o.error}),console.log(` ${vr(!1)} security: ${o.error}`),console.log(" Nothing has been changed yet."),console.log(""),1}Gr("uninstall_start",{});for(let o of Z8){let i=VF(o);switch(Gr("shim_uninstall",{tool:o,status:i.status,shimPath:i.shimPath}),i.status){case"removed":console.log(` ${vr(!0)} ${o}: removed shim at ${i.shimPath}`);break;case"not_present":console.log(` ${o}: no pand\u014D shim found`);break;case"failed":console.log(` ${vr(!1)} ${o}: could not remove shim \u2014 ${i.message}`);break}}let t=ZF();switch(Gr("self_shim_uninstall",{status:t.status,shimPath:t.shimPath}),t.status){case"removed":console.log(` ${vr(!0)} pando-ai: removed command shim at ${t.shimPath}`);break;case"not_present":console.log(" pando-ai: no pand\u014D command shim found");break;case"failed":console.log(` ${vr(!1)} pando-ai: could not remove command shim \u2014 ${t.message}`);break}for(let o of GF())switch(o.status){case"removed":console.log(` ${vr(!0)} pando-ai: removed current-terminal shim at ${o.shimPath}`);break;case"failed":console.log(` ${vr(!1)} pando-ai: could not remove current-terminal shim \u2014 ${o.message}`);break;case"not_present":break}J8();let e=r$();switch(Gr("path_deactivate",{status:e.status,target:e.target}),e.status){case"activated":console.log(` ${vr(!0)} PATH: removed managed pand\u014D block from ${e.target}`);break;case"already_present":console.log(" PATH: no managed pand\u014D block found");break;case"manual_required":console.log(` PATH: manual cleanup may be required. ${e.hint??""}`.trimEnd());break;case"failed":console.log(` ${vr(!1)} PATH: could not update ${e.target} \u2014 ${e.message}`);break}let n=c$();console.log(n?` ${vr(!0)} state: removed ${Fc()}`:` ${vr(!1)} state: could not remove ${Fc()}`);let r=t5();switch(r.status){case"removed_global":console.log(` ${vr(!0)} npm package: removed global ${Jt} package`);break;case"not_global":console.log(" npm package: no global package install detected");break;case"failed":console.log(` ${vr(!1)} npm package: could not remove global ${Jt} package \u2014 ${r.message}`);break}let s=PE();Gr("security_uninstall",{ok:s.ok,message:s.message}),console.log(s.ok?` ${vr(!0)} security: ${s.message}`:` ${vr(!1)} security: could not remove dedicated users \u2014 ${s.message}`);for(let o of Q8())switch(o.status){case"removed":console.log(` ${vr(!0)} data: removed ${o.target}`);break;case"not_present":console.log(` data: no ${o.target} found`);break;case"failed":console.log(` ${vr(!1)} data: could not remove ${o.target} \u2014 ${o.message}`);break}return console.log(""),s.ok?(console.log(" Done. pand\u014D has been removed."),0):(Gr("uninstall_incomplete",{reason:"security_teardown_failed"}),console.log(" Uninstall incomplete: the privileged security layer could not be removed."),console.log(` Re-run with root privileges to finish: sudo ${Jt} uninstall`),1)}var RL=B(require("path")),tm=["codex","claude"];function jE(){return new Date().toISOString()}function ls(t){return t?"\u2713":"\u2717"}function n5(t){return!t.realPath&&!t.shimPath?` ${t.tool.padEnd(7)} not installed`:t.proxied?` ${t.tool.padEnd(7)} ${ls(!0)} protected`:t.realPath?` ${t.tool.padEnd(7)} ${ls(!1)} unprotected (real binary present, shim not ahead on PATH)`:` ${t.tool.padEnd(7)} ${ls(!1)} shim present but real binary missing`}function Zb(t,e=process.env.PATH||""){let n=Kr(),r=XF(e);console.log(""),console.log(" pand\u014D \u2014 AI coding firewall"),console.log("");for(let s of t)console.log(n5(s));console.log(""),console.log(` PATH ~/.pando/bin ${r.present?r.first?"first \u2713":"present but not first \u2717":"missing \u2717"}`),console.log(` Policy native_tools=${n.nativeTools} other_mcp=${n.otherMcp.mode} default=${n.defaultAction}`),console.log(` source: ${WM()?Mc():"built-in defaults"}`),console.log(""),r.first||(console.log(" pand\u014D has configured future shells with this PATH entry:"),console.log(` ${fb()}`),console.log(""))}var kL=!1;function r5(){kL=!0}function nm(){kL&&(console.log(""),console.log(" Current terminal note:"),console.log(" New terminals will pick up pand\u014D automatically."),console.log(" This already-open terminal will not use pand\u014D for `codex`/`claude` until you either open a new terminal or run exactly:"),console.log(` ${fb()}`))}function Gb(t){let e=JF(t);switch(Gr("shim_install",{tool:t,status:e.status,shimPath:e.shimPath,realPath:e.realPath}),e.status){case"installed":case"updated":return console.log(` ${ls(!0)} ${t}: shim ${e.status} at ${e.shimPath}`),a$(t,e.realPath,jE()),!0;case"skipped_no_real_binary":return console.log(` ${t}: skipped (no real binary on PATH to supervise)`),!1;case"failed":return console.log(` ${ls(!1)} ${t}: install failed \u2014 ${e.message}`),!1}}function s5(){let t=KF();switch(Gr("self_shim_install",{status:t.status,shimPath:t.shimPath,currentPathShimPath:t.currentPathShimPath}),t.status){case"installed":case"updated":console.log(` ${ls(!0)} pando-ai: command shim ${t.status} at ${t.shimPath}`),t.currentPathShimPath&&console.log(` ${ls(!0)} pando-ai: current-terminal command shim ${t.currentPathShimStatus} at ${t.currentPathShimPath}`),rm();break;case"failed":console.log(` ${ls(!1)} pando-ai: could not install command shim \u2014 ${t.message}`);break}}function rm(){r5();let t=n$();switch(Gr("path_activate",{status:t.status,target:t.target}),t.status){case"activated":console.log(` ${ls(!0)} PATH: added ~/.pando/bin to ${t.target}`);break;case"already_present":console.log(` PATH: ~/.pando/bin already configured in ${t.target}`);break;case"manual_required":console.log(` ${ls(!1)} PATH: manual step required.`),t.hint&&console.log(` ${t.hint}`);break;case"failed":console.log(` ${ls(!1)} PATH: could not update startup file \u2014 ${t.message}`),console.log(` Add this yourself: ${fb()}`);break}}function o5(){let t=RL.default.join(_a(),".pando-data");console.log(" security: configuring privileged helper");let e=Qf({dataRoot:t,onProgress:n=>console.log(` security: ${n}`)});Gr("security_setup",{ok:e.ok,dataRoot:t,message:e.message}),e.ok?console.log(` ${ls(!0)} security: ${e.message}`):console.log(` ${ls(!1)} security: dedicated-user setup failed \u2014 ${e.message}`)}async function i5(t){let e=mb(),n=t.filter(s=>s.realPath&&!s.proxied&&!e.declined[s.tool]);if(n.length===0)return!1;let r=!1;if(n.length===tm.length){if(await Bf(" pand\u014D is an AI coding firewall. Replace `codex` and `claude` with pand\u014D-supervised launchers?"))for(let o of n)Gb(o.tool)&&(r=!0);else for(let o of n)Ck(o.tool,jE());return r&&rm(),r&&nm(),r}for(let s of n)await Bf(` \`${s.tool}\` is not protected by pand\u014D yet. Install the supervised launcher?`)?Gb(s.tool)&&(r=!0):Ck(s.tool,jE());return r&&rm(),r&&nm(),r}async function a5(){try{let t=await zu(Eu(),()=>{}),e=await fetch(`http://${t.host}:${t.port}/health`).then(n=>n.json());console.log(` gateway: ok (memory=${e.memory?"on":"off"})`),await t.close()}catch(t){console.log(` gateway: failed \u2014 ${t instanceof Error?t.message:String(t)}`)}}async function c5(t){switch(await l$(" What would you like to do?",["Install / repair launchers","Show / edit policy","Check gateway","Launch codex now","Launch claude now","Uninstall pand\u014D launchers","Quit"])){case 0:{let n=!1;for(let r of t)r.realPath&&Gb(r.tool)&&(n=!0);return n&&rm(),n&&nm(),{action:"continue",refreshStatus:!0}}case 1:return console.log(""),console.log(ek(Kr())),console.log(` Edit ${Mc()} to change the ruleset.`),{action:"continue",refreshStatus:!1};case 2:return await a5(),{action:"continue",refreshStatus:!1};case 3:return{action:"launch",tool:"codex"};case 4:return{action:"launch",tool:"claude"};case 5:return Kb(),{action:"uninstalled"};default:return{action:"quit"}}}async function EL(t={}){Gr("wizard_start",{force:!!t.force});let e=Bb("install/update the privileged Pando security helper");if(!e.ok){Gr("install_blocked",{reason:"sudo_failed",message:e.error}),console.log(` ${ls(!1)} security: ${e.error}`);return}s5(),o5();let n=process.env.PATH||"",r=tm.map(o=>Ra(o,n));if(Zb(r,n),t.force){let o=!1;for(let i of r)i.realPath&&Gb(i.tool)&&(o=!0);o&&rm(),o&&nm(),n=process.env.PATH||"",r=tm.map(i=>Ra(i,n)),Zb(r,n)}else await i5(r)&&(n=process.env.PATH||"",r=tm.map(i=>Ra(i,n)),Zb(r,n));let s=!1;for(;;){let o=await c5(r);if(o.action==="quit")break;if(o.action==="uninstalled"){s=!0;break}if(o.action==="launch"){console.log("");let i=await Wb(o.tool,[]);process.exit(i)}o.refreshStatus&&(n=process.env.PATH||"",r=tm.map(i=>Ra(i,n)),Zb(r,n))}console.log(""),s?console.log(" Done. pand\u014D launchers have been removed."):(nm(),console.log(` Done. Keep using \`codex\` and \`claude\` as usual \u2014 ${Jt} supervises each launch.`))}async function TL(t={}){await EL({force:t.force})}async function PL(t,e){let n=t.includes("--memory"),r=Eu({memoryEnabled:n||void 0}),s=a=>console.error(`[pando-gateway] ${a}`),o=await zu(r,s);s(`OpenAI base: ${o.openaiBaseUrl}`),s(`Anthropic base: ${o.anthropicBaseUrl}`),s("Press Ctrl-C to stop.");let i=async a=>{s(`received ${a}, shutting down`),await o.close(),process.exit(0)};process.once("SIGINT",()=>{i("SIGINT")}),process.once("SIGTERM",()=>{i("SIGTERM")}),await new Promise(()=>{})}dt();var l5=new Set(OE),u5="Reminder: raw shell is strongly discouraged for code search, navigation, references, and edits. Prefer pand\u014D AST/index tools first; use shell freely for tests, builds/compiles, package managers, git, generated or non-code files, unsupported languages, and anything pand\u014D itself does not support.";function d5(t){return l5.has(t)}Yu(!0);async function CL(){let t=await b5(),e=p5(t),n=typeof e.hook_event_name=="string"?e.hook_event_name:"",r=Kr();if(Rt("claude_hook.request",{actor:"pando.hook",channel:"claude_hook",hookEventName:n||"unknown",parsed:e.__pandoParseError!==!0,input:e,...e.__pandoParseError===!0?{rawInput:t}:{}}),x5(n||"unknown",e),n==="PreToolUse"){let o=Jb(e);if(o&&oo(o,r))return W("ClaudeHook","tool ALLOWED",{tool:o,event:n}),Gc({hookEventName:n,toolName:o,decision:"allow",blockedToolNames:[],reason:"Allowed by pand\u014D policy.",output:{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Allowed by pand\u014D policy."}}});let i=o??"unknown",a=Vb(i);return W("ClaudeHook","tool BLOCKED",{tool:i,event:n}),Gc({hookEventName:n,toolName:i,decision:"deny",blockedToolNames:[i],reason:a,output:{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:a}}})}if(n==="PostToolUse"||n==="PostToolUseFailure"){let o=Jb(e);if(!o||!oo(o,r)){let i=o??"unknown",a=Vb(i);return Gc(n==="PostToolUse"?{hookEventName:n,toolName:i,decision:"block",blockedToolNames:[i],reason:a,output:{decision:"block",reason:a,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:a,...m5(o,a)}}}:{hookEventName:n,toolName:i,decision:"steer",blockedToolNames:[i],reason:a,output:{hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:a}}})}om({hookEventName:n,toolName:o,decision:"allow",blockedToolNames:[],reason:"Allowed by pand\u014D policy.",output:null});return}if(n==="PostToolBatch"){let o=f5(e,r);if(o.length>0){let i=Vb(o.join(", "));return Gc({hookEventName:n,toolName:o.join(", "),decision:"block",blockedToolNames:o,reason:i,output:{continue:!1,decision:"block",reason:i,hookSpecificOutput:{hookEventName:"PostToolBatch",additionalContext:i}}})}om({hookEventName:n,toolName:null,decision:"allow",blockedToolNames:[],reason:"Allowed by pand\u014D policy.",output:null});return}if(n==="PermissionDenied"){let o=Jb(e);if(!o||!oo(o,r)){let i=o??"unknown",a=Vb(i);return Gc({hookEventName:n,toolName:i,decision:"retry",blockedToolNames:[i],reason:a,output:{hookSpecificOutput:{hookEventName:"PermissionDenied",retry:!0,additionalContext:a}}})}om({hookEventName:n,toolName:o,decision:"allow",blockedToolNames:[],reason:"Allowed by pand\u014D policy.",output:null});return}if(n==="SessionStart"||n==="PostCompact")return Gc({hookEventName:n,toolName:null,decision:"remind",blockedToolNames:[],reason:"Injected pand\u014D tool-selection reminder.",output:{hookSpecificOutput:{hookEventName:n,additionalContext:u5}}});let s=d5(n);om({hookEventName:n||"unknown",toolName:Jb(e),decision:"observe",blockedToolNames:[],reason:s?"Recorded (observe-only lifecycle event; not gated by pand\u014D policy).":"Recorded (event not registered by pand\u014D; captured for audit).",output:null})}function p5(t){try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{__pandoParseError:!0}}}function Jb(t){return typeof t.tool_name=="string"&&t.tool_name.trim()?t.tool_name:null}function f5(t,e){let n=g5(t);return[...new Set(n.filter(r=>!oo(r,e)))]}function Vb(t){return`pand\u014D firewall blocked off-policy Claude tool use/result: ${t}. Retry using pand\u014D MCP tools only.`}function m5(t,e){return t&&h5(t)?{updatedMCPToolOutput:e}:{updatedToolOutput:e}}function h5(t){return t.startsWith("mcp__")}function g5(t){return[...y5(t.tool_calls),...LE(t)]}function y5(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let r=n.tool_name;typeof r=="string"&&r.trim()&&e.push(r)}return e}function LE(t,e=0){if(e>6||!t||typeof t!="object")return[];if(Array.isArray(t))return t.flatMap(o=>LE(o,e+1));let n=t,r=typeof n.tool_name=="string"&&n.tool_name.trim()?[n.tool_name]:[],s=["tool_calls","tool_results","tool_responses","tool_uses","content","items"];return[...r,...s.flatMap(o=>LE(n[o],e+1))]}async function b5(){let t=[];for await(let e of process.stdin)t.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(t).toString("utf8")}function S5(t){process.stdout.write(`${JSON.stringify(t)}
1248
- `)}function Gc(t){om(t),S5(t.output)}function om(t){Rt("claude_hook.decision",{actor:t.blockedToolNames.length>0?"pando.firewall":"pando.hook",channel:"claude_hook",hookEventName:t.hookEventName,toolName:t.toolName,decision:t.decision,blockedToolNames:t.blockedToolNames,reason:t.reason,output:t.output})}function x5(t,e){let n=_5(t,e);for(let r=0;r<n.length;r+=1){let s=n[r];Rt("provider.transcript.item",{actor:s.actor,channel:"claude_hook",source:"claude_hook",hookEventName:t,itemIndex:r,itemType:s.itemType,body:s.body})}}function _5(t,e){switch(t){case"UserPromptSubmit":return sm(e,"prompt")?[{actor:"user",itemType:"user_prompt",body:{prompt:e.prompt}}]:[];case"UserPromptExpansion":return[{actor:"user",itemType:"user_prompt_expansion",body:Jc(e,["command","prompt","expanded_prompt","expansion"])}];case"MessageDisplay":return[{actor:"assistant",itemType:sm(e,"message_type")??sm(e,"type")??"message_display",body:e}];case"Stop":return sm(e,"last_assistant_message")?[{actor:"assistant",itemType:"last_assistant_message",body:{text:e.last_assistant_message,stop_hook_active:e.stop_hook_active??null}}]:[];case"StopFailure":return[{actor:"assistant",itemType:"stop_failure",body:Jc(e,["error","error_details","last_assistant_message"])}];case"SubagentStop":return sm(e,"last_assistant_message")?[{actor:"assistant",itemType:"subagent_last_assistant_message",body:Jc(e,["agent_id","agent_type","agent_transcript_path","last_assistant_message","stop_hook_active"])}]:[];case"PreToolUse":case"PermissionRequest":return[{actor:"assistant",itemType:"tool_call",body:Jc(e,["tool_name","tool_input"])}];case"PostToolUse":case"PostToolUseFailure":return[{actor:"tool",itemType:t==="PostToolUse"?"tool_result":"tool_error",body:Jc(e,["tool_name","tool_input","tool_response","error","error_details"])}];case"PostToolBatch":return[{actor:"tool",itemType:"tool_batch_result",body:Jc(e,["tool_calls","tool_results","tool_responses"])}];case"Elicitation":return[{actor:"tool",itemType:"elicitation_request",body:e}];case"ElicitationResult":return[{actor:"user",itemType:"elicitation_result",body:e}];case"Notification":return[{actor:"assistant",itemType:"notification",body:e}];case"TaskCreated":case"TaskCompleted":return[{actor:"assistant",itemType:t==="TaskCreated"?"task_created":"task_completed",body:Jc(e,["task_id","task_subject","task_description","teammate_name","team_name"])}];default:return[]}}function sm(t,e){let n=t[e];return typeof n=="string"&&n.trim()?n:null}function Jc(t,e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}Qt();dt();function w5(t,e){let n=t[0]==="serve-http"?"serve-http":"serve",r=t[1];return t.length>2&&(console.error(`Unexpected argument: ${t[2]}`),process.exit(1)),{command:n,projectPath:r?si.default.resolve(r):null,httpHost:e.httpHost,httpPort:e.httpPort,disableAuth:e.disableAuth}}var v5=new Set(["gateway","launch","security"]);function R5(t){let e={help:!1,version:!1,httpHost:"127.0.0.1",httpPort:5888,disableAuth:!1,positional:[],passthrough:[],subArgs:null},n=2;for(;n<t.length;n++){let r=t[n];if(e.positional.length===0&&!r.startsWith("-")&&v5.has(r)){e.positional.push(r),e.subArgs=t.slice(n+1);break}if(r==="--"){e.passthrough=t.slice(n+1);break}else if(r==="--help"||r==="-h")e.help=!0;else if(r==="--version"||r==="-v")e.version=!0;else if(r==="--disable-auth"||r==="--no-auth")e.disableAuth=!0;else if(r==="--host"){let s=t[++n];s||(console.error("--host requires a value"),process.exit(1)),e.httpHost=s}else if(r==="--port"){let s=t[++n],o=Number(s);(!Number.isInteger(o)||o<=0||o>65535)&&(console.error("--port requires a TCP port number"),process.exit(1)),e.httpPort=o}else r.startsWith("-")?(console.error(`Unknown option: ${r}`),process.exit(1)):e.positional.push(r)}return e}function k5(){console.error(`Usage: ${Jt} Install / update pand\u014D-supervised launchers
1245
+ `),e}function lL(){let t=S8(),e={};for(let n of OE)e[n]=[{hooks:[t]}];return{hooks:e,permissions:{deny:[...b8]}}}function S8(){return{type:"command",command:qF("claude-hook")}}zl();function uL(t,e={}){let n=[],r={ENABLE_CLAUDEAI_MCP_SERVERS:"false"},s=[];t.nativeTools==="deny"&&s.push("native tools denied by Claude hooks; Pando MCP explicitly allowed via --allowedTools"),s.push("Claude.ai MCP/connectors disabled (ENABLE_CLAUDEAI_MCP_SERVERS=false)");let o=e.supportedFlags;o?.disableSlashCommands&&s.push("Claude slash commands/skills left enabled (not disabled)"),o?.bare&&s.push("Claude bare mode left OFF (preserves subscription/OAuth auth and hooks)"),o?.noChrome&&(n.push("--no-chrome"),s.push("Claude Chrome/browser tool surface disabled"));let i=yE(),a=_8(t);switch(oL(i,a),n.push("--mcp-config",sL(i,a),"--strict-mcp-config"),s.push(`pand\u014D MCP dynamically injected via --mcp-config/--strict-mcp-config, root-scoped to ${i}; on-disk Claude config left untouched`),n.push(`--allowedTools=${x8().join(",")}`),s.push('snapshots on \u2014 every edit is checkpointed and undoable. In chat, type "pando, undo" to revert the last change, or "pando, history" to see every checkpoint and pick one to roll back to.'),(e.hooksEnabled??!0)&&(cL(),n.push("--settings",aL()),s.push("Claude hooks installed for tool call/result enforcement and transcript audit")),t.otherMcp.mode){case"deny_all":s.push("other MCP servers blocked (strict: pand\u014D only)");break;case"allow_list":t.otherMcp.tools.length>0&&n.push(`--allowedTools=${t.otherMcp.tools.join(",")}`),s.push(`other MCP restricted to allow-list (${t.otherMcp.servers.join(", ")||"none"}); strict config in effect`);break;case"deny_list":if(t.otherMcp.tools.length>0||t.otherMcp.servers.length>0){let c=[...t.otherMcp.tools,...t.otherMcp.servers.map(l=>`mcp__${l}`)];n.push(`--disallowedTools=${c.join(",")}`),s.push(`other MCP deny-list removed from Claude context (${c.join(", ")})`)}break;default:s.push("other MCP servers preserved in strict generated config");break}return{extraArgs:n,env:r,notes:s}}function x8(){let[t,e]=IE;return[...P_("core").map(n=>`mcp__${t}__${n}`),...P_("workspace").map(n=>`mcp__${e}__${n}`)]}function _8(t){switch(t.otherMcp.mode){case"deny_all":return[];case"allow_list":return t.otherMcp.servers;default:return null}}function dL(t){let e=[],n={},r=[];t.nativeTools==="deny"&&(e.push("-c",'sandbox_mode="read-only"'),e.push("-c",'web_search="disabled"'),r.push("native tools restricted (read-only sandbox, web search disabled, best-effort); tool traffic is enforced at the gateway"));let s=yE();switch(e.push(...iL(s)),r.push(`pand\u014D MCP (${IE.join(", ")}) dynamically injected via Codex -c overrides, root-scoped to ${s}; user MCP files are not modified`),r.push('snapshots on \u2014 every edit is checkpointed and undoable. In chat, type "pando, undo" to revert the last change, or "pando, history" to see every checkpoint and pick one to roll back to.'),t.otherMcp.mode){case"deny_all":case"allow_list":case"deny_list":r.push(`other MCP policy "${t.otherMcp.mode}" is best-effort for Codex (no strict-MCP flag); enforced at the gateway, not via config`);break;default:r.push("other MCP servers allowed");break}return{extraArgs:e,env:n,notes:r}}var pL=new Set(["-c","--config","--enable","--disable","--remote","--remote-auth-token-env","-i","--image","-m","--model","--local-provider","-p","--profile","-s","--sandbox","-a","--ask-for-approval","-C","--cd","--add-dir"]);function fL(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="--")return null;if(!w8(n)){if(pL.has(n)){e+=1;continue}if(!n.startsWith("-"))return{name:n,index:e}}}return null}function w8(t){let[e,n]=t.split("=",2);return n!==void 0&&pL.has(e)}var mL="pando-proxy";function v8(t){let e=`model_providers.${mL}`;return["-c",`model_provider="${mL}"`,"-c",`model_auto_compact_token_limit=${t.codexAutoCompactTokenLimit}`,"-c",`${e}.name="Pando Firewall"`,"-c",`${e}.base_url="http://${t.host}:${t.port}/v1"`,"-c",`${e}.wire_api="responses"`,"-c",`${e}.transport="responses_http"`,"-c",`${e}.requires_openai_auth=true`]}function hL(t,e){let n=v8(e),r=fL(t);return r?[...t.slice(0,r.index+1),...n,...t.slice(r.index+1)]:[...n,...t]}dt();Qt();Yc();var R8=28e4,gL="x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles";function An(t){console.error(`[pand\u014D] ${t}`)}function k8(t){let e=ot(t);process.env.PANDO_LOG_DIR||(process.env.PANDO_LOG_DIR=e),process.env.PANDO_GATEWAY_LOG_FILE||(process.env.PANDO_GATEWAY_LOG_FILE=Zc.default.join(e,"gateway-debug.jsonl"))}function E8(){return process.env.PANDO_DATA_DIR||Zc.default.join(process.env.PANDO_HOME_OVERRIDE||ME.default.homedir(),".pando-data")}function T8(t){if(process.platform!=="darwin")return!1;let e=EE(t);return e?(An(`macOS privacy warning: project root is inside ~/${e.label}. macOS may block the privileged helper even after Unix ACL setup succeeds.`),!0):!1}function P8(){An("opening macOS Full Disk Access settings so you can grant access to the Pando helper/runtime.");try{(0,em.spawnSync)("open",[gL],{stdio:"ignore"})}catch{An(`could not open Full Disk Access settings automatically: ${gL}`)}}function C8(t,e){let n=AE(),r=E8(),s=Jj(r,e),o=T8(e);if(n.daemonAvailable&&s)return!0;o&&P8();let i=[n.daemonAvailable?null:`helper daemon socket missing at ${n.socketPath}`,s?null:"repo ACLs not configured"].filter(Boolean).join("; ");An(`configuring Pando security for ${t}: ${i}`);let a=Qf({dataRoot:r,realRoot:e,onProgress:c=>An(`security setup: ${c}`)});return a.ok?(An(`security setup complete: ${a.message}`),!0):(An(`refusing to launch ${t}: security setup failed: ${a.message}`),!1)}async function Wb(t,e){let n=process.cwd();k8(n);let r=Ca();Rt("session.start",{actor:"pando.launcher",channel:"session",tool:t,projectRoot:n,originalArgs:e});let s=$o(n);if(s)return An(`refusing to launch ${t}: project root '${n}' is not allowed (matches protected path '${s}'). Start ${t} from a real project folder inside your home directory, not directly from /Users, your home directory, a system directory, or a credential/config directory.`),Rt("session.end",{actor:"pando.launcher",channel:"session",tool:t,sessionId:r,exitCode:78,reason:"forbidden_project_root",projectRoot:n,forbiddenRoot:s}),78;let o=FF(t);if(!o)return An(`could not find the real \`${t}\` binary. Is it installed and on PATH (outside ~/.pando/bin)?`),Rt("session.end",{actor:"pando.launcher",channel:"session",tool:t,sessionId:r,exitCode:127,reason:"real_binary_not_found"}),127;let i=Kr();if(t==="claude"){let y=D8();if(y)return An(`refusing to launch claude: Claude hooks are disabled by ${y}. pand\u014D requires hooks for subscription-mode tool/result enforcement.`),Rt("session.end",{actor:"pando.launcher",channel:"session",tool:t,sessionId:r,exitCode:78,reason:"claude_hooks_disabled",disabledBy:y}),78}if(!C8(t,n))return W("Launch","security setup failed",{tool:t,projectRoot:n}),Rt("session.end",{actor:"pando.launcher",channel:"session",tool:t,sessionId:r,exitCode:78,reason:"security_setup_failed"}),78;let a=Eu({memoryEnabled:i.memory}),c=i.proxy[t]==="enforce",l=t==="claude"?A8():!1,u=c&&(t==="codex"||l),d=/^(1|true|yes)$/i.test(process.env.PANDO_ALLOW_UNSUPERVISED||""),p=null;if(u)try{p=await zu(a,y=>{W("Gateway","runtime log",{message:y})})}catch(y){let b=y instanceof Error?y.message:String(y);if(!d)return An(`refusing to launch ${t}: the pand\u014D gateway could not start (${b}). Fix the problem, or set PANDO_ALLOW_UNSUPERVISED=1 to run ${t} without wire interception (NOT recommended \u2014 the firewall will be off).`),Rt("session.end",{actor:"pando.launcher",channel:"session",tool:t,sessionId:r,exitCode:78,reason:"gateway_start_failed",error:b}),78;An(`gateway failed to start (${b}); PANDO_ALLOW_UNSUPERVISED is set, so launching ${t} WITHOUT wire interception.`)}let f=t==="claude"&&!p;c?f&&!l?An("Claude gateway auth not configured; using Claude hooks-only fallback for tool call/result firewalling."):f&&An("Claude gateway unavailable; using Claude hooks-only fallback for tool call/result firewalling."):An(`${t} provider proxy disabled by policy; ${t==="claude"?"using Claude hooks only":"Codex provider-bound gateway enforcement is off"}.`);let{childArgs:m,childEnv:h}=q8(t,e,i,p,o);/^(1|true|yes)$/i.test(process.env.PANDO_DEBUG_LAUNCH_ARGS||"")&&(An(`debug launch args: ${JSON.stringify(m)}`),An(`debug launch env: ANTHROPIC_BASE_URL=${h.ANTHROPIC_BASE_URL?"set":"unset"} PANDO_ALLOW_UNSUPERVISED=${h.PANDO_ALLOW_UNSUPERVISED?"set":"unset"} PANDO_GATEWAY_MEMORY=${h.PANDO_GATEWAY_MEMORY?"set":"unset"}`)),An(`supervising ${t}: gateway=${p?"on":"off"} ${t==="claude"?"hooks=on ":""}pando_mcp=on policy native_tools=${i.nativeTools} other_mcp=${i.otherMcp.mode}`),W("Launch","supervised run start",{sessionId:r,tool:t,gateway:p?"on":"off",memory:i.memory,nativeTools:i.nativeTools,otherMcp:i.otherMcp.mode}),await U8(t);let g=await K8(o,m,h);return p&&await p.close().catch(()=>{}),W("Launch","supervised run end",{tool:t,exitCode:g}),Rt("session.end",{actor:"pando.launcher",channel:"session",tool:t,sessionId:r,exitCode:g}),g}function A8(){return!!(process.env.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||I8())}function I8(){for(let t of xL()){let e=_L(t);if(!e)continue;if(typeof e.apiKeyHelper=="string"&&e.apiKeyHelper.trim())return!0;let n=e.env;if(n&&typeof n=="object"&&!Array.isArray(n)&&(yL(n.ANTHROPIC_API_KEY)||yL(n.ANTHROPIC_AUTH_TOKEN)))return!0}return!1}function xL(){let t=N8(),e=process.env.CLAUDE_CONFIG_DIR||Zc.default.join(t,".claude"),n=process.cwd();return[...process.platform==="darwin"?[...process.env.PANDO_CLAUDE_MANAGED_SETTINGS?[process.env.PANDO_CLAUDE_MANAGED_SETTINGS]:[],"/Library/Application Support/ClaudeCode/managed-settings.json"]:process.platform==="win32"?process.env.PANDO_CLAUDE_MANAGED_SETTINGS?[process.env.PANDO_CLAUDE_MANAGED_SETTINGS]:[]:[...process.env.PANDO_CLAUDE_MANAGED_SETTINGS?[process.env.PANDO_CLAUDE_MANAGED_SETTINGS]:[],"/etc/claude-code/managed-settings.json"],Zc.default.join(n,".claude","settings.json"),Zc.default.join(n,".claude","settings.local.json"),Zc.default.join(e,"settings.json")]}function N8(){return process.env.PANDO_CLAUDE_HOME_OVERRIDE||process.env.PANDO_HOME_OVERRIDE||process.env.HOME||ME.default.homedir()}function D8(){for(let t of xL()){let e=_L(t);if(e&&O8(e.disableAllHooks))return t}return null}function O8(t){return typeof t=="boolean"?t:typeof t!="string"?!1:/^(1|true|yes|on)$/i.test(t.trim())}function _L(t){try{let e=JSON.parse(SL.default.readFileSync(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function yL(t){return typeof t=="string"&&t.trim().length>0}var M8=new Set(["--add-dir","--agents","--agent","--allowed-tools","--allowedTools","--append-system-prompt","--betas","--disallowed-tools","--disallowedTools","--fallback-model","--input-format","--json-schema","--mcp-config","--model","--output-format","--permission-mode","--plugin-dir","--session-id","--setting-sources","--settings","--system-prompt","--tools"]),F8=new Set(["--add-dir","--agent","--agents","--allowed-tools","--allowedTools","--disallowed-tools","--disallowedTools","--mcp-config","--permission-mode","--plugin-dir","--setting-sources","--settings","--tools"]),$8=new Set(["--allow-dangerously-skip-permissions","--dangerously-load-development-channels","--dangerously-skip-permissions","--ide"]);function j8(t,e){let n=L8(t),r=B8(n.args);return r===null?{args:[...n.args,...e],removed:n.removed}:{args:[...n.args.slice(0,r),...e,...n.args.slice(r)],removed:n.removed}}function L8(t){let e=[],n=[];for(let r=0;r<t.length;r+=1){let s=t[r];if(!s.startsWith("--")){e.push(s);continue}let[o,i]=z8(s);if($8.has(o)){n.push(o);continue}if(F8.has(o)){if(n.push(o),i!==void 0)continue;for(;r+1<t.length&&!t[r+1].startsWith("-");)r+=1;continue}e.push(s)}return{args:e,removed:n}}function z8(t){let e=t.indexOf("=");return e===-1?[t,void 0]:[t.slice(0,e),t.slice(e+1)]}function B8(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="--")return e;if(n.startsWith("--")){let[r,s]=n.split("=",2);s===void 0&&M8.has(r)&&(e+=1);continue}if(!n.startsWith("-"))return e}return null}function q8(t,e,n,r,s){let o={...process.env};W8(o);let i,a;if(t==="codex")a=dL(n),r?i=hL(e,{host:r.host,port:r.port,codexAutoCompactTokenLimit:R8}):i=[...e],i=[...i,...a.extraArgs];else{a=uL(n,{supportedFlags:H8(s)});let c=j8(e,a.extraArgs);i=c.args,c.removed.length>0&&An(`policy: stripped Claude flags that can bypass pand\u014D enforcement (${[...new Set(c.removed)].join(", ")})`),r&&(o.ANTHROPIC_BASE_URL=r.anthropicBaseUrl)}for(let[c,l]of Object.entries(a.env))o[c]=l;for(let c of a.notes)An(`policy: ${c}`);return{childArgs:i,childEnv:o}}var bL=new Map;function H8(t){let e=bL.get(t);if(e)return e;let n=(0,em.spawnSync)(t,["--help"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:5e3}),r=`${n.stdout||""}
1246
+ ${n.stderr||""}`,s={bare:r.includes("--bare"),noChrome:r.includes("--no-chrome"),disableSlashCommands:r.includes("--disable-slash-commands")};return bL.set(t,s),s}function W8(t){for(let e of["PANDO_ALLOW_UNSUPERVISED","PANDO_DEBUG","PANDO_DEBUG_LAUNCH_ARGS","PANDO_GATEWAY_ANTHROPIC_BASE_URL","PANDO_GATEWAY_HOST","PANDO_GATEWAY_LOG_FILE","PANDO_GATEWAY_MEMORY","PANDO_GATEWAY_OPENAI_BASE_URL","PANDO_GATEWAY_PORT","PANDO_GATEWAY_STATE_DIR"])delete t[e]}async function U8(t){An(`${Jt} ${wa}`);for(let e of[3,2,1])An(`starting ${t} in ${e}...`),await new Promise(n=>setTimeout(n,1e3))}function K8(t,e,n){return new Promise(r=>{let s=(0,em.spawn)(t,e,{stdio:"inherit",env:n}),o=c=>{try{s.kill(c)}catch{}},i=()=>o("SIGINT"),a=()=>o("SIGTERM");process.on("SIGINT",i),process.on("SIGTERM",a),s.on("error",c=>{An(`failed to launch: ${c instanceof Error?c.message:String(c)}`),process.off("SIGINT",i),process.off("SIGTERM",a),r(127)}),s.on("exit",(c,l)=>{if(process.off("SIGINT",i),process.off("SIGTERM",a),l){r(128+({SIGINT:2,SIGTERM:15}[l]??0));return}r(c??0)})})}var Li=B(require("fs")),js=B(require("path")),$E=require("child_process");var FE=B(require("fs")),Ub=B(require("path"));Qt();function Z8(){let t=process.env.PANDO_GATEWAY_LOG_FILE;return t?t.startsWith("~/")?Ub.default.join(ds(),t.slice(2)):t:Tu(process.env.PANDO_DEBUG)===!1?null:Ub.default.join(ds(),Af)}function Gr(t,e={}){let n=Z8();if(n)try{let r=JSON.stringify({ts:new Date().toISOString(),event:`installer_${t}`,...e});FE.default.mkdirSync(Ub.default.dirname(n),{recursive:!0}),FE.default.appendFileSync(n,`${r}
1247
+ `,"utf8")}catch{}}var G8=["codex","claude"],J8=[".pando",".pando-ai",".pando-data"];function vr(t){return t?"\u2713":"\u2717"}function V8(){try{Li.default.readdirSync(sr()).length===0&&Li.default.rmdirSync(sr())}catch{}}function X8(t){let e=js.default.resolve(_a()),n=js.default.resolve(t);return n===e||n===js.default.parse(n).root||js.default.dirname(n)!==e?!1:J8.includes(js.default.basename(n))}function Q8(t){if(!Li.default.existsSync(t))return{status:"not_present",target:t};if(!X8(t))return{status:"failed",target:t,message:"refusing to remove unexpected path"};try{return Li.default.rmSync(t,{recursive:!0,force:!0}),Li.default.existsSync(t)?{status:"failed",target:t,message:"path still exists after removal"}:{status:"removed",target:t}}catch(e){return{status:"failed",target:t,message:e instanceof Error?e.message:String(e)}}}function Y8(){let t=_a();return[Ms(),js.default.join(t,".pando-ai"),js.default.join(t,".pando-data")].map(Q8)}function wL(t){try{return Li.default.realpathSync.native(t)}catch{return js.default.resolve(t)}}function e5(t){let e=js.default.resolve(t);for(;;){let n=js.default.join(e,"package.json");try{if(JSON.parse(Li.default.readFileSync(n,"utf8"))?.name===Jt)return e}catch{}let r=js.default.dirname(e);if(r===e)return null;e=r}}function vL(){let t=process.env.npm_execpath;return t&&Li.default.existsSync(t)?{command:process.execPath,args:[t]}:{command:"npm",args:[]}}function t5(){let t=vL(),e=(0,$E.spawnSync)(t.command,[...t.args,"root","-g"],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(e.status!==0)return null;let n=e.stdout.trim();return n||null}function n5(){let t=e5(__dirname),e=t5();if(!t||!e)return{status:"not_global"};let n=wL(js.default.join(e,Jt)),r=wL(t);if(r!==n)return{status:"not_global"};let s=vL(),o=(0,$E.spawnSync)(s.command,[...s.args,"uninstall","-g",Jt],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return o.status===0?{status:"removed_global",packageRoot:r}:{status:"failed",message:(o.stderr||o.stdout||`exit ${o.status}`).trim()}}function Kb(){if(console.log(""),console.log(" pand\u014D uninstall"),console.log(""),zb()){let o=Bb("remove the privileged Pando security helper");if(!o.ok)return Gr("uninstall_blocked",{reason:"sudo_failed",message:o.error}),console.log(` ${vr(!1)} security: ${o.error}`),console.log(" Nothing has been changed yet."),console.log(""),1}Gr("uninstall_start",{});for(let o of G8){let i=VF(o);switch(Gr("shim_uninstall",{tool:o,status:i.status,shimPath:i.shimPath}),i.status){case"removed":console.log(` ${vr(!0)} ${o}: removed shim at ${i.shimPath}`);break;case"not_present":console.log(` ${o}: no pand\u014D shim found`);break;case"failed":console.log(` ${vr(!1)} ${o}: could not remove shim \u2014 ${i.message}`);break}}let t=ZF();switch(Gr("self_shim_uninstall",{status:t.status,shimPath:t.shimPath}),t.status){case"removed":console.log(` ${vr(!0)} pando-ai: removed command shim at ${t.shimPath}`);break;case"not_present":console.log(" pando-ai: no pand\u014D command shim found");break;case"failed":console.log(` ${vr(!1)} pando-ai: could not remove command shim \u2014 ${t.message}`);break}for(let o of GF())switch(o.status){case"removed":console.log(` ${vr(!0)} pando-ai: removed current-terminal shim at ${o.shimPath}`);break;case"failed":console.log(` ${vr(!1)} pando-ai: could not remove current-terminal shim \u2014 ${o.message}`);break;case"not_present":break}V8();let e=r$();switch(Gr("path_deactivate",{status:e.status,target:e.target}),e.status){case"activated":console.log(` ${vr(!0)} PATH: removed managed pand\u014D block from ${e.target}`);break;case"already_present":console.log(" PATH: no managed pand\u014D block found");break;case"manual_required":console.log(` PATH: manual cleanup may be required. ${e.hint??""}`.trimEnd());break;case"failed":console.log(` ${vr(!1)} PATH: could not update ${e.target} \u2014 ${e.message}`);break}let n=c$();console.log(n?` ${vr(!0)} state: removed ${Fc()}`:` ${vr(!1)} state: could not remove ${Fc()}`);let r=n5();switch(r.status){case"removed_global":console.log(` ${vr(!0)} npm package: removed global ${Jt} package`);break;case"not_global":console.log(" npm package: no global package install detected");break;case"failed":console.log(` ${vr(!1)} npm package: could not remove global ${Jt} package \u2014 ${r.message}`);break}let s=PE();Gr("security_uninstall",{ok:s.ok,message:s.message}),console.log(s.ok?` ${vr(!0)} security: ${s.message}`:` ${vr(!1)} security: could not remove dedicated users \u2014 ${s.message}`);for(let o of Y8())switch(o.status){case"removed":console.log(` ${vr(!0)} data: removed ${o.target}`);break;case"not_present":console.log(` data: no ${o.target} found`);break;case"failed":console.log(` ${vr(!1)} data: could not remove ${o.target} \u2014 ${o.message}`);break}return console.log(""),s.ok?(console.log(" Done. pand\u014D has been removed."),0):(Gr("uninstall_incomplete",{reason:"security_teardown_failed"}),console.log(" Uninstall incomplete: the privileged security layer could not be removed."),console.log(` Re-run with root privileges to finish: sudo ${Jt} uninstall`),1)}var RL=B(require("path")),tm=["codex","claude"];function jE(){return new Date().toISOString()}function ls(t){return t?"\u2713":"\u2717"}function r5(t){return!t.realPath&&!t.shimPath?` ${t.tool.padEnd(7)} not installed`:t.proxied?` ${t.tool.padEnd(7)} ${ls(!0)} protected`:t.realPath?` ${t.tool.padEnd(7)} ${ls(!1)} unprotected (real binary present, shim not ahead on PATH)`:` ${t.tool.padEnd(7)} ${ls(!1)} shim present but real binary missing`}function Zb(t,e=process.env.PATH||""){let n=Kr(),r=XF(e);console.log(""),console.log(" pand\u014D \u2014 AI coding firewall"),console.log("");for(let s of t)console.log(r5(s));console.log(""),console.log(` PATH ~/.pando/bin ${r.present?r.first?"first \u2713":"present but not first \u2717":"missing \u2717"}`),console.log(` Policy native_tools=${n.nativeTools} other_mcp=${n.otherMcp.mode} default=${n.defaultAction}`),console.log(` source: ${WM()?Mc():"built-in defaults"}`),console.log(""),r.first||(console.log(" pand\u014D has configured future shells with this PATH entry:"),console.log(` ${fb()}`),console.log(""))}var kL=!1;function s5(){kL=!0}function nm(){kL&&(console.log(""),console.log(" Current terminal note:"),console.log(" New terminals will pick up pand\u014D automatically."),console.log(" This already-open terminal will not use pand\u014D for `codex`/`claude` until you either open a new terminal or run exactly:"),console.log(` ${fb()}`))}function Gb(t){let e=JF(t);switch(Gr("shim_install",{tool:t,status:e.status,shimPath:e.shimPath,realPath:e.realPath}),e.status){case"installed":case"updated":return console.log(` ${ls(!0)} ${t}: shim ${e.status} at ${e.shimPath}`),a$(t,e.realPath,jE()),!0;case"skipped_no_real_binary":return console.log(` ${t}: skipped (no real binary on PATH to supervise)`),!1;case"failed":return console.log(` ${ls(!1)} ${t}: install failed \u2014 ${e.message}`),!1}}function o5(){let t=KF();switch(Gr("self_shim_install",{status:t.status,shimPath:t.shimPath,currentPathShimPath:t.currentPathShimPath}),t.status){case"installed":case"updated":console.log(` ${ls(!0)} pando-ai: command shim ${t.status} at ${t.shimPath}`),t.currentPathShimPath&&console.log(` ${ls(!0)} pando-ai: current-terminal command shim ${t.currentPathShimStatus} at ${t.currentPathShimPath}`),rm();break;case"failed":console.log(` ${ls(!1)} pando-ai: could not install command shim \u2014 ${t.message}`);break}}function rm(){s5();let t=n$();switch(Gr("path_activate",{status:t.status,target:t.target}),t.status){case"activated":console.log(` ${ls(!0)} PATH: added ~/.pando/bin to ${t.target}`);break;case"already_present":console.log(` PATH: ~/.pando/bin already configured in ${t.target}`);break;case"manual_required":console.log(` ${ls(!1)} PATH: manual step required.`),t.hint&&console.log(` ${t.hint}`);break;case"failed":console.log(` ${ls(!1)} PATH: could not update startup file \u2014 ${t.message}`),console.log(` Add this yourself: ${fb()}`);break}}function i5(){let t=RL.default.join(_a(),".pando-data");console.log(" security: configuring privileged helper");let e=Qf({dataRoot:t,onProgress:n=>console.log(` security: ${n}`)});Gr("security_setup",{ok:e.ok,dataRoot:t,message:e.message}),e.ok?console.log(` ${ls(!0)} security: ${e.message}`):console.log(` ${ls(!1)} security: dedicated-user setup failed \u2014 ${e.message}`)}async function a5(t){let e=mb(),n=t.filter(s=>s.realPath&&!s.proxied&&!e.declined[s.tool]);if(n.length===0)return!1;let r=!1;if(n.length===tm.length){if(await Bf(" pand\u014D is an AI coding firewall. Replace `codex` and `claude` with pand\u014D-supervised launchers?"))for(let o of n)Gb(o.tool)&&(r=!0);else for(let o of n)Ck(o.tool,jE());return r&&rm(),r&&nm(),r}for(let s of n)await Bf(` \`${s.tool}\` is not protected by pand\u014D yet. Install the supervised launcher?`)?Gb(s.tool)&&(r=!0):Ck(s.tool,jE());return r&&rm(),r&&nm(),r}async function c5(){try{let t=await zu(Eu(),()=>{}),e=await fetch(`http://${t.host}:${t.port}/health`).then(n=>n.json());console.log(` gateway: ok (memory=${e.memory?"on":"off"})`),await t.close()}catch(t){console.log(` gateway: failed \u2014 ${t instanceof Error?t.message:String(t)}`)}}async function l5(t){switch(await l$(" What would you like to do?",["Install / repair launchers","Show / edit policy","Check gateway","Launch codex now","Launch claude now","Uninstall pand\u014D launchers","Quit"])){case 0:{let n=!1;for(let r of t)r.realPath&&Gb(r.tool)&&(n=!0);return n&&rm(),n&&nm(),{action:"continue",refreshStatus:!0}}case 1:return console.log(""),console.log(ek(Kr())),console.log(` Edit ${Mc()} to change the ruleset.`),{action:"continue",refreshStatus:!1};case 2:return await c5(),{action:"continue",refreshStatus:!1};case 3:return{action:"launch",tool:"codex"};case 4:return{action:"launch",tool:"claude"};case 5:return Kb(),{action:"uninstalled"};default:return{action:"quit"}}}async function EL(t={}){Gr("wizard_start",{force:!!t.force});let e=Bb("install/update the privileged Pando security helper");if(!e.ok){Gr("install_blocked",{reason:"sudo_failed",message:e.error}),console.log(` ${ls(!1)} security: ${e.error}`);return}o5(),i5();let n=process.env.PATH||"",r=tm.map(o=>Ra(o,n));if(Zb(r,n),t.force){let o=!1;for(let i of r)i.realPath&&Gb(i.tool)&&(o=!0);o&&rm(),o&&nm(),n=process.env.PATH||"",r=tm.map(i=>Ra(i,n)),Zb(r,n)}else await a5(r)&&(n=process.env.PATH||"",r=tm.map(i=>Ra(i,n)),Zb(r,n));let s=!1;for(;;){let o=await l5(r);if(o.action==="quit")break;if(o.action==="uninstalled"){s=!0;break}if(o.action==="launch"){console.log("");let i=await Wb(o.tool,[]);process.exit(i)}o.refreshStatus&&(n=process.env.PATH||"",r=tm.map(i=>Ra(i,n)),Zb(r,n))}console.log(""),s?console.log(" Done. pand\u014D launchers have been removed."):(nm(),console.log(` Done. Keep using \`codex\` and \`claude\` as usual \u2014 ${Jt} supervises each launch.`))}async function TL(t={}){await EL({force:t.force})}async function PL(t,e){let n=t.includes("--memory"),r=Eu({memoryEnabled:n||void 0}),s=a=>console.error(`[pando-gateway] ${a}`),o=await zu(r,s);s(`OpenAI base: ${o.openaiBaseUrl}`),s(`Anthropic base: ${o.anthropicBaseUrl}`),s("Press Ctrl-C to stop.");let i=async a=>{s(`received ${a}, shutting down`),await o.close(),process.exit(0)};process.once("SIGINT",()=>{i("SIGINT")}),process.once("SIGTERM",()=>{i("SIGTERM")}),await new Promise(()=>{})}dt();var u5=new Set(OE),d5="Reminder: raw shell is strongly discouraged for code search, navigation, references, and edits. Prefer pand\u014D AST/index tools first; use shell freely for tests, builds/compiles, package managers, git, generated or non-code files, unsupported languages, and anything pand\u014D itself does not support.";function p5(t){return u5.has(t)}Yu(!0);async function CL(){let t=await S5(),e=f5(t),n=typeof e.hook_event_name=="string"?e.hook_event_name:"",r=Kr();if(Rt("claude_hook.request",{actor:"pando.hook",channel:"claude_hook",hookEventName:n||"unknown",parsed:e.__pandoParseError!==!0,input:e,...e.__pandoParseError===!0?{rawInput:t}:{}}),_5(n||"unknown",e),n==="PreToolUse"){let o=Jb(e);if(o&&oo(o,r))return W("ClaudeHook","tool ALLOWED",{tool:o,event:n}),Gc({hookEventName:n,toolName:o,decision:"allow",blockedToolNames:[],reason:"Allowed by pand\u014D policy.",output:{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Allowed by pand\u014D policy."}}});let i=o??"unknown",a=Vb(i);return W("ClaudeHook","tool BLOCKED",{tool:i,event:n}),Gc({hookEventName:n,toolName:i,decision:"deny",blockedToolNames:[i],reason:a,output:{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:a}}})}if(n==="PostToolUse"||n==="PostToolUseFailure"){let o=Jb(e);if(!o||!oo(o,r)){let i=o??"unknown",a=Vb(i);return Gc(n==="PostToolUse"?{hookEventName:n,toolName:i,decision:"block",blockedToolNames:[i],reason:a,output:{decision:"block",reason:a,hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:a,...h5(o,a)}}}:{hookEventName:n,toolName:i,decision:"steer",blockedToolNames:[i],reason:a,output:{hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:a}}})}om({hookEventName:n,toolName:o,decision:"allow",blockedToolNames:[],reason:"Allowed by pand\u014D policy.",output:null});return}if(n==="PostToolBatch"){let o=m5(e,r);if(o.length>0){let i=Vb(o.join(", "));return Gc({hookEventName:n,toolName:o.join(", "),decision:"block",blockedToolNames:o,reason:i,output:{continue:!1,decision:"block",reason:i,hookSpecificOutput:{hookEventName:"PostToolBatch",additionalContext:i}}})}om({hookEventName:n,toolName:null,decision:"allow",blockedToolNames:[],reason:"Allowed by pand\u014D policy.",output:null});return}if(n==="PermissionDenied"){let o=Jb(e);if(!o||!oo(o,r)){let i=o??"unknown",a=Vb(i);return Gc({hookEventName:n,toolName:i,decision:"retry",blockedToolNames:[i],reason:a,output:{hookSpecificOutput:{hookEventName:"PermissionDenied",retry:!0,additionalContext:a}}})}om({hookEventName:n,toolName:o,decision:"allow",blockedToolNames:[],reason:"Allowed by pand\u014D policy.",output:null});return}if(n==="SessionStart"||n==="PostCompact")return Gc({hookEventName:n,toolName:null,decision:"remind",blockedToolNames:[],reason:"Injected pand\u014D tool-selection reminder.",output:{hookSpecificOutput:{hookEventName:n,additionalContext:d5}}});let s=p5(n);om({hookEventName:n||"unknown",toolName:Jb(e),decision:"observe",blockedToolNames:[],reason:s?"Recorded (observe-only lifecycle event; not gated by pand\u014D policy).":"Recorded (event not registered by pand\u014D; captured for audit).",output:null})}function f5(t){try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{__pandoParseError:!0}}}function Jb(t){return typeof t.tool_name=="string"&&t.tool_name.trim()?t.tool_name:null}function m5(t,e){let n=y5(t);return[...new Set(n.filter(r=>!oo(r,e)))]}function Vb(t){return`pand\u014D firewall blocked off-policy Claude tool use/result: ${t}. Retry using pand\u014D MCP tools only.`}function h5(t,e){return t&&g5(t)?{updatedMCPToolOutput:e}:{updatedToolOutput:e}}function g5(t){return t.startsWith("mcp__")}function y5(t){return[...b5(t.tool_calls),...LE(t)]}function b5(t){if(!Array.isArray(t))return[];let e=[];for(let n of t){if(!n||typeof n!="object"||Array.isArray(n))continue;let r=n.tool_name;typeof r=="string"&&r.trim()&&e.push(r)}return e}function LE(t,e=0){if(e>6||!t||typeof t!="object")return[];if(Array.isArray(t))return t.flatMap(o=>LE(o,e+1));let n=t,r=typeof n.tool_name=="string"&&n.tool_name.trim()?[n.tool_name]:[],s=["tool_calls","tool_results","tool_responses","tool_uses","content","items"];return[...r,...s.flatMap(o=>LE(n[o],e+1))]}async function S5(){let t=[];for await(let e of process.stdin)t.push(typeof e=="string"?Buffer.from(e):e);return Buffer.concat(t).toString("utf8")}function x5(t){process.stdout.write(`${JSON.stringify(t)}
1248
+ `)}function Gc(t){om(t),x5(t.output)}function om(t){Rt("claude_hook.decision",{actor:t.blockedToolNames.length>0?"pando.firewall":"pando.hook",channel:"claude_hook",hookEventName:t.hookEventName,toolName:t.toolName,decision:t.decision,blockedToolNames:t.blockedToolNames,reason:t.reason,output:t.output})}function _5(t,e){let n=w5(t,e);for(let r=0;r<n.length;r+=1){let s=n[r];Rt("provider.transcript.item",{actor:s.actor,channel:"claude_hook",source:"claude_hook",hookEventName:t,itemIndex:r,itemType:s.itemType,body:s.body})}}function w5(t,e){switch(t){case"UserPromptSubmit":return sm(e,"prompt")?[{actor:"user",itemType:"user_prompt",body:{prompt:e.prompt}}]:[];case"UserPromptExpansion":return[{actor:"user",itemType:"user_prompt_expansion",body:Jc(e,["command","prompt","expanded_prompt","expansion"])}];case"MessageDisplay":return[{actor:"assistant",itemType:sm(e,"message_type")??sm(e,"type")??"message_display",body:e}];case"Stop":return sm(e,"last_assistant_message")?[{actor:"assistant",itemType:"last_assistant_message",body:{text:e.last_assistant_message,stop_hook_active:e.stop_hook_active??null}}]:[];case"StopFailure":return[{actor:"assistant",itemType:"stop_failure",body:Jc(e,["error","error_details","last_assistant_message"])}];case"SubagentStop":return sm(e,"last_assistant_message")?[{actor:"assistant",itemType:"subagent_last_assistant_message",body:Jc(e,["agent_id","agent_type","agent_transcript_path","last_assistant_message","stop_hook_active"])}]:[];case"PreToolUse":case"PermissionRequest":return[{actor:"assistant",itemType:"tool_call",body:Jc(e,["tool_name","tool_input"])}];case"PostToolUse":case"PostToolUseFailure":return[{actor:"tool",itemType:t==="PostToolUse"?"tool_result":"tool_error",body:Jc(e,["tool_name","tool_input","tool_response","error","error_details"])}];case"PostToolBatch":return[{actor:"tool",itemType:"tool_batch_result",body:Jc(e,["tool_calls","tool_results","tool_responses"])}];case"Elicitation":return[{actor:"tool",itemType:"elicitation_request",body:e}];case"ElicitationResult":return[{actor:"user",itemType:"elicitation_result",body:e}];case"Notification":return[{actor:"assistant",itemType:"notification",body:e}];case"TaskCreated":case"TaskCompleted":return[{actor:"assistant",itemType:t==="TaskCreated"?"task_created":"task_completed",body:Jc(e,["task_id","task_subject","task_description","teammate_name","team_name"])}];default:return[]}}function sm(t,e){let n=t[e];return typeof n=="string"&&n.trim()?n:null}function Jc(t,e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}Qt();dt();function v5(t,e){let n=t[0]==="serve-http"?"serve-http":"serve",r=t[1];return t.length>2&&(console.error(`Unexpected argument: ${t[2]}`),process.exit(1)),{command:n,projectPath:r?si.default.resolve(r):null,httpHost:e.httpHost,httpPort:e.httpPort,disableAuth:e.disableAuth}}var R5=new Set(["gateway","launch","security"]);function k5(t){let e={help:!1,version:!1,httpHost:"127.0.0.1",httpPort:5888,disableAuth:!1,positional:[],passthrough:[],subArgs:null},n=2;for(;n<t.length;n++){let r=t[n];if(e.positional.length===0&&!r.startsWith("-")&&R5.has(r)){e.positional.push(r),e.subArgs=t.slice(n+1);break}if(r==="--"){e.passthrough=t.slice(n+1);break}else if(r==="--help"||r==="-h")e.help=!0;else if(r==="--version"||r==="-v")e.version=!0;else if(r==="--disable-auth"||r==="--no-auth")e.disableAuth=!0;else if(r==="--host"){let s=t[++n];s||(console.error("--host requires a value"),process.exit(1)),e.httpHost=s}else if(r==="--port"){let s=t[++n],o=Number(s);(!Number.isInteger(o)||o<=0||o>65535)&&(console.error("--port requires a TCP port number"),process.exit(1)),e.httpPort=o}else r.startsWith("-")?(console.error(`Unknown option: ${r}`),process.exit(1)):e.positional.push(r)}return e}function E5(){console.error(`Usage: ${Jt} Install / update pand\u014D-supervised launchers
1249
1249
  ${Jt} install Re-run the installer wizard
1250
1250
  ${Jt} uninstall Remove pand\u014D shims, state, auth, and data
1251
1251
  ${Jt} serve [project-path]
@@ -1271,4 +1271,4 @@ Config keys:
1271
1271
 
1272
1272
  After installation you keep running \`codex\` and \`claude\` normally; pand\u014D
1273
1273
  supervises each launch transparently.
1274
- `)}function im(){let t=si.default.resolve(__dirname,"..");Ma(t,{runtimeRoot:t,workerRoot:si.default.join(t,"dist","workers"),toolsRoot:si.default.join(t,"tools"),resourcesRoot:si.default.join(t,"resources"),modelRoot:si.default.join(t,"resources","models")})}function zE(){console.error(`${Jt} ${wa}`)}function E5(t){return t?!new Set(["claude-hook","gateway","launch","security","serve","serve-http"]).has(t):!0}async function T5(){W("CLI","main start",{cwd:process.cwd(),version:wa,argv:process.argv.slice(2)});let t=R5(process.argv),e=t.positional[0];if(t.help&&(zE(),k5(),process.exit(0)),t.version&&(zE(),process.exit(0)),E5(e)&&zE(),e==="login"){let i=await VR();console.log(`Signed in as ${yu(i)}`),process.exit(0)}if(e==="logout"&&(await NM(),console.log("Signed out."),process.exit(0)),e==="config"&&(zM(t.positional.slice(1)),process.exit(0)),e==="proxy"&&(ZM(t.positional.slice(1)),process.exit(0)),(e==="memory-manager"||e==="memory")&&(JM(t.positional.slice(1)),process.exit(0)),e==="security"){let i=t.subArgs??t.positional.slice(1);W("CLI","security command",{subcommand:i[0],argCount:i.length}),im();let a=await Vj(i);W("CLI","security command end",{subcommand:i[0],exitCode:a}),process.exit(a)}if(e==="uninstall"){let i=Kb();process.exit(i??0)}if(e==="whoami"){let i=await GR();i||(console.log("Not signed in."),process.exit(1)),console.log(yu(i)),process.exit(0)}if(e==="gateway"){let i=t.subArgs??[];im(),await PL(i,[]);return}if(e==="launch"){let i=t.subArgs??[],a=i.indexOf("--"),c=a===-1?i:i.slice(0,a),l=a===-1?[]:i.slice(a+1),u=c[0];W("CLI","launch command",{tool:u,argCount:l.length}),u!=="codex"&&u!=="claude"&&(W("CLI","launch invalid tool",{tool:u}),console.error(`Usage: ${Jt} launch <codex|claude> -- <args...>`),process.exit(1)),im();let d=await Wb(u,l);W("CLI","launch command end",{tool:u,exitCode:d}),process.exit(d)}e==="claude-hook"&&(await CL(),process.exit(0)),(e===void 0||e==="install")&&(im(),await TL({force:e==="install"}),process.exit(0)),e!=="serve"&&e!=="serve-http"&&(console.error(`Unknown command: ${e}`),console.error(`Run \`${Jt} --help\` for usage.`),process.exit(1)),e==="serve"&&process.env[Sk]!=="1"&&(W("CLI","serve blocked",{reason:"PANDO_INTERNAL_SERVE not set"}),console.error(`${Jt} serve is internal. Use ${Jt} security launch --role <core|workspace> --project-root <path> --stdio.`),process.exit(1)),im();let n=w5(t.positional,t),r=n.projectPath||process.cwd(),s=process.env.PANDO_PROCESS_ROLE||"unknown";W("CLI","serve start",{projectPath:r,role:s,command:n.command,helperLaunched:process.env.PANDO_SECURITY_HELPER_LAUNCHED==="1",sandboxContext:process.env.PANDO_AGENT_SANDBOX_CONTEXT==="1"});let o=mF({projectRoot:r,runtimeRoot:si.default.resolve(__dirname,".."),sandboxStateRoot:si.default.join(zi(process.env.PANDO_DATA_DIR||process.env.PANDO_SECURITY_DATA_ROOT||si.default.join(AL.default.homedir(),".pando-data"),r),"sandbox"),extraRoots:tl(r)});if(W("CLI","serve sandbox ensured",{projectPath:r,role:s,reExecedIntoSandbox:o}),!o){if(n.command==="serve-http"){await OF(r,n.httpHost,n.httpPort,n.disableAuth);return}W("CLI","serve stdio start",{projectPath:r,role:s}),await DF(r,n.disableAuth),W("CLI","serve end",{projectPath:r,role:s})}}T5().catch(t=>{console.error(`Fatal error: ${t?.message??t}`),process.exit(1)});
1274
+ `)}function im(){let t=si.default.resolve(__dirname,"..");Ma(t,{runtimeRoot:t,workerRoot:si.default.join(t,"dist","workers"),toolsRoot:si.default.join(t,"tools"),resourcesRoot:si.default.join(t,"resources"),modelRoot:si.default.join(t,"resources","models")})}function zE(){console.error(`${Jt} ${wa}`)}function T5(t){return t?!new Set(["claude-hook","gateway","launch","security","serve","serve-http"]).has(t):!0}async function P5(){W("CLI","main start",{cwd:process.cwd(),version:wa,argv:process.argv.slice(2)});let t=k5(process.argv),e=t.positional[0];if(t.help&&(zE(),E5(),process.exit(0)),t.version&&(zE(),process.exit(0)),T5(e)&&zE(),e==="login"){let i=await VR();console.log(`Signed in as ${yu(i)}`),process.exit(0)}if(e==="logout"&&(await NM(),console.log("Signed out."),process.exit(0)),e==="config"&&(zM(t.positional.slice(1)),process.exit(0)),e==="proxy"&&(ZM(t.positional.slice(1)),process.exit(0)),(e==="memory-manager"||e==="memory")&&(JM(t.positional.slice(1)),process.exit(0)),e==="security"){let i=t.subArgs??t.positional.slice(1);W("CLI","security command",{subcommand:i[0],argCount:i.length}),im();let a=await Vj(i);W("CLI","security command end",{subcommand:i[0],exitCode:a}),process.exit(a)}if(e==="uninstall"){let i=Kb();process.exit(i??0)}if(e==="whoami"){let i=await GR();i||(console.log("Not signed in."),process.exit(1)),console.log(yu(i)),process.exit(0)}if(e==="gateway"){let i=t.subArgs??[];im(),await PL(i,[]);return}if(e==="launch"){let i=t.subArgs??[],a=i.indexOf("--"),c=a===-1?i:i.slice(0,a),l=a===-1?[]:i.slice(a+1),u=c[0];W("CLI","launch command",{tool:u,argCount:l.length}),u!=="codex"&&u!=="claude"&&(W("CLI","launch invalid tool",{tool:u}),console.error(`Usage: ${Jt} launch <codex|claude> -- <args...>`),process.exit(1)),im();let d=await Wb(u,l);W("CLI","launch command end",{tool:u,exitCode:d}),process.exit(d)}e==="claude-hook"&&(await CL(),process.exit(0)),(e===void 0||e==="install")&&(im(),await TL({force:e==="install"}),process.exit(0)),e!=="serve"&&e!=="serve-http"&&(console.error(`Unknown command: ${e}`),console.error(`Run \`${Jt} --help\` for usage.`),process.exit(1)),e==="serve"&&process.env[Sk]!=="1"&&(W("CLI","serve blocked",{reason:"PANDO_INTERNAL_SERVE not set"}),console.error(`${Jt} serve is internal. Use ${Jt} security launch --role <core|workspace> --project-root <path> --stdio.`),process.exit(1)),im();let n=v5(t.positional,t),r=n.projectPath||process.cwd(),s=process.env.PANDO_PROCESS_ROLE||"unknown";W("CLI","serve start",{projectPath:r,role:s,command:n.command,helperLaunched:process.env.PANDO_SECURITY_HELPER_LAUNCHED==="1",sandboxContext:process.env.PANDO_AGENT_SANDBOX_CONTEXT==="1"});let o=mF({projectRoot:r,runtimeRoot:si.default.resolve(__dirname,".."),sandboxStateRoot:si.default.join(zi(process.env.PANDO_DATA_DIR||process.env.PANDO_SECURITY_DATA_ROOT||si.default.join(AL.default.homedir(),".pando-data"),r),"sandbox"),extraRoots:tl(r)});if(W("CLI","serve sandbox ensured",{projectPath:r,role:s,reExecedIntoSandbox:o}),!o){if(n.command==="serve-http"){await OF(r,n.httpHost,n.httpPort,n.disableAuth);return}W("CLI","serve stdio start",{projectPath:r,role:s}),await DF(r,n.disableAuth),W("CLI","serve end",{projectPath:r,role:s})}}P5().catch(t=>{console.error(`Fatal error: ${t?.message??t}`),process.exit(1)});