makecoder 2.0.71 → 2.0.72
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/cc.mjs +2112 -2057
- package/dist/coder.js +1 -1
- package/dist/gemini/{chunk-APAUY2EN.js → chunk-742OPB22.js} +2 -2
- package/dist/gemini/{chunk-LDCK4LC4.js → chunk-CN5ZY54S.js} +2 -2
- package/dist/gemini/{chunk-BO5N4YCB.js → chunk-LJWQXOG6.js} +2 -2
- package/dist/gemini/{chunk-ECIECMFI.js → chunk-YTXPXB3F.js} +2 -2
- package/dist/gemini/{core-WBV2NJVB.js → core-CQOMB6GX.js} +1 -1
- package/dist/gemini/{devtoolsService-PCTHRK6I.js → devtoolsService-JSKAKMKA.js} +2 -2
- package/dist/gemini/{devtoolsService-BWVPXV65.js → devtoolsService-LPWJ7GXG.js} +2 -2
- package/dist/gemini/{dist-S65OG37M.js → dist-MMPCC5OA.js} +1 -1
- package/dist/gemini/gemini.js +4 -4
- package/dist/gemini/{interactiveCli-ICTGENKL.js → interactiveCli-457SCMEA.js} +2 -2
- package/dist/gemini/{interactiveCli-E47XD2XX.js → interactiveCli-XB5DZLWK.js} +2 -2
- package/dist/gemini/{oauth2-provider-OXLPSPT7.js → oauth2-provider-LSK6ONS7.js} +1 -1
- package/dist/gemini/{oauth2-provider-KNMGGRK6.js → oauth2-provider-ZNP4J6EF.js} +1 -1
- package/package.json +4 -4
- /package/dist/gemini/{tree-sitter-CZHFXNZB.js → tree-sitter-JU2EI3Z2.js} +0 -0
- /package/dist/gemini/{tree-sitter-bash-RYGED55L.js → tree-sitter-bash-IAB7XJEE.js} +0 -0
package/dist/coder.js
CHANGED
|
@@ -199,7 +199,7 @@ CONFIG:
|
|
|
199
199
|
Auth credentials can be stored in config file under "auth" section.
|
|
200
200
|
`)}};pe.exports=N});var U=m((cs,Se)=>{function Ct(d=process.argv.slice(2)){return d.includes("--print")||d.includes("-p")}Se.exports={isPrintMode:Ct}});var F=m((ls,Ee)=>{var{spawn:Et}=require("child_process"),T=require("path"),I=require("fs"),ye=require("os"),{isPrintMode:Ce}=U(),H=class{constructor(e){this.config=e}resloveSettingFilePath(e){return T.join(e,this.config.configDir,"settings.json")}readModelFromSettingsFile(e){try{let t=this.resloveSettingFilePath(e);if(I.existsSync(t)){let s=I.readFileSync(t,"utf8"),o=JSON.parse(s);if(o&&o.model)return o.model}}catch(t){console.warn(e,t.message)}return null}getCurrentModel(e){let t=e.findIndex(o=>o==="--model");if(t!==-1&&t+1<e.length)return e[t+1];let s=this.readModelFromSettingsFile(process.cwd());return s||(s=this.readModelFromSettingsFile(ye.homedir()),s)?s:this.config.defaultModel}async ensureConfig(e=0){let t=T.join(ye.homedir(),this.config.configDir,this.config.configFile),s=T.dirname(t);if(!I.existsSync(t)){let o=this.config.defaultConfig||{};try{I.existsSync(s)||I.mkdirSync(s,{recursive:!0}),I.writeFileSync(t,JSON.stringify(o,null,2)),e>0&&await new Promise(n=>setTimeout(n,e))}catch(n){console.warn(`Failed to create ${this.config.configFile}: ${n.message}`)}}}findExecutablePath(){let e=T.dirname(require.main.filename);for(let t of this.config.executablePaths){let s=T.resolve(e,t);if(I.existsSync(s))return s}throw new Error(`Could not find executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}handleChildMessages(e){process.env.CODEV_DEBUG&&console.log("Child process message handler initialized"),e.connected&&(e.on("message",t=>{this.onChildMessage(t)}),e.on("exit",async(t,s)=>{try{await this.handleChildProcessExit(t,s)}catch(o){console.error("Error in handleChildProcessExit:",o.message)}}),e.on("error",t=>{this.handleChildProcessError(t)}))}onChildMessage(e){process.env.CODEV_DEBUG&&console.log("Received IPC message from child:",e)}handleChildProcessExit(e,t){}handleChildProcessError(e){}async launch(e={}){let{remainingArgs:t=[],codevServer:s,auth_ak:o=null,auth_sk:n=null}=e;try{let i=this.getCurrentModel(t);Ce(t)||console.log(`model:\x1B[90m\x1B[3m ${i} (use /model to switch models) \x1B[0m`),await this.ensureConfig(1e3);let a=this.findExecutablePath();return process.env.CODEV_DEBUG&&console.log(`executablePath: ${a}`),new Promise((r,c)=>{let l={...process.env,...this.config.environmentVariables(s)};o&&(l.CODEV_AUTH_AK=o),n&&(l.CODEV_AUTH_SK=n);let h=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&h.push("--inspect-brk"),h.push(a,...t);let u=Et("node",h,{env:l,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(u),u.on("error",g=>{console.error(`Failed to start: ${g.message}`),c(g)}),u.on("exit",async(g,S)=>{Ce(t)||S&&console.log(`terminated by signal: ${S}`)}),process.on("SIGINT",async()=>{console.log(`
|
|
201
201
|
Terminating ...`),u.kill("SIGTERM"),setTimeout(()=>{u.killed||u.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
|
|
202
|
-
Terminating ...`),u.kill("SIGTERM"),setTimeout(()=>{u.killed||u.kill("SIGKILL")},8e3)})})}catch(i){throw i}}};Ee.exports=H});var xe=m((hs,ve)=>{var f=process.env.CODEV_DEBUG==="True",G=class{constructor(e={}){this.queue=[],this.processing=!1,this.shuttingDown=!1,this.shutdownTimeout=e.shutdownTimeout||5e3,this.maxRetries=e.maxRetries||3,this.retryDelay=e.retryDelay||1e3,this.onProcessMessage=e.onProcessMessage||null,this.shutdownPromise=null,this.currentlyProcessing=null}enqueue(e){if(this.shuttingDown)return f&&console.log("Queue is shutting down, skipping new messages"),null;let t={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(t),f&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),t.id}dequeue(){let e=this.queue.shift();return f&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let t=this.queue.findIndex(s=>s.id===e);return t>-1?(this.queue.splice(t,1),f&&console.log(`Message ${e} removed from queue`),!0):!1}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{for(;this.queue.length>0&&!this.shuttingDown;){let e=this.queue[0];e.processing=!0;try{this.onProcessMessage&&await this.onProcessMessage(e),this.dequeue()}catch(t){if(f&&console.error(`Failed to process message: ${t.message}`),e.retryCount++,f&&console.log("Start Retry:",e.retryCount,"times..."),e.retryCount>=this.maxRetries)f&&console.error("Message exceeded max retries, removing from queue"),this.dequeue();else{e.processing=!1;let s=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,s))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],f&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let t=this.queue.filter(o=>o.processing);if(t.length===0)return;f&&console.log(`Waiting for ${t.length} processing messages to complete (timeout: ${e}ms)`);let s=Date.now();for(;Date.now()-s<e;){if(this.queue.filter(n=>n.processing).length===0){f&&console.log(`All processing messages completed in ${Date.now()-s}ms`);return}await new Promise(n=>setTimeout(n,50))}if(f){let o=this.queue.filter(n=>n.processing);console.log(`Timeout waiting for processing messages. ${o.length} messages still processing`)}}async gracefulShutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let{timeoutMs:t=this.shutdownTimeout,batchSize:s=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async n=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(t*.3,3e3));let i=this.queue.filter(g=>!g.processing),a=i.length;f&&(console.log(`Starting graceful shutdown with ${a} pending messages (${this.queue.length-a} already processing)`),console.log(`Mode: ${o?"fast (parallel)":"sequential"}, timeout: ${t}ms`));let r=Date.now(),c=0,l=0;try{if(o){let g=await this.processAllParallel(t-(Date.now()-r),i);c=g.processed,l=g.failed}else{let g=await this.processInBatches(s,t-(Date.now()-r),i);c=g.processed,l=g.failed}}catch(g){f&&console.error("Error during shutdown processing:",g.message)}let h=Date.now()-r,u=this.queue.length;f&&(console.log(`Shutdown completed in ${h}ms:`),console.log(` - Total: ${a} messages`),console.log(` - Processed: ${c}`),console.log(` - Failed: ${l}`),console.log(` - Remaining: ${u}`)),n({totalMessages:a,processedMessages:c,failedMessages:l,remainingMessages:u,duration:h,allMessagesSent:u===0&&l===0})}),this.shutdownPromise}async processAllParallel(e){if(this.queue.length===0)return{processed:0,failed:0};f&&console.log(`Processing ${this.queue.length} messages in parallel...`);let t=[...this.queue];this.queue=[];let s=t.map(async r=>{try{return this.onProcessMessage&&await this.onProcessMessage(r),{success:!0,messageId:r.id}}catch(c){return f&&console.warn(`Message ${r.id} processing failed: ${c.message}`),{success:!1,messageId:r.id,error:c}}}),o=new Promise(r=>{setTimeout(()=>r({timedOut:!0}),e)}),n=await Promise.race([Promise.allSettled(s).then(r=>({results:r})),o]);if(n.timedOut)return f&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:t.length};let i=n.results.filter(r=>r.status==="fulfilled"&&r.value?.success).length,a=t.length-i;return{processed:i,failed:a}}async processInBatches(e,t){if(this.queue.length===0)return{processed:0,failed:0};f&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let s=Date.now(),o=0,n=0;for(;this.queue.length>0&&Date.now()-s<t;){let i=this.queue.splice(0,e),a=i.map(async h=>{try{return this.onProcessMessage&&await this.onProcessMessage(h),{success:!0}}catch(u){return f&&console.warn(`Batch message processing failed: ${u.message}`),{success:!1,error:u}}}),c=(await Promise.allSettled(a)).filter(h=>h.status==="fulfilled"&&h.value?.success).length,l=i.length-c;o+=c,n+=l,f&&i.length>0&&console.log(`Batch completed: ${c}/${i.length} successful`),this.queue.length>0&&await new Promise(h=>setTimeout(h,10))}return this.queue.length>0&&(n+=this.queue.length,f&&console.log(`${this.queue.length} messages not processed due to timeout`),this.queue=[]),{processed:o,failed:n}}async forceFlushAndShutdown(e=2e3){this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(e*.4,1e3));let t=this.queue.filter(r=>!r.processing);f&&console.log(`Force flush: attempting to send ${t.length} pending messages within ${e}ms (${this.queue.length-t.length} already processing)`);let s=Date.now(),o=t.map(async r=>{try{return this.onProcessMessage&&Date.now()-s<e?(await this.onProcessMessage(r),{success:!0,messageId:r.id}):{success:!1,messageId:r.id,reason:"timeout"}}catch(c){return{success:!1,messageId:r.id,error:c.message}}}),n=e-(Date.now()-s),i=new Promise(r=>{setTimeout(()=>r({timedOut:!0}),Math.max(100,n))}),a=await Promise.race([Promise.allSettled(o).then(r=>({results:r})),i]);if(t.forEach(r=>{let c=this.queue.findIndex(l=>l.id===r.id);c>-1&&this.queue.splice(c,1)}),this.processing=!1,a.timedOut)return f&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:t.length};{let r=a.results.filter(c=>c.status==="fulfilled"&&c.value.success).length;return f&&console.log(`Force flush completed: ${r}/${t.length} messages sent`),{success:r===t.length,successCount:r,totalCount:t.length,results:a.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,f&&console.log("Force shutdown: Queue cleared")}};ve.exports=G});var V=m((us,vt)=>{vt.exports={name:"makecoder",version:"2.0.71",description:"MakeCoder: Unified AI agent CLI tool integrating Claude Code, Codex and Gemini CLI",main:"./dist/coder.js",bin:{coder:"./dist/coder.js"},scripts:{test:'echo "Error: no test specified" && exit 1',start:"node ./src/coder.js",build:"node scripts/build.js","build:clean":"node scripts/build.js --clean","build:dev":"node scripts/build.js --no-minify --sourcemap",postinstall:"node scripts/postinstall.js"},keywords:["cli","ai","claude","gemini","codex","agent"],author:"makecoder",license:"MIT",dependencies:{"node-fetch":"^3.3.2",open:"^10.1.0",zod:"^3.25.76"},optionalDependencies:{"makecoder-codex-linux-x64":"*","makecoder-codex-darwin-arm64":"*","makecoder-codex-win32-x64":"*"},engines:{node:">=20.0.0"},devDependencies:{chokidar:"^4.0.3"},files:["dist","claude","scripts/postinstall.js"]}});var ke=m((ds,Ie)=>{var xt=require("http"),_t=require("https"),{URL:_e}=require("url"),{version:bt}=V(),be=process.env.CODEV_DEBUG==="True",K=class{constructor(e={}){this.baseUrl=e.baseUrl||"",this.timeout=e.timeout||3e4,this.defaultHeaders={"Content-Type":"application/json","User-Agent":`codev-cli/${bt}`,...e.headers}}setBaseUrl(e){this.baseUrl=e}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}async post(e,t,s={}){let o=this.resolveUrl(e),n={...this.defaultHeaders,...s.headers};return new Promise((i,a)=>{this.validateRequest(o,t,a);let r=this.serializeData(t,a);if(!r)return;n["Content-Length"]=Buffer.byteLength(r);let c=this.buildRequestOptions(o,"POST",n),l=this.getHttpModule(o);be&&console.debug(`HTTP POST to ${o} with data length: ${r.length}`);let h=l.request(c,u=>{this.handleResponse(u,i,a)});this.attachErrorHandlers(h,o,a),h.setTimeout(this.timeout),h.write(r),h.end()})}resolveUrl(e){return e.startsWith("http")?e:`${this.baseUrl}${e.startsWith("/")?"":"/"}${e}`}validateRequest(e,t,s){return!e||typeof e!="string"?(s(new Error(`Invalid URL: ${e}`)),!1):t?!0:(s(new Error("No data provided for HTTP POST")),!1)}serializeData(e,t){try{return typeof e=="string"?e:JSON.stringify(e)}catch(s){return t(new Error(`Failed to serialize data: ${s.message}`)),null}}buildRequestOptions(e,t,s){let o=new _e(e),n=o.protocol==="https:";return{hostname:o.hostname,port:o.port||(n?443:80),path:o.pathname+o.search,method:t,headers:s}}getHttpModule(e){return new _e(e).protocol==="https:"?_t:xt}handleResponse(e,t,s){be&&console.debug(`HTTP response status: ${e.statusCode}`);let o="";e.on("data",n=>{o+=n}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?t({statusCode:e.statusCode,data:o,headers:e.headers}):s(new Error(`HTTP request returned status ${e.statusCode}: ${o}`))})}attachErrorHandlers(e,t,s){e.on("error",o=>{s(new Error(`HTTP POST request failed: ${o.message}`))}),e.on("timeout",()=>{s(new Error(`HTTP POST request timed out for URL: ${t}`)),e.destroy()})}};Ie.exports=K});var Pe=m((gs,$e)=>{var It=require("crypto"),{URL:kt}=require("url"),W=class{static generateSignature(e,t,s,o){try{let n=new kt(e),i=Buffer.from(n.pathname),a=Buffer.from(i),r=t?typeof t=="string"?Buffer.from(t):Buffer.from(JSON.stringify(t)):Buffer.alloc(0),c=Buffer.concat([a,r,Buffer.from(o)]),l=It.createHmac("sha256",s);return l.update(c),l.digest("hex")}catch(n){throw new Error(`Failed to generate signature: ${n.message}`)}}static validateSignature(e,t,s,o,n){return this.generateSignature(e,t,s,o)===n}static generateTimestamp(){return Date.now().toString()}};$e.exports=W});var Te=m((fs,De)=>{var $t=Pe(),z=class{constructor(e={}){this.accessKey=null,this.secretKey=null,this.validateCredentials=e.validateCredentials!==!1}setCredentials(e,t){if(this.validateCredentials&&(!e||!t))throw new Error("Both access key and secret key are required");this.accessKey=e,this.secretKey=t}hasCredentials(){return!!(this.accessKey&&this.secretKey)}generateAuthHeaders(e,t=null){if(!this.hasCredentials())return{};try{return{AUTHORIZATION:`Bearer ${this.accessKey}.${this.secretKey}`}}catch(s){throw new Error(`Failed to generate auth headers: ${s.message}`)}}validateAuthHeaders(e,t,s,o){if(!this.hasCredentials())throw new Error("No credentials available for validation");return $t.validateSignature(e,t,this.secretKey,s,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};De.exports=z});var Oe=m((ms,Ae)=>{var A=process.env.CODEV_DEBUG==="True",j=class{constructor(e={}){this.currentSessionId=null,this.previousSessionId=null,this.onSessionSwitch=e.onSessionSwitch||null,this.terminateSignal=e.terminateSignal||"CODEV_TERMINATE_SIGNAL"}handleSessionSwitch(e){if(!e)return A&&console.warn("Received empty session ID"),!1;let t=this.previousSessionId!==null&&this.previousSessionId!==e;return t&&(A&&console.log(`Session switch detected: ${this.previousSessionId} -> ${e}`),this.onSessionSwitch&&this.onSessionSwitch({type:this.terminateSignal,reason:"User switch session",agent:"claude",previousSessionId:this.previousSessionId,newSessionId:e})),this.previousSessionId=this.currentSessionId,this.currentSessionId=e,t}getCurrentSessionId(){return this.currentSessionId}getPreviousSessionId(){return this.previousSessionId}hasActiveSession(){return!!this.currentSessionId}terminateCurrentSession(e="Session terminated",t=null,s=null){if(!this.hasActiveSession())return A&&console.log("No active session to terminate"),null;let o={type:this.terminateSignal,reason:s?`terminated by signal: ${s}`:e,code:t,signal:s,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId};return A&&console.log("Terminating session:",o),this.previousSessionId=null,this.currentSessionId=null,o}createErrorTermination(e){return this.hasActiveSession()?{type:this.terminateSignal,error:e.message,stack:e.stack,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId}:null}reset(){A&&console.log("Resetting session manager"),this.currentSessionId=null,this.previousSessionId=null}setSessionSwitchCallback(e){this.onSessionSwitch=e}getSessionInfo(){return{currentSessionId:this.currentSessionId,previousSessionId:this.previousSessionId,hasActiveSession:this.hasActiveSession()}}};Ae.exports=j});var Ue=m((ps,qe)=>{var k=require("fs"),P=require("path"),Pt=require("events"),Dt=require("crypto"),w=process.env.CODEV_DEBUG==="True",J=class extends Pt{constructor(e={}){super(),this.watchPaths=e.watchPaths||[],this.excludePatterns=e.excludePatterns||[/node_modules/,/\.git/,/\.DS_Store/,/\.tmp/,/\.log$/,/\.swp$/,/codev\.log/],this.includePatterns=e.includePatterns||[/\.(js|jsx|ts|tsx|py|java|c|cpp|h|hpp|go|rs|rb|php|html|css|scss|sass|less|json|xml|yaml|yml|md|txt)$/],this.watchers=new Map,this.isWatching=!1,this.debounceTimeout=e.debounceTimeout||300,this.pendingChanges=new Map,this.fileContentHashes=new Map,this.enableContentComparison=e.enableContentComparison!==!1,this.onFileChange=e.onFileChange||null}calculateFileHash(e){try{let t=k.readFileSync(e,"utf8");return Dt.createHash("sha256").update(t).digest("hex")}catch{return null}}hasContentChanged(e){if(!this.enableContentComparison)return!0;let t=this.calculateFileHash(e),s=this.fileContentHashes.get(e);return t===null?s!==void 0?(this.fileContentHashes.delete(e),!0):!1:s===void 0||t!==s?(this.fileContentHashes.set(e,t),!0):!1}preloadFileHashes(e){if(!(!this.enableContentComparison||!k.existsSync(e)))try{let t=k.readdirSync(e,{withFileTypes:!0});for(let s of t){let o=P.join(e,s.name);s.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):s.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(t){w&&console.warn(`Failed to preload hashes for ${e}:`,t.message)}}shouldExcludeDirectory(e){let t=e.replace(/\\/g,"/");for(let s of this.excludePatterns)if(s.test(t)||s.test(P.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){w&&console.log("FileWatchService is already watching");return}let t=e||this.watchPaths;if(t.length===0){w&&console.log("No watch paths specified");return}this.isWatching=!0;for(let s of t)this.enableContentComparison&&this.preloadFileHashes(s),this.watchDirectory(s);w&&(console.log(`FileWatchService started watching ${t.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,t]of this.watchers)try{t.close(),w&&console.log(`Stopped watching: ${e}`)}catch(s){w&&console.error(`Error stopping watcher for ${e}:`,s.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),w&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!k.existsSync(e)){w&&console.warn(`Watch path does not exist: ${e}`);return}if(!k.statSync(e).isDirectory()){w&&console.warn(`Watch path is not a directory: ${e}`);return}try{let s=k.watch(e,{recursive:!0,persistent:!1},(o,n)=>{if(!n)return;let i=P.join(e,n);this.handleFileChange(o,i,e)});this.watchers.set(e,s),w&&console.log(`Started watching directory: ${e}`),s.on("error",o=>{w&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(s){w&&console.error(`Failed to start watching ${e}:`,s.message)}}handleFileChange(e,t,s){if(!this.shouldWatchFile(t))return;let o=`${e}:${t}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,t,s)},this.debounceTimeout))}processFileChange(e,t,s){if(!this.isWatching)return;let o="modified",n=!1;try{k.statSync(t),n=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(n&&(o==="modified"||o==="created")&&!this.hasContentChanged(t)){w&&console.log(`Ignoring false change for: ${P.relative(s,t)}`);return}!n&&o==="deleted"&&this.fileContentHashes.delete(t);let i={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:t,relativePath:P.relative(s,t),watchPath:s,fileExists:n,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(w&&console.log(`File ${o}: ${i.data.relativePath}`),this.emit("fileChange",i),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(i)}catch(a){w&&console.error("Error in file change callback:",a.message)}}shouldWatchFile(e){let t=P.basename(e),s=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(s)||o.test(t))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(s)||o.test(t))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let t=this.watchPaths.indexOf(e);if(t>-1&&(this.watchPaths.splice(t,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),w&&console.log(`Removed watch path: ${e}`)}catch(s){w&&console.error(`Error removing watch path ${e}:`,s.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};qe.exports=J});var Me=m((ys,Fe)=>{var Tt=F(),At=require("path"),ws=require("fs"),Ss=require("os"),Ot=xe(),qt=ke(),Ut=Te(),Ft=Oe(),Mt=Ue(),p=process.env.CODEV_DEBUG==="True",Q=class extends Tt{constructor(){super({configDir:".",configFile:".claude.json",defaultModel:"Claude Sonnet 4.5",executablePaths:["cc.mjs","/tmp/claude-code/package/cc.mjs"],environmentVariables:e=>({ANTHROPIC_BASE_URL:`${e}/claude`,ANTHROPIC_API_KEY:"codev",DISABLE_TELEMETRY:!0,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,CODEV_SERVER:e,CLAUDE_CODE_ATTRIBUTION_HEADER:"0"}),defaultConfig:{numStartups:1,installMethod:"unknown",autoUpdates:!1,theme:"Coder Dark",customApiKeyResponses:{approved:["codev"]},shiftEnterKeyBindingInstalled:!0,hasCompletedOnboarding:!0,subscriptionNoticeCount:0,hasAvailableSubscription:!0,projects:{}}}),this.fileWatchService=null,this.shutdownInProgress=!1,this.initializeServices()}initializeServices(){this.httpClient=new qt({timeout:1e4}),this.authService=new Ut({validateCredentials:!1}),this.sessionManager=new Ft({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new Ot({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return At.join(e,this.config.configDir,".claude","settings.json")}initializeFileWatchService(){if(!process.env.SESSION_ID){p&&console.log("FileWatchService disabled: SESSION_ID environment variable not found");return}try{this.fileWatchService=new Mt({watchPaths:this.getFileWatchPaths(),onFileChange:e=>this.handleFileChange(e),debounceTimeout:300}),p&&console.log("FileWatchService initialized with SESSION_ID:",process.env.SESSION_ID)}catch(e){p&&console.error("Failed to initialize FileWatchService:",e.message)}}getFileWatchPaths(){let e=[],t=process.cwd();e.push(t);let s=process.env.CODEV_WATCH_PATHS;if(s){let o=s.split(",").map(n=>n.trim());e.push(...o)}return e}handleFileChange(e){if(p&&console.log("File change detected:",e.data.relativePath),this.shutdownInProgress)return;let t={message:e,sessionId:e.data.sessionId||process.env.SESSION_ID};this.messageQueue.enqueue(t)}startFileWatching(){this.fileWatchService&&!this.fileWatchService.isWatching&&(this.fileWatchService.startWatching(),p&&console.log("File watching started"))}stopFileWatching(){this.fileWatchService&&this.fileWatchService.isWatching&&(this.fileWatchService.stopWatching(),p&&console.log("File watching stopped"))}onChildMessage(e){e&&e.type==="claude:send-msg"&&this.handleClaudeSendMessage(e.data),super.onChildMessage(e)}handleClaudeSendMessage(e){if(p&&console.log("Handling claude:send-msg message:",e),!e||typeof e!="object"){console.error(`handleClaudeSendMessage: Invalid message data. Expected object, got: ${typeof e}`);return}if(this.shutdownInProgress){p&&console.log("Shutdown in progress, ignoring new message");return}let t=e.sessionId||process.env.SESSION_ID;this.sessionManager.handleSessionSwitch(t),this.messageQueue.enqueue(e)}async processMessage(e){let t=e.data.message,s=e.data.sessionId||process.env.SESSION_ID;if(!s)throw new Error("No session ID available");let o;try{o=typeof t=="string"?JSON.parse(t):t}catch(a){throw new Error(`Failed to parse message data: ${a.message}`)}let n=`/conversations/${s}/@append?task_type=codev`,i=this.authService.hasCredentials()?this.authService.generateAuthHeaders(`${this.httpClient.baseUrl}${n}`,o):{};p&&(console.debug("Sending message to:",n),console.debug("Send Message: ",JSON.stringify(o))),e.type!=="CODEV_TERMINATE_SIGNAL"&&(this.sessionManager.currentSessionId=s)}sendTerminationMessage(e){let t={message:e,sessionId:e.sessionId||this.sessionManager.getCurrentSessionId()};this.messageQueue.enqueue(t)}async handleChildProcessExit(e,t){p&&console.log(`Child process exited with code: ${e}, signal: ${t}`),this.stopFileWatching();let s=this.messageQueue.getQueueSize(),o=this.sessionManager.terminateCurrentSession("process exited normally",e,t);if(o&&this.sendTerminationMessage(o),s>0||o){p&&console.log("Starting graceful shutdown of message queue...");try{let n=!t||t==="SIGTERM",i=this.messageQueue.getQueueSize(),a={timeoutMs:n?8e3:3e3,batchSize:Math.min(i,15),fastMode:!n||i>30};p&&console.log("Shutdown options:",a);let r=await this.messageQueue.gracefulShutdown(a);p&&console.log("Message queue shutdown completed:",r),r.failedMessages>0&&p&&console.warn(`Shutdown summary: ${r.processedMessages} sent, ${r.failedMessages} failed, ${r.remainingMessages} remaining`)}catch(n){p&&console.error("Error during message queue shutdown:",n.message)}}}handleChildProcessError(e){p&&console.error(`Child process error: ${e.message}`);let t=this.sessionManager.createErrorTermination(e);t&&this.sendTerminationMessage(t)}async forceFlushMessages(e=3e3){if(this.messageQueue.getQueueSize()===0)return{success:!0,message:"No messages to flush"};p&&console.log(`Force flushing ${this.messageQueue.getQueueSize()} messages...`);try{return await this.messageQueue.forceFlushAndShutdown(e)}catch(t){return p&&console.error("Force flush failed:",t.message),{success:!1,error:t.message}}}async launch(e={}){let{codevServer:t,auth_ak:s=null,auth_sk:o=null}=e;return this.httpClient.setBaseUrl(t),s&&o&&this.authService.setCredentials(s,o),this.startFileWatching(),super.launch(e)}};Fe.exports=Q});var Le=m((Es,Be)=>{var Bt=F(),Cs=require("path"),Y=class extends Bt{constructor(){super({configDir:".gemini",configFile:"settings.json",defaultModel:"gemini-2.5-pro",executablePaths:["gemini/gemini.js","../dist/gemini/gemini.js"],environmentVariables:e=>({GOOGLE_GEMINI_BASE_URL:`${e}/gemini`,GEMINI_API_KEY:"coder",GOOGLE_API_KEY:"coder",GOOGLE_CLOUD_PROJECT:"coder",GOOGLE_CLOUD_LOCATION:"coder",DISABLE_TELEMETRY:!0,GEMINI_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,USE_VERTEX:!0}),defaultConfig:{ide:{hasSeenNudge:!0},telemetry:{enabled:!1,logPrompts:!1},privacy:{usageStatisticsEnabled:!1},general:{disableUpdateNag:!0,preferredEditor:"vscode",previewFeatures:!0},ui:{hideBanner:!0,theme:"Default"},security:{auth:{selectedType:"vertex-ai"}}}})}};Be.exports=Y});var Ne=m((vs,Re)=>{var Lt=F(),O=require("path"),x=require("fs"),Rt=require("os"),{spawn:Nt}=require("child_process"),M=process.env.CODEV_DEBUG==="True",Z=class extends Lt{constructor(){super({configDir:".codex",configFile:"config.toml",defaultModel:"o4-mini",executablePaths:["codex.mjs","../dist/codex.mjs"],environmentVariables:e=>({OPENAI_BASE_URL:`${e}/codex`,OPENAI_API_KEY:"codev-proxy-key",DEBUG:M?"true":"false",CODEX_QUIET_MODE:"0",OPENAI_DISABLE_TELEMETRY:"true",CODEX_DISABLE_PROJECT_DOC:"0",CODEV_SERVER:e}),defaultConfig:{model:"gpt-5-codex",approvalMode:"suggest",fullAutoErrorMode:"ask-user",notify:[],history:{maxSize:1e3,saveHistory:!0,sensitivePatterns:[],persistence:"save-all"}}})}checkCodexAvailability(){try{let e=this.findExecutablePath();return x.existsSync(e)}catch{return!1}}resloveSettingFilePath(e){return O.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,t=0){let s=O.join(Rt.homedir(),this.config.configDir,this.config.configFile),o=O.dirname(s);try{x.existsSync(o)||x.mkdirSync(o,{recursive:!0});let n=`${e}/codex`;if(x.existsSync(s)){let i=x.readFileSync(s,"utf8"),a=`openai_base_url = "${n}"`;/^openai_base_url\s*=/m.test(i)?i=i.replace(/^openai_base_url\s*=.*/m,a):i=i.trimEnd()+`
|
|
202
|
+
Terminating ...`),u.kill("SIGTERM"),setTimeout(()=>{u.killed||u.kill("SIGKILL")},8e3)})})}catch(i){throw i}}};Ee.exports=H});var xe=m((hs,ve)=>{var f=process.env.CODEV_DEBUG==="True",G=class{constructor(e={}){this.queue=[],this.processing=!1,this.shuttingDown=!1,this.shutdownTimeout=e.shutdownTimeout||5e3,this.maxRetries=e.maxRetries||3,this.retryDelay=e.retryDelay||1e3,this.onProcessMessage=e.onProcessMessage||null,this.shutdownPromise=null,this.currentlyProcessing=null}enqueue(e){if(this.shuttingDown)return f&&console.log("Queue is shutting down, skipping new messages"),null;let t={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(t),f&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),t.id}dequeue(){let e=this.queue.shift();return f&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let t=this.queue.findIndex(s=>s.id===e);return t>-1?(this.queue.splice(t,1),f&&console.log(`Message ${e} removed from queue`),!0):!1}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{for(;this.queue.length>0&&!this.shuttingDown;){let e=this.queue[0];e.processing=!0;try{this.onProcessMessage&&await this.onProcessMessage(e),this.dequeue()}catch(t){if(f&&console.error(`Failed to process message: ${t.message}`),e.retryCount++,f&&console.log("Start Retry:",e.retryCount,"times..."),e.retryCount>=this.maxRetries)f&&console.error("Message exceeded max retries, removing from queue"),this.dequeue();else{e.processing=!1;let s=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,s))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],f&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let t=this.queue.filter(o=>o.processing);if(t.length===0)return;f&&console.log(`Waiting for ${t.length} processing messages to complete (timeout: ${e}ms)`);let s=Date.now();for(;Date.now()-s<e;){if(this.queue.filter(n=>n.processing).length===0){f&&console.log(`All processing messages completed in ${Date.now()-s}ms`);return}await new Promise(n=>setTimeout(n,50))}if(f){let o=this.queue.filter(n=>n.processing);console.log(`Timeout waiting for processing messages. ${o.length} messages still processing`)}}async gracefulShutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let{timeoutMs:t=this.shutdownTimeout,batchSize:s=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async n=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(t*.3,3e3));let i=this.queue.filter(g=>!g.processing),a=i.length;f&&(console.log(`Starting graceful shutdown with ${a} pending messages (${this.queue.length-a} already processing)`),console.log(`Mode: ${o?"fast (parallel)":"sequential"}, timeout: ${t}ms`));let r=Date.now(),c=0,l=0;try{if(o){let g=await this.processAllParallel(t-(Date.now()-r),i);c=g.processed,l=g.failed}else{let g=await this.processInBatches(s,t-(Date.now()-r),i);c=g.processed,l=g.failed}}catch(g){f&&console.error("Error during shutdown processing:",g.message)}let h=Date.now()-r,u=this.queue.length;f&&(console.log(`Shutdown completed in ${h}ms:`),console.log(` - Total: ${a} messages`),console.log(` - Processed: ${c}`),console.log(` - Failed: ${l}`),console.log(` - Remaining: ${u}`)),n({totalMessages:a,processedMessages:c,failedMessages:l,remainingMessages:u,duration:h,allMessagesSent:u===0&&l===0})}),this.shutdownPromise}async processAllParallel(e){if(this.queue.length===0)return{processed:0,failed:0};f&&console.log(`Processing ${this.queue.length} messages in parallel...`);let t=[...this.queue];this.queue=[];let s=t.map(async r=>{try{return this.onProcessMessage&&await this.onProcessMessage(r),{success:!0,messageId:r.id}}catch(c){return f&&console.warn(`Message ${r.id} processing failed: ${c.message}`),{success:!1,messageId:r.id,error:c}}}),o=new Promise(r=>{setTimeout(()=>r({timedOut:!0}),e)}),n=await Promise.race([Promise.allSettled(s).then(r=>({results:r})),o]);if(n.timedOut)return f&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:t.length};let i=n.results.filter(r=>r.status==="fulfilled"&&r.value?.success).length,a=t.length-i;return{processed:i,failed:a}}async processInBatches(e,t){if(this.queue.length===0)return{processed:0,failed:0};f&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let s=Date.now(),o=0,n=0;for(;this.queue.length>0&&Date.now()-s<t;){let i=this.queue.splice(0,e),a=i.map(async h=>{try{return this.onProcessMessage&&await this.onProcessMessage(h),{success:!0}}catch(u){return f&&console.warn(`Batch message processing failed: ${u.message}`),{success:!1,error:u}}}),c=(await Promise.allSettled(a)).filter(h=>h.status==="fulfilled"&&h.value?.success).length,l=i.length-c;o+=c,n+=l,f&&i.length>0&&console.log(`Batch completed: ${c}/${i.length} successful`),this.queue.length>0&&await new Promise(h=>setTimeout(h,10))}return this.queue.length>0&&(n+=this.queue.length,f&&console.log(`${this.queue.length} messages not processed due to timeout`),this.queue=[]),{processed:o,failed:n}}async forceFlushAndShutdown(e=2e3){this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(e*.4,1e3));let t=this.queue.filter(r=>!r.processing);f&&console.log(`Force flush: attempting to send ${t.length} pending messages within ${e}ms (${this.queue.length-t.length} already processing)`);let s=Date.now(),o=t.map(async r=>{try{return this.onProcessMessage&&Date.now()-s<e?(await this.onProcessMessage(r),{success:!0,messageId:r.id}):{success:!1,messageId:r.id,reason:"timeout"}}catch(c){return{success:!1,messageId:r.id,error:c.message}}}),n=e-(Date.now()-s),i=new Promise(r=>{setTimeout(()=>r({timedOut:!0}),Math.max(100,n))}),a=await Promise.race([Promise.allSettled(o).then(r=>({results:r})),i]);if(t.forEach(r=>{let c=this.queue.findIndex(l=>l.id===r.id);c>-1&&this.queue.splice(c,1)}),this.processing=!1,a.timedOut)return f&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:t.length};{let r=a.results.filter(c=>c.status==="fulfilled"&&c.value.success).length;return f&&console.log(`Force flush completed: ${r}/${t.length} messages sent`),{success:r===t.length,successCount:r,totalCount:t.length,results:a.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,f&&console.log("Force shutdown: Queue cleared")}};ve.exports=G});var V=m((us,vt)=>{vt.exports={name:"makecoder",version:"2.0.72",description:"MakeCoder: Unified AI agent CLI tool integrating Claude Code, Codex and Gemini CLI",main:"./dist/coder.js",bin:{coder:"./dist/coder.js"},scripts:{test:'echo "Error: no test specified" && exit 1',start:"node ./src/coder.js",build:"node scripts/build.js","build:clean":"node scripts/build.js --clean","build:dev":"node scripts/build.js --no-minify --sourcemap",postinstall:"node scripts/postinstall.js"},keywords:["cli","ai","claude","gemini","codex","agent"],author:"makecoder",license:"MIT",dependencies:{"node-fetch":"^3.3.2",open:"^10.1.0",zod:"^3.25.76"},optionalDependencies:{"makecoder-codex-linux-x64":"*","makecoder-codex-darwin-arm64":"*","makecoder-codex-win32-x64":"*"},engines:{node:">=20.0.0"},devDependencies:{chokidar:"^4.0.3"},files:["dist","claude","scripts/postinstall.js"]}});var ke=m((ds,Ie)=>{var xt=require("http"),_t=require("https"),{URL:_e}=require("url"),{version:bt}=V(),be=process.env.CODEV_DEBUG==="True",K=class{constructor(e={}){this.baseUrl=e.baseUrl||"",this.timeout=e.timeout||3e4,this.defaultHeaders={"Content-Type":"application/json","User-Agent":`codev-cli/${bt}`,...e.headers}}setBaseUrl(e){this.baseUrl=e}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}async post(e,t,s={}){let o=this.resolveUrl(e),n={...this.defaultHeaders,...s.headers};return new Promise((i,a)=>{this.validateRequest(o,t,a);let r=this.serializeData(t,a);if(!r)return;n["Content-Length"]=Buffer.byteLength(r);let c=this.buildRequestOptions(o,"POST",n),l=this.getHttpModule(o);be&&console.debug(`HTTP POST to ${o} with data length: ${r.length}`);let h=l.request(c,u=>{this.handleResponse(u,i,a)});this.attachErrorHandlers(h,o,a),h.setTimeout(this.timeout),h.write(r),h.end()})}resolveUrl(e){return e.startsWith("http")?e:`${this.baseUrl}${e.startsWith("/")?"":"/"}${e}`}validateRequest(e,t,s){return!e||typeof e!="string"?(s(new Error(`Invalid URL: ${e}`)),!1):t?!0:(s(new Error("No data provided for HTTP POST")),!1)}serializeData(e,t){try{return typeof e=="string"?e:JSON.stringify(e)}catch(s){return t(new Error(`Failed to serialize data: ${s.message}`)),null}}buildRequestOptions(e,t,s){let o=new _e(e),n=o.protocol==="https:";return{hostname:o.hostname,port:o.port||(n?443:80),path:o.pathname+o.search,method:t,headers:s}}getHttpModule(e){return new _e(e).protocol==="https:"?_t:xt}handleResponse(e,t,s){be&&console.debug(`HTTP response status: ${e.statusCode}`);let o="";e.on("data",n=>{o+=n}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?t({statusCode:e.statusCode,data:o,headers:e.headers}):s(new Error(`HTTP request returned status ${e.statusCode}: ${o}`))})}attachErrorHandlers(e,t,s){e.on("error",o=>{s(new Error(`HTTP POST request failed: ${o.message}`))}),e.on("timeout",()=>{s(new Error(`HTTP POST request timed out for URL: ${t}`)),e.destroy()})}};Ie.exports=K});var Pe=m((gs,$e)=>{var It=require("crypto"),{URL:kt}=require("url"),W=class{static generateSignature(e,t,s,o){try{let n=new kt(e),i=Buffer.from(n.pathname),a=Buffer.from(i),r=t?typeof t=="string"?Buffer.from(t):Buffer.from(JSON.stringify(t)):Buffer.alloc(0),c=Buffer.concat([a,r,Buffer.from(o)]),l=It.createHmac("sha256",s);return l.update(c),l.digest("hex")}catch(n){throw new Error(`Failed to generate signature: ${n.message}`)}}static validateSignature(e,t,s,o,n){return this.generateSignature(e,t,s,o)===n}static generateTimestamp(){return Date.now().toString()}};$e.exports=W});var Te=m((fs,De)=>{var $t=Pe(),z=class{constructor(e={}){this.accessKey=null,this.secretKey=null,this.validateCredentials=e.validateCredentials!==!1}setCredentials(e,t){if(this.validateCredentials&&(!e||!t))throw new Error("Both access key and secret key are required");this.accessKey=e,this.secretKey=t}hasCredentials(){return!!(this.accessKey&&this.secretKey)}generateAuthHeaders(e,t=null){if(!this.hasCredentials())return{};try{return{AUTHORIZATION:`Bearer ${this.accessKey}.${this.secretKey}`}}catch(s){throw new Error(`Failed to generate auth headers: ${s.message}`)}}validateAuthHeaders(e,t,s,o){if(!this.hasCredentials())throw new Error("No credentials available for validation");return $t.validateSignature(e,t,this.secretKey,s,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};De.exports=z});var Oe=m((ms,Ae)=>{var A=process.env.CODEV_DEBUG==="True",j=class{constructor(e={}){this.currentSessionId=null,this.previousSessionId=null,this.onSessionSwitch=e.onSessionSwitch||null,this.terminateSignal=e.terminateSignal||"CODEV_TERMINATE_SIGNAL"}handleSessionSwitch(e){if(!e)return A&&console.warn("Received empty session ID"),!1;let t=this.previousSessionId!==null&&this.previousSessionId!==e;return t&&(A&&console.log(`Session switch detected: ${this.previousSessionId} -> ${e}`),this.onSessionSwitch&&this.onSessionSwitch({type:this.terminateSignal,reason:"User switch session",agent:"claude",previousSessionId:this.previousSessionId,newSessionId:e})),this.previousSessionId=this.currentSessionId,this.currentSessionId=e,t}getCurrentSessionId(){return this.currentSessionId}getPreviousSessionId(){return this.previousSessionId}hasActiveSession(){return!!this.currentSessionId}terminateCurrentSession(e="Session terminated",t=null,s=null){if(!this.hasActiveSession())return A&&console.log("No active session to terminate"),null;let o={type:this.terminateSignal,reason:s?`terminated by signal: ${s}`:e,code:t,signal:s,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId};return A&&console.log("Terminating session:",o),this.previousSessionId=null,this.currentSessionId=null,o}createErrorTermination(e){return this.hasActiveSession()?{type:this.terminateSignal,error:e.message,stack:e.stack,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId}:null}reset(){A&&console.log("Resetting session manager"),this.currentSessionId=null,this.previousSessionId=null}setSessionSwitchCallback(e){this.onSessionSwitch=e}getSessionInfo(){return{currentSessionId:this.currentSessionId,previousSessionId:this.previousSessionId,hasActiveSession:this.hasActiveSession()}}};Ae.exports=j});var Ue=m((ps,qe)=>{var k=require("fs"),P=require("path"),Pt=require("events"),Dt=require("crypto"),w=process.env.CODEV_DEBUG==="True",J=class extends Pt{constructor(e={}){super(),this.watchPaths=e.watchPaths||[],this.excludePatterns=e.excludePatterns||[/node_modules/,/\.git/,/\.DS_Store/,/\.tmp/,/\.log$/,/\.swp$/,/codev\.log/],this.includePatterns=e.includePatterns||[/\.(js|jsx|ts|tsx|py|java|c|cpp|h|hpp|go|rs|rb|php|html|css|scss|sass|less|json|xml|yaml|yml|md|txt)$/],this.watchers=new Map,this.isWatching=!1,this.debounceTimeout=e.debounceTimeout||300,this.pendingChanges=new Map,this.fileContentHashes=new Map,this.enableContentComparison=e.enableContentComparison!==!1,this.onFileChange=e.onFileChange||null}calculateFileHash(e){try{let t=k.readFileSync(e,"utf8");return Dt.createHash("sha256").update(t).digest("hex")}catch{return null}}hasContentChanged(e){if(!this.enableContentComparison)return!0;let t=this.calculateFileHash(e),s=this.fileContentHashes.get(e);return t===null?s!==void 0?(this.fileContentHashes.delete(e),!0):!1:s===void 0||t!==s?(this.fileContentHashes.set(e,t),!0):!1}preloadFileHashes(e){if(!(!this.enableContentComparison||!k.existsSync(e)))try{let t=k.readdirSync(e,{withFileTypes:!0});for(let s of t){let o=P.join(e,s.name);s.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):s.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(t){w&&console.warn(`Failed to preload hashes for ${e}:`,t.message)}}shouldExcludeDirectory(e){let t=e.replace(/\\/g,"/");for(let s of this.excludePatterns)if(s.test(t)||s.test(P.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){w&&console.log("FileWatchService is already watching");return}let t=e||this.watchPaths;if(t.length===0){w&&console.log("No watch paths specified");return}this.isWatching=!0;for(let s of t)this.enableContentComparison&&this.preloadFileHashes(s),this.watchDirectory(s);w&&(console.log(`FileWatchService started watching ${t.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,t]of this.watchers)try{t.close(),w&&console.log(`Stopped watching: ${e}`)}catch(s){w&&console.error(`Error stopping watcher for ${e}:`,s.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),w&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!k.existsSync(e)){w&&console.warn(`Watch path does not exist: ${e}`);return}if(!k.statSync(e).isDirectory()){w&&console.warn(`Watch path is not a directory: ${e}`);return}try{let s=k.watch(e,{recursive:!0,persistent:!1},(o,n)=>{if(!n)return;let i=P.join(e,n);this.handleFileChange(o,i,e)});this.watchers.set(e,s),w&&console.log(`Started watching directory: ${e}`),s.on("error",o=>{w&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(s){w&&console.error(`Failed to start watching ${e}:`,s.message)}}handleFileChange(e,t,s){if(!this.shouldWatchFile(t))return;let o=`${e}:${t}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,t,s)},this.debounceTimeout))}processFileChange(e,t,s){if(!this.isWatching)return;let o="modified",n=!1;try{k.statSync(t),n=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(n&&(o==="modified"||o==="created")&&!this.hasContentChanged(t)){w&&console.log(`Ignoring false change for: ${P.relative(s,t)}`);return}!n&&o==="deleted"&&this.fileContentHashes.delete(t);let i={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:t,relativePath:P.relative(s,t),watchPath:s,fileExists:n,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(w&&console.log(`File ${o}: ${i.data.relativePath}`),this.emit("fileChange",i),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(i)}catch(a){w&&console.error("Error in file change callback:",a.message)}}shouldWatchFile(e){let t=P.basename(e),s=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(s)||o.test(t))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(s)||o.test(t))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let t=this.watchPaths.indexOf(e);if(t>-1&&(this.watchPaths.splice(t,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),w&&console.log(`Removed watch path: ${e}`)}catch(s){w&&console.error(`Error removing watch path ${e}:`,s.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};qe.exports=J});var Me=m((ys,Fe)=>{var Tt=F(),At=require("path"),ws=require("fs"),Ss=require("os"),Ot=xe(),qt=ke(),Ut=Te(),Ft=Oe(),Mt=Ue(),p=process.env.CODEV_DEBUG==="True",Q=class extends Tt{constructor(){super({configDir:".",configFile:".claude.json",defaultModel:"Claude Sonnet 4.5",executablePaths:["cc.mjs","/tmp/claude-code/package/cc.mjs"],environmentVariables:e=>({ANTHROPIC_BASE_URL:`${e}/claude`,ANTHROPIC_API_KEY:"codev",DISABLE_TELEMETRY:!0,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,CODEV_SERVER:e,CLAUDE_CODE_ATTRIBUTION_HEADER:"0"}),defaultConfig:{numStartups:1,installMethod:"unknown",autoUpdates:!1,theme:"Coder Dark",customApiKeyResponses:{approved:["codev"]},shiftEnterKeyBindingInstalled:!0,hasCompletedOnboarding:!0,subscriptionNoticeCount:0,hasAvailableSubscription:!0,projects:{}}}),this.fileWatchService=null,this.shutdownInProgress=!1,this.initializeServices()}initializeServices(){this.httpClient=new qt({timeout:1e4}),this.authService=new Ut({validateCredentials:!1}),this.sessionManager=new Ft({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new Ot({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return At.join(e,this.config.configDir,".claude","settings.json")}initializeFileWatchService(){if(!process.env.SESSION_ID){p&&console.log("FileWatchService disabled: SESSION_ID environment variable not found");return}try{this.fileWatchService=new Mt({watchPaths:this.getFileWatchPaths(),onFileChange:e=>this.handleFileChange(e),debounceTimeout:300}),p&&console.log("FileWatchService initialized with SESSION_ID:",process.env.SESSION_ID)}catch(e){p&&console.error("Failed to initialize FileWatchService:",e.message)}}getFileWatchPaths(){let e=[],t=process.cwd();e.push(t);let s=process.env.CODEV_WATCH_PATHS;if(s){let o=s.split(",").map(n=>n.trim());e.push(...o)}return e}handleFileChange(e){if(p&&console.log("File change detected:",e.data.relativePath),this.shutdownInProgress)return;let t={message:e,sessionId:e.data.sessionId||process.env.SESSION_ID};this.messageQueue.enqueue(t)}startFileWatching(){this.fileWatchService&&!this.fileWatchService.isWatching&&(this.fileWatchService.startWatching(),p&&console.log("File watching started"))}stopFileWatching(){this.fileWatchService&&this.fileWatchService.isWatching&&(this.fileWatchService.stopWatching(),p&&console.log("File watching stopped"))}onChildMessage(e){e&&e.type==="claude:send-msg"&&this.handleClaudeSendMessage(e.data),super.onChildMessage(e)}handleClaudeSendMessage(e){if(p&&console.log("Handling claude:send-msg message:",e),!e||typeof e!="object"){console.error(`handleClaudeSendMessage: Invalid message data. Expected object, got: ${typeof e}`);return}if(this.shutdownInProgress){p&&console.log("Shutdown in progress, ignoring new message");return}let t=e.sessionId||process.env.SESSION_ID;this.sessionManager.handleSessionSwitch(t),this.messageQueue.enqueue(e)}async processMessage(e){let t=e.data.message,s=e.data.sessionId||process.env.SESSION_ID;if(!s)throw new Error("No session ID available");let o;try{o=typeof t=="string"?JSON.parse(t):t}catch(a){throw new Error(`Failed to parse message data: ${a.message}`)}let n=`/conversations/${s}/@append?task_type=codev`,i=this.authService.hasCredentials()?this.authService.generateAuthHeaders(`${this.httpClient.baseUrl}${n}`,o):{};p&&(console.debug("Sending message to:",n),console.debug("Send Message: ",JSON.stringify(o))),e.type!=="CODEV_TERMINATE_SIGNAL"&&(this.sessionManager.currentSessionId=s)}sendTerminationMessage(e){let t={message:e,sessionId:e.sessionId||this.sessionManager.getCurrentSessionId()};this.messageQueue.enqueue(t)}async handleChildProcessExit(e,t){p&&console.log(`Child process exited with code: ${e}, signal: ${t}`),this.stopFileWatching();let s=this.messageQueue.getQueueSize(),o=this.sessionManager.terminateCurrentSession("process exited normally",e,t);if(o&&this.sendTerminationMessage(o),s>0||o){p&&console.log("Starting graceful shutdown of message queue...");try{let n=!t||t==="SIGTERM",i=this.messageQueue.getQueueSize(),a={timeoutMs:n?8e3:3e3,batchSize:Math.min(i,15),fastMode:!n||i>30};p&&console.log("Shutdown options:",a);let r=await this.messageQueue.gracefulShutdown(a);p&&console.log("Message queue shutdown completed:",r),r.failedMessages>0&&p&&console.warn(`Shutdown summary: ${r.processedMessages} sent, ${r.failedMessages} failed, ${r.remainingMessages} remaining`)}catch(n){p&&console.error("Error during message queue shutdown:",n.message)}}}handleChildProcessError(e){p&&console.error(`Child process error: ${e.message}`);let t=this.sessionManager.createErrorTermination(e);t&&this.sendTerminationMessage(t)}async forceFlushMessages(e=3e3){if(this.messageQueue.getQueueSize()===0)return{success:!0,message:"No messages to flush"};p&&console.log(`Force flushing ${this.messageQueue.getQueueSize()} messages...`);try{return await this.messageQueue.forceFlushAndShutdown(e)}catch(t){return p&&console.error("Force flush failed:",t.message),{success:!1,error:t.message}}}async launch(e={}){let{codevServer:t,auth_ak:s=null,auth_sk:o=null}=e;return this.httpClient.setBaseUrl(t),s&&o&&this.authService.setCredentials(s,o),this.startFileWatching(),super.launch(e)}};Fe.exports=Q});var Le=m((Es,Be)=>{var Bt=F(),Cs=require("path"),Y=class extends Bt{constructor(){super({configDir:".gemini",configFile:"settings.json",defaultModel:"gemini-2.5-pro",executablePaths:["gemini/gemini.js","../dist/gemini/gemini.js"],environmentVariables:e=>({GOOGLE_GEMINI_BASE_URL:`${e}/gemini`,GEMINI_API_KEY:"coder",GOOGLE_API_KEY:"coder",GOOGLE_CLOUD_PROJECT:"coder",GOOGLE_CLOUD_LOCATION:"coder",DISABLE_TELEMETRY:!0,GEMINI_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,USE_VERTEX:!0}),defaultConfig:{ide:{hasSeenNudge:!0},telemetry:{enabled:!1,logPrompts:!1},privacy:{usageStatisticsEnabled:!1},general:{disableUpdateNag:!0,preferredEditor:"vscode",previewFeatures:!0},ui:{hideBanner:!0,theme:"Default"},security:{auth:{selectedType:"vertex-ai"}}}})}};Be.exports=Y});var Ne=m((vs,Re)=>{var Lt=F(),O=require("path"),x=require("fs"),Rt=require("os"),{spawn:Nt}=require("child_process"),M=process.env.CODEV_DEBUG==="True",Z=class extends Lt{constructor(){super({configDir:".codex",configFile:"config.toml",defaultModel:"o4-mini",executablePaths:["codex.mjs","../dist/codex.mjs"],environmentVariables:e=>({OPENAI_BASE_URL:`${e}/codex`,OPENAI_API_KEY:"codev-proxy-key",DEBUG:M?"true":"false",CODEX_QUIET_MODE:"0",OPENAI_DISABLE_TELEMETRY:"true",CODEX_DISABLE_PROJECT_DOC:"0",CODEV_SERVER:e}),defaultConfig:{model:"gpt-5-codex",approvalMode:"suggest",fullAutoErrorMode:"ask-user",notify:[],history:{maxSize:1e3,saveHistory:!0,sensitivePatterns:[],persistence:"save-all"}}})}checkCodexAvailability(){try{let e=this.findExecutablePath();return x.existsSync(e)}catch{return!1}}resloveSettingFilePath(e){return O.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,t=0){let s=O.join(Rt.homedir(),this.config.configDir,this.config.configFile),o=O.dirname(s);try{x.existsSync(o)||x.mkdirSync(o,{recursive:!0});let n=`${e}/codex`;if(x.existsSync(s)){let i=x.readFileSync(s,"utf8"),a=`openai_base_url = "${n}"`;/^openai_base_url\s*=/m.test(i)?i=i.replace(/^openai_base_url\s*=.*/m,a):i=i.trimEnd()+`
|
|
203
203
|
`+a+`
|
|
204
204
|
`,x.writeFileSync(s,i),M&&console.log(`Updated openai_base_url in ${s}`)}else{let i=this.config.defaultConfig||{},a=this.generateTOMLConfig(i,n);x.writeFileSync(s,a),M&&console.log(`Created Codex config file: ${s}`)}t>0&&await new Promise(i=>setTimeout(i,t))}catch(n){console.warn(`Failed to update ${this.config.configFile}: ${n.message}`)}}generateTOMLConfig(e,t){return`model = "${e.model||"gpt-5-codex"}"
|
|
205
205
|
openai_base_url = "${t}"
|
|
@@ -991,7 +991,7 @@ ${s}
|
|
|
991
991
|
|
|
992
992
|
... [${u.toLocaleString()} characters omitted] ...
|
|
993
993
|
|
|
994
|
-
${c}`}var kEr="tool-outputs";async function s3(t,e,r,n,o){let s=Cp(e).toLowerCase(),c=Cp(r.toString()).toLowerCase(),u=c.startsWith(s)?`${c}.txt`:`${s}_${c}.txt`,d=qu.join(n,kEr);if(o){let a=Cp(o);d=qu.join(d,`session-${a}`)}let l=qu.join(d,u);return await g2.mkdir(d,{recursive:!0}),await g2.writeFile(l,t),{outputFile:l}}var mh=["run_shell_command","ShellTool"];async function oZe(t){if(Zge.isAbsolute(t))try{return await Tq.promises.access(t,Tq.constants.X_OK),t}catch{return}let e=(process.env.PATH||"").split(Zge.delimiter),r=tZe.platform()==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of e)for(let o of r){let s=Zge.join(n,t+o);try{return await Tq.promises.access(s,Tq.constants.X_OK),s}catch{continue}}}var qv=null,wq=null,y2=null,Cq=class extends Error{constructor(e){super(`Failed to initialize bash parser: ${e.message}`,{cause:e}),this.name="ShellParserInitializationError"}};function LEr(t){return t instanceof Error?t:typeof t=="string"?new Error(t):new Error("Unknown tree-sitter initialization error",{cause:t})}async function MEr(){try{y2=null;let[t,e]=await Promise.all([Jge(()=>import("./tree-sitter-
|
|
994
|
+
${c}`}var kEr="tool-outputs";async function s3(t,e,r,n,o){let s=Cp(e).toLowerCase(),c=Cp(r.toString()).toLowerCase(),u=c.startsWith(s)?`${c}.txt`:`${s}_${c}.txt`,d=qu.join(n,kEr);if(o){let a=Cp(o);d=qu.join(d,`session-${a}`)}let l=qu.join(d,u);return await g2.mkdir(d,{recursive:!0}),await g2.writeFile(l,t),{outputFile:l}}var mh=["run_shell_command","ShellTool"];async function oZe(t){if(Zge.isAbsolute(t))try{return await Tq.promises.access(t,Tq.constants.X_OK),t}catch{return}let e=(process.env.PATH||"").split(Zge.delimiter),r=tZe.platform()==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of e)for(let o of r){let s=Zge.join(n,t+o);try{return await Tq.promises.access(s,Tq.constants.X_OK),s}catch{continue}}}var qv=null,wq=null,y2=null,Cq=class extends Error{constructor(e){super(`Failed to initialize bash parser: ${e.message}`,{cause:e}),this.name="ShellParserInitializationError"}};function LEr(t){return t instanceof Error?t:typeof t=="string"?new Error(t):new Error("Unknown tree-sitter initialization error",{cause:t})}async function MEr(){try{y2=null;let[t,e]=await Promise.all([Jge(()=>import("./tree-sitter-JU2EI3Z2.js"),"web-tree-sitter/tree-sitter.wasm"),Jge(()=>import("./tree-sitter-bash-IAB7XJEE.js"),"tree-sitter-bash/tree-sitter-bash.wasm")]);await Hge.init({wasmBinary:t}),qv=await $ge.load(e)}catch(t){qv=null;let e=LEr(t),r=e instanceof Cq?e:new Cq(e);throw y2=r,r}}async function yh(){wq||(wq=MEr().catch(t=>{wq=null,U.debug("Failed to initialize shell parsers:",t)})),await wq}var sZe="__GCLI_POWERSHELL_COMMAND__",BEr=1e3*1e3,UEr=Buffer.from(`
|
|
995
995
|
$ErrorActionPreference = 'Stop'
|
|
996
996
|
$commandText = $env:${sZe}
|
|
997
997
|
if ([string]::IsNullOrEmpty($commandText)) {
|
|
@@ -2839,7 +2839,7 @@ When adding a memory, route it to the right store:
|
|
|
2839
2839
|
# Insufficient context
|
|
2840
2840
|
If you find that you have insufficient context to read or modify the memories as described,
|
|
2841
2841
|
reply with what you need, and exit. Do not search the codebase for the missing context.
|
|
2842
|
-
`.trim();return{kind:"local",name:"save_memory",displayName:"Memory Manager",description:"Writes and reads memory, preferences or facts across ALL future sessions. Use this for recurring instructions like coding styles or tool aliases.",inputConfig:{inputSchema:{type:"object",properties:{request:{type:"string",description:'The memory operation to perform. Examples: "Remember that I prefer tabs over spaces", "Clean up stale memories", "De-duplicate my memories", "Organize my memories".'}},required:["request"]}},outputConfig:{outputName:"result",description:"A summary of the memory operations performed.",schema:l_i},modelConfig:{model:s2},toolConfig:{tools:[ki,Hl,$l,l2,Vl,Ni,qo]},get promptConfig(){return{systemPrompt:n(),query:`${r()}\${request}`}},runConfig:{maxTimeMinutes:5,maxTurns:10}}};var Xf=class t{static MAX_AUTH_RETRIES=2;authRetryCount=0;async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403)return this.authRetryCount>=t.MAX_AUTH_RETRIES?void 0:(this.authRetryCount++,this.headers());this.authRetryCount=0}async initialize(){}};var tpr=6e4;async function Yb(t){if(t.startsWith("$$")||t.startsWith("!!"))return t.slice(1);if(t.startsWith("$")){let e=t.slice(1),r=process.env[e];if(r===void 0||r==="")throw new Error(`Environment variable '${e}' is not set or is empty. Please set it before using this agent.`);return U.debug(`[AuthValueResolver] Resolved env var: ${e}`),r}if(t.startsWith("!")){let e=t.slice(1).trim();if(!e)throw new Error("Empty command in auth value. Expected format: !command");U.debug("[AuthValueResolver] Executing command for auth value");let r=$A();try{let{stdout:n}=await xp(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(tpr),windowsHide:!0}),o=n.trim();if(!o)throw new Error(`Command '${e}' returned empty output`);return o}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Command '${e}' timed out after ${tpr/1e3} seconds`):n}}return t}function rpr(t){return t.startsWith("$")||t.startsWith("!")}var c_i="X-API-Key",Ode=class extends Xf{config;type="apiKey";resolvedKey;headerName;constructor(e){super(),this.config=e,this.headerName=e.name??c_i}async initialize(){rpr(this.config.key)?(this.resolvedKey=await Yb(this.config.key),U.debug(`[ApiKeyAuthProvider] Resolved API key from: ${this.config.key.startsWith("$")?"env var":"command"}`)):this.resolvedKey=this.config.key}async headers(){if(!this.resolvedKey)throw new Error("ApiKeyAuthProvider not initialized. Call initialize() first.");return{[this.headerName]:this.resolvedKey}}async shouldRetryWithHeaders(e,r){if(r.status!==401&&r.status!==403){this.authRetryCount=0;return}if(!(!this.config.key.startsWith("!")||this.config.key.startsWith("!!"))&&!(this.authRetryCount>=Xf.MAX_AUTH_RETRIES))return this.authRetryCount++,U.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await Yb(this.config.key),this.headers()}};var Ide=class extends Xf{config;type="http";resolvedToken;resolvedUsername;resolvedPassword;resolvedValue;constructor(e){super(),this.config=e}async initialize(){let e=this.config;"token"in e?this.resolvedToken=await Yb(e.token):"username"in e?(this.resolvedUsername=await Yb(e.username),this.resolvedPassword=await Yb(e.password)):this.resolvedValue=await Yb(e.value),U.debug(`[HttpAuthProvider] Initialized with scheme: ${this.config.scheme}`)}async headers(){let e=this.config;if("token"in e){if(!this.resolvedToken)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Bearer ${this.resolvedToken}`}}if("username"in e){if(!this.resolvedUsername||!this.resolvedPassword)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Basic ${Buffer.from(`${this.resolvedUsername}:${this.resolvedPassword}`).toString("base64")}`}}if(!this.resolvedValue)throw new Error("HttpAuthProvider not initialized");return{Authorization:`${e.scheme} ${this.resolvedValue}`}}async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403){if(this.authRetryCount>=Xf.MAX_AUTH_RETRIES)return;U.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(e,r)}};var npr=qe(ds(),1);var LC=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},Hk=5*60*1e3,Ls=class{static buildWellKnownUrls(e,r=!1){let n=new URL(e),o=`${n.protocol}//${n.host}`,s=r?"":n.pathname.replace(/\/$/,"");return{protectedResource:new URL(`/.well-known/oauth-protected-resource${s}`,o).toString(),authorizationServer:new URL(`/.well-known/oauth-authorization-server${s}`,o).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return U.debug(`Failed to fetch protected resource metadata from ${e}: ${Te(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return U.debug(`Failed to fetch authorization server metadata from ${e}: ${Te(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,issuer:e.issuer,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[],registrationUrl:e.registration_endpoint}}static async discoverAuthorizationServerMetadata(e){let r=new URL(e),n=`${r.protocol}//${r.host}`,o=[];r.pathname!=="/"&&(o.push(new URL(`/.well-known/oauth-authorization-server${r.pathname}`,n).toString()),o.push(new URL(`/.well-known/openid-configuration${r.pathname}`,n).toString()),o.push(new URL(`${r.pathname}/.well-known/openid-configuration`,n).toString())),o.push(new URL("/.well-known/oauth-authorization-server",n).toString()),o.push(new URL("/.well-known/openid-configuration",n).toString());for(let s of o){let c=await this.fetchAuthorizationServerMetadata(s);if(c)return c}return U.debug(`Metadata discovery failed for authorization server ${e}`),null}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(!n){let s=new URL(e);if(s.pathname&&s.pathname!=="/"){let c=this.buildWellKnownUrls(e,!0);n=await this.fetchProtectedResourceMetadata(c.protectedResource)}}if(n){let s=this.buildResourceParameter(e);if(!this.isEquivalentResourceIdentifier(n.resource,s))throw new LC(`Protected resource ${n.resource} does not match expected ${s}`)}if(n?.authorization_servers?.length){let s=n.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);if(c){let u=this.metadataToOAuthConfig(c);return c.registration_endpoint&&U.log("Dynamic client registration is supported at:",c.registration_endpoint),u}}U.debug(`Trying OAuth discovery fallback at ${e}`);let o=await this.discoverAuthorizationServerMetadata(e);if(o){let s=this.metadataToOAuthConfig(o);return o.registration_endpoint&&U.log("Dynamic client registration is supported at:",o.registration_endpoint),s}return null}catch(r){if(r instanceof LC)throw r;return U.debug(`Failed to discover OAuth configuration: ${Te(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e,r){let n=this.parseWWWAuthenticateHeader(e);if(!n)return null;let o=await this.fetchProtectedResourceMetadata(n);if(o&&r){let u=this.buildResourceParameter(r);if(!this.isEquivalentResourceIdentifier(o.resource,u))throw new LC(`Protected resource ${o.resource} does not match expected ${u}`)}if(!o?.authorization_servers?.length)return null;let s=o.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);return c?this.metadataToOAuthConfig(c):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}${r.pathname}`}static isEquivalentResourceIdentifier(e,r){let n=o=>{try{return this.buildResourceParameter(o)}catch{return o}};return n(e)===n(r)}static parseTokenExpiry(e){try{let r=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString());if(r&&typeof r.exp=="number")return r.exp*1e3}catch(r){U.error("Failed to parse ID token for expiry time with error:",r)}}};var ipr=/^(.*\.)?run\.app$/,u_i=[/^.+\.googleapis\.com$/,ipr],Rde=class extends Xf{config;type="google-credentials";auth;useIdToken=!1;audience;cachedToken;tokenExpiryTime;constructor(e,r){if(super(),this.config=e,!r)throw new Error("targetUrl must be provided to GoogleCredentialsAuthProvider to determine token audience.");let n=new URL(r).hostname;if(ipr.test(n)&&(this.useIdToken=!0),this.audience=n,!this.useIdToken&&!u_i.some(c=>c.test(n)))throw new Error(`Host "${n}" is not an allowed host for Google Credential provider.`);let s=this.config.scopes&&this.config.scopes.length>0?this.config.scopes:["https://www.googleapis.com/auth/cloud-platform"];this.auth=new npr.GoogleAuth({scopes:s})}async initialize(){}async headers(){if(this.cachedToken&&this.tokenExpiryTime&&Date.now()<this.tokenExpiryTime-Hk)return{Authorization:`Bearer ${this.cachedToken}`};if(this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.useIdToken)try{let r=await(await this.auth.getIdTokenClient(this.audience)).idTokenProvider.fetchIdToken(this.audience),n=Ls.parseTokenExpiry(r);return n&&(this.tokenExpiryTime=n,this.cachedToken=r),{Authorization:`Bearer ${r}`}}catch(e){let r=`Failed to get ADC ID token: ${e instanceof Error?e.message:String(e)}`;throw U.error(r,e),new Error(r)}try{let e=await this.auth.getClient(),r=await e.getAccessToken();if(r.token){this.cachedToken=r.token;let n=e.credentials;return n.expiry_date&&(this.tokenExpiryTime=n.expiry_date),{Authorization:`Bearer ${r.token}`}}throw new Error("Failed to retrieve ADC access token.")}catch(e){let r=`Failed to get ADC access token: ${e instanceof Error?e.message:String(e)}`;throw U.error(r,e),new Error(r)}}async shouldRetryWithHeaders(e,r){if(r.status!==401&&r.status!==403){this.authRetryCount=0;return}if(!(this.authRetryCount>=Xf.MAX_AUTH_RETRIES))return this.authRetryCount++,U.debug("[GoogleCredentialsAuthProvider] Re-fetching token after auth failure"),this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.headers()}};var Jb=class t{static async create(e){let{agentName:r,authConfig:n,agentCard:o}=e;if(!n)return o?.securitySchemes&&Object.keys(o.securitySchemes).length>0,void 0;switch(n.type){case"google-credentials":{let s=new Rde(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new Ode(n);return await s.initialize(),s}case"http":{let s=new Ide(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-KNMGGRK6.js"),c=new s(n,e.agentName??"unknown",o,e.agentCardUrl);return await c.initialize(),c}case"openIdConnect":throw new Error("openIdConnect auth provider not yet implemented");default:{let s=n;throw new Error(`Unknown auth type: ${s.type}`)}}}static async createFromConfig(e,r){return await t.create({authConfig:e,agentName:r})}static validateAuthConfig(e,r){if(!r||Object.keys(r).length===0)return{valid:!0};let n=Object.keys(r);if(!e)return{valid:!1,diff:{requiredSchemes:n,configuredType:void 0,missingConfig:["Authentication is required but not configured"]}};let o=t.findMatchingScheme(e,r);return o.matched?{valid:!0}:{valid:!1,diff:{requiredSchemes:n,configuredType:e.type,missingConfig:o.missingConfig}}}static findMatchingScheme(e,r){let n=[];for(let[o,s]of Object.entries(r))switch(s.type){case"apiKey":if(e.type==="apiKey")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires apiKey authentication`);break;case"http":if(e.type==="http"){if(e.scheme.toLowerCase()===s.scheme.toLowerCase())return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication, but ${e.scheme} was configured`)}else{if(e.type==="google-credentials"&&s.scheme.toLowerCase()==="bearer")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication`)}break;case"oauth2":if(e.type==="oauth2")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OAuth 2.0 authentication`);break;case"openIdConnect":if(e.type==="openIdConnect")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OpenID Connect authentication`);break;case"mutualTLS":n.push(`Scheme '${o}' requires mTLS authentication (not yet supported)`);break;default:{let c=s;n.push(`Unknown security scheme type: ${c.type}`)}}return{matched:!1,missingConfig:n}}static describeRequiredAuth(e){let r=[];for(let[n,o]of Object.entries(e))switch(o.type){case"apiKey":r.push(`API Key (${n}): Send ${o.name} in ${o.in}`);break;case"http":r.push(`HTTP ${o.scheme} (${n})`);break;case"oauth2":r.push(`OAuth 2.0 (${n})`);break;case"openIdConnect":r.push(`OpenID Connect (${n})`);break;case"mutualTLS":r.push(`Mutual TLS (${n})`);break;default:{let s=o;r.push(`Unknown (${n}): ${s.type}`)}}return r.join(" OR ")}};var Qm=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},KVe=class extends Qm{constructor(e,r){let n=`Agent card not found at ${r} (HTTP 404)`,o=`Agent card not found (404) at ${r}. Verify the agent_card_url in your agent definition.`;super(e,n,o),this.name="AgentCardNotFoundError"}},Pde=class extends Qm{statusCode;constructor(e,r,n){let o=n===401?"Unauthorized":"Forbidden",s=`Agent card request returned ${n} ${o} for ${r}`,c=`Authentication failed (${n} ${o}) at ${r}. Check the "auth" configuration in your agent definition.`;super(e,s,c),this.name="AgentCardAuthError",this.statusCode=n}},Nde=class extends Qm{requiredAuth;missingFields;constructor(e,r,n){let o=`Agent "${e}" requires authentication but none is configured`,s=`Agent requires ${r} but no auth is configured. Missing: ${n.join(", ")}`;super(e,o,s),this.name="AgentAuthConfigMissingError",this.requiredAuth=r,this.missingFields=n}},kde=class extends Qm{constructor(e,r,n){let o=n instanceof Error?n.message:String(n),s=`Failed to connect to agent "${e}" at ${r}: ${o}`,c=`Connection failed for ${r}: ${o}`;super(e,s,c,{cause:n}),this.name="AgentConnectionError"}};function d_i(t){return typeof t=="object"&&t!==null}function p_i(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(d_i(r)){let s=r;r instanceof Error?e.push(r.message):typeof s.message=="string"&&e.push(s.message),typeof s.code=="string"&&e.push(s.code),typeof s.status=="number"?e.push(String(s.status)):typeof s.statusCode=="number"&&e.push(String(s.statusCode)),r=s.cause}else if(typeof r=="string"){e.push(r);break}else{e.push(String(r));break}n++}return e.join(" ")}function opr(t,e,r){let n=p_i(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new kde(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new KVe(t,e):/\b401\b|unauthorized/i.test(n)?new Pde(t,e,401):/\b403\b|forbidden/i.test(n)?new Pde(t,e,403):new kde(t,e,r)}function XVe(t){return`${t.name}-config`}var Dde=class{config;agents=new Map;allDefinitions=new Map;builtInAgents=new Set;constructor(e){this.config=e}async initialize(){be.on(Nr.ModelChanged,this.onModelChanged),await this.loadAgents()}isBuiltIn(e){return this.builtInAgents.has(e)}onModelChanged=()=>{this.refreshAgents("local").catch(e=>{U.error("[AgentRegistry] Failed to refresh agents on model change:",e)})};async reload(){this.config.getA2AClientManager()?.clearCache(),await this.config.reloadAgents(),this.agents.clear(),this.allDefinitions.clear(),await this.loadAgents(),be.emitAgentsRefreshed()}async acknowledgeAgent(e){let r=this.config.getAcknowledgedAgentsService(),n=this.config.getProjectRoot();e.metadata?.hash&&(await r.acknowledge(n,e.name,e.metadata.hash),await this.registerAgent(e),be.emitAgentsRefreshed())}dispose(){be.off(Nr.ModelChanged,this.onModelChanged)}async loadAgents(){if(this.agents.clear(),this.allDefinitions.clear(),this.loadBuiltInAgents(),!this.config.isAgentsEnabled())return;let e=dr.getUserAgentsDir(),r=await WVe(e);for(let s of r.errors)U.warn(`[AgentRegistry] Error loading user agent: ${s.message}`),be.emitFeedback("error",`Agent loading error: ${s.message}`);await Promise.allSettled(r.agents.map(async s=>{try{await this.registerAgent(s)}catch(c){U.warn(`[AgentRegistry] Error registering user agent "${s.name}":`,c),be.emitFeedback("error",`Error registering user agent "${s.name}": ${c instanceof Error?c.message:String(c)}`)}}));let n=this.config.getFolderTrust(),o=this.config.isTrustedFolder();if(!n||o){let s=this.config.storage.getProjectAgentsDir(),c=await WVe(s);for(let p of c.errors)be.emitFeedback("error",`Agent loading error: ${p.message}`);let u=this.config.getAcknowledgedAgentsService(),d=this.config.getProjectRoot(),l=[],a=[];for(let p of c.agents){if(p.kind==="remote"&&(p.metadata||(p.metadata={}),p.metadata.hash=p.agentCardUrl??(p.agentCardJson?spr.createHash("sha256").update(p.agentCardJson).digest("hex"):void 0)),!p.metadata?.hash){a.push(p);continue}await u.isAcknowledged(d,p.name,p.metadata.hash)?a.push(p):l.push(p)}l.length>0&&be.emitAgentsDiscovered(l),await Promise.allSettled(a.map(async p=>{try{await this.registerAgent(p)}catch(f){U.warn(`[AgentRegistry] Error registering project agent "${p.name}":`,f),be.emitFeedback("error",`Error registering project agent "${p.name}": ${f instanceof Error?f.message:String(f)}`)}}))}else be.emitFeedback("info","Skipping project agents due to untrusted folder. To enable, ensure that the project root is trusted.");for(let s of this.config.getExtensions())s.isActive&&s.agents&&await Promise.allSettled(s.agents.map(async c=>{try{await this.registerAgent(c)}catch(u){U.warn(`[AgentRegistry] Error registering extension agent "${c.name}":`,u),be.emitFeedback("error",`Error registering extension agent "${c.name}": ${u instanceof Error?u.message:String(u)}`)}}));this.config.getDebugMode()&&U.log(`[AgentRegistry] Loaded with ${this.agents.size} agents.`)}loadBuiltInAgents(){let e=iue(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=Xdr(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=Zdr(this.config);if(this.builtInAgents.add(n.name),this.registerLocalAgent(n),this.config.getBrowserAgentConfig().enabled){let s=xde(this.config);this.builtInAgents.add(s.name),this.registerLocalAgent(s)}if(this.config.isMemoryManagerEnabled()){this.registerLocalAgent(epr(this.config));try{let s=dr.getGlobalGeminiDir();this.config.getWorkspaceContext().addDirectory(s)}catch(s){U.warn("[AgentRegistry] Could not add global .gemini directory to workspace:",s)}}}async refreshAgents(e="all"){this.loadBuiltInAgents(),await Promise.allSettled(Array.from(this.agents.values()).map(async r=>{(e==="all"||r.kind===e)&&await this.registerAgent(r)}))}async registerAgent(e){e.kind==="local"?this.registerLocalAgent(e):e.kind==="remote"&&await this.registerRemoteAgent(e)}registerLocalAgent(e){if(e.kind!=="local")return;if(!e.name||!e.description){U.warn("[AgentRegistry] Skipping invalid agent definition. Missing name or description.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&U.log(`[AgentRegistry] Skipping disabled agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&U.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=this.applyOverrides(e,r);this.agents.set(n.name,n),this.registerModelConfigs(n),this.addAgentPolicy(n)}addAgentPolicy(e){let r=this.config.getPolicyEngine();if(r){if(r.hasRuleForTool(e.name,!0)){this.config.getDebugMode()&&U.log(`[AgentRegistry] User policy exists for '${e.name}', skipping dynamic registration.`);return}r.removeRulesForTool(e.name,"AgentRegistry (Dynamic)"),r.addRule({toolName:e.name,decision:e.kind==="local"?ot.ALLOW:ot.ASK_USER,priority:NQ,source:"AgentRegistry (Dynamic)"})}}isAgentEnabled(e,r){let o=!(e.experimental===!0);return r&&r.enabled!==void 0&&(o=r.enabled),o}async registerRemoteAgent(e){if(e.kind!=="remote")return;if(!e.name){U.warn("[AgentRegistry] Skipping invalid agent definition. Missing name.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&U.log(`[AgentRegistry] Skipping disabled remote agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&U.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=e;n.originalDescription===void 0&&(n.originalDescription=n.description);try{let o=this.config.getA2AClientManager();if(!o){U.warn(`[AgentRegistry] Skipping remote agent '${e.name}': A2AClientManager is not available.`);return}let s=yde(n),c;if(e.auth){let p=await Jb.create({authConfig:e.auth,agentName:e.name,targetUrl:s,agentCardUrl:n.agentCardUrl});if(!p)throw new Error(`Failed to create auth provider for agent '${e.name}'`);c=p}let u=await o.loadAgent(n.name,mde(n),c);if(u.securitySchemes){let p=Jb.validateAuthConfig(e.auth,u.securitySchemes);if(!p.valid&&p.diff){let f=Jb.describeRequiredAuth(u.securitySchemes),g=new Nde(e.name,f,p.diff.missingConfig);be.emitFeedback("warning",`[${e.name}] Agent requires authentication: ${f}`),U.warn(`[AgentRegistry] ${g.message}`)}}let d=n.originalDescription,l=u.description,a=[];if(d?.trim()&&a.push(`User Description: ${d.trim()}`),l?.trim()&&a.push(`Agent Description: ${l.trim()}`),u.skills&&u.skills.length>0){let p=u.skills.map(f=>`${f.name}: ${f.description||"No description provided"}`).join(`
|
|
2842
|
+
`.trim();return{kind:"local",name:"save_memory",displayName:"Memory Manager",description:"Writes and reads memory, preferences or facts across ALL future sessions. Use this for recurring instructions like coding styles or tool aliases.",inputConfig:{inputSchema:{type:"object",properties:{request:{type:"string",description:'The memory operation to perform. Examples: "Remember that I prefer tabs over spaces", "Clean up stale memories", "De-duplicate my memories", "Organize my memories".'}},required:["request"]}},outputConfig:{outputName:"result",description:"A summary of the memory operations performed.",schema:l_i},modelConfig:{model:s2},toolConfig:{tools:[ki,Hl,$l,l2,Vl,Ni,qo]},get promptConfig(){return{systemPrompt:n(),query:`${r()}\${request}`}},runConfig:{maxTimeMinutes:5,maxTurns:10}}};var Xf=class t{static MAX_AUTH_RETRIES=2;authRetryCount=0;async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403)return this.authRetryCount>=t.MAX_AUTH_RETRIES?void 0:(this.authRetryCount++,this.headers());this.authRetryCount=0}async initialize(){}};var tpr=6e4;async function Yb(t){if(t.startsWith("$$")||t.startsWith("!!"))return t.slice(1);if(t.startsWith("$")){let e=t.slice(1),r=process.env[e];if(r===void 0||r==="")throw new Error(`Environment variable '${e}' is not set or is empty. Please set it before using this agent.`);return U.debug(`[AuthValueResolver] Resolved env var: ${e}`),r}if(t.startsWith("!")){let e=t.slice(1).trim();if(!e)throw new Error("Empty command in auth value. Expected format: !command");U.debug("[AuthValueResolver] Executing command for auth value");let r=$A();try{let{stdout:n}=await xp(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(tpr),windowsHide:!0}),o=n.trim();if(!o)throw new Error(`Command '${e}' returned empty output`);return o}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Command '${e}' timed out after ${tpr/1e3} seconds`):n}}return t}function rpr(t){return t.startsWith("$")||t.startsWith("!")}var c_i="X-API-Key",Ode=class extends Xf{config;type="apiKey";resolvedKey;headerName;constructor(e){super(),this.config=e,this.headerName=e.name??c_i}async initialize(){rpr(this.config.key)?(this.resolvedKey=await Yb(this.config.key),U.debug(`[ApiKeyAuthProvider] Resolved API key from: ${this.config.key.startsWith("$")?"env var":"command"}`)):this.resolvedKey=this.config.key}async headers(){if(!this.resolvedKey)throw new Error("ApiKeyAuthProvider not initialized. Call initialize() first.");return{[this.headerName]:this.resolvedKey}}async shouldRetryWithHeaders(e,r){if(r.status!==401&&r.status!==403){this.authRetryCount=0;return}if(!(!this.config.key.startsWith("!")||this.config.key.startsWith("!!"))&&!(this.authRetryCount>=Xf.MAX_AUTH_RETRIES))return this.authRetryCount++,U.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await Yb(this.config.key),this.headers()}};var Ide=class extends Xf{config;type="http";resolvedToken;resolvedUsername;resolvedPassword;resolvedValue;constructor(e){super(),this.config=e}async initialize(){let e=this.config;"token"in e?this.resolvedToken=await Yb(e.token):"username"in e?(this.resolvedUsername=await Yb(e.username),this.resolvedPassword=await Yb(e.password)):this.resolvedValue=await Yb(e.value),U.debug(`[HttpAuthProvider] Initialized with scheme: ${this.config.scheme}`)}async headers(){let e=this.config;if("token"in e){if(!this.resolvedToken)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Bearer ${this.resolvedToken}`}}if("username"in e){if(!this.resolvedUsername||!this.resolvedPassword)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Basic ${Buffer.from(`${this.resolvedUsername}:${this.resolvedPassword}`).toString("base64")}`}}if(!this.resolvedValue)throw new Error("HttpAuthProvider not initialized");return{Authorization:`${e.scheme} ${this.resolvedValue}`}}async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403){if(this.authRetryCount>=Xf.MAX_AUTH_RETRIES)return;U.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(e,r)}};var npr=qe(ds(),1);var LC=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},Hk=5*60*1e3,Ls=class{static buildWellKnownUrls(e,r=!1){let n=new URL(e),o=`${n.protocol}//${n.host}`,s=r?"":n.pathname.replace(/\/$/,"");return{protectedResource:new URL(`/.well-known/oauth-protected-resource${s}`,o).toString(),authorizationServer:new URL(`/.well-known/oauth-authorization-server${s}`,o).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return U.debug(`Failed to fetch protected resource metadata from ${e}: ${Te(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return U.debug(`Failed to fetch authorization server metadata from ${e}: ${Te(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,issuer:e.issuer,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[],registrationUrl:e.registration_endpoint}}static async discoverAuthorizationServerMetadata(e){let r=new URL(e),n=`${r.protocol}//${r.host}`,o=[];r.pathname!=="/"&&(o.push(new URL(`/.well-known/oauth-authorization-server${r.pathname}`,n).toString()),o.push(new URL(`/.well-known/openid-configuration${r.pathname}`,n).toString()),o.push(new URL(`${r.pathname}/.well-known/openid-configuration`,n).toString())),o.push(new URL("/.well-known/oauth-authorization-server",n).toString()),o.push(new URL("/.well-known/openid-configuration",n).toString());for(let s of o){let c=await this.fetchAuthorizationServerMetadata(s);if(c)return c}return U.debug(`Metadata discovery failed for authorization server ${e}`),null}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(!n){let s=new URL(e);if(s.pathname&&s.pathname!=="/"){let c=this.buildWellKnownUrls(e,!0);n=await this.fetchProtectedResourceMetadata(c.protectedResource)}}if(n){let s=this.buildResourceParameter(e);if(!this.isEquivalentResourceIdentifier(n.resource,s))throw new LC(`Protected resource ${n.resource} does not match expected ${s}`)}if(n?.authorization_servers?.length){let s=n.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);if(c){let u=this.metadataToOAuthConfig(c);return c.registration_endpoint&&U.log("Dynamic client registration is supported at:",c.registration_endpoint),u}}U.debug(`Trying OAuth discovery fallback at ${e}`);let o=await this.discoverAuthorizationServerMetadata(e);if(o){let s=this.metadataToOAuthConfig(o);return o.registration_endpoint&&U.log("Dynamic client registration is supported at:",o.registration_endpoint),s}return null}catch(r){if(r instanceof LC)throw r;return U.debug(`Failed to discover OAuth configuration: ${Te(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e,r){let n=this.parseWWWAuthenticateHeader(e);if(!n)return null;let o=await this.fetchProtectedResourceMetadata(n);if(o&&r){let u=this.buildResourceParameter(r);if(!this.isEquivalentResourceIdentifier(o.resource,u))throw new LC(`Protected resource ${o.resource} does not match expected ${u}`)}if(!o?.authorization_servers?.length)return null;let s=o.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);return c?this.metadataToOAuthConfig(c):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}${r.pathname}`}static isEquivalentResourceIdentifier(e,r){let n=o=>{try{return this.buildResourceParameter(o)}catch{return o}};return n(e)===n(r)}static parseTokenExpiry(e){try{let r=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString());if(r&&typeof r.exp=="number")return r.exp*1e3}catch(r){U.error("Failed to parse ID token for expiry time with error:",r)}}};var ipr=/^(.*\.)?run\.app$/,u_i=[/^.+\.googleapis\.com$/,ipr],Rde=class extends Xf{config;type="google-credentials";auth;useIdToken=!1;audience;cachedToken;tokenExpiryTime;constructor(e,r){if(super(),this.config=e,!r)throw new Error("targetUrl must be provided to GoogleCredentialsAuthProvider to determine token audience.");let n=new URL(r).hostname;if(ipr.test(n)&&(this.useIdToken=!0),this.audience=n,!this.useIdToken&&!u_i.some(c=>c.test(n)))throw new Error(`Host "${n}" is not an allowed host for Google Credential provider.`);let s=this.config.scopes&&this.config.scopes.length>0?this.config.scopes:["https://www.googleapis.com/auth/cloud-platform"];this.auth=new npr.GoogleAuth({scopes:s})}async initialize(){}async headers(){if(this.cachedToken&&this.tokenExpiryTime&&Date.now()<this.tokenExpiryTime-Hk)return{Authorization:`Bearer ${this.cachedToken}`};if(this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.useIdToken)try{let r=await(await this.auth.getIdTokenClient(this.audience)).idTokenProvider.fetchIdToken(this.audience),n=Ls.parseTokenExpiry(r);return n&&(this.tokenExpiryTime=n,this.cachedToken=r),{Authorization:`Bearer ${r}`}}catch(e){let r=`Failed to get ADC ID token: ${e instanceof Error?e.message:String(e)}`;throw U.error(r,e),new Error(r)}try{let e=await this.auth.getClient(),r=await e.getAccessToken();if(r.token){this.cachedToken=r.token;let n=e.credentials;return n.expiry_date&&(this.tokenExpiryTime=n.expiry_date),{Authorization:`Bearer ${r.token}`}}throw new Error("Failed to retrieve ADC access token.")}catch(e){let r=`Failed to get ADC access token: ${e instanceof Error?e.message:String(e)}`;throw U.error(r,e),new Error(r)}}async shouldRetryWithHeaders(e,r){if(r.status!==401&&r.status!==403){this.authRetryCount=0;return}if(!(this.authRetryCount>=Xf.MAX_AUTH_RETRIES))return this.authRetryCount++,U.debug("[GoogleCredentialsAuthProvider] Re-fetching token after auth failure"),this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.headers()}};var Jb=class t{static async create(e){let{agentName:r,authConfig:n,agentCard:o}=e;if(!n)return o?.securitySchemes&&Object.keys(o.securitySchemes).length>0,void 0;switch(n.type){case"google-credentials":{let s=new Rde(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new Ode(n);return await s.initialize(),s}case"http":{let s=new Ide(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-ZNP4J6EF.js"),c=new s(n,e.agentName??"unknown",o,e.agentCardUrl);return await c.initialize(),c}case"openIdConnect":throw new Error("openIdConnect auth provider not yet implemented");default:{let s=n;throw new Error(`Unknown auth type: ${s.type}`)}}}static async createFromConfig(e,r){return await t.create({authConfig:e,agentName:r})}static validateAuthConfig(e,r){if(!r||Object.keys(r).length===0)return{valid:!0};let n=Object.keys(r);if(!e)return{valid:!1,diff:{requiredSchemes:n,configuredType:void 0,missingConfig:["Authentication is required but not configured"]}};let o=t.findMatchingScheme(e,r);return o.matched?{valid:!0}:{valid:!1,diff:{requiredSchemes:n,configuredType:e.type,missingConfig:o.missingConfig}}}static findMatchingScheme(e,r){let n=[];for(let[o,s]of Object.entries(r))switch(s.type){case"apiKey":if(e.type==="apiKey")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires apiKey authentication`);break;case"http":if(e.type==="http"){if(e.scheme.toLowerCase()===s.scheme.toLowerCase())return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication, but ${e.scheme} was configured`)}else{if(e.type==="google-credentials"&&s.scheme.toLowerCase()==="bearer")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication`)}break;case"oauth2":if(e.type==="oauth2")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OAuth 2.0 authentication`);break;case"openIdConnect":if(e.type==="openIdConnect")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OpenID Connect authentication`);break;case"mutualTLS":n.push(`Scheme '${o}' requires mTLS authentication (not yet supported)`);break;default:{let c=s;n.push(`Unknown security scheme type: ${c.type}`)}}return{matched:!1,missingConfig:n}}static describeRequiredAuth(e){let r=[];for(let[n,o]of Object.entries(e))switch(o.type){case"apiKey":r.push(`API Key (${n}): Send ${o.name} in ${o.in}`);break;case"http":r.push(`HTTP ${o.scheme} (${n})`);break;case"oauth2":r.push(`OAuth 2.0 (${n})`);break;case"openIdConnect":r.push(`OpenID Connect (${n})`);break;case"mutualTLS":r.push(`Mutual TLS (${n})`);break;default:{let s=o;r.push(`Unknown (${n}): ${s.type}`)}}return r.join(" OR ")}};var Qm=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},KVe=class extends Qm{constructor(e,r){let n=`Agent card not found at ${r} (HTTP 404)`,o=`Agent card not found (404) at ${r}. Verify the agent_card_url in your agent definition.`;super(e,n,o),this.name="AgentCardNotFoundError"}},Pde=class extends Qm{statusCode;constructor(e,r,n){let o=n===401?"Unauthorized":"Forbidden",s=`Agent card request returned ${n} ${o} for ${r}`,c=`Authentication failed (${n} ${o}) at ${r}. Check the "auth" configuration in your agent definition.`;super(e,s,c),this.name="AgentCardAuthError",this.statusCode=n}},Nde=class extends Qm{requiredAuth;missingFields;constructor(e,r,n){let o=`Agent "${e}" requires authentication but none is configured`,s=`Agent requires ${r} but no auth is configured. Missing: ${n.join(", ")}`;super(e,o,s),this.name="AgentAuthConfigMissingError",this.requiredAuth=r,this.missingFields=n}},kde=class extends Qm{constructor(e,r,n){let o=n instanceof Error?n.message:String(n),s=`Failed to connect to agent "${e}" at ${r}: ${o}`,c=`Connection failed for ${r}: ${o}`;super(e,s,c,{cause:n}),this.name="AgentConnectionError"}};function d_i(t){return typeof t=="object"&&t!==null}function p_i(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(d_i(r)){let s=r;r instanceof Error?e.push(r.message):typeof s.message=="string"&&e.push(s.message),typeof s.code=="string"&&e.push(s.code),typeof s.status=="number"?e.push(String(s.status)):typeof s.statusCode=="number"&&e.push(String(s.statusCode)),r=s.cause}else if(typeof r=="string"){e.push(r);break}else{e.push(String(r));break}n++}return e.join(" ")}function opr(t,e,r){let n=p_i(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new kde(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new KVe(t,e):/\b401\b|unauthorized/i.test(n)?new Pde(t,e,401):/\b403\b|forbidden/i.test(n)?new Pde(t,e,403):new kde(t,e,r)}function XVe(t){return`${t.name}-config`}var Dde=class{config;agents=new Map;allDefinitions=new Map;builtInAgents=new Set;constructor(e){this.config=e}async initialize(){be.on(Nr.ModelChanged,this.onModelChanged),await this.loadAgents()}isBuiltIn(e){return this.builtInAgents.has(e)}onModelChanged=()=>{this.refreshAgents("local").catch(e=>{U.error("[AgentRegistry] Failed to refresh agents on model change:",e)})};async reload(){this.config.getA2AClientManager()?.clearCache(),await this.config.reloadAgents(),this.agents.clear(),this.allDefinitions.clear(),await this.loadAgents(),be.emitAgentsRefreshed()}async acknowledgeAgent(e){let r=this.config.getAcknowledgedAgentsService(),n=this.config.getProjectRoot();e.metadata?.hash&&(await r.acknowledge(n,e.name,e.metadata.hash),await this.registerAgent(e),be.emitAgentsRefreshed())}dispose(){be.off(Nr.ModelChanged,this.onModelChanged)}async loadAgents(){if(this.agents.clear(),this.allDefinitions.clear(),this.loadBuiltInAgents(),!this.config.isAgentsEnabled())return;let e=dr.getUserAgentsDir(),r=await WVe(e);for(let s of r.errors)U.warn(`[AgentRegistry] Error loading user agent: ${s.message}`),be.emitFeedback("error",`Agent loading error: ${s.message}`);await Promise.allSettled(r.agents.map(async s=>{try{await this.registerAgent(s)}catch(c){U.warn(`[AgentRegistry] Error registering user agent "${s.name}":`,c),be.emitFeedback("error",`Error registering user agent "${s.name}": ${c instanceof Error?c.message:String(c)}`)}}));let n=this.config.getFolderTrust(),o=this.config.isTrustedFolder();if(!n||o){let s=this.config.storage.getProjectAgentsDir(),c=await WVe(s);for(let p of c.errors)be.emitFeedback("error",`Agent loading error: ${p.message}`);let u=this.config.getAcknowledgedAgentsService(),d=this.config.getProjectRoot(),l=[],a=[];for(let p of c.agents){if(p.kind==="remote"&&(p.metadata||(p.metadata={}),p.metadata.hash=p.agentCardUrl??(p.agentCardJson?spr.createHash("sha256").update(p.agentCardJson).digest("hex"):void 0)),!p.metadata?.hash){a.push(p);continue}await u.isAcknowledged(d,p.name,p.metadata.hash)?a.push(p):l.push(p)}l.length>0&&be.emitAgentsDiscovered(l),await Promise.allSettled(a.map(async p=>{try{await this.registerAgent(p)}catch(f){U.warn(`[AgentRegistry] Error registering project agent "${p.name}":`,f),be.emitFeedback("error",`Error registering project agent "${p.name}": ${f instanceof Error?f.message:String(f)}`)}}))}else be.emitFeedback("info","Skipping project agents due to untrusted folder. To enable, ensure that the project root is trusted.");for(let s of this.config.getExtensions())s.isActive&&s.agents&&await Promise.allSettled(s.agents.map(async c=>{try{await this.registerAgent(c)}catch(u){U.warn(`[AgentRegistry] Error registering extension agent "${c.name}":`,u),be.emitFeedback("error",`Error registering extension agent "${c.name}": ${u instanceof Error?u.message:String(u)}`)}}));this.config.getDebugMode()&&U.log(`[AgentRegistry] Loaded with ${this.agents.size} agents.`)}loadBuiltInAgents(){let e=iue(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=Xdr(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=Zdr(this.config);if(this.builtInAgents.add(n.name),this.registerLocalAgent(n),this.config.getBrowserAgentConfig().enabled){let s=xde(this.config);this.builtInAgents.add(s.name),this.registerLocalAgent(s)}if(this.config.isMemoryManagerEnabled()){this.registerLocalAgent(epr(this.config));try{let s=dr.getGlobalGeminiDir();this.config.getWorkspaceContext().addDirectory(s)}catch(s){U.warn("[AgentRegistry] Could not add global .gemini directory to workspace:",s)}}}async refreshAgents(e="all"){this.loadBuiltInAgents(),await Promise.allSettled(Array.from(this.agents.values()).map(async r=>{(e==="all"||r.kind===e)&&await this.registerAgent(r)}))}async registerAgent(e){e.kind==="local"?this.registerLocalAgent(e):e.kind==="remote"&&await this.registerRemoteAgent(e)}registerLocalAgent(e){if(e.kind!=="local")return;if(!e.name||!e.description){U.warn("[AgentRegistry] Skipping invalid agent definition. Missing name or description.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&U.log(`[AgentRegistry] Skipping disabled agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&U.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=this.applyOverrides(e,r);this.agents.set(n.name,n),this.registerModelConfigs(n),this.addAgentPolicy(n)}addAgentPolicy(e){let r=this.config.getPolicyEngine();if(r){if(r.hasRuleForTool(e.name,!0)){this.config.getDebugMode()&&U.log(`[AgentRegistry] User policy exists for '${e.name}', skipping dynamic registration.`);return}r.removeRulesForTool(e.name,"AgentRegistry (Dynamic)"),r.addRule({toolName:e.name,decision:e.kind==="local"?ot.ALLOW:ot.ASK_USER,priority:NQ,source:"AgentRegistry (Dynamic)"})}}isAgentEnabled(e,r){let o=!(e.experimental===!0);return r&&r.enabled!==void 0&&(o=r.enabled),o}async registerRemoteAgent(e){if(e.kind!=="remote")return;if(!e.name){U.warn("[AgentRegistry] Skipping invalid agent definition. Missing name.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&U.log(`[AgentRegistry] Skipping disabled remote agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&U.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=e;n.originalDescription===void 0&&(n.originalDescription=n.description);try{let o=this.config.getA2AClientManager();if(!o){U.warn(`[AgentRegistry] Skipping remote agent '${e.name}': A2AClientManager is not available.`);return}let s=yde(n),c;if(e.auth){let p=await Jb.create({authConfig:e.auth,agentName:e.name,targetUrl:s,agentCardUrl:n.agentCardUrl});if(!p)throw new Error(`Failed to create auth provider for agent '${e.name}'`);c=p}let u=await o.loadAgent(n.name,mde(n),c);if(u.securitySchemes){let p=Jb.validateAuthConfig(e.auth,u.securitySchemes);if(!p.valid&&p.diff){let f=Jb.describeRequiredAuth(u.securitySchemes),g=new Nde(e.name,f,p.diff.missingConfig);be.emitFeedback("warning",`[${e.name}] Agent requires authentication: ${f}`),U.warn(`[AgentRegistry] ${g.message}`)}}let d=n.originalDescription,l=u.description,a=[];if(d?.trim()&&a.push(`User Description: ${d.trim()}`),l?.trim()&&a.push(`Agent Description: ${l.trim()}`),u.skills&&u.skills.length>0){let p=u.skills.map(f=>`${f.name}: ${f.description||"No description provided"}`).join(`
|
|
2843
2843
|
`);a.push(`Skills:
|
|
2844
2844
|
${p}`)}a.length>0&&(e.description=a.join(`
|
|
2845
2845
|
`)),this.config.getDebugMode()&&U.log(`[AgentRegistry] Registered remote agent '${e.name}' with card: ${e.agentCardUrl??"inline JSON"}`),this.agents.set(e.name,e),this.addAgentPolicy(e)}catch(o){o instanceof Qm?be.emitFeedback("error",`[${e.name}] ${o.userMessage}`):be.emitFeedback("error",`[${e.name}] Failed to load remote agent: ${o instanceof Error?o.message:String(o)}`),U.warn(`[AgentRegistry] Error loading A2A agent "${e.name}":`,o)}}applyOverrides(e,r){if(e.kind!=="local"||!r)return e;let n={get kind(){return e.kind},get name(){return e.name},get displayName(){return e.displayName},get description(){return e.description},get experimental(){return e.experimental},get metadata(){return e.metadata},get inputConfig(){return e.inputConfig},get outputConfig(){return e.outputConfig},get promptConfig(){return e.promptConfig},get toolConfig(){return e.toolConfig},get processOutput(){return e.processOutput},get runConfig(){return r.runConfig?{...e.runConfig,...r.runConfig}:e.runConfig},get modelConfig(){return r.modelConfig?Bk.merge(e.modelConfig,r.modelConfig):e.modelConfig}};return r.tools&&(n.toolConfig={tools:r.tools}),r.mcpServers&&(n.mcpServers={...e.mcpServers,...r.mcpServers}),n}registerModelConfigs(e){let r=e.modelConfig,n=r.model;n==="inherit"&&(n=this.config.getModel());let o={...r,model:n};this.config.modelConfigService.registerRuntimeModelConfig(XVe(e),{modelConfig:o}),o.model&&qs(o.model)&&this.config.modelConfigService.registerRuntimeModelOverride({match:{overrideScope:e.name},modelConfig:{generateContentConfig:o.generateContentConfig}})}getDefinition(e){return this.agents.get(e)}getAllDefinitions(){return Array.from(this.agents.values())}getAllAgentNames(){return Array.from(this.agents.keys())}getAllDiscoveredAgentNames(){return Array.from(this.allDefinitions.keys())}getDiscoveredDefinition(e){return this.allDefinitions.get(e)}};import*as zk from"node:fs/promises";import*as apr from"node:path";var Lde=class{acknowledgedAgents={};loaded=!1;async load(){if(this.loaded)return;let e=dr.getAcknowledgedAgentsPath();try{let r=await zk.readFile(e,"utf-8");this.acknowledgedAgents=JSON.parse(r)}catch(r){(!er(r)||r.code!=="ENOENT")&&U.error("Failed to load acknowledged agents:",Te(r)),this.acknowledgedAgents={}}this.loaded=!0}async save(){let e=dr.getAcknowledgedAgentsPath();try{let r=apr.dirname(e);await zk.mkdir(r,{recursive:!0}),await zk.writeFile(e,JSON.stringify(this.acknowledgedAgents,null,2),"utf-8")}catch(r){U.error("Failed to save acknowledged agents:",Te(r))}}async isAcknowledged(e,r,n){await this.load();let o=this.acknowledgedAgents[e];return o?o[r]===n:!1}async acknowledge(e,r,n){await this.load(),this.acknowledgedAgents[e]||(this.acknowledgedAgents[e]={}),this.acknowledgedAgents[e][r]=n,await this.save()}};function Mde(t,e){let r=/\$\{(\w+)\}/g,n=new Set(Array.from(t.matchAll(r),c=>c[1])),o=new Set(Object.keys(e)),s=Array.from(n).filter(c=>!o.has(c));if(s.length>0)throw new Error(`Template validation failed: Missing required input parameters: ${s.join(", ")}. Available inputs: ${Object.keys(e).join(", ")}`);return t.replace(r,(c,u)=>String(e[u]))}import{AsyncLocalStorage as f_i}from"node:async_hooks";var lpr=new f_i;function ZVe(t,e){return lpr.run(t,e)}function Bde(){return lpr.getStore()}var cpr=qe(mse(),1);function ij(t){return typeof t=="object"&&t!==null&&"callId"in t&&"responseParts"in t}function E6o(t){let{displayName:e,status:r,approvalMode:n,hasResultDisplay:o,parentCallId:s}=t;if(s)return!0;switch(e){case KD:switch(r){case Ue.Scheduled:case Ue.Validating:case Ue.Executing:case Ue.AwaitingApproval:return!0;case Ue.Error:return!o;default:return!1}case nq:case iq:return n===ar.PLAN;default:return!1}}function oj(t,e,r=3){let n=e.map(c=>({name:c,distance:cpr.default.get(t,c)}));n.sort((c,u)=>c.distance-u.distance);let o=n.slice(0,r);if(o.length===0)return"";let s=o.map(c=>`"${c.name}"`).join(", ");return o.length>1?` Did you mean one of: ${s}?`:` Did you mean ${s}?`}function b6o(t,e,r){let n;DQ(t)?n=[t.name,t.constructor.name]:n=[t],n.some(o=>mh.includes(o))&&(n=[...new Set([...n,...mh])]);for(let o of r){let s=o.indexOf("(");if(s===-1){if(n.includes(o))return!0;continue}let c=o.substring(0,s);if(!n.includes(c)||!o.endsWith(")"))continue;let u=o.substring(s+1,o.length-1),d;if(typeof e=="string")d=e;else{if(!("command"in e.params))continue;d=String(e.params.command)}if(n.some(l=>mh.includes(l))&&(d===u||d.startsWith(u+" ")))return!0}return!1}var Ude=class{messageBus;schedulerId;onTerminalCall;activeCalls=new Map;queue=[];_completedBatch=[];constructor(e,r=Prt,n){this.messageBus=e,this.schedulerId=r,this.onTerminalCall=n}addToolCalls(e){this.enqueue(e)}getToolCall(e){return this.activeCalls.get(e)||this.queue.find(r=>r.request.callId===e)||this._completedBatch.find(r=>r.request.callId===e)}enqueue(e){this.queue.push(...e),this.emitUpdate()}dequeue(){let e=this.queue.shift();return e&&(this.activeCalls.set(e.request.callId,e),this.emitUpdate()),e}peekQueue(){return this.queue[0]}get isActive(){return this.activeCalls.size>0}get allActiveCalls(){return Array.from(this.activeCalls.values())}get activeCallCount(){return this.activeCalls.size}get queueLength(){return this.queue.length}get firstActiveCall(){return this.activeCalls.values().next().value}updateStatus(e,r,n){let o=this.activeCalls.get(e);if(!o)return;let s=this.transitionCall(o,r,n);this.activeCalls.set(e,s),this.emitUpdate()}finalizeCall(e){let r=this.activeCalls.get(e);r&&this.isTerminalCall(r)&&(this._completedBatch.push(r),this.activeCalls.delete(e),this.onTerminalCall?.(r),this.emitUpdate())}updateArgs(e,r,n){let o=this.activeCalls.get(e);!o||o.status===Ue.Error||(this.activeCalls.set(e,this.patchCall(o,{request:{...o.request,args:r},invocation:n})),this.emitUpdate())}setOutcome(e,r){let n=this.activeCalls.get(e);n&&(this.activeCalls.set(e,this.patchCall(n,{outcome:r})),this.emitUpdate())}replaceActiveCallWithTailCall(e,r){this.activeCalls.has(e)&&(this.activeCalls.delete(e),this.queue.unshift(r),this.emitUpdate())}cancelAllQueued(e){if(this.queue.length!==0){for(;this.queue.length>0;){let r=this.queue.shift();if(r.status===Ue.Error){this._completedBatch.push(r),this.onTerminalCall?.(r);continue}let n=this.toCancelled(r,e);this._completedBatch.push(n),this.onTerminalCall?.(n)}this.emitUpdate()}}getSnapshot(){return[...this._completedBatch,...Array.from(this.activeCalls.values()),...this.queue]}clearBatch(){this._completedBatch.length!==0&&(this._completedBatch=[],this.emitUpdate())}get completedBatch(){return[...this._completedBatch]}emitUpdate(){let e=this.getSnapshot();this.messageBus.publish({type:Ki.TOOL_CALLS_UPDATE,toolCalls:e,schedulerId:this.schedulerId})}isTerminalCall(e){let{status:r}=e;return r===Ue.Success||r===Ue.Error||r===Ue.Cancelled}transitionCall(e,r,n){switch(r){case Ue.Success:{if(!ij(n))throw new Error(`Invalid data for 'success' transition (callId: ${e.request.callId})`);return this.toSuccess(e,n)}case Ue.Error:{if(!ij(n))throw new Error(`Invalid data for 'error' transition (callId: ${e.request.callId})`);return this.toError(e,n)}case Ue.AwaitingApproval:{if(!n)throw new Error(`Missing data for 'awaiting_approval' transition (callId: ${e.request.callId})`);return this.toAwaitingApproval(e,n)}case Ue.Scheduled:return this.toScheduled(e);case Ue.Cancelled:{if(typeof n!="string"&&!ij(n))throw new Error(`Invalid reason (string) or response for 'cancelled' transition (callId: ${e.request.callId})`);return this.toCancelled(e,n)}case Ue.Validating:return this.toValidating(e);case Ue.Executing:{if(n!==void 0&&!this.isExecutingToolCallPatch(n))throw new Error(`Invalid patch for 'executing' transition (callId: ${e.request.callId})`);return this.toExecuting(e,n)}default:return r}}isExecutingToolCallPatch(e){return typeof e=="object"&&e!==null}validateHasToolAndInvocation(e,r){if(!("tool"in e&&e.tool&&"invocation"in e&&e.invocation))throw new Error(`Invalid state transition: cannot transition to ${r} without tool/invocation (callId: ${e.request.callId})`)}toSuccess(e,r){this.validateHasToolAndInvocation(e,Ue.Success);let n="startTime"in e?e.startTime:void 0;return{request:e.request,tool:e.tool,invocation:e.invocation,status:Ue.Success,response:r,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toError(e,r){let n="startTime"in e?e.startTime:void 0;return{request:e.request,status:Ue.Error,tool:"tool"in e?e.tool:void 0,response:r,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toAwaitingApproval(e,r){this.validateHasToolAndInvocation(e,Ue.AwaitingApproval);let n,o;return this.isEventDrivenApprovalData(r)?(o=r.correlationId,n=r.confirmationDetails):n=r,{request:e.request,tool:e.tool,status:Ue.AwaitingApproval,correlationId:o,confirmationDetails:n,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}isEventDrivenApprovalData(e){return typeof e=="object"&&e!==null&&"correlationId"in e&&"confirmationDetails"in e}toScheduled(e){return this.validateHasToolAndInvocation(e,Ue.Scheduled),{request:e.request,tool:e.tool,status:Ue.Scheduled,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toCancelled(e,r){this.validateHasToolAndInvocation(e,Ue.Cancelled);let n="startTime"in e?e.startTime:void 0,o;if(this.isWaitingToolCall(e)){let u=e.confirmationDetails;u.type==="edit"&&"fileDiff"in u&&"fileName"in u&&"filePath"in u&&"originalContent"in u&&"newContent"in u&&(o={fileDiff:u.fileDiff,fileName:u.fileName,filePath:u.filePath,originalContent:u.originalContent,newContent:u.newContent,diffStat:u.diffStat??FJe(u.fileDiff)})}let s;if(e.status===Ue.Executing&&e.liveOutput&&(s=e.liveOutput),ij(r)){let u={...r};return u.resultDisplay||(u.resultDisplay=o??s),{request:e.request,tool:e.tool,invocation:e.invocation,status:Ue.Cancelled,response:u,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}let c=`[Operation Cancelled] Reason: ${r}`;return{request:e.request,tool:e.tool,invocation:e.invocation,status:Ue.Cancelled,response:{callId:e.request.callId,responseParts:[{functionResponse:{id:e.request.callId,name:e.request.name,response:{error:c}}}],resultDisplay:o??s,error:void 0,errorType:void 0,contentLength:c.length},durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}isWaitingToolCall(e){return e.status===Ue.AwaitingApproval}patchCall(e,r){return{...e,...r}}toValidating(e){return this.validateHasToolAndInvocation(e,Ue.Validating),{request:e.request,tool:e.tool,status:Ue.Validating,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toExecuting(e,r){this.validateHasToolAndInvocation(e,Ue.Executing);let n=r,o=n?.liveOutput??("liveOutput"in e?e.liveOutput:void 0),s=n?.pid??("pid"in e?e.pid:void 0),c=n?.progressMessage??("progressMessage"in e?e.progressMessage:void 0),u=n?.progressPercent??("progressPercent"in e?e.progressPercent:void 0),d=n?.progress??("progress"in e?e.progress:void 0),l=n?.progressTotal??("progressTotal"in e?e.progressTotal:void 0);return{request:e.request,tool:e.tool,status:Ue.Executing,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,liveOutput:o,pid:s,progressMessage:c,progressPercent:u,progress:d,progressTotal:l,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}};import{on as h_i}from"node:events";import{randomUUID as g_i}from"node:crypto";async function m_i(t,e,r){if(r.aborted)throw new Error("Operation cancelled");try{for await(let[n]of h_i(t,Ki.TOOL_CONFIRMATION_RESPONSE,{signal:r})){let o=n;if(o.correlationId===e)return{outcome:o.outcome??(o.confirmed?Ht.ProceedOnce:Ht.Cancel),payload:o.payload}}}catch(n){throw r.aborted||n.name==="AbortError"?new Error("Operation cancelled"):n}throw new Error("Operation cancelled")}async function e$e(t,e,r){let{state:n,onWaitingForConfirmation:o}=r,s=t.request.callId,c=Ht.ModifyWithEditor,u;for(;c===Ht.ModifyWithEditor;){if(e.aborted)throw new Error("Operation cancelled by user");let d=n.getToolCall(s);if(!d||!("invocation"in d))throw new Error(`Tool call ${s} lost during confirmation loop`);let a=await d.invocation.shouldConfirmExecute(e,r.forcedDecision);if(!a){c=Ht.ProceedOnce;break}r.systemMessage&&(a.systemMessage=r.systemMessage),await y_i(r,a);let p=g_i(),f=a;u=f;let g="ideConfirmation"in a?a.ideConfirmation:void 0;n.updateStatus(s,Ue.AwaitingApproval,{confirmationDetails:f,correlationId:p}),o?.(!0);let y=await E_i(r.messageBus,p,e,g);if(o?.(!1),c=y.outcome,"onConfirm"in a&&typeof a.onConfirm=="function"&&await a.onConfirm(c,y.payload),c===Ht.ModifyWithEditor){let _=await A_i(r,t,e);_.error&&be.emitFeedback("error",_.error)}else y.payload&&"newContent"in y.payload&&(await __i(r,t,y.payload,e),c=Ht.ProceedOnce)}return{outcome:c,lastDetails:u}}async function y_i(t,e){t.config.getHookSystem()&&await t.config.getHookSystem()?.fireToolNotificationEvent({...e,onConfirm:async()=>{}})}async function A_i(t,e,r){let{state:n,modifier:o,getPreferredEditor:s}=t,c=s(),u=await o6t(c,r);if(!u)return{error:e6t};let d=await o.handleModifyWithEditor(n.firstActiveCall,u,r);if(d){let l=e.tool.build(d.updatedParams);n.updateArgs(e.request.callId,d.updatedParams,l)}return{}}async function __i(t,e,r,n){let{state:o,modifier:s}=t,c=await s.applyInlineModify(o.firstActiveCall,r,n);if(c){let u=e.tool.build(c.updatedParams);o.updateArgs(e.request.callId,c.updatedParams,u)}}async function E_i(t,e,r,n){let o=new AbortController,s=o.signal,c=()=>o.abort();r.aborted?o.abort():r.addEventListener("abort",c);try{let u=m_i(t,e,s);if(!n)return await u;let d=n.then(l=>({outcome:l.status==="accepted"?Ht.ProceedOnce:Ht.Cancel,payload:l.content?{newContent:l.content}:void 0})).catch(l=>(U.warn("Error waiting for confirmation via IDE",l),new Promise(()=>{})));return await Promise.race([u,d])}finally{r.removeEventListener("abort",c),o.abort()}}function upr(t,e){return{errorMessage:`Tool execution denied by policy.${e?.denyMessage?` ${e.denyMessage}`:""}`,errorType:Be.POLICY_VIOLATION}}async function dpr(t,e,r){let n=t.tool instanceof ci?t.tool.serverName:void 0,o=t.tool.toolAnnotations,s=await e.getPolicyEngine().check({name:t.request.name,args:t.request.args},n,o,r),{decision:c}=s;if(c===ot.ASK_USER&&t.request.isClientInitiated&&!t.request.args?.additional_permissions)return{decision:ot.ALLOW,rule:s.rule};if(c===ot.ASK_USER&&!e.isInteractive())throw new Error(`Tool execution for "${t.tool.displayName||t.tool.name}" requires user confirmation, which is not supported in non-interactive mode.`);return{decision:c,rule:s.rule}}async function ppr(t,e,r,n,o,s){if(b_i(t,e)){n.config.setApprovalMode(ar.AUTO_EDIT);return}let c;if(e===Ht.ProceedAlwaysAndSave&&(n.config&&n.config.isTrustedFolder()&&n.config.getWorkspacePoliciesDir()!==void 0?c="workspace":c="user"),r?.type==="mcp"){await S_i(t,e,r,o,c);return}await v_i(t,e,r,o,c,s,n.config)}function b_i(t,e){return e===Ht.ProceedAlways&&JD.has(t.name)}async function v_i(t,e,r,n,o,s,c){if(e===Ht.ProceedAlways||e===Ht.ProceedAlwaysAndSave){let u=s?.getPolicyUpdateOptions?.(e)||{};if(!u.commandPrefix&&r?.type==="exec")u.commandPrefix=r.rootCommands;else if(!u.argsPattern&&r?.type==="edit"){let d=c?Qo(r.filePath,c.getTargetDir()):r.filePath;u.argsPattern=T1(d)}await n.publish({type:Ki.UPDATE_POLICY,toolName:t.name,persist:e===Ht.ProceedAlwaysAndSave,persistScope:o,...u})}}async function S_i(t,e,r,n,o){if(!(e===Ht.ProceedAlways||e===Ht.ProceedAlwaysTool||e===Ht.ProceedAlwaysServer||e===Ht.ProceedAlwaysAndSave))return;let c=t.name,u=e===Ht.ProceedAlwaysAndSave;e===Ht.ProceedAlwaysServer&&(c=Rv(r.serverName,"*")),await n.publish({type:Ki.UPDATE_POLICY,toolName:c,mcpName:r.serverName,persist:u,persistScope:o})}function t$e(t,e){if(!(t instanceof nKe))return;let n=(e.getMcpClientManager()?.getMcpServers()??e.getMcpServers()??{})[t.serverName];if(n)return{server_name:t.serverName,tool_name:t.serverToolName,command:n.command,args:n.args,cwd:n.cwd,url:n.url??n.httpUrl,tcp:n.tcp}}async function fpr(t,e,r,n,o,s,c,u,d){let l=t.params||{},a=!1,p=[],f=c?t$e(t,c):void 0,g=c?.getHookSystem();if(g&&!d){let _=await g.fireBeforeToolEvent(e,l,f,u);if(_?.shouldStopExecution()){let b=_.getEffectiveReason();return{llmContent:`Agent execution stopped by hook: ${b}`,returnDisplay:`Agent execution stopped by hook: ${b}`,error:{type:Be.STOP_EXECUTION,message:b}}}let E=_?.getBlockingError();if(E?.blocked)return{llmContent:`Tool execution blocked: ${E.reason}`,returnDisplay:`Tool execution blocked: ${E.reason}`,error:{type:Be.EXECUTION_FAILED,message:E.reason}};if(_ instanceof uA){let b=_.getModifiedToolInput();if(b){Object.assign(t.params,b),U.debug(`Tool input modified by hook for ${e}`),a=!0,p=Object.keys(b);try{t=n.build(t.params)}catch(v){return{llmContent:`Tool parameter modification by hook failed validation: ${v instanceof Error?v.message:String(v)}`,returnDisplay:"Tool parameter modification by hook failed validation.",error:{type:Be.INVALID_TOOL_PARAMS,message:String(v)}}}}}}let y=await t.execute(r,o,s);if(a){let _=`
|
|
@@ -991,7 +991,7 @@ ${s}
|
|
|
991
991
|
|
|
992
992
|
... [${u.toLocaleString()} characters omitted] ...
|
|
993
993
|
|
|
994
|
-
${c}`}var h_r="tool-outputs";async function OD(t,e,r,n,o){let s=rp(e).toLowerCase(),c=rp(r.toString()).toLowerCase(),u=c.startsWith(s)?`${c}.txt`:`${s}_${c}.txt`,d=Eu.join(n,h_r);if(o){let a=rp(o);d=Eu.join(d,`session-${a}`)}let l=Eu.join(d,u);return await Fw.mkdir(d,{recursive:!0}),await Fw.writeFile(l,t),{outputFile:l}}var $f=["run_shell_command","ShellTool"];async function TXe(t){if(vge.isAbsolute(t))try{return await VQ.promises.access(t,VQ.constants.X_OK),t}catch{return}let e=(process.env.PATH||"").split(vge.delimiter),r=_Xe.platform()==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of e)for(let o of r){let s=vge.join(n,t+o);try{return await VQ.promises.access(s,VQ.constants.X_OK),s}catch{continue}}}var pS=null,HQ=null,Qw=null,$Q=class extends Error{constructor(e){super(`Failed to initialize bash parser: ${e.message}`,{cause:e}),this.name="ShellParserInitializationError"}};function m_r(t){return t instanceof Error?t:typeof t=="string"?new Error(t):new Error("Unknown tree-sitter initialization error",{cause:t})}async function y_r(){try{Qw=null;let[t,e]=await Promise.all([Age(()=>import("./tree-sitter-
|
|
994
|
+
${c}`}var h_r="tool-outputs";async function OD(t,e,r,n,o){let s=rp(e).toLowerCase(),c=rp(r.toString()).toLowerCase(),u=c.startsWith(s)?`${c}.txt`:`${s}_${c}.txt`,d=Eu.join(n,h_r);if(o){let a=rp(o);d=Eu.join(d,`session-${a}`)}let l=Eu.join(d,u);return await Fw.mkdir(d,{recursive:!0}),await Fw.writeFile(l,t),{outputFile:l}}var $f=["run_shell_command","ShellTool"];async function TXe(t){if(vge.isAbsolute(t))try{return await VQ.promises.access(t,VQ.constants.X_OK),t}catch{return}let e=(process.env.PATH||"").split(vge.delimiter),r=_Xe.platform()==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of e)for(let o of r){let s=vge.join(n,t+o);try{return await VQ.promises.access(s,VQ.constants.X_OK),s}catch{continue}}}var pS=null,HQ=null,Qw=null,$Q=class extends Error{constructor(e){super(`Failed to initialize bash parser: ${e.message}`,{cause:e}),this.name="ShellParserInitializationError"}};function m_r(t){return t instanceof Error?t:typeof t=="string"?new Error(t):new Error("Unknown tree-sitter initialization error",{cause:t})}async function y_r(){try{Qw=null;let[t,e]=await Promise.all([Age(()=>import("./tree-sitter-JU2EI3Z2.js"),"web-tree-sitter/tree-sitter.wasm"),Age(()=>import("./tree-sitter-bash-IAB7XJEE.js"),"tree-sitter-bash/tree-sitter-bash.wasm")]);await hge.init({wasmBinary:t}),pS=await fge.load(e)}catch(t){pS=null;let e=m_r(t),r=e instanceof $Q?e:new $Q(e);throw Qw=r,r}}async function zf(){HQ||(HQ=y_r().catch(t=>{HQ=null,F.debug("Failed to initialize shell parsers:",t)})),await HQ}var CXe="__GCLI_POWERSHELL_COMMAND__",A_r=1e3*1e3,E_r=Buffer.from(`
|
|
995
995
|
$ErrorActionPreference = 'Stop'
|
|
996
996
|
$commandText = $env:${CXe}
|
|
997
997
|
if ([string]::IsNullOrEmpty($commandText)) {
|
|
@@ -2839,7 +2839,7 @@ When adding a memory, route it to the right store:
|
|
|
2839
2839
|
# Insufficient context
|
|
2840
2840
|
If you find that you have insufficient context to read or modify the memories as described,
|
|
2841
2841
|
reply with what you need, and exit. Do not search the codebase for the missing context.
|
|
2842
|
-
`.trim();return{kind:"local",name:"save_memory",displayName:"Memory Manager",description:"Writes and reads memory, preferences or facts across ALL future sessions. Use this for recurring instructions like coding styles or tool aliases.",inputConfig:{inputSchema:{type:"object",properties:{request:{type:"string",description:'The memory operation to perform. Examples: "Remember that I prefer tabs over spaces", "Clean up stale memories", "De-duplicate my memories", "Organize my memories".'}},required:["request"]}},outputConfig:{outputName:"result",description:"A summary of the memory operations performed.",schema:KAi},modelConfig:{model:Rw},toolConfig:{tools:[Ai,Cl,Tl,kw,Sl,yi,Co]},get promptConfig(){return{systemPrompt:n(),query:`${r()}\${request}`}},runConfig:{maxTimeMinutes:5,maxTurns:10}}};var xf=class t{static MAX_AUTH_RETRIES=2;authRetryCount=0;async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403)return this.authRetryCount>=t.MAX_AUTH_RETRIES?void 0:(this.authRetryCount++,this.headers());this.authRetryCount=0}async initialize(){}};var Ndr=6e4;async function Eb(t){if(t.startsWith("$$")||t.startsWith("!!"))return t.slice(1);if(t.startsWith("$")){let e=t.slice(1),r=process.env[e];if(r===void 0||r==="")throw new Error(`Environment variable '${e}' is not set or is empty. Please set it before using this agent.`);return F.debug(`[AuthValueResolver] Resolved env var: ${e}`),r}if(t.startsWith("!")){let e=t.slice(1).trim();if(!e)throw new Error("Empty command in auth value. Expected format: !command");F.debug("[AuthValueResolver] Executing command for auth value");let r=gA();try{let{stdout:n}=await np(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(Ndr),windowsHide:!0}),o=n.trim();if(!o)throw new Error(`Command '${e}' returned empty output`);return o}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Command '${e}' timed out after ${Ndr/1e3} seconds`):n}}return t}function Ddr(t){return t.startsWith("$")||t.startsWith("!")}var XAi="X-API-Key",Yue=class extends xf{constructor(r){super();this.config=r;this.headerName=r.name??XAi}type="apiKey";resolvedKey;headerName;async initialize(){Ddr(this.config.key)?(this.resolvedKey=await Eb(this.config.key),F.debug(`[ApiKeyAuthProvider] Resolved API key from: ${this.config.key.startsWith("$")?"env var":"command"}`)):this.resolvedKey=this.config.key}async headers(){if(!this.resolvedKey)throw new Error("ApiKeyAuthProvider not initialized. Call initialize() first.");return{[this.headerName]:this.resolvedKey}}async shouldRetryWithHeaders(r,n){if(n.status!==401&&n.status!==403){this.authRetryCount=0;return}if(!(!this.config.key.startsWith("!")||this.config.key.startsWith("!!"))&&!(this.authRetryCount>=xf.MAX_AUTH_RETRIES))return this.authRetryCount++,F.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await Eb(this.config.key),this.headers()}};var Jue=class extends xf{constructor(r){super();this.config=r}type="http";resolvedToken;resolvedUsername;resolvedPassword;resolvedValue;async initialize(){let r=this.config;"token"in r?this.resolvedToken=await Eb(r.token):"username"in r?(this.resolvedUsername=await Eb(r.username),this.resolvedPassword=await Eb(r.password)):this.resolvedValue=await Eb(r.value),F.debug(`[HttpAuthProvider] Initialized with scheme: ${this.config.scheme}`)}async headers(){let r=this.config;if("token"in r){if(!this.resolvedToken)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Bearer ${this.resolvedToken}`}}if("username"in r){if(!this.resolvedUsername||!this.resolvedPassword)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Basic ${Buffer.from(`${this.resolvedUsername}:${this.resolvedPassword}`).toString("base64")}`}}if(!this.resolvedValue)throw new Error("HttpAuthProvider not initialized");return{Authorization:`${r.scheme} ${this.resolvedValue}`}}async shouldRetryWithHeaders(r,n){if(n.status===401||n.status===403){if(this.authRetryCount>=xf.MAX_AUTH_RETRIES)return;F.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(r,n)}};var Ldr=Fe(Wo(),1);var ow=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},gN=5*60*1e3,As=class{static buildWellKnownUrls(e,r=!1){let n=new URL(e),o=`${n.protocol}//${n.host}`,s=r?"":n.pathname.replace(/\/$/,"");return{protectedResource:new URL(`/.well-known/oauth-protected-resource${s}`,o).toString(),authorizationServer:new URL(`/.well-known/oauth-authorization-server${s}`,o).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return F.debug(`Failed to fetch protected resource metadata from ${e}: ${Se(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return F.debug(`Failed to fetch authorization server metadata from ${e}: ${Se(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,issuer:e.issuer,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[],registrationUrl:e.registration_endpoint}}static async discoverAuthorizationServerMetadata(e){let r=new URL(e),n=`${r.protocol}//${r.host}`,o=[];r.pathname!=="/"&&(o.push(new URL(`/.well-known/oauth-authorization-server${r.pathname}`,n).toString()),o.push(new URL(`/.well-known/openid-configuration${r.pathname}`,n).toString()),o.push(new URL(`${r.pathname}/.well-known/openid-configuration`,n).toString())),o.push(new URL("/.well-known/oauth-authorization-server",n).toString()),o.push(new URL("/.well-known/openid-configuration",n).toString());for(let s of o){let c=await this.fetchAuthorizationServerMetadata(s);if(c)return c}return F.debug(`Metadata discovery failed for authorization server ${e}`),null}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(!n){let s=new URL(e);if(s.pathname&&s.pathname!=="/"){let c=this.buildWellKnownUrls(e,!0);n=await this.fetchProtectedResourceMetadata(c.protectedResource)}}if(n){let s=this.buildResourceParameter(e);if(!this.isEquivalentResourceIdentifier(n.resource,s))throw new ow(`Protected resource ${n.resource} does not match expected ${s}`)}if(n?.authorization_servers?.length){let s=n.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);if(c){let u=this.metadataToOAuthConfig(c);return c.registration_endpoint&&F.log("Dynamic client registration is supported at:",c.registration_endpoint),u}}F.debug(`Trying OAuth discovery fallback at ${e}`);let o=await this.discoverAuthorizationServerMetadata(e);if(o){let s=this.metadataToOAuthConfig(o);return o.registration_endpoint&&F.log("Dynamic client registration is supported at:",o.registration_endpoint),s}return null}catch(r){if(r instanceof ow)throw r;return F.debug(`Failed to discover OAuth configuration: ${Se(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e,r){let n=this.parseWWWAuthenticateHeader(e);if(!n)return null;let o=await this.fetchProtectedResourceMetadata(n);if(o&&r){let u=this.buildResourceParameter(r);if(!this.isEquivalentResourceIdentifier(o.resource,u))throw new ow(`Protected resource ${o.resource} does not match expected ${u}`)}if(!o?.authorization_servers?.length)return null;let s=o.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);return c?this.metadataToOAuthConfig(c):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}${r.pathname}`}static isEquivalentResourceIdentifier(e,r){let n=o=>{try{return this.buildResourceParameter(o)}catch{return o}};return n(e)===n(r)}static parseTokenExpiry(e){try{let r=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString());if(r&&typeof r.exp=="number")return r.exp*1e3}catch(r){F.error("Failed to parse ID token for expiry time with error:",r)}}};var Mdr=/^(.*\.)?run\.app$/,ZAi=[/^.+\.googleapis\.com$/,Mdr],Kue=class extends xf{constructor(r,n){super();this.config=r;if(!n)throw new Error("targetUrl must be provided to GoogleCredentialsAuthProvider to determine token audience.");let o=new URL(n).hostname;if(Mdr.test(o)&&(this.useIdToken=!0),this.audience=o,!this.useIdToken&&!ZAi.some(u=>u.test(o)))throw new Error(`Host "${o}" is not an allowed host for Google Credential provider.`);let c=this.config.scopes&&this.config.scopes.length>0?this.config.scopes:["https://www.googleapis.com/auth/cloud-platform"];this.auth=new Ldr.GoogleAuth({scopes:c})}type="google-credentials";auth;useIdToken=!1;audience;cachedToken;tokenExpiryTime;async initialize(){}async headers(){if(this.cachedToken&&this.tokenExpiryTime&&Date.now()<this.tokenExpiryTime-gN)return{Authorization:`Bearer ${this.cachedToken}`};if(this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.useIdToken)try{let n=await(await this.auth.getIdTokenClient(this.audience)).idTokenProvider.fetchIdToken(this.audience),o=As.parseTokenExpiry(n);return o&&(this.tokenExpiryTime=o,this.cachedToken=n),{Authorization:`Bearer ${n}`}}catch(r){let n=`Failed to get ADC ID token: ${r instanceof Error?r.message:String(r)}`;throw F.error(n,r),new Error(n)}try{let r=await this.auth.getClient(),n=await r.getAccessToken();if(n.token){this.cachedToken=n.token;let o=r.credentials;return o.expiry_date&&(this.tokenExpiryTime=o.expiry_date),{Authorization:`Bearer ${n.token}`}}throw new Error("Failed to retrieve ADC access token.")}catch(r){let n=`Failed to get ADC access token: ${r instanceof Error?r.message:String(r)}`;throw F.error(n,r),new Error(n)}}async shouldRetryWithHeaders(r,n){if(n.status!==401&&n.status!==403){this.authRetryCount=0;return}if(!(this.authRetryCount>=xf.MAX_AUTH_RETRIES))return this.authRetryCount++,F.debug("[GoogleCredentialsAuthProvider] Re-fetching token after auth failure"),this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.headers()}};var _b=class t{static async create(e){let{agentName:r,authConfig:n,agentCard:o}=e;if(!n)return o?.securitySchemes&&Object.keys(o.securitySchemes).length>0,void 0;switch(n.type){case"google-credentials":{let s=new Kue(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new Yue(n);return await s.initialize(),s}case"http":{let s=new Jue(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-OXLPSPT7.js"),c=new s(n,e.agentName??"unknown",o,e.agentCardUrl);return await c.initialize(),c}case"openIdConnect":throw new Error("openIdConnect auth provider not yet implemented");default:{let s=n;throw new Error(`Unknown auth type: ${s.type}`)}}}static async createFromConfig(e,r){return await t.create({authConfig:e,agentName:r})}static validateAuthConfig(e,r){if(!r||Object.keys(r).length===0)return{valid:!0};let n=Object.keys(r);if(!e)return{valid:!1,diff:{requiredSchemes:n,configuredType:void 0,missingConfig:["Authentication is required but not configured"]}};let o=t.findMatchingScheme(e,r);return o.matched?{valid:!0}:{valid:!1,diff:{requiredSchemes:n,configuredType:e.type,missingConfig:o.missingConfig}}}static findMatchingScheme(e,r){let n=[];for(let[o,s]of Object.entries(r))switch(s.type){case"apiKey":if(e.type==="apiKey")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires apiKey authentication`);break;case"http":if(e.type==="http"){if(e.scheme.toLowerCase()===s.scheme.toLowerCase())return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication, but ${e.scheme} was configured`)}else{if(e.type==="google-credentials"&&s.scheme.toLowerCase()==="bearer")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication`)}break;case"oauth2":if(e.type==="oauth2")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OAuth 2.0 authentication`);break;case"openIdConnect":if(e.type==="openIdConnect")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OpenID Connect authentication`);break;case"mutualTLS":n.push(`Scheme '${o}' requires mTLS authentication (not yet supported)`);break;default:{let c=s;n.push(`Unknown security scheme type: ${c.type}`)}}return{matched:!1,missingConfig:n}}static describeRequiredAuth(e){let r=[];for(let[n,o]of Object.entries(e))switch(o.type){case"apiKey":r.push(`API Key (${n}): Send ${o.name} in ${o.in}`);break;case"http":r.push(`HTTP ${o.scheme} (${n})`);break;case"oauth2":r.push(`OAuth 2.0 (${n})`);break;case"openIdConnect":r.push(`OpenID Connect (${n})`);break;case"mutualTLS":r.push(`Mutual TLS (${n})`);break;default:{let s=o;r.push(`Unknown (${n}): ${s.type}`)}}return r.join(" OR ")}};var hm=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},AVe=class extends hm{constructor(e,r){let n=`Agent card not found at ${r} (HTTP 404)`,o=`Agent card not found (404) at ${r}. Verify the agent_card_url in your agent definition.`;super(e,n,o),this.name="AgentCardNotFoundError"}},Xue=class extends hm{statusCode;constructor(e,r,n){let o=n===401?"Unauthorized":"Forbidden",s=`Agent card request returned ${n} ${o} for ${r}`,c=`Authentication failed (${n} ${o}) at ${r}. Check the "auth" configuration in your agent definition.`;super(e,s,c),this.name="AgentCardAuthError",this.statusCode=n}},Zue=class extends hm{requiredAuth;missingFields;constructor(e,r,n){let o=`Agent "${e}" requires authentication but none is configured`,s=`Agent requires ${r} but no auth is configured. Missing: ${n.join(", ")}`;super(e,o,s),this.name="AgentAuthConfigMissingError",this.requiredAuth=r,this.missingFields=n}},ede=class extends hm{constructor(e,r,n){let o=n instanceof Error?n.message:String(n),s=`Failed to connect to agent "${e}" at ${r}: ${o}`,c=`Connection failed for ${r}: ${o}`;super(e,s,c,{cause:n}),this.name="AgentConnectionError"}};function eEi(t){return typeof t=="object"&&t!==null}function tEi(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(eEi(r)){let s=r;r instanceof Error?e.push(r.message):typeof s.message=="string"&&e.push(s.message),typeof s.code=="string"&&e.push(s.code),typeof s.status=="number"?e.push(String(s.status)):typeof s.statusCode=="number"&&e.push(String(s.statusCode)),r=s.cause}else if(typeof r=="string"){e.push(r);break}else{e.push(String(r));break}n++}return e.join(" ")}function Bdr(t,e,r){let n=tEi(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new ede(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new AVe(t,e):/\b401\b|unauthorized/i.test(n)?new Xue(t,e,401):/\b403\b|forbidden/i.test(n)?new Xue(t,e,403):new ede(t,e,r)}function EVe(t){return`${t.name}-config`}var tde=class{constructor(e){this.config=e}agents=new Map;allDefinitions=new Map;builtInAgents=new Set;async initialize(){_e.on("model-changed",this.onModelChanged),await this.loadAgents()}isBuiltIn(e){return this.builtInAgents.has(e)}onModelChanged=()=>{this.refreshAgents("local").catch(e=>{F.error("[AgentRegistry] Failed to refresh agents on model change:",e)})};async reload(){this.config.getA2AClientManager()?.clearCache(),await this.config.reloadAgents(),this.agents.clear(),this.allDefinitions.clear(),await this.loadAgents(),_e.emitAgentsRefreshed()}async acknowledgeAgent(e){let r=this.config.getAcknowledgedAgentsService(),n=this.config.getProjectRoot();e.metadata?.hash&&(await r.acknowledge(n,e.name,e.metadata.hash),await this.registerAgent(e),_e.emitAgentsRefreshed())}dispose(){_e.off("model-changed",this.onModelChanged)}async loadAgents(){if(this.agents.clear(),this.allDefinitions.clear(),this.loadBuiltInAgents(),!this.config.isAgentsEnabled())return;let e=er.getUserAgentsDir(),r=await gVe(e);for(let s of r.errors)F.warn(`[AgentRegistry] Error loading user agent: ${s.message}`),_e.emitFeedback("error",`Agent loading error: ${s.message}`);await Promise.allSettled(r.agents.map(async s=>{try{await this.registerAgent(s)}catch(c){F.warn(`[AgentRegistry] Error registering user agent "${s.name}":`,c),_e.emitFeedback("error",`Error registering user agent "${s.name}": ${c instanceof Error?c.message:String(c)}`)}}));let n=this.config.getFolderTrust(),o=this.config.isTrustedFolder();if(!n||o){let s=this.config.storage.getProjectAgentsDir(),c=await gVe(s);for(let p of c.errors)_e.emitFeedback("error",`Agent loading error: ${p.message}`);let u=this.config.getAcknowledgedAgentsService(),d=this.config.getProjectRoot(),l=[],a=[];for(let p of c.agents){if(p.kind==="remote"&&(p.metadata||(p.metadata={}),p.metadata.hash=p.agentCardUrl??(p.agentCardJson?Udr.createHash("sha256").update(p.agentCardJson).digest("hex"):void 0)),!p.metadata?.hash){a.push(p);continue}await u.isAcknowledged(d,p.name,p.metadata.hash)?a.push(p):l.push(p)}l.length>0&&_e.emitAgentsDiscovered(l),await Promise.allSettled(a.map(async p=>{try{await this.registerAgent(p)}catch(f){F.warn(`[AgentRegistry] Error registering project agent "${p.name}":`,f),_e.emitFeedback("error",`Error registering project agent "${p.name}": ${f instanceof Error?f.message:String(f)}`)}}))}else _e.emitFeedback("info","Skipping project agents due to untrusted folder. To enable, ensure that the project root is trusted.");for(let s of this.config.getExtensions())s.isActive&&s.agents&&await Promise.allSettled(s.agents.map(async c=>{try{await this.registerAgent(c)}catch(u){F.warn(`[AgentRegistry] Error registering extension agent "${c.name}":`,u),_e.emitFeedback("error",`Error registering extension agent "${c.name}": ${u instanceof Error?u.message:String(u)}`)}}));this.config.getDebugMode()&&F.log(`[AgentRegistry] Loaded with ${this.agents.size} agents.`)}loadBuiltInAgents(){let e=Sce(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=Rdr(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=Pdr(this.config);if(this.builtInAgents.add(n.name),this.registerLocalAgent(n),this.config.getBrowserAgentConfig().enabled){let s=Wue(this.config);this.builtInAgents.add(s.name),this.registerLocalAgent(s)}if(this.config.isMemoryManagerEnabled()){this.registerLocalAgent(kdr(this.config));try{let s=er.getGlobalGeminiDir();this.config.getWorkspaceContext().addDirectory(s)}catch(s){F.warn("[AgentRegistry] Could not add global .gemini directory to workspace:",s)}}}async refreshAgents(e="all"){this.loadBuiltInAgents(),await Promise.allSettled(Array.from(this.agents.values()).map(async r=>{(e==="all"||r.kind===e)&&await this.registerAgent(r)}))}async registerAgent(e){e.kind==="local"?this.registerLocalAgent(e):e.kind==="remote"&&await this.registerRemoteAgent(e)}registerLocalAgent(e){if(e.kind!=="local")return;if(!e.name||!e.description){F.warn("[AgentRegistry] Skipping invalid agent definition. Missing name or description.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&F.log(`[AgentRegistry] Skipping disabled agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&F.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=this.applyOverrides(e,r);this.agents.set(n.name,n),this.registerModelConfigs(n),this.addAgentPolicy(n)}addAgentPolicy(e){let r=this.config.getPolicyEngine();if(r){if(r.hasRuleForTool(e.name,!0)){this.config.getDebugMode()&&F.log(`[AgentRegistry] User policy exists for '${e.name}', skipping dynamic registration.`);return}r.removeRulesForTool(e.name,"AgentRegistry (Dynamic)"),r.addRule({toolName:e.name,decision:e.kind==="local"?"allow":"ask_user",priority:Xj,source:"AgentRegistry (Dynamic)"})}}isAgentEnabled(e,r){let o=!(e.experimental===!0);return r&&r.enabled!==void 0&&(o=r.enabled),o}async registerRemoteAgent(e){if(e.kind!=="remote")return;if(!e.name){F.warn("[AgentRegistry] Skipping invalid agent definition. Missing name.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&F.log(`[AgentRegistry] Skipping disabled remote agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&F.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=e;n.originalDescription===void 0&&(n.originalDescription=n.description);try{let o=this.config.getA2AClientManager();if(!o){F.warn(`[AgentRegistry] Skipping remote agent '${e.name}': A2AClientManager is not available.`);return}let s=Uue(n),c;if(e.auth){let p=await _b.create({authConfig:e.auth,agentName:e.name,targetUrl:s,agentCardUrl:n.agentCardUrl});if(!p)throw new Error(`Failed to create auth provider for agent '${e.name}'`);c=p}let u=await o.loadAgent(n.name,Bue(n),c);if(u.securitySchemes){let p=_b.validateAuthConfig(e.auth,u.securitySchemes);if(!p.valid&&p.diff){let f=_b.describeRequiredAuth(u.securitySchemes),g=new Zue(e.name,f,p.diff.missingConfig);_e.emitFeedback("warning",`[${e.name}] Agent requires authentication: ${f}`),F.warn(`[AgentRegistry] ${g.message}`)}}let d=n.originalDescription,l=u.description,a=[];if(d?.trim()&&a.push(`User Description: ${d.trim()}`),l?.trim()&&a.push(`Agent Description: ${l.trim()}`),u.skills&&u.skills.length>0){let p=u.skills.map(f=>`${f.name}: ${f.description||"No description provided"}`).join(`
|
|
2842
|
+
`.trim();return{kind:"local",name:"save_memory",displayName:"Memory Manager",description:"Writes and reads memory, preferences or facts across ALL future sessions. Use this for recurring instructions like coding styles or tool aliases.",inputConfig:{inputSchema:{type:"object",properties:{request:{type:"string",description:'The memory operation to perform. Examples: "Remember that I prefer tabs over spaces", "Clean up stale memories", "De-duplicate my memories", "Organize my memories".'}},required:["request"]}},outputConfig:{outputName:"result",description:"A summary of the memory operations performed.",schema:KAi},modelConfig:{model:Rw},toolConfig:{tools:[Ai,Cl,Tl,kw,Sl,yi,Co]},get promptConfig(){return{systemPrompt:n(),query:`${r()}\${request}`}},runConfig:{maxTimeMinutes:5,maxTurns:10}}};var xf=class t{static MAX_AUTH_RETRIES=2;authRetryCount=0;async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403)return this.authRetryCount>=t.MAX_AUTH_RETRIES?void 0:(this.authRetryCount++,this.headers());this.authRetryCount=0}async initialize(){}};var Ndr=6e4;async function Eb(t){if(t.startsWith("$$")||t.startsWith("!!"))return t.slice(1);if(t.startsWith("$")){let e=t.slice(1),r=process.env[e];if(r===void 0||r==="")throw new Error(`Environment variable '${e}' is not set or is empty. Please set it before using this agent.`);return F.debug(`[AuthValueResolver] Resolved env var: ${e}`),r}if(t.startsWith("!")){let e=t.slice(1).trim();if(!e)throw new Error("Empty command in auth value. Expected format: !command");F.debug("[AuthValueResolver] Executing command for auth value");let r=gA();try{let{stdout:n}=await np(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(Ndr),windowsHide:!0}),o=n.trim();if(!o)throw new Error(`Command '${e}' returned empty output`);return o}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Command '${e}' timed out after ${Ndr/1e3} seconds`):n}}return t}function Ddr(t){return t.startsWith("$")||t.startsWith("!")}var XAi="X-API-Key",Yue=class extends xf{constructor(r){super();this.config=r;this.headerName=r.name??XAi}type="apiKey";resolvedKey;headerName;async initialize(){Ddr(this.config.key)?(this.resolvedKey=await Eb(this.config.key),F.debug(`[ApiKeyAuthProvider] Resolved API key from: ${this.config.key.startsWith("$")?"env var":"command"}`)):this.resolvedKey=this.config.key}async headers(){if(!this.resolvedKey)throw new Error("ApiKeyAuthProvider not initialized. Call initialize() first.");return{[this.headerName]:this.resolvedKey}}async shouldRetryWithHeaders(r,n){if(n.status!==401&&n.status!==403){this.authRetryCount=0;return}if(!(!this.config.key.startsWith("!")||this.config.key.startsWith("!!"))&&!(this.authRetryCount>=xf.MAX_AUTH_RETRIES))return this.authRetryCount++,F.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await Eb(this.config.key),this.headers()}};var Jue=class extends xf{constructor(r){super();this.config=r}type="http";resolvedToken;resolvedUsername;resolvedPassword;resolvedValue;async initialize(){let r=this.config;"token"in r?this.resolvedToken=await Eb(r.token):"username"in r?(this.resolvedUsername=await Eb(r.username),this.resolvedPassword=await Eb(r.password)):this.resolvedValue=await Eb(r.value),F.debug(`[HttpAuthProvider] Initialized with scheme: ${this.config.scheme}`)}async headers(){let r=this.config;if("token"in r){if(!this.resolvedToken)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Bearer ${this.resolvedToken}`}}if("username"in r){if(!this.resolvedUsername||!this.resolvedPassword)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Basic ${Buffer.from(`${this.resolvedUsername}:${this.resolvedPassword}`).toString("base64")}`}}if(!this.resolvedValue)throw new Error("HttpAuthProvider not initialized");return{Authorization:`${r.scheme} ${this.resolvedValue}`}}async shouldRetryWithHeaders(r,n){if(n.status===401||n.status===403){if(this.authRetryCount>=xf.MAX_AUTH_RETRIES)return;F.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(r,n)}};var Ldr=Fe(Wo(),1);var ow=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},gN=5*60*1e3,As=class{static buildWellKnownUrls(e,r=!1){let n=new URL(e),o=`${n.protocol}//${n.host}`,s=r?"":n.pathname.replace(/\/$/,"");return{protectedResource:new URL(`/.well-known/oauth-protected-resource${s}`,o).toString(),authorizationServer:new URL(`/.well-known/oauth-authorization-server${s}`,o).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return F.debug(`Failed to fetch protected resource metadata from ${e}: ${Se(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return F.debug(`Failed to fetch authorization server metadata from ${e}: ${Se(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,issuer:e.issuer,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[],registrationUrl:e.registration_endpoint}}static async discoverAuthorizationServerMetadata(e){let r=new URL(e),n=`${r.protocol}//${r.host}`,o=[];r.pathname!=="/"&&(o.push(new URL(`/.well-known/oauth-authorization-server${r.pathname}`,n).toString()),o.push(new URL(`/.well-known/openid-configuration${r.pathname}`,n).toString()),o.push(new URL(`${r.pathname}/.well-known/openid-configuration`,n).toString())),o.push(new URL("/.well-known/oauth-authorization-server",n).toString()),o.push(new URL("/.well-known/openid-configuration",n).toString());for(let s of o){let c=await this.fetchAuthorizationServerMetadata(s);if(c)return c}return F.debug(`Metadata discovery failed for authorization server ${e}`),null}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(!n){let s=new URL(e);if(s.pathname&&s.pathname!=="/"){let c=this.buildWellKnownUrls(e,!0);n=await this.fetchProtectedResourceMetadata(c.protectedResource)}}if(n){let s=this.buildResourceParameter(e);if(!this.isEquivalentResourceIdentifier(n.resource,s))throw new ow(`Protected resource ${n.resource} does not match expected ${s}`)}if(n?.authorization_servers?.length){let s=n.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);if(c){let u=this.metadataToOAuthConfig(c);return c.registration_endpoint&&F.log("Dynamic client registration is supported at:",c.registration_endpoint),u}}F.debug(`Trying OAuth discovery fallback at ${e}`);let o=await this.discoverAuthorizationServerMetadata(e);if(o){let s=this.metadataToOAuthConfig(o);return o.registration_endpoint&&F.log("Dynamic client registration is supported at:",o.registration_endpoint),s}return null}catch(r){if(r instanceof ow)throw r;return F.debug(`Failed to discover OAuth configuration: ${Se(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e,r){let n=this.parseWWWAuthenticateHeader(e);if(!n)return null;let o=await this.fetchProtectedResourceMetadata(n);if(o&&r){let u=this.buildResourceParameter(r);if(!this.isEquivalentResourceIdentifier(o.resource,u))throw new ow(`Protected resource ${o.resource} does not match expected ${u}`)}if(!o?.authorization_servers?.length)return null;let s=o.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);return c?this.metadataToOAuthConfig(c):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}${r.pathname}`}static isEquivalentResourceIdentifier(e,r){let n=o=>{try{return this.buildResourceParameter(o)}catch{return o}};return n(e)===n(r)}static parseTokenExpiry(e){try{let r=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString());if(r&&typeof r.exp=="number")return r.exp*1e3}catch(r){F.error("Failed to parse ID token for expiry time with error:",r)}}};var Mdr=/^(.*\.)?run\.app$/,ZAi=[/^.+\.googleapis\.com$/,Mdr],Kue=class extends xf{constructor(r,n){super();this.config=r;if(!n)throw new Error("targetUrl must be provided to GoogleCredentialsAuthProvider to determine token audience.");let o=new URL(n).hostname;if(Mdr.test(o)&&(this.useIdToken=!0),this.audience=o,!this.useIdToken&&!ZAi.some(u=>u.test(o)))throw new Error(`Host "${o}" is not an allowed host for Google Credential provider.`);let c=this.config.scopes&&this.config.scopes.length>0?this.config.scopes:["https://www.googleapis.com/auth/cloud-platform"];this.auth=new Ldr.GoogleAuth({scopes:c})}type="google-credentials";auth;useIdToken=!1;audience;cachedToken;tokenExpiryTime;async initialize(){}async headers(){if(this.cachedToken&&this.tokenExpiryTime&&Date.now()<this.tokenExpiryTime-gN)return{Authorization:`Bearer ${this.cachedToken}`};if(this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.useIdToken)try{let n=await(await this.auth.getIdTokenClient(this.audience)).idTokenProvider.fetchIdToken(this.audience),o=As.parseTokenExpiry(n);return o&&(this.tokenExpiryTime=o,this.cachedToken=n),{Authorization:`Bearer ${n}`}}catch(r){let n=`Failed to get ADC ID token: ${r instanceof Error?r.message:String(r)}`;throw F.error(n,r),new Error(n)}try{let r=await this.auth.getClient(),n=await r.getAccessToken();if(n.token){this.cachedToken=n.token;let o=r.credentials;return o.expiry_date&&(this.tokenExpiryTime=o.expiry_date),{Authorization:`Bearer ${n.token}`}}throw new Error("Failed to retrieve ADC access token.")}catch(r){let n=`Failed to get ADC access token: ${r instanceof Error?r.message:String(r)}`;throw F.error(n,r),new Error(n)}}async shouldRetryWithHeaders(r,n){if(n.status!==401&&n.status!==403){this.authRetryCount=0;return}if(!(this.authRetryCount>=xf.MAX_AUTH_RETRIES))return this.authRetryCount++,F.debug("[GoogleCredentialsAuthProvider] Re-fetching token after auth failure"),this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.headers()}};var _b=class t{static async create(e){let{agentName:r,authConfig:n,agentCard:o}=e;if(!n)return o?.securitySchemes&&Object.keys(o.securitySchemes).length>0,void 0;switch(n.type){case"google-credentials":{let s=new Kue(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new Yue(n);return await s.initialize(),s}case"http":{let s=new Jue(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-LSK6ONS7.js"),c=new s(n,e.agentName??"unknown",o,e.agentCardUrl);return await c.initialize(),c}case"openIdConnect":throw new Error("openIdConnect auth provider not yet implemented");default:{let s=n;throw new Error(`Unknown auth type: ${s.type}`)}}}static async createFromConfig(e,r){return await t.create({authConfig:e,agentName:r})}static validateAuthConfig(e,r){if(!r||Object.keys(r).length===0)return{valid:!0};let n=Object.keys(r);if(!e)return{valid:!1,diff:{requiredSchemes:n,configuredType:void 0,missingConfig:["Authentication is required but not configured"]}};let o=t.findMatchingScheme(e,r);return o.matched?{valid:!0}:{valid:!1,diff:{requiredSchemes:n,configuredType:e.type,missingConfig:o.missingConfig}}}static findMatchingScheme(e,r){let n=[];for(let[o,s]of Object.entries(r))switch(s.type){case"apiKey":if(e.type==="apiKey")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires apiKey authentication`);break;case"http":if(e.type==="http"){if(e.scheme.toLowerCase()===s.scheme.toLowerCase())return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication, but ${e.scheme} was configured`)}else{if(e.type==="google-credentials"&&s.scheme.toLowerCase()==="bearer")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication`)}break;case"oauth2":if(e.type==="oauth2")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OAuth 2.0 authentication`);break;case"openIdConnect":if(e.type==="openIdConnect")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OpenID Connect authentication`);break;case"mutualTLS":n.push(`Scheme '${o}' requires mTLS authentication (not yet supported)`);break;default:{let c=s;n.push(`Unknown security scheme type: ${c.type}`)}}return{matched:!1,missingConfig:n}}static describeRequiredAuth(e){let r=[];for(let[n,o]of Object.entries(e))switch(o.type){case"apiKey":r.push(`API Key (${n}): Send ${o.name} in ${o.in}`);break;case"http":r.push(`HTTP ${o.scheme} (${n})`);break;case"oauth2":r.push(`OAuth 2.0 (${n})`);break;case"openIdConnect":r.push(`OpenID Connect (${n})`);break;case"mutualTLS":r.push(`Mutual TLS (${n})`);break;default:{let s=o;r.push(`Unknown (${n}): ${s.type}`)}}return r.join(" OR ")}};var hm=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},AVe=class extends hm{constructor(e,r){let n=`Agent card not found at ${r} (HTTP 404)`,o=`Agent card not found (404) at ${r}. Verify the agent_card_url in your agent definition.`;super(e,n,o),this.name="AgentCardNotFoundError"}},Xue=class extends hm{statusCode;constructor(e,r,n){let o=n===401?"Unauthorized":"Forbidden",s=`Agent card request returned ${n} ${o} for ${r}`,c=`Authentication failed (${n} ${o}) at ${r}. Check the "auth" configuration in your agent definition.`;super(e,s,c),this.name="AgentCardAuthError",this.statusCode=n}},Zue=class extends hm{requiredAuth;missingFields;constructor(e,r,n){let o=`Agent "${e}" requires authentication but none is configured`,s=`Agent requires ${r} but no auth is configured. Missing: ${n.join(", ")}`;super(e,o,s),this.name="AgentAuthConfigMissingError",this.requiredAuth=r,this.missingFields=n}},ede=class extends hm{constructor(e,r,n){let o=n instanceof Error?n.message:String(n),s=`Failed to connect to agent "${e}" at ${r}: ${o}`,c=`Connection failed for ${r}: ${o}`;super(e,s,c,{cause:n}),this.name="AgentConnectionError"}};function eEi(t){return typeof t=="object"&&t!==null}function tEi(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(eEi(r)){let s=r;r instanceof Error?e.push(r.message):typeof s.message=="string"&&e.push(s.message),typeof s.code=="string"&&e.push(s.code),typeof s.status=="number"?e.push(String(s.status)):typeof s.statusCode=="number"&&e.push(String(s.statusCode)),r=s.cause}else if(typeof r=="string"){e.push(r);break}else{e.push(String(r));break}n++}return e.join(" ")}function Bdr(t,e,r){let n=tEi(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new ede(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new AVe(t,e):/\b401\b|unauthorized/i.test(n)?new Xue(t,e,401):/\b403\b|forbidden/i.test(n)?new Xue(t,e,403):new ede(t,e,r)}function EVe(t){return`${t.name}-config`}var tde=class{constructor(e){this.config=e}agents=new Map;allDefinitions=new Map;builtInAgents=new Set;async initialize(){_e.on("model-changed",this.onModelChanged),await this.loadAgents()}isBuiltIn(e){return this.builtInAgents.has(e)}onModelChanged=()=>{this.refreshAgents("local").catch(e=>{F.error("[AgentRegistry] Failed to refresh agents on model change:",e)})};async reload(){this.config.getA2AClientManager()?.clearCache(),await this.config.reloadAgents(),this.agents.clear(),this.allDefinitions.clear(),await this.loadAgents(),_e.emitAgentsRefreshed()}async acknowledgeAgent(e){let r=this.config.getAcknowledgedAgentsService(),n=this.config.getProjectRoot();e.metadata?.hash&&(await r.acknowledge(n,e.name,e.metadata.hash),await this.registerAgent(e),_e.emitAgentsRefreshed())}dispose(){_e.off("model-changed",this.onModelChanged)}async loadAgents(){if(this.agents.clear(),this.allDefinitions.clear(),this.loadBuiltInAgents(),!this.config.isAgentsEnabled())return;let e=er.getUserAgentsDir(),r=await gVe(e);for(let s of r.errors)F.warn(`[AgentRegistry] Error loading user agent: ${s.message}`),_e.emitFeedback("error",`Agent loading error: ${s.message}`);await Promise.allSettled(r.agents.map(async s=>{try{await this.registerAgent(s)}catch(c){F.warn(`[AgentRegistry] Error registering user agent "${s.name}":`,c),_e.emitFeedback("error",`Error registering user agent "${s.name}": ${c instanceof Error?c.message:String(c)}`)}}));let n=this.config.getFolderTrust(),o=this.config.isTrustedFolder();if(!n||o){let s=this.config.storage.getProjectAgentsDir(),c=await gVe(s);for(let p of c.errors)_e.emitFeedback("error",`Agent loading error: ${p.message}`);let u=this.config.getAcknowledgedAgentsService(),d=this.config.getProjectRoot(),l=[],a=[];for(let p of c.agents){if(p.kind==="remote"&&(p.metadata||(p.metadata={}),p.metadata.hash=p.agentCardUrl??(p.agentCardJson?Udr.createHash("sha256").update(p.agentCardJson).digest("hex"):void 0)),!p.metadata?.hash){a.push(p);continue}await u.isAcknowledged(d,p.name,p.metadata.hash)?a.push(p):l.push(p)}l.length>0&&_e.emitAgentsDiscovered(l),await Promise.allSettled(a.map(async p=>{try{await this.registerAgent(p)}catch(f){F.warn(`[AgentRegistry] Error registering project agent "${p.name}":`,f),_e.emitFeedback("error",`Error registering project agent "${p.name}": ${f instanceof Error?f.message:String(f)}`)}}))}else _e.emitFeedback("info","Skipping project agents due to untrusted folder. To enable, ensure that the project root is trusted.");for(let s of this.config.getExtensions())s.isActive&&s.agents&&await Promise.allSettled(s.agents.map(async c=>{try{await this.registerAgent(c)}catch(u){F.warn(`[AgentRegistry] Error registering extension agent "${c.name}":`,u),_e.emitFeedback("error",`Error registering extension agent "${c.name}": ${u instanceof Error?u.message:String(u)}`)}}));this.config.getDebugMode()&&F.log(`[AgentRegistry] Loaded with ${this.agents.size} agents.`)}loadBuiltInAgents(){let e=Sce(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=Rdr(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=Pdr(this.config);if(this.builtInAgents.add(n.name),this.registerLocalAgent(n),this.config.getBrowserAgentConfig().enabled){let s=Wue(this.config);this.builtInAgents.add(s.name),this.registerLocalAgent(s)}if(this.config.isMemoryManagerEnabled()){this.registerLocalAgent(kdr(this.config));try{let s=er.getGlobalGeminiDir();this.config.getWorkspaceContext().addDirectory(s)}catch(s){F.warn("[AgentRegistry] Could not add global .gemini directory to workspace:",s)}}}async refreshAgents(e="all"){this.loadBuiltInAgents(),await Promise.allSettled(Array.from(this.agents.values()).map(async r=>{(e==="all"||r.kind===e)&&await this.registerAgent(r)}))}async registerAgent(e){e.kind==="local"?this.registerLocalAgent(e):e.kind==="remote"&&await this.registerRemoteAgent(e)}registerLocalAgent(e){if(e.kind!=="local")return;if(!e.name||!e.description){F.warn("[AgentRegistry] Skipping invalid agent definition. Missing name or description.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&F.log(`[AgentRegistry] Skipping disabled agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&F.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=this.applyOverrides(e,r);this.agents.set(n.name,n),this.registerModelConfigs(n),this.addAgentPolicy(n)}addAgentPolicy(e){let r=this.config.getPolicyEngine();if(r){if(r.hasRuleForTool(e.name,!0)){this.config.getDebugMode()&&F.log(`[AgentRegistry] User policy exists for '${e.name}', skipping dynamic registration.`);return}r.removeRulesForTool(e.name,"AgentRegistry (Dynamic)"),r.addRule({toolName:e.name,decision:e.kind==="local"?"allow":"ask_user",priority:Xj,source:"AgentRegistry (Dynamic)"})}}isAgentEnabled(e,r){let o=!(e.experimental===!0);return r&&r.enabled!==void 0&&(o=r.enabled),o}async registerRemoteAgent(e){if(e.kind!=="remote")return;if(!e.name){F.warn("[AgentRegistry] Skipping invalid agent definition. Missing name.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&F.log(`[AgentRegistry] Skipping disabled remote agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&F.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=e;n.originalDescription===void 0&&(n.originalDescription=n.description);try{let o=this.config.getA2AClientManager();if(!o){F.warn(`[AgentRegistry] Skipping remote agent '${e.name}': A2AClientManager is not available.`);return}let s=Uue(n),c;if(e.auth){let p=await _b.create({authConfig:e.auth,agentName:e.name,targetUrl:s,agentCardUrl:n.agentCardUrl});if(!p)throw new Error(`Failed to create auth provider for agent '${e.name}'`);c=p}let u=await o.loadAgent(n.name,Bue(n),c);if(u.securitySchemes){let p=_b.validateAuthConfig(e.auth,u.securitySchemes);if(!p.valid&&p.diff){let f=_b.describeRequiredAuth(u.securitySchemes),g=new Zue(e.name,f,p.diff.missingConfig);_e.emitFeedback("warning",`[${e.name}] Agent requires authentication: ${f}`),F.warn(`[AgentRegistry] ${g.message}`)}}let d=n.originalDescription,l=u.description,a=[];if(d?.trim()&&a.push(`User Description: ${d.trim()}`),l?.trim()&&a.push(`Agent Description: ${l.trim()}`),u.skills&&u.skills.length>0){let p=u.skills.map(f=>`${f.name}: ${f.description||"No description provided"}`).join(`
|
|
2843
2843
|
`);a.push(`Skills:
|
|
2844
2844
|
${p}`)}a.length>0&&(e.description=a.join(`
|
|
2845
2845
|
`)),this.config.getDebugMode()&&F.log(`[AgentRegistry] Registered remote agent '${e.name}' with card: ${e.agentCardUrl??"inline JSON"}`),this.agents.set(e.name,e),this.addAgentPolicy(e)}catch(o){o instanceof hm?_e.emitFeedback("error",`[${e.name}] ${o.userMessage}`):_e.emitFeedback("error",`[${e.name}] Failed to load remote agent: ${o instanceof Error?o.message:String(o)}`),F.warn(`[AgentRegistry] Error loading A2A agent "${e.name}":`,o)}}applyOverrides(e,r){if(e.kind!=="local"||!r)return e;let n={get kind(){return e.kind},get name(){return e.name},get displayName(){return e.displayName},get description(){return e.description},get experimental(){return e.experimental},get metadata(){return e.metadata},get inputConfig(){return e.inputConfig},get outputConfig(){return e.outputConfig},get promptConfig(){return e.promptConfig},get toolConfig(){return e.toolConfig},get processOutput(){return e.processOutput},get runConfig(){return r.runConfig?{...e.runConfig,...r.runConfig}:e.runConfig},get modelConfig(){return r.modelConfig?sN.merge(e.modelConfig,r.modelConfig):e.modelConfig}};return r.tools&&(n.toolConfig={tools:r.tools}),r.mcpServers&&(n.mcpServers={...e.mcpServers,...r.mcpServers}),n}registerModelConfigs(e){let r=e.modelConfig,n=r.model;n==="inherit"&&(n=this.config.getModel());let o={...r,model:n};this.config.modelConfigService.registerRuntimeModelConfig(EVe(e),{modelConfig:o}),o.model&&Cs(o.model)&&this.config.modelConfigService.registerRuntimeModelOverride({match:{overrideScope:e.name},modelConfig:{generateContentConfig:o.generateContentConfig}})}getDefinition(e){return this.agents.get(e)}getAllDefinitions(){return Array.from(this.agents.values())}getAllAgentNames(){return Array.from(this.agents.keys())}getAllDiscoveredAgentNames(){return Array.from(this.allDefinitions.keys())}getDiscoveredDefinition(e){return this.allDefinitions.get(e)}};import*as mN from"node:fs/promises";import*as Fdr from"node:path";var rde=class{acknowledgedAgents={};loaded=!1;async load(){if(this.loaded)return;let e=er.getAcknowledgedAgentsPath();try{let r=await mN.readFile(e,"utf-8");this.acknowledgedAgents=JSON.parse(r)}catch(r){(!Ht(r)||r.code!=="ENOENT")&&F.error("Failed to load acknowledged agents:",Se(r)),this.acknowledgedAgents={}}this.loaded=!0}async save(){let e=er.getAcknowledgedAgentsPath();try{let r=Fdr.dirname(e);await mN.mkdir(r,{recursive:!0}),await mN.writeFile(e,JSON.stringify(this.acknowledgedAgents,null,2),"utf-8")}catch(r){F.error("Failed to save acknowledged agents:",Se(r))}}async isAcknowledged(e,r,n){await this.load();let o=this.acknowledgedAgents[e];return o?o[r]===n:!1}async acknowledge(e,r,n){await this.load(),this.acknowledgedAgents[e]||(this.acknowledgedAgents[e]={}),this.acknowledgedAgents[e][r]=n,await this.save()}};function nde(t,e){let r=/\$\{(\w+)\}/g,n=new Set(Array.from(t.matchAll(r),c=>c[1])),o=new Set(Object.keys(e)),s=Array.from(n).filter(c=>!o.has(c));if(s.length>0)throw new Error(`Template validation failed: Missing required input parameters: ${s.join(", ")}. Available inputs: ${Object.keys(e).join(", ")}`);return t.replace(r,(c,u)=>String(e[u]))}import{AsyncLocalStorage as rEi}from"node:async_hooks";var jdr=new rEi;function _Ve(t,e){return jdr.run(t,e)}function ide(){return jdr.getStore()}var Qdr=Fe(Doe(),1);function C7(t){return typeof t=="object"&&t!==null&&"callId"in t&&"responseParts"in t}function mMo(t){let{displayName:e,status:r,approvalMode:n,hasResultDisplay:o,parentCallId:s}=t;if(s)return!0;switch(e){case ED:switch(r){case"scheduled":case"validating":case"executing":case"awaiting_approval":return!0;case"error":return!o;default:return!1}case SQ:case TQ:return n==="plan";default:return!1}}function w7(t,e,r=3){let n=e.map(c=>({name:c,distance:Qdr.default.get(t,c)}));n.sort((c,u)=>c.distance-u.distance);let o=n.slice(0,r);if(o.length===0)return"";let s=o.map(c=>`"${c.name}"`).join(", ");return o.length>1?` Did you mean one of: ${s}?`:` Did you mean ${s}?`}function yMo(t,e,r){let n;eQ(t)?n=[t.name,t.constructor.name]:n=[t],n.some(o=>$f.includes(o))&&(n=[...new Set([...n,...$f])]);for(let o of r){let s=o.indexOf("(");if(s===-1){if(n.includes(o))return!0;continue}let c=o.substring(0,s);if(!n.includes(c)||!o.endsWith(")"))continue;let u=o.substring(s+1,o.length-1),d;if(typeof e=="string")d=e;else{if(!("command"in e.params))continue;d=String(e.params.command)}if(n.some(l=>$f.includes(l))&&(d===u||d.startsWith(u+" ")))return!0}return!1}var ode=class{constructor(e,r=Jtt,n){this.messageBus=e;this.schedulerId=r;this.onTerminalCall=n}activeCalls=new Map;queue=[];_completedBatch=[];addToolCalls(e){this.enqueue(e)}getToolCall(e){return this.activeCalls.get(e)||this.queue.find(r=>r.request.callId===e)||this._completedBatch.find(r=>r.request.callId===e)}enqueue(e){this.queue.push(...e),this.emitUpdate()}dequeue(){let e=this.queue.shift();return e&&(this.activeCalls.set(e.request.callId,e),this.emitUpdate()),e}peekQueue(){return this.queue[0]}get isActive(){return this.activeCalls.size>0}get allActiveCalls(){return Array.from(this.activeCalls.values())}get activeCallCount(){return this.activeCalls.size}get queueLength(){return this.queue.length}get firstActiveCall(){return this.activeCalls.values().next().value}updateStatus(e,r,n){let o=this.activeCalls.get(e);if(!o)return;let s=this.transitionCall(o,r,n);this.activeCalls.set(e,s),this.emitUpdate()}finalizeCall(e){let r=this.activeCalls.get(e);r&&this.isTerminalCall(r)&&(this._completedBatch.push(r),this.activeCalls.delete(e),this.onTerminalCall?.(r),this.emitUpdate())}updateArgs(e,r,n){let o=this.activeCalls.get(e);!o||o.status==="error"||(this.activeCalls.set(e,this.patchCall(o,{request:{...o.request,args:r},invocation:n})),this.emitUpdate())}setOutcome(e,r){let n=this.activeCalls.get(e);n&&(this.activeCalls.set(e,this.patchCall(n,{outcome:r})),this.emitUpdate())}replaceActiveCallWithTailCall(e,r){this.activeCalls.has(e)&&(this.activeCalls.delete(e),this.queue.unshift(r),this.emitUpdate())}cancelAllQueued(e){if(this.queue.length!==0){for(;this.queue.length>0;){let r=this.queue.shift();if(r.status==="error"){this._completedBatch.push(r),this.onTerminalCall?.(r);continue}let n=this.toCancelled(r,e);this._completedBatch.push(n),this.onTerminalCall?.(n)}this.emitUpdate()}}getSnapshot(){return[...this._completedBatch,...Array.from(this.activeCalls.values()),...this.queue]}clearBatch(){this._completedBatch.length!==0&&(this._completedBatch=[],this.emitUpdate())}get completedBatch(){return[...this._completedBatch]}emitUpdate(){let e=this.getSnapshot();this.messageBus.publish({type:"tool-calls-update",toolCalls:e,schedulerId:this.schedulerId})}isTerminalCall(e){let{status:r}=e;return r==="success"||r==="error"||r==="cancelled"}transitionCall(e,r,n){switch(r){case"success":{if(!C7(n))throw new Error(`Invalid data for 'success' transition (callId: ${e.request.callId})`);return this.toSuccess(e,n)}case"error":{if(!C7(n))throw new Error(`Invalid data for 'error' transition (callId: ${e.request.callId})`);return this.toError(e,n)}case"awaiting_approval":{if(!n)throw new Error(`Missing data for 'awaiting_approval' transition (callId: ${e.request.callId})`);return this.toAwaitingApproval(e,n)}case"scheduled":return this.toScheduled(e);case"cancelled":{if(typeof n!="string"&&!C7(n))throw new Error(`Invalid reason (string) or response for 'cancelled' transition (callId: ${e.request.callId})`);return this.toCancelled(e,n)}case"validating":return this.toValidating(e);case"executing":{if(n!==void 0&&!this.isExecutingToolCallPatch(n))throw new Error(`Invalid patch for 'executing' transition (callId: ${e.request.callId})`);return this.toExecuting(e,n)}default:return r}}isExecutingToolCallPatch(e){return typeof e=="object"&&e!==null}validateHasToolAndInvocation(e,r){if(!("tool"in e&&e.tool&&"invocation"in e&&e.invocation))throw new Error(`Invalid state transition: cannot transition to ${r} without tool/invocation (callId: ${e.request.callId})`)}toSuccess(e,r){this.validateHasToolAndInvocation(e,"success");let n="startTime"in e?e.startTime:void 0;return{request:e.request,tool:e.tool,invocation:e.invocation,status:"success",response:r,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toError(e,r){let n="startTime"in e?e.startTime:void 0;return{request:e.request,status:"error",tool:"tool"in e?e.tool:void 0,response:r,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toAwaitingApproval(e,r){this.validateHasToolAndInvocation(e,"awaiting_approval");let n,o;return this.isEventDrivenApprovalData(r)?(o=r.correlationId,n=r.confirmationDetails):n=r,{request:e.request,tool:e.tool,status:"awaiting_approval",correlationId:o,confirmationDetails:n,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}isEventDrivenApprovalData(e){return typeof e=="object"&&e!==null&&"correlationId"in e&&"confirmationDetails"in e}toScheduled(e){return this.validateHasToolAndInvocation(e,"scheduled"),{request:e.request,tool:e.tool,status:"scheduled",startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toCancelled(e,r){this.validateHasToolAndInvocation(e,"cancelled");let n="startTime"in e?e.startTime:void 0,o;if(this.isWaitingToolCall(e)){let u=e.confirmationDetails;u.type==="edit"&&"fileDiff"in u&&"fileName"in u&&"filePath"in u&&"originalContent"in u&&"newContent"in u&&(o={fileDiff:u.fileDiff,fileName:u.fileName,filePath:u.filePath,originalContent:u.originalContent,newContent:u.newContent,diffStat:u.diffStat??iJe(u.fileDiff)})}let s;if(e.status==="executing"&&e.liveOutput&&(s=e.liveOutput),C7(r)){let u={...r};return u.resultDisplay||(u.resultDisplay=o??s),{request:e.request,tool:e.tool,invocation:e.invocation,status:"cancelled",response:u,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}let c=`[Operation Cancelled] Reason: ${r}`;return{request:e.request,tool:e.tool,invocation:e.invocation,status:"cancelled",response:{callId:e.request.callId,responseParts:[{functionResponse:{id:e.request.callId,name:e.request.name,response:{error:c}}}],resultDisplay:o??s,error:void 0,errorType:void 0,contentLength:c.length},durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}isWaitingToolCall(e){return e.status==="awaiting_approval"}patchCall(e,r){return{...e,...r}}toValidating(e){return this.validateHasToolAndInvocation(e,"validating"),{request:e.request,tool:e.tool,status:"validating",startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toExecuting(e,r){this.validateHasToolAndInvocation(e,"executing");let n=r,o=n?.liveOutput??("liveOutput"in e?e.liveOutput:void 0),s=n?.pid??("pid"in e?e.pid:void 0),c=n?.progressMessage??("progressMessage"in e?e.progressMessage:void 0),u=n?.progressPercent??("progressPercent"in e?e.progressPercent:void 0),d=n?.progress??("progress"in e?e.progress:void 0),l=n?.progressTotal??("progressTotal"in e?e.progressTotal:void 0);return{request:e.request,tool:e.tool,status:"executing",startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,liveOutput:o,pid:s,progressMessage:c,progressPercent:u,progress:d,progressTotal:l,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}};import{on as nEi}from"node:events";import{randomUUID as iEi}from"node:crypto";async function oEi(t,e,r){if(r.aborted)throw new Error("Operation cancelled");try{for await(let[n]of nEi(t,"tool-confirmation-response",{signal:r})){let o=n;if(o.correlationId===e)return{outcome:o.outcome??(o.confirmed?"proceed_once":"cancel"),payload:o.payload}}}catch(n){throw r.aborted||n.name==="AbortError"?new Error("Operation cancelled"):n}throw new Error("Operation cancelled")}async function vVe(t,e,r){let{state:n,onWaitingForConfirmation:o}=r,s=t.request.callId,c="modify_with_editor",u;for(;c==="modify_with_editor";){if(e.aborted)throw new Error("Operation cancelled by user");let d=n.getToolCall(s);if(!d||!("invocation"in d))throw new Error(`Tool call ${s} lost during confirmation loop`);let a=await d.invocation.shouldConfirmExecute(e,r.forcedDecision);if(!a){c="proceed_once";break}r.systemMessage&&(a.systemMessage=r.systemMessage),await sEi(r,a);let p=iEi(),f=a;u=f;let g="ideConfirmation"in a?a.ideConfirmation:void 0;n.updateStatus(s,"awaiting_approval",{confirmationDetails:f,correlationId:p}),o?.(!0);let y=await cEi(r.messageBus,p,e,g);if(o?.(!1),c=y.outcome,"onConfirm"in a&&typeof a.onConfirm=="function"&&await a.onConfirm(c,y.payload),c==="modify_with_editor"){let E=await aEi(r,t,e);E.error&&_e.emitFeedback("error",E.error)}else y.payload&&"newContent"in y.payload&&(await lEi(r,t,y.payload,e),c="proceed_once")}return{outcome:c,lastDetails:u}}async function sEi(t,e){t.config.getHookSystem()&&await t.config.getHookSystem()?.fireToolNotificationEvent({...e,onConfirm:async()=>{}})}async function aEi(t,e,r){let{state:n,modifier:o,getPreferredEditor:s}=t,c=s(),u=await L3t(c,r);if(!u)return{error:R3t};let d=await o.handleModifyWithEditor(n.firstActiveCall,u,r);if(d){let l=e.tool.build(d.updatedParams);n.updateArgs(e.request.callId,d.updatedParams,l)}return{}}async function lEi(t,e,r,n){let{state:o,modifier:s}=t,c=await s.applyInlineModify(o.firstActiveCall,r,n);if(c){let u=e.tool.build(c.updatedParams);o.updateArgs(e.request.callId,c.updatedParams,u)}}async function cEi(t,e,r,n){let o=new AbortController,s=o.signal,c=()=>o.abort();r.aborted?o.abort():r.addEventListener("abort",c);try{let u=oEi(t,e,s);if(!n)return await u;let d=n.then(l=>({outcome:l.status==="accepted"?"proceed_once":"cancel",payload:l.content?{newContent:l.content}:void 0})).catch(l=>(F.warn("Error waiting for confirmation via IDE",l),new Promise(()=>{})));return await Promise.race([u,d])}finally{r.removeEventListener("abort",c),o.abort()}}function qdr(t,e){return{errorMessage:`Tool execution denied by policy.${e?.denyMessage?` ${e.denyMessage}`:""}`,errorType:"policy_violation"}}async function Gdr(t,e,r){let n=t.tool instanceof Wn?t.tool.serverName:void 0,o=t.tool.toolAnnotations,s=await e.getPolicyEngine().check({name:t.request.name,args:t.request.args},n,o,r),{decision:c}=s;if(c==="ask_user"&&t.request.isClientInitiated&&!t.request.args?.additional_permissions)return{decision:"allow",rule:s.rule};if(c==="ask_user"&&!e.isInteractive())throw new Error(`Tool execution for "${t.tool.displayName||t.tool.name}" requires user confirmation, which is not supported in non-interactive mode.`);return{decision:c,rule:s.rule}}async function Vdr(t,e,r,n,o,s){if(uEi(t,e)){n.config.setApprovalMode("autoEdit");return}let c;if(e==="proceed_always_and_save"&&(n.config&&n.config.isTrustedFolder()&&n.config.getWorkspacePoliciesDir()!==void 0?c="workspace":c="user"),r?.type==="mcp"){await pEi(t,e,r,o,c);return}await dEi(t,e,r,o,c,s,n.config)}function uEi(t,e){return e==="proceed_always"&&AD.has(t.name)}async function dEi(t,e,r,n,o,s,c){if(e==="proceed_always"||e==="proceed_always_and_save"){let u=s?.getPolicyUpdateOptions?.(e)||{};if(!u.commandPrefix&&r?.type==="exec")u.commandPrefix=r.rootCommands;else if(!u.argsPattern&&r?.type==="edit"){let d=c?To(r.filePath,c.getTargetDir()):r.filePath;u.argsPattern=W_(d)}await n.publish({type:"update-policy",toolName:t.name,persist:e==="proceed_always_and_save",persistScope:o,...u})}}async function pEi(t,e,r,n,o){if(!(e==="proceed_always"||e==="proceed_always_tool"||e==="proceed_always_server"||e==="proceed_always_and_save"))return;let c=t.name,u=e==="proceed_always_and_save";e==="proceed_always_server"&&(c=eS(r.serverName,"*")),await n.publish({type:"update-policy",toolName:c,mcpName:r.serverName,persist:u,persistScope:o})}function bVe(t,e){if(!(t instanceof bJe))return;let n=(e.getMcpClientManager()?.getMcpServers()??e.getMcpServers()??{})[t.serverName];if(n)return{server_name:t.serverName,tool_name:t.serverToolName,command:n.command,args:n.args,cwd:n.cwd,url:n.url??n.httpUrl,tcp:n.tcp}}async function Hdr(t,e,r,n,o,s,c,u,d){let l=t.params||{},a=!1,p=[],f=c?bVe(t,c):void 0,g=c?.getHookSystem();if(g&&!d){let E=await g.fireBeforeToolEvent(e,l,f,u);if(E?.shouldStopExecution()){let v=E.getEffectiveReason();return{llmContent:`Agent execution stopped by hook: ${v}`,returnDisplay:`Agent execution stopped by hook: ${v}`,error:{type:"stop_execution",message:v}}}let _=E?.getBlockingError();if(_?.blocked)return{llmContent:`Tool execution blocked: ${_.reason}`,returnDisplay:`Tool execution blocked: ${_.reason}`,error:{type:"execution_failed",message:_.reason}};if(E instanceof L0){let v=E.getModifiedToolInput();if(v){Object.assign(t.params,v),F.debug(`Tool input modified by hook for ${e}`),a=!0,p=Object.keys(v);try{t=n.build(t.params)}catch(b){return{llmContent:`Tool parameter modification by hook failed validation: ${b instanceof Error?b.message:String(b)}`,returnDisplay:"Tool parameter modification by hook failed validation.",error:{type:"invalid_tool_params",message:String(b)}}}}}}let y=await t.execute(r,o,s);if(a){let E=`
|