makecoder 2.0.84 → 2.0.86

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/coder.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Be=Object.create;var Y=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Ve=Object.getPrototypeOf,Ge=Object.prototype.hasOwnProperty;var f=(u,e)=>()=>(e||u((e={exports:{}}).exports,e),e.exports);var Le=(u,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Re(e))!Ge.call(u,o)&&o!==s&&Y(u,o,{get:()=>e[o],enumerable:!(t=Ne(e,o))||t.enumerable});return u};var He=(u,e,s)=>(s=u!=null?Be(Ve(u)):{},Le(e||!u||!u.__esModule?Y(s,"default",{value:u,enumerable:!0}):s,u));var X=f((Ts,Z)=>{var Ke=require("http"),F=class{constructor(e={}){this.port=e.port||9380,this.timeout=e.timeout||300*1e3,this.server=null,this.timeoutId=null}validateTokenFormat(e){if(!e||typeof e!="string")return!1;let s=e.split(".");if(s.length!==2)return!1;let[t,o]=s;return t&&t.length>0&&o&&o.length>0}async waitForCallback(e){return new Promise((s,t)=>{let o=!1;this.server=Ke.createServer((n,r)=>{let a=new URL(n.url,`http://localhost:${this.port}`);if(a.pathname==="/callback"){let i=a.searchParams.get("token"),c=a.searchParams.get("state"),l=a.searchParams.get("error");if(l){r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
2
+ var Ke=Object.create;var se=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var ze=Object.getPrototypeOf,Je=Object.prototype.hasOwnProperty;var m=(u,e)=>()=>(e||u((e={exports:{}}).exports,e),e.exports);var Qe=(u,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of We(e))!Je.call(u,o)&&o!==s&&se(u,o,{get:()=>e[o],enumerable:!(t=je(e,o))||t.enumerable});return u};var Ye=(u,e,s)=>(s=u!=null?Ke(ze(u)):{},Qe(e||!u||!u.__esModule?se(s,"default",{value:u,enumerable:!0}):s,u));var oe=m((Ns,te)=>{var Ze=require("http"),U=class{constructor(e={}){this.port=e.port||9380,this.timeout=e.timeout||300*1e3,this.server=null,this.timeoutId=null}validateTokenFormat(e){if(!e||typeof e!="string")return!1;let s=e.split(".");if(s.length!==2)return!1;let[t,o]=s;return t&&t.length>0&&o&&o.length>0}async waitForCallback(e){return new Promise((s,t)=>{let o=!1;this.server=Ze.createServer((n,r)=>{let c=new URL(n.url,`http://localhost:${this.port}`);if(c.pathname==="/callback"){let i=c.searchParams.get("token"),a=c.searchParams.get("state"),l=c.searchParams.get("error");if(l){r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
3
3
  <!DOCTYPE html>
4
4
  <html>
5
5
  <head>
@@ -24,7 +24,7 @@ var Be=Object.create;var Y=Object.defineProperty;var Ne=Object.getOwnPropertyDes
24
24
  </div>
25
25
  </body>
26
26
  </html>
27
- `),o||(o=!0,this.cleanup(),t(new Error(`OAuth error: ${l}`)));return}if(c!==e){r.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
27
+ `),o||(o=!0,this.cleanup(),t(new Error(`OAuth error: ${l}`)));return}if(a!==e){r.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
28
28
  <!DOCTYPE html>
29
29
  <html>
30
30
  <head>
@@ -92,7 +92,7 @@ var Be=Object.create;var Y=Object.defineProperty;var Ne=Object.getOwnPropertyDes
92
92
  </div>
93
93
  </body>
94
94
  </html>
95
- `),o||(o=!0,this.cleanup(),t(new Error("Invalid token format - expected ak.sk format")));return}let[h,g]=i.split(".");r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
95
+ `),o||(o=!0,this.cleanup(),t(new Error("Invalid token format - expected ak.sk format")));return}let[h,d]=i.split(".");r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
96
96
  <!DOCTYPE html>
97
97
  <html>
98
98
  <head>
@@ -124,7 +124,7 @@ var Be=Object.create;var Y=Object.defineProperty;var Ne=Object.getOwnPropertyDes
124
124
  </script>
125
125
  </body>
126
126
  </html>
127
- `),o||(o=!0,this.cleanup(),s({ak:h,sk:g}))}else r.writeHead(404,{"Content-Type":"text/plain"}),r.end("Not Found")}),this.server.on("error",n=>{if(n.code==="EADDRINUSE"){if(this.port++,this.port>9390){o||(o=!0,t(new Error("Could not find available port for OAuth callback server")));return}this.server.close(),this.server.listen(this.port)}else o||(o=!0,this.cleanup(),t(n))}),this.server.listen(this.port,()=>{process.env.CODEV_DEBUG&&console.log(`OAuth callback server listening on port ${this.port}`)}),this.timeoutId=setTimeout(()=>{o||(o=!0,this.cleanup(),t(new Error("OAuth login timeout - no response received within 5 minutes")))},this.timeout)})}getCallbackUrl(){return`http://localhost:${this.port}/callback`}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server&&(this.server.close(),this.server=null)}};Z.exports=F});var se=f((Os,ee)=>{var ze=require("crypto"),We=X(),M=class{constructor(e={}){this.baseUrl=e.baseUrl||"https://makecoder.com",this.callbackServer=null}generateState(){return ze.randomBytes(16).toString("hex")}buildAuthorizationUrl(e,s){let t=new URLSearchParams({redirect_uri:e,state:s,response_type:"token"});return`${this.baseUrl}/oauth/authorize?${t.toString()}`}async login(){let e=this.generateState();this.callbackServer=new We;try{let s=this.callbackServer.getCallbackUrl(),t=this.buildAuthorizationUrl(s,e);console.log(`
127
+ `),o||(o=!0,this.cleanup(),s({ak:h,sk:d}))}else r.writeHead(404,{"Content-Type":"text/plain"}),r.end("Not Found")}),this.server.on("error",n=>{if(n.code==="EADDRINUSE"){if(this.port++,this.port>9390){o||(o=!0,t(new Error("Could not find available port for OAuth callback server")));return}this.server.close(),this.server.listen(this.port)}else o||(o=!0,this.cleanup(),t(n))}),this.server.listen(this.port,()=>{process.env.CODEV_DEBUG&&console.log(`OAuth callback server listening on port ${this.port}`)}),this.timeoutId=setTimeout(()=>{o||(o=!0,this.cleanup(),t(new Error("OAuth login timeout - no response received within 5 minutes")))},this.timeout)})}getCallbackUrl(){return`http://localhost:${this.port}/callback`}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server&&(this.server.close(),this.server=null)}};te.exports=U});var re=m((Rs,ne)=>{var Xe=require("crypto"),es=oe(),B=class{constructor(e={}){this.baseUrl=e.baseUrl||"https://makecoder.com",this.callbackServer=null}generateState(){return Xe.randomBytes(16).toString("hex")}buildAuthorizationUrl(e,s){let t=new URLSearchParams({redirect_uri:e,state:s,response_type:"token"});return`${this.baseUrl}/oauth/authorize?${t.toString()}`}async login(){let e=this.generateState();this.callbackServer=new es;try{let s=this.callbackServer.getCallbackUrl(),t=this.buildAuthorizationUrl(s,e);console.log(`
128
128
  \u{1F510} \u5F00\u59CB OAuth \u767B\u5F55\u6D41\u7A0B...
129
129
  `),console.log(`\u{1F4CB} \u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u767B\u5F55
130
130
  `),console.log(`\u{1F310} \u6388\u6743\u5730\u5740: ${t}
@@ -132,10 +132,10 @@ var Be=Object.create;var Y=Object.defineProperty;var Ne=Object.getOwnPropertyDes
132
132
  `);try{let n=(await import("open")).default;await n(t)}catch(n){console.warn("\u26A0\uFE0F \u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668,\u8BF7\u624B\u52A8\u590D\u5236\u4E0A\u8FF0\u94FE\u63A5\u5230\u6D4F\u89C8\u5668\u6253\u5F00"),process.env.CODEV_DEBUG&&console.error("Browser open error:",n)}let o=await this.callbackServer.waitForCallback(e);return console.log(`\u2705 API Key \u83B7\u53D6\u6210\u529F!
133
133
  `),o}catch(s){throw console.error(`
134
134
  \u274C OAuth \u767B\u5F55\u5931\u8D25: ${s.message}
135
- `),s}finally{this.callbackServer&&this.callbackServer.cleanup()}}cleanup(){this.callbackServer&&this.callbackServer.cleanup()}};ee.exports=M});var ne=f((As,oe)=>{var C=require("fs"),te=require("path"),je=require("os"),Je=require("readline"),Qe=se(),q=class{constructor(){this.configPath=te.join(je.homedir(),".coder","config.json"),this.defaultConfig={agent:"claude",auth:{ak:null,sk:null}}}async promptForAKSK(){let e=Je.createInterface({input:process.stdin,output:process.stdout});return new Promise((s,t)=>{console.log(`
136
- \u{1F510} \u8BF7\u8F93\u5165\u60A8\u7684 API Key\uFF1A`),e.question("\u8BF7\u8F93\u5165 API Key: ",o=>{let n=o.indexOf(".");if(n===-1||n===0||n===o.length-1){e.close(),t(new Error("\u683C\u5F0F\u9519\u8BEF"));return}let r=o.substring(0,n),a=o.substring(n+1);if(!r.trim()||!a.trim()){e.close(),t(new Error("\u683C\u5F0F\u9519\u8BEF"));return}e.close(),s({ak:r.trim(),sk:a.trim()})})})}ensureConfig(){let e=te.dirname(this.configPath);try{C.existsSync(e)||C.mkdirSync(e,{recursive:!0}),C.existsSync(this.configPath)||C.writeFileSync(this.configPath,JSON.stringify(this.defaultConfig,null,2))}catch(s){return console.warn(`Warning: Could not create config file: ${s.message}`),this.defaultConfig}}loadConfig(){this.ensureConfig();try{let e=C.readFileSync(this.configPath,"utf8");return JSON.parse(e)}catch(e){return console.warn(`Warning: Could not load config, using defaults: ${e.message}`),this.defaultConfig}}async parse(e=process.argv.slice(2)){let s=this.loadConfig(),t={agent:s.agent||"claude",remainingArgs:[]},o=0,n=!1;for(e.length>0&&["claude","gemini","codex"].includes(e[0])?(t.agent=e[0],n=!0,o=1):e.length>0&&e[0]==="pub"?(t.command="pub",o=1):e.length>0&&e[0]==="login"?(t.command="login",o=1):e.length>0&&e[0]==="update"?(t.command="update",o=1):e.length>0&&e[0]==="skills"&&(t.command="skills",t.skillsSubcommand=e[1],t.skillsArg=e[2],o=e.length);o<e.length;){let i=e[o];if(i==="--agent"){if(n)throw new Error(`Cannot use both subcommand '${t.agent}' and --agent flag. Please use only one method to specify the agent.`);if(o+1>=e.length)throw new Error("--agent requires a value (claude, gemini, or codex)");let c=e[o+1];if(!["claude","gemini","codex"].includes(c))throw new Error(`Invalid agent: ${c}. Must be 'claude', 'gemini', or 'codex'`);t.agent=c,o+=2}else if(i==="--apikey"||i==="--aksk")if(o+1>=e.length||e[o+1].startsWith("--"))t.needAKSKPrompt=!0,o+=1;else{let c=e[o+1],l=c.indexOf(".");if(l===-1)throw new Error("API Key Format error");t.auth_ak=c.substring(0,l),t.auth_sk=c.substring(l+1),o+=2}else if(i==="--save-auth")t.saveAuth=!0,o+=1;else if(i==="--name")o+1>=e.length||e[o+1].startsWith("--")?o+=1:(t.pubName=e[o+1],o+=2);else if(i==="--clear-auth")t.clearAuth=!0,o+=1;else if(i==="--allow-clone")t.allowClone=!0,o+=1;else{t.remainingArgs=e.slice(o);break}}if(t.needAKSKPrompt)try{let{ak:i,sk:c}=await this.promptForAKSK();t.auth_ak=i,t.auth_sk=c,delete t.needAKSKPrompt}catch(i){console.error(`\u274C ${i.message}`),process.exit(1)}if(t.command!=="login"&&(!t.auth_ak&&s.auth&&s.auth.ak&&(t.auth_ak=s.auth.ak),!t.auth_sk&&s.auth&&s.auth.sk&&(t.auth_sk=s.auth.sk),!t.auth_ak&&process.env.CODEV_AUTH_AK&&(t.auth_ak=process.env.CODEV_AUTH_AK),!t.auth_sk&&process.env.CODEV_AUTH_SK&&(t.auth_sk=process.env.CODEV_AUTH_SK)),t.saveAuth&&t.auth_ak&&t.auth_sk){let i=this.saveAuthToConfig(t.auth_ak,t.auth_sk);console.log(i?"\u2705 API Key \u5DF2\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6":"\u274C \u4FDD\u5B58 API Key \u5931\u8D25"),process.exit(0)}if(t.clearAuth){let i=this.clearAuthFromConfig();console.log(i?"\u2705 API Key \u5DF2\u4ECE\u914D\u7F6E\u6587\u4EF6\u6E05\u9664":"\u274C \u6E05\u9664 API Key \u5931\u8D25"),process.exit(0)}let r=t.remainingArgs.includes("--version")||t.remainingArgs.includes("-v"),a=t.remainingArgs.includes("--help")||t.remainingArgs.includes("-h");if(t.command!=="login"&&t.command!=="skills"&&!r&&!a&&(!t.auth_ak||!t.auth_sk))try{console.log(`\u274C \u7F3A\u5C11\u5FC5\u8981\u7684 API Key
135
+ `),s}finally{this.callbackServer&&this.callbackServer.cleanup()}}cleanup(){this.callbackServer&&this.callbackServer.cleanup()}};ne.exports=B});var ce=m((Vs,ae)=>{var v=require("fs"),ie=require("path"),ss=require("os"),ts=require("readline"),os=re(),L=class{constructor(){this.configPath=ie.join(ss.homedir(),".coder","config.json"),this.defaultConfig={agent:"claude",auth:{ak:null,sk:null}}}async promptForAKSK(){let e=ts.createInterface({input:process.stdin,output:process.stdout});return new Promise((s,t)=>{console.log(`
136
+ \u{1F510} \u8BF7\u8F93\u5165\u60A8\u7684 API Key\uFF1A`),e.question("\u8BF7\u8F93\u5165 API Key: ",o=>{let n=o.indexOf(".");if(n===-1||n===0||n===o.length-1){e.close(),t(new Error("\u683C\u5F0F\u9519\u8BEF"));return}let r=o.substring(0,n),c=o.substring(n+1);if(!r.trim()||!c.trim()){e.close(),t(new Error("\u683C\u5F0F\u9519\u8BEF"));return}e.close(),s({ak:r.trim(),sk:c.trim()})})})}ensureConfig(){let e=ie.dirname(this.configPath);try{v.existsSync(e)||v.mkdirSync(e,{recursive:!0}),v.existsSync(this.configPath)||v.writeFileSync(this.configPath,JSON.stringify(this.defaultConfig,null,2))}catch(s){return console.warn(`Warning: Could not create config file: ${s.message}`),this.defaultConfig}}loadConfig(){this.ensureConfig();try{let e=v.readFileSync(this.configPath,"utf8");return JSON.parse(e)}catch(e){return console.warn(`Warning: Could not load config, using defaults: ${e.message}`),this.defaultConfig}}async parse(e=process.argv.slice(2)){let s=this.loadConfig(),t={agent:s.agent||"claude",remainingArgs:[]},o=0,n=!1;for(e.length>0&&["claude","gemini","codex"].includes(e[0])?(t.agent=e[0],n=!0,o=1):e.length>0&&e[0]==="pub"?(t.command="pub",o=1):e.length>0&&e[0]==="login"?(t.command="login",o=1):e.length>0&&e[0]==="update"?(t.command="update",o=1):e.length>0&&e[0]==="skills"&&(t.command="skills",t.skillsSubcommand=e[1],t.skillsArg=e[2],o=e.length);o<e.length;){let i=e[o];if(i==="--agent"){if(n)throw new Error(`Cannot use both subcommand '${t.agent}' and --agent flag. Please use only one method to specify the agent.`);if(o+1>=e.length)throw new Error("--agent requires a value (claude, gemini, or codex)");let a=e[o+1];if(!["claude","gemini","codex"].includes(a))throw new Error(`Invalid agent: ${a}. Must be 'claude', 'gemini', or 'codex'`);t.agent=a,o+=2}else if(i==="--apikey"||i==="--aksk")if(o+1>=e.length||e[o+1].startsWith("--"))t.needAKSKPrompt=!0,o+=1;else{let a=e[o+1],l=a.indexOf(".");if(l===-1)throw new Error("API Key Format error");t.auth_ak=a.substring(0,l),t.auth_sk=a.substring(l+1),o+=2}else if(i==="--save-auth")t.saveAuth=!0,o+=1;else if(i==="--name")o+1>=e.length||e[o+1].startsWith("--")?o+=1:(t.pubName=e[o+1],o+=2);else if(i==="--clear-auth")t.clearAuth=!0,o+=1;else if(i==="--allow-clone")t.allowClone=!0,o+=1;else{t.remainingArgs=e.slice(o);break}}if(t.needAKSKPrompt)try{let{ak:i,sk:a}=await this.promptForAKSK();t.auth_ak=i,t.auth_sk=a,delete t.needAKSKPrompt}catch(i){console.error(`\u274C ${i.message}`),process.exit(1)}if(t.command!=="login"&&(!t.auth_ak&&s.auth&&s.auth.ak&&(t.auth_ak=s.auth.ak),!t.auth_sk&&s.auth&&s.auth.sk&&(t.auth_sk=s.auth.sk),!t.auth_ak&&process.env.CODEV_AUTH_AK&&(t.auth_ak=process.env.CODEV_AUTH_AK),!t.auth_sk&&process.env.CODEV_AUTH_SK&&(t.auth_sk=process.env.CODEV_AUTH_SK)),t.saveAuth&&t.auth_ak&&t.auth_sk){let i=this.saveAuthToConfig(t.auth_ak,t.auth_sk);console.log(i?"\u2705 API Key \u5DF2\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6":"\u274C \u4FDD\u5B58 API Key \u5931\u8D25"),process.exit(0)}if(t.clearAuth){let i=this.clearAuthFromConfig();console.log(i?"\u2705 API Key \u5DF2\u4ECE\u914D\u7F6E\u6587\u4EF6\u6E05\u9664":"\u274C \u6E05\u9664 API Key \u5931\u8D25"),process.exit(0)}let r=t.remainingArgs.includes("--version")||t.remainingArgs.includes("-v"),c=t.remainingArgs.includes("--help")||t.remainingArgs.includes("-h");if(t.command!=="login"&&t.command!=="skills"&&!r&&!c&&(!t.auth_ak||!t.auth_sk))try{console.log(`\u274C \u7F3A\u5C11\u5FC5\u8981\u7684 API Key
137
137
  `),console.log(`\u{1F510} \u6B63\u5728\u542F\u52A8\u767B\u5F55\u6D41\u7A0B...
138
- `);let c=await new Qe({baseUrl:"https://makecoder.com",apiBaseUrl:t.codevServer||"https://makecoder.com/bigapis/codev/v1"}).login();t.auth_ak=c.ak,t.auth_sk=c.sk;let l=this.saveAuthToConfig(c.ak,c.sk);console.log(l?`\u2705 API Key \u5DF2\u81EA\u52A8\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6
138
+ `);let a=await new os({baseUrl:"https://makecoder.com",apiBaseUrl:t.codevServer||"https://makecoder.com/bigapis/codev/v1"}).login();t.auth_ak=a.ak,t.auth_sk=a.sk;let l=this.saveAuthToConfig(a.ak,a.sk);console.log(l?`\u2705 API Key \u5DF2\u81EA\u52A8\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6
139
139
  `:`\u26A0\uFE0F API Key \u83B7\u53D6\u6210\u529F\u4F46\u672A\u80FD\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6,\u4E0B\u6B21\u4F7F\u7528\u9700\u8981\u91CD\u65B0\u767B\u5F55
140
140
  `)}catch(i){console.error(`
141
141
  \u274C \u767B\u5F55\u5931\u8D25: ${i.message}
@@ -145,7 +145,7 @@ var Be=Object.create;var Y=Object.defineProperty;var Ne=Object.getOwnPropertyDes
145
145
  \u{1F680} \u624B\u52A8\u4F7F\u7528\u65B9\u5F0F\uFF1A
146
146
  coder --apikey <\u4F60\u7684API Key>
147
147
  \u6216\u8005\uFF1Acoder --apikey \uFF08\u7136\u540E\u5B89\u5168\u8F93\u5165\uFF09
148
- `),process.exit(1)}return process.env.CODEV_SERVER?t.codevServer=process.env.CODEV_SERVER:s.codevServer?t.codevServer=s.codevServer:t.codevServer="https://makecoder.com/bigapis/codev/v1",t}saveAuthToConfig(e,s){let t=this.loadConfig();t.auth||(t.auth={}),t.auth.ak=e,t.auth.sk=s;try{return C.writeFileSync(this.configPath,JSON.stringify(t,null,2)),!0}catch(o){return console.warn(`Warning: Could not save auth to config: ${o.message}`),!1}}clearAuthFromConfig(){let e=this.loadConfig();e.auth&&(e.auth.ak=null,e.auth.sk=null);try{return C.writeFileSync(this.configPath,JSON.stringify(e,null,2)),!0}catch(s){return console.warn(`Warning: Could not clear auth from config: ${s.message}`),!1}}showHelp(){console.log(`
148
+ `),process.exit(1)}return process.env.CODEV_SERVER?t.codevServer=process.env.CODEV_SERVER:s.codevServer?t.codevServer=s.codevServer:t.codevServer="https://makecoder.com/bigapis/codev/v1",t}saveAuthToConfig(e,s){let t=this.loadConfig();t.auth||(t.auth={}),t.auth.ak=e,t.auth.sk=s;try{return v.writeFileSync(this.configPath,JSON.stringify(t,null,2)),!0}catch(o){return console.warn(`Warning: Could not save auth to config: ${o.message}`),!1}}clearAuthFromConfig(){let e=this.loadConfig();e.auth&&(e.auth.ak=null,e.auth.sk=null);try{return v.writeFileSync(this.configPath,JSON.stringify(e,null,2)),!0}catch(s){return console.warn(`Warning: Could not clear auth from config: ${s.message}`),!1}}showHelp(){console.log(`
149
149
  Coder AI Agent
150
150
 
151
151
  USAGE:
@@ -194,37 +194,37 @@ CONFIG:
194
194
  Default configuration is stored in ~/.coder/config.json
195
195
  Command line --agent overrides the default but doesn't modify the file.
196
196
  Auth credentials can be stored in config file under "auth" section.
197
- `)}};oe.exports=q});var P=f((Fs,re)=>{function Ye(u=process.argv.slice(2)){return u.includes("--print")||u.includes("-p")}re.exports={isPrintMode:Ye}});var $=f((Ms,ce)=>{var{spawn:Ze}=require("child_process"),I=require("path"),E=require("fs"),ie=require("os"),{isPrintMode:ae}=P(),U=class{constructor(e){this.config=e}resloveSettingFilePath(e){return I.join(e,this.config.configDir,"settings.json")}readModelFromSettingsFile(e){try{let s=this.resloveSettingFilePath(e);if(E.existsSync(s)){let t=E.readFileSync(s,"utf8"),o=JSON.parse(t);if(o&&o.model)return o.model}}catch(s){console.warn(e,s.message)}return null}getCurrentModel(e){let s=e.findIndex(o=>o==="--model");if(s!==-1&&s+1<e.length)return e[s+1];let t=this.readModelFromSettingsFile(process.cwd());return t||(t=this.readModelFromSettingsFile(ie.homedir()),t)?t:this.config.defaultModel}async ensureConfig(e=0){let s=I.join(ie.homedir(),this.config.configDir,this.config.configFile),t=I.dirname(s);if(!E.existsSync(s)){let o=this.config.defaultConfig||{};try{E.existsSync(t)||E.mkdirSync(t,{recursive:!0}),E.writeFileSync(s,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=I.dirname(require.main.filename);for(let s of this.config.executablePaths){let t=I.resolve(e,s);if(E.existsSync(t))return t}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",s=>{this.onChildMessage(s)}),e.on("exit",async(s,t)=>{try{await this.handleChildProcessExit(s,t)}catch(o){console.error("Error in handleChildProcessExit:",o.message)}}),e.on("error",s=>{this.handleChildProcessError(s)}))}onChildMessage(e){process.env.CODEV_DEBUG&&console.log("Received IPC message from child:",e)}handleChildProcessExit(e,s){}handleChildProcessError(e){}async launch(e={}){let{remainingArgs:s=[],codevServer:t,auth_ak:o=null,auth_sk:n=null}=e;try{let r=this.getCurrentModel(s);ae(s)||console.log(`model:\x1B[90m\x1B[3m ${r} (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((i,c)=>{let l={...process.env,...this.config.environmentVariables(t)};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,...s);let g=Ze("node",h,{env:l,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(g),g.on("error",S=>{console.error(`Failed to start: ${S.message}`),c(S)}),g.on("exit",async(S,Q)=>{ae(s)||Q&&console.log(`terminated by signal: ${Q}`)}),process.on("SIGINT",async()=>{console.log(`
198
- Terminating ...`),g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
199
- Terminating ...`),g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},8e3)})})}catch(r){throw r}}};ce.exports=U});var ue=f((qs,le)=>{var d=process.env.CODEV_DEBUG==="True",B=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 d&&console.log("Queue is shutting down, skipping new messages"),null;let s={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(s),d&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),s.id}dequeue(){let e=this.queue.shift();return d&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let s=this.queue.findIndex(t=>t.id===e);return s>-1?(this.queue.splice(s,1),d&&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(s){if(d&&console.error(`Failed to process message: ${s.message}`),e.retryCount++,d&&console.log("Start Retry:",e.retryCount,"times..."),e.retryCount>=this.maxRetries)d&&console.error("Message exceeded max retries, removing from queue"),this.dequeue();else{e.processing=!1;let t=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,t))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],d&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let s=this.queue.filter(o=>o.processing);if(s.length===0)return;d&&console.log(`Waiting for ${s.length} processing messages to complete (timeout: ${e}ms)`);let t=Date.now();for(;Date.now()-t<e;){if(this.queue.filter(n=>n.processing).length===0){d&&console.log(`All processing messages completed in ${Date.now()-t}ms`);return}await new Promise(n=>setTimeout(n,50))}if(d){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:s=this.shutdownTimeout,batchSize:t=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async n=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(s*.3,3e3));let r=this.queue.filter(S=>!S.processing),a=r.length;d&&(console.log(`Starting graceful shutdown with ${a} pending messages (${this.queue.length-a} already processing)`),console.log(`Mode: ${o?"fast (parallel)":"sequential"}, timeout: ${s}ms`));let i=Date.now(),c=0,l=0;try{if(o){let S=await this.processAllParallel(s-(Date.now()-i),r);c=S.processed,l=S.failed}else{let S=await this.processInBatches(t,s-(Date.now()-i),r);c=S.processed,l=S.failed}}catch(S){d&&console.error("Error during shutdown processing:",S.message)}let h=Date.now()-i,g=this.queue.length;d&&(console.log(`Shutdown completed in ${h}ms:`),console.log(` - Total: ${a} messages`),console.log(` - Processed: ${c}`),console.log(` - Failed: ${l}`),console.log(` - Remaining: ${g}`)),n({totalMessages:a,processedMessages:c,failedMessages:l,remainingMessages:g,duration:h,allMessagesSent:g===0&&l===0})}),this.shutdownPromise}async processAllParallel(e){if(this.queue.length===0)return{processed:0,failed:0};d&&console.log(`Processing ${this.queue.length} messages in parallel...`);let s=[...this.queue];this.queue=[];let t=s.map(async i=>{try{return this.onProcessMessage&&await this.onProcessMessage(i),{success:!0,messageId:i.id}}catch(c){return d&&console.warn(`Message ${i.id} processing failed: ${c.message}`),{success:!1,messageId:i.id,error:c}}}),o=new Promise(i=>{setTimeout(()=>i({timedOut:!0}),e)}),n=await Promise.race([Promise.allSettled(t).then(i=>({results:i})),o]);if(n.timedOut)return d&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:s.length};let r=n.results.filter(i=>i.status==="fulfilled"&&i.value?.success).length,a=s.length-r;return{processed:r,failed:a}}async processInBatches(e,s){if(this.queue.length===0)return{processed:0,failed:0};d&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let t=Date.now(),o=0,n=0;for(;this.queue.length>0&&Date.now()-t<s;){let r=this.queue.splice(0,e),a=r.map(async h=>{try{return this.onProcessMessage&&await this.onProcessMessage(h),{success:!0}}catch(g){return d&&console.warn(`Batch message processing failed: ${g.message}`),{success:!1,error:g}}}),c=(await Promise.allSettled(a)).filter(h=>h.status==="fulfilled"&&h.value?.success).length,l=r.length-c;o+=c,n+=l,d&&r.length>0&&console.log(`Batch completed: ${c}/${r.length} successful`),this.queue.length>0&&await new Promise(h=>setTimeout(h,10))}return this.queue.length>0&&(n+=this.queue.length,d&&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 s=this.queue.filter(i=>!i.processing);d&&console.log(`Force flush: attempting to send ${s.length} pending messages within ${e}ms (${this.queue.length-s.length} already processing)`);let t=Date.now(),o=s.map(async i=>{try{return this.onProcessMessage&&Date.now()-t<e?(await this.onProcessMessage(i),{success:!0,messageId:i.id}):{success:!1,messageId:i.id,reason:"timeout"}}catch(c){return{success:!1,messageId:i.id,error:c.message}}}),n=e-(Date.now()-t),r=new Promise(i=>{setTimeout(()=>i({timedOut:!0}),Math.max(100,n))}),a=await Promise.race([Promise.allSettled(o).then(i=>({results:i})),r]);if(s.forEach(i=>{let c=this.queue.findIndex(l=>l.id===i.id);c>-1&&this.queue.splice(c,1)}),this.processing=!1,a.timedOut)return d&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:s.length};{let i=a.results.filter(c=>c.status==="fulfilled"&&c.value.success).length;return d&&console.log(`Force flush completed: ${i}/${s.length} messages sent`),{success:i===s.length,successCount:i,totalCount:s.length,results:a.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,d&&console.log("Force shutdown: Queue cleared")}};le.exports=B});var T=f((Us,Xe)=>{Xe.exports={name:"makecoder",version:"2.0.84",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",repository:{type:"git",url:"https://github.com/makecoderai/coder.git"},homepage:"https://github.com/makecoderai/coder",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 fe=f((Bs,ge)=>{var es=require("http"),ss=require("https"),{URL:he}=require("url"),{version:ts}=T(),de=process.env.CODEV_DEBUG==="True",N=class{constructor(e={}){this.baseUrl=e.baseUrl||"",this.timeout=e.timeout||3e4,this.defaultHeaders={"Content-Type":"application/json","User-Agent":`codev-cli/${ts}`,...e.headers}}setBaseUrl(e){this.baseUrl=e}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}async post(e,s,t={}){let o=this.resolveUrl(e),n={...this.defaultHeaders,...t.headers};return new Promise((r,a)=>{this.validateRequest(o,s,a);let i=this.serializeData(s,a);if(!i)return;n["Content-Length"]=Buffer.byteLength(i);let c=this.buildRequestOptions(o,"POST",n),l=this.getHttpModule(o);de&&console.debug(`HTTP POST to ${o} with data length: ${i.length}`);let h=l.request(c,g=>{this.handleResponse(g,r,a)});this.attachErrorHandlers(h,o,a),h.setTimeout(this.timeout),h.write(i),h.end()})}resolveUrl(e){return e.startsWith("http")?e:`${this.baseUrl}${e.startsWith("/")?"":"/"}${e}`}validateRequest(e,s,t){return!e||typeof e!="string"?(t(new Error(`Invalid URL: ${e}`)),!1):s?!0:(t(new Error("No data provided for HTTP POST")),!1)}serializeData(e,s){try{return typeof e=="string"?e:JSON.stringify(e)}catch(t){return s(new Error(`Failed to serialize data: ${t.message}`)),null}}buildRequestOptions(e,s,t){let o=new he(e),n=o.protocol==="https:";return{hostname:o.hostname,port:o.port||(n?443:80),path:o.pathname+o.search,method:s,headers:t}}getHttpModule(e){return new he(e).protocol==="https:"?ss:es}handleResponse(e,s,t){de&&console.debug(`HTTP response status: ${e.statusCode}`);let o="";e.on("data",n=>{o+=n}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?s({statusCode:e.statusCode,data:o,headers:e.headers}):t(new Error(`HTTP request returned status ${e.statusCode}: ${o}`))})}attachErrorHandlers(e,s,t){e.on("error",o=>{t(new Error(`HTTP POST request failed: ${o.message}`))}),e.on("timeout",()=>{t(new Error(`HTTP POST request timed out for URL: ${s}`)),e.destroy()})}};ge.exports=N});var pe=f((Ns,me)=>{var os=require("crypto"),{URL:ns}=require("url"),R=class{static generateSignature(e,s,t,o){try{let n=new ns(e),r=Buffer.from(n.pathname),a=Buffer.from(r),i=s?typeof s=="string"?Buffer.from(s):Buffer.from(JSON.stringify(s)):Buffer.alloc(0),c=Buffer.concat([a,i,Buffer.from(o)]),l=os.createHmac("sha256",t);return l.update(c),l.digest("hex")}catch(n){throw new Error(`Failed to generate signature: ${n.message}`)}}static validateSignature(e,s,t,o,n){return this.generateSignature(e,s,t,o)===n}static generateTimestamp(){return Date.now().toString()}};me.exports=R});var ye=f((Rs,Se)=>{var rs=pe(),V=class{constructor(e={}){this.accessKey=null,this.secretKey=null,this.validateCredentials=e.validateCredentials!==!1}setCredentials(e,s){if(this.validateCredentials&&(!e||!s))throw new Error("Both access key and secret key are required");this.accessKey=e,this.secretKey=s}hasCredentials(){return!!(this.accessKey&&this.secretKey)}generateAuthHeaders(e,s=null){if(!this.hasCredentials())return{};try{return{AUTHORIZATION:`Bearer ${this.accessKey}.${this.secretKey}`}}catch(t){throw new Error(`Failed to generate auth headers: ${t.message}`)}}validateAuthHeaders(e,s,t,o){if(!this.hasCredentials())throw new Error("No credentials available for validation");return rs.validateSignature(e,s,this.secretKey,t,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};Se.exports=V});var Ce=f((Vs,we)=>{var k=process.env.CODEV_DEBUG==="True",G=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 k&&console.warn("Received empty session ID"),!1;let s=this.previousSessionId!==null&&this.previousSessionId!==e;return s&&(k&&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,s}getCurrentSessionId(){return this.currentSessionId}getPreviousSessionId(){return this.previousSessionId}hasActiveSession(){return!!this.currentSessionId}terminateCurrentSession(e="Session terminated",s=null,t=null){if(!this.hasActiveSession())return k&&console.log("No active session to terminate"),null;let o={type:this.terminateSignal,reason:t?`terminated by signal: ${t}`:e,code:s,signal:t,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId};return k&&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(){k&&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()}}};we.exports=G});var ve=f((Gs,Ee)=>{var v=require("fs"),b=require("path"),is=require("events"),as=require("crypto"),p=process.env.CODEV_DEBUG==="True",L=class extends is{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 s=v.readFileSync(e,"utf8");return as.createHash("sha256").update(s).digest("hex")}catch{return null}}hasContentChanged(e){if(!this.enableContentComparison)return!0;let s=this.calculateFileHash(e),t=this.fileContentHashes.get(e);return s===null?t!==void 0?(this.fileContentHashes.delete(e),!0):!1:t===void 0||s!==t?(this.fileContentHashes.set(e,s),!0):!1}preloadFileHashes(e){if(!(!this.enableContentComparison||!v.existsSync(e)))try{let s=v.readdirSync(e,{withFileTypes:!0});for(let t of s){let o=b.join(e,t.name);t.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):t.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(s){p&&console.warn(`Failed to preload hashes for ${e}:`,s.message)}}shouldExcludeDirectory(e){let s=e.replace(/\\/g,"/");for(let t of this.excludePatterns)if(t.test(s)||t.test(b.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){p&&console.log("FileWatchService is already watching");return}let s=e||this.watchPaths;if(s.length===0){p&&console.log("No watch paths specified");return}this.isWatching=!0;for(let t of s)this.enableContentComparison&&this.preloadFileHashes(t),this.watchDirectory(t);p&&(console.log(`FileWatchService started watching ${s.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,s]of this.watchers)try{s.close(),p&&console.log(`Stopped watching: ${e}`)}catch(t){p&&console.error(`Error stopping watcher for ${e}:`,t.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),p&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!v.existsSync(e)){p&&console.warn(`Watch path does not exist: ${e}`);return}if(!v.statSync(e).isDirectory()){p&&console.warn(`Watch path is not a directory: ${e}`);return}try{let t=v.watch(e,{recursive:!0,persistent:!1},(o,n)=>{if(!n)return;let r=b.join(e,n);this.handleFileChange(o,r,e)});this.watchers.set(e,t),p&&console.log(`Started watching directory: ${e}`),t.on("error",o=>{p&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(t){p&&console.error(`Failed to start watching ${e}:`,t.message)}}handleFileChange(e,s,t){if(!this.shouldWatchFile(s))return;let o=`${e}:${s}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,s,t)},this.debounceTimeout))}processFileChange(e,s,t){if(!this.isWatching)return;let o="modified",n=!1;try{v.statSync(s),n=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(n&&(o==="modified"||o==="created")&&!this.hasContentChanged(s)){p&&console.log(`Ignoring false change for: ${b.relative(t,s)}`);return}!n&&o==="deleted"&&this.fileContentHashes.delete(s);let r={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:s,relativePath:b.relative(t,s),watchPath:t,fileExists:n,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(p&&console.log(`File ${o}: ${r.data.relativePath}`),this.emit("fileChange",r),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(r)}catch(a){p&&console.error("Error in file change callback:",a.message)}}shouldWatchFile(e){let s=b.basename(e),t=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(t)||o.test(s))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(t)||o.test(s))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let s=this.watchPaths.indexOf(e);if(s>-1&&(this.watchPaths.splice(s,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),p&&console.log(`Removed watch path: ${e}`)}catch(t){p&&console.error(`Error removing watch path ${e}:`,t.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};Ee.exports=L});var be=f((Ks,xe)=>{var cs=$(),ls=require("path"),Ls=require("fs"),Hs=require("os"),us=ue(),hs=fe(),ds=ye(),gs=Ce(),fs=ve(),m=process.env.CODEV_DEBUG==="True",H=class extends cs{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 hs({timeout:1e4}),this.authService=new ds({validateCredentials:!1}),this.sessionManager=new gs({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new us({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return ls.join(e,this.config.configDir,".claude","settings.json")}initializeFileWatchService(){if(!process.env.SESSION_ID){m&&console.log("FileWatchService disabled: SESSION_ID environment variable not found");return}try{this.fileWatchService=new fs({watchPaths:this.getFileWatchPaths(),onFileChange:e=>this.handleFileChange(e),debounceTimeout:300}),m&&console.log("FileWatchService initialized with SESSION_ID:",process.env.SESSION_ID)}catch(e){m&&console.error("Failed to initialize FileWatchService:",e.message)}}getFileWatchPaths(){let e=[],s=process.cwd();e.push(s);let t=process.env.CODEV_WATCH_PATHS;if(t){let o=t.split(",").map(n=>n.trim());e.push(...o)}return e}handleFileChange(e){if(m&&console.log("File change detected:",e.data.relativePath),this.shutdownInProgress)return;let s={message:e,sessionId:e.data.sessionId||process.env.SESSION_ID};this.messageQueue.enqueue(s)}startFileWatching(){this.fileWatchService&&!this.fileWatchService.isWatching&&(this.fileWatchService.startWatching(),m&&console.log("File watching started"))}stopFileWatching(){this.fileWatchService&&this.fileWatchService.isWatching&&(this.fileWatchService.stopWatching(),m&&console.log("File watching stopped"))}onChildMessage(e){e&&e.type==="claude:send-msg"&&this.handleClaudeSendMessage(e.data),super.onChildMessage(e)}handleClaudeSendMessage(e){if(m&&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){m&&console.log("Shutdown in progress, ignoring new message");return}let s=e.sessionId||process.env.SESSION_ID;this.sessionManager.handleSessionSwitch(s),this.messageQueue.enqueue(e)}async processMessage(e){let s=e.data.message,t=e.data.sessionId||process.env.SESSION_ID;if(!t)throw new Error("No session ID available");let o;try{o=typeof s=="string"?JSON.parse(s):s}catch(a){throw new Error(`Failed to parse message data: ${a.message}`)}let n=`/conversations/${t}/@append?task_type=codev`,r=this.authService.hasCredentials()?this.authService.generateAuthHeaders(`${this.httpClient.baseUrl}${n}`,o):{};m&&(console.debug("Sending message to:",n),console.debug("Send Message: ",JSON.stringify(o))),e.type!=="CODEV_TERMINATE_SIGNAL"&&(this.sessionManager.currentSessionId=t)}sendTerminationMessage(e){let s={message:e,sessionId:e.sessionId||this.sessionManager.getCurrentSessionId()};this.messageQueue.enqueue(s)}async handleChildProcessExit(e,s){m&&console.log(`Child process exited with code: ${e}, signal: ${s}`),this.stopFileWatching();let t=this.messageQueue.getQueueSize(),o=this.sessionManager.terminateCurrentSession("process exited normally",e,s);if(o&&this.sendTerminationMessage(o),t>0||o){m&&console.log("Starting graceful shutdown of message queue...");try{let n=!s||s==="SIGTERM",r=this.messageQueue.getQueueSize(),a={timeoutMs:n?8e3:3e3,batchSize:Math.min(r,15),fastMode:!n||r>30};m&&console.log("Shutdown options:",a);let i=await this.messageQueue.gracefulShutdown(a);m&&console.log("Message queue shutdown completed:",i),i.failedMessages>0&&m&&console.warn(`Shutdown summary: ${i.processedMessages} sent, ${i.failedMessages} failed, ${i.remainingMessages} remaining`)}catch(n){m&&console.error("Error during message queue shutdown:",n.message)}}}handleChildProcessError(e){m&&console.error(`Child process error: ${e.message}`);let s=this.sessionManager.createErrorTermination(e);s&&this.sendTerminationMessage(s)}async forceFlushMessages(e=3e3){if(this.messageQueue.getQueueSize()===0)return{success:!0,message:"No messages to flush"};m&&console.log(`Force flushing ${this.messageQueue.getQueueSize()} messages...`);try{return await this.messageQueue.forceFlushAndShutdown(e)}catch(s){return m&&console.error("Force flush failed:",s.message),{success:!1,error:s.message}}}async launch(e={}){let{codevServer:s,auth_ak:t=null,auth_sk:o=null}=e;return this.httpClient.setBaseUrl(s),t&&o&&this.authService.setCredentials(t,o),this.startFileWatching(),super.launch(e)}};xe.exports=H});var ke=f((Ws,Ie)=>{var ms=$(),zs=require("path"),K=class extends ms{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"}}}})}};Ie.exports=K});var De=f((js,_e)=>{var ps=$(),_=require("path"),w=require("fs"),Ss=require("os"),{spawn:ys}=require("child_process"),O=process.env.CODEV_DEBUG==="True",z=class extends ps{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:O?"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 w.existsSync(e)}catch{return!1}}resloveSettingFilePath(e){return _.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,s=0){let t=_.join(Ss.homedir(),this.config.configDir,this.config.configFile),o=_.dirname(t);try{w.existsSync(o)||w.mkdirSync(o,{recursive:!0});let n=`${e}/codex`;if(w.existsSync(t)){let r=w.readFileSync(t,"utf8"),a=`openai_base_url = "${n}"`;/^openai_base_url\s*=/m.test(r)?r=r.replace(/^openai_base_url\s*=.*/m,a):r=r.trimEnd()+`
200
- `+a+`
201
- `,w.writeFileSync(t,r),O&&console.log(`Updated openai_base_url in ${t}`)}else{let r=this.config.defaultConfig||{},a=this.generateTOMLConfig(r,n);w.writeFileSync(t,a),O&&console.log(`Created Codex config file: ${t}`)}s>0&&await new Promise(r=>setTimeout(r,s))}catch(n){console.warn(`Failed to update ${this.config.configFile}: ${n.message}`)}}generateTOMLConfig(e,s){return`model = "${e.model||"gpt-5-codex"}"
197
+ `)}};ae.exports=L});var T=m((Gs,le)=>{function ns(u=process.argv.slice(2)){return u.includes("--print")||u.includes("-p")}le.exports={isPrintMode:ns}});var O=m((Hs,de)=>{var{spawn:rs}=require("child_process"),I=require("path"),E=require("fs"),ue=require("os"),{isPrintMode:he}=T(),N=class{constructor(e){this.config=e}resloveSettingFilePath(e){return I.join(e,this.config.configDir,"settings.json")}readModelFromSettingsFile(e){try{let s=this.resloveSettingFilePath(e);if(E.existsSync(s)){let t=E.readFileSync(s,"utf8"),o=JSON.parse(t);if(o&&o.model)return o.model}}catch(s){console.warn(e,s.message)}return null}getCurrentModel(e){let s=e.findIndex(o=>o==="--model");if(s!==-1&&s+1<e.length)return e[s+1];let t=this.readModelFromSettingsFile(process.cwd());return t||(t=this.readModelFromSettingsFile(ue.homedir()),t)?t:this.config.defaultModel}async ensureConfig(e=0){let s=I.join(ue.homedir(),this.config.configDir,this.config.configFile),t=I.dirname(s);if(!E.existsSync(s)){let o=this.config.defaultConfig||{};try{E.existsSync(t)||E.mkdirSync(t,{recursive:!0}),E.writeFileSync(s,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=I.dirname(require.main.filename);for(let s of this.config.executablePaths){let t=I.resolve(e,s);if(E.existsSync(t))return t}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",s=>{this.onChildMessage(s)}),e.on("exit",async(s,t)=>{try{await this.handleChildProcessExit(s,t)}catch(o){console.error("Error in handleChildProcessExit:",o.message)}}),e.on("error",s=>{this.handleChildProcessError(s)}))}onChildMessage(e){process.env.CODEV_DEBUG&&console.log("Received IPC message from child:",e)}handleChildProcessExit(e,s){}handleChildProcessError(e){}async launch(e={}){let{remainingArgs:s=[],codevServer:t,auth_ak:o=null,auth_sk:n=null}=e;try{let r=this.getCurrentModel(s);he(s)||console.log(`model:\x1B[90m\x1B[3m ${r} (use /model to switch models) \x1B[0m`),await this.ensureConfig(1e3);let c=this.findExecutablePath();return process.env.CODEV_DEBUG&&console.log(`executablePath: ${c}`),new Promise((i,a)=>{let l={...process.env,...this.config.environmentVariables(t)};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(c,...s);let d=rs("node",h,{env:l,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(d),d.on("error",f=>{console.error(`Failed to start: ${f.message}`),a(f)}),d.on("exit",async(f,ee)=>{he(s)||ee&&console.log(`terminated by signal: ${ee}`)}),process.on("SIGINT",async()=>{console.log(`
198
+ Terminating ...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
199
+ Terminating ...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},8e3)})})}catch(r){throw r}}};de.exports=N});var fe=m((Ks,ge)=>{var g=process.env.CODEV_DEBUG==="True",R=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 g&&console.log("Queue is shutting down, skipping new messages"),null;let s={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(s),g&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),s.id}dequeue(){let e=this.queue.shift();return g&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let s=this.queue.findIndex(t=>t.id===e);return s>-1?(this.queue.splice(s,1),g&&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(s){if(g&&console.error(`Failed to process message: ${s.message}`),e.retryCount++,g&&console.log("Start Retry:",e.retryCount,"times..."),e.retryCount>=this.maxRetries)g&&console.error("Message exceeded max retries, removing from queue"),this.dequeue();else{e.processing=!1;let t=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,t))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],g&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let s=this.queue.filter(o=>o.processing);if(s.length===0)return;g&&console.log(`Waiting for ${s.length} processing messages to complete (timeout: ${e}ms)`);let t=Date.now();for(;Date.now()-t<e;){if(this.queue.filter(n=>n.processing).length===0){g&&console.log(`All processing messages completed in ${Date.now()-t}ms`);return}await new Promise(n=>setTimeout(n,50))}if(g){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:s=this.shutdownTimeout,batchSize:t=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async n=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(s*.3,3e3));let r=this.queue.filter(f=>!f.processing),c=r.length;g&&(console.log(`Starting graceful shutdown with ${c} pending messages (${this.queue.length-c} already processing)`),console.log(`Mode: ${o?"fast (parallel)":"sequential"}, timeout: ${s}ms`));let i=Date.now(),a=0,l=0;try{if(o){let f=await this.processAllParallel(s-(Date.now()-i),r);a=f.processed,l=f.failed}else{let f=await this.processInBatches(t,s-(Date.now()-i),r);a=f.processed,l=f.failed}}catch(f){g&&console.error("Error during shutdown processing:",f.message)}let h=Date.now()-i,d=this.queue.length;g&&(console.log(`Shutdown completed in ${h}ms:`),console.log(` - Total: ${c} messages`),console.log(` - Processed: ${a}`),console.log(` - Failed: ${l}`),console.log(` - Remaining: ${d}`)),n({totalMessages:c,processedMessages:a,failedMessages:l,remainingMessages:d,duration:h,allMessagesSent:d===0&&l===0})}),this.shutdownPromise}async processAllParallel(e){if(this.queue.length===0)return{processed:0,failed:0};g&&console.log(`Processing ${this.queue.length} messages in parallel...`);let s=[...this.queue];this.queue=[];let t=s.map(async i=>{try{return this.onProcessMessage&&await this.onProcessMessage(i),{success:!0,messageId:i.id}}catch(a){return g&&console.warn(`Message ${i.id} processing failed: ${a.message}`),{success:!1,messageId:i.id,error:a}}}),o=new Promise(i=>{setTimeout(()=>i({timedOut:!0}),e)}),n=await Promise.race([Promise.allSettled(t).then(i=>({results:i})),o]);if(n.timedOut)return g&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:s.length};let r=n.results.filter(i=>i.status==="fulfilled"&&i.value?.success).length,c=s.length-r;return{processed:r,failed:c}}async processInBatches(e,s){if(this.queue.length===0)return{processed:0,failed:0};g&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let t=Date.now(),o=0,n=0;for(;this.queue.length>0&&Date.now()-t<s;){let r=this.queue.splice(0,e),c=r.map(async h=>{try{return this.onProcessMessage&&await this.onProcessMessage(h),{success:!0}}catch(d){return g&&console.warn(`Batch message processing failed: ${d.message}`),{success:!1,error:d}}}),a=(await Promise.allSettled(c)).filter(h=>h.status==="fulfilled"&&h.value?.success).length,l=r.length-a;o+=a,n+=l,g&&r.length>0&&console.log(`Batch completed: ${a}/${r.length} successful`),this.queue.length>0&&await new Promise(h=>setTimeout(h,10))}return this.queue.length>0&&(n+=this.queue.length,g&&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 s=this.queue.filter(i=>!i.processing);g&&console.log(`Force flush: attempting to send ${s.length} pending messages within ${e}ms (${this.queue.length-s.length} already processing)`);let t=Date.now(),o=s.map(async i=>{try{return this.onProcessMessage&&Date.now()-t<e?(await this.onProcessMessage(i),{success:!0,messageId:i.id}):{success:!1,messageId:i.id,reason:"timeout"}}catch(a){return{success:!1,messageId:i.id,error:a.message}}}),n=e-(Date.now()-t),r=new Promise(i=>{setTimeout(()=>i({timedOut:!0}),Math.max(100,n))}),c=await Promise.race([Promise.allSettled(o).then(i=>({results:i})),r]);if(s.forEach(i=>{let a=this.queue.findIndex(l=>l.id===i.id);a>-1&&this.queue.splice(a,1)}),this.processing=!1,c.timedOut)return g&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:s.length};{let i=c.results.filter(a=>a.status==="fulfilled"&&a.value.success).length;return g&&console.log(`Force flush completed: ${i}/${s.length} messages sent`),{success:i===s.length,successCount:i,totalCount:s.length,results:c.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,g&&console.log("Force shutdown: Queue cleared")}};ge.exports=R});var A=m((js,is)=>{is.exports={name:"makecoder",version:"2.0.86",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",repository:{type:"git",url:"https://github.com/makecoderai/coder.git"},homepage:"https://github.com/makecoderai/coder",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 ye=m((Ws,Se)=>{var as=require("http"),cs=require("https"),{URL:me}=require("url"),{version:ls}=A(),pe=process.env.CODEV_DEBUG==="True",V=class{constructor(e={}){this.baseUrl=e.baseUrl||"",this.timeout=e.timeout||3e4,this.defaultHeaders={"Content-Type":"application/json","User-Agent":`codev-cli/${ls}`,...e.headers}}setBaseUrl(e){this.baseUrl=e}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}async post(e,s,t={}){let o=this.resolveUrl(e),n={...this.defaultHeaders,...t.headers};return new Promise((r,c)=>{this.validateRequest(o,s,c);let i=this.serializeData(s,c);if(!i)return;n["Content-Length"]=Buffer.byteLength(i);let a=this.buildRequestOptions(o,"POST",n),l=this.getHttpModule(o);pe&&console.debug(`HTTP POST to ${o} with data length: ${i.length}`);let h=l.request(a,d=>{this.handleResponse(d,r,c)});this.attachErrorHandlers(h,o,c),h.setTimeout(this.timeout),h.write(i),h.end()})}resolveUrl(e){return e.startsWith("http")?e:`${this.baseUrl}${e.startsWith("/")?"":"/"}${e}`}validateRequest(e,s,t){return!e||typeof e!="string"?(t(new Error(`Invalid URL: ${e}`)),!1):s?!0:(t(new Error("No data provided for HTTP POST")),!1)}serializeData(e,s){try{return typeof e=="string"?e:JSON.stringify(e)}catch(t){return s(new Error(`Failed to serialize data: ${t.message}`)),null}}buildRequestOptions(e,s,t){let o=new me(e),n=o.protocol==="https:";return{hostname:o.hostname,port:o.port||(n?443:80),path:o.pathname+o.search,method:s,headers:t}}getHttpModule(e){return new me(e).protocol==="https:"?cs:as}handleResponse(e,s,t){pe&&console.debug(`HTTP response status: ${e.statusCode}`);let o="";e.on("data",n=>{o+=n}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?s({statusCode:e.statusCode,data:o,headers:e.headers}):t(new Error(`HTTP request returned status ${e.statusCode}: ${o}`))})}attachErrorHandlers(e,s,t){e.on("error",o=>{t(new Error(`HTTP POST request failed: ${o.message}`))}),e.on("timeout",()=>{t(new Error(`HTTP POST request timed out for URL: ${s}`)),e.destroy()})}};Se.exports=V});var Ce=m((zs,we)=>{var us=require("crypto"),{URL:hs}=require("url"),G=class{static generateSignature(e,s,t,o){try{let n=new hs(e),r=Buffer.from(n.pathname),c=Buffer.from(r),i=s?typeof s=="string"?Buffer.from(s):Buffer.from(JSON.stringify(s)):Buffer.alloc(0),a=Buffer.concat([c,i,Buffer.from(o)]),l=us.createHmac("sha256",t);return l.update(a),l.digest("hex")}catch(n){throw new Error(`Failed to generate signature: ${n.message}`)}}static validateSignature(e,s,t,o,n){return this.generateSignature(e,s,t,o)===n}static generateTimestamp(){return Date.now().toString()}};we.exports=G});var Ee=m((Js,ve)=>{var ds=Ce(),H=class{constructor(e={}){this.accessKey=null,this.secretKey=null,this.validateCredentials=e.validateCredentials!==!1}setCredentials(e,s){if(this.validateCredentials&&(!e||!s))throw new Error("Both access key and secret key are required");this.accessKey=e,this.secretKey=s}hasCredentials(){return!!(this.accessKey&&this.secretKey)}generateAuthHeaders(e,s=null){if(!this.hasCredentials())return{};try{return{AUTHORIZATION:`Bearer ${this.accessKey}.${this.secretKey}`}}catch(t){throw new Error(`Failed to generate auth headers: ${t.message}`)}}validateAuthHeaders(e,s,t,o){if(!this.hasCredentials())throw new Error("No credentials available for validation");return ds.validateSignature(e,s,this.secretKey,t,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};ve.exports=H});var be=m((Qs,xe)=>{var $=process.env.CODEV_DEBUG==="True",K=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 $&&console.warn("Received empty session ID"),!1;let s=this.previousSessionId!==null&&this.previousSessionId!==e;return s&&($&&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,s}getCurrentSessionId(){return this.currentSessionId}getPreviousSessionId(){return this.previousSessionId}hasActiveSession(){return!!this.currentSessionId}terminateCurrentSession(e="Session terminated",s=null,t=null){if(!this.hasActiveSession())return $&&console.log("No active session to terminate"),null;let o={type:this.terminateSignal,reason:t?`terminated by signal: ${t}`:e,code:s,signal:t,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId};return $&&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(){$&&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()}}};xe.exports=K});var Ie=m((Ys,ke)=>{var x=require("fs"),k=require("path"),gs=require("events"),fs=require("crypto"),S=process.env.CODEV_DEBUG==="True",j=class extends gs{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 s=x.readFileSync(e,"utf8");return fs.createHash("sha256").update(s).digest("hex")}catch{return null}}hasContentChanged(e){if(!this.enableContentComparison)return!0;let s=this.calculateFileHash(e),t=this.fileContentHashes.get(e);return s===null?t!==void 0?(this.fileContentHashes.delete(e),!0):!1:t===void 0||s!==t?(this.fileContentHashes.set(e,s),!0):!1}preloadFileHashes(e){if(!(!this.enableContentComparison||!x.existsSync(e)))try{let s=x.readdirSync(e,{withFileTypes:!0});for(let t of s){let o=k.join(e,t.name);t.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):t.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(s){S&&console.warn(`Failed to preload hashes for ${e}:`,s.message)}}shouldExcludeDirectory(e){let s=e.replace(/\\/g,"/");for(let t of this.excludePatterns)if(t.test(s)||t.test(k.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){S&&console.log("FileWatchService is already watching");return}let s=e||this.watchPaths;if(s.length===0){S&&console.log("No watch paths specified");return}this.isWatching=!0;for(let t of s)this.enableContentComparison&&this.preloadFileHashes(t),this.watchDirectory(t);S&&(console.log(`FileWatchService started watching ${s.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,s]of this.watchers)try{s.close(),S&&console.log(`Stopped watching: ${e}`)}catch(t){S&&console.error(`Error stopping watcher for ${e}:`,t.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),S&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!x.existsSync(e)){S&&console.warn(`Watch path does not exist: ${e}`);return}if(!x.statSync(e).isDirectory()){S&&console.warn(`Watch path is not a directory: ${e}`);return}try{let t=x.watch(e,{recursive:!0,persistent:!1},(o,n)=>{if(!n)return;let r=k.join(e,n);this.handleFileChange(o,r,e)});this.watchers.set(e,t),S&&console.log(`Started watching directory: ${e}`),t.on("error",o=>{S&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(t){S&&console.error(`Failed to start watching ${e}:`,t.message)}}handleFileChange(e,s,t){if(!this.shouldWatchFile(s))return;let o=`${e}:${s}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,s,t)},this.debounceTimeout))}processFileChange(e,s,t){if(!this.isWatching)return;let o="modified",n=!1;try{x.statSync(s),n=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(n&&(o==="modified"||o==="created")&&!this.hasContentChanged(s)){S&&console.log(`Ignoring false change for: ${k.relative(t,s)}`);return}!n&&o==="deleted"&&this.fileContentHashes.delete(s);let r={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:s,relativePath:k.relative(t,s),watchPath:t,fileExists:n,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(S&&console.log(`File ${o}: ${r.data.relativePath}`),this.emit("fileChange",r),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(r)}catch(c){S&&console.error("Error in file change callback:",c.message)}}shouldWatchFile(e){let s=k.basename(e),t=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(t)||o.test(s))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(t)||o.test(s))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let s=this.watchPaths.indexOf(e);if(s>-1&&(this.watchPaths.splice(s,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),S&&console.log(`Removed watch path: ${e}`)}catch(t){S&&console.error(`Error removing watch path ${e}:`,t.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};ke.exports=j});var _e=m((et,$e)=>{var ms=O(),ps=require("path"),Zs=require("fs"),Xs=require("os"),Ss=fe(),ys=ye(),ws=Ee(),Cs=be(),vs=Ie(),p=process.env.CODEV_DEBUG==="True",W=class extends ms{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 ys({timeout:1e4}),this.authService=new ws({validateCredentials:!1}),this.sessionManager=new Cs({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new Ss({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return ps.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 vs({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=[],s=process.cwd();e.push(s);let t=process.env.CODEV_WATCH_PATHS;if(t){let o=t.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 s={message:e,sessionId:e.data.sessionId||process.env.SESSION_ID};this.messageQueue.enqueue(s)}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 s=e.sessionId||process.env.SESSION_ID;this.sessionManager.handleSessionSwitch(s),this.messageQueue.enqueue(e)}async processMessage(e){let s=e.data.message,t=e.data.sessionId||process.env.SESSION_ID;if(!t)throw new Error("No session ID available");let o;try{o=typeof s=="string"?JSON.parse(s):s}catch(c){throw new Error(`Failed to parse message data: ${c.message}`)}let n=`/conversations/${t}/@append?task_type=codev`,r=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=t)}sendTerminationMessage(e){let s={message:e,sessionId:e.sessionId||this.sessionManager.getCurrentSessionId()};this.messageQueue.enqueue(s)}async handleChildProcessExit(e,s){p&&console.log(`Child process exited with code: ${e}, signal: ${s}`),this.stopFileWatching();let t=this.messageQueue.getQueueSize(),o=this.sessionManager.terminateCurrentSession("process exited normally",e,s);if(o&&this.sendTerminationMessage(o),t>0||o){p&&console.log("Starting graceful shutdown of message queue...");try{let n=!s||s==="SIGTERM",r=this.messageQueue.getQueueSize(),c={timeoutMs:n?8e3:3e3,batchSize:Math.min(r,15),fastMode:!n||r>30};p&&console.log("Shutdown options:",c);let i=await this.messageQueue.gracefulShutdown(c);p&&console.log("Message queue shutdown completed:",i),i.failedMessages>0&&p&&console.warn(`Shutdown summary: ${i.processedMessages} sent, ${i.failedMessages} failed, ${i.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 s=this.sessionManager.createErrorTermination(e);s&&this.sendTerminationMessage(s)}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(s){return p&&console.error("Force flush failed:",s.message),{success:!1,error:s.message}}}async launch(e={}){let{codevServer:s,auth_ak:t=null,auth_sk:o=null}=e;return this.httpClient.setBaseUrl(s),t&&o&&this.authService.setCredentials(t,o),this.startFileWatching(),super.launch(e)}};$e.exports=W});var Pe=m((tt,De)=>{var Es=O(),st=require("path"),z=class extends Es{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"}}}})}};De.exports=z});var Oe=m((ot,Te)=>{var xs=O(),_=require("path"),w=require("fs"),bs=require("os"),{spawn:ks}=require("child_process"),F=process.env.CODEV_DEBUG==="True",J=class extends xs{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:F?"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 w.existsSync(e)}catch{return!1}}resloveSettingFilePath(e){return _.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,s=0){let t=_.join(bs.homedir(),this.config.configDir,this.config.configFile),o=_.dirname(t);try{w.existsSync(o)||w.mkdirSync(o,{recursive:!0});let n=`${e}/codex`;if(w.existsSync(t)){let r=w.readFileSync(t,"utf8"),c=`openai_base_url = "${n}"`;/^openai_base_url\s*=/m.test(r)?r=r.replace(/^openai_base_url\s*=.*/m,c):r=r.trimEnd()+`
200
+ `+c+`
201
+ `,w.writeFileSync(t,r),F&&console.log(`Updated openai_base_url in ${t}`)}else{let r=this.config.defaultConfig||{},c=this.generateTOMLConfig(r,n);w.writeFileSync(t,c),F&&console.log(`Created Codex config file: ${t}`)}s>0&&await new Promise(r=>setTimeout(r,s))}catch(n){console.warn(`Failed to update ${this.config.configFile}: ${n.message}`)}}generateTOMLConfig(e,s){return`model = "${e.model||"gpt-5-codex"}"
202
202
  openai_base_url = "${s}"
203
- `}findExecutablePath(){let e=_.dirname(require.main.filename);for(let s of this.config.executablePaths){let t=_.resolve(e,s);if(w.existsSync(t))return t}throw new Error(`Could not find Codex executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}async launch(e={}){let{remainingArgs:s=[],codevServer:t,auth_ak:o=null,auth_sk:n=null}=e;try{if(!this.checkCodexAvailability())throw new Error("Codex executable not found. Please ensure makecoder is properly installed: npm install -g makecoder@latest");await this.ensureConfig(t,1e3);let r=this.findExecutablePath();return O&&console.log(`executablePath: ${r}`),new Promise((a,i)=>{let c={...process.env,...this.config.environmentVariables(t)};o&&(c.CODEV_AUTH_AK=o),n&&(c.CODEV_AUTH_SK=n);let l=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&l.push("--inspect-brk"),l.push(r,...s);let h=ys("node",l,{env:c,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(h),h.on("error",g=>{console.error(`Failed to start Codex: ${g.message}`),i(g)}),h.on("exit",async(g,S)=>{console.log(S?`terminated by signal: ${S}`:"Goodbye for now! Keep building great things!")}),process.on("SIGINT",async()=>{console.log(`
203
+ `}findExecutablePath(){let e=_.dirname(require.main.filename);for(let s of this.config.executablePaths){let t=_.resolve(e,s);if(w.existsSync(t))return t}throw new Error(`Could not find Codex executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}async launch(e={}){let{remainingArgs:s=[],codevServer:t,auth_ak:o=null,auth_sk:n=null}=e;try{if(!this.checkCodexAvailability())throw new Error("Codex executable not found. Please ensure makecoder is properly installed: npm install -g makecoder@latest");await this.ensureConfig(t,1e3);let r=this.findExecutablePath();return F&&console.log(`executablePath: ${r}`),new Promise((c,i)=>{let a={...process.env,...this.config.environmentVariables(t)};o&&(a.CODEV_AUTH_AK=o),n&&(a.CODEV_AUTH_SK=n);let l=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&l.push("--inspect-brk"),l.push(r,...s);let h=ks("node",l,{env:a,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(h),h.on("error",d=>{console.error(`Failed to start Codex: ${d.message}`),i(d)}),h.on("exit",async(d,f)=>{console.log(f?`terminated by signal: ${f}`:"Goodbye for now! Keep building great things!")}),process.on("SIGINT",async()=>{console.log(`
204
204
  Terminating ...`),h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
205
- Terminating ...`),h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},8e3)})})}catch(r){throw r}}};_e.exports=z});var Oe=f((Js,Te)=>{var D=require("fs"),Pe=require("path"),{spawn:$e}=require("child_process"),W=class{constructor(){this.extensionId="codev.codev-background";let e=require.main?Pe.dirname(require.main.filename):__dirname;this.extensionPath=Pe.resolve(e,"vendor/claude-code.vsix"),this._codeCommand=null}async resolveCodeCommand(){if(this._codeCommand)return this._codeCommand;if(process.env.IS_AISTUDIO==="True"){let e="/usr/lib/aistudio/lib/vscode/bin/remote-cli/aistudio";if(D.existsSync(e))try{return D.accessSync(e,D.constants.F_OK|D.constants.X_OK),this._codeCommand=e,process.env.CODEV_DEBUG&&console.log(`Using AI Studio VSCode path: ${e}`),this._codeCommand}catch(s){process.env.CODEV_DEBUG&&console.log(`AI Studio path exists but not executable: ${s.message}`)}else process.env.CODEV_DEBUG&&console.log(`AI Studio path not found: ${e}`)}try{let{spawn:e}=require("child_process");return new Promise(s=>{let t=e("which",["code"],{stdio:["ignore","pipe","ignore"]}),o="";t.stdout.on("data",n=>{o+=n.toString().trim()}),t.on("close",n=>{n===0&&o?(this._codeCommand=o,process.env.CODEV_DEBUG&&console.log(`Resolved code command path: ${o}`),s(this._codeCommand)):(this._codeCommand="code",s(this._codeCommand))}),t.on("error",()=>{this._codeCommand="code",s(this._codeCommand)}),setTimeout(()=>{t.kill(),this._codeCommand="code",s(this._codeCommand)},3e3)})}catch{return this._codeCommand="code",this._codeCommand}}async shouldInstallExtension(){try{return process.env.IS_AISTUDIO!=="True"?(process.env.CODEV_DEBUG&&console.log("Not in AI Studio environment (IS_AISTUDIO!=True), skipping extension installation"),!1):await this.isVSCodeAvailable()?await this.isExtensionInstalled()?(process.env.CODEV_DEBUG&&console.log(`Extension ${this.extensionId} already installed`),!1):!!D.existsSync(this.extensionPath):(process.env.CODEV_DEBUG&&console.log("VSCode not available, skipping extension installation"),!1)}catch(e){return process.env.CODEV_DEBUG&&console.error(`Error checking extension installation status: ${e.message}`),!1}}async installExtension(){try{return console.log("Installing Codev VSCode extension..."),await this.executeVSCodeCommand(["--install-extension",this.extensionPath])?(console.log("\u2705 Codev VSCode extension installed successfully"),!0):(console.warn("\u274C Failed to install Codev VSCode extension"),!1)}catch(e){return console.warn(`Error installing VSCode extension: ${e.message}`),!1}}async isVSCodeAvailable(){try{let e=process.env.IS_AISTUDIO==="True"?["--help"]:["--version"],s=await this.executeVSCodeCommand(e,{timeout:1e4});if(process.env.CODEV_DEBUG&&(console.log(`VSCode availability check (${e.join(" ")}): ${s?"available":"unavailable"}`),process.env.IS_AISTUDIO==="True")){let{spawn:t}=require("child_process");try{t("which",["code"],{stdio:["ignore","pipe","ignore"]}).stdout.on("data",n=>{console.log("which code:",n.toString().trim())})}catch(o){console.log("which command failed:",o.message)}}return s}catch(e){return process.env.CODEV_DEBUG&&console.error("VSCode availability check error:",e.message),!1}}async isExtensionInstalled(){let e=await this.resolveCodeCommand();try{return new Promise(s=>{try{let t={stdio:["ignore","pipe","ignore"],shell:!1,env:{...process.env,PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER}};process.env.CODEV_DEBUG&&console.log(`Spawning: ${e} --list-extensions`);let o=$e(e,["--list-extensions"],t),n="";o.stdout.on("data",r=>{n+=r.toString()}),o.on("close",r=>{if(r===0){let a=n.split(`
206
- `).map(i=>i.trim());s(a.includes(this.extensionId))}else s(!1)}),o.on("error",r=>{process.env.CODEV_DEBUG&&(console.error("VSCode list extensions error:",r.message),console.error("Error code:",r.code),console.error("Error errno:",r.errno),console.error("Error syscall:",r.syscall)),s(!1)}),setTimeout(()=>{try{o.kill()}catch{}s(!1)},1e4)}catch(t){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode list extensions:",t.message),s(!1)}})}catch{return!1}}async executeVSCodeCommand(e,s={}){let t=await this.resolveCodeCommand();return new Promise(o=>{try{let n={stdio:"ignore",shell:!1,env:{...process.env,PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER}};process.env.CODEV_DEBUG&&console.log(`Spawning: ${t} ${e.join(" ")}`);let r=$e(t,e,n);r.on("close",i=>{o(i===0)}),r.on("error",i=>{process.env.CODEV_DEBUG&&(console.error("VSCode command error:",i.message),console.error("Error code:",i.code),console.error("Error errno:",i.errno),console.error("Error syscall:",i.syscall)),o(!1)});let a=s.timeout||3e4;setTimeout(()=>{try{r.kill()}catch{}o(!1)},a)}catch(n){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode command:",n.message),o(!1)}})}async ensureExtensionInstalled(){try{process.env.CODEV_DEBUG&&console.log("VSCode Extension Service: Checking extension status..."),await this.shouldInstallExtension()&&await this.installExtension()}catch(e){process.env.CODEV_DEBUG&&console.error("VSCode Extension Service Error:",e)}}};Te.exports=W});var Me=f((Qs,Fe)=>{var y=require("fs"),x=require("path"),ws=require("readline"),{execSync:A}=require("child_process"),Ae=require("os"),j=class{constructor(){this.serverUrl="https://makecoder.com/bigapis/codev/v1/coderpub"}getClaudeJsonlPath(e,s=!1){let t=e.replace(/[/_]/g,"-"),o=x.join(Ae.homedir(),".claude","projects",t);if(s&&(console.log(`
207
- \u{1F4C2} [allow-clone] \u67E5\u627E JSONL \u6587\u4EF6...`),console.log(` \u9879\u76EE\u76EE\u5F55: ${e}`),console.log(` Claude \u9879\u76EE\u540D: ${t}`),console.log(` Claude \u9879\u76EE\u76EE\u5F55: ${o}`)),!y.existsSync(o))return s&&console.log(" \u274C Claude \u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728"),null;s&&console.log(" \u2713 Claude \u9879\u76EE\u76EE\u5F55\u5B58\u5728");try{let n=y.readdirSync(o).filter(r=>r.endsWith(".jsonl")).map(r=>({name:r,path:x.join(o,r),mtime:y.statSync(x.join(o,r)).mtime,size:y.statSync(x.join(o,r)).size})).sort((r,a)=>a.mtime-r.mtime);return s&&(console.log(` \u627E\u5230 ${n.length} \u4E2A JSONL \u6587\u4EF6:`),n.forEach((r,a)=>{let i=(r.size/1024).toFixed(2),c=r.mtime.toLocaleString(),l=a===0?" <- \u6700\u65B0":"";console.log(` ${a+1}. ${r.name} (${i} KB, ${c})${l}`)})),n.length>0?(s&&console.log(` \u2713 \u9009\u62E9\u6700\u65B0\u6587\u4EF6: ${n[0].name}`),n[0].path):(s&&console.log(" \u274C \u76EE\u5F55\u4E2D\u6CA1\u6709 JSONL \u6587\u4EF6"),null)}catch(n){return s&&console.log(` \u274C \u8BFB\u53D6\u76EE\u5F55\u5931\u8D25: ${n.message}`),null}}async promptForName(){let e=ws.createInterface({input:process.stdin,output:process.stdout});return new Promise((s,t)=>{e.question("\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0 (name): ",o=>{e.close();let n=o.trim();if(!n){t(new Error("\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A"));return}if(!/^[a-zA-Z0-9_-]+$/.test(n)){t(new Error("\u9879\u76EE\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26"));return}s(n)})})}async createZip(e,s={}){let{allowClone:t=!1}=s,o=Ae.tmpdir(),n=`coder-pub-${Date.now()}.zip`,r=x.join(o,n);try{let a=!1;if(y.existsSync(x.join(e,".git")))try{A(`git archive -o "${r}" HEAD`,{cwd:e,stdio:"pipe"}),console.log("\u{1F4E6} \u4F7F\u7528 git archive \u521B\u5EFA\u538B\u7F29\u5305\uFF08\u5DF2\u6392\u9664 .gitignore \u4E2D\u7684\u6587\u4EF6\uFF09"),a=!0}catch{console.log("\u26A0\uFE0F git archive \u5931\u8D25\uFF0C\u4F7F\u7528\u666E\u901A zip \u547D\u4EE4")}if(!a){let c=[".git/*","node_modules/*",".env",".env.*","*.log",".DS_Store"].map(l=>`-x "${l}"`).join(" ");A(`zip -r "${r}" . ${c}`,{cwd:e,stdio:"pipe"}),console.log("\u{1F4E6} \u5DF2\u521B\u5EFA\u538B\u7F29\u5305")}if(t){console.log(`
208
- \u{1F504} [allow-clone] \u5F00\u59CB\u5904\u7406 AI \u751F\u6210\u8BB0\u5F55...`);let i=this.getClaudeJsonlPath(e,!0);if(i){let c=x.join(o,"coder.pub.jsonl"),h=(y.statSync(i).size/1024).toFixed(2);console.log(`
209
- \u{1F4E6} [allow-clone] \u6253\u5305 JSONL \u6587\u4EF6...`),console.log(` \u6E90\u6587\u4EF6: ${i}`),console.log(` \u6587\u4EF6\u5927\u5C0F: ${h} KB`),console.log(` \u4E34\u65F6\u6587\u4EF6: ${c}`),y.copyFileSync(i,c),console.log(" \u2713 \u5DF2\u590D\u5236\u5230\u4E34\u65F6\u76EE\u5F55"),console.log(` \u76EE\u6807 ZIP: ${r}`),console.log(" \u76EE\u6807\u6587\u4EF6\u540D: coder.pub.jsonl"),A(`zip -j "${r}" "${c}"`,{stdio:"pipe"}),console.log(" \u2713 \u5DF2\u6DFB\u52A0\u5230 ZIP \u5305"),y.unlinkSync(c),console.log(" \u2713 \u5DF2\u6E05\u7406\u4E34\u65F6\u6587\u4EF6"),console.log(`\u{1F4CB} [allow-clone] AI \u751F\u6210\u8BB0\u5F55\u5904\u7406\u5B8C\u6210 (coder.pub.jsonl)
205
+ Terminating ...`),h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},8e3)})})}catch(r){throw r}}};Te.exports=J});var Me=m((nt,qe)=>{var D=require("fs"),Ae=require("path"),{spawn:Fe}=require("child_process"),Q=class{constructor(){this.extensionId="codev.codev-background";let e=require.main?Ae.dirname(require.main.filename):__dirname;this.extensionPath=Ae.resolve(e,"vendor/claude-code.vsix"),this._codeCommand=null}async resolveCodeCommand(){if(this._codeCommand)return this._codeCommand;if(process.env.IS_AISTUDIO==="True"){let e="/usr/lib/aistudio/lib/vscode/bin/remote-cli/aistudio";if(D.existsSync(e))try{return D.accessSync(e,D.constants.F_OK|D.constants.X_OK),this._codeCommand=e,process.env.CODEV_DEBUG&&console.log(`Using AI Studio VSCode path: ${e}`),this._codeCommand}catch(s){process.env.CODEV_DEBUG&&console.log(`AI Studio path exists but not executable: ${s.message}`)}else process.env.CODEV_DEBUG&&console.log(`AI Studio path not found: ${e}`)}try{let{spawn:e}=require("child_process");return new Promise(s=>{let t=e("which",["code"],{stdio:["ignore","pipe","ignore"]}),o="";t.stdout.on("data",n=>{o+=n.toString().trim()}),t.on("close",n=>{n===0&&o?(this._codeCommand=o,process.env.CODEV_DEBUG&&console.log(`Resolved code command path: ${o}`),s(this._codeCommand)):(this._codeCommand="code",s(this._codeCommand))}),t.on("error",()=>{this._codeCommand="code",s(this._codeCommand)}),setTimeout(()=>{t.kill(),this._codeCommand="code",s(this._codeCommand)},3e3)})}catch{return this._codeCommand="code",this._codeCommand}}async shouldInstallExtension(){try{return process.env.IS_AISTUDIO!=="True"?(process.env.CODEV_DEBUG&&console.log("Not in AI Studio environment (IS_AISTUDIO!=True), skipping extension installation"),!1):await this.isVSCodeAvailable()?await this.isExtensionInstalled()?(process.env.CODEV_DEBUG&&console.log(`Extension ${this.extensionId} already installed`),!1):!!D.existsSync(this.extensionPath):(process.env.CODEV_DEBUG&&console.log("VSCode not available, skipping extension installation"),!1)}catch(e){return process.env.CODEV_DEBUG&&console.error(`Error checking extension installation status: ${e.message}`),!1}}async installExtension(){try{return console.log("Installing Codev VSCode extension..."),await this.executeVSCodeCommand(["--install-extension",this.extensionPath])?(console.log("\u2705 Codev VSCode extension installed successfully"),!0):(console.warn("\u274C Failed to install Codev VSCode extension"),!1)}catch(e){return console.warn(`Error installing VSCode extension: ${e.message}`),!1}}async isVSCodeAvailable(){try{let e=process.env.IS_AISTUDIO==="True"?["--help"]:["--version"],s=await this.executeVSCodeCommand(e,{timeout:1e4});if(process.env.CODEV_DEBUG&&(console.log(`VSCode availability check (${e.join(" ")}): ${s?"available":"unavailable"}`),process.env.IS_AISTUDIO==="True")){let{spawn:t}=require("child_process");try{t("which",["code"],{stdio:["ignore","pipe","ignore"]}).stdout.on("data",n=>{console.log("which code:",n.toString().trim())})}catch(o){console.log("which command failed:",o.message)}}return s}catch(e){return process.env.CODEV_DEBUG&&console.error("VSCode availability check error:",e.message),!1}}async isExtensionInstalled(){let e=await this.resolveCodeCommand();try{return new Promise(s=>{try{let t={stdio:["ignore","pipe","ignore"],shell:!1,env:{...process.env,PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER}};process.env.CODEV_DEBUG&&console.log(`Spawning: ${e} --list-extensions`);let o=Fe(e,["--list-extensions"],t),n="";o.stdout.on("data",r=>{n+=r.toString()}),o.on("close",r=>{if(r===0){let c=n.split(`
206
+ `).map(i=>i.trim());s(c.includes(this.extensionId))}else s(!1)}),o.on("error",r=>{process.env.CODEV_DEBUG&&(console.error("VSCode list extensions error:",r.message),console.error("Error code:",r.code),console.error("Error errno:",r.errno),console.error("Error syscall:",r.syscall)),s(!1)}),setTimeout(()=>{try{o.kill()}catch{}s(!1)},1e4)}catch(t){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode list extensions:",t.message),s(!1)}})}catch{return!1}}async executeVSCodeCommand(e,s={}){let t=await this.resolveCodeCommand();return new Promise(o=>{try{let n={stdio:"ignore",shell:!1,env:{...process.env,PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER}};process.env.CODEV_DEBUG&&console.log(`Spawning: ${t} ${e.join(" ")}`);let r=Fe(t,e,n);r.on("close",i=>{o(i===0)}),r.on("error",i=>{process.env.CODEV_DEBUG&&(console.error("VSCode command error:",i.message),console.error("Error code:",i.code),console.error("Error errno:",i.errno),console.error("Error syscall:",i.syscall)),o(!1)});let c=s.timeout||3e4;setTimeout(()=>{try{r.kill()}catch{}o(!1)},c)}catch(n){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode command:",n.message),o(!1)}})}async ensureExtensionInstalled(){try{process.env.CODEV_DEBUG&&console.log("VSCode Extension Service: Checking extension status..."),await this.shouldInstallExtension()&&await this.installExtension()}catch(e){process.env.CODEV_DEBUG&&console.error("VSCode Extension Service Error:",e)}}};qe.exports=Q});var Le=m((rt,Be)=>{var y=require("fs"),b=require("path"),Is=require("readline"),{execSync:q}=require("child_process"),Ue=require("os"),Y=class{constructor(){this.serverUrl="https://makecoder.com/bigapis/codev/v1/coderpub"}getClaudeJsonlPath(e,s=!1){let t=e.replace(/[/_]/g,"-"),o=b.join(Ue.homedir(),".claude","projects",t);if(s&&(console.log(`
207
+ \u{1F4C2} [allow-clone] \u67E5\u627E JSONL \u6587\u4EF6...`),console.log(` \u9879\u76EE\u76EE\u5F55: ${e}`),console.log(` Claude \u9879\u76EE\u540D: ${t}`),console.log(` Claude \u9879\u76EE\u76EE\u5F55: ${o}`)),!y.existsSync(o))return s&&console.log(" \u274C Claude \u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728"),null;s&&console.log(" \u2713 Claude \u9879\u76EE\u76EE\u5F55\u5B58\u5728");try{let n=y.readdirSync(o).filter(r=>r.endsWith(".jsonl")).map(r=>({name:r,path:b.join(o,r),mtime:y.statSync(b.join(o,r)).mtime,size:y.statSync(b.join(o,r)).size})).sort((r,c)=>c.mtime-r.mtime);return s&&(console.log(` \u627E\u5230 ${n.length} \u4E2A JSONL \u6587\u4EF6:`),n.forEach((r,c)=>{let i=(r.size/1024).toFixed(2),a=r.mtime.toLocaleString(),l=c===0?" <- \u6700\u65B0":"";console.log(` ${c+1}. ${r.name} (${i} KB, ${a})${l}`)})),n.length>0?(s&&console.log(` \u2713 \u9009\u62E9\u6700\u65B0\u6587\u4EF6: ${n[0].name}`),n[0].path):(s&&console.log(" \u274C \u76EE\u5F55\u4E2D\u6CA1\u6709 JSONL \u6587\u4EF6"),null)}catch(n){return s&&console.log(` \u274C \u8BFB\u53D6\u76EE\u5F55\u5931\u8D25: ${n.message}`),null}}async promptForName(){let e=Is.createInterface({input:process.stdin,output:process.stdout});return new Promise((s,t)=>{e.question("\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0 (name): ",o=>{e.close();let n=o.trim();if(!n){t(new Error("\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A"));return}if(!/^[a-zA-Z0-9_-]+$/.test(n)){t(new Error("\u9879\u76EE\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26"));return}s(n)})})}async createZip(e,s={}){let{allowClone:t=!1}=s,o=Ue.tmpdir(),n=`coder-pub-${Date.now()}.zip`,r=b.join(o,n);try{let c=!1;if(y.existsSync(b.join(e,".git")))try{q(`git archive -o "${r}" HEAD`,{cwd:e,stdio:"pipe"}),console.log("\u{1F4E6} \u4F7F\u7528 git archive \u521B\u5EFA\u538B\u7F29\u5305\uFF08\u5DF2\u6392\u9664 .gitignore \u4E2D\u7684\u6587\u4EF6\uFF09"),c=!0}catch{console.log("\u26A0\uFE0F git archive \u5931\u8D25\uFF0C\u4F7F\u7528\u666E\u901A zip \u547D\u4EE4")}if(!c){let a=[".git/*","node_modules/*",".env",".env.*","*.log",".DS_Store"].map(l=>`-x "${l}"`).join(" ");q(`zip -r "${r}" . ${a}`,{cwd:e,stdio:"pipe"}),console.log("\u{1F4E6} \u5DF2\u521B\u5EFA\u538B\u7F29\u5305")}if(t){console.log(`
208
+ \u{1F504} [allow-clone] \u5F00\u59CB\u5904\u7406 AI \u751F\u6210\u8BB0\u5F55...`);let i=this.getClaudeJsonlPath(e,!0);if(i){let a=b.join(o,"coder.pub.jsonl"),h=(y.statSync(i).size/1024).toFixed(2);console.log(`
209
+ \u{1F4E6} [allow-clone] \u6253\u5305 JSONL \u6587\u4EF6...`),console.log(` \u6E90\u6587\u4EF6: ${i}`),console.log(` \u6587\u4EF6\u5927\u5C0F: ${h} KB`),console.log(` \u4E34\u65F6\u6587\u4EF6: ${a}`),y.copyFileSync(i,a),console.log(" \u2713 \u5DF2\u590D\u5236\u5230\u4E34\u65F6\u76EE\u5F55"),console.log(` \u76EE\u6807 ZIP: ${r}`),console.log(" \u76EE\u6807\u6587\u4EF6\u540D: coder.pub.jsonl"),q(`zip -j "${r}" "${a}"`,{stdio:"pipe"}),console.log(" \u2713 \u5DF2\u6DFB\u52A0\u5230 ZIP \u5305"),y.unlinkSync(a),console.log(" \u2713 \u5DF2\u6E05\u7406\u4E34\u65F6\u6587\u4EF6"),console.log(`\u{1F4CB} [allow-clone] AI \u751F\u6210\u8BB0\u5F55\u5904\u7406\u5B8C\u6210 (coder.pub.jsonl)
210
210
  `)}else console.log(`\u26A0\uFE0F [allow-clone] \u672A\u627E\u5230 Claude Code \u751F\u6210\u8BB0\u5F55
211
- `)}return r}catch(a){throw new Error(`\u521B\u5EFA\u538B\u7F29\u5305\u5931\u8D25: ${a.message}`)}}async upload(e,s,t,o,n,r=!1){let a=n?`${n}/coderpub`:this.serverUrl,i=`${t}.${o}`;console.log("\u{1F4E4} \u6B63\u5728\u4E0A\u4F20\u5230\u670D\u52A1\u5668..."),r&&(console.log(` \u670D\u52A1\u5668\u5730\u5740: ${a}`),console.log(` \u9879\u76EE\u540D\u79F0: ${s}`),console.log(` ZIP \u6587\u4EF6: ${e}`));try{let c=`curl -s -X POST "${a}" -H "Authorization: Bearer ${i}" -F "name=${s}" -F "zip_file=@${e}"`;r&&console.log(" \u6267\u884C\u4E0A\u4F20\u547D\u4EE4...");let l=A(c,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return r&&console.log(" \u2713 \u4E0A\u4F20\u5B8C\u6210\uFF0C\u89E3\u6790\u54CD\u5E94..."),JSON.parse(l)}catch(c){if(c.stdout)try{return JSON.parse(c.stdout)}catch{throw new Error(`\u4E0A\u4F20\u5931\u8D25: ${c.message}`)}throw new Error(`\u4E0A\u4F20\u5931\u8D25: ${c.message}`)}}cleanup(e){try{y.existsSync(e)&&y.unlinkSync(e)}catch{}}async publish(e){let{ak:s,sk:t,serverBaseUrl:o,allowClone:n}=e,{name:r}=e,a=null;try{r||(r=await this.promptForName()),console.log(`
212
- \u{1F680} \u6B63\u5728\u53D1\u5E03\u9879\u76EE: ${r}`),console.log(`\u{1F4C1} \u76EE\u5F55: ${process.cwd()}`),n&&console.log("\u{1F513} allow-clone: \u542F\u7528 (\u5C06\u5305\u542B AI \u751F\u6210\u8BB0\u5F55)"),console.log(),a=await this.createZip(process.cwd(),{allowClone:n});let c=(y.statSync(a).size/(1024*1024)).toFixed(2);console.log(`\u{1F4CA} \u538B\u7F29\u5305\u5927\u5C0F: ${c} MB`),n&&console.log(`
213
- \u{1F310} [allow-clone] \u5F00\u59CB\u4E0A\u4F20\u5230\u670D\u52A1\u5668...`);let l=await this.upload(a,r,s,t,o,n);return l.code===0?(console.log(`
211
+ `)}return r}catch(c){throw new Error(`\u521B\u5EFA\u538B\u7F29\u5305\u5931\u8D25: ${c.message}`)}}async upload(e,s,t,o,n,r=!1){let c=n?`${n}/coderpub`:this.serverUrl,i=`${t}.${o}`;console.log("\u{1F4E4} \u6B63\u5728\u4E0A\u4F20\u5230\u670D\u52A1\u5668..."),r&&(console.log(` \u670D\u52A1\u5668\u5730\u5740: ${c}`),console.log(` \u9879\u76EE\u540D\u79F0: ${s}`),console.log(` ZIP \u6587\u4EF6: ${e}`));try{let a=`curl -s -X POST "${c}" -H "Authorization: Bearer ${i}" -F "name=${s}" -F "zip_file=@${e}"`;r&&console.log(" \u6267\u884C\u4E0A\u4F20\u547D\u4EE4...");let l=q(a,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return r&&console.log(" \u2713 \u4E0A\u4F20\u5B8C\u6210\uFF0C\u89E3\u6790\u54CD\u5E94..."),JSON.parse(l)}catch(a){if(a.stdout)try{return JSON.parse(a.stdout)}catch{throw new Error(`\u4E0A\u4F20\u5931\u8D25: ${a.message}`)}throw new Error(`\u4E0A\u4F20\u5931\u8D25: ${a.message}`)}}cleanup(e){try{y.existsSync(e)&&y.unlinkSync(e)}catch{}}async publish(e){let{ak:s,sk:t,serverBaseUrl:o,allowClone:n}=e,{name:r}=e,c=null;try{r||(r=await this.promptForName()),console.log(`
212
+ \u{1F680} \u6B63\u5728\u53D1\u5E03\u9879\u76EE: ${r}`),console.log(`\u{1F4C1} \u76EE\u5F55: ${process.cwd()}`),n&&console.log("\u{1F513} allow-clone: \u542F\u7528 (\u5C06\u5305\u542B AI \u751F\u6210\u8BB0\u5F55)"),console.log(),c=await this.createZip(process.cwd(),{allowClone:n});let a=(y.statSync(c).size/(1024*1024)).toFixed(2);console.log(`\u{1F4CA} \u538B\u7F29\u5305\u5927\u5C0F: ${a} MB`),n&&console.log(`
213
+ \u{1F310} [allow-clone] \u5F00\u59CB\u4E0A\u4F20\u5230\u670D\u52A1\u5668...`);let l=await this.upload(c,r,s,t,o,n);return l.code===0?(console.log(`
214
214
  \u2705 \u53D1\u5E03\u6210\u529F!`),console.log(`\u{1F4CC} \u7248\u672C: ${l.data.version}`),console.log(`\u{1F310} \u8BBF\u95EE\u5730\u5740: https://${r}.coder.pub/`),0):(console.error(`
215
215
  \u274C \u53D1\u5E03\u5931\u8D25: ${l.message||l.reason}`),1)}catch(i){return console.error(`
216
- \u274C ${i.message}`),1}finally{a&&this.cleanup(a)}}};Fe.exports=j});var Ue=f((Ys,qe)=>{var Cs=ne(),Es=be(),vs=ke(),xs=De(),bs=Oe(),Is=Me(),{isPrintMode:ks}=P(),J=class{constructor(){this.argParser=new Cs,this.claudeLauncher=new Es,this.geminiLauncher=new vs,this.codexLauncher=new xs,this.vscodeExtensionService=new bs,this.publishService=new Is}async run(e=process.argv.slice(2)){try{try{await this.vscodeExtensionService.ensureExtensionInstalled()}catch(t){process.env.CODEV_DEBUG&&console.error("VSCode Extension Service Error:",t)}if(!e.includes("--agent")&&!e.includes("-a")){let t=e.length>0&&["claude","gemini","codex"].includes(e[0]),o=e.length>0&&["pub","update","skills"].includes(e[0]);if(!t&&!o&&(e.includes("--help")||e.includes("-h")))return this.argParser.showHelp(),0;if(!t&&!o&&(e.includes("--version")||e.includes("-v")))return this.showVersion(),0}let s=await this.argParser.parse(e);return s.command==="login"?await this.handleLogin(s):s.command==="update"?this.handleUpdate():s.command==="skills"?await this.handleSkills(s):s.command==="pub"?await this.publishService.publish({name:s.pubName,ak:s.auth_ak,sk:s.auth_sk,serverBaseUrl:s.codevServer,allowClone:s.allowClone}):await this.launchAgent(s)}catch(s){return console.error(`Error: ${s.message}`),process.env.CODEV_DEBUG&&console.error("Stack trace:",s.stack),1}}async launchAgent(e){let{agent:s,remainingArgs:t}=e;return ks(t)||console.log(`cwd:\x1B[90m\x1B[3m ${process.cwd()} \x1B[0m`),s==="claude"?await this.claudeLauncher.launch(e):s==="gemini"?await this.geminiLauncher.launch(e):s==="codex"?await this.codexLauncher.launch(e):1}async handleSkills({skillsSubcommand:e,skillsArg:s}){let{execFileSync:t}=require("child_process"),o="https://makecoder.com/skillhub";if(!e)return console.log(`Usage:
216
+ \u274C ${i.message}`),1}finally{c&&this.cleanup(c)}}};Be.exports=Y});var Ve=m((it,Re)=>{var Ne=require("https"),P=require("fs"),C=require("path"),$s=require("os"),M="https://makecoder.com/skillhub",Z=class{getSkillDirs(){let e=$s.homedir();return[C.join(e,".claude","skills"),C.join(e,".codex","skills"),C.join(e,".gemini","skills"),C.join(e,".agents","skills")]}fetchWithAuth(e,s){return new Promise((t,o)=>{let n=new URL(e),r={hostname:n.hostname,port:n.port||443,path:n.pathname+n.search,method:"GET",headers:s?{Authorization:`Bearer ${s}`}:{}};Ne.get(r,c=>{if(c.statusCode>=300&&c.statusCode<400&&c.headers.location)return this.fetchWithAuth(c.headers.location,s).then(t).catch(o);let i="";c.on("data",a=>{i+=a}),c.on("end",()=>t({status:c.statusCode,body:i}))}).on("error",o)})}async handle({skillsSubcommand:e,skillsArg:s,auth_ak:t,auth_sk:o}){let{execFileSync:n}=require("child_process");if(!e)return console.log(`Usage:
217
217
  coder skills add <name>
218
218
  coder skills remove <name>
219
219
  coder skills update [name]
220
- coder skills search <keyword>`),0;if(s&&e!=="search"&&!/^[@a-zA-Z0-9_\-/.]+$/.test(s))return console.error("\u274C skill \u540D\u79F0\u5305\u542B\u975E\u6CD5\u5B57\u7B26"),1;if(e==="search")return s?await this.searchSkills(s,o):(console.error("\u274C \u8BF7\u6307\u5B9A\u641C\u7D22\u5173\u952E\u8BCD"),1);try{let n;if(e==="add"){if(!s)return console.error("\u274C \u8BF7\u6307\u5B9A skill \u540D\u79F0"),1;n=["skills","add",o,"--skill",s,"-g"]}else if(e==="remove"){if(!s)return console.error("\u274C \u8BF7\u6307\u5B9A skill \u540D\u79F0"),1;n=["skills","remove","--skill",s,"-g"]}else if(e==="update")n=s?["skills","update","--skill",s,"-g"]:["skills","update","-g"];else return console.error(`\u274C \u672A\u77E5\u5B50\u547D\u4EE4: ${e}`),1;return t("npx",n,{stdio:"inherit"}),0}catch(n){return console.error(`\u274C \u6267\u884C\u5931\u8D25: ${n.message}`),1}}async searchSkills(e,s){let t=require("https"),o=`${s}/api/web/skills?q=${encodeURIComponent(e)}&sort=relevance&page=0&size=12`;return new Promise(n=>{t.get(o,r=>{let a="";r.on("data",i=>{a+=i}),r.on("end",()=>{try{let i=JSON.parse(a);if(i.code!==0)return console.error(`\u274C \u67E5\u8BE2\u5931\u8D25: ${i.msg}`),n(1);let c=i.data.items;if(c.length===0)return console.log(`\u6CA1\u6709\u627E\u5230\u4E0E "${e}" \u76F8\u5173\u7684 skill`),n(0);console.log(`\u627E\u5230 ${i.data.total} \u4E2A\u7ED3\u679C:
221
- `);for(let l of c)console.log(` ${l.slug.padEnd(20)} ${l.summary}`);n(0)}catch(i){console.error(`\u274C \u89E3\u6790\u54CD\u5E94\u5931\u8D25: ${i.message}`),n(1)}})}).on("error",r=>{console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${r.message}`),n(1)})})}async handleLogin(e){let s=e.auth_ak,t=e.auth_sk;if(!s||!t){console.log(`
220
+ coder skills search <keyword>`),0;if(s&&e!=="search"&&!/^[@a-zA-Z0-9_\-/.]+$/.test(s))return console.error("\u274C skill \u540D\u79F0\u5305\u542B\u975E\u6CD5\u5B57\u7B26"),1;if(e==="search")return s?await this.search(s):(console.error("\u274C \u8BF7\u6307\u5B9A\u641C\u7D22\u5173\u952E\u8BCD"),1);if(e==="remove")return s?this.remove(s):(console.error("\u274C \u8BF7\u6307\u5B9A skill \u540D\u79F0"),1);if((e==="add"||e==="update")&&s&&t&&o)return await this.install(s,`${t}.${o}`);try{let r;if(e==="add"){if(!s)return console.error("\u274C \u8BF7\u6307\u5B9A skill \u540D\u79F0"),1;r=["skills","add",M,"--skill",s,"-g"]}else if(e==="update")r=s?["skills","update","--skill",s,"-g"]:["skills","update","-g"];else return console.error(`\u274C \u672A\u77E5\u5B50\u547D\u4EE4: ${e}`),1;return n("npx",r,{stdio:"inherit"}),0}catch(r){return console.error(`\u274C \u6267\u884C\u5931\u8D25: ${r.message}`),1}}async install(e,s){let t=M.replace(/\/$/,"");console.log(`\u{1F50D} \u6B63\u5728\u4ECE ${M} \u67E5\u627E skill...`);let o;try{let a=await this.fetchWithAuth(`${t}/.well-known/agent-skills/index.json`,s);if(a.status!==200)return console.error(`\u274C \u65E0\u6CD5\u83B7\u53D6 skill \u5217\u8868 (HTTP ${a.status})`),1;o=JSON.parse(a.body)}catch(a){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${a.message}`),1}let n=(o.skills||[]).find(a=>a.name.toLowerCase()===e.toLowerCase());if(!n){console.error(`\u274C \u672A\u627E\u5230 skill: ${e}`);for(let a of o.skills||[])console.log(` - ${a.name}`);return 1}let r=Array.from(new Set(["SKILL.md",...n.files||[]])),c=`${t}/.well-known/agent-skills/${n.name}`,i={};for(let a of r)try{let l=await this.fetchWithAuth(`${c}/${a}`,s);if(l.status!==200){console.warn(`\u26A0\uFE0F \u8DF3\u8FC7 ${a} (HTTP ${l.status})`);continue}i[a]=l.body}catch(l){console.warn(`\u26A0\uFE0F \u4E0B\u8F7D ${a} \u5931\u8D25: ${l.message}`)}console.log(`\u{1F4E6} \u6B63\u5728\u5B89\u88C5 ${n.name}...`);for(let a of this.getSkillDirs()){let l=C.join(a,n.name);P.mkdirSync(l,{recursive:!0});for(let[h,d]of Object.entries(i)){let f=C.join(l,h);P.mkdirSync(C.dirname(f),{recursive:!0}),P.writeFileSync(f,d,"utf8")}}return console.log(`\u2705 ${n.name} \u5B89\u88C5\u5B8C\u6210`),0}remove(e){let s=!1;for(let t of this.getSkillDirs()){let o=C.join(t,e);P.existsSync(o)&&(P.rmSync(o,{recursive:!0,force:!0}),console.log(` \u{1F5D1}\uFE0F ${o}`),s=!0)}return s?(console.log(`\u2705 ${e} \u5DF2\u5220\u9664`),0):(console.error(`\u274C \u672A\u627E\u5230\u5DF2\u5B89\u88C5\u7684 skill: ${e}`),1)}async search(e){let s=`${M}/api/web/skills?q=${encodeURIComponent(e)}&sort=relevance&page=0&size=12`;return new Promise(t=>{Ne.get(s,o=>{let n="";o.on("data",r=>{n+=r}),o.on("end",()=>{try{let r=JSON.parse(n);if(r.code!==0)return console.error(`\u274C \u67E5\u8BE2\u5931\u8D25: ${r.msg}`),t(1);let c=r.data.items;if(c.length===0)return console.log(`\u6CA1\u6709\u627E\u5230\u4E0E "${e}" \u76F8\u5173\u7684 skill`),t(0);console.log(`\u627E\u5230 ${r.data.total} \u4E2A\u7ED3\u679C:
221
+ `);for(let i of c)console.log(` ${i.slug.padEnd(20)} ${i.summary}`);t(0)}catch(r){console.error(`\u274C \u89E3\u6790\u54CD\u5E94\u5931\u8D25: ${r.message}`),t(1)}})}).on("error",o=>{console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${o.message}`),t(1)})})}};Re.exports=Z});var He=m((at,Ge)=>{var _s=ce(),Ds=_e(),Ps=Pe(),Ts=Oe(),Os=Me(),As=Le(),Fs=Ve(),{isPrintMode:qs}=T(),X=class{constructor(){this.argParser=new _s,this.claudeLauncher=new Ds,this.geminiLauncher=new Ps,this.codexLauncher=new Ts,this.vscodeExtensionService=new Os,this.publishService=new As,this.skillsService=new Fs}async run(e=process.argv.slice(2)){try{try{await this.vscodeExtensionService.ensureExtensionInstalled()}catch(t){process.env.CODEV_DEBUG&&console.error("VSCode Extension Service Error:",t)}if(!e.includes("--agent")&&!e.includes("-a")){let t=e.length>0&&["claude","gemini","codex"].includes(e[0]),o=e.length>0&&["pub","update","skills"].includes(e[0]);if(!t&&!o&&(e.includes("--help")||e.includes("-h")))return this.argParser.showHelp(),0;if(!t&&!o&&(e.includes("--version")||e.includes("-v")))return this.showVersion(),0}let s=await this.argParser.parse(e);return s.command==="login"?await this.handleLogin(s):s.command==="update"?this.handleUpdate():s.command==="skills"?await this.skillsService.handle(s):s.command==="pub"?await this.publishService.publish({name:s.pubName,ak:s.auth_ak,sk:s.auth_sk,serverBaseUrl:s.codevServer,allowClone:s.allowClone}):await this.launchAgent(s)}catch(s){return console.error(`Error: ${s.message}`),process.env.CODEV_DEBUG&&console.error("Stack trace:",s.stack),1}}async launchAgent(e){let{agent:s,remainingArgs:t}=e;return qs(t)||console.log(`cwd:\x1B[90m\x1B[3m ${process.cwd()} \x1B[0m`),s==="claude"?await this.claudeLauncher.launch(e):s==="gemini"?await this.geminiLauncher.launch(e):s==="codex"?await this.codexLauncher.launch(e):1}async handleLogin(e){let s=e.auth_ak,t=e.auth_sk;if(!s||!t){console.log(`
222
222
  \u{1F511} \u8BF7\u5148\u5728 MakeCoder \u521B\u5EFA API Key\uFF1A`),console.log(` \u{1F449} https://makecoder.com/my/apikeys
223
- `);try{let n=await this.argParser.promptForAKSK();s=n.ak,t=n.sk}catch(n){return console.error(`\u274C ${n.message}`),1}}if(this.argParser.saveAuthToConfig(s,t))console.log("\u2705 API Key \u5DF2\u4FDD\u5B58\u5230 ~/.coder/config.json"),console.log(" \u73B0\u5728\u53EF\u4EE5\u76F4\u63A5\u8FD0\u884C coder \u5F00\u59CB\u4F7F\u7528\u4E86 \u{1F680}");else return console.error("\u274C \u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 ~/.coder/ \u76EE\u5F55\u7684\u6587\u4EF6\u6743\u9650"),1;return 0}handleUpdate(){let{execSync:e}=require("child_process"),s=T();console.log(`\u5F53\u524D\u7248\u672C: ${s.version}`),console.log(`\u6B63\u5728\u5347\u7EA7 Coder...
223
+ `);try{let n=await this.argParser.promptForAKSK();s=n.ak,t=n.sk}catch(n){return console.error(`\u274C ${n.message}`),1}}if(this.argParser.saveAuthToConfig(s,t))console.log("\u2705 API Key \u5DF2\u4FDD\u5B58\u5230 ~/.coder/config.json"),console.log(" \u73B0\u5728\u53EF\u4EE5\u76F4\u63A5\u8FD0\u884C coder \u5F00\u59CB\u4F7F\u7528\u4E86 \u{1F680}");else return console.error("\u274C \u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 ~/.coder/ \u76EE\u5F55\u7684\u6587\u4EF6\u6743\u9650"),1;return 0}handleUpdate(){let{execSync:e}=require("child_process"),s=A();console.log(`\u5F53\u524D\u7248\u672C: ${s.version}`),console.log(`\u6B63\u5728\u5347\u7EA7 Coder...
224
224
  `);try{return e("npm install -g makecoder@latest",{stdio:"inherit"}),console.log(`
225
225
  \u2705 \u5347\u7EA7\u6210\u529F`),0}catch(t){return console.error(`
226
- \u274C \u5347\u7EA7\u5931\u8D25:`,t.message),1}}showVersion(){let e=T();console.log(`coder version: ${e.version}`)}async shutdown(){console.log(`
227
- Shutting down...`),process.exit(0)}};qe.exports=J});var _s=Ue(),{isPrintMode:Ds}=P();process.on("unhandledRejection",(u,e)=>{console.error("Unhandled Promise Rejection:",u),process.exit(1)});process.on("uncaughtException",u=>{console.error("Uncaught Exception:",u.message),process.env.CODEV_DEBUG&&console.error(u.stack),process.exit(1)});async function Ps(){Ds()||console.log(`Welcome to Coder!
228
- `);let u=new _s;process.on("SIGINT",async()=>{console.log(`
226
+ \u274C \u5347\u7EA7\u5931\u8D25:`,t.message),1}}showVersion(){let e=A();console.log(`coder version: ${e.version}`)}async shutdown(){console.log(`
227
+ Shutting down...`),process.exit(0)}};Ge.exports=X});var Ms=He(),{isPrintMode:Us}=T();process.on("unhandledRejection",(u,e)=>{console.error("Unhandled Promise Rejection:",u),process.exit(1)});process.on("uncaughtException",u=>{console.error("Uncaught Exception:",u.message),process.env.CODEV_DEBUG&&console.error(u.stack),process.exit(1)});async function Bs(){Us()||console.log(`Welcome to Coder!
228
+ `);let u=new Ms;process.on("SIGINT",async()=>{console.log(`
229
229
  Received SIGINT, shutting down gracefully...`),await u.shutdown()}),process.on("SIGTERM",async()=>{console.log(`
230
- Received SIGTERM, shutting down gracefully...`),await u.shutdown()});try{let e=await u.run();process.exit(e)}catch(e){console.error(`Fatal error: ${e.message}`),process.env.CODEV_DEBUG&&console.error(e.stack),process.exit(1)}}Ps().catch(u=>{console.error(`Startup error: ${u.message}`),process.exit(1)});
230
+ Received SIGTERM, shutting down gracefully...`),await u.shutdown()});try{let e=await u.run();process.exit(e)}catch(e){console.error(`Fatal error: ${e.message}`),process.env.CODEV_DEBUG&&console.error(e.stack),process.exit(1)}}Bs().catch(u=>{console.error(`Startup error: ${u.message}`),process.exit(1)});
@@ -814,7 +814,7 @@ ${s}
814
814
 
815
815
  ... [${u.toLocaleString()} characters omitted] ...
816
816
 
817
- ${c}`}var wvr="tool-outputs";async function _S(t,e,r,n,o){let s=wu(e).toLowerCase(),c=wu(r.toString()).toLowerCase(),u=c.startsWith(s)?`${c}.txt`:`${s}_${c}.txt`,d=Cu.join(n,wvr);if(o){let a=wu(o);d=Cu.join(d,`session-${a}`)}let l=Cu.join(d,u);return await Xw.mkdir(d,{recursive:!0}),await Xw.writeFile(l,t),{outputFile:l}}async function EZe(t,e){await Ga();let r=[t,...e].join(" "),n=xu(r),o=vA(n).filter(s=>s!=="shopt"&&s!=="set");return o.length>0?o[0]:yq.basename(t)}function tx(t){return typeof t=="string"?t:"pattern"in t?t.pattern:"op"in t?t.op:("comment"in t,"")}var rh=["run_shell_command","ShellTool"];async function vZe(t){if(yq.isAbsolute(t))try{return await gq.promises.access(t,gq.constants.X_OK),t}catch{return}let e=(process.env.PATH||"").split(yq.delimiter),r=mZe.platform()==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of e)for(let o of r){let s=yq.join(n,t+o);try{return await gq.promises.access(s,gq.constants.X_OK),s}catch{continue}}}var vS=null,mq=null,ex=null,Aq=class extends Error{constructor(e){super(`Failed to initialize bash parser: ${e.message}`,{cause:e}),this.name="ShellParserInitializationError"}};function Ovr(t){return t instanceof Error?t:typeof t=="string"?new Error(t):new Error("Unknown tree-sitter initialization error",{cause:t})}async function Ivr(){try{ex=null;let[t,e]=await Promise.all([ome(()=>import("./tree-sitter-NXEUY244.js"),"web-tree-sitter/tree-sitter.wasm"),ome(()=>import("./tree-sitter-bash-CUUXV34I.js"),"tree-sitter-bash/tree-sitter-bash.wasm")]);await tme.init({wasmBinary:t}),vS=await eme.load(e)}catch(t){vS=null;let e=Ovr(t),r=e instanceof Aq?e:new Aq(e);throw ex=r,r}}async function Ga(){mq||(mq=Ivr().catch(t=>{mq=null,U.debug("Failed to initialize shell parsers:",t)})),await mq}var bZe="__GCLI_POWERSHELL_COMMAND__",Rvr=1e3*1e3,Pvr=Buffer.from(`
817
+ ${c}`}var wvr="tool-outputs";async function _S(t,e,r,n,o){let s=wu(e).toLowerCase(),c=wu(r.toString()).toLowerCase(),u=c.startsWith(s)?`${c}.txt`:`${s}_${c}.txt`,d=Cu.join(n,wvr);if(o){let a=wu(o);d=Cu.join(d,`session-${a}`)}let l=Cu.join(d,u);return await Xw.mkdir(d,{recursive:!0}),await Xw.writeFile(l,t),{outputFile:l}}async function EZe(t,e){await Ga();let r=[t,...e].join(" "),n=xu(r),o=vA(n).filter(s=>s!=="shopt"&&s!=="set");return o.length>0?o[0]:yq.basename(t)}function tx(t){return typeof t=="string"?t:"pattern"in t?t.pattern:"op"in t?t.op:("comment"in t,"")}var rh=["run_shell_command","ShellTool"];async function vZe(t){if(yq.isAbsolute(t))try{return await gq.promises.access(t,gq.constants.X_OK),t}catch{return}let e=(process.env.PATH||"").split(yq.delimiter),r=mZe.platform()==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of e)for(let o of r){let s=yq.join(n,t+o);try{return await gq.promises.access(s,gq.constants.X_OK),s}catch{continue}}}var vS=null,mq=null,ex=null,Aq=class extends Error{constructor(e){super(`Failed to initialize bash parser: ${e.message}`,{cause:e}),this.name="ShellParserInitializationError"}};function Ovr(t){return t instanceof Error?t:typeof t=="string"?new Error(t):new Error("Unknown tree-sitter initialization error",{cause:t})}async function Ivr(){try{ex=null;let[t,e]=await Promise.all([ome(()=>import("./tree-sitter-JU2EI3Z2.js"),"web-tree-sitter/tree-sitter.wasm"),ome(()=>import("./tree-sitter-bash-IAB7XJEE.js"),"tree-sitter-bash/tree-sitter-bash.wasm")]);await tme.init({wasmBinary:t}),vS=await eme.load(e)}catch(t){vS=null;let e=Ovr(t),r=e instanceof Aq?e:new Aq(e);throw ex=r,r}}async function Ga(){mq||(mq=Ivr().catch(t=>{mq=null,U.debug("Failed to initialize shell parsers:",t)})),await mq}var bZe="__GCLI_POWERSHELL_COMMAND__",Rvr=1e3*1e3,Pvr=Buffer.from(`
818
818
  $ErrorActionPreference = 'Stop'
819
819
  $commandText = $env:${bZe}
820
820
  if ([string]::IsNullOrEmpty($commandText)) {
@@ -2895,7 +2895,7 @@ When adding a memory, route it to the right store:
2895
2895
  # Insufficient context
2896
2896
  If you find that you have insufficient context to read or modify the memories as described,
2897
2897
  reply with what you need, and exit. Do not search the codebase for the missing context.
2898
- `.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:E_i},modelConfig:{model:Vw},toolConfig:{tools:[ci,Pl,Rl,Hw,Il,bi,xo]},get promptConfig(){return{systemPrompt:n(),query:`${r()}\${request}`}},runConfig:{maxTimeMinutes:5,maxTurns:10}}};var Lf=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 Kpr=6e4;async function Ib(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=EA();try{let{stdout:n}=await Dl(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(Kpr),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 ${Kpr/1e3} seconds`):n}}return t}function Xpr(t){return t.startsWith("$")||t.startsWith("!")}var __i="X-API-Key",Mde=class extends Lf{constructor(r){super();this.config=r;this.headerName=r.name??__i}type="apiKey";resolvedKey;headerName;async initialize(){Xpr(this.config.key)?(this.resolvedKey=await Ib(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(r,n){if(n.status!==401&&n.status!==403){this.authRetryCount=0;return}if(!(!this.config.key.startsWith("!")||this.config.key.startsWith("!!"))&&!(this.authRetryCount>=Lf.MAX_AUTH_RETRIES))return this.authRetryCount++,U.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await Ib(this.config.key),this.headers()}};var Bde=class extends Lf{constructor(r){super();this.config=r}type="http";resolvedToken;resolvedUsername;resolvedPassword;resolvedValue;async initialize(){let r=this.config;"token"in r?this.resolvedToken=await Ib(r.token):"username"in r?(this.resolvedUsername=await Ib(r.username),this.resolvedPassword=await Ib(r.password)):this.resolvedValue=await Ib(r.value),U.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>=Lf.MAX_AUTH_RETRIES)return;U.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(r,n)}};var Zpr=Me(Jo(),1);var Aw=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},MN=5*60*1e3,_s=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}: ${be(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}: ${be(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 Aw(`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 Aw)throw r;return U.debug(`Failed to discover OAuth configuration: ${be(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 Aw(`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 efr=/^(.*\.)?run\.app$/,v_i=[/^.+\.googleapis\.com$/,efr],Ude=class extends Lf{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(efr.test(o)&&(this.useIdToken=!0),this.audience=o,!this.useIdToken&&!v_i.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 Zpr.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-MN)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=_s.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 U.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 U.error(n,r),new Error(n)}}async shouldRetryWithHeaders(r,n){if(n.status!==401&&n.status!==403){this.authRetryCount=0;return}if(!(this.authRetryCount>=Lf.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 Rb=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 Ude(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new Mde(n);return await s.initialize(),s}case"http":{let s=new Bde(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-XYD42NPZ.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 _m=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},pHe=class extends _m{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"}},Fde=class extends _m{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}},jde=class extends _m{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}},Qde=class extends _m{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 b_i(t){return typeof t=="object"&&t!==null}function S_i(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(b_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 tfr(t,e,r){let n=S_i(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new Qde(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new pHe(t,e):/\b401\b|unauthorized/i.test(n)?new Fde(t,e,401):/\b403\b|forbidden/i.test(n)?new Fde(t,e,403):new Qde(t,e,r)}function fHe(t){return`${t.name}-config`}var qde=class{constructor(e){this.config=e}agents=new Map;allDefinitions=new Map;builtInAgents=new Set;async initialize(){Ee.on("model-changed",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(),Ee.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),Ee.emitAgentsRefreshed())}dispose(){Ee.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 lHe(e);for(let s of r.errors)U.warn(`[AgentRegistry] Error loading user agent: ${s.message}`),Ee.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),Ee.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 lHe(s);for(let p of c.errors)Ee.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?rfr.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&&Ee.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),Ee.emitFeedback("error",`Error registering project agent "${p.name}": ${f instanceof Error?f.message:String(f)}`)}}))}else Ee.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),Ee.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=oue(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=$pr(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=zpr(this.config);this.builtInAgents.add(n.name),this.registerLocalAgent(n);let o=this.config.getBrowserAgentConfig();if(o.enabled){let s=process.env.SANDBOX,c=!!s&&s!=="sandbox-exec"&&s!=="sandbox:none",u=o.customConfig.sessionMode??"persistent";if(c&&u!=="existing")Ee.emitFeedback("info",'Browser agent disabled in container sandbox. To use it, set sessionMode to "existing" in settings and start Chrome with --remote-debugging-port=9222 on the host.');else{let d=Lde(this.config);this.builtInAgents.add(d.name),this.registerLocalAgent(d)}}if(this.config.isMemoryManagerEnabled()){this.registerLocalAgent(Jpr(this.config));try{let s=er.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"?"allow":"ask_user",priority:CQ,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=Cde(n),c;if(e.auth){let p=await Rb.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,Tde(n),c);if(u.securitySchemes){let p=Rb.validateAuthConfig(e.auth,u.securitySchemes);if(!p.valid&&p.diff){let f=Rb.describeRequiredAuth(u.securitySchemes),g=new jde(e.name,f,p.diff.missingConfig);Ee.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(`
2898
+ `.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:E_i},modelConfig:{model:Vw},toolConfig:{tools:[ci,Pl,Rl,Hw,Il,bi,xo]},get promptConfig(){return{systemPrompt:n(),query:`${r()}\${request}`}},runConfig:{maxTimeMinutes:5,maxTurns:10}}};var Lf=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 Kpr=6e4;async function Ib(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=EA();try{let{stdout:n}=await Dl(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(Kpr),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 ${Kpr/1e3} seconds`):n}}return t}function Xpr(t){return t.startsWith("$")||t.startsWith("!")}var __i="X-API-Key",Mde=class extends Lf{constructor(r){super();this.config=r;this.headerName=r.name??__i}type="apiKey";resolvedKey;headerName;async initialize(){Xpr(this.config.key)?(this.resolvedKey=await Ib(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(r,n){if(n.status!==401&&n.status!==403){this.authRetryCount=0;return}if(!(!this.config.key.startsWith("!")||this.config.key.startsWith("!!"))&&!(this.authRetryCount>=Lf.MAX_AUTH_RETRIES))return this.authRetryCount++,U.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await Ib(this.config.key),this.headers()}};var Bde=class extends Lf{constructor(r){super();this.config=r}type="http";resolvedToken;resolvedUsername;resolvedPassword;resolvedValue;async initialize(){let r=this.config;"token"in r?this.resolvedToken=await Ib(r.token):"username"in r?(this.resolvedUsername=await Ib(r.username),this.resolvedPassword=await Ib(r.password)):this.resolvedValue=await Ib(r.value),U.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>=Lf.MAX_AUTH_RETRIES)return;U.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(r,n)}};var Zpr=Me(Jo(),1);var Aw=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},MN=5*60*1e3,_s=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}: ${be(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}: ${be(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 Aw(`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 Aw)throw r;return U.debug(`Failed to discover OAuth configuration: ${be(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 Aw(`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 efr=/^(.*\.)?run\.app$/,v_i=[/^.+\.googleapis\.com$/,efr],Ude=class extends Lf{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(efr.test(o)&&(this.useIdToken=!0),this.audience=o,!this.useIdToken&&!v_i.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 Zpr.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-MN)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=_s.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 U.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 U.error(n,r),new Error(n)}}async shouldRetryWithHeaders(r,n){if(n.status!==401&&n.status!==403){this.authRetryCount=0;return}if(!(this.authRetryCount>=Lf.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 Rb=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 Ude(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new Mde(n);return await s.initialize(),s}case"http":{let s=new Bde(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-VD7VX4RN.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 _m=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},pHe=class extends _m{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"}},Fde=class extends _m{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}},jde=class extends _m{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}},Qde=class extends _m{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 b_i(t){return typeof t=="object"&&t!==null}function S_i(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(b_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 tfr(t,e,r){let n=S_i(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new Qde(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new pHe(t,e):/\b401\b|unauthorized/i.test(n)?new Fde(t,e,401):/\b403\b|forbidden/i.test(n)?new Fde(t,e,403):new Qde(t,e,r)}function fHe(t){return`${t.name}-config`}var qde=class{constructor(e){this.config=e}agents=new Map;allDefinitions=new Map;builtInAgents=new Set;async initialize(){Ee.on("model-changed",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(),Ee.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),Ee.emitAgentsRefreshed())}dispose(){Ee.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 lHe(e);for(let s of r.errors)U.warn(`[AgentRegistry] Error loading user agent: ${s.message}`),Ee.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),Ee.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 lHe(s);for(let p of c.errors)Ee.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?rfr.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&&Ee.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),Ee.emitFeedback("error",`Error registering project agent "${p.name}": ${f instanceof Error?f.message:String(f)}`)}}))}else Ee.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),Ee.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=oue(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=$pr(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=zpr(this.config);this.builtInAgents.add(n.name),this.registerLocalAgent(n);let o=this.config.getBrowserAgentConfig();if(o.enabled){let s=process.env.SANDBOX,c=!!s&&s!=="sandbox-exec"&&s!=="sandbox:none",u=o.customConfig.sessionMode??"persistent";if(c&&u!=="existing")Ee.emitFeedback("info",'Browser agent disabled in container sandbox. To use it, set sessionMode to "existing" in settings and start Chrome with --remote-debugging-port=9222 on the host.');else{let d=Lde(this.config);this.builtInAgents.add(d.name),this.registerLocalAgent(d)}}if(this.config.isMemoryManagerEnabled()){this.registerLocalAgent(Jpr(this.config));try{let s=er.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"?"allow":"ask_user",priority:CQ,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=Cde(n),c;if(e.auth){let p=await Rb.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,Tde(n),c);if(u.securitySchemes){let p=Rb.validateAuthConfig(e.auth,u.securitySchemes);if(!p.valid&&p.diff){let f=Rb.describeRequiredAuth(u.securitySchemes),g=new jde(e.name,f,p.diff.missingConfig);Ee.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(`
2899
2899
  `);a.push(`Skills:
2900
2900
  ${p}`)}a.length>0&&(e.description=a.join(`
2901
2901
  `)),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 _m?Ee.emitFeedback("error",`[${e.name}] ${o.userMessage}`):Ee.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?wN.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(fHe(e),{modelConfig:o}),o.model&&xs(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 BN from"node:fs/promises";import*as nfr from"node:path";var Gde=class{acknowledgedAgents={};loaded=!1;async load(){if(this.loaded)return;let e=er.getAcknowledgedAgentsPath();try{let r=await BN.readFile(e,"utf-8");this.acknowledgedAgents=JSON.parse(r)}catch(r){(!Lt(r)||r.code!=="ENOENT")&&U.error("Failed to load acknowledged agents:",be(r)),this.acknowledgedAgents={}}this.loaded=!0}async save(){let e=er.getAcknowledgedAgentsPath();try{let r=nfr.dirname(e);await BN.mkdir(r,{recursive:!0}),await BN.writeFile(e,JSON.stringify(this.acknowledgedAgents,null,2),"utf-8")}catch(r){U.error("Failed to save acknowledged agents:",be(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 Vde(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 T_i}from"node:async_hooks";var ifr=new T_i;function hHe(t,e){return ifr.run(t,e)}function Hde(){return ifr.getStore()}var ofr=Me(mse(),1);function K7(t){return typeof t=="object"&&t!==null&&"callId"in t&&"responseParts"in t}function nBo(t){let{displayName:e,status:r,approvalMode:n,hasResultDisplay:o,parentCallId:s}=t;if(s)return!0;switch(e){case QD:switch(r){case"scheduled":case"validating":case"executing":case"awaiting_approval":return!0;case"error":return!o;default:return!1}case YQ:case JQ:return n==="plan";default:return!1}}function X7(t,e,r=3){let n=e.map(c=>({name:c,distance:ofr.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 iBo(t,e,r){let n;xQ(t)?n=[t.name,t.constructor.name]:n=[t],n.some(o=>rh.includes(o))&&(n=[...new Set([...n,...rh])]);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=>rh.includes(l))&&(d===u||d.startsWith(u+" ")))return!0}return!1}var $de=class{constructor(e,r=snt,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(!K7(n))throw new Error(`Invalid data for 'success' transition (callId: ${e.request.callId})`);return this.toSuccess(e,n)}case"error":{if(!K7(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"&&!K7(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??ZJe(u.fileDiff)})}let s;if(e.status==="executing"&&e.liveOutput&&(s=e.liveOutput),K7(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.originalRequestName??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 C_i}from"node:events";import{randomUUID as w_i}from"node:crypto";async function x_i(t,e,r){if(r.aborted)throw new Error("Operation cancelled");try{for await(let[n]of C_i(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 gHe(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 O_i(r,a);let p=w_i(),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 P_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==="modify_with_editor"){let E=await I_i(r,t,e);E.error&&Ee.emitFeedback("error",E.error)}else y.payload&&"newContent"in y.payload&&(await R_i(r,t,y.payload,e),c="proceed_once")}return{outcome:c,lastDetails:u}}async function O_i(t,e){t.config.getHookSystem()&&await t.config.getHookSystem()?.fireToolNotificationEvent({...e,onConfirm:async()=>{}})}async function I_i(t,e,r){let{state:n,modifier:o,getPreferredEditor:s}=t,c=s(),u=await WMt(c,r);if(!u)return{error:GMt};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 R_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 P_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=x_i(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=>(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 sfr(t,e){return{errorMessage:`Tool execution denied by policy.${e?.denyMessage?` ${e.denyMessage}`:""}`,errorType:"policy_violation"}}async function afr(t,e,r){let n=t.tool instanceof Jn?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 lfr(t,e,r,n,o,s){if(k_i(t,e)){n.config.setApprovalMode("autoEdit");return}let c,u,d=n.config.getApprovalMode();if(e==="proceed_always"||e==="proceed_always_tool"||e==="proceed_always_server"||e==="proceed_always_and_save"){let l=Age.indexOf(d);l!==-1&&(u=Age.slice(l))}if(e==="proceed_always_and_save"&&(n.config&&n.config.isTrustedFolder()&&n.config.getWorkspacePoliciesDir()!==void 0?c="workspace":c="user"),r?.type==="mcp"){await D_i(t,e,r,o,c,u);return}await N_i(t,e,r,o,c,s,n.config,u)}function k_i(t,e){return e==="proceed_always"&&jD.has(t.name)}async function N_i(t,e,r,n,o,s,c,u){if(e==="proceed_always"||e==="proceed_always_and_save"){let d=s?.getPolicyUpdateOptions?.(e)||{};if(!d.commandPrefix&&r?.type==="exec")d.commandPrefix=r.rootCommands;else if(!d.argsPattern&&r?.type==="edit"){let l=c?wo(r.filePath,c.getTargetDir()):r.filePath;d.argsPattern=ov(l)}await n.publish({type:"update-policy",toolName:t.name,persist:e==="proceed_always_and_save",persistScope:o,modes:u,...d})}}async function D_i(t,e,r,n,o,s){if(!(e==="proceed_always"||e==="proceed_always_tool"||e==="proceed_always_server"||e==="proceed_always_and_save"))return;let u=t.name,d=e==="proceed_always_and_save";e==="proceed_always_server"&&(u=dS(r.serverName,"*")),await n.publish({type:"update-policy",toolName:u,mcpName:r.serverName,persist:d,persistScope:o,modes:s})}function mHe(t,e){if(!(t instanceof _Ke))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 cfr(t,e,r,n,o,s,c,u,d){let l=t.params||{},a=!1,p=[],f=c?mHe(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 Q0){let v=E.getModifiedToolInput();if(v){Object.assign(t.params,v),U.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=`