#!/usr/bin/env node
var Be=Object.create;var Y=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Ve=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var f=(u,e)=>()=>(e||u((e={exports:{}}).exports,e),e.exports);var Le=(u,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ve(e))!Re.call(u,o)&&o!==s&&Y(u,o,{get:()=>e[o],enumerable:!(t=Ne(e,o))||t.enumerable});return u};var He=(u,e,s)=>(s=u!=null?Be(Ge(u)):{},Le(e||!u||!u.__esModule?Y(s,"default",{value:u,enumerable:!0}):s,u));var X=f((Os,Z)=>{var Ke=require("http"),T=class{constructor(e={}){this.port=e.port||9380,this.timeout=e.timeout||300*1e3,this.server=null,this.timeoutId=null}validateTokenFormat(e){if(!e||typeof e!="string")return!1;let s=e.split(".");if(s.length!==2)return!1;let[t,o]=s;return t&&t.length>0&&o&&o.length>0}async waitForCallback(e){return new Promise((s,t)=>{let o=!1;this.server=Ke.createServer((n,i)=>{let a=new URL(n.url,`http://localhost:${this.port}`);if(a.pathname==="/callback"){let r=a.searchParams.get("token"),c=a.searchParams.get("state"),l=a.searchParams.get("error");if(l){i.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),i.end(`
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>\u767B\u5F55\u5931\u8D25 - MakeCoder</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: #f3f4f6; color: #1f2937; }
    .container { text-align: center; background: white; padding: 3rem; border-radius: 1rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); max-width: 28rem; width: 90%; }
    h1 { font-size: 1.5rem; font-weight: 700; margin-bottom: 1rem; color: #111827; }
    p { color: #4b5563; line-height: 1.5; margin-bottom: 1rem; }
    .icon { font-size: 4rem; margin-bottom: 1rem; display: inline-block; }
    .error { color: #ef4444; }
    .code { background: #fee2e2; color: #b91c1c; padding: 0.25rem 0.5rem; border-radius: 0.25rem; font-family: monospace; font-size: 0.875rem; }
  </style>
</head>
<body>
  <div class="container">
    <div class="icon">\u274C</div>
    <h1>\u767B\u5F55\u5931\u8D25</h1>
    <p>\u6388\u6743\u8FC7\u7A0B\u4E2D\u51FA\u73B0\u9519\u8BEF\uFF0C\u8BF7\u8FD4\u56DE\u7EC8\u7AEF\u91CD\u8BD5\u3002</p>
    <p class="code">\u9519\u8BEF: ${l}</p>
  </div>
</body>
</html>
            `),o||(o=!0,this.cleanup(),t(new Error(`OAuth error: ${l}`)));return}if(c!==e){i.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),i.end(`
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>\u5B89\u5168\u9519\u8BEF - MakeCoder</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: #f3f4f6; color: #1f2937; }
    .container { text-align: center; background: white; padding: 3rem; border-radius: 1rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); max-width: 28rem; width: 90%; }
    h1 { font-size: 1.5rem; font-weight: 700; margin-bottom: 1rem; color: #111827; }
    p { color: #4b5563; line-height: 1.5; margin-bottom: 1rem; }
    .icon { font-size: 4rem; margin-bottom: 1rem; display: inline-block; }
  </style>
</head>
<body>
  <div class="container">
    <div class="icon">\u26A0\uFE0F</div>
    <h1>\u5B89\u5168\u9A8C\u8BC1\u5931\u8D25</h1>
    <p>\u68C0\u6D4B\u5230\u6F5C\u5728\u7684\u5B89\u5168\u98CE\u9669\uFF08CSRF\uFF09\uFF0C\u8BF7\u8FD4\u56DE\u7EC8\u7AEF\u91CD\u65B0\u5C1D\u8BD5\u767B\u5F55\u3002</p>
  </div>
</body>
</html>
            `),o||(o=!0,this.cleanup(),t(new Error("Invalid state parameter - possible CSRF attack")));return}if(!r){i.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),i.end(`
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>\u6388\u6743\u5931\u8D25 - MakeCoder</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: #f3f4f6; color: #1f2937; }
    .container { text-align: center; background: white; padding: 3rem; border-radius: 1rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); max-width: 28rem; width: 90%; }
    h1 { font-size: 1.5rem; font-weight: 700; margin-bottom: 1rem; color: #111827; }
    p { color: #4b5563; line-height: 1.5; margin-bottom: 1rem; }
    .icon { font-size: 4rem; margin-bottom: 1rem; display: inline-block; }
  </style>
</head>
<body>
  <div class="container">
    <div class="icon">\u274C</div>
    <h1>\u6388\u6743\u5931\u8D25</h1>
    <p>\u672A\u80FD\u83B7\u53D6\u6388\u6743\u4EE4\u724C\uFF0C\u8BF7\u8FD4\u56DE\u7EC8\u7AEF\u91CD\u8BD5\u3002</p>
  </div>
</body>
</html>
            `),o||(o=!0,this.cleanup(),t(new Error("No token received from OAuth callback")));return}if(!this.validateTokenFormat(r)){i.writeHead(400,{"Content-Type":"text/html; charset=utf-8"}),i.end(`
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>\u4EE4\u724C\u683C\u5F0F\u9519\u8BEF - MakeCoder</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: #f3f4f6; color: #1f2937; }
    .container { text-align: center; background: white; padding: 3rem; border-radius: 1rem; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); max-width: 28rem; width: 90%; }
    h1 { font-size: 1.5rem; font-weight: 700; margin-bottom: 1rem; color: #111827; }
    p { color: #4b5563; line-height: 1.5; margin-bottom: 1rem; }
    .icon { font-size: 4rem; margin-bottom: 1rem; display: inline-block; }
    .code { background: #fee2e2; color: #b91c1c; padding: 0.25rem 0.5rem; border-radius: 0.25rem; font-family: monospace; font-size: 0.875rem; }
  </style>
</head>
<body>
  <div class="container">
    <div class="icon">\u26A0\uFE0F</div>
    <h1>\u4EE4\u724C\u683C\u5F0F\u9519\u8BEF</h1>
    <p>\u63A5\u6536\u5230\u7684\u4EE4\u724C\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u5E94\u4E3A <span class="code">ak.sk</span> \u683C\u5F0F\u3002</p>
    <p>\u8BF7\u8FD4\u56DE\u7EC8\u7AEF\u91CD\u65B0\u5C1D\u8BD5\u767B\u5F55\u3002</p>
  </div>
</body>
</html>
            `),o||(o=!0,this.cleanup(),t(new Error("Invalid token format - expected ak.sk format")));return}let[h,g]=r.split(".");i.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),i.end(`
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>\u767B\u5F55\u6210\u529F - MakeCoder</title>
  <style>
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background-color: #f3f4f6; color: #1f2937; }
    .container { text-align: center; background: white; padding: 3rem; border-radius: 1rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); max-width: 28rem; width: 90%; }
    h1 { font-size: 1.5rem; font-weight: 700; margin-bottom: 0.5rem; color: #111827; }
    p { color: #4b5563; line-height: 1.5; margin-bottom: 0; }
    .icon { font-size: 4rem; margin-bottom: 1.5rem; display: inline-block; animation: pop 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
    .sub-text { font-size: 0.875rem; color: #9ca3af; margin-top: 2rem; }
    @keyframes pop {
      0% { transform: scale(0.5); opacity: 0; }
      100% { transform: scale(1); opacity: 1; }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="icon">\u{1F389}</div>
    <h1>\u767B\u5F55\u6210\u529F!</h1>
    <p>\u5DF2\u6210\u529F\u83B7\u53D6\u6388\u6743\uFF0C\u6B63\u5728\u914D\u7F6E\u60A8\u7684 API Key...</p>
    <p class="sub-text">\u60A8\u53EF\u4EE5\u5173\u95ED\u6B64\u7A97\u53E3\u5E76\u8FD4\u56DE\u7EC8\u7AEF</p>
  </div>
  <script>
    // Auto-close after 3 seconds
    setTimeout(() => { window.close(); }, 3000);
  </script>
</body>
</html>
          `),o||(o=!0,this.cleanup(),s({ak:h,sk:g}))}else i.writeHead(404,{"Content-Type":"text/plain"}),i.end("Not Found")}),this.server.on("error",n=>{if(n.code==="EADDRINUSE"){if(this.port++,this.port>9390){o||(o=!0,t(new Error("Could not find available port for OAuth callback server")));return}this.server.close(),this.server.listen(this.port)}else o||(o=!0,this.cleanup(),t(n))}),this.server.listen(this.port,()=>{process.env.CODEV_DEBUG&&console.log(`OAuth callback server listening on port ${this.port}`)}),this.timeoutId=setTimeout(()=>{o||(o=!0,this.cleanup(),t(new Error("OAuth login timeout - no response received within 5 minutes")))},this.timeout)})}getCallbackUrl(){return`http://localhost:${this.port}/callback`}cleanup(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.server&&(this.server.close(),this.server=null)}};Z.exports=T});var se=f((Ts,ee)=>{var We=require("crypto"),je=X(),A=class{constructor(e={}){this.baseUrl=e.baseUrl||"https://makecoder.com",this.callbackServer=null}generateState(){return We.randomBytes(16).toString("hex")}buildAuthorizationUrl(e,s){let t=new URLSearchParams({redirect_uri:e,state:s,response_type:"token"});return`${this.baseUrl}/oauth/authorize?${t.toString()}`}async login(){let e=this.generateState();this.callbackServer=new je;try{let s=this.callbackServer.getCallbackUrl(),t=this.buildAuthorizationUrl(s,e);console.log(`
\u{1F510} \u5F00\u59CB OAuth \u767B\u5F55\u6D41\u7A0B...
`),console.log(`\u{1F4CB} \u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u5B8C\u6210\u767B\u5F55
`),console.log(`\u{1F310} \u6388\u6743\u5730\u5740: ${t}
`),console.log(`\u23F3 \u7B49\u5F85\u60A8\u7684\u6388\u6743...(\u8D85\u65F6\u65F6\u95F4: 5\u5206\u949F)
`);try{let n=(await import("open")).default;await n(t)}catch(n){console.warn("\u26A0\uFE0F  \u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668,\u8BF7\u624B\u52A8\u590D\u5236\u4E0A\u8FF0\u94FE\u63A5\u5230\u6D4F\u89C8\u5668\u6253\u5F00"),process.env.CODEV_DEBUG&&console.error("Browser open error:",n)}let o=await this.callbackServer.waitForCallback(e);return console.log(`\u2705 API Key \u83B7\u53D6\u6210\u529F!
`),o}catch(s){throw console.error(`
\u274C OAuth \u767B\u5F55\u5931\u8D25: ${s.message}
`),s}finally{this.callbackServer&&this.callbackServer.cleanup()}}cleanup(){this.callbackServer&&this.callbackServer.cleanup()}};ee.exports=A});var ne=f((As,oe)=>{var y=require("fs"),te=require("path"),ze=require("os"),Je=require("readline"),Qe=se(),F=class{constructor(){this.configPath=te.join(ze.homedir(),".coder","config.json"),this.defaultConfig={agent:"claude",auth:{ak:null,sk:null}}}async promptForAKSK(){let e=Je.createInterface({input:process.stdin,output:process.stdout});return new Promise((s,t)=>{console.log(`
\u{1F510} \u8BF7\u8F93\u5165\u60A8\u7684 API Key\uFF1A`),e.question("\u8BF7\u8F93\u5165 API Key: ",o=>{let n=o.indexOf(".");if(n===-1||n===0||n===o.length-1){e.close(),t(new Error("\u683C\u5F0F\u9519\u8BEF"));return}let i=o.substring(0,n),a=o.substring(n+1);if(!i.trim()||!a.trim()){e.close(),t(new Error("\u683C\u5F0F\u9519\u8BEF"));return}e.close(),s({ak:i.trim(),sk:a.trim()})})})}ensureConfig(){let e=te.dirname(this.configPath);try{y.existsSync(e)||y.mkdirSync(e,{recursive:!0}),y.existsSync(this.configPath)||y.writeFileSync(this.configPath,JSON.stringify(this.defaultConfig,null,2))}catch(s){return console.warn(`Warning: Could not create config file: ${s.message}`),this.defaultConfig}}loadConfig(){this.ensureConfig();try{let e=y.readFileSync(this.configPath,"utf8");return JSON.parse(e)}catch(e){return console.warn(`Warning: Could not load config, using defaults: ${e.message}`),this.defaultConfig}}async parse(e=process.argv.slice(2)){let s=this.loadConfig(),t={agent:s.agent||"claude",remainingArgs:[]},o=0,n=!1;for(e.length>0&&["claude","gemini","codex"].includes(e[0])?(t.agent=e[0],n=!0,o=1):e.length>0&&e[0]==="pub"&&(t.command="pub",o=1);o<e.length;){let r=e[o];if(r==="--agent"){if(n)throw new Error(`Cannot use both subcommand '${t.agent}' and --agent flag. Please use only one method to specify the agent.`);if(o+1>=e.length)throw new Error("--agent requires a value (claude, gemini, or codex)");let c=e[o+1];if(!["claude","gemini","codex"].includes(c))throw new Error(`Invalid agent: ${c}. Must be 'claude', 'gemini', or 'codex'`);t.agent=c,o+=2}else if(r==="--apikey"||r==="--aksk")if(o+1>=e.length||e[o+1].startsWith("--"))t.needAKSKPrompt=!0,o+=1;else{let c=e[o+1],l=c.indexOf(".");if(l===-1)throw new Error("API Key Format error");t.auth_ak=c.substring(0,l),t.auth_sk=c.substring(l+1),o+=2}else if(r==="--save-auth")t.saveAuth=!0,o+=1;else if(r==="--name")o+1>=e.length||e[o+1].startsWith("--")?o+=1:(t.pubName=e[o+1],o+=2);else if(r==="--clear-auth")t.clearAuth=!0,o+=1;else if(r==="--allow-clone")t.allowClone=!0,o+=1;else{t.remainingArgs=e.slice(o);break}}if(t.needAKSKPrompt)try{let{ak:r,sk:c}=await this.promptForAKSK();t.auth_ak=r,t.auth_sk=c,delete t.needAKSKPrompt}catch(r){console.error(`\u274C ${r.message}`),process.exit(1)}if(!t.auth_ak&&s.auth&&s.auth.ak&&(t.auth_ak=s.auth.ak),!t.auth_sk&&s.auth&&s.auth.sk&&(t.auth_sk=s.auth.sk),!t.auth_ak&&process.env.CODEV_AUTH_AK&&(t.auth_ak=process.env.CODEV_AUTH_AK),!t.auth_sk&&process.env.CODEV_AUTH_SK&&(t.auth_sk=process.env.CODEV_AUTH_SK),t.saveAuth&&t.auth_ak&&t.auth_sk){let r=this.saveAuthToConfig(t.auth_ak,t.auth_sk);console.log(r?"\u2705 API Key \u5DF2\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6":"\u274C \u4FDD\u5B58 API Key \u5931\u8D25"),process.exit(0)}if(t.clearAuth){let r=this.clearAuthFromConfig();console.log(r?"\u2705 API Key \u5DF2\u4ECE\u914D\u7F6E\u6587\u4EF6\u6E05\u9664":"\u274C \u6E05\u9664 API Key \u5931\u8D25"),process.exit(0)}let i=t.remainingArgs.includes("--version")||t.remainingArgs.includes("-v"),a=t.remainingArgs.includes("--help")||t.remainingArgs.includes("-h");if(!i&&!a&&(!t.auth_ak||!t.auth_sk))try{console.log(`\u274C \u7F3A\u5C11\u5FC5\u8981\u7684 API Key
`),console.log(`\u{1F510} \u6B63\u5728\u542F\u52A8\u767B\u5F55\u6D41\u7A0B...
`);let c=await new Qe({baseUrl:"https://makecoder.com",apiBaseUrl:t.codevServer||"https://makecoder.com/bigapis/codev/v1"}).login();t.auth_ak=c.ak,t.auth_sk=c.sk;let l=this.saveAuthToConfig(c.ak,c.sk);console.log(l?`\u2705 API Key \u5DF2\u81EA\u52A8\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6
`:`\u26A0\uFE0F  API Key \u83B7\u53D6\u6210\u529F\u4F46\u672A\u80FD\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6,\u4E0B\u6B21\u4F7F\u7528\u9700\u8981\u91CD\u65B0\u767B\u5F55
`)}catch(r){console.error(`
\u274C \u767B\u5F55\u5931\u8D25: ${r.message}
`),console.error(`\u{1F4CB} \u60A8\u4E5F\u53EF\u4EE5\u624B\u52A8\u83B7\u53D6 API Key\uFF1A
   \u8BF7\u8BBF\u95EE\uFF1Ahttps://makecoder.com/my/apikeys

\u{1F680} \u624B\u52A8\u4F7F\u7528\u65B9\u5F0F\uFF1A
   coder --apikey <\u4F60\u7684API Key>
   \u6216\u8005\uFF1Acoder --apikey \uFF08\u7136\u540E\u5B89\u5168\u8F93\u5165\uFF09
`),process.exit(1)}return process.env.CODEV_SERVER?t.codevServer=process.env.CODEV_SERVER:s.codevServer?t.codevServer=s.codevServer:t.codevServer="https://makecoder.com/bigapis/codev/v1",t}saveAuthToConfig(e,s){let t=this.loadConfig();t.auth||(t.auth={}),t.auth.ak=e,t.auth.sk=s;try{return y.writeFileSync(this.configPath,JSON.stringify(t,null,2)),!0}catch(o){return console.warn(`Warning: Could not save auth to config: ${o.message}`),!1}}clearAuthFromConfig(){let e=this.loadConfig();e.auth&&(e.auth.ak=null,e.auth.sk=null);try{return y.writeFileSync(this.configPath,JSON.stringify(e,null,2)),!0}catch(s){return console.warn(`Warning: Could not clear auth from config: ${s.message}`),!1}}showHelp(){console.log(`
Coder AI Agent

USAGE:
  coder [--agent <agent>] [agent-args...]
  coder <agent> [agent-args...]
  coder pub [--name <name>]

AGENTS:
  claude    Use Claude Code (default)
  gemini    Use Gemini CLI
  codex     Use OpenAI Codex CLI

COMMANDS:
  pub       Publish current directory to hosting server

EXAMPLES:
  coder claude                    # Launch Claude agent
  coder gemini                    # Launch Gemini agent
  coder codex --help              # Launch Codex agent
  coder --agent claude            # Alternative syntax
  coder pub --name myproject      # Publish current directory as 'myproject'
  coder pub                       # Publish (will prompt for name)

OPTIONS:
  --agent <agent>         Specify which agent to use (claude|gemini|codex)
  --version               Show version
  --help                  Show this help message
  --apikey [API Key]      \u63D0\u4F9B API Key \u6216\u4F7F\u7528 --apikey \u4EA4\u4E92\u5F0F\u5B89\u5168\u8F93\u5165
                          (\u83B7\u53D6\u5730\u5740: https://makecoder.com/my/apikeys)
  --save-auth             Save provided API Key to config file ~/.coder/config.json
  --clear-auth            Clear saved API Key from config file
  --name <name>           (pub command) Project name for publishing
  --allow-clone           (pub command) Include Claude Code generation history for cloning

CONFIG:
  Default configuration is stored in ~/.coder/config.json
  Command line --agent overrides the default but doesn't modify the file.
  Auth credentials can be stored in config file under "auth" section.
`)}};oe.exports=F});var k=f((Fs,ie)=>{function Ye(u=process.argv.slice(2)){return u.includes("--print")||u.includes("-p")}ie.exports={isPrintMode:Ye}});var $=f((Ms,ce)=>{var{spawn:Ze}=require("child_process"),I=require("path"),C=require("fs"),re=require("os"),{isPrintMode:ae}=k(),M=class{constructor(e){this.config=e}resloveSettingFilePath(e){return I.join(e,this.config.configDir,"settings.json")}readModelFromSettingsFile(e){try{let s=this.resloveSettingFilePath(e);if(C.existsSync(s)){let t=C.readFileSync(s,"utf8"),o=JSON.parse(t);if(o&&o.model)return o.model}}catch(s){console.warn(e,s.message)}return null}getCurrentModel(e){let s=e.findIndex(o=>o==="--model");if(s!==-1&&s+1<e.length)return e[s+1];let t=this.readModelFromSettingsFile(process.cwd());return t||(t=this.readModelFromSettingsFile(re.homedir()),t)?t:this.config.defaultModel}async ensureConfig(e=0){let s=I.join(re.homedir(),this.config.configDir,this.config.configFile),t=I.dirname(s);if(!C.existsSync(s)){let o=this.config.defaultConfig||{};try{C.existsSync(t)||C.mkdirSync(t,{recursive:!0}),C.writeFileSync(s,JSON.stringify(o,null,2)),e>0&&await new Promise(n=>setTimeout(n,e))}catch(n){console.warn(`Failed to create ${this.config.configFile}: ${n.message}`)}}}findExecutablePath(){let e=I.dirname(require.main.filename);for(let s of this.config.executablePaths){let t=I.resolve(e,s);if(C.existsSync(t))return t}throw new Error(`Could not find executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}handleChildMessages(e){process.env.CODEV_DEBUG&&console.log("Child process message handler initialized"),e.connected&&(e.on("message",s=>{this.onChildMessage(s)}),e.on("exit",async(s,t)=>{try{await this.handleChildProcessExit(s,t)}catch(o){console.error("Error in handleChildProcessExit:",o.message)}}),e.on("error",s=>{this.handleChildProcessError(s)}))}onChildMessage(e){process.env.CODEV_DEBUG&&console.log("Received IPC message from child:",e)}handleChildProcessExit(e,s){}handleChildProcessError(e){}async launch(e={}){let{remainingArgs:s=[],codevServer:t,auth_ak:o=null,auth_sk:n=null}=e;try{let i=this.getCurrentModel(s);ae(s)||console.log(`model:\x1B[90m\x1B[3m ${i} (use /model to switch models) \x1B[0m`),await this.ensureConfig(1e3);let a=this.findExecutablePath();return process.env.CODEV_DEBUG&&console.log(`executablePath: ${a}`),new Promise((r,c)=>{let l={...process.env,...this.config.environmentVariables(t)};o&&(l.CODEV_AUTH_AK=o),n&&(l.CODEV_AUTH_SK=n);let h=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&h.push("--inspect-brk"),h.push(a,...s);let g=Ze("node",h,{env:l,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(g),g.on("error",S=>{console.error(`Failed to start: ${S.message}`),c(S)}),g.on("exit",async(S,Q)=>{ae(s)||console.log(Q?`terminated by signal: ${Q}`:"Goodbye for now! Keep building great things!")}),process.on("SIGINT",async()=>{console.log(`
Terminating ...`),g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
Terminating ...`),g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},8e3)})})}catch(i){throw i}}};ce.exports=M});var ue=f((qs,le)=>{var d=process.env.CODEV_DEBUG==="True",q=class{constructor(e={}){this.queue=[],this.processing=!1,this.shuttingDown=!1,this.shutdownTimeout=e.shutdownTimeout||5e3,this.maxRetries=e.maxRetries||3,this.retryDelay=e.retryDelay||1e3,this.onProcessMessage=e.onProcessMessage||null,this.shutdownPromise=null,this.currentlyProcessing=null}enqueue(e){if(this.shuttingDown)return d&&console.log("Queue is shutting down, skipping new messages"),null;let s={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(s),d&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),s.id}dequeue(){let e=this.queue.shift();return d&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let s=this.queue.findIndex(t=>t.id===e);return s>-1?(this.queue.splice(s,1),d&&console.log(`Message ${e} removed from queue`),!0):!1}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{for(;this.queue.length>0&&!this.shuttingDown;){let e=this.queue[0];e.processing=!0;try{this.onProcessMessage&&await this.onProcessMessage(e),this.dequeue()}catch(s){if(d&&console.error(`Failed to process message: ${s.message}`),e.retryCount++,d&&console.log("Start Retry:",e.retryCount,"times..."),e.retryCount>=this.maxRetries)d&&console.error("Message exceeded max retries, removing from queue"),this.dequeue();else{e.processing=!1;let t=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,t))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],d&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let s=this.queue.filter(o=>o.processing);if(s.length===0)return;d&&console.log(`Waiting for ${s.length} processing messages to complete (timeout: ${e}ms)`);let t=Date.now();for(;Date.now()-t<e;){if(this.queue.filter(n=>n.processing).length===0){d&&console.log(`All processing messages completed in ${Date.now()-t}ms`);return}await new Promise(n=>setTimeout(n,50))}if(d){let o=this.queue.filter(n=>n.processing);console.log(`Timeout waiting for processing messages. ${o.length} messages still processing`)}}async gracefulShutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let{timeoutMs:s=this.shutdownTimeout,batchSize:t=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async n=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(s*.3,3e3));let i=this.queue.filter(S=>!S.processing),a=i.length;d&&(console.log(`Starting graceful shutdown with ${a} pending messages (${this.queue.length-a} already processing)`),console.log(`Mode: ${o?"fast (parallel)":"sequential"}, timeout: ${s}ms`));let r=Date.now(),c=0,l=0;try{if(o){let S=await this.processAllParallel(s-(Date.now()-r),i);c=S.processed,l=S.failed}else{let S=await this.processInBatches(t,s-(Date.now()-r),i);c=S.processed,l=S.failed}}catch(S){d&&console.error("Error during shutdown processing:",S.message)}let h=Date.now()-r,g=this.queue.length;d&&(console.log(`Shutdown completed in ${h}ms:`),console.log(`  - Total: ${a} messages`),console.log(`  - Processed: ${c}`),console.log(`  - Failed: ${l}`),console.log(`  - Remaining: ${g}`)),n({totalMessages:a,processedMessages:c,failedMessages:l,remainingMessages:g,duration:h,allMessagesSent:g===0&&l===0})}),this.shutdownPromise}async processAllParallel(e){if(this.queue.length===0)return{processed:0,failed:0};d&&console.log(`Processing ${this.queue.length} messages in parallel...`);let s=[...this.queue];this.queue=[];let t=s.map(async r=>{try{return this.onProcessMessage&&await this.onProcessMessage(r),{success:!0,messageId:r.id}}catch(c){return d&&console.warn(`Message ${r.id} processing failed: ${c.message}`),{success:!1,messageId:r.id,error:c}}}),o=new Promise(r=>{setTimeout(()=>r({timedOut:!0}),e)}),n=await Promise.race([Promise.allSettled(t).then(r=>({results:r})),o]);if(n.timedOut)return d&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:s.length};let i=n.results.filter(r=>r.status==="fulfilled"&&r.value?.success).length,a=s.length-i;return{processed:i,failed:a}}async processInBatches(e,s){if(this.queue.length===0)return{processed:0,failed:0};d&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let t=Date.now(),o=0,n=0;for(;this.queue.length>0&&Date.now()-t<s;){let i=this.queue.splice(0,e),a=i.map(async h=>{try{return this.onProcessMessage&&await this.onProcessMessage(h),{success:!0}}catch(g){return d&&console.warn(`Batch message processing failed: ${g.message}`),{success:!1,error:g}}}),c=(await Promise.allSettled(a)).filter(h=>h.status==="fulfilled"&&h.value?.success).length,l=i.length-c;o+=c,n+=l,d&&i.length>0&&console.log(`Batch completed: ${c}/${i.length} successful`),this.queue.length>0&&await new Promise(h=>setTimeout(h,10))}return this.queue.length>0&&(n+=this.queue.length,d&&console.log(`${this.queue.length} messages not processed due to timeout`),this.queue=[]),{processed:o,failed:n}}async forceFlushAndShutdown(e=2e3){this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(e*.4,1e3));let s=this.queue.filter(r=>!r.processing);d&&console.log(`Force flush: attempting to send ${s.length} pending messages within ${e}ms (${this.queue.length-s.length} already processing)`);let t=Date.now(),o=s.map(async r=>{try{return this.onProcessMessage&&Date.now()-t<e?(await this.onProcessMessage(r),{success:!0,messageId:r.id}):{success:!1,messageId:r.id,reason:"timeout"}}catch(c){return{success:!1,messageId:r.id,error:c.message}}}),n=e-(Date.now()-t),i=new Promise(r=>{setTimeout(()=>r({timedOut:!0}),Math.max(100,n))}),a=await Promise.race([Promise.allSettled(o).then(r=>({results:r})),i]);if(s.forEach(r=>{let c=this.queue.findIndex(l=>l.id===r.id);c>-1&&this.queue.splice(c,1)}),this.processing=!1,a.timedOut)return d&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:s.length};{let r=a.results.filter(c=>c.status==="fulfilled"&&c.value.success).length;return d&&console.log(`Force flush completed: ${r}/${s.length} messages sent`),{success:r===s.length,successCount:r,totalCount:s.length,results:a.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,d&&console.log("Force shutdown: Queue cleared")}};le.exports=q});var U=f((Us,Xe)=>{Xe.exports={name:"makecoder",version:"2.0.3",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","agent"],author:"makecoder",license:"MIT",dependencies:{zod:"^3.25.76",open:"^10.1.0","node-fetch":"^3.3.2"},engines:{node:">=20.0.0"},devDependencies:{chokidar:"^4.0.3"},files:["dist","claude","scripts/postinstall.js"]}});var fe=f((Bs,ge)=>{var es=require("http"),ss=require("https"),{URL:he}=require("url"),{version:ts}=U(),de=process.env.CODEV_DEBUG==="True",B=class{constructor(e={}){this.baseUrl=e.baseUrl||"",this.timeout=e.timeout||3e4,this.defaultHeaders={"Content-Type":"application/json","User-Agent":`codev-cli/${ts}`,...e.headers}}setBaseUrl(e){this.baseUrl=e}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}async post(e,s,t={}){let o=this.resolveUrl(e),n={...this.defaultHeaders,...t.headers};return new Promise((i,a)=>{this.validateRequest(o,s,a);let r=this.serializeData(s,a);if(!r)return;n["Content-Length"]=Buffer.byteLength(r);let c=this.buildRequestOptions(o,"POST",n),l=this.getHttpModule(o);de&&console.debug(`HTTP POST to ${o} with data length: ${r.length}`);let h=l.request(c,g=>{this.handleResponse(g,i,a)});this.attachErrorHandlers(h,o,a),h.setTimeout(this.timeout),h.write(r),h.end()})}resolveUrl(e){return e.startsWith("http")?e:`${this.baseUrl}${e.startsWith("/")?"":"/"}${e}`}validateRequest(e,s,t){return!e||typeof e!="string"?(t(new Error(`Invalid URL: ${e}`)),!1):s?!0:(t(new Error("No data provided for HTTP POST")),!1)}serializeData(e,s){try{return typeof e=="string"?e:JSON.stringify(e)}catch(t){return s(new Error(`Failed to serialize data: ${t.message}`)),null}}buildRequestOptions(e,s,t){let o=new he(e),n=o.protocol==="https:";return{hostname:o.hostname,port:o.port||(n?443:80),path:o.pathname+o.search,method:s,headers:t}}getHttpModule(e){return new he(e).protocol==="https:"?ss:es}handleResponse(e,s,t){de&&console.debug(`HTTP response status: ${e.statusCode}`);let o="";e.on("data",n=>{o+=n}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?s({statusCode:e.statusCode,data:o,headers:e.headers}):t(new Error(`HTTP request returned status ${e.statusCode}: ${o}`))})}attachErrorHandlers(e,s,t){e.on("error",o=>{t(new Error(`HTTP POST request failed: ${o.message}`))}),e.on("timeout",()=>{t(new Error(`HTTP POST request timed out for URL: ${s}`)),e.destroy()})}};ge.exports=B});var pe=f((Ns,me)=>{var os=require("crypto"),{URL:ns}=require("url"),N=class{static generateSignature(e,s,t,o){try{let n=new ns(e),i=Buffer.from(n.pathname),a=Buffer.from(i),r=s?typeof s=="string"?Buffer.from(s):Buffer.from(JSON.stringify(s)):Buffer.alloc(0),c=Buffer.concat([a,r,Buffer.from(o)]),l=os.createHmac("sha256",t);return l.update(c),l.digest("hex")}catch(n){throw new Error(`Failed to generate signature: ${n.message}`)}}static validateSignature(e,s,t,o,n){return this.generateSignature(e,s,t,o)===n}static generateTimestamp(){return Date.now().toString()}};me.exports=N});var we=f((Vs,Se)=>{var is=pe(),V=class{constructor(e={}){this.accessKey=null,this.secretKey=null,this.validateCredentials=e.validateCredentials!==!1}setCredentials(e,s){if(this.validateCredentials&&(!e||!s))throw new Error("Both access key and secret key are required");this.accessKey=e,this.secretKey=s}hasCredentials(){return!!(this.accessKey&&this.secretKey)}generateAuthHeaders(e,s=null){if(!this.hasCredentials())return{};try{return{AUTHORIZATION:`Bearer ${this.accessKey}.${this.secretKey}`}}catch(t){throw new Error(`Failed to generate auth headers: ${t.message}`)}}validateAuthHeaders(e,s,t,o){if(!this.hasCredentials())throw new Error("No credentials available for validation");return is.validateSignature(e,s,this.secretKey,t,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};Se.exports=V});var Ce=f((Gs,ye)=>{var D=process.env.CODEV_DEBUG==="True",G=class{constructor(e={}){this.currentSessionId=null,this.previousSessionId=null,this.onSessionSwitch=e.onSessionSwitch||null,this.terminateSignal=e.terminateSignal||"CODEV_TERMINATE_SIGNAL"}handleSessionSwitch(e){if(!e)return D&&console.warn("Received empty session ID"),!1;let s=this.previousSessionId!==null&&this.previousSessionId!==e;return s&&(D&&console.log(`Session switch detected: ${this.previousSessionId} -> ${e}`),this.onSessionSwitch&&this.onSessionSwitch({type:this.terminateSignal,reason:"User switch session",agent:"claude",previousSessionId:this.previousSessionId,newSessionId:e})),this.previousSessionId=this.currentSessionId,this.currentSessionId=e,s}getCurrentSessionId(){return this.currentSessionId}getPreviousSessionId(){return this.previousSessionId}hasActiveSession(){return!!this.currentSessionId}terminateCurrentSession(e="Session terminated",s=null,t=null){if(!this.hasActiveSession())return D&&console.log("No active session to terminate"),null;let o={type:this.terminateSignal,reason:t?`terminated by signal: ${t}`:e,code:s,signal:t,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId};return D&&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(){D&&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()}}};ye.exports=G});var Ee=f((Rs,ve)=>{var v=require("fs"),x=require("path"),rs=require("events"),as=require("crypto"),p=process.env.CODEV_DEBUG==="True",R=class extends rs{constructor(e={}){super(),this.watchPaths=e.watchPaths||[],this.excludePatterns=e.excludePatterns||[/node_modules/,/\.git/,/\.DS_Store/,/\.tmp/,/\.log$/,/\.swp$/,/codev\.log/],this.includePatterns=e.includePatterns||[/\.(js|jsx|ts|tsx|py|java|c|cpp|h|hpp|go|rs|rb|php|html|css|scss|sass|less|json|xml|yaml|yml|md|txt)$/],this.watchers=new Map,this.isWatching=!1,this.debounceTimeout=e.debounceTimeout||300,this.pendingChanges=new Map,this.fileContentHashes=new Map,this.enableContentComparison=e.enableContentComparison!==!1,this.onFileChange=e.onFileChange||null}calculateFileHash(e){try{let s=v.readFileSync(e,"utf8");return as.createHash("sha256").update(s).digest("hex")}catch{return null}}hasContentChanged(e){if(!this.enableContentComparison)return!0;let s=this.calculateFileHash(e),t=this.fileContentHashes.get(e);return s===null?t!==void 0?(this.fileContentHashes.delete(e),!0):!1:t===void 0||s!==t?(this.fileContentHashes.set(e,s),!0):!1}preloadFileHashes(e){if(!(!this.enableContentComparison||!v.existsSync(e)))try{let s=v.readdirSync(e,{withFileTypes:!0});for(let t of s){let o=x.join(e,t.name);t.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):t.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(s){p&&console.warn(`Failed to preload hashes for ${e}:`,s.message)}}shouldExcludeDirectory(e){let s=e.replace(/\\/g,"/");for(let t of this.excludePatterns)if(t.test(s)||t.test(x.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){p&&console.log("FileWatchService is already watching");return}let s=e||this.watchPaths;if(s.length===0){p&&console.log("No watch paths specified");return}this.isWatching=!0;for(let t of s)this.enableContentComparison&&this.preloadFileHashes(t),this.watchDirectory(t);p&&(console.log(`FileWatchService started watching ${s.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,s]of this.watchers)try{s.close(),p&&console.log(`Stopped watching: ${e}`)}catch(t){p&&console.error(`Error stopping watcher for ${e}:`,t.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),p&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!v.existsSync(e)){p&&console.warn(`Watch path does not exist: ${e}`);return}if(!v.statSync(e).isDirectory()){p&&console.warn(`Watch path is not a directory: ${e}`);return}try{let t=v.watch(e,{recursive:!0,persistent:!1},(o,n)=>{if(!n)return;let i=x.join(e,n);this.handleFileChange(o,i,e)});this.watchers.set(e,t),p&&console.log(`Started watching directory: ${e}`),t.on("error",o=>{p&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(t){p&&console.error(`Failed to start watching ${e}:`,t.message)}}handleFileChange(e,s,t){if(!this.shouldWatchFile(s))return;let o=`${e}:${s}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,s,t)},this.debounceTimeout))}processFileChange(e,s,t){if(!this.isWatching)return;let o="modified",n=!1;try{v.statSync(s),n=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(n&&(o==="modified"||o==="created")&&!this.hasContentChanged(s)){p&&console.log(`Ignoring false change for: ${x.relative(t,s)}`);return}!n&&o==="deleted"&&this.fileContentHashes.delete(s);let i={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:s,relativePath:x.relative(t,s),watchPath:t,fileExists:n,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(p&&console.log(`File ${o}: ${i.data.relativePath}`),this.emit("fileChange",i),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(i)}catch(a){p&&console.error("Error in file change callback:",a.message)}}shouldWatchFile(e){let s=x.basename(e),t=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(t)||o.test(s))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(t)||o.test(s))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let s=this.watchPaths.indexOf(e);if(s>-1&&(this.watchPaths.splice(s,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),p&&console.log(`Removed watch path: ${e}`)}catch(t){p&&console.error(`Error removing watch path ${e}:`,t.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};ve.exports=R});var be=f((Ks,xe)=>{var cs=$(),ls=require("path"),Ls=require("fs"),Hs=require("os"),us=ue(),hs=fe(),ds=we(),gs=Ce(),fs=Ee(),m=process.env.CODEV_DEBUG==="True",L=class extends cs{constructor(){super({configDir:".",configFile:".claude.json",defaultModel:"Claude Sonnet 4.5",executablePaths:["cc.mjs","/tmp/claude-code/package/cc.mjs"],environmentVariables:e=>({ANTHROPIC_BASE_URL:`${e}/claude`,ANTHROPIC_API_KEY:"codev",DISABLE_TELEMETRY:!0,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,CODEV_SERVER:e}),defaultConfig:{numStartups:1,installMethod:"unknown",autoUpdates:!1,theme:"Coder Dark",customApiKeyResponses:{approved:["codev"]},shiftEnterKeyBindingInstalled:!0,hasCompletedOnboarding:!0,subscriptionNoticeCount:0,hasAvailableSubscription:!0,projects:{}}}),this.fileWatchService=null,this.shutdownInProgress=!1,this.initializeServices()}initializeServices(){this.httpClient=new hs({timeout:1e4}),this.authService=new ds({validateCredentials:!1}),this.sessionManager=new gs({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new us({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return ls.join(e,this.config.configDir,".claude","settings.json")}initializeFileWatchService(){if(!process.env.SESSION_ID){m&&console.log("FileWatchService disabled: SESSION_ID environment variable not found");return}try{this.fileWatchService=new fs({watchPaths:this.getFileWatchPaths(),onFileChange:e=>this.handleFileChange(e),debounceTimeout:300}),m&&console.log("FileWatchService initialized with SESSION_ID:",process.env.SESSION_ID)}catch(e){m&&console.error("Failed to initialize FileWatchService:",e.message)}}getFileWatchPaths(){let e=[],s=process.cwd();e.push(s);let t=process.env.CODEV_WATCH_PATHS;if(t){let o=t.split(",").map(n=>n.trim());e.push(...o)}return e}handleFileChange(e){if(m&&console.log("File change detected:",e.data.relativePath),this.shutdownInProgress)return;let s={message:e,sessionId:e.data.sessionId||process.env.SESSION_ID};this.messageQueue.enqueue(s)}startFileWatching(){this.fileWatchService&&!this.fileWatchService.isWatching&&(this.fileWatchService.startWatching(),m&&console.log("File watching started"))}stopFileWatching(){this.fileWatchService&&this.fileWatchService.isWatching&&(this.fileWatchService.stopWatching(),m&&console.log("File watching stopped"))}onChildMessage(e){e&&e.type==="claude:send-msg"&&this.handleClaudeSendMessage(e.data),super.onChildMessage(e)}handleClaudeSendMessage(e){if(m&&console.log("Handling claude:send-msg message:",e),!e||typeof e!="object"){console.error(`handleClaudeSendMessage: Invalid message data. Expected object, got: ${typeof e}`);return}if(this.shutdownInProgress){m&&console.log("Shutdown in progress, ignoring new message");return}let s=e.sessionId||process.env.SESSION_ID;this.sessionManager.handleSessionSwitch(s),this.messageQueue.enqueue(e)}async processMessage(e){let s=e.data.message,t=e.data.sessionId||process.env.SESSION_ID;if(!t)throw new Error("No session ID available");let o;try{o=typeof s=="string"?JSON.parse(s):s}catch(a){throw new Error(`Failed to parse message data: ${a.message}`)}let n=`/conversations/${t}/@append?task_type=codev`,i=this.authService.hasCredentials()?this.authService.generateAuthHeaders(`${this.httpClient.baseUrl}${n}`,o):{};m&&(console.debug("Sending message to:",n),console.debug("Send Message: ",JSON.stringify(o))),e.type!=="CODEV_TERMINATE_SIGNAL"&&(this.sessionManager.currentSessionId=t)}sendTerminationMessage(e){let s={message:e,sessionId:e.sessionId||this.sessionManager.getCurrentSessionId()};this.messageQueue.enqueue(s)}async handleChildProcessExit(e,s){m&&console.log(`Child process exited with code: ${e}, signal: ${s}`),this.stopFileWatching();let t=this.messageQueue.getQueueSize(),o=this.sessionManager.terminateCurrentSession("process exited normally",e,s);if(o&&this.sendTerminationMessage(o),t>0||o){m&&console.log("Starting graceful shutdown of message queue...");try{let n=!s||s==="SIGTERM",i=this.messageQueue.getQueueSize(),a={timeoutMs:n?8e3:3e3,batchSize:Math.min(i,15),fastMode:!n||i>30};m&&console.log("Shutdown options:",a);let r=await this.messageQueue.gracefulShutdown(a);m&&console.log("Message queue shutdown completed:",r),r.failedMessages>0&&m&&console.warn(`Shutdown summary: ${r.processedMessages} sent, ${r.failedMessages} failed, ${r.remainingMessages} remaining`)}catch(n){m&&console.error("Error during message queue shutdown:",n.message)}}}handleChildProcessError(e){m&&console.error(`Child process error: ${e.message}`);let s=this.sessionManager.createErrorTermination(e);s&&this.sendTerminationMessage(s)}async forceFlushMessages(e=3e3){if(this.messageQueue.getQueueSize()===0)return{success:!0,message:"No messages to flush"};m&&console.log(`Force flushing ${this.messageQueue.getQueueSize()} messages...`);try{return await this.messageQueue.forceFlushAndShutdown(e)}catch(s){return m&&console.error("Force flush failed:",s.message),{success:!1,error:s.message}}}async launch(e={}){let{codevServer:s,auth_ak:t=null,auth_sk:o=null}=e;return this.httpClient.setBaseUrl(s),t&&o&&this.authService.setCredentials(t,o),this.startFileWatching(),super.launch(e)}};xe.exports=L});var De=f((js,Ie)=>{var ms=$(),Ws=require("path"),H=class extends ms{constructor(){super({configDir:".gemini",configFile:"settings.json",defaultModel:"gemini-2.5-pro",executablePaths:["gcli.mjs","../libs/codev-gemini-cli/bundle/gemini.js"],environmentVariables:e=>({GOOGLE_GEMINI_BASE_URL:`${e}/gemini`,GEMINI_API_KEY:"coder",GOOGLE_API_KEY:"coder",GOOGLE_CLOUD_PROJECT:"coder",GOOGLE_CLOUD_LOCATION:"coder",DISABLE_TELEMETRY:!0,GEMINI_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,USE_VERTEX:!0}),defaultConfig:{ide:{hasSeenNudge:!0},telemetry:{enabled:!1,logPrompts:!1},privacy:{usageStatisticsEnabled:!1},general:{disableUpdateNag:!0,preferredEditor:"vscode",previewFeatures:!0},ui:{hideBanner:!0,theme:"Default"},security:{auth:{selectedType:"vertex-ai"}}}})}};Ie.exports=H});var _e=f((zs,Pe)=>{var ps=$(),P=require("path"),b=require("fs"),Ss=require("os"),{spawn:ws}=require("child_process"),K=process.env.CODEV_DEBUG==="True",W=class extends ps{constructor(){super({configDir:".codex",configFile:"config.toml",defaultModel:"o4-mini",executablePaths:["codex.mjs","../dist/codex.mjs"],environmentVariables:e=>({OPENAI_BASE_URL:`${e}/codex`,OPENAI_API_KEY:"codev-proxy-key",DEBUG:K?"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 b.existsSync(e)}catch{return!1}}resloveSettingFilePath(e){return P.join(e,this.config.configDir,"config.toml")}async ensureConfig(e=0){let s=P.join(Ss.homedir(),this.config.configDir,this.config.configFile),t=P.dirname(s);if(!b.existsSync(s)){let o=this.config.defaultConfig||{};try{b.existsSync(t)||b.mkdirSync(t,{recursive:!0});let n=this.generateTOMLConfig(o);b.writeFileSync(s,n),K&&console.log(`Created Codex config file: ${s}`),e>0&&await new Promise(i=>setTimeout(i,e))}catch(n){console.warn(`Failed to create ${this.config.configFile}: ${n.message}`)}}}generateTOMLConfig(e){return`model = "${e.model||"gpt-5-codex"}"`}findExecutablePath(){let e=P.dirname(require.main.filename);for(let s of this.config.executablePaths){let t=P.resolve(e,s);if(b.existsSync(t))return t}throw new Error(`Could not find Codex executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}async launch(e={}){let{remainingArgs:s=[],codevServer:t,auth_ak:o=null,auth_sk:n=null}=e;try{if(!this.checkCodexAvailability())throw new Error("Codex executable not found. Please ensure the Codex CLI is available in libs/codex/codex-cli/bin/");await this.ensureConfig(1e3);let i=this.findExecutablePath();return K&&console.log(`executablePath: ${i}`),new Promise((a,r)=>{let c={...process.env,...this.config.environmentVariables(t)};o&&(c.CODEV_AUTH_AK=o),n&&(c.CODEV_AUTH_SK=n);let l=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&l.push("--inspect-brk"),l.push(i,...s);let h=ws("node",l,{env:c,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(h),h.on("error",g=>{console.error(`Failed to start Codex: ${g.message}`),r(g)}),h.on("exit",async(g,S)=>{console.log(S?`terminated by signal: ${S}`:"Goodbye for now! Keep building great things!")}),process.on("SIGINT",async()=>{console.log(`
Terminating ...`),h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
Terminating ...`),h.kill("SIGTERM"),setTimeout(()=>{h.killed||h.kill("SIGKILL")},8e3)})})}catch(i){throw i}}};Pe.exports=W});var Te=f((Js,Oe)=>{var _=require("fs"),ke=require("path"),{spawn:$e}=require("child_process"),j=class{constructor(){this.extensionId="codev.codev-background";let e=require.main?ke.dirname(require.main.filename):__dirname;this.extensionPath=ke.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(_.existsSync(e))try{return _.accessSync(e,_.constants.F_OK|_.constants.X_OK),this._codeCommand=e,process.env.CODEV_DEBUG&&console.log(`Using AI Studio VSCode path: ${e}`),this._codeCommand}catch(s){process.env.CODEV_DEBUG&&console.log(`AI Studio path exists but not executable: ${s.message}`)}else process.env.CODEV_DEBUG&&console.log(`AI Studio path not found: ${e}`)}try{let{spawn:e}=require("child_process");return new Promise(s=>{let t=e("which",["code"],{stdio:"pipe"}),o="";t.stdout.on("data",n=>{o+=n.toString().trim()}),t.on("close",n=>{n===0&&o?(this._codeCommand=o,process.env.CODEV_DEBUG&&console.log(`Resolved code command path: ${o}`),s(this._codeCommand)):(this._codeCommand="code",s(this._codeCommand))}),t.on("error",()=>{this._codeCommand="code",s(this._codeCommand)}),setTimeout(()=>{t.kill(),this._codeCommand="code",s(this._codeCommand)},3e3)})}catch{return this._codeCommand="code",this._codeCommand}}async shouldInstallExtension(){try{return process.env.IS_AISTUDIO!=="True"?(process.env.CODEV_DEBUG&&console.log("Not in AI Studio environment (IS_AISTUDIO!=True), skipping extension installation"),!1):await this.isVSCodeAvailable()?await this.isExtensionInstalled()?(process.env.CODEV_DEBUG&&console.log(`Extension ${this.extensionId} already installed`),!1):_.existsSync(this.extensionPath)?!0:(console.warn(`VSCode extension file not found: ${this.extensionPath}`),!1):(process.env.CODEV_DEBUG&&console.log("VSCode not available, skipping extension installation"),!1)}catch(e){return process.env.CODEV_DEBUG&&console.error(`Error checking extension installation status: ${e.message}`),!1}}async installExtension(){try{return console.log("Installing Codev VSCode extension..."),await this.executeVSCodeCommand(["--install-extension",this.extensionPath])?(console.log("\u2705 Codev VSCode extension installed successfully"),!0):(console.warn("\u274C Failed to install Codev VSCode extension"),!1)}catch(e){return console.warn(`Error installing VSCode extension: ${e.message}`),!1}}async isVSCodeAvailable(){try{let e=process.env.IS_AISTUDIO==="True"?["--help"]:["--version"],s=await this.executeVSCodeCommand(e,{timeout:1e4});if(process.env.CODEV_DEBUG&&(console.log(`VSCode availability check (${e.join(" ")}): ${s?"available":"unavailable"}`),process.env.IS_AISTUDIO==="True")){let{spawn:t}=require("child_process");try{t("which",["code"],{stdio:"pipe"}).stdout.on("data",n=>{console.log("which code:",n.toString().trim())})}catch(o){console.log("which command failed:",o.message)}}return s}catch(e){return process.env.CODEV_DEBUG&&console.error("VSCode availability check error:",e.message),!1}}async isExtensionInstalled(){let e=await this.resolveCodeCommand();try{return new Promise(s=>{try{let t={stdio:["ignore","pipe","ignore"],shell:!1,env:{...process.env,PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER}};process.env.CODEV_DEBUG&&console.log(`Spawning: ${e} --list-extensions`);let o=$e(e,["--list-extensions"],t),n="";o.stdout.on("data",i=>{n+=i.toString()}),o.on("close",i=>{if(i===0){let a=n.split(`
`).map(r=>r.trim());s(a.includes(this.extensionId))}else s(!1)}),o.on("error",i=>{process.env.CODEV_DEBUG&&(console.error("VSCode list extensions error:",i.message),console.error("Error code:",i.code),console.error("Error errno:",i.errno),console.error("Error syscall:",i.syscall)),s(!1)}),setTimeout(()=>{try{o.kill()}catch{}s(!1)},1e4)}catch(t){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode list extensions:",t.message),s(!1)}})}catch{return!1}}async executeVSCodeCommand(e,s={}){let t=await this.resolveCodeCommand();return new Promise(o=>{try{let n={stdio:"ignore",shell:!1,env:{...process.env,PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER}};process.env.CODEV_DEBUG&&console.log(`Spawning: ${t} ${e.join(" ")}`);let i=$e(t,e,n);i.on("close",r=>{o(r===0)}),i.on("error",r=>{process.env.CODEV_DEBUG&&(console.error("VSCode command error:",r.message),console.error("Error code:",r.code),console.error("Error errno:",r.errno),console.error("Error syscall:",r.syscall)),o(!1)});let a=s.timeout||3e4;setTimeout(()=>{try{i.kill()}catch{}o(!1)},a)}catch(n){process.env.CODEV_DEBUG&&console.error("Failed to spawn VSCode command:",n.message),o(!1)}})}async ensureExtensionInstalled(){try{process.env.CODEV_DEBUG&&console.log("VSCode Extension Service: Checking extension status..."),await this.shouldInstallExtension()&&await this.installExtension()}catch(e){process.env.CODEV_DEBUG&&console.error("VSCode Extension Service Error:",e)}}};Oe.exports=j});var Me=f((Qs,Fe)=>{var w=require("fs"),E=require("path"),ys=require("readline"),{execSync:O}=require("child_process"),Ae=require("os"),z=class{constructor(){this.serverUrl="https://makecoder.com/bigapis/codev/v1/coderpub"}getClaudeJsonlPath(e,s=!1){let t=e.replace(/[/_]/g,"-"),o=E.join(Ae.homedir(),".claude","projects",t);if(s&&(console.log(`
\u{1F4C2} [allow-clone] \u67E5\u627E JSONL \u6587\u4EF6...`),console.log(`   \u9879\u76EE\u76EE\u5F55: ${e}`),console.log(`   Claude \u9879\u76EE\u540D: ${t}`),console.log(`   Claude \u9879\u76EE\u76EE\u5F55: ${o}`)),!w.existsSync(o))return s&&console.log("   \u274C Claude \u9879\u76EE\u76EE\u5F55\u4E0D\u5B58\u5728"),null;s&&console.log("   \u2713 Claude \u9879\u76EE\u76EE\u5F55\u5B58\u5728");try{let n=w.readdirSync(o).filter(i=>i.endsWith(".jsonl")).map(i=>({name:i,path:E.join(o,i),mtime:w.statSync(E.join(o,i)).mtime,size:w.statSync(E.join(o,i)).size})).sort((i,a)=>a.mtime-i.mtime);return s&&(console.log(`   \u627E\u5230 ${n.length} \u4E2A JSONL \u6587\u4EF6:`),n.forEach((i,a)=>{let r=(i.size/1024).toFixed(2),c=i.mtime.toLocaleString(),l=a===0?" <- \u6700\u65B0":"";console.log(`     ${a+1}. ${i.name} (${r} KB, ${c})${l}`)})),n.length>0?(s&&console.log(`   \u2713 \u9009\u62E9\u6700\u65B0\u6587\u4EF6: ${n[0].name}`),n[0].path):(s&&console.log("   \u274C \u76EE\u5F55\u4E2D\u6CA1\u6709 JSONL \u6587\u4EF6"),null)}catch(n){return s&&console.log(`   \u274C \u8BFB\u53D6\u76EE\u5F55\u5931\u8D25: ${n.message}`),null}}async promptForName(){let e=ys.createInterface({input:process.stdin,output:process.stdout});return new Promise((s,t)=>{e.question("\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0 (name): ",o=>{e.close();let n=o.trim();if(!n){t(new Error("\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A"));return}if(!/^[a-zA-Z0-9_-]+$/.test(n)){t(new Error("\u9879\u76EE\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26"));return}s(n)})})}async createZip(e,s={}){let{allowClone:t=!1}=s,o=Ae.tmpdir(),n=`coder-pub-${Date.now()}.zip`,i=E.join(o,n);try{let a=!1;if(w.existsSync(E.join(e,".git")))try{O(`git archive -o "${i}" HEAD`,{cwd:e,stdio:"pipe"}),console.log("\u{1F4E6} \u4F7F\u7528 git archive \u521B\u5EFA\u538B\u7F29\u5305\uFF08\u5DF2\u6392\u9664 .gitignore \u4E2D\u7684\u6587\u4EF6\uFF09"),a=!0}catch{console.log("\u26A0\uFE0F  git archive \u5931\u8D25\uFF0C\u4F7F\u7528\u666E\u901A zip \u547D\u4EE4")}if(!a){let c=[".git/*","node_modules/*",".env",".env.*","*.log",".DS_Store"].map(l=>`-x "${l}"`).join(" ");O(`zip -r "${i}" . ${c}`,{cwd:e,stdio:"pipe"}),console.log("\u{1F4E6} \u5DF2\u521B\u5EFA\u538B\u7F29\u5305")}if(t){console.log(`
\u{1F504} [allow-clone] \u5F00\u59CB\u5904\u7406 AI \u751F\u6210\u8BB0\u5F55...`);let r=this.getClaudeJsonlPath(e,!0);if(r){let c=E.join(o,"coder.pub.jsonl"),h=(w.statSync(r).size/1024).toFixed(2);console.log(`
\u{1F4E6} [allow-clone] \u6253\u5305 JSONL \u6587\u4EF6...`),console.log(`   \u6E90\u6587\u4EF6: ${r}`),console.log(`   \u6587\u4EF6\u5927\u5C0F: ${h} KB`),console.log(`   \u4E34\u65F6\u6587\u4EF6: ${c}`),w.copyFileSync(r,c),console.log("   \u2713 \u5DF2\u590D\u5236\u5230\u4E34\u65F6\u76EE\u5F55"),console.log(`   \u76EE\u6807 ZIP: ${i}`),console.log("   \u76EE\u6807\u6587\u4EF6\u540D: coder.pub.jsonl"),O(`zip -j "${i}" "${c}"`,{stdio:"pipe"}),console.log("   \u2713 \u5DF2\u6DFB\u52A0\u5230 ZIP \u5305"),w.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)
`)}else console.log(`\u26A0\uFE0F  [allow-clone] \u672A\u627E\u5230 Claude Code \u751F\u6210\u8BB0\u5F55
`)}return i}catch(a){throw new Error(`\u521B\u5EFA\u538B\u7F29\u5305\u5931\u8D25: ${a.message}`)}}async upload(e,s,t,o,n,i=!1){let a=n?`${n}/coderpub`:this.serverUrl,r=`${t}.${o}`;console.log("\u{1F4E4} \u6B63\u5728\u4E0A\u4F20\u5230\u670D\u52A1\u5668..."),i&&(console.log(`   \u670D\u52A1\u5668\u5730\u5740: ${a}`),console.log(`   \u9879\u76EE\u540D\u79F0: ${s}`),console.log(`   ZIP \u6587\u4EF6: ${e}`));try{let c=`curl -s -X POST "${a}" -H "Authorization: Bearer ${r}" -F "name=${s}" -F "zip_file=@${e}"`;i&&console.log("   \u6267\u884C\u4E0A\u4F20\u547D\u4EE4...");let l=O(c,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});return i&&console.log("   \u2713 \u4E0A\u4F20\u5B8C\u6210\uFF0C\u89E3\u6790\u54CD\u5E94..."),JSON.parse(l)}catch(c){if(c.stdout)try{return JSON.parse(c.stdout)}catch{throw new Error(`\u4E0A\u4F20\u5931\u8D25: ${c.message}`)}throw new Error(`\u4E0A\u4F20\u5931\u8D25: ${c.message}`)}}cleanup(e){try{w.existsSync(e)&&w.unlinkSync(e)}catch{}}async publish(e){let{ak:s,sk:t,serverBaseUrl:o,allowClone:n}=e,{name:i}=e,a=null;try{i||(i=await this.promptForName()),console.log(`
\u{1F680} \u6B63\u5728\u53D1\u5E03\u9879\u76EE: ${i}`),console.log(`\u{1F4C1} \u76EE\u5F55: ${process.cwd()}`),n&&console.log("\u{1F513} allow-clone: \u542F\u7528 (\u5C06\u5305\u542B AI \u751F\u6210\u8BB0\u5F55)"),console.log(),a=await this.createZip(process.cwd(),{allowClone:n});let c=(w.statSync(a).size/(1024*1024)).toFixed(2);console.log(`\u{1F4CA} \u538B\u7F29\u5305\u5927\u5C0F: ${c} MB`),n&&console.log(`
\u{1F310} [allow-clone] \u5F00\u59CB\u4E0A\u4F20\u5230\u670D\u52A1\u5668...`);let l=await this.upload(a,i,s,t,o,n);return l.code===0?(console.log(`
\u2705 \u53D1\u5E03\u6210\u529F!`),console.log(`\u{1F4CC} \u7248\u672C: ${l.data.version}`),console.log(`\u{1F310} \u8BBF\u95EE\u5730\u5740: https://${i}.coder.pub/`),0):(console.error(`
\u274C \u53D1\u5E03\u5931\u8D25: ${l.message||l.reason}`),1)}catch(r){return console.error(`
\u274C ${r.message}`),1}finally{a&&this.cleanup(a)}}};Fe.exports=z});var Ue=f((Ys,qe)=>{var Cs=ne(),vs=be(),Es=De(),xs=_e(),bs=Te(),Is=Me(),{isPrintMode:Ds}=k(),J=class{constructor(){this.argParser=new Cs,this.claudeLauncher=new vs,this.geminiLauncher=new Es,this.codexLauncher=new xs,this.vscodeExtensionService=new bs,this.publishService=new Is}async run(e=process.argv.slice(2)){try{try{await this.vscodeExtensionService.ensureExtensionInstalled()}catch(t){process.env.CODEV_DEBUG&&console.error("VSCode Extension Service Error:",t)}if(!e.includes("--agent")&&!e.includes("-a")){let t=e.length>0&&["claude","gemini","codex"].includes(e[0]);if(!t&&(e.includes("--help")||e.includes("-h")))return this.argParser.showHelp(),0;if(!t&&(e.includes("--version")||e.includes("-v")))return this.showVersion(),0}let s=await this.argParser.parse(e);return s.command==="pub"?await this.publishService.publish({name:s.pubName,ak:s.auth_ak,sk:s.auth_sk,serverBaseUrl:s.codevServer,allowClone:s.allowClone}):await this.launchAgent(s)}catch(s){return console.error(`Error: ${s.message}`),process.env.CODEV_DEBUG&&console.error("Stack trace:",s.stack),1}}async launchAgent(e){let{agent:s,remainingArgs:t}=e;return Ds(t)||console.log(`cwd:\x1B[90m\x1B[3m ${process.cwd()} \x1B[0m`),s==="claude"?await this.claudeLauncher.launch(e):s==="gemini"?await this.geminiLauncher.launch(e):s==="codex"?await this.codexLauncher.launch(e):1}showVersion(){let e=U();console.log(`coder version: ${e.version}`)}async shutdown(){console.log(`
Shutting down...`),process.exit(0)}};qe.exports=J});var Ps=Ue(),{isPrintMode:_s}=k();process.on("unhandledRejection",(u,e)=>{console.error("Unhandled Promise Rejection:",u),process.exit(1)});process.on("uncaughtException",u=>{console.error("Uncaught Exception:",u.message),process.env.CODEV_DEBUG&&console.error(u.stack),process.exit(1)});async function ks(){_s()||console.log(`Welcome to Coder!
`);let u=new Ps;process.on("SIGINT",async()=>{console.log(`
Received SIGINT, shutting down gracefully...`),await u.shutdown()}),process.on("SIGTERM",async()=>{console.log(`
Received SIGTERM, shutting down gracefully...`),await u.shutdown()});try{let e=await u.run();process.exit(e)}catch(e){console.error(`Fatal error: ${e.message}`),process.env.CODEV_DEBUG&&console.error(e.stack),process.exit(1)}}ks().catch(u=>{console.error(`Startup error: ${u.message}`),process.exit(1)});
