makecoder 2.0.86 → 2.0.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cc.mjs CHANGED
@@ -20,13 +20,13 @@ import{createRequire as yj5}from"node:module";var fj5=Object.create;var{getProto
20
20
  Object.assign(A, {
21
21
  post(...args) {
22
22
  const [url, payload, ...remainArgs] = args;
23
- const patchedUrl = url + (url.includes('?') ? '&' : ':') + '&app=codev-cli' + '&version=2.0.86' + '&session_id=' + L8();
23
+ const patchedUrl = url + (url.includes('?') ? '&' : ':') + '&app=codev-cli' + '&version=2.0.87' + '&session_id=' + L8();
24
24
  if (process.env.CODEV_AUTH_SK && process.env.CODEV_AUTH_AK) {
25
25
  const headerValues = payload.headers.values;
26
26
  headerValues.set('AUTHORIZATION', `Bearer ${process.env.CODEV_AUTH_AK}.${process.env.CODEV_AUTH_SK}`)
27
27
  }
28
28
 
29
- payload.headers.values.set('X-Coder-Version', '2.0.86');
29
+ payload.headers.values.set('X-Coder-Version', '2.0.87');
30
30
  payload.headers.values.set('X-Coder-Platform', process.platform);
31
31
  payload.headers.values.set('X-Coder-Arch', process.arch);
32
32
 
package/dist/coder.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Ke=Object.create;var se=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var ze=Object.getPrototypeOf,Je=Object.prototype.hasOwnProperty;var m=(u,e)=>()=>(e||u((e={exports:{}}).exports,e),e.exports);var Qe=(u,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of We(e))!Je.call(u,o)&&o!==s&&se(u,o,{get:()=>e[o],enumerable:!(t=je(e,o))||t.enumerable});return u};var Ye=(u,e,s)=>(s=u!=null?Ke(ze(u)):{},Qe(e||!u||!u.__esModule?se(s,"default",{value:u,enumerable:!0}):s,u));var oe=m((Ns,te)=>{var Ze=require("http"),U=class{constructor(e={}){this.port=e.port||9380,this.timeout=e.timeout||300*1e3,this.server=null,this.timeoutId=null}validateTokenFormat(e){if(!e||typeof e!="string")return!1;let s=e.split(".");if(s.length!==2)return!1;let[t,o]=s;return t&&t.length>0&&o&&o.length>0}async waitForCallback(e){return new Promise((s,t)=>{let o=!1;this.server=Ze.createServer((n,r)=>{let c=new URL(n.url,`http://localhost:${this.port}`);if(c.pathname==="/callback"){let i=c.searchParams.get("token"),a=c.searchParams.get("state"),l=c.searchParams.get("error");if(l){r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
2
+ var Qe=Object.create;var ie=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,es=Object.prototype.hasOwnProperty;var p=(h,e)=>()=>(e||h((e={exports:{}}).exports,e),e.exports);var ss=(h,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Xe(e))!es.call(h,o)&&o!==s&&ie(h,o,{get:()=>e[o],enumerable:!(t=Ye(e,o))||t.enumerable});return h};var ts=(h,e,s)=>(s=h!=null?Qe(Ze(h)):{},ss(e||!h||!h.__esModule?ie(s,"default",{value:h,enumerable:!0}):s,h));var ae=p((Ks,re)=>{var os=require("http"),V=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=os.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(`
3
3
  <!DOCTYPE html>
4
4
  <html>
5
5
  <head>
@@ -24,7 +24,7 @@ var Ke=Object.create;var se=Object.defineProperty;var je=Object.getOwnPropertyDe
24
24
  </div>
25
25
  </body>
26
26
  </html>
27
- `),o||(o=!0,this.cleanup(),t(new Error(`OAuth error: ${l}`)));return}if(a!==e){r.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
27
+ `),o||(o=!0,this.cleanup(),t(new Error(`OAuth error: ${l}`)));return}if(c!==e){i.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),i.end(`
28
28
  <!DOCTYPE html>
29
29
  <html>
30
30
  <head>
@@ -46,7 +46,7 @@ var Ke=Object.create;var se=Object.defineProperty;var je=Object.getOwnPropertyDe
46
46
  </div>
47
47
  </body>
48
48
  </html>
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(`
49
+ `),o||(o=!0,this.cleanup(),t(new Error("Invalid state parameter - possible CSRF attack")));return}if(!r){i.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),i.end(`
50
50
  <!DOCTYPE html>
51
51
  <html>
52
52
  <head>
@@ -68,7 +68,7 @@ var Ke=Object.create;var se=Object.defineProperty;var je=Object.getOwnPropertyDe
68
68
  </div>
69
69
  </body>
70
70
  </html>
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(`
71
+ `),o||(o=!0,this.cleanup(),t(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(`
72
72
  <!DOCTYPE html>
73
73
  <html>
74
74
  <head>
@@ -92,7 +92,7 @@ var Ke=Object.create;var se=Object.defineProperty;var je=Object.getOwnPropertyDe
92
92
  </div>
93
93
  </body>
94
94
  </html>
95
- `),o||(o=!0,this.cleanup(),t(new Error("Invalid token format - expected ak.sk format")));return}let[h,d]=i.split(".");r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(`
95
+ `),o||(o=!0,this.cleanup(),t(new Error("Invalid token format - expected ak.sk format")));return}let[u,d]=r.split(".");i.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),i.end(`
96
96
  <!DOCTYPE html>
97
97
  <html>
98
98
  <head>
@@ -124,7 +124,7 @@ var Ke=Object.create;var se=Object.defineProperty;var je=Object.getOwnPropertyDe
124
124
  </script>
125
125
  </body>
126
126
  </html>
127
- `),o||(o=!0,this.cleanup(),s({ak:h,sk:d}))}else r.writeHead(404,{"Content-Type":"text/plain"}),r.end("Not Found")}),this.server.on("error",n=>{if(n.code==="EADDRINUSE"){if(this.port++,this.port>9390){o||(o=!0,t(new Error("Could not find available port for OAuth callback server")));return}this.server.close(),this.server.listen(this.port)}else o||(o=!0,this.cleanup(),t(n))}),this.server.listen(this.port,()=>{process.env.CODEV_DEBUG&&console.log(`OAuth callback server listening on port ${this.port}`)}),this.timeoutId=setTimeout(()=>{o||(o=!0,this.cleanup(),t(new Error("OAuth login timeout - no response received within 5 minutes")))},this.timeout)})}getCallbackUrl(){return`http://localhost:${this.port}/callback`}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server&&(this.server.close(),this.server=null)}};te.exports=U});var re=m((Rs,ne)=>{var Xe=require("crypto"),es=oe(),B=class{constructor(e={}){this.baseUrl=e.baseUrl||"https://makecoder.com",this.callbackServer=null}generateState(){return Xe.randomBytes(16).toString("hex")}buildAuthorizationUrl(e,s){let t=new URLSearchParams({redirect_uri:e,state:s,response_type:"token"});return`${this.baseUrl}/oauth/authorize?${t.toString()}`}async login(){let e=this.generateState();this.callbackServer=new es;try{let s=this.callbackServer.getCallbackUrl(),t=this.buildAuthorizationUrl(s,e);console.log(`
127
+ `),o||(o=!0,this.cleanup(),s({ak:u,sk:d}))}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,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)}};re.exports=V});var le=p((js,ce)=>{var ns=require("crypto"),is=ae(),G=class{constructor(e={}){this.baseUrl=e.baseUrl||"https://makecoder.com",this.callbackServer=null}generateState(){return ns.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 is;try{let s=this.callbackServer.getCallbackUrl(),t=this.buildAuthorizationUrl(s,e);console.log(`
128
128
  \u{1F510} \u5F00\u59CB OAuth \u767B\u5F55\u6D41\u7A0B...
129
129
  `),console.log(`\u{1F4CB} \u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u767B\u5F55
130
130
  `),console.log(`\u{1F310} \u6388\u6743\u5730\u5740: ${t}
@@ -132,20 +132,20 @@ var Ke=Object.create;var se=Object.defineProperty;var je=Object.getOwnPropertyDe
132
132
  `);try{let n=(await import("open")).default;await n(t)}catch(n){console.warn("\u26A0\uFE0F \u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668,\u8BF7\u624B\u52A8\u590D\u5236\u4E0A\u8FF0\u94FE\u63A5\u5230\u6D4F\u89C8\u5668\u6253\u5F00"),process.env.CODEV_DEBUG&&console.error("Browser open error:",n)}let o=await this.callbackServer.waitForCallback(e);return console.log(`\u2705 API Key \u83B7\u53D6\u6210\u529F!
133
133
  `),o}catch(s){throw console.error(`
134
134
  \u274C OAuth \u767B\u5F55\u5931\u8D25: ${s.message}
135
- `),s}finally{this.callbackServer&&this.callbackServer.cleanup()}}cleanup(){this.callbackServer&&this.callbackServer.cleanup()}};ne.exports=B});var ce=m((Vs,ae)=>{var v=require("fs"),ie=require("path"),ss=require("os"),ts=require("readline"),os=re(),L=class{constructor(){this.configPath=ie.join(ss.homedir(),".coder","config.json"),this.defaultConfig={agent:"claude",auth:{ak:null,sk:null}}}async promptForAKSK(){let e=ts.createInterface({input:process.stdin,output:process.stdout});return new Promise((s,t)=>{console.log(`
136
- \u{1F510} \u8BF7\u8F93\u5165\u60A8\u7684 API Key\uFF1A`),e.question("\u8BF7\u8F93\u5165 API Key: ",o=>{let n=o.indexOf(".");if(n===-1||n===0||n===o.length-1){e.close(),t(new Error("\u683C\u5F0F\u9519\u8BEF"));return}let r=o.substring(0,n),c=o.substring(n+1);if(!r.trim()||!c.trim()){e.close(),t(new Error("\u683C\u5F0F\u9519\u8BEF"));return}e.close(),s({ak:r.trim(),sk:c.trim()})})})}ensureConfig(){let e=ie.dirname(this.configPath);try{v.existsSync(e)||v.mkdirSync(e,{recursive:!0}),v.existsSync(this.configPath)||v.writeFileSync(this.configPath,JSON.stringify(this.defaultConfig,null,2))}catch(s){return console.warn(`Warning: Could not create config file: ${s.message}`),this.defaultConfig}}loadConfig(){this.ensureConfig();try{let e=v.readFileSync(this.configPath,"utf8");return JSON.parse(e)}catch(e){return console.warn(`Warning: Could not load config, using defaults: ${e.message}`),this.defaultConfig}}async parse(e=process.argv.slice(2)){let s=this.loadConfig(),t={agent:s.agent||"claude",remainingArgs:[]},o=0,n=!1;for(e.length>0&&["claude","gemini","codex"].includes(e[0])?(t.agent=e[0],n=!0,o=1):e.length>0&&e[0]==="pub"?(t.command="pub",o=1):e.length>0&&e[0]==="login"?(t.command="login",o=1):e.length>0&&e[0]==="update"?(t.command="update",o=1):e.length>0&&e[0]==="skills"&&(t.command="skills",t.skillsSubcommand=e[1],t.skillsArg=e[2],o=e.length);o<e.length;){let i=e[o];if(i==="--agent"){if(n)throw new Error(`Cannot use both subcommand '${t.agent}' and --agent flag. Please use only one method to specify the agent.`);if(o+1>=e.length)throw new Error("--agent requires a value (claude, gemini, or codex)");let a=e[o+1];if(!["claude","gemini","codex"].includes(a))throw new Error(`Invalid agent: ${a}. Must be 'claude', 'gemini', or 'codex'`);t.agent=a,o+=2}else if(i==="--apikey"||i==="--aksk")if(o+1>=e.length||e[o+1].startsWith("--"))t.needAKSKPrompt=!0,o+=1;else{let a=e[o+1],l=a.indexOf(".");if(l===-1)throw new Error("API Key Format error");t.auth_ak=a.substring(0,l),t.auth_sk=a.substring(l+1),o+=2}else if(i==="--save-auth")t.saveAuth=!0,o+=1;else if(i==="--name")o+1>=e.length||e[o+1].startsWith("--")?o+=1:(t.pubName=e[o+1],o+=2);else if(i==="--clear-auth")t.clearAuth=!0,o+=1;else if(i==="--allow-clone")t.allowClone=!0,o+=1;else{t.remainingArgs=e.slice(o);break}}if(t.needAKSKPrompt)try{let{ak:i,sk:a}=await this.promptForAKSK();t.auth_ak=i,t.auth_sk=a,delete t.needAKSKPrompt}catch(i){console.error(`\u274C ${i.message}`),process.exit(1)}if(t.command!=="login"&&(!t.auth_ak&&s.auth&&s.auth.ak&&(t.auth_ak=s.auth.ak),!t.auth_sk&&s.auth&&s.auth.sk&&(t.auth_sk=s.auth.sk),!t.auth_ak&&process.env.CODEV_AUTH_AK&&(t.auth_ak=process.env.CODEV_AUTH_AK),!t.auth_sk&&process.env.CODEV_AUTH_SK&&(t.auth_sk=process.env.CODEV_AUTH_SK)),t.saveAuth&&t.auth_ak&&t.auth_sk){let i=this.saveAuthToConfig(t.auth_ak,t.auth_sk);console.log(i?"\u2705 API Key \u5DF2\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6":"\u274C \u4FDD\u5B58 API Key \u5931\u8D25"),process.exit(0)}if(t.clearAuth){let i=this.clearAuthFromConfig();console.log(i?"\u2705 API Key \u5DF2\u4ECE\u914D\u7F6E\u6587\u4EF6\u6E05\u9664":"\u274C \u6E05\u9664 API Key \u5931\u8D25"),process.exit(0)}let r=t.remainingArgs.includes("--version")||t.remainingArgs.includes("-v"),c=t.remainingArgs.includes("--help")||t.remainingArgs.includes("-h");if(t.command!=="login"&&t.command!=="skills"&&!r&&!c&&(!t.auth_ak||!t.auth_sk))try{console.log(`\u274C \u7F3A\u5C11\u5FC5\u8981\u7684 API Key
135
+ `),s}finally{this.callbackServer&&this.callbackServer.cleanup()}}cleanup(){this.callbackServer&&this.callbackServer.cleanup()}};ce.exports=G});var de=p((zs,he)=>{var k=require("fs"),ue=require("path"),rs=require("os"),as=require("readline"),cs=le(),H=class{constructor(){this.configPath=ue.join(rs.homedir(),".coder","config.json"),this.defaultConfig={agent:"claude",auth:{ak:null,sk:null}}}async promptForAKSK(){let e=as.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 i=o.substring(0,n),a=o.substring(n+1);if(!i.trim()||!a.trim()){e.close(),t(new Error("\u683C\u5F0F\u9519\u8BEF"));return}e.close(),s({ak:i.trim(),sk:a.trim()})})})}ensureConfig(){let e=ue.dirname(this.configPath);try{k.existsSync(e)||k.mkdirSync(e,{recursive:!0}),k.existsSync(this.configPath)||k.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=k.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;if(e.length>0&&["claude","gemini","codex"].includes(e[0]))t.agent=e[0],n=!0,o=1;else if(e.length>0&&e[0]==="pub")t.command="pub",o=1;else if(e.length>0&&e[0]==="login")t.command="login",o=1;else if(e.length>0&&e[0]==="update")t.command="update",o=1;else if(e.length>0&&e[0]==="skills"){t.command="skills";let r=e[1];t.skillsSubcommand=r==="--help"||r==="-h"?void 0:r,t.skillsArg=e[2],t.skillsRemainingArgs=e.slice(2),o=e.length}for(;o<e.length;){let r=e[o];if(r==="--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(r==="--apikey"||r==="--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(r==="--save-auth")t.saveAuth=!0,o+=1;else if(r==="--name")o+1>=e.length||e[o+1].startsWith("--")?o+=1:(t.pubName=e[o+1],o+=2);else if(r==="--clear-auth")t.clearAuth=!0,o+=1;else if(r==="--allow-clone")t.allowClone=!0,o+=1;else{t.remainingArgs=e.slice(o);break}}if(t.needAKSKPrompt)try{let{ak:r,sk:c}=await this.promptForAKSK();t.auth_ak=r,t.auth_sk=c,delete t.needAKSKPrompt}catch(r){console.error(`\u274C ${r.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 r=this.saveAuthToConfig(t.auth_ak,t.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(t.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=t.remainingArgs.includes("--version")||t.remainingArgs.includes("-v"),a=t.remainingArgs.includes("--help")||t.remainingArgs.includes("-h");if(t.command!=="login"&&t.command!=="skills"&&!i&&!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 a=await new os({baseUrl:"https://makecoder.com",apiBaseUrl:t.codevServer||"https://makecoder.com/bigapis/codev/v1"}).login();t.auth_ak=a.ak,t.auth_sk=a.sk;let l=this.saveAuthToConfig(a.ak,a.sk);console.log(l?`\u2705 API Key \u5DF2\u81EA\u52A8\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6
138
+ `);let c=await new cs({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(i){console.error(`
141
- \u274C \u767B\u5F55\u5931\u8D25: ${i.message}
140
+ `)}catch(r){console.error(`
141
+ \u274C \u767B\u5F55\u5931\u8D25: ${r.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?t.codevServer=process.env.CODEV_SERVER:s.codevServer?t.codevServer=s.codevServer:t.codevServer="https://makecoder.com/bigapis/codev/v1",t}saveAuthToConfig(e,s){let t=this.loadConfig();t.auth||(t.auth={}),t.auth.ak=e,t.auth.sk=s;try{return v.writeFileSync(this.configPath,JSON.stringify(t,null,2)),!0}catch(o){return console.warn(`Warning: Could not save auth to config: ${o.message}`),!1}}clearAuthFromConfig(){let e=this.loadConfig();e.auth&&(e.auth.ak=null,e.auth.sk=null);try{return v.writeFileSync(this.configPath,JSON.stringify(e,null,2)),!0}catch(s){return console.warn(`Warning: Could not clear auth from config: ${s.message}`),!1}}showHelp(){console.log(`
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 k.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 k.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:
@@ -170,6 +170,10 @@ SKILLS:
170
170
  coder skills remove <name> \u5378\u8F7D skill
171
171
  coder skills update [name] \u66F4\u65B0 skill\uFF08\u4E0D\u6307\u5B9A\u540D\u79F0\u5219\u66F4\u65B0\u5168\u90E8\uFF09
172
172
  coder skills search <keyword> \u641C\u7D22 skill
173
+ coder skills list \u67E5\u770B\u6211\u53D1\u5E03\u7684 skill
174
+ coder skills publish [--namespace <ns>] [--visibility PUBLIC|NAMESPACE_ONLY|PRIVATE] [<dir-or-zip>]
175
+ coder skills unpublish <namespace>/<slug> \u4E0B\u67B6 skill
176
+ coder skills namespaces \u67E5\u770B\u6211\u7684\u547D\u540D\u7A7A\u95F4
173
177
 
174
178
  EXAMPLES:
175
179
  coder claude # Launch Claude agent
@@ -194,37 +198,68 @@ CONFIG:
194
198
  Default configuration is stored in ~/.coder/config.json
195
199
  Command line --agent overrides the default but doesn't modify the file.
196
200
  Auth credentials can be stored in config file under "auth" section.
197
- `)}};ae.exports=L});var T=m((Gs,le)=>{function ns(u=process.argv.slice(2)){return u.includes("--print")||u.includes("-p")}le.exports={isPrintMode:ns}});var O=m((Hs,de)=>{var{spawn:rs}=require("child_process"),I=require("path"),E=require("fs"),ue=require("os"),{isPrintMode:he}=T(),N=class{constructor(e){this.config=e}resloveSettingFilePath(e){return I.join(e,this.config.configDir,"settings.json")}readModelFromSettingsFile(e){try{let s=this.resloveSettingFilePath(e);if(E.existsSync(s)){let t=E.readFileSync(s,"utf8"),o=JSON.parse(t);if(o&&o.model)return o.model}}catch(s){console.warn(e,s.message)}return null}getCurrentModel(e){let s=e.findIndex(o=>o==="--model");if(s!==-1&&s+1<e.length)return e[s+1];let t=this.readModelFromSettingsFile(process.cwd());return t||(t=this.readModelFromSettingsFile(ue.homedir()),t)?t:this.config.defaultModel}async ensureConfig(e=0){let s=I.join(ue.homedir(),this.config.configDir,this.config.configFile),t=I.dirname(s);if(!E.existsSync(s)){let o=this.config.defaultConfig||{};try{E.existsSync(t)||E.mkdirSync(t,{recursive:!0}),E.writeFileSync(s,JSON.stringify(o,null,2)),e>0&&await new Promise(n=>setTimeout(n,e))}catch(n){console.warn(`Failed to create ${this.config.configFile}: ${n.message}`)}}}findExecutablePath(){let e=I.dirname(require.main.filename);for(let s of this.config.executablePaths){let t=I.resolve(e,s);if(E.existsSync(t))return t}throw new Error(`Could not find executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}handleChildMessages(e){process.env.CODEV_DEBUG&&console.log("Child process message handler initialized"),e.connected&&(e.on("message",s=>{this.onChildMessage(s)}),e.on("exit",async(s,t)=>{try{await this.handleChildProcessExit(s,t)}catch(o){console.error("Error in handleChildProcessExit:",o.message)}}),e.on("error",s=>{this.handleChildProcessError(s)}))}onChildMessage(e){process.env.CODEV_DEBUG&&console.log("Received IPC message from child:",e)}handleChildProcessExit(e,s){}handleChildProcessError(e){}async launch(e={}){let{remainingArgs:s=[],codevServer:t,auth_ak:o=null,auth_sk:n=null}=e;try{let r=this.getCurrentModel(s);he(s)||console.log(`model:\x1B[90m\x1B[3m ${r} (use /model to switch models) \x1B[0m`),await this.ensureConfig(1e3);let c=this.findExecutablePath();return process.env.CODEV_DEBUG&&console.log(`executablePath: ${c}`),new Promise((i,a)=>{let l={...process.env,...this.config.environmentVariables(t)};o&&(l.CODEV_AUTH_AK=o),n&&(l.CODEV_AUTH_SK=n);let h=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&h.push("--inspect-brk"),h.push(c,...s);let d=rs("node",h,{env:l,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(d),d.on("error",f=>{console.error(`Failed to start: ${f.message}`),a(f)}),d.on("exit",async(f,ee)=>{he(s)||ee&&console.log(`terminated by signal: ${ee}`)}),process.on("SIGINT",async()=>{console.log(`
201
+ `)}};he.exports=H});var U=p((Ws,ge)=>{function ls(h=process.argv.slice(2)){return h.includes("--print")||h.includes("-p")}ge.exports={isPrintMode:ls}});var N=p((Js,pe)=>{var{spawn:us}=require("child_process"),A=require("path"),I=require("fs"),fe=require("os"),{isPrintMode:me}=U(),K=class{constructor(e){this.config=e}resloveSettingFilePath(e){return A.join(e,this.config.configDir,"settings.json")}readModelFromSettingsFile(e){try{let s=this.resloveSettingFilePath(e);if(I.existsSync(s)){let t=I.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(fe.homedir()),t)?t:this.config.defaultModel}async ensureConfig(e=0){let s=A.join(fe.homedir(),this.config.configDir,this.config.configFile),t=A.dirname(s);if(!I.existsSync(s)){let o=this.config.defaultConfig||{};try{I.existsSync(t)||I.mkdirSync(t,{recursive:!0}),I.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=A.dirname(require.main.filename);for(let s of this.config.executablePaths){let t=A.resolve(e,s);if(I.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 i=this.getCurrentModel(s);me(s)||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(t)};o&&(l.CODEV_AUTH_AK=o),n&&(l.CODEV_AUTH_SK=n);let u=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&u.push("--inspect-brk"),u.push(a,...s);let d=us("node",u,{env:l,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(d),d.on("error",f=>{console.error(`Failed to start: ${f.message}`),c(f)}),d.on("exit",async(f,q)=>{me(s)||q&&console.log(`terminated by signal: ${q}`)}),process.on("SIGINT",async()=>{console.log(`
198
202
  Terminating ...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
199
- Terminating ...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},8e3)})})}catch(r){throw r}}};de.exports=N});var fe=m((Ks,ge)=>{var g=process.env.CODEV_DEBUG==="True",R=class{constructor(e={}){this.queue=[],this.processing=!1,this.shuttingDown=!1,this.shutdownTimeout=e.shutdownTimeout||5e3,this.maxRetries=e.maxRetries||3,this.retryDelay=e.retryDelay||1e3,this.onProcessMessage=e.onProcessMessage||null,this.shutdownPromise=null,this.currentlyProcessing=null}enqueue(e){if(this.shuttingDown)return g&&console.log("Queue is shutting down, skipping new messages"),null;let s={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(s),g&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),s.id}dequeue(){let e=this.queue.shift();return g&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let s=this.queue.findIndex(t=>t.id===e);return s>-1?(this.queue.splice(s,1),g&&console.log(`Message ${e} removed from queue`),!0):!1}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{for(;this.queue.length>0&&!this.shuttingDown;){let e=this.queue[0];e.processing=!0;try{this.onProcessMessage&&await this.onProcessMessage(e),this.dequeue()}catch(s){if(g&&console.error(`Failed to process message: ${s.message}`),e.retryCount++,g&&console.log("Start Retry:",e.retryCount,"times..."),e.retryCount>=this.maxRetries)g&&console.error("Message exceeded max retries, removing from queue"),this.dequeue();else{e.processing=!1;let t=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,t))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],g&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let s=this.queue.filter(o=>o.processing);if(s.length===0)return;g&&console.log(`Waiting for ${s.length} processing messages to complete (timeout: ${e}ms)`);let t=Date.now();for(;Date.now()-t<e;){if(this.queue.filter(n=>n.processing).length===0){g&&console.log(`All processing messages completed in ${Date.now()-t}ms`);return}await new Promise(n=>setTimeout(n,50))}if(g){let o=this.queue.filter(n=>n.processing);console.log(`Timeout waiting for processing messages. ${o.length} messages still processing`)}}async gracefulShutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let{timeoutMs:s=this.shutdownTimeout,batchSize:t=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async n=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(s*.3,3e3));let r=this.queue.filter(f=>!f.processing),c=r.length;g&&(console.log(`Starting graceful shutdown with ${c} pending messages (${this.queue.length-c} already processing)`),console.log(`Mode: ${o?"fast (parallel)":"sequential"}, timeout: ${s}ms`));let i=Date.now(),a=0,l=0;try{if(o){let f=await this.processAllParallel(s-(Date.now()-i),r);a=f.processed,l=f.failed}else{let f=await this.processInBatches(t,s-(Date.now()-i),r);a=f.processed,l=f.failed}}catch(f){g&&console.error("Error during shutdown processing:",f.message)}let h=Date.now()-i,d=this.queue.length;g&&(console.log(`Shutdown completed in ${h}ms:`),console.log(` - Total: ${c} messages`),console.log(` - Processed: ${a}`),console.log(` - Failed: ${l}`),console.log(` - Remaining: ${d}`)),n({totalMessages:c,processedMessages:a,failedMessages:l,remainingMessages:d,duration:h,allMessagesSent:d===0&&l===0})}),this.shutdownPromise}async processAllParallel(e){if(this.queue.length===0)return{processed:0,failed:0};g&&console.log(`Processing ${this.queue.length} messages in parallel...`);let s=[...this.queue];this.queue=[];let t=s.map(async i=>{try{return this.onProcessMessage&&await this.onProcessMessage(i),{success:!0,messageId:i.id}}catch(a){return g&&console.warn(`Message ${i.id} processing failed: ${a.message}`),{success:!1,messageId:i.id,error:a}}}),o=new Promise(i=>{setTimeout(()=>i({timedOut:!0}),e)}),n=await Promise.race([Promise.allSettled(t).then(i=>({results:i})),o]);if(n.timedOut)return g&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:s.length};let r=n.results.filter(i=>i.status==="fulfilled"&&i.value?.success).length,c=s.length-r;return{processed:r,failed:c}}async processInBatches(e,s){if(this.queue.length===0)return{processed:0,failed:0};g&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let t=Date.now(),o=0,n=0;for(;this.queue.length>0&&Date.now()-t<s;){let r=this.queue.splice(0,e),c=r.map(async h=>{try{return this.onProcessMessage&&await this.onProcessMessage(h),{success:!0}}catch(d){return g&&console.warn(`Batch message processing failed: ${d.message}`),{success:!1,error:d}}}),a=(await Promise.allSettled(c)).filter(h=>h.status==="fulfilled"&&h.value?.success).length,l=r.length-a;o+=a,n+=l,g&&r.length>0&&console.log(`Batch completed: ${a}/${r.length} successful`),this.queue.length>0&&await new Promise(h=>setTimeout(h,10))}return this.queue.length>0&&(n+=this.queue.length,g&&console.log(`${this.queue.length} messages not processed due to timeout`),this.queue=[]),{processed:o,failed:n}}async forceFlushAndShutdown(e=2e3){this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(e*.4,1e3));let s=this.queue.filter(i=>!i.processing);g&&console.log(`Force flush: attempting to send ${s.length} pending messages within ${e}ms (${this.queue.length-s.length} already processing)`);let t=Date.now(),o=s.map(async i=>{try{return this.onProcessMessage&&Date.now()-t<e?(await this.onProcessMessage(i),{success:!0,messageId:i.id}):{success:!1,messageId:i.id,reason:"timeout"}}catch(a){return{success:!1,messageId:i.id,error:a.message}}}),n=e-(Date.now()-t),r=new Promise(i=>{setTimeout(()=>i({timedOut:!0}),Math.max(100,n))}),c=await Promise.race([Promise.allSettled(o).then(i=>({results:i})),r]);if(s.forEach(i=>{let a=this.queue.findIndex(l=>l.id===i.id);a>-1&&this.queue.splice(a,1)}),this.processing=!1,c.timedOut)return g&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:s.length};{let i=c.results.filter(a=>a.status==="fulfilled"&&a.value.success).length;return g&&console.log(`Force flush completed: ${i}/${s.length} messages sent`),{success:i===s.length,successCount:i,totalCount:s.length,results:c.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,g&&console.log("Force shutdown: Queue cleared")}};ge.exports=R});var A=m((js,is)=>{is.exports={name:"makecoder",version:"2.0.86",description:"MakeCoder: Unified AI agent CLI tool integrating Claude Code, Codex and Gemini CLI",main:"./dist/coder.js",bin:{coder:"./dist/coder.js"},scripts:{test:'echo "Error: no test specified" && exit 1',start:"node ./src/coder.js",build:"node scripts/build.js","build:clean":"node scripts/build.js --clean","build:dev":"node scripts/build.js --no-minify --sourcemap",postinstall:"node scripts/postinstall.js"},keywords:["cli","ai","claude","gemini","codex","agent"],author:"makecoder",license:"MIT",repository:{type:"git",url:"https://github.com/makecoderai/coder.git"},homepage:"https://github.com/makecoderai/coder",dependencies:{"node-fetch":"^3.3.2",open:"^10.1.0",zod:"^3.25.76"},optionalDependencies:{"makecoder-codex-linux-x64":"*","makecoder-codex-darwin-arm64":"*","makecoder-codex-win32-x64":"*"},engines:{node:">=20.0.0"},devDependencies:{chokidar:"^4.0.3"},files:["dist","claude","scripts/postinstall.js"]}});var ye=m((Ws,Se)=>{var as=require("http"),cs=require("https"),{URL:me}=require("url"),{version:ls}=A(),pe=process.env.CODEV_DEBUG==="True",V=class{constructor(e={}){this.baseUrl=e.baseUrl||"",this.timeout=e.timeout||3e4,this.defaultHeaders={"Content-Type":"application/json","User-Agent":`codev-cli/${ls}`,...e.headers}}setBaseUrl(e){this.baseUrl=e}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}async post(e,s,t={}){let o=this.resolveUrl(e),n={...this.defaultHeaders,...t.headers};return new Promise((r,c)=>{this.validateRequest(o,s,c);let i=this.serializeData(s,c);if(!i)return;n["Content-Length"]=Buffer.byteLength(i);let a=this.buildRequestOptions(o,"POST",n),l=this.getHttpModule(o);pe&&console.debug(`HTTP POST to ${o} with data length: ${i.length}`);let h=l.request(a,d=>{this.handleResponse(d,r,c)});this.attachErrorHandlers(h,o,c),h.setTimeout(this.timeout),h.write(i),h.end()})}resolveUrl(e){return e.startsWith("http")?e:`${this.baseUrl}${e.startsWith("/")?"":"/"}${e}`}validateRequest(e,s,t){return!e||typeof e!="string"?(t(new Error(`Invalid URL: ${e}`)),!1):s?!0:(t(new Error("No data provided for HTTP POST")),!1)}serializeData(e,s){try{return typeof e=="string"?e:JSON.stringify(e)}catch(t){return s(new Error(`Failed to serialize data: ${t.message}`)),null}}buildRequestOptions(e,s,t){let o=new me(e),n=o.protocol==="https:";return{hostname:o.hostname,port:o.port||(n?443:80),path:o.pathname+o.search,method:s,headers:t}}getHttpModule(e){return new me(e).protocol==="https:"?cs:as}handleResponse(e,s,t){pe&&console.debug(`HTTP response status: ${e.statusCode}`);let o="";e.on("data",n=>{o+=n}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?s({statusCode:e.statusCode,data:o,headers:e.headers}):t(new Error(`HTTP request returned status ${e.statusCode}: ${o}`))})}attachErrorHandlers(e,s,t){e.on("error",o=>{t(new Error(`HTTP POST request failed: ${o.message}`))}),e.on("timeout",()=>{t(new Error(`HTTP POST request timed out for URL: ${s}`)),e.destroy()})}};Se.exports=V});var Ce=m((zs,we)=>{var us=require("crypto"),{URL:hs}=require("url"),G=class{static generateSignature(e,s,t,o){try{let n=new hs(e),r=Buffer.from(n.pathname),c=Buffer.from(r),i=s?typeof s=="string"?Buffer.from(s):Buffer.from(JSON.stringify(s)):Buffer.alloc(0),a=Buffer.concat([c,i,Buffer.from(o)]),l=us.createHmac("sha256",t);return l.update(a),l.digest("hex")}catch(n){throw new Error(`Failed to generate signature: ${n.message}`)}}static validateSignature(e,s,t,o,n){return this.generateSignature(e,s,t,o)===n}static generateTimestamp(){return Date.now().toString()}};we.exports=G});var Ee=m((Js,ve)=>{var ds=Ce(),H=class{constructor(e={}){this.accessKey=null,this.secretKey=null,this.validateCredentials=e.validateCredentials!==!1}setCredentials(e,s){if(this.validateCredentials&&(!e||!s))throw new Error("Both access key and secret key are required");this.accessKey=e,this.secretKey=s}hasCredentials(){return!!(this.accessKey&&this.secretKey)}generateAuthHeaders(e,s=null){if(!this.hasCredentials())return{};try{return{AUTHORIZATION:`Bearer ${this.accessKey}.${this.secretKey}`}}catch(t){throw new Error(`Failed to generate auth headers: ${t.message}`)}}validateAuthHeaders(e,s,t,o){if(!this.hasCredentials())throw new Error("No credentials available for validation");return ds.validateSignature(e,s,this.secretKey,t,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};ve.exports=H});var be=m((Qs,xe)=>{var $=process.env.CODEV_DEBUG==="True",K=class{constructor(e={}){this.currentSessionId=null,this.previousSessionId=null,this.onSessionSwitch=e.onSessionSwitch||null,this.terminateSignal=e.terminateSignal||"CODEV_TERMINATE_SIGNAL"}handleSessionSwitch(e){if(!e)return $&&console.warn("Received empty session ID"),!1;let s=this.previousSessionId!==null&&this.previousSessionId!==e;return s&&($&&console.log(`Session switch detected: ${this.previousSessionId} -> ${e}`),this.onSessionSwitch&&this.onSessionSwitch({type:this.terminateSignal,reason:"User switch session",agent:"claude",previousSessionId:this.previousSessionId,newSessionId:e})),this.previousSessionId=this.currentSessionId,this.currentSessionId=e,s}getCurrentSessionId(){return this.currentSessionId}getPreviousSessionId(){return this.previousSessionId}hasActiveSession(){return!!this.currentSessionId}terminateCurrentSession(e="Session terminated",s=null,t=null){if(!this.hasActiveSession())return $&&console.log("No active session to terminate"),null;let o={type:this.terminateSignal,reason:t?`terminated by signal: ${t}`:e,code:s,signal:t,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId};return $&&console.log("Terminating session:",o),this.previousSessionId=null,this.currentSessionId=null,o}createErrorTermination(e){return this.hasActiveSession()?{type:this.terminateSignal,error:e.message,stack:e.stack,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId}:null}reset(){$&&console.log("Resetting session manager"),this.currentSessionId=null,this.previousSessionId=null}setSessionSwitchCallback(e){this.onSessionSwitch=e}getSessionInfo(){return{currentSessionId:this.currentSessionId,previousSessionId:this.previousSessionId,hasActiveSession:this.hasActiveSession()}}};xe.exports=K});var Ie=m((Ys,ke)=>{var x=require("fs"),k=require("path"),gs=require("events"),fs=require("crypto"),S=process.env.CODEV_DEBUG==="True",j=class extends gs{constructor(e={}){super(),this.watchPaths=e.watchPaths||[],this.excludePatterns=e.excludePatterns||[/node_modules/,/\.git/,/\.DS_Store/,/\.tmp/,/\.log$/,/\.swp$/,/codev\.log/],this.includePatterns=e.includePatterns||[/\.(js|jsx|ts|tsx|py|java|c|cpp|h|hpp|go|rs|rb|php|html|css|scss|sass|less|json|xml|yaml|yml|md|txt)$/],this.watchers=new Map,this.isWatching=!1,this.debounceTimeout=e.debounceTimeout||300,this.pendingChanges=new Map,this.fileContentHashes=new Map,this.enableContentComparison=e.enableContentComparison!==!1,this.onFileChange=e.onFileChange||null}calculateFileHash(e){try{let s=x.readFileSync(e,"utf8");return fs.createHash("sha256").update(s).digest("hex")}catch{return null}}hasContentChanged(e){if(!this.enableContentComparison)return!0;let s=this.calculateFileHash(e),t=this.fileContentHashes.get(e);return s===null?t!==void 0?(this.fileContentHashes.delete(e),!0):!1:t===void 0||s!==t?(this.fileContentHashes.set(e,s),!0):!1}preloadFileHashes(e){if(!(!this.enableContentComparison||!x.existsSync(e)))try{let s=x.readdirSync(e,{withFileTypes:!0});for(let t of s){let o=k.join(e,t.name);t.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):t.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(s){S&&console.warn(`Failed to preload hashes for ${e}:`,s.message)}}shouldExcludeDirectory(e){let s=e.replace(/\\/g,"/");for(let t of this.excludePatterns)if(t.test(s)||t.test(k.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){S&&console.log("FileWatchService is already watching");return}let s=e||this.watchPaths;if(s.length===0){S&&console.log("No watch paths specified");return}this.isWatching=!0;for(let t of s)this.enableContentComparison&&this.preloadFileHashes(t),this.watchDirectory(t);S&&(console.log(`FileWatchService started watching ${s.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,s]of this.watchers)try{s.close(),S&&console.log(`Stopped watching: ${e}`)}catch(t){S&&console.error(`Error stopping watcher for ${e}:`,t.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),S&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!x.existsSync(e)){S&&console.warn(`Watch path does not exist: ${e}`);return}if(!x.statSync(e).isDirectory()){S&&console.warn(`Watch path is not a directory: ${e}`);return}try{let t=x.watch(e,{recursive:!0,persistent:!1},(o,n)=>{if(!n)return;let r=k.join(e,n);this.handleFileChange(o,r,e)});this.watchers.set(e,t),S&&console.log(`Started watching directory: ${e}`),t.on("error",o=>{S&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(t){S&&console.error(`Failed to start watching ${e}:`,t.message)}}handleFileChange(e,s,t){if(!this.shouldWatchFile(s))return;let o=`${e}:${s}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,s,t)},this.debounceTimeout))}processFileChange(e,s,t){if(!this.isWatching)return;let o="modified",n=!1;try{x.statSync(s),n=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(n&&(o==="modified"||o==="created")&&!this.hasContentChanged(s)){S&&console.log(`Ignoring false change for: ${k.relative(t,s)}`);return}!n&&o==="deleted"&&this.fileContentHashes.delete(s);let r={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:s,relativePath:k.relative(t,s),watchPath:t,fileExists:n,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(S&&console.log(`File ${o}: ${r.data.relativePath}`),this.emit("fileChange",r),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(r)}catch(c){S&&console.error("Error in file change callback:",c.message)}}shouldWatchFile(e){let s=k.basename(e),t=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(t)||o.test(s))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(t)||o.test(s))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let s=this.watchPaths.indexOf(e);if(s>-1&&(this.watchPaths.splice(s,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),S&&console.log(`Removed watch path: ${e}`)}catch(t){S&&console.error(`Error removing watch path ${e}:`,t.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};ke.exports=j});var _e=m((et,$e)=>{var ms=O(),ps=require("path"),Zs=require("fs"),Xs=require("os"),Ss=fe(),ys=ye(),ws=Ee(),Cs=be(),vs=Ie(),p=process.env.CODEV_DEBUG==="True",W=class extends ms{constructor(){super({configDir:".",configFile:".claude.json",defaultModel:"Claude Sonnet 4.5",executablePaths:["cc.mjs","/tmp/claude-code/package/cc.mjs"],environmentVariables:e=>({ANTHROPIC_BASE_URL:`${e}/claude`,ANTHROPIC_API_KEY:"codev",DISABLE_TELEMETRY:!0,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,CODEV_SERVER:e,CLAUDE_CODE_ATTRIBUTION_HEADER:"0"}),defaultConfig:{numStartups:1,installMethod:"unknown",autoUpdates:!1,theme:"Coder Dark",customApiKeyResponses:{approved:["codev"]},shiftEnterKeyBindingInstalled:!0,hasCompletedOnboarding:!0,subscriptionNoticeCount:0,hasAvailableSubscription:!0,projects:{}}}),this.fileWatchService=null,this.shutdownInProgress=!1,this.initializeServices()}initializeServices(){this.httpClient=new ys({timeout:1e4}),this.authService=new ws({validateCredentials:!1}),this.sessionManager=new Cs({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new Ss({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return ps.join(e,this.config.configDir,".claude","settings.json")}initializeFileWatchService(){if(!process.env.SESSION_ID){p&&console.log("FileWatchService disabled: SESSION_ID environment variable not found");return}try{this.fileWatchService=new vs({watchPaths:this.getFileWatchPaths(),onFileChange:e=>this.handleFileChange(e),debounceTimeout:300}),p&&console.log("FileWatchService initialized with SESSION_ID:",process.env.SESSION_ID)}catch(e){p&&console.error("Failed to initialize FileWatchService:",e.message)}}getFileWatchPaths(){let e=[],s=process.cwd();e.push(s);let t=process.env.CODEV_WATCH_PATHS;if(t){let o=t.split(",").map(n=>n.trim());e.push(...o)}return e}handleFileChange(e){if(p&&console.log("File change detected:",e.data.relativePath),this.shutdownInProgress)return;let s={message:e,sessionId:e.data.sessionId||process.env.SESSION_ID};this.messageQueue.enqueue(s)}startFileWatching(){this.fileWatchService&&!this.fileWatchService.isWatching&&(this.fileWatchService.startWatching(),p&&console.log("File watching started"))}stopFileWatching(){this.fileWatchService&&this.fileWatchService.isWatching&&(this.fileWatchService.stopWatching(),p&&console.log("File watching stopped"))}onChildMessage(e){e&&e.type==="claude:send-msg"&&this.handleClaudeSendMessage(e.data),super.onChildMessage(e)}handleClaudeSendMessage(e){if(p&&console.log("Handling claude:send-msg message:",e),!e||typeof e!="object"){console.error(`handleClaudeSendMessage: Invalid message data. Expected object, got: ${typeof e}`);return}if(this.shutdownInProgress){p&&console.log("Shutdown in progress, ignoring new message");return}let s=e.sessionId||process.env.SESSION_ID;this.sessionManager.handleSessionSwitch(s),this.messageQueue.enqueue(e)}async processMessage(e){let s=e.data.message,t=e.data.sessionId||process.env.SESSION_ID;if(!t)throw new Error("No session ID available");let o;try{o=typeof s=="string"?JSON.parse(s):s}catch(c){throw new Error(`Failed to parse message data: ${c.message}`)}let n=`/conversations/${t}/@append?task_type=codev`,r=this.authService.hasCredentials()?this.authService.generateAuthHeaders(`${this.httpClient.baseUrl}${n}`,o):{};p&&(console.debug("Sending message to:",n),console.debug("Send Message: ",JSON.stringify(o))),e.type!=="CODEV_TERMINATE_SIGNAL"&&(this.sessionManager.currentSessionId=t)}sendTerminationMessage(e){let s={message:e,sessionId:e.sessionId||this.sessionManager.getCurrentSessionId()};this.messageQueue.enqueue(s)}async handleChildProcessExit(e,s){p&&console.log(`Child process exited with code: ${e}, signal: ${s}`),this.stopFileWatching();let t=this.messageQueue.getQueueSize(),o=this.sessionManager.terminateCurrentSession("process exited normally",e,s);if(o&&this.sendTerminationMessage(o),t>0||o){p&&console.log("Starting graceful shutdown of message queue...");try{let n=!s||s==="SIGTERM",r=this.messageQueue.getQueueSize(),c={timeoutMs:n?8e3:3e3,batchSize:Math.min(r,15),fastMode:!n||r>30};p&&console.log("Shutdown options:",c);let i=await this.messageQueue.gracefulShutdown(c);p&&console.log("Message queue shutdown completed:",i),i.failedMessages>0&&p&&console.warn(`Shutdown summary: ${i.processedMessages} sent, ${i.failedMessages} failed, ${i.remainingMessages} remaining`)}catch(n){p&&console.error("Error during message queue shutdown:",n.message)}}}handleChildProcessError(e){p&&console.error(`Child process error: ${e.message}`);let s=this.sessionManager.createErrorTermination(e);s&&this.sendTerminationMessage(s)}async forceFlushMessages(e=3e3){if(this.messageQueue.getQueueSize()===0)return{success:!0,message:"No messages to flush"};p&&console.log(`Force flushing ${this.messageQueue.getQueueSize()} messages...`);try{return await this.messageQueue.forceFlushAndShutdown(e)}catch(s){return p&&console.error("Force flush failed:",s.message),{success:!1,error:s.message}}}async launch(e={}){let{codevServer:s,auth_ak:t=null,auth_sk:o=null}=e;return this.httpClient.setBaseUrl(s),t&&o&&this.authService.setCredentials(t,o),this.startFileWatching(),super.launch(e)}};$e.exports=W});var Pe=m((tt,De)=>{var Es=O(),st=require("path"),z=class extends Es{constructor(){super({configDir:".gemini",configFile:"settings.json",defaultModel:"gemini-2.5-pro",executablePaths:["gemini/gemini.js","../dist/gemini/gemini.js"],environmentVariables:e=>({GOOGLE_GEMINI_BASE_URL:`${e}/gemini`,GEMINI_API_KEY:"coder",GOOGLE_API_KEY:"coder",GOOGLE_CLOUD_PROJECT:"coder",GOOGLE_CLOUD_LOCATION:"coder",DISABLE_TELEMETRY:!0,GEMINI_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,USE_VERTEX:!0}),defaultConfig:{ide:{hasSeenNudge:!0},telemetry:{enabled:!1,logPrompts:!1},privacy:{usageStatisticsEnabled:!1},general:{disableUpdateNag:!0,preferredEditor:"vscode",previewFeatures:!0},ui:{hideBanner:!0,theme:"Default"},security:{auth:{selectedType:"vertex-ai"}}}})}};De.exports=z});var Oe=m((ot,Te)=>{var xs=O(),_=require("path"),w=require("fs"),bs=require("os"),{spawn:ks}=require("child_process"),F=process.env.CODEV_DEBUG==="True",J=class extends xs{constructor(){super({configDir:".codex",configFile:"config.toml",defaultModel:"o4-mini",executablePaths:["codex.mjs","../dist/codex.mjs"],environmentVariables:e=>({OPENAI_BASE_URL:`${e}/codex`,OPENAI_API_KEY:"codev-proxy-key",DEBUG:F?"true":"false",CODEX_QUIET_MODE:"0",OPENAI_DISABLE_TELEMETRY:"true",CODEX_DISABLE_PROJECT_DOC:"0",CODEV_SERVER:e}),defaultConfig:{model:"gpt-5-codex",approvalMode:"suggest",fullAutoErrorMode:"ask-user",notify:[],history:{maxSize:1e3,saveHistory:!0,sensitivePatterns:[],persistence:"save-all"}}})}checkCodexAvailability(){try{let e=this.findExecutablePath();return w.existsSync(e)}catch{return!1}}resloveSettingFilePath(e){return _.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,s=0){let t=_.join(bs.homedir(),this.config.configDir,this.config.configFile),o=_.dirname(t);try{w.existsSync(o)||w.mkdirSync(o,{recursive:!0});let n=`${e}/codex`;if(w.existsSync(t)){let r=w.readFileSync(t,"utf8"),c=`openai_base_url = "${n}"`;/^openai_base_url\s*=/m.test(r)?r=r.replace(/^openai_base_url\s*=.*/m,c):r=r.trimEnd()+`
200
- `+c+`
201
- `,w.writeFileSync(t,r),F&&console.log(`Updated openai_base_url in ${t}`)}else{let r=this.config.defaultConfig||{},c=this.generateTOMLConfig(r,n);w.writeFileSync(t,c),F&&console.log(`Created Codex config file: ${t}`)}s>0&&await new Promise(r=>setTimeout(r,s))}catch(n){console.warn(`Failed to update ${this.config.configFile}: ${n.message}`)}}generateTOMLConfig(e,s){return`model = "${e.model||"gpt-5-codex"}"
203
+ Terminating ...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},8e3)})})}catch(i){throw i}}};pe.exports=K});var Se=p((Qs,ye)=>{var g=process.env.CODEV_DEBUG==="True",j=class{constructor(e={}){this.queue=[],this.processing=!1,this.shuttingDown=!1,this.shutdownTimeout=e.shutdownTimeout||5e3,this.maxRetries=e.maxRetries||3,this.retryDelay=e.retryDelay||1e3,this.onProcessMessage=e.onProcessMessage||null,this.shutdownPromise=null,this.currentlyProcessing=null}enqueue(e){if(this.shuttingDown)return g&&console.log("Queue is shutting down, skipping new messages"),null;let s={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(s),g&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),s.id}dequeue(){let e=this.queue.shift();return g&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let s=this.queue.findIndex(t=>t.id===e);return s>-1?(this.queue.splice(s,1),g&&console.log(`Message ${e} removed from queue`),!0):!1}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{for(;this.queue.length>0&&!this.shuttingDown;){let e=this.queue[0];e.processing=!0;try{this.onProcessMessage&&await this.onProcessMessage(e),this.dequeue()}catch(s){if(g&&console.error(`Failed to process message: ${s.message}`),e.retryCount++,g&&console.log("Start Retry:",e.retryCount,"times..."),e.retryCount>=this.maxRetries)g&&console.error("Message exceeded max retries, removing from queue"),this.dequeue();else{e.processing=!1;let t=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,t))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],g&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let s=this.queue.filter(o=>o.processing);if(s.length===0)return;g&&console.log(`Waiting for ${s.length} processing messages to complete (timeout: ${e}ms)`);let t=Date.now();for(;Date.now()-t<e;){if(this.queue.filter(n=>n.processing).length===0){g&&console.log(`All processing messages completed in ${Date.now()-t}ms`);return}await new Promise(n=>setTimeout(n,50))}if(g){let o=this.queue.filter(n=>n.processing);console.log(`Timeout waiting for processing messages. ${o.length} messages still processing`)}}async gracefulShutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let{timeoutMs:s=this.shutdownTimeout,batchSize:t=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async n=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(s*.3,3e3));let i=this.queue.filter(f=>!f.processing),a=i.length;g&&(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 r=Date.now(),c=0,l=0;try{if(o){let f=await this.processAllParallel(s-(Date.now()-r),i);c=f.processed,l=f.failed}else{let f=await this.processInBatches(t,s-(Date.now()-r),i);c=f.processed,l=f.failed}}catch(f){g&&console.error("Error during shutdown processing:",f.message)}let u=Date.now()-r,d=this.queue.length;g&&(console.log(`Shutdown completed in ${u}ms:`),console.log(` - Total: ${a} messages`),console.log(` - Processed: ${c}`),console.log(` - Failed: ${l}`),console.log(` - Remaining: ${d}`)),n({totalMessages:a,processedMessages:c,failedMessages:l,remainingMessages:d,duration:u,allMessagesSent:d===0&&l===0})}),this.shutdownPromise}async processAllParallel(e){if(this.queue.length===0)return{processed:0,failed:0};g&&console.log(`Processing ${this.queue.length} messages in parallel...`);let s=[...this.queue];this.queue=[];let t=s.map(async r=>{try{return this.onProcessMessage&&await this.onProcessMessage(r),{success:!0,messageId:r.id}}catch(c){return g&&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(t).then(r=>({results:r})),o]);if(n.timedOut)return g&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:s.length};let i=n.results.filter(r=>r.status==="fulfilled"&&r.value?.success).length,a=s.length-i;return{processed:i,failed:a}}async processInBatches(e,s){if(this.queue.length===0)return{processed:0,failed:0};g&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let t=Date.now(),o=0,n=0;for(;this.queue.length>0&&Date.now()-t<s;){let i=this.queue.splice(0,e),a=i.map(async u=>{try{return this.onProcessMessage&&await this.onProcessMessage(u),{success:!0}}catch(d){return g&&console.warn(`Batch message processing failed: ${d.message}`),{success:!1,error:d}}}),c=(await Promise.allSettled(a)).filter(u=>u.status==="fulfilled"&&u.value?.success).length,l=i.length-c;o+=c,n+=l,g&&i.length>0&&console.log(`Batch completed: ${c}/${i.length} successful`),this.queue.length>0&&await new Promise(u=>setTimeout(u,10))}return this.queue.length>0&&(n+=this.queue.length,g&&console.log(`${this.queue.length} messages not processed due to timeout`),this.queue=[]),{processed:o,failed:n}}async forceFlushAndShutdown(e=2e3){this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(e*.4,1e3));let s=this.queue.filter(r=>!r.processing);g&&console.log(`Force flush: attempting to send ${s.length} pending messages within ${e}ms (${this.queue.length-s.length} already processing)`);let t=Date.now(),o=s.map(async r=>{try{return this.onProcessMessage&&Date.now()-t<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()-t),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(s.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 g&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:s.length};{let r=a.results.filter(c=>c.status==="fulfilled"&&c.value.success).length;return g&&console.log(`Force flush completed: ${r}/${s.length} messages sent`),{success:r===s.length,successCount:r,totalCount:s.length,results:a.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,g&&console.log("Force shutdown: Queue cleared")}};ye.exports=j});var B=p((Ys,hs)=>{hs.exports={name:"makecoder",version:"2.0.87",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 ve=p((Xs,Ee)=>{var ds=require("http"),gs=require("https"),{URL:we}=require("url"),{version:fs}=B(),Ce=process.env.CODEV_DEBUG==="True",z=class{constructor(e={}){this.baseUrl=e.baseUrl||"",this.timeout=e.timeout||3e4,this.defaultHeaders={"Content-Type":"application/json","User-Agent":`codev-cli/${fs}`,...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((i,a)=>{this.validateRequest(o,s,a);let r=this.serializeData(s,a);if(!r)return;n["Content-Length"]=Buffer.byteLength(r);let c=this.buildRequestOptions(o,"POST",n),l=this.getHttpModule(o);Ce&&console.debug(`HTTP POST to ${o} with data length: ${r.length}`);let u=l.request(c,d=>{this.handleResponse(d,i,a)});this.attachErrorHandlers(u,o,a),u.setTimeout(this.timeout),u.write(r),u.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 we(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 we(e).protocol==="https:"?gs:ds}handleResponse(e,s,t){Ce&&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()})}};Ee.exports=z});var xe=p((Zs,be)=>{var ms=require("crypto"),{URL:ps}=require("url"),W=class{static generateSignature(e,s,t,o){try{let n=new ps(e),i=Buffer.from(n.pathname),a=Buffer.from(i),r=s?typeof s=="string"?Buffer.from(s):Buffer.from(JSON.stringify(s)):Buffer.alloc(0),c=Buffer.concat([a,r,Buffer.from(o)]),l=ms.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()}};be.exports=W});var ke=p((et,$e)=>{var ys=xe(),J=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 ys.validateSignature(e,s,this.secretKey,t,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};$e.exports=J});var Pe=p((st,Ie)=>{var O=process.env.CODEV_DEBUG==="True",Q=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 O&&console.warn("Received empty session ID"),!1;let s=this.previousSessionId!==null&&this.previousSessionId!==e;return s&&(O&&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 O&&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 O&&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(){O&&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()}}};Ie.exports=Q});var _e=p((tt,De)=>{var P=require("fs"),_=require("path"),Ss=require("events"),ws=require("crypto"),S=process.env.CODEV_DEBUG==="True",Y=class extends Ss{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=P.readFileSync(e,"utf8");return ws.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||!P.existsSync(e)))try{let s=P.readdirSync(e,{withFileTypes:!0});for(let t of s){let o=_.join(e,t.name);t.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):t.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(s){S&&console.warn(`Failed to preload hashes for ${e}:`,s.message)}}shouldExcludeDirectory(e){let s=e.replace(/\\/g,"/");for(let t of this.excludePatterns)if(t.test(s)||t.test(_.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){S&&console.log("FileWatchService is already watching");return}let s=e||this.watchPaths;if(s.length===0){S&&console.log("No watch paths specified");return}this.isWatching=!0;for(let t of s)this.enableContentComparison&&this.preloadFileHashes(t),this.watchDirectory(t);S&&(console.log(`FileWatchService started watching ${s.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,s]of this.watchers)try{s.close(),S&&console.log(`Stopped watching: ${e}`)}catch(t){S&&console.error(`Error stopping watcher for ${e}:`,t.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),S&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!P.existsSync(e)){S&&console.warn(`Watch path does not exist: ${e}`);return}if(!P.statSync(e).isDirectory()){S&&console.warn(`Watch path is not a directory: ${e}`);return}try{let t=P.watch(e,{recursive:!0,persistent:!1},(o,n)=>{if(!n)return;let i=_.join(e,n);this.handleFileChange(o,i,e)});this.watchers.set(e,t),S&&console.log(`Started watching directory: ${e}`),t.on("error",o=>{S&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(t){S&&console.error(`Failed to start watching ${e}:`,t.message)}}handleFileChange(e,s,t){if(!this.shouldWatchFile(s))return;let o=`${e}:${s}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,s,t)},this.debounceTimeout))}processFileChange(e,s,t){if(!this.isWatching)return;let o="modified",n=!1;try{P.statSync(s),n=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(n&&(o==="modified"||o==="created")&&!this.hasContentChanged(s)){S&&console.log(`Ignoring false change for: ${_.relative(t,s)}`);return}!n&&o==="deleted"&&this.fileContentHashes.delete(s);let i={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:s,relativePath:_.relative(t,s),watchPath:t,fileExists:n,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(S&&console.log(`File ${o}: ${i.data.relativePath}`),this.emit("fileChange",i),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(i)}catch(a){S&&console.error("Error in file change callback:",a.message)}}shouldWatchFile(e){let s=_.basename(e),t=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(t)||o.test(s))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(t)||o.test(s))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let s=this.watchPaths.indexOf(e);if(s>-1&&(this.watchPaths.splice(s,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),S&&console.log(`Removed watch path: ${e}`)}catch(t){S&&console.error(`Error removing watch path ${e}:`,t.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};De.exports=Y});var Oe=p((it,Ae)=>{var Cs=N(),Es=require("path"),ot=require("fs"),nt=require("os"),vs=Se(),bs=ve(),xs=ke(),$s=Pe(),ks=_e(),y=process.env.CODEV_DEBUG==="True",X=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 bs({timeout:1e4}),this.authService=new xs({validateCredentials:!1}),this.sessionManager=new $s({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new vs({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return Es.join(e,this.config.configDir,".claude","settings.json")}initializeFileWatchService(){if(!process.env.SESSION_ID){y&&console.log("FileWatchService disabled: SESSION_ID environment variable not found");return}try{this.fileWatchService=new ks({watchPaths:this.getFileWatchPaths(),onFileChange:e=>this.handleFileChange(e),debounceTimeout:300}),y&&console.log("FileWatchService initialized with SESSION_ID:",process.env.SESSION_ID)}catch(e){y&&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(y&&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(),y&&console.log("File watching started"))}stopFileWatching(){this.fileWatchService&&this.fileWatchService.isWatching&&(this.fileWatchService.stopWatching(),y&&console.log("File watching stopped"))}onChildMessage(e){e&&e.type==="claude:send-msg"&&this.handleClaudeSendMessage(e.data),super.onChildMessage(e)}handleClaudeSendMessage(e){if(y&&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){y&&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`,i=this.authService.hasCredentials()?this.authService.generateAuthHeaders(`${this.httpClient.baseUrl}${n}`,o):{};y&&(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){y&&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){y&&console.log("Starting graceful shutdown of message queue...");try{let n=!s||s==="SIGTERM",i=this.messageQueue.getQueueSize(),a={timeoutMs:n?8e3:3e3,batchSize:Math.min(i,15),fastMode:!n||i>30};y&&console.log("Shutdown options:",a);let r=await this.messageQueue.gracefulShutdown(a);y&&console.log("Message queue shutdown completed:",r),r.failedMessages>0&&y&&console.warn(`Shutdown summary: ${r.processedMessages} sent, ${r.failedMessages} failed, ${r.remainingMessages} remaining`)}catch(n){y&&console.error("Error during message queue shutdown:",n.message)}}}handleChildProcessError(e){y&&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"};y&&console.log(`Force flushing ${this.messageQueue.getQueueSize()} messages...`);try{return await this.messageQueue.forceFlushAndShutdown(e)}catch(s){return y&&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)}};Ae.exports=X});var Me=p((at,Te)=>{var Is=N(),rt=require("path"),Z=class extends Is{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"}}}})}};Te.exports=Z});var Fe=p((ct,qe)=>{var Ps=N(),T=require("path"),x=require("fs"),Ds=require("os"),{spawn:_s}=require("child_process"),L=process.env.CODEV_DEBUG==="True",ee=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:L?"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 T.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,s=0){let t=T.join(Ds.homedir(),this.config.configDir,this.config.configFile),o=T.dirname(t);try{x.existsSync(o)||x.mkdirSync(o,{recursive:!0});let n=`${e}/codex`;if(x.existsSync(t)){let i=x.readFileSync(t,"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()+`
204
+ `+a+`
205
+ `,x.writeFileSync(t,i),L&&console.log(`Updated openai_base_url in ${t}`)}else{let i=this.config.defaultConfig||{},a=this.generateTOMLConfig(i,n);x.writeFileSync(t,a),L&&console.log(`Created Codex config file: ${t}`)}s>0&&await new Promise(i=>setTimeout(i,s))}catch(n){console.warn(`Failed to update ${this.config.configFile}: ${n.message}`)}}generateTOMLConfig(e,s){return`model = "${e.model||"gpt-5-codex"}"
202
206
  openai_base_url = "${s}"
203
- `}findExecutablePath(){let e=_.dirname(require.main.filename);for(let s of this.config.executablePaths){let t=_.resolve(e,s);if(w.existsSync(t))return t}throw new Error(`Could not find Codex executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}async launch(e={}){let{remainingArgs:s=[],codevServer:t,auth_ak:o=null,auth_sk:n=null}=e;try{if(!this.checkCodexAvailability())throw new Error("Codex executable not found. Please ensure makecoder is properly installed: npm install -g makecoder@latest");await this.ensureConfig(t,1e3);let r=this.findExecutablePath();return F&&console.log(`executablePath: ${r}`),new Promise((c,i)=>{let a={...process.env,...this.config.environmentVariables(t)};o&&(a.CODEV_AUTH_AK=o),n&&(a.CODEV_AUTH_SK=n);let l=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&l.push("--inspect-brk"),l.push(r,...s);let h=ks("node",l,{env:a,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(h),h.on("error",d=>{console.error(`Failed to start Codex: ${d.message}`),i(d)}),h.on("exit",async(d,f)=>{console.log(f?`terminated by signal: ${f}`:"Goodbye for now! Keep building great things!")}),process.on("SIGINT",async()=>{console.log(`
204
- Terminating ...`),h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
205
- Terminating ...`),h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},8e3)})})}catch(r){throw r}}};Te.exports=J});var Me=m((nt,qe)=>{var D=require("fs"),Ae=require("path"),{spawn:Fe}=require("child_process"),Q=class{constructor(){this.extensionId="codev.codev-background";let e=require.main?Ae.dirname(require.main.filename):__dirname;this.extensionPath=Ae.resolve(e,"vendor/claude-code.vsix"),this._codeCommand=null}async resolveCodeCommand(){if(this._codeCommand)return this._codeCommand;if(process.env.IS_AISTUDIO==="True"){let e="/usr/lib/aistudio/lib/vscode/bin/remote-cli/aistudio";if(D.existsSync(e))try{return D.accessSync(e,D.constants.F_OK|D.constants.X_OK),this._codeCommand=e,process.env.CODEV_DEBUG&&console.log(`Using AI Studio VSCode path: ${e}`),this._codeCommand}catch(s){process.env.CODEV_DEBUG&&console.log(`AI Studio path exists but not executable: ${s.message}`)}else process.env.CODEV_DEBUG&&console.log(`AI Studio path not found: ${e}`)}try{let{spawn:e}=require("child_process");return new Promise(s=>{let t=e("which",["code"],{stdio:["ignore","pipe","ignore"]}),o="";t.stdout.on("data",n=>{o+=n.toString().trim()}),t.on("close",n=>{n===0&&o?(this._codeCommand=o,process.env.CODEV_DEBUG&&console.log(`Resolved code command path: ${o}`),s(this._codeCommand)):(this._codeCommand="code",s(this._codeCommand))}),t.on("error",()=>{this._codeCommand="code",s(this._codeCommand)}),setTimeout(()=>{t.kill(),this._codeCommand="code",s(this._codeCommand)},3e3)})}catch{return this._codeCommand="code",this._codeCommand}}async shouldInstallExtension(){try{return process.env.IS_AISTUDIO!=="True"?(process.env.CODEV_DEBUG&&console.log("Not in AI Studio environment (IS_AISTUDIO!=True), skipping extension installation"),!1):await this.isVSCodeAvailable()?await this.isExtensionInstalled()?(process.env.CODEV_DEBUG&&console.log(`Extension ${this.extensionId} already installed`),!1):!!D.existsSync(this.extensionPath):(process.env.CODEV_DEBUG&&console.log("VSCode not available, skipping extension installation"),!1)}catch(e){return process.env.CODEV_DEBUG&&console.error(`Error checking extension installation status: ${e.message}`),!1}}async installExtension(){try{return console.log("Installing Codev VSCode extension..."),await this.executeVSCodeCommand(["--install-extension",this.extensionPath])?(console.log("\u2705 Codev VSCode extension installed successfully"),!0):(console.warn("\u274C Failed to install Codev VSCode extension"),!1)}catch(e){return console.warn(`Error installing VSCode extension: ${e.message}`),!1}}async isVSCodeAvailable(){try{let e=process.env.IS_AISTUDIO==="True"?["--help"]:["--version"],s=await this.executeVSCodeCommand(e,{timeout:1e4});if(process.env.CODEV_DEBUG&&(console.log(`VSCode availability check (${e.join(" ")}): ${s?"available":"unavailable"}`),process.env.IS_AISTUDIO==="True")){let{spawn:t}=require("child_process");try{t("which",["code"],{stdio:["ignore","pipe","ignore"]}).stdout.on("data",n=>{console.log("which code:",n.toString().trim())})}catch(o){console.log("which command failed:",o.message)}}return s}catch(e){return process.env.CODEV_DEBUG&&console.error("VSCode availability check error:",e.message),!1}}async isExtensionInstalled(){let e=await this.resolveCodeCommand();try{return new Promise(s=>{try{let t={stdio:["ignore","pipe","ignore"],shell:!1,env:{...process.env,PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER}};process.env.CODEV_DEBUG&&console.log(`Spawning: ${e} --list-extensions`);let o=Fe(e,["--list-extensions"],t),n="";o.stdout.on("data",r=>{n+=r.toString()}),o.on("close",r=>{if(r===0){let c=n.split(`
206
- `).map(i=>i.trim());s(c.includes(this.extensionId))}else s(!1)}),o.on("error",r=>{process.env.CODEV_DEBUG&&(console.error("VSCode list extensions error:",r.message),console.error("Error code:",r.code),console.error("Error errno:",r.errno),console.error("Error syscall:",r.syscall)),s(!1)}),setTimeout(()=>{try{o.kill()}catch{}s(!1)},1e4)}catch(t){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode list extensions:",t.message),s(!1)}})}catch{return!1}}async executeVSCodeCommand(e,s={}){let t=await this.resolveCodeCommand();return new Promise(o=>{try{let n={stdio:"ignore",shell:!1,env:{...process.env,PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER}};process.env.CODEV_DEBUG&&console.log(`Spawning: ${t} ${e.join(" ")}`);let r=Fe(t,e,n);r.on("close",i=>{o(i===0)}),r.on("error",i=>{process.env.CODEV_DEBUG&&(console.error("VSCode command error:",i.message),console.error("Error code:",i.code),console.error("Error errno:",i.errno),console.error("Error syscall:",i.syscall)),o(!1)});let c=s.timeout||3e4;setTimeout(()=>{try{r.kill()}catch{}o(!1)},c)}catch(n){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode command:",n.message),o(!1)}})}async ensureExtensionInstalled(){try{process.env.CODEV_DEBUG&&console.log("VSCode Extension Service: Checking extension status..."),await this.shouldInstallExtension()&&await this.installExtension()}catch(e){process.env.CODEV_DEBUG&&console.error("VSCode Extension Service Error:",e)}}};qe.exports=Q});var Le=m((rt,Be)=>{var y=require("fs"),b=require("path"),Is=require("readline"),{execSync:q}=require("child_process"),Ue=require("os"),Y=class{constructor(){this.serverUrl="https://makecoder.com/bigapis/codev/v1/coderpub"}getClaudeJsonlPath(e,s=!1){let t=e.replace(/[/_]/g,"-"),o=b.join(Ue.homedir(),".claude","projects",t);if(s&&(console.log(`
207
- \u{1F4C2} [allow-clone] \u67E5\u627E JSONL \u6587\u4EF6...`),console.log(` \u9879\u76EE\u76EE\u5F55: ${e}`),console.log(` Claude \u9879\u76EE\u540D: ${t}`),console.log(` Claude \u9879\u76EE\u76EE\u5F55: ${o}`)),!y.existsSync(o))return s&&console.log(" \u274C Claude \u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728"),null;s&&console.log(" \u2713 Claude \u9879\u76EE\u76EE\u5F55\u5B58\u5728");try{let n=y.readdirSync(o).filter(r=>r.endsWith(".jsonl")).map(r=>({name:r,path:b.join(o,r),mtime:y.statSync(b.join(o,r)).mtime,size:y.statSync(b.join(o,r)).size})).sort((r,c)=>c.mtime-r.mtime);return s&&(console.log(` \u627E\u5230 ${n.length} \u4E2A JSONL \u6587\u4EF6:`),n.forEach((r,c)=>{let i=(r.size/1024).toFixed(2),a=r.mtime.toLocaleString(),l=c===0?" <- \u6700\u65B0":"";console.log(` ${c+1}. ${r.name} (${i} KB, ${a})${l}`)})),n.length>0?(s&&console.log(` \u2713 \u9009\u62E9\u6700\u65B0\u6587\u4EF6: ${n[0].name}`),n[0].path):(s&&console.log(" \u274C \u76EE\u5F55\u4E2D\u6CA1\u6709 JSONL \u6587\u4EF6"),null)}catch(n){return s&&console.log(` \u274C \u8BFB\u53D6\u76EE\u5F55\u5931\u8D25: ${n.message}`),null}}async promptForName(){let e=Is.createInterface({input:process.stdin,output:process.stdout});return new Promise((s,t)=>{e.question("\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0 (name): ",o=>{e.close();let n=o.trim();if(!n){t(new Error("\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A"));return}if(!/^[a-zA-Z0-9_-]+$/.test(n)){t(new Error("\u9879\u76EE\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26"));return}s(n)})})}async createZip(e,s={}){let{allowClone:t=!1}=s,o=Ue.tmpdir(),n=`coder-pub-${Date.now()}.zip`,r=b.join(o,n);try{let c=!1;if(y.existsSync(b.join(e,".git")))try{q(`git archive -o "${r}" HEAD`,{cwd:e,stdio:"pipe"}),console.log("\u{1F4E6} \u4F7F\u7528 git archive \u521B\u5EFA\u538B\u7F29\u5305\uFF08\u5DF2\u6392\u9664 .gitignore \u4E2D\u7684\u6587\u4EF6\uFF09"),c=!0}catch{console.log("\u26A0\uFE0F git archive \u5931\u8D25\uFF0C\u4F7F\u7528\u666E\u901A zip \u547D\u4EE4")}if(!c){let a=[".git/*","node_modules/*",".env",".env.*","*.log",".DS_Store"].map(l=>`-x "${l}"`).join(" ");q(`zip -r "${r}" . ${a}`,{cwd:e,stdio:"pipe"}),console.log("\u{1F4E6} \u5DF2\u521B\u5EFA\u538B\u7F29\u5305")}if(t){console.log(`
208
- \u{1F504} [allow-clone] \u5F00\u59CB\u5904\u7406 AI \u751F\u6210\u8BB0\u5F55...`);let i=this.getClaudeJsonlPath(e,!0);if(i){let a=b.join(o,"coder.pub.jsonl"),h=(y.statSync(i).size/1024).toFixed(2);console.log(`
209
- \u{1F4E6} [allow-clone] \u6253\u5305 JSONL \u6587\u4EF6...`),console.log(` \u6E90\u6587\u4EF6: ${i}`),console.log(` \u6587\u4EF6\u5927\u5C0F: ${h} KB`),console.log(` \u4E34\u65F6\u6587\u4EF6: ${a}`),y.copyFileSync(i,a),console.log(" \u2713 \u5DF2\u590D\u5236\u5230\u4E34\u65F6\u76EE\u5F55"),console.log(` \u76EE\u6807 ZIP: ${r}`),console.log(" \u76EE\u6807\u6587\u4EF6\u540D: coder.pub.jsonl"),q(`zip -j "${r}" "${a}"`,{stdio:"pipe"}),console.log(" \u2713 \u5DF2\u6DFB\u52A0\u5230 ZIP \u5305"),y.unlinkSync(a),console.log(" \u2713 \u5DF2\u6E05\u7406\u4E34\u65F6\u6587\u4EF6"),console.log(`\u{1F4CB} [allow-clone] AI \u751F\u6210\u8BB0\u5F55\u5904\u7406\u5B8C\u6210 (coder.pub.jsonl)
207
+ `}findExecutablePath(){let e=T.dirname(require.main.filename);for(let s of this.config.executablePaths){let t=T.resolve(e,s);if(x.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 i=this.findExecutablePath();return L&&console.log(`executablePath: ${i}`),new Promise((a,r)=>{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(i,...s);let u=_s("node",l,{env:c,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(u),u.on("error",d=>{console.error(`Failed to start Codex: ${d.message}`),r(d)}),u.on("exit",async(d,f)=>{console.log(f?`terminated by signal: ${f}`:"Goodbye for now! Keep building great things!")}),process.on("SIGINT",async()=>{console.log(`
208
+ Terminating ...`),u.kill("SIGTERM"),setTimeout(()=>{u.killed||u.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
209
+ Terminating ...`),u.kill("SIGTERM"),setTimeout(()=>{u.killed||u.kill("SIGKILL")},8e3)})})}catch(i){throw i}}};qe.exports=ee});var Le=p((lt,Be)=>{var M=require("fs"),Ue=require("path"),{spawn:Ne}=require("child_process"),se=class{constructor(){this.extensionId="codev.codev-background";let e=require.main?Ue.dirname(require.main.filename):__dirname;this.extensionPath=Ue.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(M.existsSync(e))try{return M.accessSync(e,M.constants.F_OK|M.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):!!M.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=Ne(e,["--list-extensions"],t),n="";o.stdout.on("data",i=>{n+=i.toString()}),o.on("close",i=>{if(i===0){let a=n.split(`
210
+ `).map(r=>r.trim());s(a.includes(this.extensionId))}else s(!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)),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 i=Ne(t,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=s.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)}}};Be.exports=se});var Ge=p((ut,Ve)=>{var C=require("fs"),D=require("path"),As=require("readline"),{execSync:R}=require("child_process"),Re=require("os"),te=class{constructor(){this.serverUrl="https://makecoder.com/bigapis/codev/v1/coderpub"}getClaudeJsonlPath(e,s=!1){let t=e.replace(/[/_]/g,"-"),o=D.join(Re.homedir(),".claude","projects",t);if(s&&(console.log(`
211
+ \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}`)),!C.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=C.readdirSync(o).filter(i=>i.endsWith(".jsonl")).map(i=>({name:i,path:D.join(o,i),mtime:C.statSync(D.join(o,i)).mtime,size:C.statSync(D.join(o,i)).size})).sort((i,a)=>a.mtime-i.mtime);return s&&(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?(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=As.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=Re.tmpdir(),n=`coder-pub-${Date.now()}.zip`,i=D.join(o,n);try{let a=!1;if(C.existsSync(D.join(e,".git")))try{R(`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(" ");R(`zip -r "${i}" . ${c}`,{cwd:e,stdio:"pipe"}),console.log("\u{1F4E6} \u5DF2\u521B\u5EFA\u538B\u7F29\u5305")}if(t){console.log(`
212
+ \u{1F504} [allow-clone] \u5F00\u59CB\u5904\u7406 AI \u751F\u6210\u8BB0\u5F55...`);let r=this.getClaudeJsonlPath(e,!0);if(r){let c=D.join(o,"coder.pub.jsonl"),u=(C.statSync(r).size/1024).toFixed(2);console.log(`
213
+ \u{1F4E6} [allow-clone] \u6253\u5305 JSONL \u6587\u4EF6...`),console.log(` \u6E90\u6587\u4EF6: ${r}`),console.log(` \u6587\u4EF6\u5927\u5C0F: ${u} KB`),console.log(` \u4E34\u65F6\u6587\u4EF6: ${c}`),C.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"),R(`zip -j "${i}" "${c}"`,{stdio:"pipe"}),console.log(" \u2713 \u5DF2\u6DFB\u52A0\u5230 ZIP \u5305"),C.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)
210
214
  `)}else console.log(`\u26A0\uFE0F [allow-clone] \u672A\u627E\u5230 Claude Code \u751F\u6210\u8BB0\u5F55
211
- `)}return r}catch(c){throw new Error(`\u521B\u5EFA\u538B\u7F29\u5305\u5931\u8D25: ${c.message}`)}}async upload(e,s,t,o,n,r=!1){let c=n?`${n}/coderpub`:this.serverUrl,i=`${t}.${o}`;console.log("\u{1F4E4} \u6B63\u5728\u4E0A\u4F20\u5230\u670D\u52A1\u5668..."),r&&(console.log(` \u670D\u52A1\u5668\u5730\u5740: ${c}`),console.log(` \u9879\u76EE\u540D\u79F0: ${s}`),console.log(` ZIP \u6587\u4EF6: ${e}`));try{let a=`curl -s -X POST "${c}" -H "Authorization: Bearer ${i}" -F "name=${s}" -F "zip_file=@${e}"`;r&&console.log(" \u6267\u884C\u4E0A\u4F20\u547D\u4EE4...");let l=q(a,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return r&&console.log(" \u2713 \u4E0A\u4F20\u5B8C\u6210\uFF0C\u89E3\u6790\u54CD\u5E94..."),JSON.parse(l)}catch(a){if(a.stdout)try{return JSON.parse(a.stdout)}catch{throw new Error(`\u4E0A\u4F20\u5931\u8D25: ${a.message}`)}throw new Error(`\u4E0A\u4F20\u5931\u8D25: ${a.message}`)}}cleanup(e){try{y.existsSync(e)&&y.unlinkSync(e)}catch{}}async publish(e){let{ak:s,sk:t,serverBaseUrl:o,allowClone:n}=e,{name:r}=e,c=null;try{r||(r=await this.promptForName()),console.log(`
212
- \u{1F680} \u6B63\u5728\u53D1\u5E03\u9879\u76EE: ${r}`),console.log(`\u{1F4C1} \u76EE\u5F55: ${process.cwd()}`),n&&console.log("\u{1F513} allow-clone: \u542F\u7528 (\u5C06\u5305\u542B AI \u751F\u6210\u8BB0\u5F55)"),console.log(),c=await this.createZip(process.cwd(),{allowClone:n});let a=(y.statSync(c).size/(1024*1024)).toFixed(2);console.log(`\u{1F4CA} \u538B\u7F29\u5305\u5927\u5C0F: ${a} MB`),n&&console.log(`
213
- \u{1F310} [allow-clone] \u5F00\u59CB\u4E0A\u4F20\u5230\u670D\u52A1\u5668...`);let l=await this.upload(c,r,s,t,o,n);return l.code===0?(console.log(`
214
- \u2705 \u53D1\u5E03\u6210\u529F!`),console.log(`\u{1F4CC} \u7248\u672C: ${l.data.version}`),console.log(`\u{1F310} \u8BBF\u95EE\u5730\u5740: https://${r}.coder.pub/`),0):(console.error(`
215
- \u274C \u53D1\u5E03\u5931\u8D25: ${l.message||l.reason}`),1)}catch(i){return console.error(`
216
- \u274C ${i.message}`),1}finally{c&&this.cleanup(c)}}};Be.exports=Y});var Ve=m((it,Re)=>{var Ne=require("https"),P=require("fs"),C=require("path"),$s=require("os"),M="https://makecoder.com/skillhub",Z=class{getSkillDirs(){let e=$s.homedir();return[C.join(e,".claude","skills"),C.join(e,".codex","skills"),C.join(e,".gemini","skills"),C.join(e,".agents","skills")]}fetchWithAuth(e,s){return new Promise((t,o)=>{let n=new URL(e),r={hostname:n.hostname,port:n.port||443,path:n.pathname+n.search,method:"GET",headers:s?{Authorization:`Bearer ${s}`}:{}};Ne.get(r,c=>{if(c.statusCode>=300&&c.statusCode<400&&c.headers.location)return this.fetchWithAuth(c.headers.location,s).then(t).catch(o);let i="";c.on("data",a=>{i+=a}),c.on("end",()=>t({status:c.statusCode,body:i}))}).on("error",o)})}async handle({skillsSubcommand:e,skillsArg:s,auth_ak:t,auth_sk:o}){let{execFileSync:n}=require("child_process");if(!e)return console.log(`Usage:
217
- coder skills add <name>
218
- coder skills remove <name>
219
- coder skills update [name]
220
- coder skills search <keyword>`),0;if(s&&e!=="search"&&!/^[@a-zA-Z0-9_\-/.]+$/.test(s))return console.error("\u274C skill \u540D\u79F0\u5305\u542B\u975E\u6CD5\u5B57\u7B26"),1;if(e==="search")return s?await this.search(s):(console.error("\u274C \u8BF7\u6307\u5B9A\u641C\u7D22\u5173\u952E\u8BCD"),1);if(e==="remove")return s?this.remove(s):(console.error("\u274C \u8BF7\u6307\u5B9A skill \u540D\u79F0"),1);if((e==="add"||e==="update")&&s&&t&&o)return await this.install(s,`${t}.${o}`);try{let r;if(e==="add"){if(!s)return console.error("\u274C \u8BF7\u6307\u5B9A skill \u540D\u79F0"),1;r=["skills","add",M,"--skill",s,"-g"]}else if(e==="update")r=s?["skills","update","--skill",s,"-g"]:["skills","update","-g"];else return console.error(`\u274C \u672A\u77E5\u5B50\u547D\u4EE4: ${e}`),1;return n("npx",r,{stdio:"inherit"}),0}catch(r){return console.error(`\u274C \u6267\u884C\u5931\u8D25: ${r.message}`),1}}async install(e,s){let t=M.replace(/\/$/,"");console.log(`\u{1F50D} \u6B63\u5728\u4ECE ${M} \u67E5\u627E skill...`);let o;try{let a=await this.fetchWithAuth(`${t}/.well-known/agent-skills/index.json`,s);if(a.status!==200)return console.error(`\u274C \u65E0\u6CD5\u83B7\u53D6 skill \u5217\u8868 (HTTP ${a.status})`),1;o=JSON.parse(a.body)}catch(a){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${a.message}`),1}let n=(o.skills||[]).find(a=>a.name.toLowerCase()===e.toLowerCase());if(!n){console.error(`\u274C \u672A\u627E\u5230 skill: ${e}`);for(let a of o.skills||[])console.log(` - ${a.name}`);return 1}let r=Array.from(new Set(["SKILL.md",...n.files||[]])),c=`${t}/.well-known/agent-skills/${n.name}`,i={};for(let a of r)try{let l=await this.fetchWithAuth(`${c}/${a}`,s);if(l.status!==200){console.warn(`\u26A0\uFE0F \u8DF3\u8FC7 ${a} (HTTP ${l.status})`);continue}i[a]=l.body}catch(l){console.warn(`\u26A0\uFE0F \u4E0B\u8F7D ${a} \u5931\u8D25: ${l.message}`)}console.log(`\u{1F4E6} \u6B63\u5728\u5B89\u88C5 ${n.name}...`);for(let a of this.getSkillDirs()){let l=C.join(a,n.name);P.mkdirSync(l,{recursive:!0});for(let[h,d]of Object.entries(i)){let f=C.join(l,h);P.mkdirSync(C.dirname(f),{recursive:!0}),P.writeFileSync(f,d,"utf8")}}return console.log(`\u2705 ${n.name} \u5B89\u88C5\u5B8C\u6210`),0}remove(e){let s=!1;for(let t of this.getSkillDirs()){let o=C.join(t,e);P.existsSync(o)&&(P.rmSync(o,{recursive:!0,force:!0}),console.log(` \u{1F5D1}\uFE0F ${o}`),s=!0)}return s?(console.log(`\u2705 ${e} \u5DF2\u5220\u9664`),0):(console.error(`\u274C \u672A\u627E\u5230\u5DF2\u5B89\u88C5\u7684 skill: ${e}`),1)}async search(e){let s=`${M}/api/web/skills?q=${encodeURIComponent(e)}&sort=relevance&page=0&size=12`;return new Promise(t=>{Ne.get(s,o=>{let n="";o.on("data",r=>{n+=r}),o.on("end",()=>{try{let r=JSON.parse(n);if(r.code!==0)return console.error(`\u274C \u67E5\u8BE2\u5931\u8D25: ${r.msg}`),t(1);let c=r.data.items;if(c.length===0)return console.log(`\u6CA1\u6709\u627E\u5230\u4E0E "${e}" \u76F8\u5173\u7684 skill`),t(0);console.log(`\u627E\u5230 ${r.data.total} \u4E2A\u7ED3\u679C:
221
- `);for(let i of c)console.log(` ${i.slug.padEnd(20)} ${i.summary}`);t(0)}catch(r){console.error(`\u274C \u89E3\u6790\u54CD\u5E94\u5931\u8D25: ${r.message}`),t(1)}})}).on("error",o=>{console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${o.message}`),t(1)})})}};Re.exports=Z});var He=m((at,Ge)=>{var _s=ce(),Ds=_e(),Ps=Pe(),Ts=Oe(),Os=Me(),As=Le(),Fs=Ve(),{isPrintMode:qs}=T(),X=class{constructor(){this.argParser=new _s,this.claudeLauncher=new Ds,this.geminiLauncher=new Ps,this.codexLauncher=new Ts,this.vscodeExtensionService=new Os,this.publishService=new As,this.skillsService=new Fs}async run(e=process.argv.slice(2)){try{try{await this.vscodeExtensionService.ensureExtensionInstalled()}catch(t){process.env.CODEV_DEBUG&&console.error("VSCode Extension Service Error:",t)}if(!e.includes("--agent")&&!e.includes("-a")){let t=e.length>0&&["claude","gemini","codex"].includes(e[0]),o=e.length>0&&["pub","update","skills"].includes(e[0]);if(!t&&!o&&(e.includes("--help")||e.includes("-h")))return this.argParser.showHelp(),0;if(!t&&!o&&(e.includes("--version")||e.includes("-v")))return this.showVersion(),0}let s=await this.argParser.parse(e);return s.command==="login"?await this.handleLogin(s):s.command==="update"?this.handleUpdate():s.command==="skills"?await this.skillsService.handle(s):s.command==="pub"?await this.publishService.publish({name:s.pubName,ak:s.auth_ak,sk:s.auth_sk,serverBaseUrl:s.codevServer,allowClone:s.allowClone}):await this.launchAgent(s)}catch(s){return console.error(`Error: ${s.message}`),process.env.CODEV_DEBUG&&console.error("Stack trace:",s.stack),1}}async launchAgent(e){let{agent:s,remainingArgs:t}=e;return qs(t)||console.log(`cwd:\x1B[90m\x1B[3m ${process.cwd()} \x1B[0m`),s==="claude"?await this.claudeLauncher.launch(e):s==="gemini"?await this.geminiLauncher.launch(e):s==="codex"?await this.codexLauncher.launch(e):1}async handleLogin(e){let s=e.auth_ak,t=e.auth_sk;if(!s||!t){console.log(`
215
+ `)}return i}catch(a){throw new Error(`\u521B\u5EFA\u538B\u7F29\u5305\u5931\u8D25: ${a.message}`)}}async upload(e,s,t,o,n,i=!1){let a=n?`${n}/coderpub`:this.serverUrl,r=`${t}.${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: ${s}`),console.log(` ZIP \u6587\u4EF6: ${e}`));try{let c=`curl -s -X POST "${a}" -H "Authorization: Bearer ${r}" -F "name=${s}" -F "zip_file=@${e}"`;i&&console.log(" \u6267\u884C\u4E0A\u4F20\u547D\u4EE4...");let l=R(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{C.existsSync(e)&&C.unlinkSync(e)}catch{}}async publish(e){let{ak:s,sk:t,serverBaseUrl:o,allowClone:n}=e,{name:i}=e,a=null;try{i||(i=await this.promptForName()),console.log(`
216
+ \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=(C.statSync(a).size/(1024*1024)).toFixed(2);console.log(`\u{1F4CA} \u538B\u7F29\u5305\u5927\u5C0F: ${c} MB`),n&&console.log(`
217
+ \u{1F310} [allow-clone] \u5F00\u59CB\u4E0A\u4F20\u5230\u670D\u52A1\u5668...`);let l=await this.upload(a,i,s,t,o,n);return l.code===0?(console.log(`
218
+ \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(`
219
+ \u274C \u53D1\u5E03\u5931\u8D25: ${l.message||l.reason}`),1)}catch(r){return console.error(`
220
+ \u274C ${r.message}`),1}finally{a&&this.cleanup(a)}}};Ve.exports=te});var je=p((ht,Ke)=>{var He=require("https"),E=require("fs"),v=require("path"),Os=require("os"),b="https://makecoder.com/skillhub",oe=class{getSkillDirs(){let e=Os.homedir();return[v.join(e,".claude","skills"),v.join(e,".codex","skills"),v.join(e,".gemini","skills"),v.join(e,".agents","skills")]}fetchWithAuth(e,s){return new Promise((t,o)=>{let n=new URL(e),i={hostname:n.hostname,port:n.port||443,path:n.pathname+n.search,method:"GET",headers:s?{Authorization:`Bearer ${s}`}:{}};He.get(i,a=>{if(a.statusCode>=300&&a.statusCode<400&&a.headers.location)return this.fetchWithAuth(a.headers.location,s).then(t).catch(o);let r="";a.on("data",c=>{r+=c}),a.on("end",()=>t({status:a.statusCode,body:r}))}).on("error",o)})}async handle({skillsSubcommand:e,skillsArg:s,skillsRemainingArgs:t,auth_ak:o,auth_sk:n}){let{execFileSync:i}=require("child_process");if(!e||e==="--help"||e==="-h")return this.showHelp(),0;if(e==="publish")return await this.publish(t||[],o,n);if(e==="unpublish")return await this.unpublish(s,o,n);if(e==="list")return await this.listMySkills(o,n);if(e==="namespaces")return await this.listNamespaces(o,n);if(s&&e!=="search"&&!/^[@a-zA-Z0-9_\-/.]+$/.test(s))return console.error("\u274C skill \u540D\u79F0\u5305\u542B\u975E\u6CD5\u5B57\u7B26"),1;if(e==="search")return s?await this.search(s):(console.error("\u274C \u8BF7\u6307\u5B9A\u641C\u7D22\u5173\u952E\u8BCD"),1);if(e==="remove")return s?this.remove(s):(console.error("\u274C \u8BF7\u6307\u5B9A skill \u540D\u79F0"),1);if((e==="add"||e==="update")&&s&&o&&n)return await this.install(s,`${o}.${n}`);try{let a;if(e==="add"){if(!s)return console.error("\u274C \u8BF7\u6307\u5B9A skill \u540D\u79F0"),1;a=["skills","add",b,"--skill",s,"-g"]}else if(e==="update")a=s?["skills","update","--skill",s,"-g"]:["skills","update","-g"];else return console.error(`\u274C \u672A\u77E5\u5B50\u547D\u4EE4: ${e}`),1;return i("npx",a,{stdio:"inherit"}),0}catch(a){return console.error(`\u274C \u6267\u884C\u5931\u8D25: ${a.message}`),1}}async install(e,s){let t=b.replace(/\/$/,"");console.log(`\u{1F50D} \u6B63\u5728\u4ECE ${b} \u67E5\u627E skill...`);let o;try{let c=await this.fetchWithAuth(`${t}/.well-known/agent-skills/index.json`,s);if(c.status!==200)return console.error(`\u274C \u65E0\u6CD5\u83B7\u53D6 skill \u5217\u8868 (HTTP ${c.status})`),1;o=JSON.parse(c.body)}catch(c){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${c.message}`),1}let n=(o.skills||[]).find(c=>c.name.toLowerCase()===e.toLowerCase());if(!n){console.error(`\u274C \u672A\u627E\u5230 skill: ${e}`);for(let c of o.skills||[])console.log(` - ${c.name}`);return 1}let i=Array.from(new Set(["SKILL.md",...n.files||[]])),a=`${t}/.well-known/agent-skills/${n.name}`,r={};for(let c of i)try{let l=await this.fetchWithAuth(`${a}/${c}`,s);if(l.status!==200){console.warn(`\u26A0\uFE0F \u8DF3\u8FC7 ${c} (HTTP ${l.status})`);continue}r[c]=l.body}catch(l){console.warn(`\u26A0\uFE0F \u4E0B\u8F7D ${c} \u5931\u8D25: ${l.message}`)}console.log(`\u{1F4E6} \u6B63\u5728\u5B89\u88C5 ${n.name}...`);for(let c of this.getSkillDirs()){let l=v.join(c,n.name);E.mkdirSync(l,{recursive:!0});for(let[u,d]of Object.entries(r)){let f=v.join(l,u);E.mkdirSync(v.dirname(f),{recursive:!0}),E.writeFileSync(f,d,"utf8")}}return console.log(`\u2705 ${n.name} \u5B89\u88C5\u5B8C\u6210`),0}remove(e){let s=!1;for(let t of this.getSkillDirs()){let o=v.join(t,e);E.existsSync(o)&&(E.rmSync(o,{recursive:!0,force:!0}),console.log(` \u{1F5D1}\uFE0F ${o}`),s=!0)}return s?(console.log(`\u2705 ${e} \u5DF2\u5220\u9664`),0):(console.error(`\u274C \u672A\u627E\u5230\u5DF2\u5B89\u88C5\u7684 skill: ${e}`),1)}async search(e){let s=`${b}/api/web/skills?q=${encodeURIComponent(e)}&sort=relevance&page=0&size=12`;return new Promise(t=>{He.get(s,o=>{let n="";o.on("data",i=>{n+=i}),o.on("end",()=>{try{let i=JSON.parse(n);if(i.code!==0)return console.error(`\u274C \u67E5\u8BE2\u5931\u8D25: ${i.msg}`),t(1);let a=i.data.items;if(a.length===0)return console.log(`\u6CA1\u6709\u627E\u5230\u4E0E "${e}" \u76F8\u5173\u7684 skill`),t(0);console.log(`\u627E\u5230 ${i.data.total} \u4E2A\u7ED3\u679C:
221
+ `);for(let r of a)console.log(` ${r.slug.padEnd(20)} ${r.summary}`);t(0)}catch(i){console.error(`\u274C \u89E3\u6790\u54CD\u5E94\u5931\u8D25: ${i.message}`),t(1)}})}).on("error",o=>{console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${o.message}`),t(1)})})}async publish(e,s,t){let{execSync:o}=require("child_process"),n=require("os"),i="global",a="PUBLIC",r=null,c=null,l=null;for(let m=0;m<e.length;m++)if(e[m]==="--namespace"||e[m]==="-n")i=e[++m];else if(e[m]==="--visibility"||e[m]==="-v")a=e[++m];else if(!e[m].startsWith("-")){let w=e[m];E.existsSync(w)&&E.statSync(w).isDirectory()?l=w:r=w}if(!s||!t)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let u=i.startsWith("@")?i.slice(1):i;u==="global"||(a="NAMESPACE_ONLY");let f=["PUBLIC","NAMESPACE_ONLY","PRIVATE"];if(!f.includes(a))return console.error(`\u274C visibility \u5FC5\u987B\u662F: ${f.join(", ")}`),1;if(r){if(!E.existsSync(r))return console.error(`\u274C \u6587\u4EF6\u4E0D\u5B58\u5728: ${r}`),1}else{let m=l?v.resolve(l):process.cwd();c=v.join(n.tmpdir(),`skill-pub-${Date.now()}.zip`),console.log(`\u{1F4E6} \u6B63\u5728\u6253\u5305 ${m}...`);try{E.existsSync(v.join(m,".git"))?(o(`git archive -o "${c}" HEAD`,{cwd:m,stdio:"pipe"}),console.log(" \u4F7F\u7528 git archive\uFF08\u5DF2\u6392\u9664 .gitignore \u6587\u4EF6\uFF09")):o(`zip -r "${c}" . -x ".git/*" -x "node_modules/*" -x ".env" -x "*.log"`,{cwd:m,stdio:"pipe"})}catch(w){return console.error(`\u274C \u6253\u5305\u5931\u8D25: ${w.message}`),1}r=c}let q=`${b}/api/v1/skills/${encodeURIComponent(u)}/publish?visibility=${encodeURIComponent(a)}`,Je=`${s}.${t}`;console.log(`\u{1F680} \u6B63\u5728\u53D1\u5E03\u5230 ${b}...`),console.log(` namespace: ${u}`),console.log(` visibility: ${a}`);try{let m=`curl -s -X POST "${q}" -H "Authorization: Bearer ${Je}" -F "file=@${r}"`,w=o(m,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),$=JSON.parse(w);if($.code===0){let F=$.data;return console.log(`
222
+ \u2705 \u53D1\u5E03\u6210\u529F!`),console.log(` ${F.namespace}/${F.slug}@${F.version}`),F.status==="PUBLISHED"?console.log(" \u72B6\u6001: \u5DF2\u53D1\u5E03"):console.log(" \u72B6\u6001: \u5F85\u5BA1\u6838"),0}else return console.error(`
223
+ \u274C \u53D1\u5E03\u5931\u8D25: ${$.msg||JSON.stringify($)}`),1}catch(m){let w=m.stdout;if(w)try{let $=JSON.parse(w);return console.error(`
224
+ \u274C \u53D1\u5E03\u5931\u8D25: ${$.msg||w}`),1}catch{}return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${m.message}`),1}finally{c&&E.existsSync(c)&&E.unlinkSync(c)}}async unpublish(e,s,t){let{execSync:o}=require("child_process");if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A skill: coder skills unpublish <namespace>/<slug>"),1;if(!s||!t)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let n=e.split("/");if(n.length!==2||!n[0]||!n[1])return console.error("\u274C \u683C\u5F0F\u9519\u8BEF\uFF0C\u5E94\u4E3A <namespace>/<slug>\uFF0C\u4F8B\u5982: global/my-skill"),1;let[i,a]=n,r=i.startsWith("@")?i.slice(1):i,c=`${b}/api/v1/skills/${encodeURIComponent(r)}/${encodeURIComponent(a)}`,l=`${s}.${t}`;console.log(`\u{1F5D1}\uFE0F \u6B63\u5728\u4E0B\u67B6 ${r}/${a}...`);try{let u=o(`curl -s -X DELETE "${c}" -H "Authorization: Bearer ${l}"`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),d=JSON.parse(u);return d.code===0?(console.log(`\u2705 \u5DF2\u4E0B\u67B6 ${r}/${a}`),0):(console.error(`\u274C \u4E0B\u67B6\u5931\u8D25: ${d.msg||JSON.stringify(d)}`),1)}catch(u){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${u.message}`),1}}async listMySkills(e,s){let{execSync:t}=require("child_process");if(!e||!s)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let o=`${b}/api/v1/me/skills?size=50`,n=`${e}.${s}`;try{let i=t(`curl -s "${o}" -H "Authorization: Bearer ${n}"`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),a=JSON.parse(i);if(a.code!==0)return console.error(`\u274C \u83B7\u53D6\u5931\u8D25: ${a.msg}`),1;let r=a.data?.items||[],c=a.data?.total||0;if(r.length===0)return console.log("\u6682\u65E0\u5DF2\u53D1\u5E03\u7684 skill"),0;console.log(`\u5171 ${c} \u4E2A skill:
225
+ `);for(let l of r){let u=`${l.namespace}/${l.slug}`.padEnd(36),d=`\u2B50 ${l.starCount??0}`.padEnd(8),f=`\u2193 ${l.downloadCount??0}`.padEnd(10);console.log(` ${u} ${d} ${f} [${l.status}]`),l.displayName&&l.displayName!==l.slug&&console.log(` ${"".padEnd(36)} ${l.displayName}`)}return 0}catch(i){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${i.message}`),1}}async listNamespaces(e,s){let{execSync:t}=require("child_process");if(!e||!s)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let o=`${b}/api/v1/me/namespaces`,n=`${e}.${s}`;try{let i=t(`curl -s "${o}" -H "Authorization: Bearer ${n}"`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),a=JSON.parse(i);if(a.code!==0)return console.error(`\u274C \u83B7\u53D6\u5931\u8D25: ${a.msg}`),1;let r=a.data||[];if(r.length===0)return console.log("\u6682\u65E0\u547D\u540D\u7A7A\u95F4"),0;console.log(`\u5171 ${r.length} \u4E2A\u547D\u540D\u7A7A\u95F4:
226
+ `);for(let c of r){let l=c.type==="GLOBAL"?"\u5168\u5C40":"\u56E2\u961F";console.log(` @${c.slug.padEnd(20)} ${c.displayName.padEnd(20)} [${l}] ${c.status}`)}return 0}catch(i){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${i.message}`),1}}showHelp(){console.log(`
227
+ coder skills \u2014 \u7BA1\u7406 Claude Code skills
228
+
229
+ USAGE:
230
+ coder skills <subcommand> [options]
231
+
232
+ SUBCOMMANDS:
233
+ add <name> \u5B89\u88C5 skill
234
+ remove <name> \u5378\u8F7D skill
235
+ update [name] \u66F4\u65B0 skill\uFF08\u4E0D\u6307\u5B9A\u540D\u79F0\u5219\u66F4\u65B0\u5168\u90E8\uFF09
236
+ search <keyword> \u641C\u7D22 skill
237
+ list \u67E5\u770B\u6211\u53D1\u5E03\u7684 skill
238
+ publish [options] [<dir-or-zip>] \u53D1\u5E03 skill \u5230 skillhub
239
+ unpublish <namespace>/<slug> \u4E0B\u67B6 skill
240
+ namespaces \u67E5\u770B\u6211\u7684\u547D\u540D\u7A7A\u95F4
241
+
242
+ PUBLISH OPTIONS:
243
+ --namespace <ns> \u76EE\u6807\u547D\u540D\u7A7A\u95F4\uFF08\u9ED8\u8BA4: global\uFF09
244
+ --visibility <v> \u53EF\u89C1\u6027: PUBLIC | NAMESPACE_ONLY | PRIVATE\uFF08\u9ED8\u8BA4: PUBLIC\uFF09
245
+ \u975E global \u547D\u540D\u7A7A\u95F4\u65F6\u81EA\u52A8\u9501\u5B9A\u4E3A NAMESPACE_ONLY
246
+
247
+ EXAMPLES:
248
+ coder skills add vue
249
+ coder skills search react
250
+ coder skills list
251
+ coder skills publish ./my-skill-dir
252
+ coder skills publish --namespace myteam ./my-skill-dir
253
+ coder skills publish --visibility PRIVATE my-skill.zip
254
+ coder skills unpublish global/my-skill
255
+ coder skills namespaces
256
+ `)}};Ke.exports=oe});var We=p((dt,ze)=>{var Ts=de(),Ms=Oe(),qs=Me(),Fs=Fe(),Us=Le(),Ns=Ge(),Bs=je(),{isPrintMode:Ls}=U(),ne=class{constructor(){this.argParser=new Ts,this.claudeLauncher=new Ms,this.geminiLauncher=new qs,this.codexLauncher=new Fs,this.vscodeExtensionService=new Us,this.publishService=new Ns,this.skillsService=new Bs}async run(e=process.argv.slice(2)){try{try{await this.vscodeExtensionService.ensureExtensionInstalled()}catch(t){process.env.CODEV_DEBUG&&console.error("VSCode Extension Service Error:",t)}if(!e.includes("--agent")&&!e.includes("-a")){let t=e.length>0&&["claude","gemini","codex"].includes(e[0]),o=e.length>0&&["pub","update","skills"].includes(e[0]);if(!t&&!o&&(e.includes("--help")||e.includes("-h")))return this.argParser.showHelp(),0;if(!t&&!o&&(e.includes("--version")||e.includes("-v")))return this.showVersion(),0}let s=await this.argParser.parse(e);return s.command==="login"?await this.handleLogin(s):s.command==="update"?this.handleUpdate():s.command==="skills"?await this.skillsService.handle(s):s.command==="pub"?await this.publishService.publish({name:s.pubName,ak:s.auth_ak,sk:s.auth_sk,serverBaseUrl:s.codevServer,allowClone:s.allowClone}):await this.launchAgent(s)}catch(s){return console.error(`Error: ${s.message}`),process.env.CODEV_DEBUG&&console.error("Stack trace:",s.stack),1}}async launchAgent(e){let{agent:s,remainingArgs:t}=e;return Ls(t)||console.log(`cwd:\x1B[90m\x1B[3m ${process.cwd()} \x1B[0m`),s==="claude"?await this.claudeLauncher.launch(e):s==="gemini"?await this.geminiLauncher.launch(e):s==="codex"?await this.codexLauncher.launch(e):1}async handleLogin(e){let s=e.auth_ak,t=e.auth_sk;if(!s||!t){console.log(`
222
257
  \u{1F511} \u8BF7\u5148\u5728 MakeCoder \u521B\u5EFA API Key\uFF1A`),console.log(` \u{1F449} https://makecoder.com/my/apikeys
223
- `);try{let n=await this.argParser.promptForAKSK();s=n.ak,t=n.sk}catch(n){return console.error(`\u274C ${n.message}`),1}}if(this.argParser.saveAuthToConfig(s,t))console.log("\u2705 API Key \u5DF2\u4FDD\u5B58\u5230 ~/.coder/config.json"),console.log(" \u73B0\u5728\u53EF\u4EE5\u76F4\u63A5\u8FD0\u884C coder \u5F00\u59CB\u4F7F\u7528\u4E86 \u{1F680}");else return console.error("\u274C \u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 ~/.coder/ \u76EE\u5F55\u7684\u6587\u4EF6\u6743\u9650"),1;return 0}handleUpdate(){let{execSync:e}=require("child_process"),s=A();console.log(`\u5F53\u524D\u7248\u672C: ${s.version}`),console.log(`\u6B63\u5728\u5347\u7EA7 Coder...
258
+ `);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=B();console.log(`\u5F53\u524D\u7248\u672C: ${s.version}`),console.log(`\u6B63\u5728\u5347\u7EA7 Coder...
224
259
  `);try{return e("npm install -g makecoder@latest",{stdio:"inherit"}),console.log(`
225
260
  \u2705 \u5347\u7EA7\u6210\u529F`),0}catch(t){return console.error(`
226
- \u274C \u5347\u7EA7\u5931\u8D25:`,t.message),1}}showVersion(){let e=A();console.log(`coder version: ${e.version}`)}async shutdown(){console.log(`
227
- Shutting down...`),process.exit(0)}};Ge.exports=X});var Ms=He(),{isPrintMode:Us}=T();process.on("unhandledRejection",(u,e)=>{console.error("Unhandled Promise Rejection:",u),process.exit(1)});process.on("uncaughtException",u=>{console.error("Uncaught Exception:",u.message),process.env.CODEV_DEBUG&&console.error(u.stack),process.exit(1)});async function Bs(){Us()||console.log(`Welcome to Coder!
228
- `);let u=new Ms;process.on("SIGINT",async()=>{console.log(`
229
- Received SIGINT, shutting down gracefully...`),await u.shutdown()}),process.on("SIGTERM",async()=>{console.log(`
230
- Received SIGTERM, shutting down gracefully...`),await u.shutdown()});try{let e=await u.run();process.exit(e)}catch(e){console.error(`Fatal error: ${e.message}`),process.env.CODEV_DEBUG&&console.error(e.stack),process.exit(1)}}Bs().catch(u=>{console.error(`Startup error: ${u.message}`),process.exit(1)});
261
+ \u274C \u5347\u7EA7\u5931\u8D25:`,t.message),1}}showVersion(){let e=B();console.log(`coder version: ${e.version}`)}async shutdown(){console.log(`
262
+ Shutting down...`),process.exit(0)}};ze.exports=ne});var Rs=We(),{isPrintMode:Vs}=U();process.on("unhandledRejection",(h,e)=>{console.error("Unhandled Promise Rejection:",h),process.exit(1)});process.on("uncaughtException",h=>{console.error("Uncaught Exception:",h.message),process.env.CODEV_DEBUG&&console.error(h.stack),process.exit(1)});async function Gs(){Vs()||console.log(`Welcome to Coder!
263
+ `);let h=new Rs;process.on("SIGINT",async()=>{console.log(`
264
+ Received SIGINT, shutting down gracefully...`),await h.shutdown()}),process.on("SIGTERM",async()=>{console.log(`
265
+ Received SIGTERM, shutting down gracefully...`),await h.shutdown()});try{let e=await h.run();process.exit(e)}catch(e){console.error(`Fatal error: ${e.message}`),process.env.CODEV_DEBUG&&console.error(e.stack),process.exit(1)}}Gs().catch(h=>{console.error(`Startup error: ${h.message}`),process.exit(1)});