makecoder 2.0.82 → 2.0.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/coder.js CHANGED
@@ -196,7 +196,7 @@ CONFIG:
196
196
  Auth credentials can be stored in config file under "auth" section.
197
197
  `)}};oe.exports=q});var P=f((Fs,re)=>{function Ye(u=process.argv.slice(2)){return u.includes("--print")||u.includes("-p")}re.exports={isPrintMode:Ye}});var $=f((Ms,ce)=>{var{spawn:Ze}=require("child_process"),I=require("path"),E=require("fs"),ie=require("os"),{isPrintMode:ae}=P(),U=class{constructor(e){this.config=e}resloveSettingFilePath(e){return I.join(e,this.config.configDir,"settings.json")}readModelFromSettingsFile(e){try{let s=this.resloveSettingFilePath(e);if(E.existsSync(s)){let t=E.readFileSync(s,"utf8"),o=JSON.parse(t);if(o&&o.model)return o.model}}catch(s){console.warn(e,s.message)}return null}getCurrentModel(e){let s=e.findIndex(o=>o==="--model");if(s!==-1&&s+1<e.length)return e[s+1];let t=this.readModelFromSettingsFile(process.cwd());return t||(t=this.readModelFromSettingsFile(ie.homedir()),t)?t:this.config.defaultModel}async ensureConfig(e=0){let s=I.join(ie.homedir(),this.config.configDir,this.config.configFile),t=I.dirname(s);if(!E.existsSync(s)){let o=this.config.defaultConfig||{};try{E.existsSync(t)||E.mkdirSync(t,{recursive:!0}),E.writeFileSync(s,JSON.stringify(o,null,2)),e>0&&await new Promise(n=>setTimeout(n,e))}catch(n){console.warn(`Failed to create ${this.config.configFile}: ${n.message}`)}}}findExecutablePath(){let e=I.dirname(require.main.filename);for(let s of this.config.executablePaths){let t=I.resolve(e,s);if(E.existsSync(t))return t}throw new Error(`Could not find executable in any of the configured paths: ${this.config.executablePaths.join(", ")}`)}handleChildMessages(e){process.env.CODEV_DEBUG&&console.log("Child process message handler initialized"),e.connected&&(e.on("message",s=>{this.onChildMessage(s)}),e.on("exit",async(s,t)=>{try{await this.handleChildProcessExit(s,t)}catch(o){console.error("Error in handleChildProcessExit:",o.message)}}),e.on("error",s=>{this.handleChildProcessError(s)}))}onChildMessage(e){process.env.CODEV_DEBUG&&console.log("Received IPC message from child:",e)}handleChildProcessExit(e,s){}handleChildProcessError(e){}async launch(e={}){let{remainingArgs:s=[],codevServer:t,auth_ak:o=null,auth_sk:n=null}=e;try{let r=this.getCurrentModel(s);ae(s)||console.log(`model:\x1B[90m\x1B[3m ${r} (use /model to switch models) \x1B[0m`),await this.ensureConfig(1e3);let a=this.findExecutablePath();return process.env.CODEV_DEBUG&&console.log(`executablePath: ${a}`),new Promise((i,c)=>{let l={...process.env,...this.config.environmentVariables(t)};o&&(l.CODEV_AUTH_AK=o),n&&(l.CODEV_AUTH_SK=n);let h=["--no-warnings"];process.env.CODEV_INSPECT_BRK==="True"&&h.push("--inspect-brk"),h.push(a,...s);let g=Ze("node",h,{env:l,stdio:["inherit","inherit","inherit","ipc"]});this.handleChildMessages(g),g.on("error",S=>{console.error(`Failed to start: ${S.message}`),c(S)}),g.on("exit",async(S,Q)=>{ae(s)||Q&&console.log(`terminated by signal: ${Q}`)}),process.on("SIGINT",async()=>{console.log(`
198
198
  Terminating ...`),g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},8e3)}),process.on("SIGTERM",async()=>{console.log(`
199
- Terminating ...`),g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},8e3)})})}catch(r){throw r}}};ce.exports=U});var ue=f((qs,le)=>{var d=process.env.CODEV_DEBUG==="True",B=class{constructor(e={}){this.queue=[],this.processing=!1,this.shuttingDown=!1,this.shutdownTimeout=e.shutdownTimeout||5e3,this.maxRetries=e.maxRetries||3,this.retryDelay=e.retryDelay||1e3,this.onProcessMessage=e.onProcessMessage||null,this.shutdownPromise=null,this.currentlyProcessing=null}enqueue(e){if(this.shuttingDown)return d&&console.log("Queue is shutting down, skipping new messages"),null;let s={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(s),d&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),s.id}dequeue(){let e=this.queue.shift();return d&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let s=this.queue.findIndex(t=>t.id===e);return s>-1?(this.queue.splice(s,1),d&&console.log(`Message ${e} removed from queue`),!0):!1}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{for(;this.queue.length>0&&!this.shuttingDown;){let e=this.queue[0];e.processing=!0;try{this.onProcessMessage&&await this.onProcessMessage(e),this.dequeue()}catch(s){if(d&&console.error(`Failed to process message: ${s.message}`),e.retryCount++,d&&console.log("Start Retry:",e.retryCount,"times..."),e.retryCount>=this.maxRetries)d&&console.error("Message exceeded max retries, removing from queue"),this.dequeue();else{e.processing=!1;let t=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,t))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],d&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let s=this.queue.filter(o=>o.processing);if(s.length===0)return;d&&console.log(`Waiting for ${s.length} processing messages to complete (timeout: ${e}ms)`);let t=Date.now();for(;Date.now()-t<e;){if(this.queue.filter(n=>n.processing).length===0){d&&console.log(`All processing messages completed in ${Date.now()-t}ms`);return}await new Promise(n=>setTimeout(n,50))}if(d){let o=this.queue.filter(n=>n.processing);console.log(`Timeout waiting for processing messages. ${o.length} messages still processing`)}}async gracefulShutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let{timeoutMs:s=this.shutdownTimeout,batchSize:t=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async n=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(s*.3,3e3));let r=this.queue.filter(S=>!S.processing),a=r.length;d&&(console.log(`Starting graceful shutdown with ${a} pending messages (${this.queue.length-a} already processing)`),console.log(`Mode: ${o?"fast (parallel)":"sequential"}, timeout: ${s}ms`));let i=Date.now(),c=0,l=0;try{if(o){let S=await this.processAllParallel(s-(Date.now()-i),r);c=S.processed,l=S.failed}else{let S=await this.processInBatches(t,s-(Date.now()-i),r);c=S.processed,l=S.failed}}catch(S){d&&console.error("Error during shutdown processing:",S.message)}let h=Date.now()-i,g=this.queue.length;d&&(console.log(`Shutdown completed in ${h}ms:`),console.log(` - Total: ${a} messages`),console.log(` - Processed: ${c}`),console.log(` - Failed: ${l}`),console.log(` - Remaining: ${g}`)),n({totalMessages:a,processedMessages:c,failedMessages:l,remainingMessages:g,duration:h,allMessagesSent:g===0&&l===0})}),this.shutdownPromise}async processAllParallel(e){if(this.queue.length===0)return{processed:0,failed:0};d&&console.log(`Processing ${this.queue.length} messages in parallel...`);let s=[...this.queue];this.queue=[];let t=s.map(async i=>{try{return this.onProcessMessage&&await this.onProcessMessage(i),{success:!0,messageId:i.id}}catch(c){return d&&console.warn(`Message ${i.id} processing failed: ${c.message}`),{success:!1,messageId:i.id,error:c}}}),o=new Promise(i=>{setTimeout(()=>i({timedOut:!0}),e)}),n=await Promise.race([Promise.allSettled(t).then(i=>({results:i})),o]);if(n.timedOut)return d&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:s.length};let r=n.results.filter(i=>i.status==="fulfilled"&&i.value?.success).length,a=s.length-r;return{processed:r,failed:a}}async processInBatches(e,s){if(this.queue.length===0)return{processed:0,failed:0};d&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let t=Date.now(),o=0,n=0;for(;this.queue.length>0&&Date.now()-t<s;){let r=this.queue.splice(0,e),a=r.map(async h=>{try{return this.onProcessMessage&&await this.onProcessMessage(h),{success:!0}}catch(g){return d&&console.warn(`Batch message processing failed: ${g.message}`),{success:!1,error:g}}}),c=(await Promise.allSettled(a)).filter(h=>h.status==="fulfilled"&&h.value?.success).length,l=r.length-c;o+=c,n+=l,d&&r.length>0&&console.log(`Batch completed: ${c}/${r.length} successful`),this.queue.length>0&&await new Promise(h=>setTimeout(h,10))}return this.queue.length>0&&(n+=this.queue.length,d&&console.log(`${this.queue.length} messages not processed due to timeout`),this.queue=[]),{processed:o,failed:n}}async forceFlushAndShutdown(e=2e3){this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(e*.4,1e3));let s=this.queue.filter(i=>!i.processing);d&&console.log(`Force flush: attempting to send ${s.length} pending messages within ${e}ms (${this.queue.length-s.length} already processing)`);let t=Date.now(),o=s.map(async i=>{try{return this.onProcessMessage&&Date.now()-t<e?(await this.onProcessMessage(i),{success:!0,messageId:i.id}):{success:!1,messageId:i.id,reason:"timeout"}}catch(c){return{success:!1,messageId:i.id,error:c.message}}}),n=e-(Date.now()-t),r=new Promise(i=>{setTimeout(()=>i({timedOut:!0}),Math.max(100,n))}),a=await Promise.race([Promise.allSettled(o).then(i=>({results:i})),r]);if(s.forEach(i=>{let c=this.queue.findIndex(l=>l.id===i.id);c>-1&&this.queue.splice(c,1)}),this.processing=!1,a.timedOut)return d&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:s.length};{let i=a.results.filter(c=>c.status==="fulfilled"&&c.value.success).length;return d&&console.log(`Force flush completed: ${i}/${s.length} messages sent`),{success:i===s.length,successCount:i,totalCount:s.length,results:a.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,d&&console.log("Force shutdown: Queue cleared")}};le.exports=B});var T=f((Us,Xe)=>{Xe.exports={name:"makecoder",version:"2.0.82",description:"MakeCoder: Unified AI agent CLI tool integrating Claude Code, Codex and Gemini CLI",main:"./dist/coder.js",bin:{coder:"./dist/coder.js"},scripts:{test:'echo "Error: no test specified" && exit 1',start:"node ./src/coder.js",build:"node scripts/build.js","build:clean":"node scripts/build.js --clean","build:dev":"node scripts/build.js --no-minify --sourcemap",postinstall:"node scripts/postinstall.js"},keywords:["cli","ai","claude","gemini","codex","agent"],author:"makecoder",license:"MIT",repository:{type:"git",url:"https://github.com/makecoderai/coder.git"},homepage:"https://github.com/makecoderai/coder",dependencies:{"node-fetch":"^3.3.2",open:"^10.1.0",zod:"^3.25.76"},optionalDependencies:{"makecoder-codex-linux-x64":"*","makecoder-codex-darwin-arm64":"*","makecoder-codex-win32-x64":"*"},engines:{node:">=20.0.0"},devDependencies:{chokidar:"^4.0.3"},files:["dist","claude","scripts/postinstall.js"]}});var fe=f((Bs,ge)=>{var es=require("http"),ss=require("https"),{URL:he}=require("url"),{version:ts}=T(),de=process.env.CODEV_DEBUG==="True",N=class{constructor(e={}){this.baseUrl=e.baseUrl||"",this.timeout=e.timeout||3e4,this.defaultHeaders={"Content-Type":"application/json","User-Agent":`codev-cli/${ts}`,...e.headers}}setBaseUrl(e){this.baseUrl=e}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}async post(e,s,t={}){let o=this.resolveUrl(e),n={...this.defaultHeaders,...t.headers};return new Promise((r,a)=>{this.validateRequest(o,s,a);let i=this.serializeData(s,a);if(!i)return;n["Content-Length"]=Buffer.byteLength(i);let c=this.buildRequestOptions(o,"POST",n),l=this.getHttpModule(o);de&&console.debug(`HTTP POST to ${o} with data length: ${i.length}`);let h=l.request(c,g=>{this.handleResponse(g,r,a)});this.attachErrorHandlers(h,o,a),h.setTimeout(this.timeout),h.write(i),h.end()})}resolveUrl(e){return e.startsWith("http")?e:`${this.baseUrl}${e.startsWith("/")?"":"/"}${e}`}validateRequest(e,s,t){return!e||typeof e!="string"?(t(new Error(`Invalid URL: ${e}`)),!1):s?!0:(t(new Error("No data provided for HTTP POST")),!1)}serializeData(e,s){try{return typeof e=="string"?e:JSON.stringify(e)}catch(t){return s(new Error(`Failed to serialize data: ${t.message}`)),null}}buildRequestOptions(e,s,t){let o=new he(e),n=o.protocol==="https:";return{hostname:o.hostname,port:o.port||(n?443:80),path:o.pathname+o.search,method:s,headers:t}}getHttpModule(e){return new he(e).protocol==="https:"?ss:es}handleResponse(e,s,t){de&&console.debug(`HTTP response status: ${e.statusCode}`);let o="";e.on("data",n=>{o+=n}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?s({statusCode:e.statusCode,data:o,headers:e.headers}):t(new Error(`HTTP request returned status ${e.statusCode}: ${o}`))})}attachErrorHandlers(e,s,t){e.on("error",o=>{t(new Error(`HTTP POST request failed: ${o.message}`))}),e.on("timeout",()=>{t(new Error(`HTTP POST request timed out for URL: ${s}`)),e.destroy()})}};ge.exports=N});var pe=f((Ns,me)=>{var os=require("crypto"),{URL:ns}=require("url"),R=class{static generateSignature(e,s,t,o){try{let n=new ns(e),r=Buffer.from(n.pathname),a=Buffer.from(r),i=s?typeof s=="string"?Buffer.from(s):Buffer.from(JSON.stringify(s)):Buffer.alloc(0),c=Buffer.concat([a,i,Buffer.from(o)]),l=os.createHmac("sha256",t);return l.update(c),l.digest("hex")}catch(n){throw new Error(`Failed to generate signature: ${n.message}`)}}static validateSignature(e,s,t,o,n){return this.generateSignature(e,s,t,o)===n}static generateTimestamp(){return Date.now().toString()}};me.exports=R});var ye=f((Rs,Se)=>{var rs=pe(),V=class{constructor(e={}){this.accessKey=null,this.secretKey=null,this.validateCredentials=e.validateCredentials!==!1}setCredentials(e,s){if(this.validateCredentials&&(!e||!s))throw new Error("Both access key and secret key are required");this.accessKey=e,this.secretKey=s}hasCredentials(){return!!(this.accessKey&&this.secretKey)}generateAuthHeaders(e,s=null){if(!this.hasCredentials())return{};try{return{AUTHORIZATION:`Bearer ${this.accessKey}.${this.secretKey}`}}catch(t){throw new Error(`Failed to generate auth headers: ${t.message}`)}}validateAuthHeaders(e,s,t,o){if(!this.hasCredentials())throw new Error("No credentials available for validation");return rs.validateSignature(e,s,this.secretKey,t,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};Se.exports=V});var Ce=f((Vs,we)=>{var k=process.env.CODEV_DEBUG==="True",G=class{constructor(e={}){this.currentSessionId=null,this.previousSessionId=null,this.onSessionSwitch=e.onSessionSwitch||null,this.terminateSignal=e.terminateSignal||"CODEV_TERMINATE_SIGNAL"}handleSessionSwitch(e){if(!e)return k&&console.warn("Received empty session ID"),!1;let s=this.previousSessionId!==null&&this.previousSessionId!==e;return s&&(k&&console.log(`Session switch detected: ${this.previousSessionId} -> ${e}`),this.onSessionSwitch&&this.onSessionSwitch({type:this.terminateSignal,reason:"User switch session",agent:"claude",previousSessionId:this.previousSessionId,newSessionId:e})),this.previousSessionId=this.currentSessionId,this.currentSessionId=e,s}getCurrentSessionId(){return this.currentSessionId}getPreviousSessionId(){return this.previousSessionId}hasActiveSession(){return!!this.currentSessionId}terminateCurrentSession(e="Session terminated",s=null,t=null){if(!this.hasActiveSession())return k&&console.log("No active session to terminate"),null;let o={type:this.terminateSignal,reason:t?`terminated by signal: ${t}`:e,code:s,signal:t,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId};return k&&console.log("Terminating session:",o),this.previousSessionId=null,this.currentSessionId=null,o}createErrorTermination(e){return this.hasActiveSession()?{type:this.terminateSignal,error:e.message,stack:e.stack,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId}:null}reset(){k&&console.log("Resetting session manager"),this.currentSessionId=null,this.previousSessionId=null}setSessionSwitchCallback(e){this.onSessionSwitch=e}getSessionInfo(){return{currentSessionId:this.currentSessionId,previousSessionId:this.previousSessionId,hasActiveSession:this.hasActiveSession()}}};we.exports=G});var ve=f((Gs,Ee)=>{var v=require("fs"),b=require("path"),is=require("events"),as=require("crypto"),p=process.env.CODEV_DEBUG==="True",L=class extends is{constructor(e={}){super(),this.watchPaths=e.watchPaths||[],this.excludePatterns=e.excludePatterns||[/node_modules/,/\.git/,/\.DS_Store/,/\.tmp/,/\.log$/,/\.swp$/,/codev\.log/],this.includePatterns=e.includePatterns||[/\.(js|jsx|ts|tsx|py|java|c|cpp|h|hpp|go|rs|rb|php|html|css|scss|sass|less|json|xml|yaml|yml|md|txt)$/],this.watchers=new Map,this.isWatching=!1,this.debounceTimeout=e.debounceTimeout||300,this.pendingChanges=new Map,this.fileContentHashes=new Map,this.enableContentComparison=e.enableContentComparison!==!1,this.onFileChange=e.onFileChange||null}calculateFileHash(e){try{let s=v.readFileSync(e,"utf8");return as.createHash("sha256").update(s).digest("hex")}catch{return null}}hasContentChanged(e){if(!this.enableContentComparison)return!0;let s=this.calculateFileHash(e),t=this.fileContentHashes.get(e);return s===null?t!==void 0?(this.fileContentHashes.delete(e),!0):!1:t===void 0||s!==t?(this.fileContentHashes.set(e,s),!0):!1}preloadFileHashes(e){if(!(!this.enableContentComparison||!v.existsSync(e)))try{let s=v.readdirSync(e,{withFileTypes:!0});for(let t of s){let o=b.join(e,t.name);t.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):t.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(s){p&&console.warn(`Failed to preload hashes for ${e}:`,s.message)}}shouldExcludeDirectory(e){let s=e.replace(/\\/g,"/");for(let t of this.excludePatterns)if(t.test(s)||t.test(b.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){p&&console.log("FileWatchService is already watching");return}let s=e||this.watchPaths;if(s.length===0){p&&console.log("No watch paths specified");return}this.isWatching=!0;for(let t of s)this.enableContentComparison&&this.preloadFileHashes(t),this.watchDirectory(t);p&&(console.log(`FileWatchService started watching ${s.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,s]of this.watchers)try{s.close(),p&&console.log(`Stopped watching: ${e}`)}catch(t){p&&console.error(`Error stopping watcher for ${e}:`,t.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),p&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!v.existsSync(e)){p&&console.warn(`Watch path does not exist: ${e}`);return}if(!v.statSync(e).isDirectory()){p&&console.warn(`Watch path is not a directory: ${e}`);return}try{let t=v.watch(e,{recursive:!0,persistent:!1},(o,n)=>{if(!n)return;let r=b.join(e,n);this.handleFileChange(o,r,e)});this.watchers.set(e,t),p&&console.log(`Started watching directory: ${e}`),t.on("error",o=>{p&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(t){p&&console.error(`Failed to start watching ${e}:`,t.message)}}handleFileChange(e,s,t){if(!this.shouldWatchFile(s))return;let o=`${e}:${s}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,s,t)},this.debounceTimeout))}processFileChange(e,s,t){if(!this.isWatching)return;let o="modified",n=!1;try{v.statSync(s),n=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(n&&(o==="modified"||o==="created")&&!this.hasContentChanged(s)){p&&console.log(`Ignoring false change for: ${b.relative(t,s)}`);return}!n&&o==="deleted"&&this.fileContentHashes.delete(s);let r={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:s,relativePath:b.relative(t,s),watchPath:t,fileExists:n,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(p&&console.log(`File ${o}: ${r.data.relativePath}`),this.emit("fileChange",r),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(r)}catch(a){p&&console.error("Error in file change callback:",a.message)}}shouldWatchFile(e){let s=b.basename(e),t=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(t)||o.test(s))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(t)||o.test(s))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let s=this.watchPaths.indexOf(e);if(s>-1&&(this.watchPaths.splice(s,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),p&&console.log(`Removed watch path: ${e}`)}catch(t){p&&console.error(`Error removing watch path ${e}:`,t.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};Ee.exports=L});var be=f((Ks,xe)=>{var cs=$(),ls=require("path"),Ls=require("fs"),Hs=require("os"),us=ue(),hs=fe(),ds=ye(),gs=Ce(),fs=ve(),m=process.env.CODEV_DEBUG==="True",H=class extends cs{constructor(){super({configDir:".",configFile:".claude.json",defaultModel:"Claude Sonnet 4.5",executablePaths:["cc.mjs","/tmp/claude-code/package/cc.mjs"],environmentVariables:e=>({ANTHROPIC_BASE_URL:`${e}/claude`,ANTHROPIC_API_KEY:"codev",DISABLE_TELEMETRY:!0,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,CODEV_SERVER:e,CLAUDE_CODE_ATTRIBUTION_HEADER:"0"}),defaultConfig:{numStartups:1,installMethod:"unknown",autoUpdates:!1,theme:"Coder Dark",customApiKeyResponses:{approved:["codev"]},shiftEnterKeyBindingInstalled:!0,hasCompletedOnboarding:!0,subscriptionNoticeCount:0,hasAvailableSubscription:!0,projects:{}}}),this.fileWatchService=null,this.shutdownInProgress=!1,this.initializeServices()}initializeServices(){this.httpClient=new hs({timeout:1e4}),this.authService=new ds({validateCredentials:!1}),this.sessionManager=new gs({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new us({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return ls.join(e,this.config.configDir,".claude","settings.json")}initializeFileWatchService(){if(!process.env.SESSION_ID){m&&console.log("FileWatchService disabled: SESSION_ID environment variable not found");return}try{this.fileWatchService=new fs({watchPaths:this.getFileWatchPaths(),onFileChange:e=>this.handleFileChange(e),debounceTimeout:300}),m&&console.log("FileWatchService initialized with SESSION_ID:",process.env.SESSION_ID)}catch(e){m&&console.error("Failed to initialize FileWatchService:",e.message)}}getFileWatchPaths(){let e=[],s=process.cwd();e.push(s);let t=process.env.CODEV_WATCH_PATHS;if(t){let o=t.split(",").map(n=>n.trim());e.push(...o)}return e}handleFileChange(e){if(m&&console.log("File change detected:",e.data.relativePath),this.shutdownInProgress)return;let s={message:e,sessionId:e.data.sessionId||process.env.SESSION_ID};this.messageQueue.enqueue(s)}startFileWatching(){this.fileWatchService&&!this.fileWatchService.isWatching&&(this.fileWatchService.startWatching(),m&&console.log("File watching started"))}stopFileWatching(){this.fileWatchService&&this.fileWatchService.isWatching&&(this.fileWatchService.stopWatching(),m&&console.log("File watching stopped"))}onChildMessage(e){e&&e.type==="claude:send-msg"&&this.handleClaudeSendMessage(e.data),super.onChildMessage(e)}handleClaudeSendMessage(e){if(m&&console.log("Handling claude:send-msg message:",e),!e||typeof e!="object"){console.error(`handleClaudeSendMessage: Invalid message data. Expected object, got: ${typeof e}`);return}if(this.shutdownInProgress){m&&console.log("Shutdown in progress, ignoring new message");return}let s=e.sessionId||process.env.SESSION_ID;this.sessionManager.handleSessionSwitch(s),this.messageQueue.enqueue(e)}async processMessage(e){let s=e.data.message,t=e.data.sessionId||process.env.SESSION_ID;if(!t)throw new Error("No session ID available");let o;try{o=typeof s=="string"?JSON.parse(s):s}catch(a){throw new Error(`Failed to parse message data: ${a.message}`)}let n=`/conversations/${t}/@append?task_type=codev`,r=this.authService.hasCredentials()?this.authService.generateAuthHeaders(`${this.httpClient.baseUrl}${n}`,o):{};m&&(console.debug("Sending message to:",n),console.debug("Send Message: ",JSON.stringify(o))),e.type!=="CODEV_TERMINATE_SIGNAL"&&(this.sessionManager.currentSessionId=t)}sendTerminationMessage(e){let s={message:e,sessionId:e.sessionId||this.sessionManager.getCurrentSessionId()};this.messageQueue.enqueue(s)}async handleChildProcessExit(e,s){m&&console.log(`Child process exited with code: ${e}, signal: ${s}`),this.stopFileWatching();let t=this.messageQueue.getQueueSize(),o=this.sessionManager.terminateCurrentSession("process exited normally",e,s);if(o&&this.sendTerminationMessage(o),t>0||o){m&&console.log("Starting graceful shutdown of message queue...");try{let n=!s||s==="SIGTERM",r=this.messageQueue.getQueueSize(),a={timeoutMs:n?8e3:3e3,batchSize:Math.min(r,15),fastMode:!n||r>30};m&&console.log("Shutdown options:",a);let i=await this.messageQueue.gracefulShutdown(a);m&&console.log("Message queue shutdown completed:",i),i.failedMessages>0&&m&&console.warn(`Shutdown summary: ${i.processedMessages} sent, ${i.failedMessages} failed, ${i.remainingMessages} remaining`)}catch(n){m&&console.error("Error during message queue shutdown:",n.message)}}}handleChildProcessError(e){m&&console.error(`Child process error: ${e.message}`);let s=this.sessionManager.createErrorTermination(e);s&&this.sendTerminationMessage(s)}async forceFlushMessages(e=3e3){if(this.messageQueue.getQueueSize()===0)return{success:!0,message:"No messages to flush"};m&&console.log(`Force flushing ${this.messageQueue.getQueueSize()} messages...`);try{return await this.messageQueue.forceFlushAndShutdown(e)}catch(s){return m&&console.error("Force flush failed:",s.message),{success:!1,error:s.message}}}async launch(e={}){let{codevServer:s,auth_ak:t=null,auth_sk:o=null}=e;return this.httpClient.setBaseUrl(s),t&&o&&this.authService.setCredentials(t,o),this.startFileWatching(),super.launch(e)}};xe.exports=H});var ke=f((Ws,Ie)=>{var ms=$(),zs=require("path"),K=class extends ms{constructor(){super({configDir:".gemini",configFile:"settings.json",defaultModel:"gemini-2.5-pro",executablePaths:["gemini/gemini.js","../dist/gemini/gemini.js"],environmentVariables:e=>({GOOGLE_GEMINI_BASE_URL:`${e}/gemini`,GEMINI_API_KEY:"coder",GOOGLE_API_KEY:"coder",GOOGLE_CLOUD_PROJECT:"coder",GOOGLE_CLOUD_LOCATION:"coder",DISABLE_TELEMETRY:!0,GEMINI_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,USE_VERTEX:!0}),defaultConfig:{ide:{hasSeenNudge:!0},telemetry:{enabled:!1,logPrompts:!1},privacy:{usageStatisticsEnabled:!1},general:{disableUpdateNag:!0,preferredEditor:"vscode",previewFeatures:!0},ui:{hideBanner:!0,theme:"Default"},security:{auth:{selectedType:"vertex-ai"}}}})}};Ie.exports=K});var De=f((js,_e)=>{var ps=$(),_=require("path"),w=require("fs"),Ss=require("os"),{spawn:ys}=require("child_process"),O=process.env.CODEV_DEBUG==="True",z=class extends ps{constructor(){super({configDir:".codex",configFile:"config.toml",defaultModel:"o4-mini",executablePaths:["codex.mjs","../dist/codex.mjs"],environmentVariables:e=>({OPENAI_BASE_URL:`${e}/codex`,OPENAI_API_KEY:"codev-proxy-key",DEBUG:O?"true":"false",CODEX_QUIET_MODE:"0",OPENAI_DISABLE_TELEMETRY:"true",CODEX_DISABLE_PROJECT_DOC:"0",CODEV_SERVER:e}),defaultConfig:{model:"gpt-5-codex",approvalMode:"suggest",fullAutoErrorMode:"ask-user",notify:[],history:{maxSize:1e3,saveHistory:!0,sensitivePatterns:[],persistence:"save-all"}}})}checkCodexAvailability(){try{let e=this.findExecutablePath();return w.existsSync(e)}catch{return!1}}resloveSettingFilePath(e){return _.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,s=0){let t=_.join(Ss.homedir(),this.config.configDir,this.config.configFile),o=_.dirname(t);try{w.existsSync(o)||w.mkdirSync(o,{recursive:!0});let n=`${e}/codex`;if(w.existsSync(t)){let r=w.readFileSync(t,"utf8"),a=`openai_base_url = "${n}"`;/^openai_base_url\s*=/m.test(r)?r=r.replace(/^openai_base_url\s*=.*/m,a):r=r.trimEnd()+`
199
+ Terminating ...`),g.kill("SIGTERM"),setTimeout(()=>{g.killed||g.kill("SIGKILL")},8e3)})})}catch(r){throw r}}};ce.exports=U});var ue=f((qs,le)=>{var d=process.env.CODEV_DEBUG==="True",B=class{constructor(e={}){this.queue=[],this.processing=!1,this.shuttingDown=!1,this.shutdownTimeout=e.shutdownTimeout||5e3,this.maxRetries=e.maxRetries||3,this.retryDelay=e.retryDelay||1e3,this.onProcessMessage=e.onProcessMessage||null,this.shutdownPromise=null,this.currentlyProcessing=null}enqueue(e){if(this.shuttingDown)return d&&console.log("Queue is shutting down, skipping new messages"),null;let s={id:Date.now()+Math.random(),data:e,timestamp:Date.now(),retryCount:0,processing:!1};return this.queue.push(s),d&&console.log(`Message enqueued, queue length: ${this.queue.length}`),this.processQueue(),s.id}dequeue(){let e=this.queue.shift();return d&&e&&console.log(`Message dequeued, remaining queue length: ${this.queue.length}`),e}removeById(e){let s=this.queue.findIndex(t=>t.id===e);return s>-1?(this.queue.splice(s,1),d&&console.log(`Message ${e} removed from queue`),!0):!1}async processQueue(){if(!(this.processing||this.queue.length===0)){this.processing=!0;try{for(;this.queue.length>0&&!this.shuttingDown;){let e=this.queue[0];e.processing=!0;try{this.onProcessMessage&&await this.onProcessMessage(e),this.dequeue()}catch(s){if(d&&console.error(`Failed to process message: ${s.message}`),e.retryCount++,d&&console.log("Start Retry:",e.retryCount,"times..."),e.retryCount>=this.maxRetries)d&&console.error("Message exceeded max retries, removing from queue"),this.dequeue();else{e.processing=!1;let t=this.shuttingDown?100:this.retryDelay*e.retryCount;await new Promise(o=>setTimeout(o,t))}}}}finally{this.processing=!1}}}getQueueSize(){return this.queue.length}clear(){this.queue=[],d&&console.log("Message queue cleared")}setMessageProcessor(e){this.onProcessMessage=e}async waitForProcessingMessages(e=5e3){let s=this.queue.filter(o=>o.processing);if(s.length===0)return;d&&console.log(`Waiting for ${s.length} processing messages to complete (timeout: ${e}ms)`);let t=Date.now();for(;Date.now()-t<e;){if(this.queue.filter(n=>n.processing).length===0){d&&console.log(`All processing messages completed in ${Date.now()-t}ms`);return}await new Promise(n=>setTimeout(n,50))}if(d){let o=this.queue.filter(n=>n.processing);console.log(`Timeout waiting for processing messages. ${o.length} messages still processing`)}}async gracefulShutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;let{timeoutMs:s=this.shutdownTimeout,batchSize:t=10,fastMode:o=!1}=e;return this.shutdownPromise=new Promise(async n=>{this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(s*.3,3e3));let r=this.queue.filter(S=>!S.processing),a=r.length;d&&(console.log(`Starting graceful shutdown with ${a} pending messages (${this.queue.length-a} already processing)`),console.log(`Mode: ${o?"fast (parallel)":"sequential"}, timeout: ${s}ms`));let i=Date.now(),c=0,l=0;try{if(o){let S=await this.processAllParallel(s-(Date.now()-i),r);c=S.processed,l=S.failed}else{let S=await this.processInBatches(t,s-(Date.now()-i),r);c=S.processed,l=S.failed}}catch(S){d&&console.error("Error during shutdown processing:",S.message)}let h=Date.now()-i,g=this.queue.length;d&&(console.log(`Shutdown completed in ${h}ms:`),console.log(` - Total: ${a} messages`),console.log(` - Processed: ${c}`),console.log(` - Failed: ${l}`),console.log(` - Remaining: ${g}`)),n({totalMessages:a,processedMessages:c,failedMessages:l,remainingMessages:g,duration:h,allMessagesSent:g===0&&l===0})}),this.shutdownPromise}async processAllParallel(e){if(this.queue.length===0)return{processed:0,failed:0};d&&console.log(`Processing ${this.queue.length} messages in parallel...`);let s=[...this.queue];this.queue=[];let t=s.map(async i=>{try{return this.onProcessMessage&&await this.onProcessMessage(i),{success:!0,messageId:i.id}}catch(c){return d&&console.warn(`Message ${i.id} processing failed: ${c.message}`),{success:!1,messageId:i.id,error:c}}}),o=new Promise(i=>{setTimeout(()=>i({timedOut:!0}),e)}),n=await Promise.race([Promise.allSettled(t).then(i=>({results:i})),o]);if(n.timedOut)return d&&console.log(`Parallel processing timed out after ${e}ms`),{processed:0,failed:s.length};let r=n.results.filter(i=>i.status==="fulfilled"&&i.value?.success).length,a=s.length-r;return{processed:r,failed:a}}async processInBatches(e,s){if(this.queue.length===0)return{processed:0,failed:0};d&&console.log(`Processing ${this.queue.length} messages in batches of ${e}...`);let t=Date.now(),o=0,n=0;for(;this.queue.length>0&&Date.now()-t<s;){let r=this.queue.splice(0,e),a=r.map(async h=>{try{return this.onProcessMessage&&await this.onProcessMessage(h),{success:!0}}catch(g){return d&&console.warn(`Batch message processing failed: ${g.message}`),{success:!1,error:g}}}),c=(await Promise.allSettled(a)).filter(h=>h.status==="fulfilled"&&h.value?.success).length,l=r.length-c;o+=c,n+=l,d&&r.length>0&&console.log(`Batch completed: ${c}/${r.length} successful`),this.queue.length>0&&await new Promise(h=>setTimeout(h,10))}return this.queue.length>0&&(n+=this.queue.length,d&&console.log(`${this.queue.length} messages not processed due to timeout`),this.queue=[]),{processed:o,failed:n}}async forceFlushAndShutdown(e=2e3){this.shuttingDown=!0,await this.waitForProcessingMessages(Math.min(e*.4,1e3));let s=this.queue.filter(i=>!i.processing);d&&console.log(`Force flush: attempting to send ${s.length} pending messages within ${e}ms (${this.queue.length-s.length} already processing)`);let t=Date.now(),o=s.map(async i=>{try{return this.onProcessMessage&&Date.now()-t<e?(await this.onProcessMessage(i),{success:!0,messageId:i.id}):{success:!1,messageId:i.id,reason:"timeout"}}catch(c){return{success:!1,messageId:i.id,error:c.message}}}),n=e-(Date.now()-t),r=new Promise(i=>{setTimeout(()=>i({timedOut:!0}),Math.max(100,n))}),a=await Promise.race([Promise.allSettled(o).then(i=>({results:i})),r]);if(s.forEach(i=>{let c=this.queue.findIndex(l=>l.id===i.id);c>-1&&this.queue.splice(c,1)}),this.processing=!1,a.timedOut)return d&&console.log(`Force flush timed out after ${e}ms`),{success:!1,reason:"timeout",attemptedCount:s.length};{let i=a.results.filter(c=>c.status==="fulfilled"&&c.value.success).length;return d&&console.log(`Force flush completed: ${i}/${s.length} messages sent`),{success:i===s.length,successCount:i,totalCount:s.length,results:a.results}}}forceShutdown(){this.shuttingDown=!0,this.queue=[],this.processing=!1,d&&console.log("Force shutdown: Queue cleared")}};le.exports=B});var T=f((Us,Xe)=>{Xe.exports={name:"makecoder",version:"2.0.83",description:"MakeCoder: Unified AI agent CLI tool integrating Claude Code, Codex and Gemini CLI",main:"./dist/coder.js",bin:{coder:"./dist/coder.js"},scripts:{test:'echo "Error: no test specified" && exit 1',start:"node ./src/coder.js",build:"node scripts/build.js","build:clean":"node scripts/build.js --clean","build:dev":"node scripts/build.js --no-minify --sourcemap",postinstall:"node scripts/postinstall.js"},keywords:["cli","ai","claude","gemini","codex","agent"],author:"makecoder",license:"MIT",repository:{type:"git",url:"https://github.com/makecoderai/coder.git"},homepage:"https://github.com/makecoderai/coder",dependencies:{"node-fetch":"^3.3.2",open:"^10.1.0",zod:"^3.25.76"},optionalDependencies:{"makecoder-codex-linux-x64":"*","makecoder-codex-darwin-arm64":"*","makecoder-codex-win32-x64":"*"},engines:{node:">=20.0.0"},devDependencies:{chokidar:"^4.0.3"},files:["dist","claude","scripts/postinstall.js"]}});var fe=f((Bs,ge)=>{var es=require("http"),ss=require("https"),{URL:he}=require("url"),{version:ts}=T(),de=process.env.CODEV_DEBUG==="True",N=class{constructor(e={}){this.baseUrl=e.baseUrl||"",this.timeout=e.timeout||3e4,this.defaultHeaders={"Content-Type":"application/json","User-Agent":`codev-cli/${ts}`,...e.headers}}setBaseUrl(e){this.baseUrl=e}setDefaultHeaders(e){this.defaultHeaders={...this.defaultHeaders,...e}}async post(e,s,t={}){let o=this.resolveUrl(e),n={...this.defaultHeaders,...t.headers};return new Promise((r,a)=>{this.validateRequest(o,s,a);let i=this.serializeData(s,a);if(!i)return;n["Content-Length"]=Buffer.byteLength(i);let c=this.buildRequestOptions(o,"POST",n),l=this.getHttpModule(o);de&&console.debug(`HTTP POST to ${o} with data length: ${i.length}`);let h=l.request(c,g=>{this.handleResponse(g,r,a)});this.attachErrorHandlers(h,o,a),h.setTimeout(this.timeout),h.write(i),h.end()})}resolveUrl(e){return e.startsWith("http")?e:`${this.baseUrl}${e.startsWith("/")?"":"/"}${e}`}validateRequest(e,s,t){return!e||typeof e!="string"?(t(new Error(`Invalid URL: ${e}`)),!1):s?!0:(t(new Error("No data provided for HTTP POST")),!1)}serializeData(e,s){try{return typeof e=="string"?e:JSON.stringify(e)}catch(t){return s(new Error(`Failed to serialize data: ${t.message}`)),null}}buildRequestOptions(e,s,t){let o=new he(e),n=o.protocol==="https:";return{hostname:o.hostname,port:o.port||(n?443:80),path:o.pathname+o.search,method:s,headers:t}}getHttpModule(e){return new he(e).protocol==="https:"?ss:es}handleResponse(e,s,t){de&&console.debug(`HTTP response status: ${e.statusCode}`);let o="";e.on("data",n=>{o+=n}),e.on("end",()=>{e.statusCode>=200&&e.statusCode<300?s({statusCode:e.statusCode,data:o,headers:e.headers}):t(new Error(`HTTP request returned status ${e.statusCode}: ${o}`))})}attachErrorHandlers(e,s,t){e.on("error",o=>{t(new Error(`HTTP POST request failed: ${o.message}`))}),e.on("timeout",()=>{t(new Error(`HTTP POST request timed out for URL: ${s}`)),e.destroy()})}};ge.exports=N});var pe=f((Ns,me)=>{var os=require("crypto"),{URL:ns}=require("url"),R=class{static generateSignature(e,s,t,o){try{let n=new ns(e),r=Buffer.from(n.pathname),a=Buffer.from(r),i=s?typeof s=="string"?Buffer.from(s):Buffer.from(JSON.stringify(s)):Buffer.alloc(0),c=Buffer.concat([a,i,Buffer.from(o)]),l=os.createHmac("sha256",t);return l.update(c),l.digest("hex")}catch(n){throw new Error(`Failed to generate signature: ${n.message}`)}}static validateSignature(e,s,t,o,n){return this.generateSignature(e,s,t,o)===n}static generateTimestamp(){return Date.now().toString()}};me.exports=R});var ye=f((Rs,Se)=>{var rs=pe(),V=class{constructor(e={}){this.accessKey=null,this.secretKey=null,this.validateCredentials=e.validateCredentials!==!1}setCredentials(e,s){if(this.validateCredentials&&(!e||!s))throw new Error("Both access key and secret key are required");this.accessKey=e,this.secretKey=s}hasCredentials(){return!!(this.accessKey&&this.secretKey)}generateAuthHeaders(e,s=null){if(!this.hasCredentials())return{};try{return{AUTHORIZATION:`Bearer ${this.accessKey}.${this.secretKey}`}}catch(t){throw new Error(`Failed to generate auth headers: ${t.message}`)}}validateAuthHeaders(e,s,t,o){if(!this.hasCredentials())throw new Error("No credentials available for validation");return rs.validateSignature(e,s,this.secretKey,t,o)}clearCredentials(){this.accessKey=null,this.secretKey=null}getCredentials(){return{accessKey:this.accessKey,hasCredentials:this.hasCredentials()}}};Se.exports=V});var Ce=f((Vs,we)=>{var k=process.env.CODEV_DEBUG==="True",G=class{constructor(e={}){this.currentSessionId=null,this.previousSessionId=null,this.onSessionSwitch=e.onSessionSwitch||null,this.terminateSignal=e.terminateSignal||"CODEV_TERMINATE_SIGNAL"}handleSessionSwitch(e){if(!e)return k&&console.warn("Received empty session ID"),!1;let s=this.previousSessionId!==null&&this.previousSessionId!==e;return s&&(k&&console.log(`Session switch detected: ${this.previousSessionId} -> ${e}`),this.onSessionSwitch&&this.onSessionSwitch({type:this.terminateSignal,reason:"User switch session",agent:"claude",previousSessionId:this.previousSessionId,newSessionId:e})),this.previousSessionId=this.currentSessionId,this.currentSessionId=e,s}getCurrentSessionId(){return this.currentSessionId}getPreviousSessionId(){return this.previousSessionId}hasActiveSession(){return!!this.currentSessionId}terminateCurrentSession(e="Session terminated",s=null,t=null){if(!this.hasActiveSession())return k&&console.log("No active session to terminate"),null;let o={type:this.terminateSignal,reason:t?`terminated by signal: ${t}`:e,code:s,signal:t,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId};return k&&console.log("Terminating session:",o),this.previousSessionId=null,this.currentSessionId=null,o}createErrorTermination(e){return this.hasActiveSession()?{type:this.terminateSignal,error:e.message,stack:e.stack,timestamp:Date.now(),agent:"claude",sessionId:this.currentSessionId}:null}reset(){k&&console.log("Resetting session manager"),this.currentSessionId=null,this.previousSessionId=null}setSessionSwitchCallback(e){this.onSessionSwitch=e}getSessionInfo(){return{currentSessionId:this.currentSessionId,previousSessionId:this.previousSessionId,hasActiveSession:this.hasActiveSession()}}};we.exports=G});var ve=f((Gs,Ee)=>{var v=require("fs"),b=require("path"),is=require("events"),as=require("crypto"),p=process.env.CODEV_DEBUG==="True",L=class extends is{constructor(e={}){super(),this.watchPaths=e.watchPaths||[],this.excludePatterns=e.excludePatterns||[/node_modules/,/\.git/,/\.DS_Store/,/\.tmp/,/\.log$/,/\.swp$/,/codev\.log/],this.includePatterns=e.includePatterns||[/\.(js|jsx|ts|tsx|py|java|c|cpp|h|hpp|go|rs|rb|php|html|css|scss|sass|less|json|xml|yaml|yml|md|txt)$/],this.watchers=new Map,this.isWatching=!1,this.debounceTimeout=e.debounceTimeout||300,this.pendingChanges=new Map,this.fileContentHashes=new Map,this.enableContentComparison=e.enableContentComparison!==!1,this.onFileChange=e.onFileChange||null}calculateFileHash(e){try{let s=v.readFileSync(e,"utf8");return as.createHash("sha256").update(s).digest("hex")}catch{return null}}hasContentChanged(e){if(!this.enableContentComparison)return!0;let s=this.calculateFileHash(e),t=this.fileContentHashes.get(e);return s===null?t!==void 0?(this.fileContentHashes.delete(e),!0):!1:t===void 0||s!==t?(this.fileContentHashes.set(e,s),!0):!1}preloadFileHashes(e){if(!(!this.enableContentComparison||!v.existsSync(e)))try{let s=v.readdirSync(e,{withFileTypes:!0});for(let t of s){let o=b.join(e,t.name);t.isFile()&&this.shouldWatchFile(o)?(this.calculateFileHash(o),this.fileContentHashes.set(o,this.calculateFileHash(o))):t.isDirectory()&&!this.shouldExcludeDirectory(o)&&this.preloadFileHashes(o)}}catch(s){p&&console.warn(`Failed to preload hashes for ${e}:`,s.message)}}shouldExcludeDirectory(e){let s=e.replace(/\\/g,"/");for(let t of this.excludePatterns)if(t.test(s)||t.test(b.basename(e)))return!0;return!1}startWatching(e=null){if(this.isWatching){p&&console.log("FileWatchService is already watching");return}let s=e||this.watchPaths;if(s.length===0){p&&console.log("No watch paths specified");return}this.isWatching=!0;for(let t of s)this.enableContentComparison&&this.preloadFileHashes(t),this.watchDirectory(t);p&&(console.log(`FileWatchService started watching ${s.length} paths`),this.enableContentComparison&&console.log(`Preloaded hashes for ${this.fileContentHashes.size} files`))}stopWatching(){if(this.isWatching){this.isWatching=!1;for(let[e,s]of this.watchers)try{s.close(),p&&console.log(`Stopped watching: ${e}`)}catch(t){p&&console.error(`Error stopping watcher for ${e}:`,t.message)}this.watchers.clear(),this.pendingChanges.clear(),this.fileContentHashes.clear(),p&&console.log("FileWatchService stopped watching all paths")}}watchDirectory(e){if(!v.existsSync(e)){p&&console.warn(`Watch path does not exist: ${e}`);return}if(!v.statSync(e).isDirectory()){p&&console.warn(`Watch path is not a directory: ${e}`);return}try{let t=v.watch(e,{recursive:!0,persistent:!1},(o,n)=>{if(!n)return;let r=b.join(e,n);this.handleFileChange(o,r,e)});this.watchers.set(e,t),p&&console.log(`Started watching directory: ${e}`),t.on("error",o=>{p&&console.error(`Watcher error for ${e}:`,o.message),this.watchers.delete(e)})}catch(t){p&&console.error(`Failed to start watching ${e}:`,t.message)}}handleFileChange(e,s,t){if(!this.shouldWatchFile(s))return;let o=`${e}:${s}`;this.pendingChanges.has(o)&&clearTimeout(this.pendingChanges.get(o)),this.pendingChanges.set(o,setTimeout(()=>{this.pendingChanges.delete(o),this.processFileChange(e,s,t)},this.debounceTimeout))}processFileChange(e,s,t){if(!this.isWatching)return;let o="modified",n=!1;try{v.statSync(s),n=!0,e==="rename"?o="created":e==="change"&&(o="modified")}catch{e==="rename"&&(o="deleted")}if(n&&(o==="modified"||o==="created")&&!this.hasContentChanged(s)){p&&console.log(`Ignoring false change for: ${b.relative(t,s)}`);return}!n&&o==="deleted"&&this.fileContentHashes.delete(s);let r={type:"CODEV_FILE_CHANGE_DETECTTED",data:{eventType:e,changeType:o,filePath:s,relativePath:b.relative(t,s),watchPath:t,fileExists:n,timestamp:Date.now(),sessionId:process.env.SESSION_ID||"default"}};if(p&&console.log(`File ${o}: ${r.data.relativePath}`),this.emit("fileChange",r),this.onFileChange&&typeof this.onFileChange=="function")try{this.onFileChange(r)}catch(a){p&&console.error("Error in file change callback:",a.message)}}shouldWatchFile(e){let s=b.basename(e),t=e.replace(/\\/g,"/");for(let o of this.excludePatterns)if(o.test(t)||o.test(s))return!1;if(this.includePatterns.length===0)return!0;for(let o of this.includePatterns)if(o.test(t)||o.test(s))return!0;return!1}addWatchPath(e){this.watchPaths.includes(e)||(this.watchPaths.push(e),this.isWatching&&this.watchDirectory(e))}removeWatchPath(e){let s=this.watchPaths.indexOf(e);if(s>-1&&(this.watchPaths.splice(s,1),this.watchers.has(e)))try{this.watchers.get(e).close(),this.watchers.delete(e),p&&console.log(`Removed watch path: ${e}`)}catch(t){p&&console.error(`Error removing watch path ${e}:`,t.message)}}getStatus(){return{isWatching:this.isWatching,watchPaths:[...this.watchPaths],activeWatchers:this.watchers.size,pendingChanges:this.pendingChanges.size}}setFileChangeCallback(e){this.onFileChange=e}};Ee.exports=L});var be=f((Ks,xe)=>{var cs=$(),ls=require("path"),Ls=require("fs"),Hs=require("os"),us=ue(),hs=fe(),ds=ye(),gs=Ce(),fs=ve(),m=process.env.CODEV_DEBUG==="True",H=class extends cs{constructor(){super({configDir:".",configFile:".claude.json",defaultModel:"Claude Sonnet 4.5",executablePaths:["cc.mjs","/tmp/claude-code/package/cc.mjs"],environmentVariables:e=>({ANTHROPIC_BASE_URL:`${e}/claude`,ANTHROPIC_API_KEY:"codev",DISABLE_TELEMETRY:!0,CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,CODEV_SERVER:e,CLAUDE_CODE_ATTRIBUTION_HEADER:"0"}),defaultConfig:{numStartups:1,installMethod:"unknown",autoUpdates:!1,theme:"Coder Dark",customApiKeyResponses:{approved:["codev"]},shiftEnterKeyBindingInstalled:!0,hasCompletedOnboarding:!0,subscriptionNoticeCount:0,hasAvailableSubscription:!0,projects:{}}}),this.fileWatchService=null,this.shutdownInProgress=!1,this.initializeServices()}initializeServices(){this.httpClient=new hs({timeout:1e4}),this.authService=new ds({validateCredentials:!1}),this.sessionManager=new gs({onSessionSwitch:e=>{this.sendTerminationMessage(e)}}),this.messageQueue=new us({maxRetries:2,retryDelay:500,shutdownTimeout:3e3,onProcessMessage:e=>this.processMessage(e)}),this.initializeFileWatchService()}resloveSettingFilePath(e){return ls.join(e,this.config.configDir,".claude","settings.json")}initializeFileWatchService(){if(!process.env.SESSION_ID){m&&console.log("FileWatchService disabled: SESSION_ID environment variable not found");return}try{this.fileWatchService=new fs({watchPaths:this.getFileWatchPaths(),onFileChange:e=>this.handleFileChange(e),debounceTimeout:300}),m&&console.log("FileWatchService initialized with SESSION_ID:",process.env.SESSION_ID)}catch(e){m&&console.error("Failed to initialize FileWatchService:",e.message)}}getFileWatchPaths(){let e=[],s=process.cwd();e.push(s);let t=process.env.CODEV_WATCH_PATHS;if(t){let o=t.split(",").map(n=>n.trim());e.push(...o)}return e}handleFileChange(e){if(m&&console.log("File change detected:",e.data.relativePath),this.shutdownInProgress)return;let s={message:e,sessionId:e.data.sessionId||process.env.SESSION_ID};this.messageQueue.enqueue(s)}startFileWatching(){this.fileWatchService&&!this.fileWatchService.isWatching&&(this.fileWatchService.startWatching(),m&&console.log("File watching started"))}stopFileWatching(){this.fileWatchService&&this.fileWatchService.isWatching&&(this.fileWatchService.stopWatching(),m&&console.log("File watching stopped"))}onChildMessage(e){e&&e.type==="claude:send-msg"&&this.handleClaudeSendMessage(e.data),super.onChildMessage(e)}handleClaudeSendMessage(e){if(m&&console.log("Handling claude:send-msg message:",e),!e||typeof e!="object"){console.error(`handleClaudeSendMessage: Invalid message data. Expected object, got: ${typeof e}`);return}if(this.shutdownInProgress){m&&console.log("Shutdown in progress, ignoring new message");return}let s=e.sessionId||process.env.SESSION_ID;this.sessionManager.handleSessionSwitch(s),this.messageQueue.enqueue(e)}async processMessage(e){let s=e.data.message,t=e.data.sessionId||process.env.SESSION_ID;if(!t)throw new Error("No session ID available");let o;try{o=typeof s=="string"?JSON.parse(s):s}catch(a){throw new Error(`Failed to parse message data: ${a.message}`)}let n=`/conversations/${t}/@append?task_type=codev`,r=this.authService.hasCredentials()?this.authService.generateAuthHeaders(`${this.httpClient.baseUrl}${n}`,o):{};m&&(console.debug("Sending message to:",n),console.debug("Send Message: ",JSON.stringify(o))),e.type!=="CODEV_TERMINATE_SIGNAL"&&(this.sessionManager.currentSessionId=t)}sendTerminationMessage(e){let s={message:e,sessionId:e.sessionId||this.sessionManager.getCurrentSessionId()};this.messageQueue.enqueue(s)}async handleChildProcessExit(e,s){m&&console.log(`Child process exited with code: ${e}, signal: ${s}`),this.stopFileWatching();let t=this.messageQueue.getQueueSize(),o=this.sessionManager.terminateCurrentSession("process exited normally",e,s);if(o&&this.sendTerminationMessage(o),t>0||o){m&&console.log("Starting graceful shutdown of message queue...");try{let n=!s||s==="SIGTERM",r=this.messageQueue.getQueueSize(),a={timeoutMs:n?8e3:3e3,batchSize:Math.min(r,15),fastMode:!n||r>30};m&&console.log("Shutdown options:",a);let i=await this.messageQueue.gracefulShutdown(a);m&&console.log("Message queue shutdown completed:",i),i.failedMessages>0&&m&&console.warn(`Shutdown summary: ${i.processedMessages} sent, ${i.failedMessages} failed, ${i.remainingMessages} remaining`)}catch(n){m&&console.error("Error during message queue shutdown:",n.message)}}}handleChildProcessError(e){m&&console.error(`Child process error: ${e.message}`);let s=this.sessionManager.createErrorTermination(e);s&&this.sendTerminationMessage(s)}async forceFlushMessages(e=3e3){if(this.messageQueue.getQueueSize()===0)return{success:!0,message:"No messages to flush"};m&&console.log(`Force flushing ${this.messageQueue.getQueueSize()} messages...`);try{return await this.messageQueue.forceFlushAndShutdown(e)}catch(s){return m&&console.error("Force flush failed:",s.message),{success:!1,error:s.message}}}async launch(e={}){let{codevServer:s,auth_ak:t=null,auth_sk:o=null}=e;return this.httpClient.setBaseUrl(s),t&&o&&this.authService.setCredentials(t,o),this.startFileWatching(),super.launch(e)}};xe.exports=H});var ke=f((Ws,Ie)=>{var ms=$(),zs=require("path"),K=class extends ms{constructor(){super({configDir:".gemini",configFile:"settings.json",defaultModel:"gemini-2.5-pro",executablePaths:["gemini/gemini.js","../dist/gemini/gemini.js"],environmentVariables:e=>({GOOGLE_GEMINI_BASE_URL:`${e}/gemini`,GEMINI_API_KEY:"coder",GOOGLE_API_KEY:"coder",GOOGLE_CLOUD_PROJECT:"coder",GOOGLE_CLOUD_LOCATION:"coder",DISABLE_TELEMETRY:!0,GEMINI_CODE_DISABLE_NONESSENTIAL_TRAFFIC:!0,DISABLE_COST_WARNINGS:!0,DISABLE_NON_ESSENTIAL_MODEL_CALLS:!0,USE_VERTEX:!0}),defaultConfig:{ide:{hasSeenNudge:!0},telemetry:{enabled:!1,logPrompts:!1},privacy:{usageStatisticsEnabled:!1},general:{disableUpdateNag:!0,preferredEditor:"vscode",previewFeatures:!0},ui:{hideBanner:!0,theme:"Default"},security:{auth:{selectedType:"vertex-ai"}}}})}};Ie.exports=K});var De=f((js,_e)=>{var ps=$(),_=require("path"),w=require("fs"),Ss=require("os"),{spawn:ys}=require("child_process"),O=process.env.CODEV_DEBUG==="True",z=class extends ps{constructor(){super({configDir:".codex",configFile:"config.toml",defaultModel:"o4-mini",executablePaths:["codex.mjs","../dist/codex.mjs"],environmentVariables:e=>({OPENAI_BASE_URL:`${e}/codex`,OPENAI_API_KEY:"codev-proxy-key",DEBUG:O?"true":"false",CODEX_QUIET_MODE:"0",OPENAI_DISABLE_TELEMETRY:"true",CODEX_DISABLE_PROJECT_DOC:"0",CODEV_SERVER:e}),defaultConfig:{model:"gpt-5-codex",approvalMode:"suggest",fullAutoErrorMode:"ask-user",notify:[],history:{maxSize:1e3,saveHistory:!0,sensitivePatterns:[],persistence:"save-all"}}})}checkCodexAvailability(){try{let e=this.findExecutablePath();return w.existsSync(e)}catch{return!1}}resloveSettingFilePath(e){return _.join(e,this.config.configDir,"config.toml")}async ensureConfig(e,s=0){let t=_.join(Ss.homedir(),this.config.configDir,this.config.configFile),o=_.dirname(t);try{w.existsSync(o)||w.mkdirSync(o,{recursive:!0});let n=`${e}/codex`;if(w.existsSync(t)){let r=w.readFileSync(t,"utf8"),a=`openai_base_url = "${n}"`;/^openai_base_url\s*=/m.test(r)?r=r.replace(/^openai_base_url\s*=.*/m,a):r=r.trimEnd()+`
200
200
  `+a+`
201
201
  `,w.writeFileSync(t,r),O&&console.log(`Updated openai_base_url in ${t}`)}else{let r=this.config.defaultConfig||{},a=this.generateTOMLConfig(r,n);w.writeFileSync(t,a),O&&console.log(`Created Codex config file: ${t}`)}s>0&&await new Promise(r=>setTimeout(r,s))}catch(n){console.warn(`Failed to update ${this.config.configFile}: ${n.message}`)}}generateTOMLConfig(e,s){return`model = "${e.model||"gpt-5-codex"}"
202
202
  openai_base_url = "${s}"