makecoder 2.0.98 → 2.0.99
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/claude/mcp-channel/wecom/.mcp.json +8 -0
- package/claude/mcp-channel/wecom/package.json +14 -0
- package/claude/mcp-channel/wecom/server.js +371 -0
- package/dist/cc.mjs +2 -2
- package/dist/coder.js +71 -34
- package/dist/gemini/{chunk-FOZ4F2ZF.js → chunk-PV736O4V.js} +2 -2
- package/dist/gemini/{chunk-SE6D5TIW.js → chunk-VHTOM3KV.js} +2 -2
- package/dist/gemini/{chunk-HLGK44EU.js → chunk-WXQ3OUHY.js} +2 -2
- package/dist/gemini/{chunk-G6FZ6TVH.js → chunk-XJCP4SNL.js} +2 -2
- package/dist/gemini/{core-BWKCHNCV.js → core-TKHFKK2W.js} +1 -1
- package/dist/gemini/{devtoolsService-N5WZ4GG3.js → devtoolsService-RUL4FIJA.js} +2 -2
- package/dist/gemini/{devtoolsService-BK4YMW24.js → devtoolsService-UC4LLBEB.js} +2 -2
- package/dist/gemini/{dist-UIFGDXQH.js → dist-RP6OD3OZ.js} +1 -1
- package/dist/gemini/gemini.js +5 -5
- package/dist/gemini/{interactiveCli-LZ4YRLXR.js → interactiveCli-JTCIGNCG.js} +2 -2
- package/dist/gemini/{interactiveCli-KH54H72C.js → interactiveCli-TZP2RCFN.js} +2 -2
- package/dist/gemini/{oauth2-provider-SWOGOEC6.js → oauth2-provider-QVGZD7NX.js} +1 -1
- package/dist/gemini/{oauth2-provider-YQYSWNR3.js → oauth2-provider-SWSDEUUE.js} +1 -1
- package/package.json +4 -4
- /package/dist/gemini/{tree-sitter-YT6TECRE.js → tree-sitter-44HBOLVO.js} +0 -0
- /package/dist/gemini/{tree-sitter-bash-J3PYLNH4.js → tree-sitter-bash-2VW3T3MV.js} +0 -0
package/dist/coder.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var gt=Object.create;var ge=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var yt=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,St=Object.prototype.hasOwnProperty;var m=(h,e)=>()=>(e||h((e={exports:{}}).exports,e),e.exports);var Ct=(h,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of yt(e))!St.call(h,o)&&o!==t&&ge(h,o,{get:()=>e[o],enumerable:!(s=mt(e,o))||s.enumerable});return h};var It=(h,e,t)=>(t=h!=null?gt(wt(h)):{},Ct(e||!h||!h.__esModule?ge(t,"default",{value:h,enumerable:!0}):t,h));var ye=m((ms,me)=>{var Et=require("http"),Q=class{constructor(e={}){this.port=e.port||9380,this.timeout=e.timeout||300*1e3,this.server=null,this.timeoutId=null}validateTokenFormat(e){if(!e||typeof e!="string")return!1;let t=e.split(".");if(t.length!==2)return!1;let[s,o]=t;return s&&s.length>0&&o&&o.length>0}async waitForCallback(e){return new Promise((t,s)=>{let o=!1;this.server=Et.createServer((r,n)=>{let i=new URL(r.url,`http://localhost:${this.port}`);if(i.pathname==="/callback"){let a=i.searchParams.get("token"),c=i.searchParams.get("state"),l=i.searchParams.get("error");if(l){n.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),n.end(`
|
|
3
3
|
<!DOCTYPE html>
|
|
4
4
|
<html>
|
|
5
5
|
<head>
|
|
@@ -92,7 +92,7 @@ var it=Object.create;var de=Object.defineProperty;var at=Object.getOwnPropertyDe
|
|
|
92
92
|
</div>
|
|
93
93
|
</body>
|
|
94
94
|
</html>
|
|
95
|
-
`),o||(o=!0,this.cleanup(),s(new Error("Invalid token format - expected ak.sk format")));return}let[u
|
|
95
|
+
`),o||(o=!0,this.cleanup(),s(new Error("Invalid token format - expected ak.sk format")));return}let[d,u]=a.split(".");n.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),n.end(`
|
|
96
96
|
<!DOCTYPE html>
|
|
97
97
|
<html>
|
|
98
98
|
<head>
|
|
@@ -124,7 +124,7 @@ var it=Object.create;var de=Object.defineProperty;var at=Object.getOwnPropertyDe
|
|
|
124
124
|
</script>
|
|
125
125
|
</body>
|
|
126
126
|
</html>
|
|
127
|
-
`),o||(o=!0,this.cleanup(),t({ak:
|
|
127
|
+
`),o||(o=!0,this.cleanup(),t({ak:d,sk:u}))}else n.writeHead(404,{"Content-Type":"text/plain"}),n.end("Not Found")}),this.server.on("error",r=>{if(r.code==="EADDRINUSE"){if(this.port++,this.port>9390){o||(o=!0,s(new Error("Could not find available port for OAuth callback server")));return}this.server.close(),this.server.listen(this.port)}else o||(o=!0,this.cleanup(),s(r))}),this.server.listen(this.port,()=>{process.env.CODEV_DEBUG&&console.log(`OAuth callback server listening on port ${this.port}`)}),this.timeoutId=setTimeout(()=>{o||(o=!0,this.cleanup(),s(new Error("OAuth login timeout - no response received within 5 minutes")))},this.timeout)})}getCallbackUrl(){return`http://localhost:${this.port}/callback`}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server&&(this.server.close(),this.server=null)}};me.exports=Q});var Se=m((ys,we)=>{var bt=require("crypto"),vt=ye(),Y=class{constructor(e={}){this.baseUrl=e.baseUrl||"https://makecoder.com",this.callbackServer=null}generateState(){return bt.randomBytes(16).toString("hex")}buildAuthorizationUrl(e,t){let s=new URLSearchParams({redirect_uri:e,state:t,response_type:"token"});return`${this.baseUrl}/oauth/authorize?${s.toString()}`}async login(){let e=this.generateState();this.callbackServer=new vt;try{let t=this.callbackServer.getCallbackUrl(),s=this.buildAuthorizationUrl(t,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: ${s}
|
|
@@ -132,10 +132,10 @@ var it=Object.create;var de=Object.defineProperty;var at=Object.getOwnPropertyDe
|
|
|
132
132
|
`);try{let r=(await import("open")).default;await r(s)}catch(r){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:",r)}let o=await this.callbackServer.waitForCallback(e);return console.log(`\u2705 API Key \u83B7\u53D6\u6210\u529F!
|
|
133
133
|
`),o}catch(t){throw console.error(`
|
|
134
134
|
\u274C OAuth \u767B\u5F55\u5931\u8D25: ${t.message}
|
|
135
|
-
`),t}finally{this.callbackServer&&this.callbackServer.cleanup()}}cleanup(){this.callbackServer&&this.callbackServer.cleanup()}};
|
|
136
|
-
\u{1F510} \u8BF7\u8F93\u5165\u60A8\u7684 API Key\uFF1A`),e.question("\u8BF7\u8F93\u5165 API Key: ",o=>{e.close();let r=o.indexOf(".");if(r<=0||r===o.length-1)return s(new Error("\u683C\u5F0F\u9519\u8BEF"));let n=o.substring(0,r).trim(),i=o.substring(r+1).trim();if(!n||!i)return s(new Error("\u683C\u5F0F\u9519\u8BEF"));t({ak:n,sk:i})})})}promptForName(){let e=
|
|
135
|
+
`),t}finally{this.callbackServer&&this.callbackServer.cleanup()}}cleanup(){this.callbackServer&&this.callbackServer.cleanup()}};we.exports=Y});var ve=m((ws,be)=>{var _=require("fs"),Ce=require("path"),xt=require("os"),Ie=require("readline"),$t=Se(),Dt=new Set(["login","skills","wiki","channel"]),Ee=new Set(["claude","gemini","codex"]),Pt=new Set(["pub","login","update","skills","wiki","channel"]),X=class{constructor(){this.configPath=Ce.join(xt.homedir(),".coder","config.json"),this.defaultConfig={agent:"claude",auth:{ak:null,sk:null}}}loadConfig(){let e=Ce.dirname(this.configPath);try{return _.existsSync(e)||_.mkdirSync(e,{recursive:!0}),_.existsSync(this.configPath)||_.writeFileSync(this.configPath,JSON.stringify(this.defaultConfig,null,2)),JSON.parse(_.readFileSync(this.configPath,"utf8"))}catch{return{...this.defaultConfig}}}saveAuthToConfig(e,t){let s=this.loadConfig();s.auth={...s.auth,ak:e,sk:t};try{return _.writeFileSync(this.configPath,JSON.stringify(s,null,2)),!0}catch{return!1}}clearAuthFromConfig(){let e=this.loadConfig();e.auth&&(e.auth={ak:null,sk:null});try{return _.writeFileSync(this.configPath,JSON.stringify(e,null,2)),!0}catch{return!1}}promptForAKSK(){let e=Ie.createInterface({input:process.stdin,output:process.stdout});return new Promise((t,s)=>{console.log(`
|
|
136
|
+
\u{1F510} \u8BF7\u8F93\u5165\u60A8\u7684 API Key\uFF1A`),e.question("\u8BF7\u8F93\u5165 API Key: ",o=>{e.close();let r=o.indexOf(".");if(r<=0||r===o.length-1)return s(new Error("\u683C\u5F0F\u9519\u8BEF"));let n=o.substring(0,r).trim(),i=o.substring(r+1).trim();if(!n||!i)return s(new Error("\u683C\u5F0F\u9519\u8BEF"));t({ak:n,sk:i})})})}promptForName(){let e=Ie.createInterface({input:process.stdin,output:process.stdout});return new Promise((t,s)=>{e.question("\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0 (name): ",o=>{e.close();let r=o.trim();if(!r)return s(new Error("\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A"));if(!/^[a-zA-Z0-9_-]+$/.test(r))return s(new Error("\u9879\u76EE\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26"));t(r)})})}async parse(e=process.argv.slice(2)){let t=this.loadConfig(),s={agent:t.agent||"claude",remainingArgs:[]},o=0;if(e.length>0){if(Ee.has(e[0]))s.agent=e[0],s.agentSetBySubcommand=!0,o=1;else if(Pt.has(e[0])){if(s.command=e[0],o=1,e[0]==="skills"){let n=e[1];s.skillsSubcommand=n==="--help"||n==="-h"?void 0:n,s.skillsArg=e[2],s.skillsRemainingArgs=e.slice(2),o=e.length}else if(e[0]==="wiki"){let n=e[1];s.wikiSubcommand=n==="--help"||n==="-h"?void 0:n,s.wikiArg=e[2],s.wikiRemainingArgs=e.slice(2),o=e.length}else if(e[0]==="channel"){let n=e[1];n==="--help"||n==="-h"?s.channelSubcommand="--help":n==="list"||n==="show"||n==="add"||n==="remove"||n==="update"?(s.channelSubcommand=n,s.channelArg=e[2],s.channelRemainingArgs=e.slice(2)):s.channelRemainingArgs=e.slice(1),o=e.length}}}for(;o<e.length;){let n=e[o];if(n==="--agent"){if(s.agentSetBySubcommand)throw new Error(`\u4E0D\u80FD\u540C\u65F6\u4F7F\u7528\u5B50\u547D\u4EE4 '${s.agent}' \u548C --agent\uFF0C\u8BF7\u9009\u62E9\u5176\u4E00`);let i=e[o+1];if(!i||!Ee.has(i))throw new Error("--agent \u9700\u8981\u6307\u5B9A\u4EE3\u7406\u7C7B\u578B\uFF08claude|gemini|codex\uFF09");s.agent=i,o+=2}else if(n==="--apikey"||n==="--aksk"){let i=e[o+1];if(!i||i.startsWith("--"))s.needAKSKPrompt=!0,o+=1;else{let a=i.indexOf(".");if(a===-1)throw new Error("API Key \u683C\u5F0F\u9519\u8BEF\uFF0C\u5E94\u4E3A <ak>.<sk>");s.auth_ak=i.substring(0,a),s.auth_sk=i.substring(a+1),o+=2}}else if(n==="--save-auth")s.saveAuth=!0,o+=1;else if(n==="--clear-auth")s.clearAuth=!0,o+=1;else if(n==="--name"){let i=e[o+1];i&&!i.startsWith("--")?(s.pubName=i,o+=2):o+=1}else if(n==="--allow-clone")s.allowClone=!0,o+=1;else if(n==="--meta-data"){let i=e[o+1];if(!i||i.startsWith("--"))throw new Error("--meta-data \u9700\u8981\u4E00\u4E2A JSON \u5B57\u7B26\u4E32\u503C");try{JSON.parse(i)}catch(a){throw new Error(`--meta-data \u4E0D\u662F\u5408\u6CD5\u7684 JSON\uFF1A${a.message}`)}s.pubMetaData=i,o+=2}else{s.remainingArgs=e.slice(o);break}}if(s.needAKSKPrompt)try{let{ak:n,sk:i}=await this.promptForAKSK();s.auth_ak=n,s.auth_sk=i,delete s.needAKSKPrompt}catch(n){console.error(`\u274C ${n.message}`),process.exit(1)}s.clearAuth&&(console.log(this.clearAuthFromConfig()?"\u2705 API Key \u5DF2\u4ECE\u914D\u7F6E\u6587\u4EF6\u6E05\u9664":"\u274C \u6E05\u9664 API Key \u5931\u8D25"),process.exit(0)),s.saveAuth&&s.auth_ak&&s.auth_sk&&(console.log(this.saveAuthToConfig(s.auth_ak,s.auth_sk)?"\u2705 API Key \u5DF2\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6":"\u274C \u4FDD\u5B58 API Key \u5931\u8D25"),process.exit(0)),s.command!=="login"&&(s.auth_ak||=t.auth?.ak||process.env.CODEV_AUTH_AK,s.auth_sk||=t.auth?.sk||process.env.CODEV_AUTH_SK),s.codevServer=process.env.CODEV_SERVER||t.codevServer||"https://makecoder.com/bigapis/codev/v1";let r=s.remainingArgs.includes("--version")||s.remainingArgs.includes("-v")||s.remainingArgs.includes("--help")||s.remainingArgs.includes("-h");return!Dt.has(s.command)&&!r&&(!s.auth_ak||!s.auth_sk)&&await this._oauthLogin(s),s}async _oauthLogin(e){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
|
-
`);try{let s=await new
|
|
138
|
+
`);try{let s=await new $t({baseUrl:"https://makecoder.com",apiBaseUrl:e.codevServer}).login();e.auth_ak=s.ak,e.auth_sk=s.sk,console.log(this.saveAuthToConfig(s.ak,s.sk)?`\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\uFF0C\u4E0B\u6B21\u4F7F\u7528\u9700\u8981\u91CD\u65B0\u767B\u5F55
|
|
140
140
|
`)}catch(t){console.error(`
|
|
141
141
|
\u274C \u767B\u5F55\u5931\u8D25\uFF1A${t.message}
|
|
@@ -165,6 +165,7 @@ AI \u4EE3\u7406:
|
|
|
165
165
|
pub \u53D1\u5E03\u5F53\u524D\u76EE\u5F55\u5230\u6258\u7BA1\u670D\u52A1\u5668
|
|
166
166
|
skills \u7BA1\u7406 Claude Code skills
|
|
167
167
|
wiki \u7BA1\u7406 MakeCoder \u77E5\u8BC6\u5E93
|
|
168
|
+
channel \u7BA1\u7406\u6E20\u9053\u7ED1\u5B9A\uFF08\u4F01\u4E1A\u5FAE\u4FE1\u7B49\uFF09\uFF0C\u4E0D\u5E26\u5B50\u547D\u4EE4\u65F6\u542F\u52A8 Claude \u6E20\u9053\u6A21\u5F0F
|
|
168
169
|
|
|
169
170
|
\u9009\u9879:
|
|
170
171
|
--agent <\u4EE3\u7406> \u6307\u5B9A\u4F7F\u7528\u7684 AI \u4EE3\u7406\uFF08claude|gemini|codex\uFF09
|
|
@@ -188,31 +189,31 @@ AI \u4EE3\u7406:
|
|
|
188
189
|
coder wiki --help # \u67E5\u770B wiki \u5B50\u547D\u4EE4\u5E2E\u52A9
|
|
189
190
|
|
|
190
191
|
\u914D\u7F6E\u6587\u4EF6: ~/.coder/config.json
|
|
191
|
-
`)}};
|
|
192
|
-
Terminating ...`),
|
|
193
|
-
Terminating ...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},8e3)})})}catch(n){throw n}}};be.exports=Q});var $e=m((ls,xe)=>{var g=process.env.CODEV_DEBUG==="True",Y=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 t={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(t),g&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),t.id}dequeue(){let e=this.queue.shift();return g&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let t=this.queue.findIndex(s=>s.id===e);return t>-1?(this.queue.splice(t,1),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(t){if(g&&console.error(`Failed to process message: ${t.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 s=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,s))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],g&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let t=this.queue.filter(o=>o.processing);if(t.length===0)return;g&&console.log(`Waiting for ${t.length} processing messages to complete (timeout: ${e}ms)`);let s=Date.now();for(;Date.now()-s<e;){if(this.queue.filter(r=>r.processing).length===0){g&&console.log(`All processing messages completed in ${Date.now()-s}ms`);return}await new Promise(r=>setTimeout(r,50))}if(g){let o=this.queue.filter(r=>r.processing);console.log(`Timeout waiting for processing messages. ${o.length} messages still processing`)}}async gracefulShutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let{timeoutMs:t=this.shutdownTimeout,batchSize:s=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async r=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(t*.3,3e3));let n=this.queue.filter(p=>!p.processing),i=n.length;g&&(console.log(`Starting graceful shutdown with ${i} pending messages (${this.queue.length-i} already processing)`),console.log(`Mode: ${o?"fast (parallel)":"sequential"}, timeout: ${t}ms`));let a=Date.now(),c=0,l=0;try{if(o){let p=await this.processAllParallel(t-(Date.now()-a),n);c=p.processed,l=p.failed}else{let p=await this.processInBatches(s,t-(Date.now()-a),n);c=p.processed,l=p.failed}}catch(p){g&&console.error("Error during shutdown processing:",p.message)}let u=Date.now()-a,d=this.queue.length;g&&(console.log(`Shutdown completed in ${u}ms:`),console.log(` - Total: ${i} messages`),console.log(` - Processed: ${c}`),console.log(` - Failed: ${l}`),console.log(` - Remaining: ${d}`)),r({totalMessages:i,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 t=[...this.queue];this.queue=[];let s=t.map(async a=>{try{return this.onProcessMessage&&await this.onProcessMessage(a),{success:!0,messageId:a.id}}catch(c){return g&&console.warn(`Message ${a.id} processing failed: ${c.message}`),{success:!1,messageId:a.id,error:c}}}),o=new Promise(a=>{setTimeout(()=>a({timedOut:!0}),e)}),r=await Promise.race([Promise.allSettled(s).then(a=>({results:a})),o]);if(r.timedOut)return g&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:t.length};let n=r.results.filter(a=>a.status==="fulfilled"&&a.value?.success).length,i=t.length-n;return{processed:n,failed:i}}async processInBatches(e,t){if(this.queue.length===0)return{processed:0,failed:0};g&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let s=Date.now(),o=0,r=0;for(;this.queue.length>0&&Date.now()-s<t;){let n=this.queue.splice(0,e),i=n.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(i)).filter(u=>u.status==="fulfilled"&&u.value?.success).length,l=n.length-c;o+=c,r+=l,g&&n.length>0&&console.log(`Batch completed: ${c}/${n.length} successful`),this.queue.length>0&&await new Promise(u=>setTimeout(u,10))}return this.queue.length>0&&(r+=this.queue.length,g&&console.log(`${this.queue.length} messages not processed due to timeout`),this.queue=[]),{processed:o,failed:r}}async forceFlushAndShutdown(e=2e3){this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(e*.4,1e3));let t=this.queue.filter(a=>!a.processing);g&&console.log(`Force flush: attempting to send ${t.length} pending messages within ${e}ms (${this.queue.length-t.length} already processing)`);let s=Date.now(),o=t.map(async a=>{try{return this.onProcessMessage&&Date.now()-s<e?(await this.onProcessMessage(a),{success:!0,messageId:a.id}):{success:!1,messageId:a.id,reason:"timeout"}}catch(c){return{success:!1,messageId:a.id,error:c.message}}}),r=e-(Date.now()-s),n=new Promise(a=>{setTimeout(()=>a({timedOut:!0}),Math.max(100,r))}),i=await Promise.race([Promise.allSettled(o).then(a=>({results:a})),n]);if(t.forEach(a=>{let c=this.queue.findIndex(l=>l.id===a.id);c>-1&&this.queue.splice(c,1)}),this.processing=!1,i.timedOut)return g&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:t.length};{let a=i.results.filter(c=>c.status==="fulfilled"&&c.value.success).length;return g&&console.log(`Force flush completed: ${a}/${t.length} messages sent`),{success:a===t.length,successCount:a,totalCount:t.length,results:i.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,g&&console.log("Force shutdown: Queue cleared")}};xe.exports=Y});var H=m((us,It)=>{It.exports={name:"makecoder",version:"2.0.98",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 _e=m((ds,ke)=>{var vt=require("http"),bt=require("https"),{URL:De}=require("url"),{version:xt}=H(),Pe=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/${xt}`,...e.headers}}setBaseUrl(e){this.baseUrl=e}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}async post(e,t,s={}){let o=this.resolveUrl(e),r={...this.defaultHeaders,...s.headers};return new Promise((n,i)=>{this.validateRequest(o,t,i);let a=this.serializeData(t,i);if(!a)return;r["Content-Length"]=Buffer.byteLength(a);let c=this.buildRequestOptions(o,"POST",r),l=this.getHttpModule(o);Pe&&console.debug(`HTTP POST to ${o} with data length: ${a.length}`);let u=l.request(c,d=>{this.handleResponse(d,n,i)});this.attachErrorHandlers(u,o,i),u.setTimeout(this.timeout),u.write(a),u.end()})}resolveUrl(e){return e.startsWith("http")?e:`${this.baseUrl}${e.startsWith("/")?"":"/"}${e}`}validateRequest(e,t,s){return!e||typeof e!="string"?(s(new Error(`Invalid URL: ${e}`)),!1):t?!0:(s(new Error("No data provided for HTTP POST")),!1)}serializeData(e,t){try{return typeof e=="string"?e:JSON.stringify(e)}catch(s){return t(new Error(`Failed to serialize data: ${s.message}`)),null}}buildRequestOptions(e,t,s){let o=new De(e),r=o.protocol==="https:";return{hostname:o.hostname,port:o.port||(r?443:80),path:o.pathname+o.search,method:t,headers:s}}getHttpModule(e){return new De(e).protocol==="https:"?bt:vt}handleResponse(e,t,s){Pe&&console.debug(`HTTP response status: ${e.statusCode}`);let o="";e.on("data",r=>{o+=r}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?t({statusCode:e.statusCode,data:o,headers:e.headers}):s(new Error(`HTTP request returned status ${e.statusCode}: ${o}`))})}attachErrorHandlers(e,t,s){e.on("error",o=>{s(new Error(`HTTP POST request failed: ${o.message}`))}),e.on("timeout",()=>{s(new Error(`HTTP POST request timed out for URL: ${t}`)),e.destroy()})}};ke.exports=Z});var Te=m((hs,Oe)=>{var $t=require("crypto"),{URL:Dt}=require("url"),X=class{static generateSignature(e,t,s,o){try{let r=new Dt(e),n=Buffer.from(r.pathname),i=Buffer.from(n),a=t?typeof t=="string"?Buffer.from(t):Buffer.from(JSON.stringify(t)):Buffer.alloc(0),c=Buffer.concat([i,a,Buffer.from(o)]),l=$t.createHmac("sha256",s);return l.update(c),l.digest("hex")}catch(r){throw new Error(`Failed to generate signature: ${r.message}`)}}static validateSignature(e,t,s,o,r){return this.generateSignature(e,t,s,o)===r}static generateTimestamp(){return Date.now().toString()}};Oe.exports=X});var Me=m((ps,Ae)=>{var Pt=Te(),ee=class{constructor(e={}){this.accessKey=null,this.secretKey=null,this.validateCredentials=e.validateCredentials!==!1}setCredentials(e,t){if(this.validateCredentials&&(!e||!t))throw new Error("Both access key and secret key are required");this.accessKey=e,this.secretKey=t}hasCredentials(){return!!(this.accessKey&&this.secretKey)}generateAuthHeaders(e,t=null){if(!this.hasCredentials())return{};try{return{AUTHORIZATION:`Bearer ${this.accessKey}.${this.secretKey}`}}catch(s){throw new Error(`Failed to generate auth headers: ${s.message}`)}}validateAuthHeaders(e,t,s,o){if(!this.hasCredentials())throw new Error("No credentials available for validation");return Pt.validateSignature(e,t,this.secretKey,s,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};Ae.exports=ee});var Ue=m((fs,qe)=>{var q=process.env.CODEV_DEBUG==="True",te=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 q&&console.warn("Received empty session ID"),!1;let t=this.previousSessionId!==null&&this.previousSessionId!==e;return t&&(q&&console.log(`Session switch detected: ${this.previousSessionId} -> ${e}`),this.onSessionSwitch&&this.onSessionSwitch({type:this.terminateSignal,reason:"User switch session",agent:"claude",previousSessionId:this.previousSessionId,newSessionId:e})),this.previousSessionId=this.currentSessionId,this.currentSessionId=e,t}getCurrentSessionId(){return this.currentSessionId}getPreviousSessionId(){return this.previousSessionId}hasActiveSession(){return!!this.currentSessionId}terminateCurrentSession(e="Session terminated",t=null,s=null){if(!this.hasActiveSession())return q&&console.log("No active session to terminate"),null;let o={type:this.terminateSignal,reason:s?`terminated by signal: ${s}`:e,code:t,signal:s,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId};return q&&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(){q&&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()}}};qe.exports=te});var Ne=m((gs,Fe)=>{var _=require("fs"),T=require("path"),kt=require("events"),_t=require("crypto"),S=process.env.CODEV_DEBUG==="True",se=class extends kt{constructor(e={}){super(),this.watchPaths=e.watchPaths||[],this.excludePatterns=e.excludePatterns||[/node_modules/,/\.git/,/\.DS_Store/,/\.tmp/,/\.log$/,/\.swp$/,/codev\.log/],this.includePatterns=e.includePatterns||[/\.(js|jsx|ts|tsx|py|java|c|cpp|h|hpp|go|rs|rb|php|html|css|scss|sass|less|json|xml|yaml|yml|md|txt)$/],this.watchers=new Map,this.isWatching=!1,this.debounceTimeout=e.debounceTimeout||300,this.pendingChanges=new Map,this.fileContentHashes=new Map,this.enableContentComparison=e.enableContentComparison!==!1,this.onFileChange=e.onFileChange||null}calculateFileHash(e){try{let t=_.readFileSync(e,"utf8");return _t.createHash("sha256").update(t).digest("hex")}catch{return null}}hasContentChanged(e){if(!this.enableContentComparison)return!0;let t=this.calculateFileHash(e),s=this.fileContentHashes.get(e);return t===null?s!==void 0?(this.fileContentHashes.delete(e),!0):!1:s===void 0||t!==s?(this.fileContentHashes.set(e,t),!0):!1}preloadFileHashes(e){if(!(!this.enableContentComparison||!_.existsSync(e)))try{let t=_.readdirSync(e,{withFileTypes:!0});for(let s of t){let o=T.join(e,s.name);s.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):s.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(t){S&&console.warn(`Failed to preload hashes for ${e}:`,t.message)}}shouldExcludeDirectory(e){let t=e.replace(/\\/g,"/");for(let s of this.excludePatterns)if(s.test(t)||s.test(T.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){S&&console.log("FileWatchService is already watching");return}let t=e||this.watchPaths;if(t.length===0){S&&console.log("No watch paths specified");return}this.isWatching=!0;for(let s of t)this.enableContentComparison&&this.preloadFileHashes(s),this.watchDirectory(s);S&&(console.log(`FileWatchService started watching ${t.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,t]of this.watchers)try{t.close(),S&&console.log(`Stopped watching: ${e}`)}catch(s){S&&console.error(`Error stopping watcher for ${e}:`,s.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),S&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!_.existsSync(e)){S&&console.warn(`Watch path does not exist: ${e}`);return}if(!_.statSync(e).isDirectory()){S&&console.warn(`Watch path is not a directory: ${e}`);return}try{let s=_.watch(e,{recursive:!0,persistent:!1},(o,r)=>{if(!r)return;let n=T.join(e,r);this.handleFileChange(o,n,e)});this.watchers.set(e,s),S&&console.log(`Started watching directory: ${e}`),s.on("error",o=>{S&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(s){S&&console.error(`Failed to start watching ${e}:`,s.message)}}handleFileChange(e,t,s){if(!this.shouldWatchFile(t))return;let o=`${e}:${t}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,t,s)},this.debounceTimeout))}processFileChange(e,t,s){if(!this.isWatching)return;let o="modified",r=!1;try{_.statSync(t),r=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(r&&(o==="modified"||o==="created")&&!this.hasContentChanged(t)){S&&console.log(`Ignoring false change for: ${T.relative(s,t)}`);return}!r&&o==="deleted"&&this.fileContentHashes.delete(t);let n={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:t,relativePath:T.relative(s,t),watchPath:s,fileExists:r,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(S&&console.log(`File ${o}: ${n.data.relativePath}`),this.emit("fileChange",n),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(n)}catch(i){S&&console.error("Error in file change callback:",i.message)}}shouldWatchFile(e){let t=T.basename(e),s=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(s)||o.test(t))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(s)||o.test(t))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let t=this.watchPaths.indexOf(e);if(t>-1&&(this.watchPaths.splice(t,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),S&&console.log(`Removed watch path: ${e}`)}catch(s){S&&console.error(`Error removing watch path ${e}:`,s.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};Fe.exports=se});var je=m((ws,Be)=>{var Ot=R(),Tt=require("path"),ms=require("fs"),ys=require("os"),At=$e(),Mt=_e(),qt=Me(),Ut=Ue(),Ft=Ne(),w=process.env.CODEV_DEBUG==="True",oe=class extends Ot{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 Mt({timeout:1e4}),this.authService=new qt({validateCredentials:!1}),this.sessionManager=new Ut({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new At({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return Tt.join(e,this.config.configDir,".claude","settings.json")}initializeFileWatchService(){if(!process.env.SESSION_ID){w&&console.log("FileWatchService disabled: SESSION_ID environment variable not found");return}try{this.fileWatchService=new Ft({watchPaths:this.getFileWatchPaths(),onFileChange:e=>this.handleFileChange(e),debounceTimeout:300}),w&&console.log("FileWatchService initialized with SESSION_ID:",process.env.SESSION_ID)}catch(e){w&&console.error("Failed to initialize FileWatchService:",e.message)}}getFileWatchPaths(){let e=[],t=process.cwd();e.push(t);let s=process.env.CODEV_WATCH_PATHS;if(s){let o=s.split(",").map(r=>r.trim());e.push(...o)}return e}handleFileChange(e){if(w&&console.log("File change detected:",e.data.relativePath),this.shutdownInProgress)return;let t={message:e,sessionId:e.data.sessionId||process.env.SESSION_ID};this.messageQueue.enqueue(t)}startFileWatching(){this.fileWatchService&&!this.fileWatchService.isWatching&&(this.fileWatchService.startWatching(),w&&console.log("File watching started"))}stopFileWatching(){this.fileWatchService&&this.fileWatchService.isWatching&&(this.fileWatchService.stopWatching(),w&&console.log("File watching stopped"))}onChildMessage(e){e&&e.type==="claude:send-msg"&&this.handleClaudeSendMessage(e.data),super.onChildMessage(e)}handleClaudeSendMessage(e){if(w&&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){w&&console.log("Shutdown in progress, ignoring new message");return}let t=e.sessionId||process.env.SESSION_ID;this.sessionManager.handleSessionSwitch(t),this.messageQueue.enqueue(e)}async processMessage(e){let t=e.data.message,s=e.data.sessionId||process.env.SESSION_ID;if(!s)throw new Error("No session ID available");let o;try{o=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error(`Failed to parse message data: ${i.message}`)}let r=`/conversations/${s}/@append?task_type=codev`,n=this.authService.hasCredentials()?this.authService.generateAuthHeaders(`${this.httpClient.baseUrl}${r}`,o):{};w&&(console.debug("Sending message to:",r),console.debug("Send Message: ",JSON.stringify(o))),e.type!=="CODEV_TERMINATE_SIGNAL"&&(this.sessionManager.currentSessionId=s)}sendTerminationMessage(e){let t={message:e,sessionId:e.sessionId||this.sessionManager.getCurrentSessionId()};this.messageQueue.enqueue(t)}async handleChildProcessExit(e,t){w&&console.log(`Child process exited with code: ${e}, signal: ${t}`),this.stopFileWatching();let s=this.messageQueue.getQueueSize(),o=this.sessionManager.terminateCurrentSession("process exited normally",e,t);if(o&&this.sendTerminationMessage(o),s>0||o){w&&console.log("Starting graceful shutdown of message queue...");try{let r=!t||t==="SIGTERM",n=this.messageQueue.getQueueSize(),i={timeoutMs:r?8e3:3e3,batchSize:Math.min(n,15),fastMode:!r||n>30};w&&console.log("Shutdown options:",i);let a=await this.messageQueue.gracefulShutdown(i);w&&console.log("Message queue shutdown completed:",a),a.failedMessages>0&&w&&console.warn(`Shutdown summary: ${a.processedMessages} sent, ${a.failedMessages} failed, ${a.remainingMessages} remaining`)}catch(r){w&&console.error("Error during message queue shutdown:",r.message)}}}handleChildProcessError(e){w&&console.error(`Child process error: ${e.message}`);let t=this.sessionManager.createErrorTermination(e);t&&this.sendTerminationMessage(t)}async forceFlushMessages(e=3e3){if(this.messageQueue.getQueueSize()===0)return{success:!0,message:"No messages to flush"};w&&console.log(`Force flushing ${this.messageQueue.getQueueSize()} messages...`);try{return await this.messageQueue.forceFlushAndShutdown(e)}catch(t){return w&&console.error("Force flush failed:",t.message),{success:!1,error:t.message}}}async launch(e={}){let{codevServer:t,auth_ak:s=null,auth_sk:o=null}=e;return this.httpClient.setBaseUrl(t),s&&o&&this.authService.setCredentials(s,o),this.startFileWatching(),super.launch(e)}};Be.exports=oe});var Re=m((Cs,Le)=>{var Nt=R(),Ss=require("path"),ne=class extends Nt{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"}}}})}};Le.exports=ne});var Ge=m((Es,He)=>{var Bt=R(),U=require("path"),$=require("fs"),jt=require("os"),{spawn:Lt}=require("child_process"),G=process.env.CODEV_DEBUG==="True",re=class extends Bt{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:G?"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 $.existsSync(e)}catch{return!1}}resloveSettingFilePath(e){return U.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,t=0){let s=U.join(jt.homedir(),this.config.configDir,this.config.configFile),o=U.dirname(s);try{$.existsSync(o)||$.mkdirSync(o,{recursive:!0});let r=`${e}/codex`;if($.existsSync(s)){let n=$.readFileSync(s,"utf8"),i=`openai_base_url = "${r}"`;/^openai_base_url\s*=/m.test(n)?n=n.replace(/^openai_base_url\s*=.*/m,i):n=n.trimEnd()+`
|
|
192
|
+
`)}};be.exports=X});var R=m((Ss,xe)=>{function _t(h=process.argv.slice(2)){return h.includes("--print")||h.includes("-p")}xe.exports={isPrintMode:_t}});var H=m((Cs,Pe)=>{var{spawn:kt}=require("child_process"),q=require("path"),k=require("fs"),$e=require("os"),{isPrintMode:De}=R(),Z=class{constructor(e){this.config=e}resloveSettingFilePath(e){return q.join(e,this.config.configDir,"settings.json")}readModelFromSettingsFile(e){try{let t=this.resloveSettingFilePath(e);if(k.existsSync(t)){let s=k.readFileSync(t,"utf8"),o=JSON.parse(s);if(o&&o.model)return o.model}}catch(t){console.warn(e,t.message)}return null}getCurrentModel(e){let t=e.findIndex(o=>o==="--model");if(t!==-1&&t+1<e.length)return e[t+1];let s=this.readModelFromSettingsFile(process.cwd());return s||(s=this.readModelFromSettingsFile($e.homedir()),s)?s:this.config.defaultModel}async ensureConfig(e=0){let t=q.join($e.homedir(),this.config.configDir,this.config.configFile),s=q.dirname(t);if(!k.existsSync(t)){let o=this.config.defaultConfig||{};try{k.existsSync(s)||k.mkdirSync(s,{recursive:!0}),k.writeFileSync(t,JSON.stringify(o,null,2)),e>0&&await new Promise(r=>setTimeout(r,e))}catch(r){console.warn(`Failed to create ${this.config.configFile}: ${r.message}`)}}}findExecutablePath(){let e=q.dirname(require.main.filename);for(let t of this.config.executablePaths){let s=q.resolve(e,t);if(k.existsSync(s))return s}throw new Error(`Could not find executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}handleChildMessages(e){process.env.CODEV_DEBUG&&console.log("Child process message handler initialized"),e.connected&&(e.on("message",t=>{this.onChildMessage(t)}),e.on("exit",async(t,s)=>{try{await this.handleChildProcessExit(t,s)}catch(o){console.error("Error in handleChildProcessExit:",o.message)}}),e.on("error",t=>{this.handleChildProcessError(t)}))}onChildMessage(e){process.env.CODEV_DEBUG&&console.log("Received IPC message from child:",e)}handleChildProcessExit(e,t){}handleChildProcessError(e){}async launch(e={}){let{remainingArgs:t=[],codevServer:s,auth_ak:o=null,auth_sk:r=null,extraEnv:n={}}=e;try{let i=this.getCurrentModel(t);De(t)||console.log(`model:\x1B[90m\x1B[3m ${i} (use /model to switch models) \x1B[0m`),await this.ensureConfig(1e3);let a=this.findExecutablePath();return process.env.CODEV_DEBUG&&console.log(`executablePath: ${a}`),new Promise((c,l)=>{let d={...process.env,...this.config.environmentVariables(s),...n};o&&(d.CODEV_AUTH_AK=o),r&&(d.CODEV_AUTH_SK=r);let u=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&u.push("--inspect-brk"),u.push(a,...t);let f=kt("node",u,{env:d,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(f),f.on("error",C=>{console.error(`Failed to start: ${C.message}`),l(C)}),f.on("exit",async(C,P)=>{De(t)||P&&console.log(`terminated by signal: ${P}`)}),process.on("SIGINT",async()=>{console.log(`
|
|
193
|
+
Terminating ...`),f.kill("SIGTERM"),setTimeout(()=>{f.killed||f.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
|
|
194
|
+
Terminating ...`),f.kill("SIGTERM"),setTimeout(()=>{f.killed||f.kill("SIGKILL")},8e3)})})}catch(i){throw i}}};Pe.exports=Z});var ke=m((Is,_e)=>{var g=process.env.CODEV_DEBUG==="True",ee=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 t={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(t),g&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),t.id}dequeue(){let e=this.queue.shift();return g&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let t=this.queue.findIndex(s=>s.id===e);return t>-1?(this.queue.splice(t,1),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(t){if(g&&console.error(`Failed to process message: ${t.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 s=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,s))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],g&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let t=this.queue.filter(o=>o.processing);if(t.length===0)return;g&&console.log(`Waiting for ${t.length} processing messages to complete (timeout: ${e}ms)`);let s=Date.now();for(;Date.now()-s<e;){if(this.queue.filter(r=>r.processing).length===0){g&&console.log(`All processing messages completed in ${Date.now()-s}ms`);return}await new Promise(r=>setTimeout(r,50))}if(g){let o=this.queue.filter(r=>r.processing);console.log(`Timeout waiting for processing messages. ${o.length} messages still processing`)}}async gracefulShutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let{timeoutMs:t=this.shutdownTimeout,batchSize:s=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async r=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(t*.3,3e3));let n=this.queue.filter(f=>!f.processing),i=n.length;g&&(console.log(`Starting graceful shutdown with ${i} pending messages (${this.queue.length-i} already processing)`),console.log(`Mode: ${o?"fast (parallel)":"sequential"}, timeout: ${t}ms`));let a=Date.now(),c=0,l=0;try{if(o){let f=await this.processAllParallel(t-(Date.now()-a),n);c=f.processed,l=f.failed}else{let f=await this.processInBatches(s,t-(Date.now()-a),n);c=f.processed,l=f.failed}}catch(f){g&&console.error("Error during shutdown processing:",f.message)}let d=Date.now()-a,u=this.queue.length;g&&(console.log(`Shutdown completed in ${d}ms:`),console.log(` - Total: ${i} messages`),console.log(` - Processed: ${c}`),console.log(` - Failed: ${l}`),console.log(` - Remaining: ${u}`)),r({totalMessages:i,processedMessages:c,failedMessages:l,remainingMessages:u,duration:d,allMessagesSent:u===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 t=[...this.queue];this.queue=[];let s=t.map(async a=>{try{return this.onProcessMessage&&await this.onProcessMessage(a),{success:!0,messageId:a.id}}catch(c){return g&&console.warn(`Message ${a.id} processing failed: ${c.message}`),{success:!1,messageId:a.id,error:c}}}),o=new Promise(a=>{setTimeout(()=>a({timedOut:!0}),e)}),r=await Promise.race([Promise.allSettled(s).then(a=>({results:a})),o]);if(r.timedOut)return g&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:t.length};let n=r.results.filter(a=>a.status==="fulfilled"&&a.value?.success).length,i=t.length-n;return{processed:n,failed:i}}async processInBatches(e,t){if(this.queue.length===0)return{processed:0,failed:0};g&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let s=Date.now(),o=0,r=0;for(;this.queue.length>0&&Date.now()-s<t;){let n=this.queue.splice(0,e),i=n.map(async d=>{try{return this.onProcessMessage&&await this.onProcessMessage(d),{success:!0}}catch(u){return g&&console.warn(`Batch message processing failed: ${u.message}`),{success:!1,error:u}}}),c=(await Promise.allSettled(i)).filter(d=>d.status==="fulfilled"&&d.value?.success).length,l=n.length-c;o+=c,r+=l,g&&n.length>0&&console.log(`Batch completed: ${c}/${n.length} successful`),this.queue.length>0&&await new Promise(d=>setTimeout(d,10))}return this.queue.length>0&&(r+=this.queue.length,g&&console.log(`${this.queue.length} messages not processed due to timeout`),this.queue=[]),{processed:o,failed:r}}async forceFlushAndShutdown(e=2e3){this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(e*.4,1e3));let t=this.queue.filter(a=>!a.processing);g&&console.log(`Force flush: attempting to send ${t.length} pending messages within ${e}ms (${this.queue.length-t.length} already processing)`);let s=Date.now(),o=t.map(async a=>{try{return this.onProcessMessage&&Date.now()-s<e?(await this.onProcessMessage(a),{success:!0,messageId:a.id}):{success:!1,messageId:a.id,reason:"timeout"}}catch(c){return{success:!1,messageId:a.id,error:c.message}}}),r=e-(Date.now()-s),n=new Promise(a=>{setTimeout(()=>a({timedOut:!0}),Math.max(100,r))}),i=await Promise.race([Promise.allSettled(o).then(a=>({results:a})),n]);if(t.forEach(a=>{let c=this.queue.findIndex(l=>l.id===a.id);c>-1&&this.queue.splice(c,1)}),this.processing=!1,i.timedOut)return g&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:t.length};{let a=i.results.filter(c=>c.status==="fulfilled"&&c.value.success).length;return g&&console.log(`Force flush completed: ${a}/${t.length} messages sent`),{success:a===t.length,successCount:a,totalCount:t.length,results:i.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,g&&console.log("Force shutdown: Queue cleared")}};_e.exports=ee});var G=m((Es,Ot)=>{Ot.exports={name:"makecoder",version:"2.0.99",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 Me=m((bs,Te)=>{var At=require("http"),Tt=require("https"),{URL:Oe}=require("url"),{version:Mt}=G(),Ae=process.env.CODEV_DEBUG==="True",te=class{constructor(e={}){this.baseUrl=e.baseUrl||"",this.timeout=e.timeout||3e4,this.defaultHeaders={"Content-Type":"application/json","User-Agent":`codev-cli/${Mt}`,...e.headers}}setBaseUrl(e){this.baseUrl=e}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}async post(e,t,s={}){let o=this.resolveUrl(e),r={...this.defaultHeaders,...s.headers};return new Promise((n,i)=>{this.validateRequest(o,t,i);let a=this.serializeData(t,i);if(!a)return;r["Content-Length"]=Buffer.byteLength(a);let c=this.buildRequestOptions(o,"POST",r),l=this.getHttpModule(o);Ae&&console.debug(`HTTP POST to ${o} with data length: ${a.length}`);let d=l.request(c,u=>{this.handleResponse(u,n,i)});this.attachErrorHandlers(d,o,i),d.setTimeout(this.timeout),d.write(a),d.end()})}resolveUrl(e){return e.startsWith("http")?e:`${this.baseUrl}${e.startsWith("/")?"":"/"}${e}`}validateRequest(e,t,s){return!e||typeof e!="string"?(s(new Error(`Invalid URL: ${e}`)),!1):t?!0:(s(new Error("No data provided for HTTP POST")),!1)}serializeData(e,t){try{return typeof e=="string"?e:JSON.stringify(e)}catch(s){return t(new Error(`Failed to serialize data: ${s.message}`)),null}}buildRequestOptions(e,t,s){let o=new Oe(e),r=o.protocol==="https:";return{hostname:o.hostname,port:o.port||(r?443:80),path:o.pathname+o.search,method:t,headers:s}}getHttpModule(e){return new Oe(e).protocol==="https:"?Tt:At}handleResponse(e,t,s){Ae&&console.debug(`HTTP response status: ${e.statusCode}`);let o="";e.on("data",r=>{o+=r}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?t({statusCode:e.statusCode,data:o,headers:e.headers}):s(new Error(`HTTP request returned status ${e.statusCode}: ${o}`))})}attachErrorHandlers(e,t,s){e.on("error",o=>{s(new Error(`HTTP POST request failed: ${o.message}`))}),e.on("timeout",()=>{s(new Error(`HTTP POST request timed out for URL: ${t}`)),e.destroy()})}};Te.exports=te});var Fe=m((vs,qe)=>{var qt=require("crypto"),{URL:Ft}=require("url"),se=class{static generateSignature(e,t,s,o){try{let r=new Ft(e),n=Buffer.from(r.pathname),i=Buffer.from(n),a=t?typeof t=="string"?Buffer.from(t):Buffer.from(JSON.stringify(t)):Buffer.alloc(0),c=Buffer.concat([i,a,Buffer.from(o)]),l=qt.createHmac("sha256",s);return l.update(c),l.digest("hex")}catch(r){throw new Error(`Failed to generate signature: ${r.message}`)}}static validateSignature(e,t,s,o,r){return this.generateSignature(e,t,s,o)===r}static generateTimestamp(){return Date.now().toString()}};qe.exports=se});var Ne=m((xs,Ue)=>{var Ut=Fe(),oe=class{constructor(e={}){this.accessKey=null,this.secretKey=null,this.validateCredentials=e.validateCredentials!==!1}setCredentials(e,t){if(this.validateCredentials&&(!e||!t))throw new Error("Both access key and secret key are required");this.accessKey=e,this.secretKey=t}hasCredentials(){return!!(this.accessKey&&this.secretKey)}generateAuthHeaders(e,t=null){if(!this.hasCredentials())return{};try{return{AUTHORIZATION:`Bearer ${this.accessKey}.${this.secretKey}`}}catch(s){throw new Error(`Failed to generate auth headers: ${s.message}`)}}validateAuthHeaders(e,t,s,o){if(!this.hasCredentials())throw new Error("No credentials available for validation");return Ut.validateSignature(e,t,this.secretKey,s,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};Ue.exports=oe});var Be=m(($s,je)=>{var F=process.env.CODEV_DEBUG==="True",ne=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 F&&console.warn("Received empty session ID"),!1;let t=this.previousSessionId!==null&&this.previousSessionId!==e;return t&&(F&&console.log(`Session switch detected: ${this.previousSessionId} -> ${e}`),this.onSessionSwitch&&this.onSessionSwitch({type:this.terminateSignal,reason:"User switch session",agent:"claude",previousSessionId:this.previousSessionId,newSessionId:e})),this.previousSessionId=this.currentSessionId,this.currentSessionId=e,t}getCurrentSessionId(){return this.currentSessionId}getPreviousSessionId(){return this.previousSessionId}hasActiveSession(){return!!this.currentSessionId}terminateCurrentSession(e="Session terminated",t=null,s=null){if(!this.hasActiveSession())return F&&console.log("No active session to terminate"),null;let o={type:this.terminateSignal,reason:s?`terminated by signal: ${s}`:e,code:t,signal:s,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId};return F&&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(){F&&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()}}};je.exports=ne});var Re=m((Ds,Le)=>{var O=require("fs"),T=require("path"),Nt=require("events"),jt=require("crypto"),S=process.env.CODEV_DEBUG==="True",re=class extends Nt{constructor(e={}){super(),this.watchPaths=e.watchPaths||[],this.excludePatterns=e.excludePatterns||[/node_modules/,/\.git/,/\.DS_Store/,/\.tmp/,/\.log$/,/\.swp$/,/codev\.log/],this.includePatterns=e.includePatterns||[/\.(js|jsx|ts|tsx|py|java|c|cpp|h|hpp|go|rs|rb|php|html|css|scss|sass|less|json|xml|yaml|yml|md|txt)$/],this.watchers=new Map,this.isWatching=!1,this.debounceTimeout=e.debounceTimeout||300,this.pendingChanges=new Map,this.fileContentHashes=new Map,this.enableContentComparison=e.enableContentComparison!==!1,this.onFileChange=e.onFileChange||null}calculateFileHash(e){try{let t=O.readFileSync(e,"utf8");return jt.createHash("sha256").update(t).digest("hex")}catch{return null}}hasContentChanged(e){if(!this.enableContentComparison)return!0;let t=this.calculateFileHash(e),s=this.fileContentHashes.get(e);return t===null?s!==void 0?(this.fileContentHashes.delete(e),!0):!1:s===void 0||t!==s?(this.fileContentHashes.set(e,t),!0):!1}preloadFileHashes(e){if(!(!this.enableContentComparison||!O.existsSync(e)))try{let t=O.readdirSync(e,{withFileTypes:!0});for(let s of t){let o=T.join(e,s.name);s.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):s.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(t){S&&console.warn(`Failed to preload hashes for ${e}:`,t.message)}}shouldExcludeDirectory(e){let t=e.replace(/\\/g,"/");for(let s of this.excludePatterns)if(s.test(t)||s.test(T.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){S&&console.log("FileWatchService is already watching");return}let t=e||this.watchPaths;if(t.length===0){S&&console.log("No watch paths specified");return}this.isWatching=!0;for(let s of t)this.enableContentComparison&&this.preloadFileHashes(s),this.watchDirectory(s);S&&(console.log(`FileWatchService started watching ${t.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,t]of this.watchers)try{t.close(),S&&console.log(`Stopped watching: ${e}`)}catch(s){S&&console.error(`Error stopping watcher for ${e}:`,s.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),S&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!O.existsSync(e)){S&&console.warn(`Watch path does not exist: ${e}`);return}if(!O.statSync(e).isDirectory()){S&&console.warn(`Watch path is not a directory: ${e}`);return}try{let s=O.watch(e,{recursive:!0,persistent:!1},(o,r)=>{if(!r)return;let n=T.join(e,r);this.handleFileChange(o,n,e)});this.watchers.set(e,s),S&&console.log(`Started watching directory: ${e}`),s.on("error",o=>{S&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(s){S&&console.error(`Failed to start watching ${e}:`,s.message)}}handleFileChange(e,t,s){if(!this.shouldWatchFile(t))return;let o=`${e}:${t}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,t,s)},this.debounceTimeout))}processFileChange(e,t,s){if(!this.isWatching)return;let o="modified",r=!1;try{O.statSync(t),r=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(r&&(o==="modified"||o==="created")&&!this.hasContentChanged(t)){S&&console.log(`Ignoring false change for: ${T.relative(s,t)}`);return}!r&&o==="deleted"&&this.fileContentHashes.delete(t);let n={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:t,relativePath:T.relative(s,t),watchPath:s,fileExists:r,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(S&&console.log(`File ${o}: ${n.data.relativePath}`),this.emit("fileChange",n),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(n)}catch(i){S&&console.error("Error in file change callback:",i.message)}}shouldWatchFile(e){let t=T.basename(e),s=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(s)||o.test(t))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(s)||o.test(t))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let t=this.watchPaths.indexOf(e);if(t>-1&&(this.watchPaths.splice(t,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),S&&console.log(`Removed watch path: ${e}`)}catch(s){S&&console.error(`Error removing watch path ${e}:`,s.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};Le.exports=re});var Ge=m((ks,He)=>{var Bt=H(),Lt=require("path"),Ps=require("fs"),_s=require("os"),Rt=ke(),Ht=Me(),Gt=Ne(),Vt=Be(),Kt=Re(),w=process.env.CODEV_DEBUG==="True",ie=class extends Bt{constructor(){super({configDir:".",configFile:".claude.json",defaultModel:"Claude Sonnet 4.5",executablePaths:["cc.mjs","../dist/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 Ht({timeout:1e4}),this.authService=new Gt({validateCredentials:!1}),this.sessionManager=new Vt({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new Rt({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return Lt.join(e,this.config.configDir,".claude","settings.json")}initializeFileWatchService(){if(!process.env.SESSION_ID){w&&console.log("FileWatchService disabled: SESSION_ID environment variable not found");return}try{this.fileWatchService=new Kt({watchPaths:this.getFileWatchPaths(),onFileChange:e=>this.handleFileChange(e),debounceTimeout:300}),w&&console.log("FileWatchService initialized with SESSION_ID:",process.env.SESSION_ID)}catch(e){w&&console.error("Failed to initialize FileWatchService:",e.message)}}getFileWatchPaths(){let e=[],t=process.cwd();e.push(t);let s=process.env.CODEV_WATCH_PATHS;if(s){let o=s.split(",").map(r=>r.trim());e.push(...o)}return e}handleFileChange(e){if(w&&console.log("File change detected:",e.data.relativePath),this.shutdownInProgress)return;let t={message:e,sessionId:e.data.sessionId||process.env.SESSION_ID};this.messageQueue.enqueue(t)}startFileWatching(){this.fileWatchService&&!this.fileWatchService.isWatching&&(this.fileWatchService.startWatching(),w&&console.log("File watching started"))}stopFileWatching(){this.fileWatchService&&this.fileWatchService.isWatching&&(this.fileWatchService.stopWatching(),w&&console.log("File watching stopped"))}onChildMessage(e){e&&e.type==="claude:send-msg"&&this.handleClaudeSendMessage(e.data),super.onChildMessage(e)}handleClaudeSendMessage(e){if(w&&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){w&&console.log("Shutdown in progress, ignoring new message");return}let t=e.sessionId||process.env.SESSION_ID;this.sessionManager.handleSessionSwitch(t),this.messageQueue.enqueue(e)}async processMessage(e){let t=e.data.message,s=e.data.sessionId||process.env.SESSION_ID;if(!s)throw new Error("No session ID available");let o;try{o=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error(`Failed to parse message data: ${i.message}`)}let r=`/conversations/${s}/@append?task_type=codev`,n=this.authService.hasCredentials()?this.authService.generateAuthHeaders(`${this.httpClient.baseUrl}${r}`,o):{};w&&(console.debug("Sending message to:",r),console.debug("Send Message: ",JSON.stringify(o))),e.type!=="CODEV_TERMINATE_SIGNAL"&&(this.sessionManager.currentSessionId=s)}sendTerminationMessage(e){let t={message:e,sessionId:e.sessionId||this.sessionManager.getCurrentSessionId()};this.messageQueue.enqueue(t)}async handleChildProcessExit(e,t){w&&console.log(`Child process exited with code: ${e}, signal: ${t}`),this.stopFileWatching();let s=this.messageQueue.getQueueSize(),o=this.sessionManager.terminateCurrentSession("process exited normally",e,t);if(o&&this.sendTerminationMessage(o),s>0||o){w&&console.log("Starting graceful shutdown of message queue...");try{let r=!t||t==="SIGTERM",n=this.messageQueue.getQueueSize(),i={timeoutMs:r?8e3:3e3,batchSize:Math.min(n,15),fastMode:!r||n>30};w&&console.log("Shutdown options:",i);let a=await this.messageQueue.gracefulShutdown(i);w&&console.log("Message queue shutdown completed:",a),a.failedMessages>0&&w&&console.warn(`Shutdown summary: ${a.processedMessages} sent, ${a.failedMessages} failed, ${a.remainingMessages} remaining`)}catch(r){w&&console.error("Error during message queue shutdown:",r.message)}}}handleChildProcessError(e){w&&console.error(`Child process error: ${e.message}`);let t=this.sessionManager.createErrorTermination(e);t&&this.sendTerminationMessage(t)}async forceFlushMessages(e=3e3){if(this.messageQueue.getQueueSize()===0)return{success:!0,message:"No messages to flush"};w&&console.log(`Force flushing ${this.messageQueue.getQueueSize()} messages...`);try{return await this.messageQueue.forceFlushAndShutdown(e)}catch(t){return w&&console.error("Force flush failed:",t.message),{success:!1,error:t.message}}}async launch(e={}){let{codevServer:t,auth_ak:s=null,auth_sk:o=null}=e;return this.httpClient.setBaseUrl(t),s&&o&&this.authService.setCredentials(s,o),this.startFileWatching(),super.launch(e)}};He.exports=ie});var Ke=m((As,Ve)=>{var zt=H(),Os=require("path"),ae=class extends zt{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"}}}})}};Ve.exports=ae});var We=m((Ts,ze)=>{var Wt=H(),U=require("path"),$=require("fs"),Jt=require("os"),{spawn:Qt}=require("child_process"),V=process.env.CODEV_DEBUG==="True",ce=class extends Wt{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:V?"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 $.existsSync(e)}catch{return!1}}resloveSettingFilePath(e){return U.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,t=0){let s=U.join(Jt.homedir(),this.config.configDir,this.config.configFile),o=U.dirname(s);try{$.existsSync(o)||$.mkdirSync(o,{recursive:!0});let r=`${e}/codex`;if($.existsSync(s)){let n=$.readFileSync(s,"utf8"),i=`openai_base_url = "${r}"`;/^openai_base_url\s*=/m.test(n)?n=n.replace(/^openai_base_url\s*=.*/m,i):n=n.trimEnd()+`
|
|
194
195
|
`+i+`
|
|
195
|
-
`,$.writeFileSync(s,n),
|
|
196
|
+
`,$.writeFileSync(s,n),V&&console.log(`Updated openai_base_url in ${s}`)}else{let n=this.config.defaultConfig||{},i=this.generateTOMLConfig(n,r);$.writeFileSync(s,i),V&&console.log(`Created Codex config file: ${s}`)}t>0&&await new Promise(n=>setTimeout(n,t))}catch(r){console.warn(`Failed to update ${this.config.configFile}: ${r.message}`)}}generateTOMLConfig(e,t){return`model = "${e.model||"gpt-5-codex"}"
|
|
196
197
|
openai_base_url = "${t}"
|
|
197
|
-
`}findExecutablePath(){let e=U.dirname(require.main.filename);for(let t of this.config.executablePaths){let s=U.resolve(e,t);if($.existsSync(s))return s}throw new Error(`Could not find Codex executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}async launch(e={}){let{remainingArgs:t=[],codevServer:s,auth_ak:o=null,auth_sk:r=null}=e;try{if(!this.checkCodexAvailability())throw new Error("Codex executable not found. Please ensure makecoder is properly installed: npm install -g makecoder@latest");await this.ensureConfig(s,1e3);let n=this.findExecutablePath();return
|
|
198
|
-
Terminating ...`),
|
|
199
|
-
Terminating ...`),
|
|
200
|
-
`).map(a=>a.trim());t(i.includes(this.extensionId))}else t(!1)}),o.on("error",n=>{process.env.CODEV_DEBUG&&(console.error("VSCode list extensions error:",n.message),console.error("Error code:",n.code),console.error("Error errno:",n.errno),console.error("Error syscall:",n.syscall)),t(!1)}),setTimeout(()=>{try{o.kill()}catch{}t(!1)},1e4)}catch(s){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode list extensions:",s.message),t(!1)}})}catch{return!1}}async executeVSCodeCommand(e,t={}){let s=await this.resolveCodeCommand();return new Promise(o=>{try{let r={stdio:"ignore",shell:!1,env:{...process.env,PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER}};process.env.CODEV_DEBUG&&console.log(`Spawning: ${s} ${e.join(" ")}`);let n=
|
|
201
|
-
\u{1F4C2} [allow-clone] \u67E5\u627E JSONL \u6587\u4EF6...`),console.log(` \u9879\u76EE\u76EE\u5F55: ${e}`),console.log(` Claude \u9879\u76EE\u540D: ${s}`),console.log(` Claude \u9879\u76EE\u76EE\u5F55: ${o}`)),!
|
|
202
|
-
\u{1F504} [allow-clone] \u5F00\u59CB\u5904\u7406 AI \u751F\u6210\u8BB0\u5F55...`);let a=this.getClaudeJsonlPath(e,!0);if(a){let c=
|
|
203
|
-
\u{1F4E6} [allow-clone] \u6253\u5305 JSONL \u6587\u4EF6...`),console.log(` \u6E90\u6587\u4EF6: ${a}`),console.log(` \u6587\u4EF6\u5927\u5C0F: ${
|
|
198
|
+
`}findExecutablePath(){let e=U.dirname(require.main.filename);for(let t of this.config.executablePaths){let s=U.resolve(e,t);if($.existsSync(s))return s}throw new Error(`Could not find Codex executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}async launch(e={}){let{remainingArgs:t=[],codevServer:s,auth_ak:o=null,auth_sk:r=null}=e;try{if(!this.checkCodexAvailability())throw new Error("Codex executable not found. Please ensure makecoder is properly installed: npm install -g makecoder@latest");await this.ensureConfig(s,1e3);let n=this.findExecutablePath();return V&&console.log(`executablePath: ${n}`),new Promise((i,a)=>{let c={...process.env,...this.config.environmentVariables(s)};o&&(c.CODEV_AUTH_AK=o),r&&(c.CODEV_AUTH_SK=r);let l=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&l.push("--inspect-brk"),l.push(n,...t);let d=Qt("node",l,{env:c,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(d),d.on("error",u=>{console.error(`Failed to start Codex: ${u.message}`),a(u)}),d.on("exit",async(u,f)=>{f&&console.log(`terminated by signal: ${f}`)}),process.on("SIGINT",async()=>{console.log(`
|
|
199
|
+
Terminating ...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
|
|
200
|
+
Terminating ...`),d.kill("SIGTERM"),setTimeout(()=>{d.killed||d.kill("SIGKILL")},8e3)})})}catch(n){throw n}}};ze.exports=ce});var Xe=m((Ms,Ye)=>{var N=require("fs"),Je=require("path"),{spawn:Qe}=require("child_process"),le=class{constructor(){this.extensionId="codev.codev-background";let e=require.main?Je.dirname(require.main.filename):__dirname;this.extensionPath=Je.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(N.existsSync(e))try{return N.accessSync(e,N.constants.F_OK|N.constants.X_OK),this._codeCommand=e,process.env.CODEV_DEBUG&&console.log(`Using AI Studio VSCode path: ${e}`),this._codeCommand}catch(t){process.env.CODEV_DEBUG&&console.log(`AI Studio path exists but not executable: ${t.message}`)}else process.env.CODEV_DEBUG&&console.log(`AI Studio path not found: ${e}`)}try{let{spawn:e}=require("child_process");return new Promise(t=>{let s=e("which",["code"],{stdio:["ignore","pipe","ignore"]}),o="";s.stdout.on("data",r=>{o+=r.toString().trim()}),s.on("close",r=>{r===0&&o?(this._codeCommand=o,process.env.CODEV_DEBUG&&console.log(`Resolved code command path: ${o}`),t(this._codeCommand)):(this._codeCommand="code",t(this._codeCommand))}),s.on("error",()=>{this._codeCommand="code",t(this._codeCommand)}),setTimeout(()=>{s.kill(),this._codeCommand="code",t(this._codeCommand)},3e3)})}catch{return this._codeCommand="code",this._codeCommand}}async shouldInstallExtension(){try{return process.env.IS_AISTUDIO!=="True"?(process.env.CODEV_DEBUG&&console.log("Not in AI Studio environment (IS_AISTUDIO!=True), skipping extension installation"),!1):await this.isVSCodeAvailable()?await this.isExtensionInstalled()?(process.env.CODEV_DEBUG&&console.log(`Extension ${this.extensionId} already installed`),!1):!!N.existsSync(this.extensionPath):(process.env.CODEV_DEBUG&&console.log("VSCode not available, skipping extension installation"),!1)}catch(e){return process.env.CODEV_DEBUG&&console.error(`Error checking extension installation status: ${e.message}`),!1}}async installExtension(){try{return console.log("Installing Codev VSCode extension..."),await this.executeVSCodeCommand(["--install-extension",this.extensionPath])?(console.log("\u2705 Codev VSCode extension installed successfully"),!0):(console.warn("\u274C Failed to install Codev VSCode extension"),!1)}catch(e){return console.warn(`Error installing VSCode extension: ${e.message}`),!1}}async isVSCodeAvailable(){try{let e=process.env.IS_AISTUDIO==="True"?["--help"]:["--version"],t=await this.executeVSCodeCommand(e,{timeout:1e4});if(process.env.CODEV_DEBUG&&(console.log(`VSCode availability check (${e.join(" ")}): ${t?"available":"unavailable"}`),process.env.IS_AISTUDIO==="True")){let{spawn:s}=require("child_process");try{s("which",["code"],{stdio:["ignore","pipe","ignore"]}).stdout.on("data",r=>{console.log("which code:",r.toString().trim())})}catch(o){console.log("which command failed:",o.message)}}return t}catch(e){return process.env.CODEV_DEBUG&&console.error("VSCode availability check error:",e.message),!1}}async isExtensionInstalled(){let e=await this.resolveCodeCommand();try{return new Promise(t=>{try{let s={stdio:["ignore","pipe","ignore"],shell:!1,env:{...process.env,PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER}};process.env.CODEV_DEBUG&&console.log(`Spawning: ${e} --list-extensions`);let o=Qe(e,["--list-extensions"],s),r="";o.stdout.on("data",n=>{r+=n.toString()}),o.on("close",n=>{if(n===0){let i=r.split(`
|
|
201
|
+
`).map(a=>a.trim());t(i.includes(this.extensionId))}else t(!1)}),o.on("error",n=>{process.env.CODEV_DEBUG&&(console.error("VSCode list extensions error:",n.message),console.error("Error code:",n.code),console.error("Error errno:",n.errno),console.error("Error syscall:",n.syscall)),t(!1)}),setTimeout(()=>{try{o.kill()}catch{}t(!1)},1e4)}catch(s){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode list extensions:",s.message),t(!1)}})}catch{return!1}}async executeVSCodeCommand(e,t={}){let s=await this.resolveCodeCommand();return new Promise(o=>{try{let r={stdio:"ignore",shell:!1,env:{...process.env,PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER}};process.env.CODEV_DEBUG&&console.log(`Spawning: ${s} ${e.join(" ")}`);let n=Qe(s,e,r);n.on("close",a=>{o(a===0)}),n.on("error",a=>{process.env.CODEV_DEBUG&&(console.error("VSCode command error:",a.message),console.error("Error code:",a.code),console.error("Error errno:",a.errno),console.error("Error syscall:",a.syscall)),o(!1)});let i=t.timeout||3e4;setTimeout(()=>{try{n.kill()}catch{}o(!1)},i)}catch(r){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode command:",r.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)}}};Ye.exports=le});var tt=m((qs,et)=>{var I=require("fs"),A=require("path"),Yt=require("readline"),{execSync:K}=require("child_process"),Ze=require("os"),de=class{constructor(){this.serverUrl="https://makecoder.com/bigapis/codev/v1/coderpub"}getClaudeJsonlPath(e,t=!1){let s=e.replace(/[/_]/g,"-"),o=A.join(Ze.homedir(),".claude","projects",s);if(t&&(console.log(`
|
|
202
|
+
\u{1F4C2} [allow-clone] \u67E5\u627E JSONL \u6587\u4EF6...`),console.log(` \u9879\u76EE\u76EE\u5F55: ${e}`),console.log(` Claude \u9879\u76EE\u540D: ${s}`),console.log(` Claude \u9879\u76EE\u76EE\u5F55: ${o}`)),!I.existsSync(o))return t&&console.log(" \u274C Claude \u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728"),null;t&&console.log(" \u2713 Claude \u9879\u76EE\u76EE\u5F55\u5B58\u5728");try{let r=I.readdirSync(o).filter(n=>n.endsWith(".jsonl")).map(n=>({name:n,path:A.join(o,n),mtime:I.statSync(A.join(o,n)).mtime,size:I.statSync(A.join(o,n)).size})).sort((n,i)=>i.mtime-n.mtime);return t&&(console.log(` \u627E\u5230 ${r.length} \u4E2A JSONL \u6587\u4EF6:`),r.forEach((n,i)=>{let a=(n.size/1024).toFixed(2),c=n.mtime.toLocaleString(),l=i===0?" <- \u6700\u65B0":"";console.log(` ${i+1}. ${n.name} (${a} KB, ${c})${l}`)})),r.length>0?(t&&console.log(` \u2713 \u9009\u62E9\u6700\u65B0\u6587\u4EF6: ${r[0].name}`),r[0].path):(t&&console.log(" \u274C \u76EE\u5F55\u4E2D\u6CA1\u6709 JSONL \u6587\u4EF6"),null)}catch(r){return t&&console.log(` \u274C \u8BFB\u53D6\u76EE\u5F55\u5931\u8D25: ${r.message}`),null}}async promptForName(){let e=Yt.createInterface({input:process.stdin,output:process.stdout});return new Promise((t,s)=>{e.question("\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0 (name): ",o=>{e.close();let r=o.trim();if(!r){s(new Error("\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A"));return}if(!/^[a-zA-Z0-9_-]+$/.test(r)){s(new Error("\u9879\u76EE\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26"));return}t(r)})})}async createZip(e,t={}){let{allowClone:s=!1}=t,o=Ze.tmpdir(),r=`coder-pub-${Date.now()}.zip`,n=A.join(o,r);try{let i=!1;if(I.existsSync(A.join(e,".git")))try{K(`git archive -o "${n}" 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"),i=!0}catch{console.log("\u26A0\uFE0F git archive \u5931\u8D25\uFF0C\u4F7F\u7528\u666E\u901A zip \u547D\u4EE4")}if(!i){let c=[".git/*","node_modules/*",".env",".env.*","*.log",".DS_Store"].map(l=>`-x "${l}"`).join(" ");K(`zip -r "${n}" . ${c}`,{cwd:e,stdio:"pipe"}),console.log("\u{1F4E6} \u5DF2\u521B\u5EFA\u538B\u7F29\u5305")}if(s){console.log(`
|
|
203
|
+
\u{1F504} [allow-clone] \u5F00\u59CB\u5904\u7406 AI \u751F\u6210\u8BB0\u5F55...`);let a=this.getClaudeJsonlPath(e,!0);if(a){let c=A.join(o,"coder.pub.jsonl"),d=(I.statSync(a).size/1024).toFixed(2);console.log(`
|
|
204
|
+
\u{1F4E6} [allow-clone] \u6253\u5305 JSONL \u6587\u4EF6...`),console.log(` \u6E90\u6587\u4EF6: ${a}`),console.log(` \u6587\u4EF6\u5927\u5C0F: ${d} KB`),console.log(` \u4E34\u65F6\u6587\u4EF6: ${c}`),I.copyFileSync(a,c),console.log(" \u2713 \u5DF2\u590D\u5236\u5230\u4E34\u65F6\u76EE\u5F55"),console.log(` \u76EE\u6807 ZIP: ${n}`),console.log(" \u76EE\u6807\u6587\u4EF6\u540D: coder.pub.jsonl"),K(`zip -j "${n}" "${c}"`,{stdio:"pipe"}),console.log(" \u2713 \u5DF2\u6DFB\u52A0\u5230 ZIP \u5305"),I.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)
|
|
204
205
|
`)}else console.log(`\u26A0\uFE0F [allow-clone] \u672A\u627E\u5230 Claude Code \u751F\u6210\u8BB0\u5F55
|
|
205
|
-
`)}return n}catch(i){throw new Error(`\u521B\u5EFA\u538B\u7F29\u5305\u5931\u8D25: ${i.message}`)}}async upload(e,t,s,o,r,n=!1){let i=r?`${r}/coderpub`:this.serverUrl,a=`${s}.${o}`;console.log("\u{1F4E4} \u6B63\u5728\u4E0A\u4F20\u5230\u670D\u52A1\u5668..."),n&&(console.log(` \u670D\u52A1\u5668\u5730\u5740: ${i}`),console.log(` \u9879\u76EE\u540D\u79F0: ${t}`),console.log(` ZIP \u6587\u4EF6: ${e}`));try{let c=`curl -s -X POST "${i}" -H "Authorization: Bearer ${a}" -F "name=${t}" -F "zip_file=@${e}"`;n&&console.log(" \u6267\u884C\u4E0A\u4F20\u547D\u4EE4...");let l=
|
|
206
|
-
\u{1F680} \u6B63\u5728\u53D1\u5E03\u9879\u76EE: ${n}`),console.log(`\u{1F4C1} \u76EE\u5F55: ${process.cwd()}`),r&&console.log("\u{1F513} allow-clone: \u542F\u7528 (\u5C06\u5305\u542B AI \u751F\u6210\u8BB0\u5F55)"),console.log(),i=await this.createZip(process.cwd(),{allowClone:r});let c=(
|
|
206
|
+
`)}return n}catch(i){throw new Error(`\u521B\u5EFA\u538B\u7F29\u5305\u5931\u8D25: ${i.message}`)}}async upload(e,t,s,o,r,n=!1){let i=r?`${r}/coderpub`:this.serverUrl,a=`${s}.${o}`;console.log("\u{1F4E4} \u6B63\u5728\u4E0A\u4F20\u5230\u670D\u52A1\u5668..."),n&&(console.log(` \u670D\u52A1\u5668\u5730\u5740: ${i}`),console.log(` \u9879\u76EE\u540D\u79F0: ${t}`),console.log(` ZIP \u6587\u4EF6: ${e}`));try{let c=`curl -s -X POST "${i}" -H "Authorization: Bearer ${a}" -F "name=${t}" -F "zip_file=@${e}"`;n&&console.log(" \u6267\u884C\u4E0A\u4F20\u547D\u4EE4...");let l=K(c,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return n&&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{I.existsSync(e)&&I.unlinkSync(e)}catch{}}async publish(e){let{ak:t,sk:s,serverBaseUrl:o,allowClone:r}=e,{name:n}=e,i=null;try{n||(n=await this.promptForName()),console.log(`
|
|
207
|
+
\u{1F680} \u6B63\u5728\u53D1\u5E03\u9879\u76EE: ${n}`),console.log(`\u{1F4C1} \u76EE\u5F55: ${process.cwd()}`),r&&console.log("\u{1F513} allow-clone: \u542F\u7528 (\u5C06\u5305\u542B AI \u751F\u6210\u8BB0\u5F55)"),console.log(),i=await this.createZip(process.cwd(),{allowClone:r});let c=(I.statSync(i).size/(1024*1024)).toFixed(2);console.log(`\u{1F4CA} \u538B\u7F29\u5305\u5927\u5C0F: ${c} MB`),r&&console.log(`
|
|
207
208
|
\u{1F310} [allow-clone] \u5F00\u59CB\u4E0A\u4F20\u5230\u670D\u52A1\u5668...`);let l=await this.upload(i,n,t,s,o,r);return l.code===0?(console.log(`
|
|
208
209
|
\u2705 \u53D1\u5E03\u6210\u529F!`),console.log(`\u{1F4CC} \u7248\u672C: ${l.data.version}`),console.log(`\u{1F310} \u8BBF\u95EE\u5730\u5740: https://${n}.coder.pub/`),0):(console.error(`
|
|
209
210
|
\u274C \u53D1\u5E03\u5931\u8D25: ${l.message||l.reason}`),1)}catch(a){return console.error(`
|
|
210
|
-
\u274C ${a.message}`),1}finally{i&&this.cleanup(i)}}};
|
|
211
|
-
`);for(let a of i)console.log(` ${a.slug.padEnd(20)} ${a.summary}`);s(0)}catch(n){console.error(`\u274C \u89E3\u6790\u54CD\u5E94\u5931\u8D25: ${n.message}`),s(1)}})}).on("error",o=>{console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${o.message}`),s(1)})})}async publish(e,t,s){let{execSync:o}=require("child_process"),r=require("os"),n="global",i="PUBLIC",a=null,c=null,l=null,
|
|
212
|
-
\u2705 \u53D1\u5E03\u6210\u529F!`),console.log(` ${
|
|
213
|
-
\u274C \u53D1\u5E03\u5931\u8D25: ${B.msg||JSON.stringify(B)}`),1}catch(
|
|
214
|
-
\u274C \u53D1\u5E03\u5931\u8D25: ${
|
|
215
|
-
`);for(let l of a){let
|
|
211
|
+
\u274C ${a.message}`),1}finally{i&&this.cleanup(i)}}};et.exports=de});var nt=m((Fs,ot)=>{var st=require("https"),E=require("fs"),b=require("path"),Xt=require("os"),x="https://makecoder.com/skillhub",ue=class{getSkillDirs(){let e=Xt.homedir();return[b.join(e,".claude","skills"),b.join(e,".codex","skills"),b.join(e,".gemini","skills"),b.join(e,".agents","skills")]}fetchWithAuth(e,t){return new Promise((s,o)=>{let r=new URL(e),n={hostname:r.hostname,port:r.port||443,path:r.pathname+r.search,method:"GET",headers:t?{Authorization:`Bearer ${t}`}:{}};st.get(n,i=>{if(i.statusCode>=300&&i.statusCode<400&&i.headers.location)return this.fetchWithAuth(i.headers.location,t).then(s).catch(o);let a="";i.on("data",c=>{a+=c}),i.on("end",()=>s({status:i.statusCode,body:a}))}).on("error",o)})}async handle({skillsSubcommand:e,skillsArg:t,skillsRemainingArgs:s,auth_ak:o,auth_sk:r}){let{execFileSync:n}=require("child_process");if(!e||e==="--help"||e==="-h")return this.showHelp(),0;if(e==="publish")return await this.publish(s||[],o,r);if(e==="unpublish")return await this.unpublish(t,o,r);if(e==="list")return await this.listMySkills(o,r);if(e==="namespaces")return await this.listNamespaces(o,r);if(t&&e!=="search"&&!/^[@a-zA-Z0-9_\-/.]+$/.test(t))return console.error("\u274C skill \u540D\u79F0\u5305\u542B\u975E\u6CD5\u5B57\u7B26"),1;if(e==="search")return t?await this.search(t):(console.error("\u274C \u8BF7\u6307\u5B9A\u641C\u7D22\u5173\u952E\u8BCD"),1);if(e==="remove")return t?this.remove(t):(console.error("\u274C \u8BF7\u6307\u5B9A skill \u540D\u79F0"),1);if((e==="add"||e==="update")&&t&&o&&r)return await this.install(t,`${o}.${r}`);try{let i;if(e==="add"){if(!t)return console.error("\u274C \u8BF7\u6307\u5B9A skill \u540D\u79F0"),1;i=["skills","add",x,"--skill",t,"-g"]}else if(e==="update")i=t?["skills","update","--skill",t,"-g"]:["skills","update","-g"];else return console.error(`\u274C \u672A\u77E5\u5B50\u547D\u4EE4: ${e}`),1;return n("npx",i,{stdio:"inherit"}),0}catch(i){return console.error(`\u274C \u6267\u884C\u5931\u8D25: ${i.message}`),1}}async install(e,t){let s=x.replace(/\/$/,"");console.log(`\u{1F50D} \u6B63\u5728\u4ECE ${x} \u67E5\u627E skill...`);let o;try{let c=await this.fetchWithAuth(`${s}/.well-known/agent-skills/index.json?skill=${encodeURIComponent(e)}`,t);if(c.status===404)return console.error(`\u274C \u672A\u627E\u5230 skill: ${e}`),1;if(c.status!==200)return console.error(`\u274C \u65E0\u6CD5\u83B7\u53D6 skill \u4FE1\u606F (HTTP ${c.status})`),1;o=JSON.parse(c.body)}catch(c){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${c.message}`),1}let r=(o.skills||[])[0];if(!r)return console.error(`\u274C \u672A\u627E\u5230 skill: ${e}`),1;let n=Array.from(new Set(["SKILL.md",...r.files||[]])),i=`${s}/.well-known/agent-skills/${r.name}`,a={};for(let c of n)try{let l=await this.fetchWithAuth(`${i}/${c}`,t);if(l.status!==200){console.warn(`\u26A0\uFE0F \u8DF3\u8FC7 ${c} (HTTP ${l.status})`);continue}a[c]=l.body}catch(l){console.warn(`\u26A0\uFE0F \u4E0B\u8F7D ${c} \u5931\u8D25: ${l.message}`)}console.log(`\u{1F4E6} \u6B63\u5728\u5B89\u88C5 ${r.name}...`);for(let c of this.getSkillDirs()){let l=b.join(c,r.name);E.mkdirSync(l,{recursive:!0});for(let[d,u]of Object.entries(a)){let f=b.join(l,d);E.mkdirSync(b.dirname(f),{recursive:!0}),E.writeFileSync(f,u,"utf8")}}return console.log(`\u2705 ${r.name} \u5B89\u88C5\u5B8C\u6210`),0}remove(e){let t=!1;for(let s of this.getSkillDirs()){let o=b.join(s,e);E.existsSync(o)&&(E.rmSync(o,{recursive:!0,force:!0}),console.log(` \u{1F5D1}\uFE0F ${o}`),t=!0)}return t?(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 t=`${x}/api/web/skills?q=${encodeURIComponent(e)}&sort=relevance&page=0&size=12`;return new Promise(s=>{st.get(t,o=>{let r="";o.on("data",n=>{r+=n}),o.on("end",()=>{try{let n=JSON.parse(r);if(n.code!==0)return console.error(`\u274C \u67E5\u8BE2\u5931\u8D25: ${n.msg}`),s(1);let i=n.data.items;if(i.length===0)return console.log(`\u6CA1\u6709\u627E\u5230\u4E0E "${e}" \u76F8\u5173\u7684 skill`),s(0);console.log(`\u627E\u5230 ${n.data.total} \u4E2A\u7ED3\u679C:
|
|
212
|
+
`);for(let a of i)console.log(` ${a.slug.padEnd(20)} ${a.summary}`);s(0)}catch(n){console.error(`\u274C \u89E3\u6790\u54CD\u5E94\u5931\u8D25: ${n.message}`),s(1)}})}).on("error",o=>{console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${o.message}`),s(1)})})}async publish(e,t,s){let{execSync:o}=require("child_process"),r=require("os"),n="global",i="PUBLIC",a=null,c=null,l=null,d=null;for(let p=0;p<e.length;p++)if(e[p]==="--namespace"||e[p]==="-n")n=e[++p];else if(e[p]==="--visibility"||e[p]==="-v")i=e[++p];else if(e[p]==="--meta-data"){let y=e[++p];try{JSON.parse(y)}catch(v){return console.error(`\u274C --meta-data \u4E0D\u662F\u5408\u6CD5\u7684 JSON\uFF1A${v.message}`),1}a=y}else if(!e[p].startsWith("-")){let y=e[p];E.existsSync(y)&&E.statSync(y).isDirectory()?d=y:c=y}if(!t||!s)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let u=n.startsWith("@")?n.slice(1):n;u==="global"||(i="NAMESPACE_ONLY");let C=["PUBLIC","NAMESPACE_ONLY","PRIVATE"];if(!C.includes(i))return console.error(`\u274C visibility \u5FC5\u987B\u662F: ${C.join(", ")}`),1;if(c){if(!E.existsSync(c))return console.error(`\u274C \u6587\u4EF6\u4E0D\u5B58\u5728: ${c}`),1}else{let p=d?b.resolve(d):process.cwd();l=b.join(r.tmpdir(),`skill-pub-${Date.now()}.zip`),console.log(`\u{1F4E6} \u6B63\u5728\u6253\u5305 ${p}...`);try{E.existsSync(b.join(p,".git"))?(o(`git archive -o "${l}" HEAD`,{cwd:p,stdio:"pipe"}),console.log(" \u4F7F\u7528 git archive\uFF08\u5DF2\u6392\u9664 .gitignore \u6587\u4EF6\uFF09")):o(`zip -r "${l}" . -x ".git/*" -x "node_modules/*" -x ".env" -x "*.log"`,{cwd:p,stdio:"pipe"})}catch(y){return console.error(`\u274C \u6253\u5305\u5931\u8D25: ${y.message}`),1}c=l}let P=`${x}/api/v1/skills/${encodeURIComponent(u)}/publish?visibility=${encodeURIComponent(i)}`,M=`${t}.${s}`;console.log(`\u{1F680} \u6B63\u5728\u53D1\u5E03\u5230 ${x}...`),console.log(` namespace: ${u}`),console.log(` visibility: ${i}`);try{let p=a?` -F "meta_data=${a.replace(/"/g,'\\"')}"`:"",y=`curl -s -X POST "${P}" -H "Authorization: Bearer ${M}" -F "file=@${c}"${p}`,v=o(y,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),B=JSON.parse(v);if(B.code===0){let L=B.data;return console.log(`
|
|
213
|
+
\u2705 \u53D1\u5E03\u6210\u529F!`),console.log(` ${L.namespace}/${L.slug}@${L.version}`),L.status==="PUBLISHED"?console.log(" \u72B6\u6001: \u5DF2\u53D1\u5E03"):console.log(" \u72B6\u6001: \u5F85\u5BA1\u6838"),0}else return console.error(`
|
|
214
|
+
\u274C \u53D1\u5E03\u5931\u8D25: ${B.msg||JSON.stringify(B)}`),1}catch(p){let y=p.stdout;if(y)try{let v=JSON.parse(y);return console.error(`
|
|
215
|
+
\u274C \u53D1\u5E03\u5931\u8D25: ${v.msg||y}`),1}catch{}return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${p.message}`),1}finally{l&&E.existsSync(l)&&E.unlinkSync(l)}}async unpublish(e,t,s){let{execSync:o}=require("child_process");if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A skill: coder skills unpublish <namespace>/<slug>"),1;if(!t||!s)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let r=e.split("/");if(r.length!==2||!r[0]||!r[1])return console.error("\u274C \u683C\u5F0F\u9519\u8BEF\uFF0C\u5E94\u4E3A <namespace>/<slug>\uFF0C\u4F8B\u5982: global/my-skill"),1;let[n,i]=r,a=n.startsWith("@")?n.slice(1):n,c=`${x}/api/v1/skills/${encodeURIComponent(a)}/${encodeURIComponent(i)}`,l=`${t}.${s}`;console.log(`\u{1F5D1}\uFE0F \u6B63\u5728\u4E0B\u67B6 ${a}/${i}...`);try{let d=o(`curl -s -X DELETE "${c}" -H "Authorization: Bearer ${l}"`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),u=JSON.parse(d);return u.code===0?(console.log(`\u2705 \u5DF2\u4E0B\u67B6 ${a}/${i}`),0):(console.error(`\u274C \u4E0B\u67B6\u5931\u8D25: ${u.msg||JSON.stringify(u)}`),1)}catch(d){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${d.message}`),1}}async listMySkills(e,t){let{execSync:s}=require("child_process");if(!e||!t)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let o=`${x}/api/v1/me/skills?size=50`,r=`${e}.${t}`;try{let n=s(`curl -s "${o}" -H "Authorization: Bearer ${r}"`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),i=JSON.parse(n);if(i.code!==0)return console.error(`\u274C \u83B7\u53D6\u5931\u8D25: ${i.msg}`),1;let a=i.data?.items||[],c=i.data?.total||0;if(a.length===0)return console.log("\u6682\u65E0\u5DF2\u53D1\u5E03\u7684 skill"),0;console.log(`\u5171 ${c} \u4E2A skill:
|
|
216
|
+
`);for(let l of a){let d=`${l.namespace}/${l.slug}`.padEnd(36),u=`\u2B50 ${l.starCount??0}`.padEnd(8),f=`\u2193 ${l.downloadCount??0}`.padEnd(10);console.log(` ${d} ${u} ${f} [${l.status}]`),l.displayName&&l.displayName!==l.slug&&console.log(` ${"".padEnd(36)} ${l.displayName}`)}return 0}catch(n){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${n.message}`),1}}async listNamespaces(e,t){let{execSync:s}=require("child_process");if(!e||!t)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let o=`${x}/api/v1/me/namespaces`,r=`${e}.${t}`;try{let n=s(`curl -s "${o}" -H "Authorization: Bearer ${r}"`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}),i=JSON.parse(n);if(i.code!==0)return console.error(`\u274C \u83B7\u53D6\u5931\u8D25: ${i.msg}`),1;let a=i.data||[];if(a.length===0)return console.log("\u6682\u65E0\u547D\u540D\u7A7A\u95F4"),0;console.log(`\u5171 ${a.length} \u4E2A\u547D\u540D\u7A7A\u95F4:
|
|
216
217
|
`);for(let c of a){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(n){return console.error(`\u274C \u8BF7\u6C42\u5931\u8D25: ${n.message}`),1}}showHelp(){console.log(`
|
|
217
218
|
coder skills \u2014 \u7BA1\u7406 Claude Code skills
|
|
218
219
|
|
|
@@ -245,11 +246,11 @@ EXAMPLES:
|
|
|
245
246
|
coder skills publish --meta-data '{"category":"tool"}' ./my-skill-dir
|
|
246
247
|
coder skills unpublish global/my-skill
|
|
247
248
|
coder skills namespaces
|
|
248
|
-
`)}};
|
|
249
|
+
`)}};ot.exports=ue});var at=m((Us,it)=>{var Zt=require("https"),z="https://makecoder.com/wiki",es=`${z}/api`,D=h=>`${z}/doc/${h}`,rt=h=>`${z}/collection/${h}`,he=class{getToken(e,t){return e&&t?`${e}.${t}`:null}post(e,t,s){return new Promise((o,r)=>{let n=JSON.stringify(t),i=new URL(`${es}/${e}`),a={hostname:i.hostname,port:i.port||443,path:i.pathname,method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(n),Authorization:`Bearer ${s}`}},c=Zt.request(a,l=>{let d="";l.on("data",u=>d+=u),l.on("end",()=>o({status:l.statusCode,body:d}))});c.on("error",r),c.write(n),c.end()})}parseJson(e){try{return JSON.parse(e)}catch{return null}}async handle({wikiSubcommand:e,wikiArg:t,wikiRemainingArgs:s,auth_ak:o,auth_sk:r}){if(!e||e==="--help"||e==="-h")return this.showHelp(),0;let n=this.getToken(o,r);if(!n)return console.error("\u274C \u7F3A\u5C11 API Key\uFF0C\u8BF7\u5148\u767B\u5F55: coder login"),1;let i=s||[];return e==="list"?await this.list(t,i,n):e==="create-collection"?await this.createCollection(i,n):e==="update-collection"?await this.updateCollection(t,i,n):e==="delete-collection"?await this.deleteCollection(t,n):e==="get"?await this.get(t,n):e==="publish"?await this.publish(t,i,n):e==="update"?await this.update(i,n):e==="delete"?await this.delete(t,i,n):e==="move"?await this.move(i,n):e==="archive"?await this.archive(t,n):e==="restore"?await this.restore(t,n):e==="drafts"?await this.drafts(n):e==="recent"?await this.recent(n):e==="search"?t?await this.search([t,...i],n):(console.error("\u274C \u8BF7\u6307\u5B9A\u641C\u7D22\u5173\u952E\u8BCD"),1):e==="stars"?await this.stars(n):e==="star"?await this.star(t,i,n):e==="unstar"?await this.unstar(t,n):e==="pins"?await this.pins(t,n):e==="pin"?await this.pin(t,i,n):e==="unpin"?await this.unpin(t,n):e==="comments"?await this.comments(t,n):e==="comment"?await this.comment(t,i,n):(console.error(`\u274C \u672A\u77E5\u5B50\u547D\u4EE4: ${e}`),this.showHelp(),1)}async list(e,t,s){let o=t.indexOf("-d"),r=o!==-1?parseInt(t[o+1],10):null;if(!e){let c=await this.post("collections.list",{limit:100,offset:0},s),l=this.parseJson(c.body);if(!l?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",c.body),1;let d=l.data.collections||l.data||[];return d.length?(this.printTable(d.map(u=>({collectionId:u.id,\u76EE\u5F55\u540D\u79F0:u.name,URL:rt(u.urlId||u.id)}))),0):(console.log("\u6682\u65E0\u76EE\u5F55"),0)}if(r===null){let c=await this.post("documents.list",{collectionId:e,sort:"updatedAt",direction:"DESC"},s),l=this.parseJson(c.body);if(!l?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",c.body),1;let d=l.data.documents||l.data||[];return d.length?(this.printTable(d.map(u=>({docId:u.id,\u6807\u9898:u.title,URL:D(u.urlId||u.id)}))),0):(console.log("\u6682\u65E0\u6587\u6863"),0)}let n=await this.post("collections.documents",{id:e},s),i=this.parseJson(n.body);if(!i?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",n.body),1;let a=r===-1?1/0:r;return this.printTree(i.data,"",a,0),0}printTree(e,t,s,o){if(Array.isArray(e))for(let r=0;r<e.length;r++){let n=e[r],i=r===e.length-1,a=i?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",c=n.url?`${z}${n.url}`:D(n.id);console.log(`${t}${a}${n.title||n.id} \x1B[90m${c}\x1B[0m`),n.children?.length&&o+1<s&&this.printTree(n.children,t+(i?" ":"\u2502 "),s,o+1)}}printTable(e){if(!e.length)return;let t=Object.keys(e[0]),s=i=>[...String(i)].reduce((a,c)=>a+(c.charCodeAt(0)>127?2:1),0),o=(i,a)=>i+" ".repeat(Math.max(0,a-s(i))),r=t.map(i=>Math.max(s(i),...e.map(a=>s(a[i]||"")))),n=r.map(i=>"-".repeat(i)).join("-+-");console.log(t.map((i,a)=>o(i,r[a])).join(" | ")),console.log(n);for(let i of e)console.log(t.map((a,c)=>o(String(i[a]||""),r[c])).join(" | "))}async createCollection(e,t){let s=e.indexOf("--permission"),o="read_write";s!==-1&&(o=e[s+1]||"read_write",e.splice(s,2));let r=e[0];if(!r)return console.error("\u274C \u8BF7\u6307\u5B9A\u76EE\u5F55\u540D\u79F0"),1;let n=e.slice(1).join(" "),i={name:r,description:n,sharing:!0};o==="null"||o==="none"?i.permission=null:i.permission=o;let a=await this.post("collections.create",i,t),c=this.parseJson(a.body);return c?.data?(console.log(`\u2705 \u76EE\u5F55\u5DF2\u521B\u5EFA: ${c.data.id} \u2014 ${c.data.name}`),0):(console.error("\u274C \u521B\u5EFA\u5931\u8D25:",a.body),1)}async updateCollection(e,t,s){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u76EE\u5F55 ID"),1;let o={id:e},r=t.indexOf("--name");r!==-1&&(o.name=t[r+1]);let n=t.indexOf("--description");n!==-1&&(o.description=t[n+1]);let i=t.indexOf("--permission");if(i!==-1){let u=t[i+1];o.permission=u==="null"||u==="none"?null:u}let a=t.indexOf("--color");a!==-1&&(o.color=t[a+1]);let c=t.indexOf("--sharing");if(c!==-1&&(o.sharing=t[c+1]==="true"),Object.keys(o).length<=1)return console.error("\u274C \u8BF7\u81F3\u5C11\u6307\u5B9A\u4E00\u4E2A\u8981\u66F4\u65B0\u7684\u5B57\u6BB5\uFF08--name, --description, --permission, --color, --sharing\uFF09"),1;let l=await this.post("collections.update",o,s),d=this.parseJson(l.body);return d?.data?(console.log(`\u2705 \u76EE\u5F55\u5DF2\u66F4\u65B0: ${d.data.id} \u2014 ${d.data.name}`),0):(console.error("\u274C \u66F4\u65B0\u76EE\u5F55\u5931\u8D25:",l.body),1)}async deleteCollection(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u76EE\u5F55 ID"),1;let s=await this.post("collections.delete",{id:e},t);return this.parseJson(s.body)?.ok===!1||s.status>=400?(console.error("\u274C \u5220\u9664\u76EE\u5F55\u5931\u8D25:",s.body),1):(console.log("\u2705 \u76EE\u5F55\u5DF2\u5220\u9664"),0)}async get(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863 ID"),1;let s=await this.post("documents.info",{id:e},t),o=this.parseJson(s.body);if(!o?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",s.body),1;let r=o.data;return console.log(`\u6807\u9898: ${r.title}`),console.log(`ID: ${r.id}`),console.log(`\u76EE\u5F55: ${r.collectionId}`),console.log(`\u66F4\u65B0: ${r.updatedAt}`),r.text&&console.log(`
|
|
249
250
|
${r.text}`),0}async publish(e,t,s){let o=require("fs"),r=require("path");if(!e)return console.error(`\u274C \u7528\u6CD5: wiki publish <collectionId> <title> [text]
|
|
250
|
-
wiki publish <collectionId> --file <path> [--parent <parentDocId>]`),1;let n,i,a,c=t.indexOf("--file"),l=t.indexOf("--parent");if(l!==-1&&(a=t[l+1]),c!==-1){let
|
|
251
|
-
${D(
|
|
252
|
-
`),this.printTable(n.map(i=>{let a=i.document||i;return{docId:a.id,\u6807\u9898:a.title,URL:D(a.urlId||a.id)}})),0):(console.log(`\u6CA1\u6709\u627E\u5230\u4E0E "${s}" \u76F8\u5173\u7684\u6587\u6863`),0)}async stars(e){let t=await this.post("stars.list",{},e),s=this.parseJson(t.body);if(!s?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",t.body),1;let o=s.data.stars||s.data||[];return o.length?(this.printTable(o.map(r=>({starId:r.id,\u6807\u9898:r.document?.title||r.collection?.name||"",URL:r.document?D(r.document.urlId||r.document.id):r.collection?
|
|
251
|
+
wiki publish <collectionId> --file <path> [--parent <parentDocId>]`),1;let n,i,a,c=t.indexOf("--file"),l=t.indexOf("--parent");if(l!==-1&&(a=t[l+1]),c!==-1){let p=t[c+1];if(!p)return console.error("\u274C \u8BF7\u6307\u5B9A --file \u8DEF\u5F84"),1;let y=r.resolve(p);if(!o.existsSync(y))return console.error(`\u274C \u6587\u4EF6\u4E0D\u5B58\u5728: ${y}`),1;i=o.readFileSync(y,"utf8");let v=i.match(/^#\s+(.+)/m);if(!v)return console.error("\u274C \u6587\u4EF6\u7F3A\u5C11 H1 \u6807\u9898\uFF08# \u6807\u9898\uFF09\uFF0C\u8BF7\u6DFB\u52A0\u540E\u91CD\u8BD5"),1;n=v[1].trim(),i=i.replace(/^#\s+.+\n?/,"").trimStart()}else if(n=t[0],i=t.slice(1).join(" "),!n)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863\u6807\u9898"),1;let d={collectionId:e,title:n,text:"",publish:!0};a&&(d.parentDocumentId=a);let u=await this.post("documents.create",d,s),f=this.parseJson(u.body);if(!f?.data)return console.error("\u274C \u521B\u5EFA\u6587\u6863\u5931\u8D25:",u.body),1;let C=f.data.id;console.log(` \u521B\u5EFA\u6587\u6863: ${C}`);let P=await this.post("documents.update",{id:C,title:n,text:i,publish:!0},s),M=this.parseJson(P.body);return M?.data?(console.log(`\u2705 \u6587\u6863\u5DF2\u53D1\u5E03: ${M.data.title}
|
|
252
|
+
${D(M.data.urlId||C)}`),0):(console.error("\u274C \u66F4\u65B0\u5185\u5BB9\u5931\u8D25:",P.body),1)}async update(e,t){let s=require("fs"),o=require("path"),r=e[0];if(!r)return console.error("\u274C \u7528\u6CD5: wiki update <docId> <title> [text] | <docId> --file <path>"),1;let n,i,a=e.indexOf("--file");if(a!==-1){let u=e[a+1];if(!u)return console.error("\u274C \u8BF7\u6307\u5B9A --file \u8DEF\u5F84"),1;let f=o.resolve(u);if(!s.existsSync(f))return console.error(`\u274C \u6587\u4EF6\u4E0D\u5B58\u5728: ${f}`),1;i=s.readFileSync(f,"utf8");let C=i.match(/^#\s+(.+)/m);if(!C)return console.error("\u274C \u6587\u4EF6\u7F3A\u5C11 H1 \u6807\u9898\uFF08# \u6807\u9898\uFF09\uFF0C\u8BF7\u6DFB\u52A0\u540E\u91CD\u8BD5"),1;n=C[1].trim(),i=i.replace(/^#\s+.+\n?/,"").trimStart()}else if(n=e[1],i=e.slice(2).join(" "),!n)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863\u6807\u9898"),1;let c={id:r,title:n,publish:!0};i&&(c.text=i);let l=await this.post("documents.update",c,t),d=this.parseJson(l.body);return d?.data?(console.log(`\u2705 \u6587\u6863\u5DF2\u66F4\u65B0: ${d.data.title}`),0):(console.error("\u274C \u66F4\u65B0\u5931\u8D25:",l.body),1)}async delete(e,t,s){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863 ID"),1;let o=t.includes("--permanent"),r=await this.post("documents.delete",{id:e,...o?{permanent:!0}:{}},s);return this.parseJson(r.body)?.ok===!1||r.status>=400?(console.error("\u274C \u5220\u9664\u5931\u8D25:",r.body),1):(console.log(`\u2705 \u6587\u6863\u5DF2${o?"\u6C38\u4E45":""}\u5220\u9664`),0)}async move(e,t){let[s,o,r]=e;if(!s||!o)return console.error("\u274C \u7528\u6CD5: wiki move <docId> <collectionId> [parentDocId]"),1;let n={id:s,collectionId:o};r&&(n.parentDocumentId=r);let i=await this.post("documents.move",n,t);return this.parseJson(i.body)?.data?(console.log("\u2705 \u6587\u6863\u5DF2\u79FB\u52A8"),0):(console.error("\u274C \u79FB\u52A8\u5931\u8D25:",i.body),1)}async archive(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863 ID"),1;let s=await this.post("documents.archive",{id:e},t);return this.parseJson(s.body)?.data?(console.log("\u2705 \u6587\u6863\u5DF2\u5F52\u6863"),0):(console.error("\u274C \u5F52\u6863\u5931\u8D25:",s.body),1)}async restore(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863 ID"),1;let s=await this.post("documents.restore",{id:e},t);return this.parseJson(s.body)?.data?(console.log("\u2705 \u6587\u6863\u5DF2\u6062\u590D"),0):(console.error("\u274C \u6062\u590D\u5931\u8D25:",s.body),1)}async drafts(e){let t=await this.post("documents.drafts",{sort:"updatedAt",direction:"DESC"},e),s=this.parseJson(t.body);if(!s?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",t.body),1;let o=s.data.documents||s.data||[];return o.length?(this.printTable(o.map(r=>({ID:r.id,\u6807\u9898:r.title,URL:D(r.urlId||r.id)}))),0):(console.log("\u6682\u65E0\u8349\u7A3F"),0)}async recent(e){let t=await this.post("documents.viewed",{sort:"updatedAt",direction:"DESC"},e),s=this.parseJson(t.body);if(!s?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",t.body),1;let o=s.data.documents||s.data||[];return o.length?(this.printTable(o.map(r=>({ID:r.id,\u6807\u9898:r.title,URL:D(r.urlId||r.id)}))),0):(console.log("\u6682\u65E0\u6D4F\u89C8\u8BB0\u5F55"),0)}async search(e,t){let s=e.join(" "),o=await this.post("documents.search",{query:s,snippetMinWords:20,snippetMaxWords:30},t),r=this.parseJson(o.body);if(!r?.data)return console.error("\u274C \u641C\u7D22\u5931\u8D25:",o.body),1;let n=r.data||[];return n.length?(console.log(`\u627E\u5230 ${n.length} \u4E2A\u7ED3\u679C:
|
|
253
|
+
`),this.printTable(n.map(i=>{let a=i.document||i;return{docId:a.id,\u6807\u9898:a.title,URL:D(a.urlId||a.id)}})),0):(console.log(`\u6CA1\u6709\u627E\u5230\u4E0E "${s}" \u76F8\u5173\u7684\u6587\u6863`),0)}async stars(e){let t=await this.post("stars.list",{},e),s=this.parseJson(t.body);if(!s?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",t.body),1;let o=s.data.stars||s.data||[];return o.length?(this.printTable(o.map(r=>({starId:r.id,\u6807\u9898:r.document?.title||r.collection?.name||"",URL:r.document?D(r.document.urlId||r.document.id):r.collection?rt(r.collection.urlId||r.collection.id):""}))),0):(console.log("\u6682\u65E0\u6536\u85CF"),0)}async star(e,t,s){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863\u6216\u76EE\u5F55 ID"),1;let r=t.includes("--collection")?{collectionId:e}:{documentId:e},n=await this.post("stars.create",r,s);return this.parseJson(n.body)?.data?(console.log("\u2705 \u5DF2\u6536\u85CF"),0):(console.error("\u274C \u6536\u85CF\u5931\u8D25:",n.body),1)}async unstar(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6536\u85CF ID"),1;let s=await this.post("stars.delete",{id:e},t);return s.status>=400?(console.error("\u274C \u53D6\u6D88\u6536\u85CF\u5931\u8D25:",s.body),1):(console.log("\u2705 \u5DF2\u53D6\u6D88\u6536\u85CF"),0)}async pins(e,t){let s=e?{collectionId:e}:{},o=await this.post("pins.list",s,t),r=this.parseJson(o.body);if(!r?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",o.body),1;let n=r.data.pins||r.data||[];return n.length?(this.printTable(n.map(i=>({pinId:i.id,\u6807\u9898:i.document?.title||i.documentId,URL:D(i.document?.urlId||i.documentId)}))),0):(console.log("\u6682\u65E0\u7F6E\u9876"),0)}async pin(e,t,s){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863 ID"),1;let o={documentId:e,...t[0]?{collectionId:t[0]}:{}},r=await this.post("pins.create",o,s),n=this.parseJson(r.body);return n?.data?(console.log(`\u2705 \u5DF2\u7F6E\u9876: ${n.data.id}`),0):(console.error("\u274C \u7F6E\u9876\u5931\u8D25:",r.body),1)}async unpin(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u7F6E\u9876 ID"),1;let s=await this.post("pins.delete",{id:e},t);return s.status>=400?(console.error("\u274C \u53D6\u6D88\u7F6E\u9876\u5931\u8D25:",s.body),1):(console.log("\u2705 \u5DF2\u53D6\u6D88\u7F6E\u9876"),0)}async comments(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6587\u6863 ID"),1;let s=await this.post("comments.list",{documentId:e,sort:"createdAt",direction:"ASC"},t),o=this.parseJson(s.body);if(!o?.data)return console.error("\u274C \u8BF7\u6C42\u5931\u8D25:",s.body),1;let r=o.data.comments||o.data||[];if(!r.length)return console.log("\u6682\u65E0\u8BC4\u8BBA"),0;for(let n of r){let i=this.extractCommentText(n.data);console.log(` [${n.id}] ${n.createdBy?.name||"?"}: ${i}`)}return 0}async comment(e,t,s){let o=t.join(" ");if(!e||!o)return console.error("\u274C \u7528\u6CD5: wiki comment <docId> <text>"),1;let r={type:"doc",content:[{type:"paragraph",content:[{type:"text",text:o}]}]},n=await this.post("comments.create",{documentId:e,data:r},s),i=this.parseJson(n.body);return i?.data?(console.log(`\u2705 \u8BC4\u8BBA\u5DF2\u53D1\u5E03: ${i.data.id}`),0):(console.error("\u274C \u8BC4\u8BBA\u5931\u8D25:",n.body),1)}extractCommentText(e){return e?.content?e.content.flatMap(t=>t.content||[]).filter(t=>t.type==="text").map(t=>t.text).join(""):""}showHelp(){console.log(`
|
|
253
254
|
coder wiki \u2014 \u7BA1\u7406 MakeCoder \u77E5\u8BC6\u5E93
|
|
254
255
|
|
|
255
256
|
USAGE:
|
|
@@ -298,12 +299,48 @@ EXAMPLES:
|
|
|
298
299
|
coder wiki publish <collectionId> --file ./doc.md
|
|
299
300
|
coder wiki search "\u5173\u952E\u8BCD"
|
|
300
301
|
coder wiki comment <docId> "\u5F88\u6709\u5E2E\u52A9\uFF01"
|
|
301
|
-
`)}};
|
|
302
|
+
`)}};it.exports=he});var ht=m((Ns,ut)=>{var j=require("fs"),J=require("path"),dt=require("os"),ts=require("readline"),W=J.join(dt.homedir(),".coder","config.json"),ss=process.env.MCP_CHANNEL_DIR||J.join(dt.homedir(),".claude","mcp-channel"),ct=["wecom"];function lt(h){return!h||h.length<=8?"****":h.slice(0,3)+"****"+h.slice(-3)}var fe=class{load(){try{return JSON.parse(j.readFileSync(W,"utf8"))}catch{return{}}}save(e){let t=J.dirname(W);j.existsSync(t)||j.mkdirSync(t,{recursive:!0}),j.writeFileSync(W,JSON.stringify(e,null,2)+`
|
|
303
|
+
`)}getChannels(){return this.load().channels??[]}saveChannels(e){let t=this.load();t.channels=e,this.save(t)}async handle({channelSubcommand:e,channelArg:t,channelRemainingArgs:s,remainingArgs:o,claudeLauncher:r,parsedArgs:n}){return e?e==="--help"||e==="-h"?(this.showHelp(),0):e==="list"?this.list(t):e==="show"?this.show(t):e==="add"?this.add(t,s||[]):e==="remove"?this.remove(t):e==="update"?this.update(t,s||[]):(console.error(`\u274C \u672A\u77E5\u5B50\u547D\u4EE4: ${e}`),this.showHelp(),1):this.launch(s||[],r,n)}async launch(e,t,s){let o=this.getChannels().filter(d=>d.enabled!==!1);if(!o.length)return console.error("\u274C \u6CA1\u6709\u5DF2\u542F\u7528\u7684\u6E20\u9053\uFF0C\u8BF7\u5148\u7ED1\u5B9A\u6E20\u9053\uFF1A"),console.error(" coder channel add wecom --bot-id <botId> --secret <secret>"),1;let r=null,n=e.indexOf("--channel-id");n!==-1&&(r=e[n+1],e=e.filter((d,u)=>u!==n&&u!==n+1));let i;if(r){if(i=o.find(d=>d.id===r),!i)return console.error(`\u274C \u6E20\u9053\u4E0D\u5B58\u5728: ${r}`),1}else if(o.length===1)i=o[0];else if(i=await this.promptSelectChannel(o),!i)return 1;let a=J.join(ss,i.type);if(!j.existsSync(a))return console.error(`\u274C MCP \u76EE\u5F55\u4E0D\u5B58\u5728: ${a}`),1;let c=["--plugin-dir",a,"--dangerously-load-development-channels",`plugin:${i.type}@${i.type}`],l={WECOM_CHANNEL_FILE:W,WECOM_CHANNEL_KEY:i.id};return i.botId&&(l.WECOM_BOT_ID=i.botId),i.secret&&(l.WECOM_BOT_SECRET=i.secret),s.remainingArgs=[...c,...e,...s.remainingArgs||[]],s.extraEnv={...s.extraEnv||{},...l},await t.launch(s)}async promptSelectChannel(e){console.log(`
|
|
304
|
+
\u8BF7\u9009\u62E9\u8981\u542F\u52A8\u7684\u6E20\u9053\uFF1A
|
|
305
|
+
`),e.forEach((s,o)=>{let r=s.botId?lt(s.botId):"(\u672A\u914D\u7F6E)";console.log(` ${o+1}. [${s.type}] ${s.name||s.id} botId: ${r}`)}),console.log("");let t=ts.createInterface({input:process.stdin,output:process.stdout});return new Promise(s=>{t.question(`\u8BF7\u8F93\u5165\u5E8F\u53F7 (1-${e.length}): `,o=>{t.close();let r=parseInt(o,10);isNaN(r)||r<1||r>e.length?(console.error("\u274C \u65E0\u6548\u9009\u62E9"),s(null)):s(e[r-1])})})}list(e){let t=this.getChannels();return e&&(t=t.filter(s=>s.type===e)),t.length?(this.printTable(t.map(s=>({id:s.id,type:s.type,name:s.name||"",enabled:s.enabled!==!1?"\u2713":"\u2717",botId:s.botId?lt(s.botId):"",allowFrom:(s.allowFrom??[]).join(", "),updatedAt:s.updatedAt||s.createdAt||""}))),0):(console.log(e?`\u6682\u65E0 ${e} \u6E20\u9053`:"\u6682\u65E0\u6E20\u9053\u7ED1\u5B9A"),0)}show(e){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6E20\u9053 ID"),1;let t=this.getChannels().find(s=>s.id===e);return t?(console.log(JSON.stringify(t,null,2)),0):(console.error(`\u274C \u6E20\u9053\u4E0D\u5B58\u5728: ${e}`),1)}add(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6E20\u9053\u7C7B\u578B\uFF0C\u4F8B\u5982: coder channel add wecom --bot-id xxx --secret yyy"),1;if(!ct.includes(e))return console.error(`\u274C \u4E0D\u652F\u6301\u7684\u6E20\u9053\u7C7B\u578B: ${e}\uFF0C\u652F\u6301: ${ct.join(", ")}`),1;let s=t.indexOf("--id"),o=(s!==-1?t[s+1]:void 0)||`${e}-${Date.now()}`,r=this.getChannels();if(r.find(i=>i.id===o))return console.error(`\u274C \u6E20\u9053 ID \u5DF2\u5B58\u5728: ${o}`),1;let n={id:o,type:e,enabled:!0,createdAt:new Date().toISOString()};return this._applyArgs(n,t),r.push(n),this.saveChannels(r),console.log(`\u2705 \u6E20\u9053\u5DF2\u6DFB\u52A0: ${o} (${e})`),0}remove(e){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6E20\u9053 ID"),1;let t=this.getChannels(),s=t.findIndex(o=>o.id===e);return s===-1?(console.error(`\u274C \u6E20\u9053\u4E0D\u5B58\u5728: ${e}`),1):(t.splice(s,1),this.saveChannels(t),console.log(`\u2705 \u6E20\u9053\u5DF2\u5220\u9664: ${e}`),0)}update(e,t){if(!e)return console.error("\u274C \u8BF7\u6307\u5B9A\u6E20\u9053 ID"),1;let s=this.getChannels(),o=s.find(r=>r.id===e);return o?(t.includes("--enable")&&(o.enabled=!0),t.includes("--disable")&&(o.enabled=!1),this._applyArgs(o,t),o.updatedAt=new Date().toISOString(),this.saveChannels(s),console.log(`\u2705 \u6E20\u9053\u5DF2\u66F4\u65B0: ${e}`),0):(console.error(`\u274C \u6E20\u9053\u4E0D\u5B58\u5728: ${e}`),1)}_applyArgs(e,t){let s=r=>{let n=t.indexOf(r);return n!==-1?t[n+1]:void 0},o=s("--name");if(o!==void 0&&(e.name=o),e.type==="wecom"){let r=s("--bot-id");r!==void 0&&(e.botId=r);let n=s("--secret");n!==void 0&&(e.secret=n);let i=s("--allow");i!==void 0&&(e.allowFrom=e.allowFrom??[],e.allowFrom.includes(i)||e.allowFrom.push(i));let a=s("--deny");a!==void 0&&(e.allowFrom=(e.allowFrom??[]).filter(c=>c!==a))}}printTable(e){if(!e.length)return;let t=Object.keys(e[0]),s=i=>[...String(i)].reduce((a,c)=>a+(c.charCodeAt(0)>127?2:1),0),o=(i,a)=>i+" ".repeat(Math.max(0,a-s(i))),r=t.map(i=>Math.max(s(i),...e.map(a=>s(String(a[i]||""))))),n=r.map(i=>"-".repeat(i)).join("-+-");console.log(t.map((i,a)=>o(i,r[a])).join(" | ")),console.log(n);for(let i of e)console.log(t.map((a,c)=>o(String(i[a]||""),r[c])).join(" | "))}showHelp(){console.log(`
|
|
306
|
+
coder channel \u2014 \u7BA1\u7406 Claude \u6E20\u9053\u7ED1\u5B9A
|
|
307
|
+
|
|
308
|
+
USAGE:
|
|
309
|
+
coder channel \u542F\u52A8 Claude\uFF08\u81EA\u52A8\u9009\u62E9\u6216\u4EA4\u4E92\u9009\u62E9\u6E20\u9053\uFF09
|
|
310
|
+
coder channel --channel-id <id> \u542F\u52A8\u6307\u5B9A\u6E20\u9053
|
|
311
|
+
coder channel list [type] \u5217\u51FA\u6E20\u9053
|
|
312
|
+
coder channel show <id> \u67E5\u770B\u6E20\u9053\u8BE6\u60C5
|
|
313
|
+
coder channel add <type> [options] \u6DFB\u52A0\u6E20\u9053
|
|
314
|
+
coder channel update <id> [options] \u66F4\u65B0\u6E20\u9053
|
|
315
|
+
coder channel remove <id> \u5220\u9664\u6E20\u9053
|
|
316
|
+
|
|
317
|
+
TYPES:
|
|
318
|
+
wecom \u4F01\u4E1A\u5FAE\u4FE1 AI Bot
|
|
319
|
+
|
|
320
|
+
OPTIONS (wecom):
|
|
321
|
+
--bot-id <botId> \u4F01\u4E1A\u5FAE\u4FE1 AI Bot ID
|
|
322
|
+
--secret <secret> \u4F01\u4E1A\u5FAE\u4FE1 AI Bot Secret
|
|
323
|
+
--allow <userId> \u5C06\u7528\u6237\u52A0\u5165\u767D\u540D\u5355
|
|
324
|
+
--deny <userId> \u5C06\u7528\u6237\u79FB\u51FA\u767D\u540D\u5355
|
|
325
|
+
--enable / --disable
|
|
326
|
+
--id <id> \u81EA\u5B9A\u4E49\u6E20\u9053 ID\uFF08add \u65F6\u4F7F\u7528\uFF09
|
|
327
|
+
--name <\u540D\u79F0> \u6E20\u9053\u663E\u793A\u540D\u79F0
|
|
328
|
+
|
|
329
|
+
EXAMPLES:
|
|
330
|
+
coder channel add wecom --bot-id xxx --secret yyy --name \u4E3B\u6E20\u9053
|
|
331
|
+
coder channel add wecom --bot-id zzz --secret www --name \u5907\u7528\u6E20\u9053
|
|
332
|
+
coder channel update wecom-xxx --allow zhangsan
|
|
333
|
+
coder channel list
|
|
334
|
+
coder channel # \u591A\u6E20\u9053\u65F6\u4EA4\u4E92\u9009\u62E9
|
|
335
|
+
coder channel --channel-id wecom-xxx # \u76F4\u63A5\u542F\u52A8\u6307\u5B9A\u6E20\u9053
|
|
336
|
+
|
|
337
|
+
\u914D\u7F6E\u6587\u4EF6: ~/.coder/config.json
|
|
338
|
+
`)}};ut.exports=fe});var pt=m((js,ft)=>{var os=ve(),ns=Ge(),rs=Ke(),is=We(),as=Xe(),cs=tt(),ls=nt(),ds=at(),us=ht(),{isPrintMode:hs}=R(),pe=class{constructor(){this.argParser=new os,this.claudeLauncher=new ns,this.geminiLauncher=new rs,this.codexLauncher=new is,this.vscodeExtensionService=new as,this.publishService=new cs,this.skillsService=new ls,this.wikiService=new ds,this.channelService=new us}async run(e=process.argv.slice(2)){try{try{await this.vscodeExtensionService.ensureExtensionInstalled()}catch(s){process.env.CODEV_DEBUG&&console.error("VSCode Extension Service Error:",s)}if(!e.includes("--agent")&&!e.includes("-a")){let s=e.length>0&&["claude","gemini","codex"].includes(e[0]),o=e.length>0&&["pub","update","skills","wiki","channel"].includes(e[0]);if(!s&&!o&&(e.includes("--help")||e.includes("-h")))return this.argParser.showHelp(),0;if(!s&&!o&&(e.includes("--version")||e.includes("-v")))return this.showVersion(),0}let t=await this.argParser.parse(e);return t.command==="login"?await this.handleLogin(t):t.command==="update"?this.handleUpdate():t.command==="skills"?await this.skillsService.handle(t):t.command==="wiki"?await this.wikiService.handle(t):t.command==="channel"?await this.channelService.handle({...t,claudeLauncher:this.claudeLauncher,parsedArgs:t}):t.command==="pub"?await this.publishService.publish({name:t.pubName,ak:t.auth_ak,sk:t.auth_sk,serverBaseUrl:t.codevServer,allowClone:t.allowClone}):await this.launchAgent(t)}catch(t){return console.error(`Error: ${t.message}`),process.env.CODEV_DEBUG&&console.error("Stack trace:",t.stack),1}}async launchAgent(e){let{agent:t,remainingArgs:s}=e;return hs(s)||console.log(`cwd:\x1B[90m\x1B[3m ${process.cwd()} \x1B[0m`),t==="claude"?await this.claudeLauncher.launch(e):t==="gemini"?await this.geminiLauncher.launch(e):t==="codex"?await this.codexLauncher.launch(e):1}async handleLogin(e){let t=e.auth_ak,s=e.auth_sk;if(!t||!s){console.log(`
|
|
302
339
|
\u{1F511} \u8BF7\u5148\u5728 MakeCoder \u521B\u5EFA API Key\uFF1A`),console.log(` \u{1F449} https://makecoder.com/my/apikeys
|
|
303
|
-
`);try{let r=await this.argParser.promptForAKSK();t=r.ak,s=r.sk}catch(r){return console.error(`\u274C ${r.message}`),1}}if(this.argParser.saveAuthToConfig(t,s))console.log("\u2705 API Key \u5DF2\u4FDD\u5B58\u5230 ~/.coder/config.json"),console.log(" \u73B0\u5728\u53EF\u4EE5\u76F4\u63A5\u8FD0\u884C coder \u5F00\u59CB\u4F7F\u7528\u4E86 \u{1F680}");else return console.error("\u274C \u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 ~/.coder/ \u76EE\u5F55\u7684\u6587\u4EF6\u6743\u9650"),1;return 0}handleUpdate(){let{execSync:e}=require("child_process"),t=
|
|
340
|
+
`);try{let r=await this.argParser.promptForAKSK();t=r.ak,s=r.sk}catch(r){return console.error(`\u274C ${r.message}`),1}}if(this.argParser.saveAuthToConfig(t,s))console.log("\u2705 API Key \u5DF2\u4FDD\u5B58\u5230 ~/.coder/config.json"),console.log(" \u73B0\u5728\u53EF\u4EE5\u76F4\u63A5\u8FD0\u884C coder \u5F00\u59CB\u4F7F\u7528\u4E86 \u{1F680}");else return console.error("\u274C \u4FDD\u5B58\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5 ~/.coder/ \u76EE\u5F55\u7684\u6587\u4EF6\u6743\u9650"),1;return 0}handleUpdate(){let{execSync:e}=require("child_process"),t=G();console.log(`\u5F53\u524D\u7248\u672C: ${t.version}`),console.log(`\u6B63\u5728\u5347\u7EA7 Coder...
|
|
304
341
|
`);try{return e("npm install -g makecoder@latest",{stdio:"inherit"}),console.log(`
|
|
305
342
|
\u2705 \u5347\u7EA7\u6210\u529F`),0}catch(s){return console.error(`
|
|
306
|
-
\u274C \u5347\u7EA7\u5931\u8D25:`,s.message),1}}showVersion(){let e=
|
|
307
|
-
Shutting down...`),process.exit(0)}};
|
|
343
|
+
\u274C \u5347\u7EA7\u5931\u8D25:`,s.message),1}}showVersion(){let e=G();console.log(`coder version: ${e.version}`)}async shutdown(){console.log(`
|
|
344
|
+
Shutting down...`),process.exit(0)}};ft.exports=pe});var fs=pt(),{isPrintMode:Bs}=R();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 ps(){let h=new fs;process.on("SIGINT",async()=>{console.log(`
|
|
308
345
|
Received SIGINT, shutting down gracefully...`),await h.shutdown()}),process.on("SIGTERM",async()=>{console.log(`
|
|
309
|
-
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)}}
|
|
346
|
+
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)}}ps().catch(h=>{console.error(`Startup error: ${h.message}`),process.exit(1)});
|