makecoder 2.0.71 → 2.0.75

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 at=Object.create;var he=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ht=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var m=(d,e)=>()=>(e||d((e={exports:{}}).exports,e),e.exports);var dt=(d,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of lt(e))!ut.call(d,o)&&o!==t&&he(d,o,{get:()=>e[o],enumerable:!(s=ct(e,o))||s.enumerable});return d};var gt=(d,e,t)=>(t=d!=null?at(ht(d)):{},dt(e||!d||!d.__esModule?he(t,"default",{value:d,enumerable:!0}):t,d));var de=m((rs,ue)=>{var ft=require("http"),L=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 t=e.split(".");if(t.length!==2)return!1;let[s,o]=t;return s&&s.length>0&&o&&o.length>0}async waitForCallback(e){return new Promise((t,s)=>{let o=!1;this.server=ft.createServer((n,i)=>{let a=new URL(n.url,`http://localhost:${this.port}`);if(a.pathname==="/callback"){let r=a.searchParams.get("token"),c=a.searchParams.get("state"),l=a.searchParams.get("error");if(l){i.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),i.end(`
2
+ var Be=Object.create;var Y=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Ve=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Re=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 Ve(e))!Re.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(Ge(u)):{},Le(e||!u||!u.__esModule?Y(s,"default",{value:u,enumerable:!0}):s,u));var X=f((As,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(`
3
3
  <!DOCTYPE html>
4
4
  <html>
5
5
  <head>
@@ -24,7 +24,7 @@ var at=Object.create;var he=Object.defineProperty;var ct=Object.getOwnPropertyDe
24
24
  </div>
25
25
  </body>
26
26
  </html>
27
- `),o||(o=!0,this.cleanup(),s(new Error(`OAuth error: ${l}`)));return}if(c!==e){i.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),i.end(`
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(`
28
28
  <!DOCTYPE html>
29
29
  <html>
30
30
  <head>
@@ -46,7 +46,7 @@ var at=Object.create;var he=Object.defineProperty;var ct=Object.getOwnPropertyDe
46
46
  </div>
47
47
  </body>
48
48
  </html>
49
- `),o||(o=!0,this.cleanup(),s(new Error("Invalid state parameter - possible CSRF attack")));return}if(!r){i.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),i.end(`
49
+ `),o||(o=!0,this.cleanup(),t(new Error("Invalid state parameter - possible CSRF attack")));return}if(!i){r.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
50
50
  <!DOCTYPE html>
51
51
  <html>
52
52
  <head>
@@ -68,7 +68,7 @@ var at=Object.create;var he=Object.defineProperty;var ct=Object.getOwnPropertyDe
68
68
  </div>
69
69
  </body>
70
70
  </html>
71
- `),o||(o=!0,this.cleanup(),s(new Error("No token received from OAuth callback")));return}if(!this.validateTokenFormat(r)){i.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),i.end(`
71
+ `),o||(o=!0,this.cleanup(),t(new Error("No token received from OAuth callback")));return}if(!this.validateTokenFormat(i)){r.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
72
72
  <!DOCTYPE html>
73
73
  <html>
74
74
  <head>
@@ -92,7 +92,7 @@ var at=Object.create;var he=Object.defineProperty;var ct=Object.getOwnPropertyDe
92
92
  </div>
93
93
  </body>
94
94
  </html>
95
- `),o||(o=!0,this.cleanup(),s(new Error("Invalid token format - expected ak.sk format")));return}let[h,u]=r.split(".");i.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),i.end(`
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(`
96
96
  <!DOCTYPE html>
97
97
  <html>
98
98
  <head>
@@ -124,28 +124,28 @@ var at=Object.create;var he=Object.defineProperty;var ct=Object.getOwnPropertyDe
124
124
  </script>
125
125
  </body>
126
126
  </html>
127
- `),o||(o=!0,this.cleanup(),t({ak:h,sk:u}))}else i.writeHead(404,{"Content-Type":"text/plain"}),i.end("Not Found")}),this.server.on("error",n=>{if(n.code==="EADDRINUSE"){if(this.port++,this.port>9390){o||(o=!0,s(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(),s(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(),s(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)}};ue.exports=L});var fe=m((is,ge)=>{var mt=require("crypto"),pt=de(),R=class{constructor(e={}){this.baseUrl=e.baseUrl||"https://makecoder.com",this.callbackServer=null}generateState(){return mt.randomBytes(16).toString("hex")}buildAuthorizationUrl(e,t){let s=new URLSearchParams({redirect_uri:e,state:t,response_type:"token"});return`${this.baseUrl}/oauth/authorize?${s.toString()}`}async login(){let e=this.generateState();this.callbackServer=new pt;try{let t=this.callbackServer.getCallbackUrl(),s=this.buildAuthorizationUrl(t,e);console.log(`
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((Ts,ee)=>{var We=require("crypto"),je=X(),M=class{constructor(e={}){this.baseUrl=e.baseUrl||"https://makecoder.com",this.callbackServer=null}generateState(){return We.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 je;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
- `),console.log(`\u{1F310} \u6388\u6743\u5730\u5740: ${s}
130
+ `),console.log(`\u{1F310} \u6388\u6743\u5730\u5740: ${t}
131
131
  `),console.log(`\u23F3 \u7B49\u5F85\u60A8\u7684\u6388\u6743...(\u8D85\u65F6\u65F6\u95F4: 5\u5206\u949F)
132
- `);try{let n=(await import("open")).default;await n(s)}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
- `),o}catch(t){throw console.error(`
134
- \u274C OAuth \u767B\u5F55\u5931\u8D25: ${t.message}
135
- `),t}finally{this.callbackServer&&this.callbackServer.cleanup()}}cleanup(){this.callbackServer&&this.callbackServer.cleanup()}};ge.exports=R});var we=m((as,pe)=>{var b=require("fs"),me=require("path"),wt=require("os"),St=require("readline"),yt=fe(),N=class{constructor(){this.configPath=me.join(wt.homedir(),".coder","config.json"),this.defaultConfig={agent:"claude",auth:{ak:null,sk:null}}}async promptForAKSK(){let e=St.createInterface({input:process.stdin,output:process.stdout});return new Promise((t,s)=>{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(),s(new Error("\u683C\u5F0F\u9519\u8BEF"));return}let i=o.substring(0,n),a=o.substring(n+1);if(!i.trim()||!a.trim()){e.close(),s(new Error("\u683C\u5F0F\u9519\u8BEF"));return}e.close(),t({ak:i.trim(),sk:a.trim()})})})}ensureConfig(){let e=me.dirname(this.configPath);try{b.existsSync(e)||b.mkdirSync(e,{recursive:!0}),b.existsSync(this.configPath)||b.writeFileSync(this.configPath,JSON.stringify(this.defaultConfig,null,2))}catch(t){return console.warn(`Warning: Could not create config file: ${t.message}`),this.defaultConfig}}loadConfig(){this.ensureConfig();try{let e=b.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 t=this.loadConfig(),s={agent:t.agent||"claude",remainingArgs:[]},o=0,n=!1;if(e.length>0&&["claude","gemini","codex"].includes(e[0])?(s.agent=e[0],n=!0,o=1):e.length>0&&e[0]==="pub"?(s.command="pub",o=1):e.length>0&&e[0]==="tunnel"?(s.command="tunnel",o=1):e.length>0&&e[0]==="login"&&(s.command="login",o=1),s.command==="tunnel"){let r={port:null,host:null,name:null,localHost:null,allowedPaths:[],printRequests:!1};for(;o<e.length;){let c=e[o];if(c==="--port"||c==="-p"){if(o+1>=e.length)throw new Error("--port requires a port number");if(r.port=parseInt(e[o+1],10),isNaN(r.port))throw new Error(`Invalid port number: ${e[o+1]}`);o+=2}else if(c==="--host"){if(o+1>=e.length)throw new Error("--host requires a URL");r.host=e[o+1],o+=2}else if(c==="--name"||c==="-n"){if(o+1>=e.length)throw new Error("--name requires a service name");r.name=e[o+1],o+=2}else if(c==="--local-host"){if(o+1>=e.length)throw new Error("--local-host requires a hostname");r.localHost=e[o+1],o+=2}else if(c==="--path"){if(o+1>=e.length)throw new Error("--path requires a URL path (e.g. /claw/wecom)");r.allowedPaths.push(e[o+1]),o+=2}else if(c==="--print-requests")r.printRequests=!0,o+=1;else if(c==="--help"||c==="-h")s.tunnelHelp=!0,o+=1;else throw new Error(`Unknown tunnel option: ${c}`)}if(!s.tunnelHelp&&!r.port)throw new Error("--port is required for tunnel command. Usage: coder tunnel --port <port>");s.tunnelArgs=r}for(;o<e.length;){let r=e[o];if(r==="--agent"){if(n)throw new Error(`Cannot use both subcommand '${s.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'`);s.agent=c,o+=2}else if(r==="--apikey"||r==="--aksk")if(o+1>=e.length||e[o+1].startsWith("--"))s.needAKSKPrompt=!0,o+=1;else{let c=e[o+1],l=c.indexOf(".");if(l===-1)throw new Error("API Key Format error");s.auth_ak=c.substring(0,l),s.auth_sk=c.substring(l+1),o+=2}else if(r==="--save-auth")s.saveAuth=!0,o+=1;else if(r==="--name")o+1>=e.length||e[o+1].startsWith("--")?o+=1:(s.pubName=e[o+1],o+=2);else if(r==="--clear-auth")s.clearAuth=!0,o+=1;else if(r==="--allow-clone")s.allowClone=!0,o+=1;else{s.remainingArgs=e.slice(o);break}}if(s.needAKSKPrompt)try{let{ak:r,sk:c}=await this.promptForAKSK();s.auth_ak=r,s.auth_sk=c,delete s.needAKSKPrompt}catch(r){console.error(`\u274C ${r.message}`),process.exit(1)}if(s.command!=="login"&&(!s.auth_ak&&t.auth&&t.auth.ak&&(s.auth_ak=t.auth.ak),!s.auth_sk&&t.auth&&t.auth.sk&&(s.auth_sk=t.auth.sk),!s.auth_ak&&process.env.CODEV_AUTH_AK&&(s.auth_ak=process.env.CODEV_AUTH_AK),!s.auth_sk&&process.env.CODEV_AUTH_SK&&(s.auth_sk=process.env.CODEV_AUTH_SK)),s.saveAuth&&s.auth_ak&&s.auth_sk){let r=this.saveAuthToConfig(s.auth_ak,s.auth_sk);console.log(r?"\u2705 API Key \u5DF2\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6":"\u274C \u4FDD\u5B58 API Key \u5931\u8D25"),process.exit(0)}if(s.clearAuth){let r=this.clearAuthFromConfig();console.log(r?"\u2705 API Key \u5DF2\u4ECE\u914D\u7F6E\u6587\u4EF6\u6E05\u9664":"\u274C \u6E05\u9664 API Key \u5931\u8D25"),process.exit(0)}let i=s.remainingArgs.includes("--version")||s.remainingArgs.includes("-v"),a=s.remainingArgs.includes("--help")||s.remainingArgs.includes("-h");if(s.command!=="login"&&!i&&!a&&(!s.auth_ak||!s.auth_sk))try{console.log(`\u274C \u7F3A\u5C11\u5FC5\u8981\u7684 API Key
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
+ `),o}catch(s){throw console.error(`
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((Os,oe)=>{var C=require("fs"),te=require("path"),ze=require("os"),Je=require("readline"),Qe=se(),q=class{constructor(){this.configPath=te.join(ze.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);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"&&!r&&!a&&(!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 yt({baseUrl:"https://makecoder.com",apiBaseUrl:s.codevServer||"https://makecoder.com/bigapis/codev/v1"}).login();s.auth_ak=c.ak,s.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 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
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
- `)}catch(r){console.error(`
141
- \u274C \u767B\u5F55\u5931\u8D25: ${r.message}
140
+ `)}catch(i){console.error(`
141
+ \u274C \u767B\u5F55\u5931\u8D25: ${i.message}
142
142
  `),console.error(`\u{1F4CB} \u60A8\u4E5F\u53EF\u4EE5\u624B\u52A8\u83B7\u53D6 API Key\uFF1A
143
143
  \u8BF7\u8BBF\u95EE\uFF1Ahttps://makecoder.com/my/apikeys
144
144
 
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?s.codevServer=process.env.CODEV_SERVER:t.codevServer?s.codevServer=t.codevServer:s.codevServer="https://makecoder.com/bigapis/codev/v1",s}saveAuthToConfig(e,t){let s=this.loadConfig();s.auth||(s.auth={}),s.auth.ak=e,s.auth.sk=t;try{return b.writeFileSync(this.configPath,JSON.stringify(s,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 b.writeFileSync(this.configPath,JSON.stringify(e,null,2)),!0}catch(t){return console.warn(`Warning: Could not clear auth from config: ${t.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 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(`
149
149
  Coder AI Agent
150
150
 
151
151
  USAGE:
@@ -153,7 +153,6 @@ USAGE:
153
153
  coder <agent> [agent-args...]
154
154
  coder login [--apikey <API Key>]
155
155
  coder pub [--name <name>]
156
- coder tunnel --port <port> [options]
157
156
 
158
157
  AGENTS:
159
158
  claude Use Claude Code (default)
@@ -162,8 +161,8 @@ AGENTS:
162
161
 
163
162
  COMMANDS:
164
163
  login \u767B\u5F55 MakeCoder\uFF0C\u4FDD\u5B58 API Key \u5230\u672C\u5730\u914D\u7F6E
164
+ update \u5347\u7EA7 Coder \u5230\u6700\u65B0\u7248\u672C
165
165
  pub Publish current directory to hosting server
166
- tunnel Expose a local port via tunnel (for webhook callbacks, etc.)
167
166
 
168
167
  EXAMPLES:
169
168
  coder claude # Launch Claude agent
@@ -172,7 +171,6 @@ EXAMPLES:
172
171
  coder --agent claude # Alternative syntax
173
172
  coder pub --name myproject # Publish current directory as 'myproject'
174
173
  coder pub # Publish (will prompt for name)
175
- coder tunnel --port 18789 --name myapp # Expose local port via tunnel
176
174
 
177
175
  OPTIONS:
178
176
  --agent <agent> Specify which agent to use (claude|gemini|codex)
@@ -185,76 +183,36 @@ OPTIONS:
185
183
  --name <name> (pub command) Project name for publishing
186
184
  --allow-clone (pub command) Include Claude Code generation history for cloning
187
185
 
188
- TUNNEL OPTIONS:
189
- --port, -p <port> (tunnel) Local port to expose (required)
190
- --name, -n <name> (tunnel) Service name (server assigns subdomain as <userid>-<name>)
191
- --path <path> (tunnel) Allow only this URL path (can be used multiple times)
192
- --host <url> (tunnel) Tunnel server URL (default: https://tunnel.makecoder.com)
193
- --local-host <host> (tunnel) Tunnel traffic to this host instead of localhost
194
- --print-requests (tunnel) Print incoming request info
195
-
196
186
  CONFIG:
197
187
  Default configuration is stored in ~/.coder/config.json
198
188
  Command line --agent overrides the default but doesn't modify the file.
199
189
  Auth credentials can be stored in config file under "auth" section.
200
- `)}};pe.exports=N});var U=m((cs,Se)=>{function Ct(d=process.argv.slice(2)){return d.includes("--print")||d.includes("-p")}Se.exports={isPrintMode:Ct}});var F=m((ls,Ee)=>{var{spawn:Et}=require("child_process"),T=require("path"),I=require("fs"),ye=require("os"),{isPrintMode:Ce}=U(),H=class{constructor(e){this.config=e}resloveSettingFilePath(e){return T.join(e,this.config.configDir,"settings.json")}readModelFromSettingsFile(e){try{let t=this.resloveSettingFilePath(e);if(I.existsSync(t)){let s=I.readFileSync(t,"utf8"),o=JSON.parse(s);if(o&&o.model)return o.model}}catch(t){console.warn(e,t.message)}return null}getCurrentModel(e){let t=e.findIndex(o=>o==="--model");if(t!==-1&&t+1<e.length)return e[t+1];let s=this.readModelFromSettingsFile(process.cwd());return s||(s=this.readModelFromSettingsFile(ye.homedir()),s)?s:this.config.defaultModel}async ensureConfig(e=0){let t=T.join(ye.homedir(),this.config.configDir,this.config.configFile),s=T.dirname(t);if(!I.existsSync(t)){let o=this.config.defaultConfig||{};try{I.existsSync(s)||I.mkdirSync(s,{recursive:!0}),I.writeFileSync(t,JSON.stringify(o,null,2)),e>0&&await new Promise(n=>setTimeout(n,e))}catch(n){console.warn(`Failed to create ${this.config.configFile}: ${n.message}`)}}}findExecutablePath(){let e=T.dirname(require.main.filename);for(let t of this.config.executablePaths){let s=T.resolve(e,t);if(I.existsSync(s))return s}throw new Error(`Could not find executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}handleChildMessages(e){process.env.CODEV_DEBUG&&console.log("Child process message handler initialized"),e.connected&&(e.on("message",t=>{this.onChildMessage(t)}),e.on("exit",async(t,s)=>{try{await this.handleChildProcessExit(t,s)}catch(o){console.error("Error in handleChildProcessExit:",o.message)}}),e.on("error",t=>{this.handleChildProcessError(t)}))}onChildMessage(e){process.env.CODEV_DEBUG&&console.log("Received IPC message from child:",e)}handleChildProcessExit(e,t){}handleChildProcessError(e){}async launch(e={}){let{remainingArgs:t=[],codevServer:s,auth_ak:o=null,auth_sk:n=null}=e;try{let i=this.getCurrentModel(t);Ce(t)||console.log(`model:\x1B[90m\x1B[3m ${i} (use /model to switch models) \x1B[0m`),await this.ensureConfig(1e3);let a=this.findExecutablePath();return process.env.CODEV_DEBUG&&console.log(`executablePath: ${a}`),new Promise((r,c)=>{let l={...process.env,...this.config.environmentVariables(s)};o&&(l.CODEV_AUTH_AK=o),n&&(l.CODEV_AUTH_SK=n);let h=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&h.push("--inspect-brk"),h.push(a,...t);let u=Et("node",h,{env:l,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(u),u.on("error",g=>{console.error(`Failed to start: ${g.message}`),c(g)}),u.on("exit",async(g,S)=>{Ce(t)||S&&console.log(`terminated by signal: ${S}`)}),process.on("SIGINT",async()=>{console.log(`
201
- Terminating ...`),u.kill("SIGTERM"),setTimeout(()=>{u.killed||u.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
202
- Terminating ...`),u.kill("SIGTERM"),setTimeout(()=>{u.killed||u.kill("SIGKILL")},8e3)})})}catch(i){throw i}}};Ee.exports=H});var xe=m((hs,ve)=>{var f=process.env.CODEV_DEBUG==="True",G=class{constructor(e={}){this.queue=[],this.processing=!1,this.shuttingDown=!1,this.shutdownTimeout=e.shutdownTimeout||5e3,this.maxRetries=e.maxRetries||3,this.retryDelay=e.retryDelay||1e3,this.onProcessMessage=e.onProcessMessage||null,this.shutdownPromise=null,this.currentlyProcessing=null}enqueue(e){if(this.shuttingDown)return f&&console.log("Queue is shutting down, skipping new messages"),null;let t={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(t),f&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),t.id}dequeue(){let e=this.queue.shift();return f&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let t=this.queue.findIndex(s=>s.id===e);return t>-1?(this.queue.splice(t,1),f&&console.log(`Message ${e} removed from queue`),!0):!1}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{for(;this.queue.length>0&&!this.shuttingDown;){let e=this.queue[0];e.processing=!0;try{this.onProcessMessage&&await this.onProcessMessage(e),this.dequeue()}catch(t){if(f&&console.error(`Failed to process message: ${t.message}`),e.retryCount++,f&&console.log("Start Retry:",e.retryCount,"times..."),e.retryCount>=this.maxRetries)f&&console.error("Message exceeded max retries, removing from queue"),this.dequeue();else{e.processing=!1;let s=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,s))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],f&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let t=this.queue.filter(o=>o.processing);if(t.length===0)return;f&&console.log(`Waiting for ${t.length} processing messages to complete (timeout: ${e}ms)`);let s=Date.now();for(;Date.now()-s<e;){if(this.queue.filter(n=>n.processing).length===0){f&&console.log(`All processing messages completed in ${Date.now()-s}ms`);return}await new Promise(n=>setTimeout(n,50))}if(f){let o=this.queue.filter(n=>n.processing);console.log(`Timeout waiting for processing messages. ${o.length} messages still processing`)}}async gracefulShutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let{timeoutMs:t=this.shutdownTimeout,batchSize:s=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async n=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(t*.3,3e3));let i=this.queue.filter(g=>!g.processing),a=i.length;f&&(console.log(`Starting graceful shutdown with ${a} pending messages (${this.queue.length-a} already processing)`),console.log(`Mode: ${o?"fast (parallel)":"sequential"}, timeout: ${t}ms`));let r=Date.now(),c=0,l=0;try{if(o){let g=await this.processAllParallel(t-(Date.now()-r),i);c=g.processed,l=g.failed}else{let g=await this.processInBatches(s,t-(Date.now()-r),i);c=g.processed,l=g.failed}}catch(g){f&&console.error("Error during shutdown processing:",g.message)}let h=Date.now()-r,u=this.queue.length;f&&(console.log(`Shutdown completed in ${h}ms:`),console.log(` - Total: ${a} messages`),console.log(` - Processed: ${c}`),console.log(` - Failed: ${l}`),console.log(` - Remaining: ${u}`)),n({totalMessages:a,processedMessages:c,failedMessages:l,remainingMessages:u,duration:h,allMessagesSent:u===0&&l===0})}),this.shutdownPromise}async processAllParallel(e){if(this.queue.length===0)return{processed:0,failed:0};f&&console.log(`Processing ${this.queue.length} messages in parallel...`);let t=[...this.queue];this.queue=[];let s=t.map(async r=>{try{return this.onProcessMessage&&await this.onProcessMessage(r),{success:!0,messageId:r.id}}catch(c){return f&&console.warn(`Message ${r.id} processing failed: ${c.message}`),{success:!1,messageId:r.id,error:c}}}),o=new Promise(r=>{setTimeout(()=>r({timedOut:!0}),e)}),n=await Promise.race([Promise.allSettled(s).then(r=>({results:r})),o]);if(n.timedOut)return f&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:t.length};let i=n.results.filter(r=>r.status==="fulfilled"&&r.value?.success).length,a=t.length-i;return{processed:i,failed:a}}async processInBatches(e,t){if(this.queue.length===0)return{processed:0,failed:0};f&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let s=Date.now(),o=0,n=0;for(;this.queue.length>0&&Date.now()-s<t;){let i=this.queue.splice(0,e),a=i.map(async h=>{try{return this.onProcessMessage&&await this.onProcessMessage(h),{success:!0}}catch(u){return f&&console.warn(`Batch message processing failed: ${u.message}`),{success:!1,error:u}}}),c=(await Promise.allSettled(a)).filter(h=>h.status==="fulfilled"&&h.value?.success).length,l=i.length-c;o+=c,n+=l,f&&i.length>0&&console.log(`Batch completed: ${c}/${i.length} successful`),this.queue.length>0&&await new Promise(h=>setTimeout(h,10))}return this.queue.length>0&&(n+=this.queue.length,f&&console.log(`${this.queue.length} messages not processed due to timeout`),this.queue=[]),{processed:o,failed:n}}async forceFlushAndShutdown(e=2e3){this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(e*.4,1e3));let t=this.queue.filter(r=>!r.processing);f&&console.log(`Force flush: attempting to send ${t.length} pending messages within ${e}ms (${this.queue.length-t.length} already processing)`);let s=Date.now(),o=t.map(async r=>{try{return this.onProcessMessage&&Date.now()-s<e?(await this.onProcessMessage(r),{success:!0,messageId:r.id}):{success:!1,messageId:r.id,reason:"timeout"}}catch(c){return{success:!1,messageId:r.id,error:c.message}}}),n=e-(Date.now()-s),i=new Promise(r=>{setTimeout(()=>r({timedOut:!0}),Math.max(100,n))}),a=await Promise.race([Promise.allSettled(o).then(r=>({results:r})),i]);if(t.forEach(r=>{let c=this.queue.findIndex(l=>l.id===r.id);c>-1&&this.queue.splice(c,1)}),this.processing=!1,a.timedOut)return f&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:t.length};{let r=a.results.filter(c=>c.status==="fulfilled"&&c.value.success).length;return f&&console.log(`Force flush completed: ${r}/${t.length} messages sent`),{success:r===t.length,successCount:r,totalCount:t.length,results:a.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,f&&console.log("Force shutdown: Queue cleared")}};ve.exports=G});var V=m((us,vt)=>{vt.exports={name:"makecoder",version:"2.0.71",description:"MakeCoder: Unified AI agent CLI tool integrating Claude Code, Codex and Gemini CLI",main:"./dist/coder.js",bin:{coder:"./dist/coder.js"},scripts:{test:'echo "Error: no test specified" && exit 1',start:"node ./src/coder.js",build:"node scripts/build.js","build:clean":"node scripts/build.js --clean","build:dev":"node scripts/build.js --no-minify --sourcemap",postinstall:"node scripts/postinstall.js"},keywords:["cli","ai","claude","gemini","codex","agent"],author:"makecoder",license:"MIT",dependencies:{"node-fetch":"^3.3.2",open:"^10.1.0",zod:"^3.25.76"},optionalDependencies:{"makecoder-codex-linux-x64":"*","makecoder-codex-darwin-arm64":"*","makecoder-codex-win32-x64":"*"},engines:{node:">=20.0.0"},devDependencies:{chokidar:"^4.0.3"},files:["dist","claude","scripts/postinstall.js"]}});var ke=m((ds,Ie)=>{var xt=require("http"),_t=require("https"),{URL:_e}=require("url"),{version:bt}=V(),be=process.env.CODEV_DEBUG==="True",K=class{constructor(e={}){this.baseUrl=e.baseUrl||"",this.timeout=e.timeout||3e4,this.defaultHeaders={"Content-Type":"application/json","User-Agent":`codev-cli/${bt}`,...e.headers}}setBaseUrl(e){this.baseUrl=e}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}async post(e,t,s={}){let o=this.resolveUrl(e),n={...this.defaultHeaders,...s.headers};return new Promise((i,a)=>{this.validateRequest(o,t,a);let r=this.serializeData(t,a);if(!r)return;n["Content-Length"]=Buffer.byteLength(r);let c=this.buildRequestOptions(o,"POST",n),l=this.getHttpModule(o);be&&console.debug(`HTTP POST to ${o} with data length: ${r.length}`);let h=l.request(c,u=>{this.handleResponse(u,i,a)});this.attachErrorHandlers(h,o,a),h.setTimeout(this.timeout),h.write(r),h.end()})}resolveUrl(e){return e.startsWith("http")?e:`${this.baseUrl}${e.startsWith("/")?"":"/"}${e}`}validateRequest(e,t,s){return!e||typeof e!="string"?(s(new Error(`Invalid URL: ${e}`)),!1):t?!0:(s(new Error("No data provided for HTTP POST")),!1)}serializeData(e,t){try{return typeof e=="string"?e:JSON.stringify(e)}catch(s){return t(new Error(`Failed to serialize data: ${s.message}`)),null}}buildRequestOptions(e,t,s){let o=new _e(e),n=o.protocol==="https:";return{hostname:o.hostname,port:o.port||(n?443:80),path:o.pathname+o.search,method:t,headers:s}}getHttpModule(e){return new _e(e).protocol==="https:"?_t:xt}handleResponse(e,t,s){be&&console.debug(`HTTP response status: ${e.statusCode}`);let o="";e.on("data",n=>{o+=n}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?t({statusCode:e.statusCode,data:o,headers:e.headers}):s(new Error(`HTTP request returned status ${e.statusCode}: ${o}`))})}attachErrorHandlers(e,t,s){e.on("error",o=>{s(new Error(`HTTP POST request failed: ${o.message}`))}),e.on("timeout",()=>{s(new Error(`HTTP POST request timed out for URL: ${t}`)),e.destroy()})}};Ie.exports=K});var Pe=m((gs,$e)=>{var It=require("crypto"),{URL:kt}=require("url"),W=class{static generateSignature(e,t,s,o){try{let n=new kt(e),i=Buffer.from(n.pathname),a=Buffer.from(i),r=t?typeof t=="string"?Buffer.from(t):Buffer.from(JSON.stringify(t)):Buffer.alloc(0),c=Buffer.concat([a,r,Buffer.from(o)]),l=It.createHmac("sha256",s);return l.update(c),l.digest("hex")}catch(n){throw new Error(`Failed to generate signature: ${n.message}`)}}static validateSignature(e,t,s,o,n){return this.generateSignature(e,t,s,o)===n}static generateTimestamp(){return Date.now().toString()}};$e.exports=W});var Te=m((fs,De)=>{var $t=Pe(),z=class{constructor(e={}){this.accessKey=null,this.secretKey=null,this.validateCredentials=e.validateCredentials!==!1}setCredentials(e,t){if(this.validateCredentials&&(!e||!t))throw new Error("Both access key and secret key are required");this.accessKey=e,this.secretKey=t}hasCredentials(){return!!(this.accessKey&&this.secretKey)}generateAuthHeaders(e,t=null){if(!this.hasCredentials())return{};try{return{AUTHORIZATION:`Bearer ${this.accessKey}.${this.secretKey}`}}catch(s){throw new Error(`Failed to generate auth headers: ${s.message}`)}}validateAuthHeaders(e,t,s,o){if(!this.hasCredentials())throw new Error("No credentials available for validation");return $t.validateSignature(e,t,this.secretKey,s,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};De.exports=z});var Oe=m((ms,Ae)=>{var A=process.env.CODEV_DEBUG==="True",j=class{constructor(e={}){this.currentSessionId=null,this.previousSessionId=null,this.onSessionSwitch=e.onSessionSwitch||null,this.terminateSignal=e.terminateSignal||"CODEV_TERMINATE_SIGNAL"}handleSessionSwitch(e){if(!e)return A&&console.warn("Received empty session ID"),!1;let t=this.previousSessionId!==null&&this.previousSessionId!==e;return t&&(A&&console.log(`Session switch detected: ${this.previousSessionId} -> ${e}`),this.onSessionSwitch&&this.onSessionSwitch({type:this.terminateSignal,reason:"User switch session",agent:"claude",previousSessionId:this.previousSessionId,newSessionId:e})),this.previousSessionId=this.currentSessionId,this.currentSessionId=e,t}getCurrentSessionId(){return this.currentSessionId}getPreviousSessionId(){return this.previousSessionId}hasActiveSession(){return!!this.currentSessionId}terminateCurrentSession(e="Session terminated",t=null,s=null){if(!this.hasActiveSession())return A&&console.log("No active session to terminate"),null;let o={type:this.terminateSignal,reason:s?`terminated by signal: ${s}`:e,code:t,signal:s,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId};return A&&console.log("Terminating session:",o),this.previousSessionId=null,this.currentSessionId=null,o}createErrorTermination(e){return this.hasActiveSession()?{type:this.terminateSignal,error:e.message,stack:e.stack,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId}:null}reset(){A&&console.log("Resetting session manager"),this.currentSessionId=null,this.previousSessionId=null}setSessionSwitchCallback(e){this.onSessionSwitch=e}getSessionInfo(){return{currentSessionId:this.currentSessionId,previousSessionId:this.previousSessionId,hasActiveSession:this.hasActiveSession()}}};Ae.exports=j});var Ue=m((ps,qe)=>{var k=require("fs"),P=require("path"),Pt=require("events"),Dt=require("crypto"),w=process.env.CODEV_DEBUG==="True",J=class extends Pt{constructor(e={}){super(),this.watchPaths=e.watchPaths||[],this.excludePatterns=e.excludePatterns||[/node_modules/,/\.git/,/\.DS_Store/,/\.tmp/,/\.log$/,/\.swp$/,/codev\.log/],this.includePatterns=e.includePatterns||[/\.(js|jsx|ts|tsx|py|java|c|cpp|h|hpp|go|rs|rb|php|html|css|scss|sass|less|json|xml|yaml|yml|md|txt)$/],this.watchers=new Map,this.isWatching=!1,this.debounceTimeout=e.debounceTimeout||300,this.pendingChanges=new Map,this.fileContentHashes=new Map,this.enableContentComparison=e.enableContentComparison!==!1,this.onFileChange=e.onFileChange||null}calculateFileHash(e){try{let t=k.readFileSync(e,"utf8");return Dt.createHash("sha256").update(t).digest("hex")}catch{return null}}hasContentChanged(e){if(!this.enableContentComparison)return!0;let t=this.calculateFileHash(e),s=this.fileContentHashes.get(e);return t===null?s!==void 0?(this.fileContentHashes.delete(e),!0):!1:s===void 0||t!==s?(this.fileContentHashes.set(e,t),!0):!1}preloadFileHashes(e){if(!(!this.enableContentComparison||!k.existsSync(e)))try{let t=k.readdirSync(e,{withFileTypes:!0});for(let s of t){let o=P.join(e,s.name);s.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):s.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(t){w&&console.warn(`Failed to preload hashes for ${e}:`,t.message)}}shouldExcludeDirectory(e){let t=e.replace(/\\/g,"/");for(let s of this.excludePatterns)if(s.test(t)||s.test(P.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){w&&console.log("FileWatchService is already watching");return}let t=e||this.watchPaths;if(t.length===0){w&&console.log("No watch paths specified");return}this.isWatching=!0;for(let s of t)this.enableContentComparison&&this.preloadFileHashes(s),this.watchDirectory(s);w&&(console.log(`FileWatchService started watching ${t.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,t]of this.watchers)try{t.close(),w&&console.log(`Stopped watching: ${e}`)}catch(s){w&&console.error(`Error stopping watcher for ${e}:`,s.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),w&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!k.existsSync(e)){w&&console.warn(`Watch path does not exist: ${e}`);return}if(!k.statSync(e).isDirectory()){w&&console.warn(`Watch path is not a directory: ${e}`);return}try{let s=k.watch(e,{recursive:!0,persistent:!1},(o,n)=>{if(!n)return;let i=P.join(e,n);this.handleFileChange(o,i,e)});this.watchers.set(e,s),w&&console.log(`Started watching directory: ${e}`),s.on("error",o=>{w&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(s){w&&console.error(`Failed to start watching ${e}:`,s.message)}}handleFileChange(e,t,s){if(!this.shouldWatchFile(t))return;let o=`${e}:${t}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,t,s)},this.debounceTimeout))}processFileChange(e,t,s){if(!this.isWatching)return;let o="modified",n=!1;try{k.statSync(t),n=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(n&&(o==="modified"||o==="created")&&!this.hasContentChanged(t)){w&&console.log(`Ignoring false change for: ${P.relative(s,t)}`);return}!n&&o==="deleted"&&this.fileContentHashes.delete(t);let i={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:t,relativePath:P.relative(s,t),watchPath:s,fileExists:n,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(w&&console.log(`File ${o}: ${i.data.relativePath}`),this.emit("fileChange",i),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(i)}catch(a){w&&console.error("Error in file change callback:",a.message)}}shouldWatchFile(e){let t=P.basename(e),s=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(s)||o.test(t))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(s)||o.test(t))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let t=this.watchPaths.indexOf(e);if(t>-1&&(this.watchPaths.splice(t,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),w&&console.log(`Removed watch path: ${e}`)}catch(s){w&&console.error(`Error removing watch path ${e}:`,s.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};qe.exports=J});var Me=m((ys,Fe)=>{var Tt=F(),At=require("path"),ws=require("fs"),Ss=require("os"),Ot=xe(),qt=ke(),Ut=Te(),Ft=Oe(),Mt=Ue(),p=process.env.CODEV_DEBUG==="True",Q=class extends Tt{constructor(){super({configDir:".",configFile:".claude.json",defaultModel:"Claude Sonnet 4.5",executablePaths:["cc.mjs","/tmp/claude-code/package/cc.mjs"],environmentVariables:e=>({ANTHROPIC_BASE_URL:`${e}/claude`,ANTHROPIC_API_KEY:"codev",DISABLE_TELEMETRY:!0,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,CODEV_SERVER:e,CLAUDE_CODE_ATTRIBUTION_HEADER:"0"}),defaultConfig:{numStartups:1,installMethod:"unknown",autoUpdates:!1,theme:"Coder Dark",customApiKeyResponses:{approved:["codev"]},shiftEnterKeyBindingInstalled:!0,hasCompletedOnboarding:!0,subscriptionNoticeCount:0,hasAvailableSubscription:!0,projects:{}}}),this.fileWatchService=null,this.shutdownInProgress=!1,this.initializeServices()}initializeServices(){this.httpClient=new qt({timeout:1e4}),this.authService=new Ut({validateCredentials:!1}),this.sessionManager=new Ft({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new Ot({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return At.join(e,this.config.configDir,".claude","settings.json")}initializeFileWatchService(){if(!process.env.SESSION_ID){p&&console.log("FileWatchService disabled: SESSION_ID environment variable not found");return}try{this.fileWatchService=new Mt({watchPaths:this.getFileWatchPaths(),onFileChange:e=>this.handleFileChange(e),debounceTimeout:300}),p&&console.log("FileWatchService initialized with SESSION_ID:",process.env.SESSION_ID)}catch(e){p&&console.error("Failed to initialize FileWatchService:",e.message)}}getFileWatchPaths(){let e=[],t=process.cwd();e.push(t);let s=process.env.CODEV_WATCH_PATHS;if(s){let o=s.split(",").map(n=>n.trim());e.push(...o)}return e}handleFileChange(e){if(p&&console.log("File change detected:",e.data.relativePath),this.shutdownInProgress)return;let t={message:e,sessionId:e.data.sessionId||process.env.SESSION_ID};this.messageQueue.enqueue(t)}startFileWatching(){this.fileWatchService&&!this.fileWatchService.isWatching&&(this.fileWatchService.startWatching(),p&&console.log("File watching started"))}stopFileWatching(){this.fileWatchService&&this.fileWatchService.isWatching&&(this.fileWatchService.stopWatching(),p&&console.log("File watching stopped"))}onChildMessage(e){e&&e.type==="claude:send-msg"&&this.handleClaudeSendMessage(e.data),super.onChildMessage(e)}handleClaudeSendMessage(e){if(p&&console.log("Handling claude:send-msg message:",e),!e||typeof e!="object"){console.error(`handleClaudeSendMessage: Invalid message data. Expected object, got: ${typeof e}`);return}if(this.shutdownInProgress){p&&console.log("Shutdown in progress, ignoring new message");return}let t=e.sessionId||process.env.SESSION_ID;this.sessionManager.handleSessionSwitch(t),this.messageQueue.enqueue(e)}async processMessage(e){let t=e.data.message,s=e.data.sessionId||process.env.SESSION_ID;if(!s)throw new Error("No session ID available");let o;try{o=typeof t=="string"?JSON.parse(t):t}catch(a){throw new Error(`Failed to parse message data: ${a.message}`)}let n=`/conversations/${s}/@append?task_type=codev`,i=this.authService.hasCredentials()?this.authService.generateAuthHeaders(`${this.httpClient.baseUrl}${n}`,o):{};p&&(console.debug("Sending message to:",n),console.debug("Send Message: ",JSON.stringify(o))),e.type!=="CODEV_TERMINATE_SIGNAL"&&(this.sessionManager.currentSessionId=s)}sendTerminationMessage(e){let t={message:e,sessionId:e.sessionId||this.sessionManager.getCurrentSessionId()};this.messageQueue.enqueue(t)}async handleChildProcessExit(e,t){p&&console.log(`Child process exited with code: ${e}, signal: ${t}`),this.stopFileWatching();let s=this.messageQueue.getQueueSize(),o=this.sessionManager.terminateCurrentSession("process exited normally",e,t);if(o&&this.sendTerminationMessage(o),s>0||o){p&&console.log("Starting graceful shutdown of message queue...");try{let n=!t||t==="SIGTERM",i=this.messageQueue.getQueueSize(),a={timeoutMs:n?8e3:3e3,batchSize:Math.min(i,15),fastMode:!n||i>30};p&&console.log("Shutdown options:",a);let r=await this.messageQueue.gracefulShutdown(a);p&&console.log("Message queue shutdown completed:",r),r.failedMessages>0&&p&&console.warn(`Shutdown summary: ${r.processedMessages} sent, ${r.failedMessages} failed, ${r.remainingMessages} remaining`)}catch(n){p&&console.error("Error during message queue shutdown:",n.message)}}}handleChildProcessError(e){p&&console.error(`Child process error: ${e.message}`);let t=this.sessionManager.createErrorTermination(e);t&&this.sendTerminationMessage(t)}async forceFlushMessages(e=3e3){if(this.messageQueue.getQueueSize()===0)return{success:!0,message:"No messages to flush"};p&&console.log(`Force flushing ${this.messageQueue.getQueueSize()} messages...`);try{return await this.messageQueue.forceFlushAndShutdown(e)}catch(t){return p&&console.error("Force flush failed:",t.message),{success:!1,error:t.message}}}async launch(e={}){let{codevServer:t,auth_ak:s=null,auth_sk:o=null}=e;return this.httpClient.setBaseUrl(t),s&&o&&this.authService.setCredentials(s,o),this.startFileWatching(),super.launch(e)}};Fe.exports=Q});var Le=m((Es,Be)=>{var Bt=F(),Cs=require("path"),Y=class extends Bt{constructor(){super({configDir:".gemini",configFile:"settings.json",defaultModel:"gemini-2.5-pro",executablePaths:["gemini/gemini.js","../dist/gemini/gemini.js"],environmentVariables:e=>({GOOGLE_GEMINI_BASE_URL:`${e}/gemini`,GEMINI_API_KEY:"coder",GOOGLE_API_KEY:"coder",GOOGLE_CLOUD_PROJECT:"coder",GOOGLE_CLOUD_LOCATION:"coder",DISABLE_TELEMETRY:!0,GEMINI_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,USE_VERTEX:!0}),defaultConfig:{ide:{hasSeenNudge:!0},telemetry:{enabled:!1,logPrompts:!1},privacy:{usageStatisticsEnabled:!1},general:{disableUpdateNag:!0,preferredEditor:"vscode",previewFeatures:!0},ui:{hideBanner:!0,theme:"Default"},security:{auth:{selectedType:"vertex-ai"}}}})}};Be.exports=Y});var Ne=m((vs,Re)=>{var Lt=F(),O=require("path"),x=require("fs"),Rt=require("os"),{spawn:Nt}=require("child_process"),M=process.env.CODEV_DEBUG==="True",Z=class extends Lt{constructor(){super({configDir:".codex",configFile:"config.toml",defaultModel:"o4-mini",executablePaths:["codex.mjs","../dist/codex.mjs"],environmentVariables:e=>({OPENAI_BASE_URL:`${e}/codex`,OPENAI_API_KEY:"codev-proxy-key",DEBUG:M?"true":"false",CODEX_QUIET_MODE:"0",OPENAI_DISABLE_TELEMETRY:"true",CODEX_DISABLE_PROJECT_DOC:"0",CODEV_SERVER:e}),defaultConfig:{model:"gpt-5-codex",approvalMode:"suggest",fullAutoErrorMode:"ask-user",notify:[],history:{maxSize:1e3,saveHistory:!0,sensitivePatterns:[],persistence:"save-all"}}})}checkCodexAvailability(){try{let e=this.findExecutablePath();return x.existsSync(e)}catch{return!1}}resloveSettingFilePath(e){return O.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,t=0){let s=O.join(Rt.homedir(),this.config.configDir,this.config.configFile),o=O.dirname(s);try{x.existsSync(o)||x.mkdirSync(o,{recursive:!0});let n=`${e}/codex`;if(x.existsSync(s)){let i=x.readFileSync(s,"utf8"),a=`openai_base_url = "${n}"`;/^openai_base_url\s*=/m.test(i)?i=i.replace(/^openai_base_url\s*=.*/m,a):i=i.trimEnd()+`
190
+ `)}};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(`
191
+ Terminating ...`),g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
192
+ 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 A=f((Us,Xe)=>{Xe.exports={name:"makecoder",version:"2.0.75",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}=A(),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"),V=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=V});var ye=f((Vs,Se)=>{var rs=pe(),G=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=G});var Ce=f((Gs,we)=>{var _=process.env.CODEV_DEBUG==="True",R=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()}}};we.exports=R});var ve=f((Rs,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 _e=f((js,Ie)=>{var ms=$(),Ws=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((zs,ke)=>{var ps=$(),k=require("path"),w=require("fs"),Ss=require("os"),{spawn:ys}=require("child_process"),T=process.env.CODEV_DEBUG==="True",W=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:T?"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 k.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,s=0){let t=k.join(Ss.homedir(),this.config.configDir,this.config.configFile),o=k.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()+`
203
193
  `+a+`
204
- `,x.writeFileSync(s,i),M&&console.log(`Updated openai_base_url in ${s}`)}else{let i=this.config.defaultConfig||{},a=this.generateTOMLConfig(i,n);x.writeFileSync(s,a),M&&console.log(`Created Codex config file: ${s}`)}t>0&&await new Promise(i=>setTimeout(i,t))}catch(n){console.warn(`Failed to update ${this.config.configFile}: ${n.message}`)}}generateTOMLConfig(e,t){return`model = "${e.model||"gpt-5-codex"}"
205
- openai_base_url = "${t}"
206
- `}findExecutablePath(){let e=O.dirname(require.main.filename);for(let t of this.config.executablePaths){let s=O.resolve(e,t);if(x.existsSync(s))return s}throw new Error(`Could not find Codex executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}async launch(e={}){let{remainingArgs:t=[],codevServer:s,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(s,1e3);let i=this.findExecutablePath();return M&&console.log(`executablePath: ${i}`),new Promise((a,r)=>{let c={...process.env,...this.config.environmentVariables(s)};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(i,...t);let h=Nt("node",l,{env:c,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(h),h.on("error",u=>{console.error(`Failed to start Codex: ${u.message}`),r(u)}),h.on("exit",async(u,g)=>{console.log(g?`terminated by signal: ${g}`:"Goodbye for now! Keep building great things!")}),process.on("SIGINT",async()=>{console.log(`
194
+ `,w.writeFileSync(t,r),T&&console.log(`Updated openai_base_url in ${t}`)}else{let r=this.config.defaultConfig||{},a=this.generateTOMLConfig(r,n);w.writeFileSync(t,a),T&&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"}"
195
+ openai_base_url = "${s}"
196
+ `}findExecutablePath(){let e=k.dirname(require.main.filename);for(let s of this.config.executablePaths){let t=k.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 T&&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(`
207
197
  Terminating ...`),h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
208
- Terminating ...`),h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},8e3)})})}catch(i){throw i}}};Re.exports=Z});var Ke=m((xs,Ve)=>{var q=require("fs"),He=require("path"),{spawn:Ge}=require("child_process"),X=class{constructor(){this.extensionId="codev.codev-background";let e=require.main?He.dirname(require.main.filename):__dirname;this.extensionPath=He.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(q.existsSync(e))try{return q.accessSync(e,q.constants.F_OK|q.constants.X_OK),this._codeCommand=e,process.env.CODEV_DEBUG&&console.log(`Using AI Studio VSCode path: ${e}`),this._codeCommand}catch(t){process.env.CODEV_DEBUG&&console.log(`AI Studio path exists but not executable: ${t.message}`)}else process.env.CODEV_DEBUG&&console.log(`AI Studio path not found: ${e}`)}try{let{spawn:e}=require("child_process");return new Promise(t=>{let s=e("which",["code"],{stdio:["ignore","pipe","ignore"]}),o="";s.stdout.on("data",n=>{o+=n.toString().trim()}),s.on("close",n=>{n===0&&o?(this._codeCommand=o,process.env.CODEV_DEBUG&&console.log(`Resolved code command path: ${o}`),t(this._codeCommand)):(this._codeCommand="code",t(this._codeCommand))}),s.on("error",()=>{this._codeCommand="code",t(this._codeCommand)}),setTimeout(()=>{s.kill(),this._codeCommand="code",t(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):!!q.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"],t=await this.executeVSCodeCommand(e,{timeout:1e4});if(process.env.CODEV_DEBUG&&(console.log(`VSCode availability check (${e.join(" ")}): ${t?"available":"unavailable"}`),process.env.IS_AISTUDIO==="True")){let{spawn:s}=require("child_process");try{s("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 t}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(t=>{try{let s={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=Ge(e,["--list-extensions"],s),n="";o.stdout.on("data",i=>{n+=i.toString()}),o.on("close",i=>{if(i===0){let a=n.split(`
209
- `).map(r=>r.trim());t(a.includes(this.extensionId))}else t(!1)}),o.on("error",i=>{process.env.CODEV_DEBUG&&(console.error("VSCode list extensions error:",i.message),console.error("Error code:",i.code),console.error("Error errno:",i.errno),console.error("Error syscall:",i.syscall)),t(!1)}),setTimeout(()=>{try{o.kill()}catch{}t(!1)},1e4)}catch(s){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode list extensions:",s.message),t(!1)}})}catch{return!1}}async executeVSCodeCommand(e,t={}){let s=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: ${s} ${e.join(" ")}`);let i=Ge(s,e,n);i.on("close",r=>{o(r===0)}),i.on("error",r=>{process.env.CODEV_DEBUG&&(console.error("VSCode command error:",r.message),console.error("Error code:",r.code),console.error("Error errno:",r.errno),console.error("Error syscall:",r.syscall)),o(!1)});let a=t.timeout||3e4;setTimeout(()=>{try{i.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)}}};Ve.exports=X});var je=m((_s,ze)=>{var E=require("fs"),$=require("path"),Ht=require("readline"),{execSync:B}=require("child_process"),We=require("os"),ee=class{constructor(){this.serverUrl="https://makecoder.com/bigapis/codev/v1/coderpub"}getClaudeJsonlPath(e,t=!1){let s=e.replace(/[/_]/g,"-"),o=$.join(We.homedir(),".claude","projects",s);if(t&&(console.log(`
210
- \u{1F4C2} [allow-clone] \u67E5\u627E JSONL \u6587\u4EF6...`),console.log(` \u9879\u76EE\u76EE\u5F55: ${e}`),console.log(` Claude \u9879\u76EE\u540D: ${s}`),console.log(` Claude \u9879\u76EE\u76EE\u5F55: ${o}`)),!E.existsSync(o))return t&&console.log(" \u274C Claude \u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728"),null;t&&console.log(" \u2713 Claude \u9879\u76EE\u76EE\u5F55\u5B58\u5728");try{let n=E.readdirSync(o).filter(i=>i.endsWith(".jsonl")).map(i=>({name:i,path:$.join(o,i),mtime:E.statSync($.join(o,i)).mtime,size:E.statSync($.join(o,i)).size})).sort((i,a)=>a.mtime-i.mtime);return t&&(console.log(` \u627E\u5230 ${n.length} \u4E2A JSONL \u6587\u4EF6:`),n.forEach((i,a)=>{let r=(i.size/1024).toFixed(2),c=i.mtime.toLocaleString(),l=a===0?" <- \u6700\u65B0":"";console.log(` ${a+1}. ${i.name} (${r} KB, ${c})${l}`)})),n.length>0?(t&&console.log(` \u2713 \u9009\u62E9\u6700\u65B0\u6587\u4EF6: ${n[0].name}`),n[0].path):(t&&console.log(" \u274C \u76EE\u5F55\u4E2D\u6CA1\u6709 JSONL \u6587\u4EF6"),null)}catch(n){return t&&console.log(` \u274C \u8BFB\u53D6\u76EE\u5F55\u5931\u8D25: ${n.message}`),null}}async promptForName(){let e=Ht.createInterface({input:process.stdin,output:process.stdout});return new Promise((t,s)=>{e.question("\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0 (name): ",o=>{e.close();let n=o.trim();if(!n){s(new Error("\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A"));return}if(!/^[a-zA-Z0-9_-]+$/.test(n)){s(new Error("\u9879\u76EE\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26"));return}t(n)})})}async createZip(e,t={}){let{allowClone:s=!1}=t,o=We.tmpdir(),n=`coder-pub-${Date.now()}.zip`,i=$.join(o,n);try{let a=!1;if(E.existsSync($.join(e,".git")))try{B(`git archive -o "${i}" 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(" ");B(`zip -r "${i}" . ${c}`,{cwd:e,stdio:"pipe"}),console.log("\u{1F4E6} \u5DF2\u521B\u5EFA\u538B\u7F29\u5305")}if(s){console.log(`
211
- \u{1F504} [allow-clone] \u5F00\u59CB\u5904\u7406 AI \u751F\u6210\u8BB0\u5F55...`);let r=this.getClaudeJsonlPath(e,!0);if(r){let c=$.join(o,"coder.pub.jsonl"),h=(E.statSync(r).size/1024).toFixed(2);console.log(`
212
- \u{1F4E6} [allow-clone] \u6253\u5305 JSONL \u6587\u4EF6...`),console.log(` \u6E90\u6587\u4EF6: ${r}`),console.log(` \u6587\u4EF6\u5927\u5C0F: ${h} KB`),console.log(` \u4E34\u65F6\u6587\u4EF6: ${c}`),E.copyFileSync(r,c),console.log(" \u2713 \u5DF2\u590D\u5236\u5230\u4E34\u65F6\u76EE\u5F55"),console.log(` \u76EE\u6807 ZIP: ${i}`),console.log(" \u76EE\u6807\u6587\u4EF6\u540D: coder.pub.jsonl"),B(`zip -j "${i}" "${c}"`,{stdio:"pipe"}),console.log(" \u2713 \u5DF2\u6DFB\u52A0\u5230 ZIP \u5305"),E.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)
198
+ Terminating ...`),h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},8e3)})})}catch(r){throw r}}};ke.exports=W});var Te=f((Js,Ae)=>{var D=require("fs"),Pe=require("path"),{spawn:$e}=require("child_process"),j=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(`
199
+ `).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)}}};Ae.exports=j});var Me=f((Qs,Fe)=>{var y=require("fs"),x=require("path"),ws=require("readline"),{execSync:O}=require("child_process"),Oe=require("os"),z=class{constructor(){this.serverUrl="https://makecoder.com/bigapis/codev/v1/coderpub"}getClaudeJsonlPath(e,s=!1){let t=e.replace(/[/_]/g,"-"),o=x.join(Oe.homedir(),".claude","projects",t);if(s&&(console.log(`
200
+ \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=Oe.tmpdir(),n=`coder-pub-${Date.now()}.zip`,r=x.join(o,n);try{let a=!1;if(y.existsSync(x.join(e,".git")))try{O(`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(" ");O(`zip -r "${r}" . ${c}`,{cwd:e,stdio:"pipe"}),console.log("\u{1F4E6} \u5DF2\u521B\u5EFA\u538B\u7F29\u5305")}if(t){console.log(`
201
+ \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(`
202
+ \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"),O(`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)
213
203
  `)}else console.log(`\u26A0\uFE0F [allow-clone] \u672A\u627E\u5230 Claude Code \u751F\u6210\u8BB0\u5F55
214
- `)}return i}catch(a){throw new Error(`\u521B\u5EFA\u538B\u7F29\u5305\u5931\u8D25: ${a.message}`)}}async upload(e,t,s,o,n,i=!1){let a=n?`${n}/coderpub`:this.serverUrl,r=`${s}.${o}`;console.log("\u{1F4E4} \u6B63\u5728\u4E0A\u4F20\u5230\u670D\u52A1\u5668..."),i&&(console.log(` \u670D\u52A1\u5668\u5730\u5740: ${a}`),console.log(` \u9879\u76EE\u540D\u79F0: ${t}`),console.log(` ZIP \u6587\u4EF6: ${e}`));try{let c=`curl -s -X POST "${a}" -H "Authorization: Bearer ${r}" -F "name=${t}" -F "zip_file=@${e}"`;i&&console.log(" \u6267\u884C\u4E0A\u4F20\u547D\u4EE4...");let l=B(c,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return i&&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{E.existsSync(e)&&E.unlinkSync(e)}catch{}}async publish(e){let{ak:t,sk:s,serverBaseUrl:o,allowClone:n}=e,{name:i}=e,a=null;try{i||(i=await this.promptForName()),console.log(`
215
- \u{1F680} \u6B63\u5728\u53D1\u5E03\u9879\u76EE: ${i}`),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=(E.statSync(a).size/(1024*1024)).toFixed(2);console.log(`\u{1F4CA} \u538B\u7F29\u5305\u5927\u5C0F: ${c} MB`),n&&console.log(`
216
- \u{1F310} [allow-clone] \u5F00\u59CB\u4E0A\u4F20\u5230\u670D\u52A1\u5668...`);let l=await this.upload(a,i,t,s,o,n);return l.code===0?(console.log(`
217
- \u2705 \u53D1\u5E03\u6210\u529F!`),console.log(`\u{1F4CC} \u7248\u672C: ${l.data.version}`),console.log(`\u{1F310} \u8BBF\u95EE\u5730\u5740: https://${i}.coder.pub/`),0):(console.error(`
218
- \u274C \u53D1\u5E03\u5931\u8D25: ${l.message||l.reason}`),1)}catch(r){return console.error(`
219
- \u274C ${r.message}`),1}finally{a&&this.cleanup(a)}}};ze.exports=ee});var st=m((bs,tt)=>{var{EventEmitter:se}=require("events"),{Transform:Je,Duplex:Gt}=require("stream"),{URL:Qe}=require("url"),Ye=require("crypto"),Ze=require("http"),Xe=require("https"),Vt=require("net"),Kt=require("tls"),te=require("fs"),et="https://tunnel.makecoder.com",oe=class extends Gt{constructor(e){super(),this._socket=e,this._readBuffer=Buffer.alloc(0),this._ended=!1,e.on("data",s=>{this.destroyed||(this._readBuffer=Buffer.concat([this._readBuffer,s]),this._processFrames())});let t=()=>{this._ended||(this._ended=!0,this.destroyed||this.push(null)),this.destroyed||this.destroy()};e.on("close",t),e.on("end",t),e.on("error",s=>{this.destroyed||this.destroy(s)})}_processFrames(){for(;this._readBuffer.length>=2&&!this.destroyed;){let e=this._readBuffer[0],t=this._readBuffer[1],s=(t&128)!==0,o=t&127,n=2;if(o===126){if(this._readBuffer.length<4)return;o=this._readBuffer.readUInt16BE(2),n=4}else if(o===127){if(this._readBuffer.length<10)return;o=this._readBuffer.readUInt32BE(6),n=10}s&&(n+=4);let i=n+o;if(this._readBuffer.length<i)return;let a=e&15,r=Buffer.from(this._readBuffer.slice(n,i));if(s){let c=this._readBuffer.slice(n-4,n);for(let l=0;l<r.length;l++)r[l]^=c[l%4]}if(this._readBuffer=this._readBuffer.slice(i),a===8){this._sendFrame(8,Buffer.alloc(0)),this._ended||(this._ended=!0,this.destroyed||this.push(null)),this.destroyed||this.destroy();return}else if(a===9)this._sendFrame(10,r);else if(a!==10){if((a===1||a===2)&&!this.push(r))return}}}_sendFrame(e,t){if(!(this.destroyed||this._socket.destroyed))try{let s=Ye.randomBytes(4),o=t.length,n;o<126?(n=Buffer.alloc(6),n[0]=128|e,n[1]=128|o,s.copy(n,2)):o<65536?(n=Buffer.alloc(8),n[0]=128|e,n[1]=254,n.writeUInt16BE(o,2),s.copy(n,4)):(n=Buffer.alloc(14),n[0]=128|e,n[1]=255,n.writeUInt32BE(0,2),n.writeUInt32BE(o,6),s.copy(n,10));let i=Buffer.alloc(o);for(let a=0;a<o;a++)i[a]=t[a]^s[a%4];this._socket.write(Buffer.concat([n,i]))}catch{}}_write(e,t,s){if(this.destroyed)return s();try{this._sendFrame(2,e)}catch{}s()}_read(){}end(...e){!this.destroyed&&!this._socket.destroyed&&this._sendFrame(8,Buffer.alloc(0)),super.end(...e)}destroy(e){this.destroyed||(this._socket.destroyed||this._socket.destroy(),super.destroy(e))}};function Wt(d,e={}){return new Promise((t,s)=>{let o=new Qe(d),n=o.protocol==="wss:",i=n?Xe:Ze,a=o.port||(n?443:80),r=Ye.randomBytes(16).toString("base64"),c=i.request({hostname:o.hostname,port:a,path:o.pathname+o.search,method:"GET",headers:{...e,Connection:"Upgrade",Upgrade:"websocket","Sec-WebSocket-Key":r,"Sec-WebSocket-Version":"13"}});c.on("upgrade",(l,h,u)=>{let g=new oe(h);u&&u.length>0&&(g._readBuffer=Buffer.concat([g._readBuffer,u]),g._processFrames()),t(g)}),c.on("response",l=>{let h="";l.on("data",u=>h+=u),l.on("end",()=>{s(new Error(`WebSocket upgrade failed (${l.statusCode}): ${h||l.statusMessage}`))})}),c.on("error",s),c.setTimeout(1e4,()=>{c.destroy(new Error("WebSocket connection timeout"))}),c.end()})}var ne=class extends Je{constructor(e={}){super(e),this.host=e.host||"localhost",this.replaced=!1}_transform(e,t,s){s(null,this.replaced?e:e.toString().replace(/(\r\n[Hh]ost: )\S+/,(o,n)=>(this.replaced=!0,n+this.host)))}},re=class extends Je{constructor(e={}){super(e),this.allowedPaths=e.allowedPaths||[],this.remote=e.remote,this.checked=!1}_transform(e,t,s){if(!this.checked){this.checked=!0;let o=e.toString().match(/^(\w+) (\S+)/);if(o){let n=o[2].split("?")[0];if(!this.allowedPaths.some(a=>n===a||n.startsWith(a+"/"))){let a="Forbidden",r=`HTTP/1.1 403 Forbidden\r
220
- Content-Length: ${a.length}\r
221
- Connection: close\r
222
- \r
223
- `+a;this.remote.write(r),this.remote.end(),s();return}}}s(null,e)}},ie=class extends se{constructor(e={}){super(e),this.opts=e,this.destroyed=!1}destroy(){this.destroyed=!0,this.removeAllListeners()}_safeEmit(e,...t){this.destroyed||this.emit(e,...t)}open(){if(this.destroyed)return;let e=this.opts,t=e.ws_url,s=e.local_host||"localhost",o=e.local_port,n=e.allow_invalid_cert,i={};e.authorization&&(i.AUTHORIZATION=e.authorization);let a=this._safeEmit.bind(this);Wt(t,i).then(r=>{if(this.destroyed){r.destroy();return}r.on("error",l=>{a("error",new Error(`remote error: ${l.message||l.code||l}`)),r.end()}),r.on("data",l=>{let h=l.toString().match(/^(\w+) (\S+)/);h&&a("request",{method:h[1],path:h[2]})}),a("open",r);let c=()=>{if(this.destroyed||r.destroyed){a("dead");return}r.pause();let l=()=>n?{rejectUnauthorized:!1}:{cert:te.readFileSync(e.local_cert),key:te.readFileSync(e.local_key),ca:e.local_ca?[te.readFileSync(e.local_ca)]:void 0},h=e.local_https?Kt.connect({host:s,port:o,...l()}):Vt.connect({host:s,port:o}),u=()=>{a("dead"),h.end()};r.once("close",u),h.on("error",g=>{if(a("info",`local connection error: ${g.message||g.code||g} (${s}:${o})`),h.end(),r.removeListener("close",u),g.code!=="ECONNREFUSED"&&g.code!=="ECONNRESET")return r.end();setTimeout(c,1e3)}),h.once("connect",()=>{r.resume();let g=r,S=()=>{};if(e.local_host){let y=new ne({host:e.local_host});y.on("error",S),g=g.pipe(y)}if(e.allowed_paths&&e.allowed_paths.length>0){let y=new re({allowedPaths:e.allowed_paths,remote:r});y.on("error",S),g=g.pipe(y)}g.pipe(h).pipe(r)})};c()}).catch(r=>{a("error",new Error(`WebSocket connect failed: ${r.message||r}`)),a("dead")})}},ae=class extends se{constructor(e={}){super(e),this.opts=e,this.closed=!1,this.opts.host||(this.opts.host=et)}_getInfo(e){let{id:t,url:s,cached_url:o,max_conn_count:n,token:i}=e,{host:a,port:r,local_host:c}=this.opts,{local_https:l,local_cert:h,local_key:u,local_ca:g,allow_invalid_cert:S,allowed_paths:y,authorization:_}=this.opts,D=new Qe(a),C=`${D.protocol==="https:"?"wss:":"ws:"}//${D.host}/tunnel/${t}${i?`?token=${i}`:""}`;return{name:t,url:s,cached_url:o,max_conn:n||1,ws_url:C,authorization:_,local_port:r,local_host:c,local_https:l,local_cert:h,local_key:u,local_ca:g,allow_invalid_cert:S,allowed_paths:y}}_init(e){let t=this.opts,s=this._getInfo.bind(this),o=`${t.host}/`,n=t.subdomain,i=o+(n||"?new"),a=()=>{let r=i.startsWith("https")?Xe:Ze,c={headers:{}};t.authorization&&(c.headers.AUTHORIZATION=t.authorization),r.get(i,c,l=>{let h="";l.on("data",u=>{h+=u}),l.on("end",()=>{if(l.statusCode!==200){let u=`tunnel server error (${l.statusCode})`;try{let g=JSON.parse(h);g&&g.message?u+=`: ${g.message}`:u+=`: ${h}`}catch{h&&(u+=`: ${h}`)}return e(new Error(u))}try{let u=JSON.parse(h);e(null,s(u))}catch(u){e(new Error(`Invalid response from tunnel server: ${u.message}`))}})}).on("error",l=>{console.error(`\u26A0\uFE0F tunnel server unreachable: ${l.message||l.code||l}, retrying in 1s...`),setTimeout(a,1e3)})};a()}_establish(e){this.setMaxListeners(e.max_conn+(se.defaultMaxListeners||10)),this.tunnelCluster=new ie(e),this.tunnelCluster.once("open",()=>{this.emit("url",e.url)}),this.tunnelCluster.on("info",n=>{this.emit("info",n)});let t=0,s=!1,o=1e3;this.tunnelCluster.on("error",n=>{let i=n.message||"";if(i.includes("(403)")){this.emit("error",n),this.close();return}if(i.includes("WebSocket upgrade failed")&&!s){s=!0,this._reconnect();return}o=Math.min(o*1.5,3e4),this.emit("error",n)}),this.tunnelCluster.on("open",n=>{t++,o=1e3;let i=()=>{n.destroy()};if(this.closed)return i();this.once("close",i),n.once("close",()=>{this.removeListener("close",i)})}),this.tunnelCluster.on("dead",()=>{t--,!(this.closed||s)&&setTimeout(()=>{this.closed||s||this.tunnelCluster&&!this.tunnelCluster.destroyed&&this.tunnelCluster.open()},o)}),this.tunnelCluster.on("request",n=>{this.emit("request",n)});for(let n=0;n<e.max_conn;++n)this.tunnelCluster.open()}_reconnect(){if(this.closed)return;this.tunnelCluster&&(this.tunnelCluster.destroy(),this.tunnelCluster=null);let e=3e3,t=()=>{this.closed||(this.emit("info","re-registering with tunnel server..."),this._init((s,o)=>{if(s){this.emit("error",new Error(`re-registration failed: ${s.message}`)),e=Math.min(e*1.5,3e4),this.emit("info",`retrying in ${(e/1e3).toFixed(0)}s...`),setTimeout(t,e);return}this.clientId=o.name;let n=this.url;this.url=o.url,o.cached_url&&(this.cachedUrl=o.cached_url),this.url!==n&&this.emit("error",new Error(`tunnel URL changed: ${n} -> ${this.url}`)),this._establish(o),this.tunnelCluster.once("open",()=>{this.emit("reconnected",this.url)})}))};this.emit("error",new Error("lost connection to tunnel server, reconnecting...")),setTimeout(t,e)}open(e){this._init((t,s)=>{if(t)return e(t);this.clientId=s.name,this.url=s.url,s.cached_url&&(this.cachedUrl=s.cached_url),this._establish(s),e()})}close(){this.closed=!0,this.emit("close")}},ce=class{constructor(){this.tunnel=null}async start(e){process.on("uncaughtException",u=>{let g=new Date().toLocaleTimeString();console.error(` ${g} \u26A0\uFE0F uncaught: ${u&&u.stack?u.stack:u}`)}),process.on("unhandledRejection",u=>{let g=new Date().toLocaleTimeString();console.error(` ${g} \u26A0\uFE0F unhandled rejection: ${u&&u.stack?u.stack:u}`)}),process.on("exit",u=>{console.error(`
224
- \u26A0\uFE0F process exiting (code=${u})`)}),this._keepalive=setInterval(()=>{},6e4);let{port:t,name:s,localHost:o,allowedPaths:n,printRequests:i,ak:a,sk:r}=e,c=e.host||et;console.log(`
225
- \u{1F687} Starting tunnel...`),console.log(` Local: localhost:${t}`),console.log(` Server: ${c}`),n&&n.length>0&&console.log(` Paths: ${n.join(", ")}`),console.log();let l={port:t,host:c,local_host:o,allowed_paths:n&&n.length>0?n:null,authorization:a&&r?`Bearer ${a}.${r}`:null};s&&(l.subdomain=s);let h=new ae(l);return new Promise((u,g)=>{h.open(S=>{if(S){console.error(`\u274C Failed to establish tunnel: ${S.message}`),g(S);return}this.tunnel=h,console.log(`\u2705 Tunnel established!
226
- `),console.log(` \u{1F310} Public URL: \x1B[36m\x1B[1m${h.url}\x1B[0m
227
- `),h.cachedUrl&&console.log(` \u{1F4E6} Cached URL: ${h.cachedUrl}
228
- `),console.log(` Press \x1B[1mCtrl+C\x1B[0m to close the tunnel.
229
- `),i&&h.on("request",v=>{let C=new Date().toLocaleTimeString();console.log(` ${C} ${v.method} ${v.path}`)});let y="",_=0;h.on("error",v=>{let C=v.message;if(C===y){_++;return}if(_>0){let it=new Date().toLocaleTimeString();console.error(` ${it} \u26A0\uFE0F (repeated ${_} more times)`)}y=C,_=0;let rt=new Date().toLocaleTimeString();console.error(` ${rt} \u26A0\uFE0F ${C}`)}),h.on("info",v=>{if(process.env.CODEV_DEBUG){let C=new Date().toLocaleTimeString();console.log(` ${C} \u2139\uFE0F ${v}`)}}),h.on("close",()=>{console.error(`
230
- \u274C Tunnel closed.`),clearInterval(this._keepalive),process.exit(1)}),h.on("reconnected",v=>{let C=new Date().toLocaleTimeString();console.log(`
231
- ${C} \u2705 Tunnel reconnected!`),console.log(` \u{1F310} Public URL: \x1B[36m\x1B[1m${v}\x1B[0m
232
- `),y="",_=0});let D=()=>{console.log(`
233
-
234
- \u{1F50C} Closing tunnel...`),clearInterval(this._keepalive),h.close(),process.exit(0)};process.on("SIGINT",D),process.on("SIGTERM",D),u()})})}};tt.exports=ce});var nt=m((Is,ot)=>{var zt=we(),jt=Me(),Jt=Le(),Qt=Ne(),Yt=Ke(),Zt=je(),Xt=st(),{isPrintMode:es}=U(),le=class{constructor(){this.argParser=new zt,this.claudeLauncher=new jt,this.geminiLauncher=new Jt,this.codexLauncher=new Qt,this.vscodeExtensionService=new Yt,this.publishService=new Zt,this.tunnelService=new Xt}async run(e=process.argv.slice(2)){try{try{await this.vscodeExtensionService.ensureExtensionInstalled()}catch(s){process.env.CODEV_DEBUG&&console.error("VSCode Extension Service Error:",s)}if(!e.includes("--agent")&&!e.includes("-a")){let s=e.length>0&&["claude","gemini","codex"].includes(e[0]),o=e.length>0&&["pub","tunnel"].includes(e[0]);if(!s&&!o&&(e.includes("--help")||e.includes("-h")))return this.argParser.showHelp(),0;if(!s&&!o&&(e.includes("--version")||e.includes("-v")))return this.showVersion(),0}let t=await this.argParser.parse(e);return t.command==="login"?await this.handleLogin(t):t.command==="pub"?await this.publishService.publish({name:t.pubName,ak:t.auth_ak,sk:t.auth_sk,serverBaseUrl:t.codevServer,allowClone:t.allowClone}):t.command==="tunnel"?t.tunnelHelp?(this.showTunnelHelp(),0):(await this.tunnelService.start({...t.tunnelArgs,ak:t.auth_ak,sk:t.auth_sk}),await new Promise(()=>{})):await this.launchAgent(t)}catch(t){return console.error(`Error: ${t.message}`),process.env.CODEV_DEBUG&&console.error("Stack trace:",t.stack),1}}async launchAgent(e){let{agent:t,remainingArgs:s}=e;return es(s)||console.log(`cwd:\x1B[90m\x1B[3m ${process.cwd()} \x1B[0m`),t==="claude"?await this.claudeLauncher.launch(e):t==="gemini"?await this.geminiLauncher.launch(e):t==="codex"?await this.codexLauncher.launch(e):1}async handleLogin(e){let t=e.auth_ak,s=e.auth_sk;if(!t||!s){console.log(`
204
+ `)}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=O(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(`
205
+ \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(`
206
+ \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(`
207
+ \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(`
208
+ \u274C \u53D1\u5E03\u5931\u8D25: ${l.message||l.reason}`),1)}catch(i){return console.error(`
209
+ \u274C ${i.message}`),1}finally{a&&this.cleanup(a)}}};Fe.exports=z});var Ue=f((Ys,qe)=>{var Cs=ne(),Es=be(),vs=_e(),xs=De(),bs=Te(),Is=Me(),{isPrintMode:_s}=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"].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==="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 _s(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(`
235
210
  \u{1F511} \u8BF7\u5148\u5728 MakeCoder \u521B\u5EFA API Key\uFF1A`),console.log(` \u{1F449} https://makecoder.com/my/apikeys
236
- `);try{let n=await this.argParser.promptForAKSK();t=n.ak,s=n.sk}catch(n){return console.error(`\u274C ${n.message}`),1}}if(this.argParser.saveAuthToConfig(t,s))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}showVersion(){let e=V();console.log(`coder version: ${e.version}`)}showTunnelHelp(){console.log(`
237
- Coder Tunnel - Expose a local port via tunnel
238
-
239
- USAGE:
240
- coder tunnel --port <port> [options]
241
-
242
- OPTIONS:
243
- --port, -p <port> Local port to expose (required)
244
- --name, -n <name> Service name (server assigns subdomain as <userid>-<name>)
245
- --path <path> Allow only this URL path (can repeat, others get 403)
246
- --host <url> Tunnel server URL (default: https://tunnel.makecoder.com)
247
- --local-host <host> Tunnel traffic to this host instead of localhost
248
- --print-requests Print incoming request info
249
- --help, -h Show this help message
250
-
251
- EXAMPLES:
252
- coder tunnel --port 18789 # Expose port 18789
253
- coder tunnel --port 3000 --name myapp # Use service name
254
- coder tunnel --port 18789 --path /claw/wecom # Only allow /claw/wecom
255
- coder tunnel --port 18789 --path /a --path /b # Allow multiple paths
256
- `)}async shutdown(){console.log(`
257
- Shutting down...`),process.exit(0)}};ot.exports=le});var ts=nt(),{isPrintMode:ss}=U();process.on("unhandledRejection",(d,e)=>{console.error("Unhandled Promise Rejection:",d),process.exit(1)});process.on("uncaughtException",d=>{console.error("Uncaught Exception:",d.message),process.env.CODEV_DEBUG&&console.error(d.stack),process.exit(1)});async function os(){ss()||console.log(`Welcome to Coder!
258
- `);let d=new ts;process.on("SIGINT",async()=>{console.log(`
259
- Received SIGINT, shutting down gracefully...`),await d.shutdown()}),process.on("SIGTERM",async()=>{console.log(`
260
- Received SIGTERM, shutting down gracefully...`),await d.shutdown()});try{let e=await d.run();process.exit(e)}catch(e){console.error(`Fatal error: ${e.message}`),process.env.CODEV_DEBUG&&console.error(e.stack),process.exit(1)}}os().catch(d=>{console.error(`Startup error: ${d.message}`),process.exit(1)});
211
+ `);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...
212
+ `);try{return e("npm install -g makecoder@latest",{stdio:"inherit"}),console.log(`
213
+ \u2705 \u5347\u7EA7\u6210\u529F`),0}catch(t){return console.error(`
214
+ \u274C \u5347\u7EA7\u5931\u8D25:`,t.message),1}}showVersion(){let e=A();console.log(`coder version: ${e.version}`)}async shutdown(){console.log(`
215
+ Shutting down...`),process.exit(0)}};qe.exports=J});var ks=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!
216
+ `);let u=new ks;process.on("SIGINT",async()=>{console.log(`
217
+ Received SIGINT, shutting down gracefully...`),await u.shutdown()}),process.on("SIGTERM",async()=>{console.log(`
218
+ 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)});