pando-ai 0.9.3 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -5,7 +5,7 @@
5
5
  `)}catch{}try{hT(),hm.default.appendFileSync(mT(),o+`
6
6
  `,"utf8")}catch{}}function Rt(t,e={}){if(!yT("PandoAudit"))return;let n=new Date().toISOString();try{hT();let r=JSON.stringify({ts:n,recordType:"audit",schemaVersion:1,sessionId:Ca(),event:t,credentialFieldsRedacted:!0,...aS(e)});hm.default.appendFileSync(pz(),r+`
7
7
  `,"utf8")}catch{}}function aS(t){if(Array.isArray(t))return t.map(aS);if(!t||typeof t!="object")return t;let e={};for(let[n,r]of Object.entries(t))e[n]=Sz(n)?"[redacted]":aS(r);return e}function Sz(t){let e=t.toLowerCase();return e==="authorization"||e==="proxy-authorization"||e==="access_token"||e==="refresh_token"||e==="id_token"||e==="api_key"||e==="apikey"||e==="openai_api_key"||e==="anthropic_api_key"||e==="x-api-key"||e==="sessionkey"||e==="cookie"||e==="set-cookie"}function bm(){return mT()}var hm,iS,Xu,pT,fT,gm,fz,ym,mz,hz,gz,yz,gT,Vu,dt=te(()=>{"use strict";hm=B(require("fs")),iS=B(require("os")),Xu=B(require("path"));Vt();pT=require("util"),fT=require("crypto");gm=t=>{if(t==null)return!1;let e=t.trim().toLowerCase();return e!=="0"&&e!=="false"&&e!=="off"&&e!=="no"},fz=gm(process.env.PANDO_LOG_DISABLED),ym=!fz&&(process.env.PANDO_DEBUG==null||gm(process.env.PANDO_DEBUG)),mz=ym&&(process.env.PANDO_INDEX_HOT_LOG==null||gm(process.env.PANDO_INDEX_HOT_LOG)),hz=ym&&(process.env.PANDO_INDEX_TIMING==null||gm(process.env.PANDO_INDEX_TIMING)),gz=new Set(["BatchAnalysisScheduler","ClojureIndex","ClojureIndexer","ThreadedIndexer"]),yz=new Set(["IndexTiming"]);gT=!1,Vu=null});var rl={};en(rl,{CodeEngineFactory:()=>Dn});var bT,Dn,zs=te(()=>{"use strict";bT=require("ts-morph");lS();Uu();Vt();dt();Dn=class{static{this.instances=new Map}static{this.projects=new Map}static{this.engineOptions=new Map}static disposeEngineInstance(e){W("CodeEngineFactory","disposeEngineInstance begin",{canonicalPath:e,hasEngine:this.instances.has(e),hasProject:this.projects.has(e),hasOptions:this.engineOptions.has(e)});let n=this.instances.get(e);if(n&&typeof n.dispose=="function")try{n.dispose()}catch{}this.instances.delete(e),this.projects.delete(e),W("CodeEngineFactory","disposeEngineInstance complete",{canonicalPath:e})}static callerHint(e=4){try{let n=new Error().stack;return n?n.split(`
8
- `).slice(3,3+e).map(r=>r.trim()).join(" | "):"unknown"}catch{return"unknown"}}static canonicalProjectPath(e){return vt(e)}static getEngine(e,n){let r=this.canonicalProjectPath(e),s=this.instances.get(r);if(process.env.PANDO_QUIET||console.log("[RootTrace] CodeEngineFactory.getEngine",{projectPath:e,canonicalPath:r,hasExisting:!!s,hasInlineOptions:!!n,hasStoredOptions:this.engineOptions.has(r),caller:this.callerHint()}),s){if(n??this.engineOptions.get(r)){let o=n??this.engineOptions.get(r);typeof s.setRuntimeOptions=="function"&&s.setRuntimeOptions({languageSupport:o?.languageSupport,lspHost:o?.lspHost})}}else{let o=n??this.engineOptions.get(r);process.env.PANDO_QUIET||console.log("[CodeEngineFactory] create engine",{projectPath:e,canonicalPath:r,pid:process.pid}),s=new Yu(r,void 0,{languageSupport:o?.languageSupport,lspHost:o?.lspHost}),this.instances.set(r,s)}return s}static setEngineOptions(e,n){let r=this.canonicalProjectPath(e);process.env.PANDO_QUIET||console.log("[RootTrace] CodeEngineFactory.setEngineOptions",{projectPath:e,canonicalPath:r,hasLanguageSupport:!!n?.languageSupport,hasLspHost:!!n?.lspHost,caller:this.callerHint()}),this.engineOptions.set(r,n);let s=this.instances.get(r);s&&typeof s.setRuntimeOptions=="function"&&(s.setRuntimeOptions(n),n.lspHost&&!s.lspHost&&(process.env.PANDO_QUIET||console.log("[RootTrace] CodeEngineFactory.setEngineOptions forcing engine recreation",{canonicalPath:r,reason:"existing engine missing lspHost after runtime option update"}),this.disposeEngineInstance(r)))}static getExistingEngine(e){return this.instances.get(this.canonicalProjectPath(e))}static getEngineOptions(e){return this.engineOptions.get(this.canonicalProjectPath(e))}static getProject(e){let n=this.canonicalProjectPath(e),r=this.projects.get(n);if(!r){let s=`${n}/tsconfig.json`,o={};try{require("fs").existsSync(s)?(o.tsConfigFilePath=s,o.skipAddingFilesFromTsConfig=!0,o.compilerOptions=uo.getSupportedEditCompilerOptions()):o.compilerOptions={target:99,module:99,jsx:2,allowJs:!0}}catch{o.compilerOptions={target:99,module:99,jsx:2}}if(r=new bT.Project(o),!o.tsConfigFilePath)try{r.addSourceFilesAtPaths([`${n}/**/*.ts`,`${n}/**/*.tsx`,`!${n}/node_modules/**`,`!${n}/**/dist/**`,`!${n}/**/build/**`])}catch(i){console.log("Failed to add source files:",i)}this.projects.set(n,r)}return r}static clearEngine(e){let n=this.canonicalProjectPath(e);W("CodeEngineFactory","clearEngine",{projectPath:e,canonicalPath:n}),this.disposeEngineInstance(n),this.engineOptions.delete(n)}static resetEngine(e){let n=this.canonicalProjectPath(e);W("CodeEngineFactory","resetEngine",{projectPath:e,canonicalPath:n,hasStoredOptions:this.engineOptions.has(n)}),this.disposeEngineInstance(n)}static clearAll(){for(let e of this.instances.values())if(e&&typeof e.dispose=="function")try{e.dispose()}catch{}this.instances.clear(),this.projects.clear(),this.engineOptions.clear()}static getStats(){return{engines:this.instances.size,projects:this.projects.size,paths:Array.from(this.instances.keys())}}}});function uS(t,e){Xt()&&W("ClojureTrace",t,e)}var Sm,ST=te(()=>{"use strict";tT();dt();Sm=class{constructor(e,n){this.fileStates=new Map;this.operationMetadata=new WeakMap;this.project=e,this.projectRoot=n,this.ls={getForFile:r=>dm(this.projectRoot,r),ensureInProgram:r=>YE(this.projectRoot,r),bump:r=>eT(this.projectRoot,r)}}setQueryLayer(e){this._queries=e}get queries(){return this._queries}getOperationMetadata(e,n){return this.operationMetadata.get(e)?.get(n)}setOperationMetadata(e,n,r){let s=this.operationMetadata.get(e);s||(s=new Map,this.operationMetadata.set(e,s)),s.set(n,r)}clearOperationMetadata(e,n){if(n==null){this.operationMetadata.delete(e);return}let r=this.operationMetadata.get(e);r&&(r.delete(n),r.size===0&&this.operationMetadata.delete(e))}setLspHost(e){this._lspHost=e}get lsp(){if(!this._lspHost)try{let{CodeEngineFactory:e}=(zs(),ke(rl)),n=e.getEngineOptions(this.projectRoot);n?.lspHost&&(this._lspHost=n.lspHost,uS("ExecutionContext.lsp recovered host from engine options",{projectRoot:this.projectRoot,hasHost:!0}))}catch{}return this._lspHost?uS("ExecutionContext.lsp returning host",{projectRoot:this.projectRoot,lspType:this._lspHost?.constructor?.name??typeof this._lspHost,hasReferences:!!this._lspHost?.references,hasRename:!!this._lspHost?.rename,hasWorkspaceFilesChanged:!!this._lspHost?.workspaceFilesChanged}):uS("ExecutionContext.lsp returning undefined host",{projectRoot:this.projectRoot}),this._lspHost}saveFileState(e){let n=this.project.getSourceFile(e);n&&this.fileStates.set(e,n.getFullText())}saveFileStates(e){for(let n of e)this.saveFileState(n)}getSavedFilePaths(){return Array.from(this.fileStates.keys())}restoreFileStates(){for(let[e,n]of this.fileStates){let r=this.project.getSourceFile(e);r&&r.replaceWithText(n)}this.fileStates.clear()}}});var fs={};en(fs,{Database:()=>_m,Statement:()=>xm,default:()=>Dt});var xT,xm,_m,Dt,an=te(()=>{"use strict";xT=require("node:sqlite"),xm=class{constructor(e){this.statement=e}run(...e){let n=this.statement.run(...e);return{changes:n.changes,lastInsertRowid:n.lastInsertRowid}}get(...e){let n=this.statement.get(...e);return n??void 0}all(...e){return this.statement.all(...e)}iterate(...e){return this.statement.iterate(...e)}setAllowBareNamedParameters(e){return this.statement.setAllowBareNamedParameters(e),this}setReadBigInts(e){return this.statement.setReadBigInts(e),this}},_m=class t{constructor(e,n){this.file=e;this.transactionDepth=0;let r=n??{},s=!!(r.readOnly??r.readonly);this.connectionId=t.nextId++,this.database=new xT.DatabaseSync(e,{readOnly:s,fileMustExist:!!r.fileMustExist,timeout:typeof r.timeout=="number"?Math.max(0,Math.floor(r.timeout)):void 0})}static{this.nextId=1}prepare(e){return new xm(this.database.prepare(e))}exec(e){this.database.exec(e)}close(){this.database.close()}getConnectionId(){return this.connectionId}pragma(e){return this.database.prepare(`PRAGMA ${e}`).all()}transaction(e){return(...n)=>{this.transactionDepth+=1;let r=this.transactionDepth;r===1&&this.database.exec("BEGIN");try{let s=e(...n);if(s instanceof Promise)throw new TypeError("SQLite transactions must be synchronous. Received a Promise.");return r===1&&this.database.exec("COMMIT"),s}catch(s){if(r===1)try{this.database.exec("ROLLBACK")}catch{}throw s}finally{this.transactionDepth=Math.max(0,this.transactionDepth-1)}}}loadExtension(){throw new Error("loadExtension is not supported by the embedded SQLite runtime")}},Dt=_m});var Aa,_T,xz,ed,wT=te(()=>{"use strict";Aa=B(require("fs")),_T=B(require("path"));an();Vt();xz=2,ed=class{constructor(e=process.cwd()){this.projectRoot=e,this.chunkDbPaths=[],this.discoverChunkDatabases()}discoverChunkDatabases(){let e=ot(this.projectRoot),n;try{n=Aa.readdirSync(e)}catch{this.chunkDbPaths=[];return}let r=/^\.pando-index-chunk-\d+\.db$/;this.chunkDbPaths=n.filter(s=>r.test(s)).sort().map(s=>_T.join(e,s))}getChunkPaths(){return[...this.chunkDbPaths]}async queryAllChunks(e,n=[],r={}){let s=Date.now();if(this.chunkDbPaths.length===0)return console.log("\u26A0\uFE0F No chunk databases found. Run indexing first."),[];console.log(`\u{1F50D} Querying ${this.chunkDbPaths.length} chunks in parallel...`);let o=this.chunkDbPaths.map(async(d,p)=>this.queryChunk(d,p,e,n)),i=await Promise.all(o),a=[],c=0,l=[];for(let d of i)d.error?l.push(`Chunk ${d.chunkIndex}: ${d.error}`):(a.push(...d.results),c+=d.queryTime);if(r.deduplicateBy){let d=new Set;a=a.filter(p=>{let f=p[r.deduplicateBy];return d.has(f)?!1:(d.add(f),!0)})}if(r.orderBy){let d=r.orderDirection==="DESC"?-1:1;a.sort((p,f)=>{let m=p[r.orderBy],h=f[r.orderBy];return m<h?-1*d:m>h?1*d:0})}r.offset&&(a=a.slice(r.offset)),r.limit&&(a=a.slice(0,r.limit));let u=Date.now()-s;return console.log(`\u2705 Distributed query complete: ${a.length} results in ${u}ms`),console.log(` \u{1F4CA} Avg chunk query time: ${(c/this.chunkDbPaths.length).toFixed(1)}ms`),l.length>0&&console.log(`\u26A0\uFE0F ${l.length} chunk errors:`,l),a}async queryChunk(e,n,r,s){let o=Date.now();try{if(!Aa.existsSync(e))return{chunkIndex:n,chunkPath:e,results:[],queryTime:0,error:`Database file not found: ${e}`};let i=new Dt(e,{readonly:!0}),c=i.prepare(r).all(...s);i.close();let l=Date.now()-o;return{chunkIndex:n,chunkPath:e,results:c,queryTime:l}}catch(i){let a=Date.now()-o;return{chunkIndex:n,chunkPath:e,results:[],queryTime:a,error:`Query failed: ${i.message}`}}}async getStats(){console.log(`\u{1F4CA} Gathering statistics from ${this.chunkDbPaths.length} chunks...`);let e=`
8
+ `).slice(3,3+e).map(r=>r.trim()).join(" | "):"unknown"}catch{return"unknown"}}static canonicalProjectPath(e){return vt(e)}static getEngine(e,n){let r=this.canonicalProjectPath(e),s=this.instances.get(r);if(process.env.PANDO_QUIET||console.log("[RootTrace] CodeEngineFactory.getEngine",{projectPath:e,canonicalPath:r,hasExisting:!!s,hasInlineOptions:!!n,hasStoredOptions:this.engineOptions.has(r),caller:this.callerHint()}),s){if(n??this.engineOptions.get(r)){let o=n??this.engineOptions.get(r);typeof s.setRuntimeOptions=="function"&&s.setRuntimeOptions({languageSupport:o?.languageSupport,lspHost:o?.lspHost})}}else{let o=n??this.engineOptions.get(r);process.env.PANDO_QUIET||console.log("[CodeEngineFactory] create engine",{projectPath:e,canonicalPath:r,pid:process.pid}),s=new Yu(r,void 0,{languageSupport:o?.languageSupport,lspHost:o?.lspHost}),this.instances.set(r,s)}return s}static setEngineOptions(e,n){let r=this.canonicalProjectPath(e);process.env.PANDO_QUIET||console.log("[RootTrace] CodeEngineFactory.setEngineOptions",{projectPath:e,canonicalPath:r,hasLanguageSupport:!!n?.languageSupport,hasLspHost:!!n?.lspHost,caller:this.callerHint()}),this.engineOptions.set(r,n);let s=this.instances.get(r);s&&typeof s.setRuntimeOptions=="function"&&(s.setRuntimeOptions(n),n.lspHost&&!s.lspHost&&(process.env.PANDO_QUIET||console.log("[RootTrace] CodeEngineFactory.setEngineOptions forcing engine recreation",{canonicalPath:r,reason:"existing engine missing lspHost after runtime option update"}),this.disposeEngineInstance(r)))}static getExistingEngine(e){return this.instances.get(this.canonicalProjectPath(e))}static getEngineOptions(e){return this.engineOptions.get(this.canonicalProjectPath(e))}static getProject(e){let n=this.canonicalProjectPath(e),r=this.projects.get(n);if(!r){let s=`${n}/tsconfig.json`,o={};try{require("fs").existsSync(s)?(o.tsConfigFilePath=s,o.skipAddingFilesFromTsConfig=!0,o.compilerOptions=uo.getSupportedEditCompilerOptions()):o.compilerOptions={target:99,module:99,jsx:2,allowJs:!0}}catch{o.compilerOptions={target:99,module:99,jsx:2}}if(r=new bT.Project(o),!o.tsConfigFilePath)try{r.addSourceFilesAtPaths([`${n}/**/*.ts`,`${n}/**/*.tsx`,`!${n}/node_modules/**`,`!${n}/**/dist/**`,`!${n}/**/build/**`])}catch(i){console.log("Failed to add source files:",i)}this.projects.set(n,r)}return r}static clearEngine(e){let n=this.canonicalProjectPath(e);W("CodeEngineFactory","clearEngine",{projectPath:e,canonicalPath:n}),this.disposeEngineInstance(n),this.engineOptions.delete(n)}static resetEngine(e){let n=this.canonicalProjectPath(e);W("CodeEngineFactory","resetEngine",{projectPath:e,canonicalPath:n,hasStoredOptions:this.engineOptions.has(n)}),this.disposeEngineInstance(n)}static clearAll(){for(let e of this.instances.values())if(e&&typeof e.dispose=="function")try{e.dispose()}catch{}this.instances.clear(),this.projects.clear(),this.engineOptions.clear()}static getStats(){return{engines:this.instances.size,projects:this.projects.size,paths:Array.from(this.instances.keys())}}}});function uS(t,e){Xt()&&W("ClojureTrace",t,e)}var Sm,ST=te(()=>{"use strict";tT();dt();Sm=class{constructor(e,n){this.fileStates=new Map;this.operationMetadata=new WeakMap;this.project=e,this.projectRoot=n,this.ls={getForFile:r=>dm(this.projectRoot,r),ensureInProgram:r=>YE(this.projectRoot,r),bump:r=>eT(this.projectRoot,r)}}setQueryLayer(e){this._queries=e}get queries(){return this._queries}getOperationMetadata(e,n){return this.operationMetadata.get(e)?.get(n)}setOperationMetadata(e,n,r){let s=this.operationMetadata.get(e);s||(s=new Map,this.operationMetadata.set(e,s)),s.set(n,r)}clearOperationMetadata(e,n){if(n==null){this.operationMetadata.delete(e);return}let r=this.operationMetadata.get(e);r&&(r.delete(n),r.size===0&&this.operationMetadata.delete(e))}setLspHost(e){this._lspHost=e}get lsp(){if(!this._lspHost)try{let{CodeEngineFactory:e}=(zs(),ke(rl)),n=e.getEngineOptions(this.projectRoot);n?.lspHost&&(this._lspHost=n.lspHost,uS("ExecutionContext.lsp recovered host from engine options",{projectRoot:this.projectRoot,hasHost:!0}))}catch{}return this._lspHost?uS("ExecutionContext.lsp returning host",{projectRoot:this.projectRoot,lspType:this._lspHost?.constructor?.name??typeof this._lspHost,hasReferences:!!this._lspHost?.references,hasRename:!!this._lspHost?.rename,hasWorkspaceFilesChanged:!!this._lspHost?.workspaceFilesChanged}):uS("ExecutionContext.lsp returning undefined host",{projectRoot:this.projectRoot}),this._lspHost}saveFileState(e){let n=this.project.getSourceFile(e);n&&this.fileStates.set(e,n.getFullText())}saveFileStates(e){for(let n of e)this.saveFileState(n)}getSavedFilePaths(){return Array.from(this.fileStates.keys())}restoreFileStates(){for(let[e,n]of this.fileStates){let r=this.project.getSourceFile(e);r&&r.replaceWithText(n)}this.fileStates.clear()}}});var fs={};en(fs,{Database:()=>_m,Statement:()=>xm,default:()=>Dt});var xT,xm,_m,Dt,an=te(()=>{"use strict";xT=require("node:sqlite"),xm=class{constructor(e){this.statement=e}run(...e){let n=this.statement.run(...e);return{changes:n.changes,lastInsertRowid:n.lastInsertRowid}}get(...e){let n=this.statement.get(...e);return n??void 0}all(...e){return this.statement.all(...e)}iterate(...e){return this.statement.iterate(...e)}setAllowBareNamedParameters(e){return this.statement.setAllowBareNamedParameters(e),this}setReadBigInts(e){return this.statement.setReadBigInts(e),this}},_m=class t{constructor(e,n){this.file=e;this.transactionDepth=0;let r=n??{},s=!!(r.readOnly??r.readonly);this.connectionId=t.nextId++,this.database=new xT.DatabaseSync(e,{readOnly:s,fileMustExist:!!r.fileMustExist,timeout:typeof r.timeout=="number"?Math.max(0,Math.floor(r.timeout)):void 0});try{this.database.exec("PRAGMA temp_store = MEMORY")}catch{}}static{this.nextId=1}prepare(e){return new xm(this.database.prepare(e))}exec(e){this.database.exec(e)}close(){this.database.close()}getConnectionId(){return this.connectionId}pragma(e){return this.database.prepare(`PRAGMA ${e}`).all()}transaction(e){return(...n)=>{this.transactionDepth+=1;let r=this.transactionDepth;r===1&&this.database.exec("BEGIN");try{let s=e(...n);if(s instanceof Promise)throw new TypeError("SQLite transactions must be synchronous. Received a Promise.");return r===1&&this.database.exec("COMMIT"),s}catch(s){if(r===1)try{this.database.exec("ROLLBACK")}catch{}throw s}finally{this.transactionDepth=Math.max(0,this.transactionDepth-1)}}}loadExtension(){throw new Error("loadExtension is not supported by the embedded SQLite runtime")}},Dt=_m});var Aa,_T,xz,ed,wT=te(()=>{"use strict";Aa=B(require("fs")),_T=B(require("path"));an();Vt();xz=2,ed=class{constructor(e=process.cwd()){this.projectRoot=e,this.chunkDbPaths=[],this.discoverChunkDatabases()}discoverChunkDatabases(){let e=ot(this.projectRoot),n;try{n=Aa.readdirSync(e)}catch{this.chunkDbPaths=[];return}let r=/^\.pando-index-chunk-\d+\.db$/;this.chunkDbPaths=n.filter(s=>r.test(s)).sort().map(s=>_T.join(e,s))}getChunkPaths(){return[...this.chunkDbPaths]}async queryAllChunks(e,n=[],r={}){let s=Date.now();if(this.chunkDbPaths.length===0)return console.log("\u26A0\uFE0F No chunk databases found. Run indexing first."),[];console.log(`\u{1F50D} Querying ${this.chunkDbPaths.length} chunks in parallel...`);let o=this.chunkDbPaths.map(async(d,p)=>this.queryChunk(d,p,e,n)),i=await Promise.all(o),a=[],c=0,l=[];for(let d of i)d.error?l.push(`Chunk ${d.chunkIndex}: ${d.error}`):(a.push(...d.results),c+=d.queryTime);if(r.deduplicateBy){let d=new Set;a=a.filter(p=>{let f=p[r.deduplicateBy];return d.has(f)?!1:(d.add(f),!0)})}if(r.orderBy){let d=r.orderDirection==="DESC"?-1:1;a.sort((p,f)=>{let m=p[r.orderBy],h=f[r.orderBy];return m<h?-1*d:m>h?1*d:0})}r.offset&&(a=a.slice(r.offset)),r.limit&&(a=a.slice(0,r.limit));let u=Date.now()-s;return console.log(`\u2705 Distributed query complete: ${a.length} results in ${u}ms`),console.log(` \u{1F4CA} Avg chunk query time: ${(c/this.chunkDbPaths.length).toFixed(1)}ms`),l.length>0&&console.log(`\u26A0\uFE0F ${l.length} chunk errors:`,l),a}async queryChunk(e,n,r,s){let o=Date.now();try{if(!Aa.existsSync(e))return{chunkIndex:n,chunkPath:e,results:[],queryTime:0,error:`Database file not found: ${e}`};let i=new Dt(e,{readonly:!0}),c=i.prepare(r).all(...s);i.close();let l=Date.now()-o;return{chunkIndex:n,chunkPath:e,results:c,queryTime:l}}catch(i){let a=Date.now()-o;return{chunkIndex:n,chunkPath:e,results:[],queryTime:a,error:`Query failed: ${i.message}`}}}async getStats(){console.log(`\u{1F4CA} Gathering statistics from ${this.chunkDbPaths.length} chunks...`);let e=`
9
9
  SELECT
10
10
  (SELECT COUNT(*) FROM nodes) as nodes,
11
11
  0 as calls,
@@ -1245,7 +1245,7 @@ WantedBy=multi-user.target
1245
1245
  `),s}function b8(t,e){let n=e===null?null:new Set(e.map(Yj).filter(Boolean));if(n&&n.size===0)return{};let r={};for(let s of S8(t)){let o;try{o=JSON.parse(Qf.default.readFileSync(s,"utf8"))}catch{continue}let i=x8(o);for(let[a,c]of Object.entries(i))(n===null||n.has(Yj(a)))&&!(a in r)&&(r[a]=c)}return r}function S8(t){let e=process.env.PANDO_CLAUDE_MCP_CONFIG?[process.env.PANDO_CLAUDE_MCP_CONFIG]:[],n=eL.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 x8(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 Yj(t){return t.replace(/^mcp__/,"").replace(/__.*$/,"").trim()}function aL(t){let e=[],n={};for(let[r,s]of Object.entries(rL(t))){n[r]={command:s.command,args:s.args,env:{PANDO_PROCESS_ROLE:s.env?.[PE],PANDO_BROKERED_AUTH:s.env?.[qb]},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 IE=B(require("fs")),NE=B(require("path"));var _8=["mcp__computer-use","mcp__computer-use__*"],DE=["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 cL(){return JSON.stringify(uL())}function lL(){let t=NE.default.join(Fs(),"claude");IE.default.mkdirSync(t,{recursive:!0});let e=NE.default.join(t,"hook-settings.json");return IE.default.writeFileSync(e,`${JSON.stringify(uL(),null,2)}
1246
1246
  `),e}function uL(){let t=w8(),e={};for(let n of DE)e[n]=[{hooks:[t]}];return{hooks:e,permissions:{deny:[..._8]}}}function w8(){return{type:"command",command:qF("claude-hook")}}zl();function dL(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=gE(),a=R8(t);switch(iL(i,a),n.push("--mcp-config",oL(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=${v8().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)&&(lL(),n.push("--settings",cL()),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 v8(){let[t,e]=AE;return[...T_("core").map(n=>`mcp__${t}__${n}`),...T_("workspace").map(n=>`mcp__${e}__${n}`)]}function R8(t){switch(t.otherMcp.mode){case"deny_all":return[];case"allow_list":return t.otherMcp.servers;default:return null}}function pL(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=gE();switch(e.push(...aL(s)),r.push(`pand\u014D MCP (${AE.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 fL=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 mL(t){for(let e=0;e<t.length;e+=1){let n=t[e];if(n==="--")return null;if(!k8(n)){if(fL.has(n)){e+=1;continue}if(!n.startsWith("-"))return{name:n,index:e}}}return null}function k8(t){let[e,n]=t.split("=",2);return n!==void 0&&fL.has(e)}var hL="pando-proxy";function E8(t){let e=`model_providers.${hL}`;return["-c",`model_provider="${hL}"`,"-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 gL(t,e){let n=E8(e),r=mL(t);return r?[...t.slice(0,r.index+1),...n,...t.slice(r.index+1)]:[...n,...t]}dt();Vt();Yc();var T8=28e4,yL="x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles";function An(t){console.error(`[pand\u014D] ${t}`)}function P8(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 C8(){return process.env.PANDO_DATA_DIR||Zc.default.join(process.env.PANDO_HOME_OVERRIDE||OE.default.homedir(),".pando-data")}function A8(t){if(process.platform!=="darwin")return!1;let e=kE(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 I8(){An("opening macOS Full Disk Access settings so you can grant access to the Pando helper/runtime.");try{(0,Yf.spawnSync)("open",[yL],{stdio:"ignore"})}catch{An(`could not open Full Disk Access settings automatically: ${yL}`)}}function N8(t,e){let n=CE(),r=C8(),s=Vj(r,e),o=A8(e);if(n.daemonAvailable&&s)return!0;o&&I8();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=Xf({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 Hb(t,e){let n=process.cwd();P8(n);let r=Ca();Rt("session.start",{actor:"pando.launcher",channel:"session",tool:t,projectRoot:n,originalArgs:e});let s=Lo(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=F8();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(!N8(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"?D8():!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}=U8(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 G8(t);let g=await J8(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 D8(){return!!(process.env.ANTHROPIC_API_KEY||process.env.ANTHROPIC_AUTH_TOKEN||O8())}function O8(){for(let t of _L()){let e=wL(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)&&(bL(n.ANTHROPIC_API_KEY)||bL(n.ANTHROPIC_AUTH_TOKEN)))return!0}return!1}function _L(){let t=M8(),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 M8(){return process.env.PANDO_CLAUDE_HOME_OVERRIDE||process.env.PANDO_HOME_OVERRIDE||process.env.HOME||OE.default.homedir()}function F8(){for(let t of _L()){let e=wL(t);if(e&&$8(e.disableAllHooks))return t}return null}function $8(t){return typeof t=="boolean"?t:typeof t!="string"?!1:/^(1|true|yes|on)$/i.test(t.trim())}function wL(t){try{let e=JSON.parse(xL.default.readFileSync(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function bL(t){return typeof t=="string"&&t.trim().length>0}var j8=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"]),L8=new Set(["--add-dir","--agent","--agents","--allowed-tools","--allowedTools","--disallowed-tools","--disallowedTools","--mcp-config","--permission-mode","--plugin-dir","--setting-sources","--settings","--tools"]),z8=new Set(["--allow-dangerously-skip-permissions","--dangerously-load-development-channels","--dangerously-skip-permissions","--ide"]);function B8(t,e){let n=q8(t),r=W8(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 q8(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]=H8(s);if(z8.has(o)){n.push(o);continue}if(L8.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 H8(t){let e=t.indexOf("=");return e===-1?[t,void 0]:[t.slice(0,e),t.slice(e+1)]}function W8(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&&j8.has(r)&&(e+=1);continue}if(!n.startsWith("-"))return e}return null}function U8(t,e,n,r,s){let o={...process.env};Z8(o);let i,a;if(t==="codex")a=pL(n),r?i=gL(e,{host:r.host,port:r.port,codexAutoCompactTokenLimit:T8}):i=[...e],i=[...i,...a.extraArgs];else{a=dL(n,{supportedFlags:K8(s)});let c=B8(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 SL=new Map;function K8(t){let e=SL.get(t);if(e)return e;let n=(0,Yf.spawnSync)(t,["--help"],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:5e3}),r=`${n.stdout||""}
1247
1247
  ${n.stderr||""}`,s={bare:r.includes("--bare"),noChrome:r.includes("--no-chrome"),disableSlashCommands:r.includes("--disable-slash-commands")};return SL.set(t,s),s}function Z8(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 G8(t){An(`${Jt} ${wa}`);for(let e of[3,2,1])An(`starting ${t} in ${e}...`),await new Promise(n=>setTimeout(n,1e3))}function J8(t,e,n){return new Promise(r=>{let s=(0,Yf.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 zi=B(require("fs")),Ls=B(require("path")),FE=require("child_process");var ME=B(require("fs")),Wb=B(require("path"));Vt();function V8(){let t=process.env.PANDO_GATEWAY_LOG_FILE;return t?t.startsWith("~/")?Wb.default.join(Vr(),t.slice(2)):t:Tu(process.env.PANDO_DEBUG)===!1?null:Wb.default.join(Vr(),Cf)}function Gr(t,e={}){let n=V8();if(n)try{let r=JSON.stringify({ts:new Date().toISOString(),event:`installer_${t}`,...e});ME.default.mkdirSync(Wb.default.dirname(n),{recursive:!0}),ME.default.appendFileSync(n,`${r}
1248
- `,"utf8")}catch{}}var X8=["codex","claude"],Q8=[".pando",".pando-ai",".pando-data"];function vr(t){return t?"\u2713":"\u2717"}function Y8(){try{zi.default.readdirSync(sr()).length===0&&zi.default.rmdirSync(sr())}catch{}}function e5(t){let e=Ls.default.resolve(_a()),n=Ls.default.resolve(t);return n===e||n===Ls.default.parse(n).root||Ls.default.dirname(n)!==e?!1:Q8.includes(Ls.default.basename(n))}function t5(t){if(!zi.default.existsSync(t))return{status:"not_present",target:t};if(!e5(t))return{status:"failed",target:t,message:"refusing to remove unexpected path"};try{return zi.default.rmSync(t,{recursive:!0,force:!0}),zi.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 n5(){let t=_a();return[Fs(),Ls.default.join(t,".pando-ai"),Ls.default.join(t,".pando-data")].map(t5)}function vL(t){try{return zi.default.realpathSync.native(t)}catch{return Ls.default.resolve(t)}}function r5(t){let e=Ls.default.resolve(t);for(;;){let n=Ls.default.join(e,"package.json");try{if(JSON.parse(zi.default.readFileSync(n,"utf8"))?.name===Jt)return e}catch{}let r=Ls.default.dirname(e);if(r===e)return null;e=r}}function RL(){let t=process.env.npm_execpath;return t&&zi.default.existsSync(t)?{command:process.execPath,args:[t]}:{command:"npm",args:[]}}function s5(){let t=RL(),e=(0,FE.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 o5(){let t=r5(__dirname),e=s5();if(!t||!e)return{status:"not_global"};let n=vL(Ls.default.join(e,Jt)),r=vL(t);if(r!==n)return{status:"not_global"};let s=RL(),o=(0,FE.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 Ub(){if(console.log(""),console.log(" pand\u014D uninstall"),console.log(""),Lb()){let o=zb("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 X8){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}Y8();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=o5();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=TE();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 n5())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 kL=B(require("path")),em=["codex","claude"];function $E(){return new Date().toISOString()}function ds(t){return t?"\u2713":"\u2717"}function i5(t){return!t.realPath&&!t.shimPath?` ${t.tool.padEnd(7)} not installed`:t.proxied?` ${t.tool.padEnd(7)} ${ds(!0)} protected`:t.realPath?` ${t.tool.padEnd(7)} ${ds(!1)} unprotected (real binary present, shim not ahead on PATH)`:` ${t.tool.padEnd(7)} ${ds(!1)} shim present but real binary missing`}function Kb(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(i5(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(` ${pb()}`),console.log(""))}var EL=!1;function a5(){EL=!0}function tm(){EL&&(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(` ${pb()}`))}function Zb(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(` ${ds(!0)} ${t}: shim ${e.status} at ${e.shimPath}`),a$(t,e.realPath,$E()),!0;case"skipped_no_real_binary":return console.log(` ${t}: skipped (no real binary on PATH to supervise)`),!1;case"failed":return console.log(` ${ds(!1)} ${t}: install failed \u2014 ${e.message}`),!1}}function c5(){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(` ${ds(!0)} pando-ai: command shim ${t.status} at ${t.shimPath}`),t.currentPathShimPath&&console.log(` ${ds(!0)} pando-ai: current-terminal command shim ${t.currentPathShimStatus} at ${t.currentPathShimPath}`),nm();break;case"failed":console.log(` ${ds(!1)} pando-ai: could not install command shim \u2014 ${t.message}`);break}}function nm(){a5();let t=n$();switch(Gr("path_activate",{status:t.status,target:t.target}),t.status){case"activated":console.log(` ${ds(!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(` ${ds(!1)} PATH: manual step required.`),t.hint&&console.log(` ${t.hint}`);break;case"failed":console.log(` ${ds(!1)} PATH: could not update startup file \u2014 ${t.message}`),console.log(` Add this yourself: ${pb()}`);break}}function l5(){let t=kL.default.join(_a(),".pando-data");console.log(" security: configuring privileged helper");let e=Xf({dataRoot:t,onProgress:n=>console.log(` security: ${n}`)});Gr("security_setup",{ok:e.ok,dataRoot:t,message:e.message}),e.ok?console.log(` ${ds(!0)} security: ${e.message}`):console.log(` ${ds(!1)} security: dedicated-user setup failed \u2014 ${e.message}`)}async function u5(t){let e=fb(),n=t.filter(s=>s.realPath&&!s.proxied&&!e.declined[s.tool]);if(n.length===0)return!1;let r=!1;if(n.length===em.length){if(await zf(" pand\u014D is an AI coding firewall. Replace `codex` and `claude` with pand\u014D-supervised launchers?"))for(let o of n)Zb(o.tool)&&(r=!0);else for(let o of n)Pk(o.tool,$E());return r&&nm(),r&&tm(),r}for(let s of n)await zf(` \`${s.tool}\` is not protected by pand\u014D yet. Install the supervised launcher?`)?Zb(s.tool)&&(r=!0):Pk(s.tool,$E());return r&&nm(),r&&tm(),r}async function d5(){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 p5(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&&Zb(r.tool)&&(n=!0);return n&&nm(),n&&tm(),{action:"continue",refreshStatus:!0}}case 1:return console.log(""),console.log(YR(Kr())),console.log(` Edit ${Mc()} to change the ruleset.`),{action:"continue",refreshStatus:!1};case 2:return await d5(),{action:"continue",refreshStatus:!1};case 3:return{action:"launch",tool:"codex"};case 4:return{action:"launch",tool:"claude"};case 5:return Ub(),{action:"uninstalled"};default:return{action:"quit"}}}async function TL(t={}){Gr("wizard_start",{force:!!t.force});let e=zb("install/update the privileged Pando security helper");if(!e.ok){Gr("install_blocked",{reason:"sudo_failed",message:e.error}),console.log(` ${ds(!1)} security: ${e.error}`);return}c5(),l5();let n=process.env.PATH||"",r=em.map(o=>Ra(o,n));if(Kb(r,n),t.force){let o=!1;for(let i of r)i.realPath&&Zb(i.tool)&&(o=!0);o&&nm(),o&&tm(),n=process.env.PATH||"",r=em.map(i=>Ra(i,n)),Kb(r,n)}else await u5(r)&&(n=process.env.PATH||"",r=em.map(i=>Ra(i,n)),Kb(r,n));let s=!1;for(;;){let o=await p5(r);if(o.action==="quit")break;if(o.action==="uninstalled"){s=!0;break}if(o.action==="launch"){console.log("");let i=await Hb(o.tool,[]);process.exit(i)}o.refreshStatus&&(n=process.env.PATH||"",r=em.map(i=>Ra(i,n)),Kb(r,n))}console.log(""),s?console.log(" Done. pand\u014D launchers have been removed."):(tm(),console.log(` Done. Keep using \`codex\` and \`claude\` as usual \u2014 ${Jt} supervises each launch.`))}async function PL(t={}){await TL({force:t.force})}async function CL(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 f5=new Set(DE),m5="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 h5(t){return f5.has(t)}Qu(!0);async function AL(){let t=await w5(),e=g5(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}:{}}),R5(n||"unknown",e),n==="PreToolUse"){let o=Gb(e);if(o&&io(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=Jb(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=Gb(e);if(!o||!io(o,r)){let i=o??"unknown",a=Jb(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,...b5(o,a)}}}:{hookEventName:n,toolName:i,decision:"steer",blockedToolNames:[i],reason:a,output:{hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:a}}})}sm({hookEventName:n,toolName:o,decision:"allow",blockedToolNames:[],reason:"Allowed by pand\u014D policy.",output:null});return}if(n==="PostToolBatch"){let o=y5(e,r);if(o.length>0){let i=Jb(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}}})}sm({hookEventName:n,toolName:null,decision:"allow",blockedToolNames:[],reason:"Allowed by pand\u014D policy.",output:null});return}if(n==="PermissionDenied"){let o=Gb(e);if(!o||!io(o,r)){let i=o??"unknown",a=Jb(i);return Gc({hookEventName:n,toolName:i,decision:"retry",blockedToolNames:[i],reason:a,output:{hookSpecificOutput:{hookEventName:"PermissionDenied",retry:!0,additionalContext:a}}})}sm({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:m5}}});let s=h5(n);sm({hookEventName:n||"unknown",toolName:Gb(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 g5(t){try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{__pandoParseError:!0}}}function Gb(t){return typeof t.tool_name=="string"&&t.tool_name.trim()?t.tool_name:null}function y5(t,e){let n=x5(t);return[...new Set(n.filter(r=>!io(r,e)))]}function Jb(t){return`pand\u014D firewall blocked off-policy Claude tool use/result: ${t}. Retry using pand\u014D MCP tools only.`}function b5(t,e){return t&&S5(t)?{updatedMCPToolOutput:e}:{updatedToolOutput:e}}function S5(t){return t.startsWith("mcp__")}function x5(t){return[..._5(t.tool_calls),...jE(t)]}function _5(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 jE(t,e=0){if(e>6||!t||typeof t!="object")return[];if(Array.isArray(t))return t.flatMap(o=>jE(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=>jE(n[o],e+1))]}async function w5(){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 v5(t){process.stdout.write(`${JSON.stringify(t)}
1248
+ `,"utf8")}catch{}}var X8=["codex","claude"],Q8=[".pando",".pando-ai",".pando-data"];function vr(t){return t?"\u2713":"\u2717"}function Y8(){try{zi.default.readdirSync(sr()).length===0&&zi.default.rmdirSync(sr())}catch{}}function e5(t){let e=Ls.default.resolve(_a()),n=Ls.default.resolve(t);return n===e||n===Ls.default.parse(n).root||Ls.default.dirname(n)!==e?!1:Q8.includes(Ls.default.basename(n))}function t5(t){if(!zi.default.existsSync(t))return{status:"not_present",target:t};if(!e5(t))return{status:"failed",target:t,message:"refusing to remove unexpected path"};try{return zi.default.rmSync(t,{recursive:!0,force:!0}),zi.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 n5(){let t=_a();return[Fs(),Ls.default.join(t,".pando-ai"),Ls.default.join(t,".pando-data")].map(t5)}function vL(t){try{return zi.default.realpathSync.native(t)}catch{return Ls.default.resolve(t)}}function r5(t){let e=Ls.default.resolve(t);for(;;){let n=Ls.default.join(e,"package.json");try{if(JSON.parse(zi.default.readFileSync(n,"utf8"))?.name===Jt)return e}catch{}let r=Ls.default.dirname(e);if(r===e)return null;e=r}}function RL(){let t=process.env.npm_execpath;return t&&zi.default.existsSync(t)?{command:process.execPath,args:[t]}:{command:"npm",args:[]}}function s5(){let t=RL(),e=(0,FE.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 o5(){let t=r5(__dirname),e=s5();if(!t||!e)return{status:"not_global"};let n=vL(Ls.default.join(e,Jt)),r=vL(t);if(r!==n)return{status:"not_global"};let s=RL(),o=(0,FE.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 Ub(){if(console.log(""),console.log(" pand\u014D uninstall"),console.log(""),Lb()){let o=zb("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 X8){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}Y8();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=o5();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=TE();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 n5())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 kL=B(require("path")),em=["codex","claude"];function $E(){return new Date().toISOString()}function ds(t){return t?"\u2713":"\u2717"}function i5(t){return!t.realPath&&!t.shimPath?` ${t.tool.padEnd(7)} not installed`:t.proxied?` ${t.tool.padEnd(7)} ${ds(!0)} protected`:t.realPath?` ${t.tool.padEnd(7)} ${ds(!1)} unprotected (real binary present, shim not ahead on PATH)`:` ${t.tool.padEnd(7)} ${ds(!1)} shim present but real binary missing`}function Kb(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(i5(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(` ${pb()}`),console.log(""))}var EL=!1;function a5(){EL=!0}function tm(){EL&&(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(` ${pb()}`))}function Zb(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(` ${ds(!0)} ${t}: shim ${e.status} at ${e.shimPath}`),a$(t,e.realPath,$E()),!0;case"skipped_no_real_binary":return console.log(` ${t}: skipped (no real binary on PATH to supervise)`),!1;case"failed":return console.log(` ${ds(!1)} ${t}: install failed \u2014 ${e.message}`),!1}}function c5(){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(` ${ds(!0)} pando-ai: command shim ${t.status} at ${t.shimPath}`),t.currentPathShimPath&&console.log(` ${ds(!0)} pando-ai: current-terminal command shim ${t.currentPathShimStatus} at ${t.currentPathShimPath}`),nm();break;case"failed":console.log(` ${ds(!1)} pando-ai: could not install command shim \u2014 ${t.message}`);break}}function nm(){a5();let t=n$();switch(Gr("path_activate",{status:t.status,target:t.target}),t.status){case"activated":console.log(` ${ds(!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(` ${ds(!1)} PATH: manual step required.`),t.hint&&console.log(` ${t.hint}`);break;case"failed":console.log(` ${ds(!1)} PATH: could not update startup file \u2014 ${t.message}`),console.log(` Add this yourself: ${pb()}`);break}}function l5(){let t=kL.default.join(_a(),".pando-data");console.log(" security: configuring privileged helper");let e=Xf({dataRoot:t,onProgress:n=>console.log(` security: ${n}`)});Gr("security_setup",{ok:e.ok,dataRoot:t,message:e.message}),e.ok?console.log(` ${ds(!0)} security: ${e.message}`):console.log(` ${ds(!1)} security: dedicated-user setup failed \u2014 ${e.message}`)}async function u5(t){let e=fb(),n=t.filter(s=>s.realPath&&!s.proxied&&!e.declined[s.tool]);if(n.length===0)return!1;let r=!1;if(n.length===em.length){if(await zf(" pand\u014D is an AI coding firewall. Replace `codex` and `claude` with pand\u014D-supervised launchers?"))for(let o of n)Zb(o.tool)&&(r=!0);else for(let o of n)Pk(o.tool,$E());return r&&nm(),r&&tm(),r}for(let s of n)await zf(` \`${s.tool}\` is not protected by pand\u014D yet. Install the supervised launcher?`)?Zb(s.tool)&&(r=!0):Pk(s.tool,$E());return r&&nm(),r&&tm(),r}async function d5(){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 p5(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&&Zb(r.tool)&&(n=!0);return n&&nm(),n&&tm(),{action:"continue",refreshStatus:!0}}case 1:return console.log(""),console.log(YR(Kr())),console.log(` Edit ${Mc()} to change the ruleset.`),{action:"continue",refreshStatus:!1};case 2:return await d5(),{action:"continue",refreshStatus:!1};case 3:return{action:"launch",tool:"codex"};case 4:return{action:"launch",tool:"claude"};case 5:return Ub(),{action:"uninstalled"};default:return{action:"quit"}}}async function TL(t={}){Gr("wizard_start",{force:!!t.force});let e=zb("install/update the privileged Pando security helper");if(!e.ok){Gr("install_blocked",{reason:"sudo_failed",message:e.error}),console.log(` ${ds(!1)} security: ${e.error}`);return}c5(),l5();let n=process.env.PATH||"",r=em.map(o=>Ra(o,n));if(Kb(r,n),t.force){let o=!1;for(let i of r)i.realPath&&Zb(i.tool)&&(o=!0);o&&nm(),o&&tm(),n=process.env.PATH||"",r=em.map(i=>Ra(i,n)),Kb(r,n)}else await u5(r)&&(n=process.env.PATH||"",r=em.map(i=>Ra(i,n)),Kb(r,n));let s=!1;for(;;){let o=await p5(r);if(o.action==="quit")break;if(o.action==="uninstalled"){s=!0;break}if(o.action==="launch"){console.log("");let i=await Hb(o.tool,[]);process.exit(i)}o.refreshStatus&&(n=process.env.PATH||"",r=em.map(i=>Ra(i,n)),Kb(r,n))}console.log(""),s?console.log(" Done. pand\u014D launchers have been removed."):(tm(),console.log(` Done. Keep using \`codex\` and \`claude\` as usual \u2014 ${Jt} supervises each launch.`))}async function PL(t={}){await TL({force:t.force})}async function CL(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 f5=new Set(DE),m5="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 h5(t){return f5.has(t)}Qu(!0);async function AL(){let t=await w5(),e=g5(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}:{}}),R5(n||"unknown",e),n==="PreToolUse"){let o=Gb(e);if(o&&io(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=Jb(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=Gb(e);if(!o||!io(o,r)){let i=o??"unknown",a=Jb(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,...b5(o,a)}}}:{hookEventName:n,toolName:i,decision:"steer",blockedToolNames:[i],reason:a,output:{hookSpecificOutput:{hookEventName:"PostToolUseFailure",additionalContext:a}}})}sm({hookEventName:n,toolName:o,decision:"allow",blockedToolNames:[],reason:"Allowed by pand\u014D policy.",output:null});return}if(n==="PostToolBatch"){let o=y5(e,r);if(o.length>0){let i=Jb(o.join(", "));return Gc({hookEventName:n,toolName:o.join(", "),decision:"block",blockedToolNames:o,reason:i,output:{decision:"block",reason:i,hookSpecificOutput:{hookEventName:"PostToolBatch",additionalContext:i}}})}sm({hookEventName:n,toolName:null,decision:"allow",blockedToolNames:[],reason:"Allowed by pand\u014D policy.",output:null});return}if(n==="PermissionDenied"){let o=Gb(e);if(!o||!io(o,r)){let i=o??"unknown",a=Jb(i);return Gc({hookEventName:n,toolName:i,decision:"retry",blockedToolNames:[i],reason:a,output:{hookSpecificOutput:{hookEventName:"PermissionDenied",retry:!0,additionalContext:a}}})}sm({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:m5}}});let s=h5(n);sm({hookEventName:n||"unknown",toolName:Gb(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 g5(t){try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{__pandoParseError:!0}}}function Gb(t){return typeof t.tool_name=="string"&&t.tool_name.trim()?t.tool_name:null}function y5(t,e){let n=x5(t);return[...new Set(n.filter(r=>!io(r,e)))]}function Jb(t){return`pand\u014D firewall blocked off-policy Claude tool use/result: ${t}. Retry using pand\u014D MCP tools only \u2014 do NOT stop; re-do the action this turn with the pand\u014D equivalent. Map: Read/cat/sed/head \u2192 find-nodes (include.body) or mcp__pando_workspace__shell-command; Bash \u2192 mcp__pando_workspace__shell-command; Write/Edit on source \u2192 pand\u014D AST writers (replace/insert/delete), on docs/generated files \u2192 shell-command; Grep/search \u2192 find-nodes. TaskCreate/TaskUpdate, ScheduleWakeup, WebFetch/WebSearch are unavailable under the firewall \u2014 skip them or record TODOs as notes via shell-command instead.`}function b5(t,e){return t&&S5(t)?{updatedMCPToolOutput:e}:{updatedToolOutput:e}}function S5(t){return t.startsWith("mcp__")}function x5(t){return[..._5(t.tool_calls),...jE(t)]}function _5(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 jE(t,e=0){if(e>6||!t||typeof t!="object")return[];if(Array.isArray(t))return t.flatMap(o=>jE(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=>jE(n[o],e+1))]}async function w5(){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 v5(t){process.stdout.write(`${JSON.stringify(t)}
1249
1249
  `)}function Gc(t){sm(t),v5(t.output)}function sm(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 R5(t,e){let n=k5(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 k5(t,e){switch(t){case"UserPromptSubmit":return rm(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:rm(e,"message_type")??rm(e,"type")??"message_display",body:e}];case"Stop":return rm(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 rm(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 rm(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}Vt();dt();function E5(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?oi.default.resolve(r):null,httpHost:e.httpHost,httpPort:e.httpPort,disableAuth:e.disableAuth}}var T5=new Set(["gateway","launch","security"]);function P5(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("-")&&T5.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 C5(){console.error(`Usage: ${Jt} Install / update pand\u014D-supervised launchers
1250
1250
  ${Jt} install Re-run the installer wizard
1251
1251
  ${Jt} uninstall Remove pand\u014D shims, state, auth, and data