@quantiya/codevibe-codex-plugin 1.0.33 → 1.0.34
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/server.js +11 -11
- package/package.json +1 -1
package/dist/server.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var _e=Object.create;var j=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var we=Object.getPrototypeOf,Ee=Object.prototype.hasOwnProperty;var Ie=(p,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Pe(e))!Ee.call(p,i)&&i!==t&&j(p,i,{get:()=>e[i],enumerable:!(s=be(e,i))||s.enumerable});return p};var f=(p,e,t)=>(t=p!=null?_e(we(p)):{},Ie(e||!p||!p.__esModule?j(t,"default",{value:p,enumerable:!0}):t,p));var ge=require("uuid"),I=f(require("fs")),x=f(require("path")),ye=f(require("os")),ve=require("util"),Se=require("child_process"),c=require("@quantiya/codevibe-core");var V=f(require("os")),G=f(require("path")),q=require("@quantiya/codevibe-core"),n=(0,q.createLogger)({name:"codevibe-codex",logFile:G.default.join(V.default.tmpdir(),"codevibe-codex-mcp.log"),level:"debug"});var X=require("events"),v=f(require("fs")),F=f(require("path")),J=require("chokidar"),Y=require("@quantiya/codevibe-core");var C=class extends X.EventEmitter{constructor(){super();this.watcher=null;this.filePositions=new Map;this.activeLogFile=null;this.sessionId=null;this.isWatching=!1;this.startTime=0;this.sessionsDir=null;this.activeReads=new Map;this.pendingReads=new Set;this.readGeneration=0}start(){if(this.isWatching){n.warn("Session log watcher already running");return}let t=(0,Y.getConfig)().codex.sessionsDir;this.sessionsDir=t,n.info("Starting Codex session log watcher",{sessionsDir:t}),v.existsSync(t)||(n.info("Codex sessions directory does not exist yet, creating...",{sessionsDir:t}),v.mkdirSync(t,{recursive:!0})),this.startTime=Date.now(),this.readGeneration++,this.watcher=(0,J.watch)(t,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},depth:4,ignored:s=>{let i=F.basename(s);return v.existsSync(s)&&v.statSync(s).isDirectory()?!1:!i.startsWith("rollout-")||!i.endsWith(".jsonl")}}),this.watcher.on("add",s=>{s.endsWith(".jsonl")&&this.onFileAdded(s)}),this.watcher.on("change",s=>{s.endsWith(".jsonl")&&this.onFileChanged(s)}),this.watcher.on("error",s=>{n.error("Watcher error:",s),this.emit("error",s)}),this.watcher.on("ready",()=>{n.info("Session log watcher ready"),this.bindRecentSessionFile()}),this.isWatching=!0,n.info("Session log watcher started")}stop(){this.watcher&&(this.watcher.close(),this.watcher=null),this.isWatching=!1,this.readGeneration++,this.filePositions.clear(),this.activeReads.clear(),this.pendingReads.clear(),this.activeLogFile=null,this.sessionId=null,this.sessionsDir=null,n.info("Session log watcher stopped")}getSessionId(){return this.sessionId}getActiveLogFile(){return this.activeLogFile}onFileAdded(t){try{let s=v.statSync(t),i=s.birthtimeMs||s.ctimeMs;if(i<this.startTime-5e3){n.debug("Ignoring old session file",{filePath:t,fileCreatedAt:new Date(i).toISOString(),startTime:new Date(this.startTime).toISOString()});return}}catch(s){n.warn("Could not check file creation time",{filePath:t,error:s})}if(this.activeLogFile){n.debug("Ignoring additional Codex session log for this server instance",{activeLogFile:this.activeLogFile,ignoredFile:t});return}n.info("New Codex session log detected",{filePath:t}),this.activeLogFile=t,this.filePositions.set(t,0),this.scheduleReadNewLines(t)}onFileChanged(t){if(this.activeLogFile&&t!==this.activeLogFile){n.debug("Ignoring change for non-active session log",{activeLogFile:this.activeLogFile,ignoredFile:t});return}if(!this.activeLogFile){try{let s=v.statSync(t),i=s.birthtimeMs||s.ctimeMs,o=s.mtimeMs;if(i<this.startTime-5e3&&o<this.startTime-5e3){n.debug("Ignoring change for pre-existing session file",{filePath:t,fileCreatedAt:new Date(i).toISOString(),fileModifiedAt:new Date(o).toISOString(),startTime:new Date(this.startTime).toISOString()});return}}catch(s){n.warn("Could not check file creation time during change event",{filePath:t,error:s})}this.activeLogFile=t,this.filePositions.set(t,0)}this.scheduleReadNewLines(t)}bindRecentSessionFile(){if(!(this.activeLogFile||!this.sessionsDir))try{let s=this.collectRecentSessionFiles(this.sessionsDir).sort((i,o)=>o.modifiedAt-i.modifiedAt)[0];if(!s)return;n.info("Binding recent session file missed during initial watch scan",{filePath:s.filePath,fileCreatedAt:new Date(s.createdAt).toISOString(),fileModifiedAt:new Date(s.modifiedAt).toISOString(),watcherStartTime:new Date(this.startTime).toISOString()}),this.activeLogFile=s.filePath,this.filePositions.set(s.filePath,0),this.scheduleReadNewLines(s.filePath)}catch(t){n.warn("Failed to backfill recent session file",{error:t})}}collectRecentSessionFiles(t){let s=[],i=[t];for(;i.length>0;){let o=i.pop();if(!o)continue;let r;try{r=v.readdirSync(o,{withFileTypes:!0})}catch{continue}for(let a of r){let l=F.join(o,a.name);if(a.isDirectory()){i.push(l);continue}if(!(!a.isFile()||!a.name.startsWith("rollout-")||!a.name.endsWith(".jsonl")))try{let d=v.statSync(l),u=d.birthtimeMs||d.ctimeMs,h=d.mtimeMs;(u>=this.startTime||h>=this.startTime-5e3)&&s.push({filePath:l,createdAt:u,modifiedAt:h})}catch{}}}return s}scheduleReadNewLines(t){let s=this.activeReads.get(t);if(s)return this.pendingReads.add(t),s;let i=this.readGeneration,o=this.drainReadQueue(t,i);return this.activeReads.set(t,o),o.finally(()=>{this.activeReads.get(t)===o&&(this.activeReads.delete(t),this.pendingReads.delete(t))}),o}async drainReadQueue(t,s){do this.pendingReads.delete(t),await this.readNewLines(t,s);while(s===this.readGeneration&&this.pendingReads.has(t))}async readNewLines(t,s){if(s!==this.readGeneration)return;let i=this.filePositions.get(t)||0;try{if(v.statSync(t).size<=i)return;let r=v.createReadStream(t,{start:i,encoding:"utf-8"}),a=i,l="";for await(let d of r){if(s!==this.readGeneration){r.destroy();return}l+=d;let u=l.indexOf(`
|
|
2
2
|
`);for(;u!==-1;){if(s!==this.readGeneration){r.destroy();return}let h=l.slice(0,u),g=l.slice(0,u+1);l=l.slice(u+1),a+=Buffer.byteLength(g,"utf-8");let S=h.endsWith("\r")?h.slice(0,-1):h;if(S.trim())try{let b=JSON.parse(S);this.processLogEntry(b)}catch(b){n.warn("Failed to parse log line",{filePath:t,line:S.substring(0,100),error:b})}if(s!==this.readGeneration){r.destroy();return}u=l.indexOf(`
|
|
3
|
-
`)}}s===this.readGeneration&&this.filePositions.set(t,a)}catch(o){n.error("Error reading log file",{filePath:t,error:o}),this.emit("error",o)}}processLogEntry(t){if(n.debug("Processing log entry",{type:t.type}),t.type==="session_meta"){let s=t.payload;this.sessionId=s.id,n.info("Codex session started",{sessionId:s.id,cwd:s.cwd,cliVersion:s.cli_version}),this.emit("session-started",s);return}this.emit("log-entry",t),t.type==="event_msg"&&t.payload?.type?this.emit(`event:${t.payload.type}`,t):t.type==="response_item"&&t.payload?.type&&this.emit(`response:${t.payload.type}`,t)}};var
|
|
4
|
-
${l}`,metadata:{toolName:a,toolOutput:o,callId:i,status:"completed"}}}if(s==="custom_tool_call"){let{name:i,call_id:o,input:r,status:a}=p.payload;
|
|
3
|
+
`)}}s===this.readGeneration&&this.filePositions.set(t,a)}catch(o){n.error("Error reading log file",{filePath:t,error:o}),this.emit("error",o)}}processLogEntry(t){if(n.debug("Processing log entry",{type:t.type}),t.type==="session_meta"){let s=t.payload;this.sessionId=s.id,n.info("Codex session started",{sessionId:s.id,cwd:s.cwd,cliVersion:s.cli_version}),this.emit("session-started",s);return}this.emit("log-entry",t),t.type==="event_msg"&&t.payload?.type?this.emit(`event:${t.payload.type}`,t):t.type==="response_item"&&t.payload?.type&&this.emit(`response:${t.payload.type}`,t)}};var D=require("uuid"),_=require("@quantiya/codevibe-core");var P=new Map;function Z(p,e){let t={sessionId:e,source:_.EventSource.DESKTOP};if(p.type==="event_msg"&&p.payload){let s=p.payload.type;switch(s){case"user_message":return{...t,type:_.EventType.USER_PROMPT,content:p.payload.message||"",metadata:{images:p.payload.images||[]}};case"agent_message":return{...t,type:_.EventType.ASSISTANT_RESPONSE,content:p.payload.message||""};case"agent_reasoning":return{...t,type:_.EventType.REASONING,content:p.payload.text||""};case"token_count":return n.debug("Skipping token_count entry"),null;default:return n.debug("Unknown event_msg type",{type:s}),null}}if(p.type==="response_item"&&p.payload){let s=p.payload.type;if(s==="function_call"){let{name:i,arguments:o,call_id:r}=p.payload,a={};try{a=JSON.parse(o||"{}")}catch{a={raw:o}}let l=(0,D.v4)();P.set(r,{name:i,input:o,eventId:l});let d=U(i),u=Te(i,a);return{...t,type:_.EventType.TOOL_USE,content:u,metadata:{toolName:d,toolInput:a,callId:r,status:"running"}}}if(s==="function_call_output"){let{call_id:i,output:o}=p.payload,r=P.get(i);P.delete(i);let a=r?.name?U(r.name):"Tool",l=Fe(o,500);return{...t,type:_.EventType.TOOL_USE,content:`${a} completed:
|
|
4
|
+
${l}`,metadata:{toolName:a,toolOutput:o,callId:i,status:"completed"}}}if(s==="custom_tool_call"){let{name:i,call_id:o,input:r,status:a}=p.payload;P.set(o,{name:i,input:r,eventId:(0,D.v4)()});let l=Ce(r),{oldString:d,newString:u}=xe(r),h=l?`Editing: ${l.filePath}`:"Applying patch";return{...t,type:_.EventType.TOOL_USE,content:h,metadata:{tool_name:"Edit",tool_input:{file_path:l?.filePath||"",old_string:d,new_string:u},callId:o,status:a||"running"}}}if(s==="custom_tool_call_output"){let{call_id:i,output:o}=p.payload,r=P.get(i);P.delete(i);let a={};try{a=JSON.parse(o||"{}")}catch{a={raw:o}}let l=a.output?.includes("Success")||!a.error;return{...t,type:_.EventType.TOOL_USE,content:l?"File edit applied successfully":`Edit failed: ${a.error||"Unknown error"}`,metadata:{toolName:"Edit",toolOutput:a,callId:i,status:"completed",success:l}}}return n.debug("Unknown response_item type",{type:s}),null}return p.type==="turn_context"?(n.debug("Skipping turn_context entry"),null):(n.debug("Unhandled log entry type",{type:p.type}),null)}function U(p){return{shell_command:"Bash",shell:"Bash",apply_patch:"Edit",write_file:"Write",read_file:"Read",list_files:"Glob",search_files:"Grep",web_search:"WebSearch",web_fetch:"WebFetch"}[p]||p}function Te(p,e){switch(p){case"shell_command":case"shell":return`Running: ${e.command||"command"}`;case"read_file":return`Reading: ${e.file_path||e.path||"file"}`;case"write_file":return`Writing: ${e.file_path||e.path||"file"}`;case"list_files":return`Listing: ${e.path||"."}`;case"search_files":return`Searching for: ${e.pattern||e.query||"pattern"}`;case"web_search":return`Searching web: ${e.query||"query"}`;default:return`Running ${U(p)}`}}function xe(p){let e=[],t=[],s=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;for(let i of p.split(`
|
|
5
5
|
`))if(!(s.test(i)||i.startsWith("***")||i.startsWith("---")||i.startsWith("+++"))){if(i.startsWith("-"))e.push(i.slice(1));else if(i.startsWith("+"))t.push(i.slice(1));else if(i.startsWith(" ")){let o=i.slice(1);e.push(o),t.push(o)}}return{oldString:e.join(`
|
|
6
6
|
`),newString:t.join(`
|
|
7
|
-
`)}}function
|
|
7
|
+
`)}}function Ce(p){if(!p)return null;let e=p.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);return e?{filePath:e[1].trim()}:null}function Fe(p,e){return p?p.length<=e?p:p.substring(0,e)+"...":""}function Q(){P.clear()}var ee=require("events"),te=require("@quantiya/codevibe-core");var O=class extends ee.EventEmitter{constructor(){super();this.pendingCalls=new Map;this.timers=new Map;this.timeoutMs=(0,te.getConfig)().codex.approvalTimeoutMs,n.info("Approval detector initialized",{timeoutMs:this.timeoutMs})}onToolCallStart(t,s,i){n.debug("Tool call started",{callId:t,name:s});let o=this.parseInput(i),r=this.extractFilePath(s,i,o),a=this.extractDiff(s,i,o),l={callId:t,name:s,input:i,filePath:r,diff:a,parsedInput:o,timestamp:Date.now(),notificationSent:!1};if(this.pendingCalls.set(t,l),!this.shouldScheduleApprovalTimeout(s,o)){n.debug("Skipping approval timeout for non-escalated tool call",{callId:t,name:s});return}let d=setTimeout(()=>{this.checkPendingCall(t)},this.timeoutMs);this.timers.set(t,d)}onToolCallComplete(t){n.debug("Tool call completed",{callId:t}),this.pendingCalls.delete(t);let s=this.timers.get(t);s&&(clearTimeout(s),this.timers.delete(t))}checkPendingCall(t){let s=this.pendingCalls.get(t);if(!s||s.notificationSent)return;let i=Date.now()-s.timestamp;n.info("Tool call still pending after timeout",{callId:t,name:s.name,elapsedMs:i}),s.notificationSent=!0,this.pendingCalls.set(t,s),this.emit("approval-pending",{callId:t,toolName:s.name,hint:this.extractHint(s.name,s.input,s.filePath),filePath:s.filePath,diff:s.diff,toolInput:s.parsedInput,rawInput:s.input,elapsedMs:i})}extractHint(t,s,i){if(i)return`File: ${i}`;if(t==="apply_patch"&&s){let o=s.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(o)return`File: ${o[1].trim()}`}if(t==="shell_command"||t==="shell")try{let o=JSON.parse(s);if(o.command)return`Command: ${o.command.substring(0,50)}${o.command.length>50?"...":""}`}catch{}return`Tool: ${this.mapToolName(t)}`}mapToolName(t){return{shell_command:"Bash",shell:"Bash",apply_patch:"File Edit",write_file:"Write File",read_file:"Read File"}[t]||t}parseInput(t){if(t)try{return JSON.parse(t)}catch{return}}shouldScheduleApprovalTimeout(t,s){return t!=="exec_command"&&t!=="shell_command"&&t!=="shell"?!1:s?.sandbox_permissions==="require_escalated"}extractFilePath(t,s,i){if(t==="apply_patch"&&s){let r=s.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(r)return r[1].trim()}let o=i?.file_path||i?.path||i?.filePath;if(o&&typeof o=="string")return o}extractDiff(t,s,i){if(t==="apply_patch"&&s)return s;if(i?.diff&&typeof i.diff=="string")return i.diff}getPendingCalls(){return Array.from(this.pendingCalls.values())}hasPendingCalls(){return this.pendingCalls.size>0}clear(){for(let t of this.timers.values())clearTimeout(t);this.timers.clear(),this.pendingCalls.clear(),n.debug("Approval detector cleared")}shutdown(){this.clear(),this.removeAllListeners(),n.info("Approval detector shutdown")}};var ie=require("child_process"),ne=require("util");var se=(0,ne.promisify)(ie.exec),R=class{async sendInput(e,t){n.info("Attempting to send input to Codex",{sessionId:e,input:t});try{let s=process.env.CODEVIBE_CODEX_TMUX_SESSION;return s?(n.info("Using tmux send-keys",{tmuxSession:s}),await this.sendViaTmux(s,t),n.info("Successfully sent input to Codex",{sessionId:e,input:t}),!0):(n.error("No tmux session found - codevibe-codex wrapper is required",{sessionId:e,hint:"Start Codex CLI using the codevibe-codex wrapper script"}),!1)}catch(s){return n.error("Failed to send input to Codex",{sessionId:e,error:s instanceof Error?s.message:String(s)}),!1}}async sendViaTmux(e,t){let s=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");n.info("Sending via tmux",{sessionName:e,inputLength:t.length});try{let i=`tmux send-keys -t "${e}" -l "${s}"`;await se(i),await this.delay(500);let o=`tmux send-keys -t "${e}" Enter`;await se(o),n.info("tmux send-keys completed")}catch(i){throw n.error("tmux send-keys failed",{sessionName:e,error:i}),i}}delay(e){return new Promise(t=>setTimeout(t,e))}isApprovalResponse(e){let t=e.trim().toLowerCase();return["y","n","a","q","e","yes","no"].includes(t)||/^[0-9]+$/.test(t)}};var y=f(require("fs")),re=f(require("os")),A=f(require("path")),oe=require("crypto"),ae=require("child_process"),le=require("events"),pe=require("util");var $=(0,pe.promisify)(ae.exec),M=class extends le.EventEmitter{constructor(){super(...arguments);this.sessionName=null;this.started=!1;this.pipeFilePath=null;this.filePosition=0;this.watcher=null;this.processing=!1;this.pendingRead=!1;this.lastPromptHash=null}async start(t){if(this.started&&this.sessionName===t){n.debug("Tmux pane observer already started",{sessionName:t});return}this.started&&await this.stop(),this.sessionName=t,this.started=!0,this.filePosition=0,this.lastPromptHash=null,this.pipeFilePath=A.join(re.tmpdir(),`codevibe-codex-pane-${process.pid}.log`),y.mkdirSync(A.dirname(this.pipeFilePath),{recursive:!0}),y.writeFileSync(this.pipeFilePath,""),await this.enablePipePane(),this.startFileWatcher(),n.info("Tmux pane observer started",{sessionName:t})}async stop(){if(this.started){try{await this.disablePipePane()}catch(t){n.debug("Failed to disable tmux pipe-pane cleanly",{error:t})}if(this.watcher&&(this.watcher.close(),this.watcher=null),this.pipeFilePath)try{y.unlinkSync(this.pipeFilePath)}catch{}n.info("Tmux pane observer stopped",{sessionName:this.sessionName}),this.started=!1,this.sessionName=null,this.pipeFilePath=null,this.filePosition=0,this.processing=!1,this.pendingRead=!1,this.lastPromptHash=null,this.removeAllListeners("prompt-candidate"),this.removeAllListeners("observer-error")}}async captureSnapshot(t=120){if(!this.sessionName)throw new Error("Tmux pane observer is not started");let s=Math.max(1,Math.floor(t)),i=this.escapeShellArg(this.sessionName),o=`tmux capture-pane -p -e -S -${s} -t '${i}'`;try{let{stdout:r}=await $(o);return r}catch(r){throw n.error("Failed to capture tmux pane snapshot",{sessionName:this.sessionName,error:r}),this.emit("observer-error",r),r}}escapeShellArg(t){return t.replace(/'/g,"'\\''")}async enablePipePane(){if(!this.sessionName||!this.pipeFilePath)throw new Error("Tmux pane observer is not initialized");let t=this.escapeShellArg(this.sessionName),s=this.escapeShellArg(this.pipeFilePath),i=`tmux pipe-pane -O -t '${t}' "cat >> '${s}'"`;await $(i),n.debug("Enabled tmux pipe-pane mirroring",{sessionName:this.sessionName,pipeFilePath:this.pipeFilePath})}async disablePipePane(){if(!this.sessionName)return;let s=`tmux pipe-pane -t '${this.escapeShellArg(this.sessionName)}'`;await $(s)}startFileWatcher(){this.pipeFilePath&&(this.watcher=y.watch(this.pipeFilePath,t=>{t==="change"&&this.processFileChanges()}))}async processFileChanges(){if(this.pipeFilePath){if(this.processing){this.pendingRead=!0;return}this.processing=!0;try{do{this.pendingRead=!1;let t=this.readAppendedChunk();if(!t||!this.looksLikePromptDelta(t))continue;let s=await this.captureSnapshot();if(!s||!this.looksLikePromptSnapshot(s))continue;let i=this.hashPromptSnapshot(s);i!==this.lastPromptHash&&(this.lastPromptHash=i,this.emit("prompt-candidate",{rawDelta:t,snapshot:s,detectedAt:Date.now()}))}while(this.pendingRead)}catch(t){n.error("Failed to process tmux pane changes",{error:t}),this.emit("observer-error",t)}finally{this.processing=!1}}}readAppendedChunk(){if(!this.pipeFilePath)return"";let t=y.statSync(this.pipeFilePath);if(t.size<=this.filePosition)return"";let s=y.openSync(this.pipeFilePath,"r");try{let i=t.size-this.filePosition,o=Buffer.alloc(i);return y.readSync(s,o,0,i,this.filePosition),this.filePosition=t.size,o.toString("utf-8")}finally{y.closeSync(s)}}looksLikePromptDelta(t){return/\[(?:y\/n|Y\/n|y\/N)\]|\b(?:apply|approve|allow|reject|deny|continue)\b/i.test(t)}looksLikePromptSnapshot(t){let s=t.split(`
|
|
8
8
|
`).slice(-20).join(`
|
|
9
9
|
`);return/\[(?:y\/n|Y\/n|y\/N)\]|^\s*\d+\.\s+/im.test(s)}hashPromptSnapshot(t){let s=t.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"").replace(/\r/g,`
|
|
10
10
|
`).replace(/[ \t]+\n/g,`
|
|
11
|
-
`).trim();return(0,re.createHash)("sha256").update(s).digest("hex")}};var P=require("@quantiya/codevibe-core");var $=f(require("express")),E=f(require("fs")),W=f(require("path")),H=f(require("os"));var N=class{constructor(){this.assignedPort=0;this.app=(0,$.default)(),this.setupMiddleware(),this.setupRoutes(),this.tmuxSession=process.env.CODEVIBE_CODEX_TMUX_SESSION}getPort(){return this.assignedPort}setupMiddleware(){this.app.use($.default.json({limit:"1mb"})),this.app.use((e,t,s)=>{n.debug(`${e.method} ${e.path}`,{body:e.body}),s()})}setupRoutes(){this.app.get("/health",(e,t)=>{t.json({success:!0,data:{status:"healthy",uptime:process.uptime()}})}),this.app.post("/event",this.handleEvent.bind(this))}async handleEvent(e,t){try{let s=e.body;if(!s.session_id||!s.hook_event_name){t.status(400).json({success:!1,error:"Missing session_id or hook_event_name"});return}let i=this.transformHookToEvent(s);n.info("Received hook event",{sessionId:s.session_id,hookEvent:s.hook_event_name,type:i.type}),this.eventHandler&&await this.eventHandler(i),t.json({success:!0})}catch(s){n.error("Error handling event:",s),t.status(500).json({success:!1,error:s instanceof Error?s.message:"Unknown error"})}}transformHookToEvent(e){let t={cwd:e.cwd,hook_event_name:e.hook_event_name,...e.metadata||{}},s,i;switch(e.hook_event_name){case"SessionStart":s="NOTIFICATION",i="Session started",t.source=e.source;break;case"UserPromptSubmit":s="USER_PROMPT",i=e.prompt||"";break;case"PreToolUse":s="NOTIFICATION",i="PreToolUse observed",t.tool_name=e.tool_name,t.tool_input=e.tool_input,t.tool_use_id=e.tool_use_id,t.approval_status="observed_pre_tool",t.requires_user_action=!1;break;case"PostToolUse":s="TOOL_USE",i=JSON.stringify({tool_name:e.tool_name,tool_input:e.tool_input,tool_response:e.tool_response}),t.tool_name=e.tool_name;break;case"Stop":s="ASSISTANT_RESPONSE",i=e.last_assistant_message||"";break;default:s="NOTIFICATION",i=`Hook: ${e.hook_event_name}`}return{session_id:e.session_id,hook_event_name:e.hook_event_name,type:s,source:"DESKTOP",content:i,metadata:t}}onEvent(e){this.eventHandler=e}async start(){return new Promise((e,t)=>{try{this.server=this.app.listen(0,"localhost",()=>{let s=this.server.address();this.assignedPort=s.port,n.info(`HTTP API listening on http://localhost:${this.assignedPort}`),this.writePortFile(this.assignedPort),e(this.assignedPort)}),this.server.on("error",s=>{n.error("HTTP server error:",s),t(s)})}catch(s){t(s)}})}writePortFile(e){if(!this.tmuxSession){n.warn("No CODEVIBE_CODEX_TMUX_SESSION set, skipping port file");return}let t=W.join(H.tmpdir(),`codevibe-codex-${this.tmuxSession}.port`);try{E.writeFileSync(t,e.toString()),n.info(`Port file written: ${t} -> ${e}`)}catch(s){n.error(`Failed to write port file: ${t}`,s)}}removePortFile(){if(!this.tmuxSession)return;let e=W.join(H.tmpdir(),`codevibe-codex-${this.tmuxSession}.port`);try{E.existsSync(e)&&(E.unlinkSync(e),n.info(`Port file removed: ${e}`))}catch(t){n.warn(`Failed to remove port file: ${e}`,t)}}async stop(){return this.removePortFile(),new Promise(e=>{this.server?this.server.close(()=>{n.info("HTTP API stopped"),e()}):e()})}};var ce=f(require("crypto")),de=f(require("fs")),ue=f(require("https")),M=f(require("os")),he=f(require("path")),Oe="G-GS74YEQTB8",Re="lAfOF6OxRzSQ-NsLBRjhAg",Fe="www.google-analytics.com",Ae=`/mp/collect?measurement_id=${Oe}&api_secret=${Re}`,pe=800;function ke(){try{let p=he.resolve(__dirname,"..","package.json"),e=de.readFileSync(p,"utf-8"),t=JSON.parse(e);if(typeof t.version=="string"&&t.version.length>0&&t.version.length<30)return t.version}catch{}return"unknown"}var Ne=ke();function Me(){let p=typeof process.getuid=="function"?process.getuid():0;return ce.createHash("sha256").update(`${M.hostname()}-${p}`).digest("hex").substring(0,36)}function Le(p){if(!p)return"";let e=M.homedir(),t=p.replace(/[\n\r\t]/g," ");if(e&&e.length>0){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replace(new RegExp(s,"g"),"~")}return t=t.replace(/\/Users\/[^/\s"'`]+/g,"/Users/<user>").replace(/\/home\/[^/\s"'`]+/g,"/home/<user>").replace(/[^\x20-\x7E]/g,""),t.trim().substring(0,100)}function m(p,e){return new Promise(t=>{let s,i=!1,o=()=>{i||(i=!0,clearTimeout(r),t())},r=setTimeout(()=>{try{s?.destroy()}catch{}o()},pe);typeof r.unref=="function"&&r.unref();try{let a={...e};typeof a.error_message=="string"&&(a.error_message=Le(a.error_message));let l=JSON.stringify({client_id:Me(),events:[{name:p,params:{agent:"codex",plugin_version:Ne,platform:process.platform,source:process.env.CODEVIBE_TELEMETRY_SOURCE||"production",...a}}]});s=ue.request({hostname:Fe,path:Ae,method:"POST",headers:{"Content-Type":"application/json"},timeout:pe},d=>{d.resume(),d.on("end",o),d.on("close",o),d.on("error",o)}),s.on("error",o),s.on("timeout",()=>{try{s?.destroy()}catch{}o()}),s.on("close",o),s.write(l),s.end()}catch{o()}})}var De=(0,ve.promisify)(ye.exec),Ue="/quit",me="CODEVIBE_CODEX_TMUX_SESSION",$e=600*1e3;async function We(p,e){let t=async(s,i)=>{try{await De(s)}catch(o){n.warn("tmux send-keys failed during self-terminate",{sessionName:p,label:i,error:String(o)})}};await t(`tmux send-keys -t "${p}" C-c`,"ctrl-c"),await new Promise(s=>setTimeout(s,200)),await t(`tmux send-keys -t "${p}" -l "${e}"`,"quit-text"),await new Promise(s=>setTimeout(s,500)),await t(`tmux send-keys -t "${p}" Enter`,"enter")}var K=class{constructor(){this.sessionState=null;this.unsubscribe=null;this.sessionKey=null;this.pendingInteractivePrompt=null;this.isInitializingSession=!1;this.bufferedLogEntries=[];this.hooksActive=!1;this.subscribedSessionId=null;this.launchSessionInitPromise=null;this.sessionStartedInitPromise=null;this.httpApi=new N,this.sessionWatcher=new C,this.approvalDetector=new R,this.promptResponder=new F,this.tmuxPaneObserver=new A}async start(){n.info("Starting CodeVibe Codex companion server",{environment:(0,c.getEnvironment)()}),this.appSyncClient=new c.AppSyncClient,await this.appSyncClient.authenticateWithStoredTokens()||(n.error('Authentication failed. Run "codevibe-codex login" first.'),console.error('Not authenticated. Run "codevibe-codex login" to sign in.'),process.exit(1)),n.info("Authenticated successfully",{userId:this.appSyncClient.getCurrentUserId(),email:this.appSyncClient.getCurrentUserEmail()}),await(0,c.registerDeviceEncryptionKey)(this.appSyncClient,n),(0,c.startDeviceKeyWatcher)(this.appSyncClient,n);try{let s=await this.appSyncClient.sweepOrphanSessions({agentType:"CODEX"});s>0&&n.info("Orphan sweep: marked stale Codex sessions INACTIVE",{swept:s})}catch(s){n.warn("Orphan sweep failed, continuing startup",{error:s instanceof Error?s.message:String(s)})}this.httpApi.onEvent(this.handleEventFromHook.bind(this));let t=await this.httpApi.start();n.info("HTTP API started for hooks",{port:t}),await this.createLaunchSession(),this.setupEventHandlers(),this.sessionWatcher.start(),n.info("CodeVibe Codex companion server started")}async createLaunchSession(){let e=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!e){n.warn("No CODEVIBE_CODEX_TMUX_SESSION \u2014 skipping launch session");return}let t;this.launchSessionInitPromise=new Promise(s=>{t=s});try{let s=process.env.CODEX_WORKING_DIRECTORY||process.cwd(),i=this.generateSessionId(e),o=this.appSyncClient.getCurrentUserId();n.info("Creating launch session",{sessionId:i,projectPath:s});let r=!1;try{let a=await(0,c.resumeOrCreateSession)({sessionId:i,userId:o,agentType:c.AgentType.CODEX,projectPath:s,metadata:{launchSession:!0}},this.appSyncClient,n);this.sessionKey=a.sessionKey,r=!0,this.sessionState={sessionId:i,userId:o,projectPath:s,cwd:s,createdAt:new Date,subscriptionActive:!1,metadata:{launchSession:!0},codexSessionId:e,codexLogFile:void 0},await m("daemon_init_step_completed",{step:"session_resume_or_create",path:"launch_session"})}catch(a){await m("daemon_init_step_failed",{step:"session_resume_or_create",path:"launch_session",error_class:a?.name||"Error",error_message:a?.message||String(a)}),n.error("Failed to create/resume launch session (non-fatal)",{error:a})}if(!r)return;await m("daemon_init_step_completed",{step:"session_state_set",path:"launch_session"});try{this.subscribeToMobileEvents(i)?await m("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"launch_session"}):await m("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(a){await m("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:a?.name||"Error",error_message:a?.message||String(a)}),n.error("Failed to subscribe to mobile events for launch session",{error:a})}try{this.appSyncClient.startHeartbeat(i),await m("daemon_init_step_completed",{step:"heartbeat_start",path:"launch_session"})}catch(a){await m("daemon_init_step_failed",{step:"heartbeat_start",path:"launch_session",error_class:a?.name||"Error",error_message:a?.message||String(a)}),n.error("Failed to start heartbeat for launch session",{error:a})}this.startMobileEndWatcher(i),n.info("Launch session created",{sessionId:i})}finally{t()}}async handleEventFromHook(e){let{session_id:t,hook_event_name:s,type:i,content:o,metadata:r}=e;if(this.hooksActive=!0,n.info("[Hooks] Received event",{sessionId:t,hookEvent:s,type:i,contentLength:o?.length}),s==="SessionStart"){if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionState)n.info("[Hooks] SessionStart \u2014 launch session already exists, updating codexSessionId",{existingSessionId:this.sessionState.sessionId,codexSessionId:t}),this.sessionState.codexSessionId=t,this.sessionState.metadata={...this.sessionState.metadata,codexSessionId:t,cliVersion:r?.model||"unknown",modelProvider:r?.model||"unknown",launchSession:void 0},this.appSyncClient.updateSession({sessionId:this.sessionState.sessionId,metadata:this.sessionState.metadata}).catch(l=>n.warn("Failed to update session metadata",{error:l}));else{let l={id:t,timestamp:new Date().toISOString(),cwd:r?.cwd||process.cwd(),originator:"hook",cli_version:r?.model||"unknown",instructions:null,source:r?.source||"startup",model_provider:r?.model||"unknown"};await this.ensureSessionStarted(l)}return}if(!this.sessionState){n.warn("[Hooks] Session not initialized, buffering event",{hook_event_name:s});return}let a=this.sessionState.sessionId;if(i==="USER_PROMPT"&&o&&this.isRecentMobilePrompt(o)){n.info("[Hooks] Skipping duplicate USER_PROMPT from mobile");return}if(s==="PreToolUse"){n.debug("[Hooks] PreToolUse observed; AppSync emission suppressed",{toolName:r?.tool_name||"unknown",sessionId:a});return}if(s==="PostToolUse"){let l=o,d=r,u=!1;this.sessionKey&&(l=c.cryptoService.encryptContent(o,this.sessionKey),r&&(d={encrypted:c.cryptoService.encryptMetadata(r,this.sessionKey)}),u=!0),await this.appSyncClient.createEvent({sessionId:a,type:c.EventType.TOOL_USE,source:c.EventSource.DESKTOP,content:l,metadata:d,isEncrypted:u});return}if(i==="ASSISTANT_RESPONSE"||i==="USER_PROMPT"){let l=o,d=!1;this.sessionKey&&o&&(l=c.cryptoService.encryptContent(o,this.sessionKey),d=!0),await this.appSyncClient.createEvent({sessionId:a,type:i==="ASSISTANT_RESPONSE"?c.EventType.ASSISTANT_RESPONSE:c.EventType.USER_PROMPT,source:c.EventSource.DESKTOP,content:l,isEncrypted:d});return}}mapToolName(e){return{shell_command:"Bash",shell:"Bash",apply_patch:"Edit",create_file:"Write",read_file:"Read"}[e]||e}isRecentMobilePrompt(e){return!1}setupEventHandlers(){this.sessionWatcher.on("session-started",async e=>{if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionState){n.info("[JSONL] Session already active, skipping",{currentSessionId:this.sessionState.sessionId,codexSessionId:e.id});return}await this.ensureSessionStarted(e)}),this.sessionWatcher.on("log-entry",async e=>{await this.handleLogEntry(e)}),this.approvalDetector.on("approval-pending",async e=>{await this.handleApprovalPending(e)}),this.tmuxPaneObserver.on("prompt-candidate",async e=>{await this.handleTmuxPromptCandidate(e.snapshot)}),this.tmuxPaneObserver.on("observer-error",e=>{n.debug("Tmux pane observer error",{error:e})}),this.sessionWatcher.on("error",e=>{n.error("Session watcher error:",e)})}async ensureSessionStarted(e){if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionState)return;if(this.sessionStartedInitPromise){try{await this.sessionStartedInitPromise}catch{}return}let t=this.handleSessionStarted(e);this.sessionStartedInitPromise=t.catch(()=>{});try{await t}finally{this.sessionStartedInitPromise=null}}async handleSessionStarted(e){n.info("Handling new Codex session",{codexSessionId:e.id}),this.isInitializingSession=!0,this.bufferedLogEntries=[],this.sessionState&&await this.endActiveSession("new-codex-session-started");let t=process.env.CODEX_WORKING_DIRECTORY||e.cwd||process.cwd(),s=this.generateSessionId(e.id),i=this.appSyncClient.getCurrentUserId(),o={codexSessionId:e.id,cliVersion:e.cli_version,modelProvider:e.model_provider};try{let r=await(0,c.resumeOrCreateSession)({sessionId:s,userId:i,agentType:c.AgentType.CODEX,projectPath:t,metadata:o},this.appSyncClient,n);this.sessionKey=r.sessionKey,await m("daemon_init_step_completed",{step:"session_resume_or_create",path:"session_started"})}catch(r){throw this.isInitializingSession=!1,await m("daemon_init_step_failed",{step:"session_resume_or_create",path:"session_started",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to create/resume session:",r),r}try{this.sessionState={sessionId:s,userId:i,projectPath:t,cwd:e.cwd,createdAt:new Date,subscriptionActive:!1,metadata:o,codexSessionId:e.id,codexLogFile:this.sessionWatcher.getActiveLogFile()||void 0},await m("daemon_init_step_completed",{step:"session_state_set",path:"session_started"})}catch(r){await m("daemon_init_step_failed",{step:"session_state_set",path:"session_started",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to set session state:",r)}try{this.subscribeToMobileEvents(s)?await m("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"session_started"}):await m("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(r){await m("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to subscribe to mobile events:",r)}try{this.appSyncClient.startHeartbeat(s),await m("daemon_init_step_completed",{step:"heartbeat_start",path:"session_started"})}catch(r){await m("daemon_init_step_failed",{step:"heartbeat_start",path:"session_started",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to start heartbeat:",r)}this.startMobileEndWatcher(s);try{await this.flushBufferedLogEntries(),await m("daemon_init_step_completed",{step:"flush_buffered_entries",path:"session_started"})}catch(r){await m("daemon_init_step_failed",{step:"flush_buffered_entries",path:"session_started",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to flush buffered log entries:",r),this.bufferedLogEntries=[]}try{await this.startTmuxObserver()?await m("daemon_init_step_completed",{step:"tmux_observer_start",path:"session_started"}):await m("daemon_init_step_failed",{step:"tmux_observer_start",path:"session_started",error_class:"TmuxObserverStartFailed",error_message:"tmuxPaneObserver.start threw (see plugin log)"})}catch(r){await m("daemon_init_step_failed",{step:"tmux_observer_start",path:"session_started",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to start tmux observer:",r)}this.isInitializingSession=!1}async flushBufferedLogEntries(){if(this.bufferedLogEntries.length===0)return;let e=this.bufferedLogEntries;this.bufferedLogEntries=[],n.info("Flushing buffered log entries after session initialization",{count:e.length,sessionId:this.sessionState?.sessionId});for(let t of e)await this.handleLogEntry(t)}async handleLogEntry(e){if(!this.sessionState){if(this.isInitializingSession){this.bufferedLogEntries.push(e),n.debug("Buffering log entry until session initialization completes",{type:e.type,bufferedCount:this.bufferedLogEntries.length});return}n.warn("Received log entry but no active session");return}if(e.type==="response_item"&&e.payload){let s=e.payload.type;s==="function_call"||s==="custom_tool_call"?this.approvalDetector.onToolCallStart(e.payload.call_id,e.payload.name,e.payload.arguments||e.payload.input||""):(s==="function_call_output"||s==="custom_tool_call_output")&&(this.approvalDetector.onToolCallComplete(e.payload.call_id),this.pendingInteractivePrompt?.callId===e.payload.call_id&&(this.pendingInteractivePrompt=null))}let t=Y(e,this.sessionState.sessionId);if(t){if(this.hooksActive){if(t.type===c.EventType.USER_PROMPT||t.type===c.EventType.ASSISTANT_RESPONSE){n.debug("[JSONL] Skipping \u2014 hooks deliver this event type",{type:t.type});return}let s=e.payload?.type;if((s==="function_call"||s==="function_call_output")&&(t.type===c.EventType.TOOL_USE||t.type===c.EventType.INTERACTIVE_PROMPT)){n.debug("[JSONL] Skipping function_call \u2014 hooks deliver this",{type:t.type,tool:e.payload?.name});return}}try{if(this.sessionKey){if(t.content=c.cryptoService.encryptContent(t.content,this.sessionKey),t.metadata){let s=c.cryptoService.encryptMetadata(t.metadata,this.sessionKey);t.metadata={encrypted:s}}t.isEncrypted=!0,n.debug("Event encrypted",{type:t.type})}await this.appSyncClient.createEvent(t),n.debug("Event synced to backend",{type:t.type,encrypted:!!this.sessionKey})}catch(s){n.error("Failed to sync event:",s)}}}async handleApprovalPending(e){if(this.sessionState){n.info("Sending approval pending interactive prompt",e);try{let t=await this.tryParseInteractivePromptFromTmux(),s=t?.parsedPrompt??null,i=this.buildToolDetailsForInteractivePrompt(e,t?.snapshot),o=i.tool_name||this.mapToolNameForApproval(e.toolName),r=i.tool_input||this.buildFallbackToolInput(e),a=!!(o&&r),l=this.buildPromptPresentation(s),d=l.options,u=e.filePath?`File: ${e.filePath}`:void 0,h=l.content||`Codex is waiting for approval.
|
|
11
|
+
`).trim();return(0,oe.createHash)("sha256").update(s).digest("hex")}};var w=require("@quantiya/codevibe-core");var z=f(require("express")),E=f(require("fs")),W=f(require("path")),H=f(require("os"));var L=class{constructor(){this.assignedPort=0;this.app=(0,z.default)(),this.setupMiddleware(),this.setupRoutes(),this.tmuxSession=process.env.CODEVIBE_CODEX_TMUX_SESSION}getPort(){return this.assignedPort}setupMiddleware(){this.app.use(z.default.json({limit:"1mb"})),this.app.use((e,t,s)=>{n.debug(`${e.method} ${e.path}`,{body:e.body}),s()})}setupRoutes(){this.app.get("/health",(e,t)=>{t.json({success:!0,data:{status:"healthy",uptime:process.uptime()}})}),this.app.post("/event",this.handleEvent.bind(this))}async handleEvent(e,t){try{let s=e.body;if(!s.session_id||!s.hook_event_name){t.status(400).json({success:!1,error:"Missing session_id or hook_event_name"});return}let i=this.transformHookToEvent(s);n.info("Received hook event",{sessionId:s.session_id,hookEvent:s.hook_event_name,type:i.type}),this.eventHandler&&await this.eventHandler(i),t.json({success:!0})}catch(s){n.error("Error handling event:",s),t.status(500).json({success:!1,error:s instanceof Error?s.message:"Unknown error"})}}transformHookToEvent(e){let t={cwd:e.cwd,hook_event_name:e.hook_event_name,...e.metadata||{}},s,i;switch(e.hook_event_name){case"SessionStart":s="NOTIFICATION",i="Session started",t.source=e.source;break;case"UserPromptSubmit":s="USER_PROMPT",i=e.prompt||"";break;case"PreToolUse":s="NOTIFICATION",i="PreToolUse observed",t.tool_name=e.tool_name,t.tool_input=e.tool_input,t.tool_use_id=e.tool_use_id,t.approval_status="observed_pre_tool",t.requires_user_action=!1;break;case"PostToolUse":s="TOOL_USE",i=JSON.stringify({tool_name:e.tool_name,tool_input:e.tool_input,tool_response:e.tool_response}),t.tool_name=e.tool_name;break;case"Stop":s="ASSISTANT_RESPONSE",i=e.last_assistant_message||"";break;default:s="NOTIFICATION",i=`Hook: ${e.hook_event_name}`}return{session_id:e.session_id,hook_event_name:e.hook_event_name,type:s,source:"DESKTOP",content:i,metadata:t}}onEvent(e){this.eventHandler=e}async start(){return new Promise((e,t)=>{try{this.server=this.app.listen(0,"localhost",()=>{let s=this.server.address();this.assignedPort=s.port,n.info(`HTTP API listening on http://localhost:${this.assignedPort}`),this.writePortFile(this.assignedPort),e(this.assignedPort)}),this.server.on("error",s=>{n.error("HTTP server error:",s),t(s)})}catch(s){t(s)}})}writePortFile(e){if(!this.tmuxSession){n.warn("No CODEVIBE_CODEX_TMUX_SESSION set, skipping port file");return}let t=W.join(H.tmpdir(),`codevibe-codex-${this.tmuxSession}.port`);try{E.writeFileSync(t,e.toString()),n.info(`Port file written: ${t} -> ${e}`)}catch(s){n.error(`Failed to write port file: ${t}`,s)}}removePortFile(){if(!this.tmuxSession)return;let e=W.join(H.tmpdir(),`codevibe-codex-${this.tmuxSession}.port`);try{E.existsSync(e)&&(E.unlinkSync(e),n.info(`Port file removed: ${e}`))}catch(t){n.warn(`Failed to remove port file: ${e}`,t)}}async stop(){return this.removePortFile(),new Promise(e=>{this.server?this.server.close(()=>{n.info("HTTP API stopped"),e()}):e()})}};var k=class{constructor(e={}){this.pendingBySession=new Map;this.expiryMs=e.expiryMs??1e4,this.minFuzzyEchoLength=e.minFuzzyEchoLength??16,this.minFuzzyEchoRatio=e.minFuzzyEchoRatio??.35,this.now=e.now??Date.now}track(e,t){let s=this.normalize(t);if(!s)return;let i=this.validEntries(e);i.push({normalized:s,timestamp:this.now()}),this.pendingBySession.set(e,i)}forget(e,t){let s=this.normalize(t);if(!s)return;let i=!1,o=this.validEntries(e).filter(r=>!i&&r.normalized===s?(i=!0,!1):!0);this.replaceEntries(e,o)}consumeIfDuplicate(e,t){let s=this.normalize(t);if(!s)return null;let i=null,o=this.validEntries(e).filter(r=>{if(!i){let a=this.matchType(r.normalized,s);if(a)return i={matchType:a,originalLength:r.normalized.length,echoLength:s.length},!1}return!0});return this.replaceEntries(e,o),i}validEntries(e){let t=this.now()-this.expiryMs;return(this.pendingBySession.get(e)||[]).filter(s=>s.timestamp>=t)}replaceEntries(e,t){t.length>0?this.pendingBySession.set(e,t):this.pendingBySession.delete(e)}matchType(e,t){if(e===t)return"exact";let s=t.length>=this.minFuzzyEchoLength,i=t.length/e.length>=this.minFuzzyEchoRatio;return s&&i&&e.endsWith(t)?"suffix":null}normalize(e){return e.replace(/\s+/g," ").trim()}};var de=f(require("crypto")),ue=f(require("fs")),he=f(require("https")),N=f(require("os")),me=f(require("path")),Oe="G-GS74YEQTB8",Re="lAfOF6OxRzSQ-NsLBRjhAg",Me="www.google-analytics.com",Ae=`/mp/collect?measurement_id=${Oe}&api_secret=${Re}`,ce=800;function Le(){try{let p=me.resolve(__dirname,"..","package.json"),e=ue.readFileSync(p,"utf-8"),t=JSON.parse(e);if(typeof t.version=="string"&&t.version.length>0&&t.version.length<30)return t.version}catch{}return"unknown"}var ke=Le();function Ne(){let p=typeof process.getuid=="function"?process.getuid():0;return de.createHash("sha256").update(`${N.hostname()}-${p}`).digest("hex").substring(0,36)}function De(p){if(!p)return"";let e=N.homedir(),t=p.replace(/[\n\r\t]/g," ");if(e&&e.length>0){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replace(new RegExp(s,"g"),"~")}return t=t.replace(/\/Users\/[^/\s"'`]+/g,"/Users/<user>").replace(/\/home\/[^/\s"'`]+/g,"/home/<user>").replace(/[^\x20-\x7E]/g,""),t.trim().substring(0,100)}function m(p,e){return new Promise(t=>{let s,i=!1,o=()=>{i||(i=!0,clearTimeout(r),t())},r=setTimeout(()=>{try{s?.destroy()}catch{}o()},ce);typeof r.unref=="function"&&r.unref();try{let a={...e};typeof a.error_message=="string"&&(a.error_message=De(a.error_message));let l=JSON.stringify({client_id:Ne(),events:[{name:p,params:{agent:"codex",plugin_version:ke,platform:process.platform,source:process.env.CODEVIBE_TELEMETRY_SOURCE||"production",...a}}]});s=he.request({hostname:Me,path:Ae,method:"POST",headers:{"Content-Type":"application/json"},timeout:ce},d=>{d.resume(),d.on("end",o),d.on("close",o),d.on("error",o)}),s.on("error",o),s.on("timeout",()=>{try{s?.destroy()}catch{}o()}),s.on("close",o),s.write(l),s.end()}catch{o()}})}var Ue=(0,ve.promisify)(Se.exec),$e="/quit",fe="CODEVIBE_CODEX_TMUX_SESSION",ze=600*1e3;async function We(p,e){let t=async(s,i)=>{try{await Ue(s)}catch(o){n.warn("tmux send-keys failed during self-terminate",{sessionName:p,label:i,error:String(o)})}};await t(`tmux send-keys -t "${p}" C-c`,"ctrl-c"),await new Promise(s=>setTimeout(s,200)),await t(`tmux send-keys -t "${p}" -l "${e}"`,"quit-text"),await new Promise(s=>setTimeout(s,500)),await t(`tmux send-keys -t "${p}" Enter`,"enter")}var K=class{constructor(){this.sessionState=null;this.unsubscribe=null;this.sessionKey=null;this.pendingInteractivePrompt=null;this.isInitializingSession=!1;this.bufferedLogEntries=[];this.hooksActive=!1;this.subscribedSessionId=null;this.mobilePromptDeduper=new k({expiryMs:1e4});this.launchSessionInitPromise=null;this.sessionStartedInitPromise=null;this.httpApi=new L,this.sessionWatcher=new C,this.approvalDetector=new O,this.promptResponder=new R,this.tmuxPaneObserver=new M}async start(){n.info("Starting CodeVibe Codex companion server",{environment:(0,c.getEnvironment)()}),this.appSyncClient=new c.AppSyncClient,await this.appSyncClient.authenticateWithStoredTokens()||(n.error('Authentication failed. Run "codevibe-codex login" first.'),console.error('Not authenticated. Run "codevibe-codex login" to sign in.'),process.exit(1)),n.info("Authenticated successfully",{userId:this.appSyncClient.getCurrentUserId(),email:this.appSyncClient.getCurrentUserEmail()}),await(0,c.registerDeviceEncryptionKey)(this.appSyncClient,n),(0,c.startDeviceKeyWatcher)(this.appSyncClient,n);try{let s=await this.appSyncClient.sweepOrphanSessions({agentType:"CODEX"});s>0&&n.info("Orphan sweep: marked stale Codex sessions INACTIVE",{swept:s})}catch(s){n.warn("Orphan sweep failed, continuing startup",{error:s instanceof Error?s.message:String(s)})}this.httpApi.onEvent(this.handleEventFromHook.bind(this));let t=await this.httpApi.start();n.info("HTTP API started for hooks",{port:t}),await this.createLaunchSession(),this.setupEventHandlers(),this.sessionWatcher.start(),n.info("CodeVibe Codex companion server started")}async createLaunchSession(){let e=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!e){n.warn("No CODEVIBE_CODEX_TMUX_SESSION \u2014 skipping launch session");return}let t;this.launchSessionInitPromise=new Promise(s=>{t=s});try{let s=process.env.CODEX_WORKING_DIRECTORY||process.cwd(),i=this.generateSessionId(e),o=this.appSyncClient.getCurrentUserId();n.info("Creating launch session",{sessionId:i,projectPath:s});let r=!1;try{let a=await(0,c.resumeOrCreateSession)({sessionId:i,userId:o,agentType:c.AgentType.CODEX,projectPath:s,metadata:{launchSession:!0}},this.appSyncClient,n);this.sessionKey=a.sessionKey,r=!0,this.sessionState={sessionId:i,userId:o,projectPath:s,cwd:s,createdAt:new Date,subscriptionActive:!1,metadata:{launchSession:!0},codexSessionId:e,codexLogFile:void 0},await m("daemon_init_step_completed",{step:"session_resume_or_create",path:"launch_session"})}catch(a){await m("daemon_init_step_failed",{step:"session_resume_or_create",path:"launch_session",error_class:a?.name||"Error",error_message:a?.message||String(a)}),n.error("Failed to create/resume launch session (non-fatal)",{error:a})}if(!r)return;await m("daemon_init_step_completed",{step:"session_state_set",path:"launch_session"});try{this.subscribeToMobileEvents(i)?await m("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"launch_session"}):await m("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(a){await m("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:a?.name||"Error",error_message:a?.message||String(a)}),n.error("Failed to subscribe to mobile events for launch session",{error:a})}try{this.appSyncClient.startHeartbeat(i),await m("daemon_init_step_completed",{step:"heartbeat_start",path:"launch_session"})}catch(a){await m("daemon_init_step_failed",{step:"heartbeat_start",path:"launch_session",error_class:a?.name||"Error",error_message:a?.message||String(a)}),n.error("Failed to start heartbeat for launch session",{error:a})}this.startMobileEndWatcher(i),n.info("Launch session created",{sessionId:i})}finally{t()}}async handleEventFromHook(e){let{session_id:t,hook_event_name:s,type:i,content:o,metadata:r}=e;if(this.hooksActive=!0,n.info("[Hooks] Received event",{sessionId:t,hookEvent:s,type:i,contentLength:o?.length}),s==="SessionStart"){if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionState)n.info("[Hooks] SessionStart \u2014 launch session already exists, updating codexSessionId",{existingSessionId:this.sessionState.sessionId,codexSessionId:t}),this.sessionState.codexSessionId=t,this.sessionState.metadata={...this.sessionState.metadata,codexSessionId:t,cliVersion:r?.model||"unknown",modelProvider:r?.model||"unknown",launchSession:void 0},this.appSyncClient.updateSession({sessionId:this.sessionState.sessionId,metadata:this.sessionState.metadata}).catch(l=>n.warn("Failed to update session metadata",{error:l}));else{let l={id:t,timestamp:new Date().toISOString(),cwd:r?.cwd||process.cwd(),originator:"hook",cli_version:r?.model||"unknown",instructions:null,source:r?.source||"startup",model_provider:r?.model||"unknown"};await this.ensureSessionStarted(l)}return}if(!this.sessionState){n.warn("[Hooks] Session not initialized, buffering event",{hook_event_name:s});return}let a=this.sessionState.sessionId;if(i==="USER_PROMPT"&&o){let l=this.consumeRecentMobilePrompt(a,o);if(l){n.info("[Hooks] Skipping duplicate USER_PROMPT from mobile",{sessionId:a,matchType:l.matchType,originalLength:l.originalLength,echoLength:l.echoLength});return}}if(s==="PreToolUse"){n.debug("[Hooks] PreToolUse observed; AppSync emission suppressed",{toolName:r?.tool_name||"unknown",sessionId:a});return}if(s==="PostToolUse"){let l=o,d=r,u=!1;this.sessionKey&&(l=c.cryptoService.encryptContent(o,this.sessionKey),r&&(d={encrypted:c.cryptoService.encryptMetadata(r,this.sessionKey)}),u=!0),await this.appSyncClient.createEvent({sessionId:a,type:c.EventType.TOOL_USE,source:c.EventSource.DESKTOP,content:l,metadata:d,isEncrypted:u});return}if(i==="ASSISTANT_RESPONSE"||i==="USER_PROMPT"){let l=o,d=!1;this.sessionKey&&o&&(l=c.cryptoService.encryptContent(o,this.sessionKey),d=!0),await this.appSyncClient.createEvent({sessionId:a,type:i==="ASSISTANT_RESPONSE"?c.EventType.ASSISTANT_RESPONSE:c.EventType.USER_PROMPT,source:c.EventSource.DESKTOP,content:l,isEncrypted:d});return}}mapToolName(e){return{shell_command:"Bash",shell:"Bash",apply_patch:"Edit",create_file:"Write",read_file:"Read"}[e]||e}trackMobilePrompt(e,t){this.mobilePromptDeduper.track(e,t),n.debug("Tracking mobile prompt for USER_PROMPT echo deduplication",{sessionId:e,promptLength:t.trim().length})}forgetMobilePrompt(e,t){this.mobilePromptDeduper.forget(e,t)}consumeRecentMobilePrompt(e,t){return this.mobilePromptDeduper.consumeIfDuplicate(e,t)}setupEventHandlers(){this.sessionWatcher.on("session-started",async e=>{if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionState){n.info("[JSONL] Session already active, skipping",{currentSessionId:this.sessionState.sessionId,codexSessionId:e.id});return}await this.ensureSessionStarted(e)}),this.sessionWatcher.on("log-entry",async e=>{await this.handleLogEntry(e)}),this.approvalDetector.on("approval-pending",async e=>{await this.handleApprovalPending(e)}),this.tmuxPaneObserver.on("prompt-candidate",async e=>{await this.handleTmuxPromptCandidate(e.snapshot)}),this.tmuxPaneObserver.on("observer-error",e=>{n.debug("Tmux pane observer error",{error:e})}),this.sessionWatcher.on("error",e=>{n.error("Session watcher error:",e)})}async ensureSessionStarted(e){if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionState)return;if(this.sessionStartedInitPromise){try{await this.sessionStartedInitPromise}catch{}return}let t=this.handleSessionStarted(e);this.sessionStartedInitPromise=t.catch(()=>{});try{await t}finally{this.sessionStartedInitPromise=null}}async handleSessionStarted(e){n.info("Handling new Codex session",{codexSessionId:e.id}),this.isInitializingSession=!0,this.bufferedLogEntries=[],this.sessionState&&await this.endActiveSession("new-codex-session-started");let t=process.env.CODEX_WORKING_DIRECTORY||e.cwd||process.cwd(),s=this.generateSessionId(e.id),i=this.appSyncClient.getCurrentUserId(),o={codexSessionId:e.id,cliVersion:e.cli_version,modelProvider:e.model_provider};try{let r=await(0,c.resumeOrCreateSession)({sessionId:s,userId:i,agentType:c.AgentType.CODEX,projectPath:t,metadata:o},this.appSyncClient,n);this.sessionKey=r.sessionKey,await m("daemon_init_step_completed",{step:"session_resume_or_create",path:"session_started"})}catch(r){throw this.isInitializingSession=!1,await m("daemon_init_step_failed",{step:"session_resume_or_create",path:"session_started",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to create/resume session:",r),r}try{this.sessionState={sessionId:s,userId:i,projectPath:t,cwd:e.cwd,createdAt:new Date,subscriptionActive:!1,metadata:o,codexSessionId:e.id,codexLogFile:this.sessionWatcher.getActiveLogFile()||void 0},await m("daemon_init_step_completed",{step:"session_state_set",path:"session_started"})}catch(r){await m("daemon_init_step_failed",{step:"session_state_set",path:"session_started",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to set session state:",r)}try{this.subscribeToMobileEvents(s)?await m("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"session_started"}):await m("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(r){await m("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to subscribe to mobile events:",r)}try{this.appSyncClient.startHeartbeat(s),await m("daemon_init_step_completed",{step:"heartbeat_start",path:"session_started"})}catch(r){await m("daemon_init_step_failed",{step:"heartbeat_start",path:"session_started",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to start heartbeat:",r)}this.startMobileEndWatcher(s);try{await this.flushBufferedLogEntries(),await m("daemon_init_step_completed",{step:"flush_buffered_entries",path:"session_started"})}catch(r){await m("daemon_init_step_failed",{step:"flush_buffered_entries",path:"session_started",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to flush buffered log entries:",r),this.bufferedLogEntries=[]}try{await this.startTmuxObserver()?await m("daemon_init_step_completed",{step:"tmux_observer_start",path:"session_started"}):await m("daemon_init_step_failed",{step:"tmux_observer_start",path:"session_started",error_class:"TmuxObserverStartFailed",error_message:"tmuxPaneObserver.start threw (see plugin log)"})}catch(r){await m("daemon_init_step_failed",{step:"tmux_observer_start",path:"session_started",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to start tmux observer:",r)}this.isInitializingSession=!1}async flushBufferedLogEntries(){if(this.bufferedLogEntries.length===0)return;let e=this.bufferedLogEntries;this.bufferedLogEntries=[],n.info("Flushing buffered log entries after session initialization",{count:e.length,sessionId:this.sessionState?.sessionId});for(let t of e)await this.handleLogEntry(t)}async handleLogEntry(e){if(!this.sessionState){if(this.isInitializingSession){this.bufferedLogEntries.push(e),n.debug("Buffering log entry until session initialization completes",{type:e.type,bufferedCount:this.bufferedLogEntries.length});return}n.warn("Received log entry but no active session");return}if(e.type==="response_item"&&e.payload){let s=e.payload.type;s==="function_call"||s==="custom_tool_call"?this.approvalDetector.onToolCallStart(e.payload.call_id,e.payload.name,e.payload.arguments||e.payload.input||""):(s==="function_call_output"||s==="custom_tool_call_output")&&(this.approvalDetector.onToolCallComplete(e.payload.call_id),this.pendingInteractivePrompt?.callId===e.payload.call_id&&(this.pendingInteractivePrompt=null))}let t=Z(e,this.sessionState.sessionId);if(t){if(this.hooksActive){if(t.type===c.EventType.USER_PROMPT||t.type===c.EventType.ASSISTANT_RESPONSE){n.debug("[JSONL] Skipping \u2014 hooks deliver this event type",{type:t.type});return}let s=e.payload?.type;if((s==="function_call"||s==="function_call_output")&&(t.type===c.EventType.TOOL_USE||t.type===c.EventType.INTERACTIVE_PROMPT)){n.debug("[JSONL] Skipping function_call \u2014 hooks deliver this",{type:t.type,tool:e.payload?.name});return}}if(t.type===c.EventType.USER_PROMPT&&t.source===c.EventSource.DESKTOP){let s=this.consumeRecentMobilePrompt(this.sessionState.sessionId,t.content);if(s){n.info("[JSONL] Skipping duplicate USER_PROMPT from mobile",{sessionId:this.sessionState.sessionId,matchType:s.matchType,originalLength:s.originalLength,echoLength:s.echoLength});return}}try{if(this.sessionKey){if(t.content=c.cryptoService.encryptContent(t.content,this.sessionKey),t.metadata){let s=c.cryptoService.encryptMetadata(t.metadata,this.sessionKey);t.metadata={encrypted:s}}t.isEncrypted=!0,n.debug("Event encrypted",{type:t.type})}await this.appSyncClient.createEvent(t),n.debug("Event synced to backend",{type:t.type,encrypted:!!this.sessionKey})}catch(s){n.error("Failed to sync event:",s)}}}async handleApprovalPending(e){if(this.sessionState){n.info("Sending approval pending interactive prompt",e);try{let t=await this.tryParseInteractivePromptFromTmux(),s=t?.parsedPrompt??null,i=this.buildToolDetailsForInteractivePrompt(e,t?.snapshot),o=i.tool_name||this.mapToolNameForApproval(e.toolName),r=i.tool_input||this.buildFallbackToolInput(e),a=!!(o&&r),l=this.buildPromptPresentation(s),d=l.options,u=e.filePath?`File: ${e.filePath}`:void 0,h=l.content||`Codex is waiting for approval.
|
|
12
12
|
${e.hint}`;u&&!h.includes(u)&&(h=`${h}
|
|
13
|
-
${u}`);let g={promptId:e.callId,callId:e.callId,kind:l.kind,options:d,submitMap:l.submitMap,promptText:l.promptText,createdAt:Date.now(),source:s?"tmux":"heuristic",requiresFollowUpText:l.requiresFollowUpText};if(!this.reserveInteractivePrompt(g))return;let S={isApprovalHint:!0,toolName:e.toolName,toolInput:e.toolInput,hint:e.hint,callId:e.callId,filePath:e.filePath,diff:e.diff,rawInput:e.rawInput,tool_name:o,tool_input:r,has_details:a,options:d,instructions:l.instructions,prompt_source:s?"tmux":"heuristic"},b=!1;n.debug("Interactive prompt (pre-encryption)",{sessionId:this.sessionState.sessionId,callId:e.callId,contentPreview:h.substring(0,200),toolDetails:i,metadata:S}),this.sessionKey&&(h=c.cryptoService.encryptContent(h,this.sessionKey),S={encrypted:c.cryptoService.encryptMetadata(S,this.sessionKey)},b=!0),await this.appSyncClient.createEvent({sessionId:this.sessionState.sessionId,type:c.EventType.INTERACTIVE_PROMPT,source:c.EventSource.DESKTOP,content:h,metadata:S,promptId:e.callId,...b?{isEncrypted:!0}:{}})}catch(t){n.error("Failed to send approval interactive prompt:",t)}}}async handleTmuxPromptCandidate(e){if(!this.sessionState)return;let t=(0,
|
|
13
|
+
${u}`);let g={promptId:e.callId,callId:e.callId,kind:l.kind,options:d,submitMap:l.submitMap,promptText:l.promptText,createdAt:Date.now(),source:s?"tmux":"heuristic",requiresFollowUpText:l.requiresFollowUpText};if(!this.reserveInteractivePrompt(g))return;let S={isApprovalHint:!0,toolName:e.toolName,toolInput:e.toolInput,hint:e.hint,callId:e.callId,filePath:e.filePath,diff:e.diff,rawInput:e.rawInput,tool_name:o,tool_input:r,has_details:a,options:d,instructions:l.instructions,prompt_source:s?"tmux":"heuristic"},b=!1;n.debug("Interactive prompt (pre-encryption)",{sessionId:this.sessionState.sessionId,callId:e.callId,contentPreview:h.substring(0,200),toolDetails:i,metadata:S}),this.sessionKey&&(h=c.cryptoService.encryptContent(h,this.sessionKey),S={encrypted:c.cryptoService.encryptMetadata(S,this.sessionKey)},b=!0),await this.appSyncClient.createEvent({sessionId:this.sessionState.sessionId,type:c.EventType.INTERACTIVE_PROMPT,source:c.EventSource.DESKTOP,content:h,metadata:S,promptId:e.callId,...b?{isEncrypted:!0}:{}})}catch(t){n.error("Failed to send approval interactive prompt:",t)}}}async handleTmuxPromptCandidate(e){if(!this.sessionState)return;let t=(0,w.parseInteractivePrompt)(e);if(!t)return;let s=this.buildPromptPresentation(t),i=this.getMostRecentPendingToolCall();i||(await new Promise(T=>setTimeout(T,500)),i=this.getMostRecentPendingToolCall());let o=i?this.buildApprovalPromptContextFromPendingCall(i):null,r=o?this.buildToolDetailsForInteractivePrompt(o,e):{},a=r.tool_name||this.mapToolNameForApproval(i?.name),l=r.tool_input||(o?this.buildFallbackToolInput(o):void 0),d=!!(a&&l),u=i?.callId||(0,ge.v4)(),h={promptId:u,callId:i?.callId,kind:s.kind,options:s.options,submitMap:s.submitMap,promptText:s.promptText,createdAt:Date.now(),source:"tmux",requiresFollowUpText:s.requiresFollowUpText};if(!this.reserveInteractivePrompt(h))return;let g={options:s.options,instructions:s.instructions,prompt_source:"tmux_live",tool_name:a,tool_input:l,has_details:d},S=s.content,b=!1;this.sessionKey&&(S=c.cryptoService.encryptContent(S,this.sessionKey),g={encrypted:c.cryptoService.encryptMetadata(g,this.sessionKey)},b=!0);try{await this.appSyncClient.createEvent({sessionId:this.sessionState.sessionId,type:c.EventType.INTERACTIVE_PROMPT,source:c.EventSource.DESKTOP,content:S,metadata:g,promptId:u,...b?{isEncrypted:!0}:{}}),n.info("Sent tmux-detected interactive prompt",{sessionId:this.sessionState.sessionId,promptText:t.promptText,kind:t.kind})}catch(T){n.error("Failed to send tmux-detected interactive prompt",{error:T})}}reserveInteractivePrompt(e){let t=this.pendingInteractivePrompt;return t&&this.isSameInteractivePrompt(t,e)?(!t.callId&&e.callId&&(t.callId=e.callId,n.debug("Merged callId into existing interactive prompt",{source:t.source,callId:e.callId,promptText:t.promptText})),n.debug("Skipping duplicate interactive prompt emission",{existingSource:t.source,candidateSource:e.source,existingCallId:t.callId,candidateCallId:e.callId,promptText:e.promptText}),!1):(this.pendingInteractivePrompt=e,!0)}isSameInteractivePrompt(e,t){return Date.now()-e.createdAt>ze?!1:e.callId&&t.callId?e.callId===t.callId:e.kind===t.kind&&this.normalizePromptDedupeText(e.promptText)===this.normalizePromptDedupeText(t.promptText)}normalizePromptDedupeText(e){return e.replace(/\s+/g," ").trim().toLowerCase()}async startTmuxObserver(){let e=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!e)return n.debug("Skipping tmux pane observer start - no tmux session in environment"),!0;try{return await this.tmuxPaneObserver.start(e),!0}catch(t){return n.warn("Failed to start tmux pane observer",{tmuxSession:e,error:t}),!1}}async tryParseInteractivePromptFromTmux(){try{let e=await this.tmuxPaneObserver.captureSnapshot(),t=(0,w.parseInteractivePrompt)(e);return n.debug("tmux prompt parse result",{parsed:!!t,kind:t?.kind,promptText:t?.promptText,snapshotPreview:this.summarizePromptSnapshot(e)}),{parsedPrompt:t,snapshot:e}}catch(e){return n.debug("tmux prompt parsing unavailable",{error:e}),null}}buildPromptPresentation(e){return e?{content:e.promptText,promptText:e.promptText,kind:e.kind,options:e.options,submitMap:e.submitMap,instructions:this.buildPromptInstructions(e),requiresFollowUpText:e.requiresFollowUpText}:{content:"Codex is waiting for approval.",promptText:"Codex is waiting for approval.",kind:"yes_no",options:[{number:"1",text:'Yes (sends "y")'},{number:"2",text:'No, tell Codex what to change (sends "n <instructions>")'}],submitMap:{1:"y",2:"n"},instructions:"Reply with 1 to approve, or 2 followed by what to change",requiresFollowUpText:!0}}getMostRecentPendingToolCall(){let e=this.approvalDetector.getPendingCalls();return e.length===0?null:e.reduce((t,s)=>s.timestamp>t.timestamp?s:t)}buildApprovalPromptContextFromPendingCall(e){return{toolName:e.name,filePath:e.filePath,diff:e.diff,toolInput:e.parsedInput,rawInput:e.input,hint:e.filePath?`File: ${e.filePath}`:`Tool: ${this.mapToolNameForApproval(e.name)||e.name}`}}buildPromptInstructions(e){return e.kind==="yes_no"&&e.requiresFollowUpText?"Reply with 1 to approve, or 2 followed by what to change":e.kind==="yes_no"?"Reply with 1 for yes or 2 for no":e.kind==="numbered"?"Reply with the number of the option you want":"Reply with your response"}summarizePromptSnapshot(e){return e.split(`
|
|
14
14
|
`).map(t=>t.trimEnd()).filter(t=>t.length>0).slice(-12).map(t=>t.slice(0,160)).join(`
|
|
15
15
|
`)}translatePromptResponse(e){let t=this.pendingInteractivePrompt;if(!t)return{primaryInput:e};let i=e.trim().match(/^(\d+)(?:[,.:;\-\s]+([\s\S]+))?$/);if(!i)return{primaryInput:e};let o=i[1],r=i[2]?.trim(),a=t.submitMap[o];return a?t.requiresFollowUpText&&r?{primaryInput:a,followUpInput:r}:{primaryInput:a}:{primaryInput:e}}buildToolDetailsForInteractivePrompt(e,t){let s=e.toolName,i=e.toolInput&&typeof e.toolInput=="object"?e.toolInput:void 0;if(s==="apply_patch"){let r=e.diff||e.rawInput;if(r){let{oldString:a,newString:l,oldStartLine:d,newStartLine:u}=this.extractOldNewFromPatch(r),h=t?this.extractDiffLineAnchorsFromSnapshot(t):{};return{tool_name:"Edit",tool_input:{file_path:e.filePath,content:r,diff:e.diff,raw_patch:e.rawInput,old_string:a,new_string:l,old_start_line:d??h.oldStartLine,new_start_line:u??h.newStartLine}}}}if(s==="shell_command"||s==="shell"){let r=i?.command||e.rawInput||e.hint;if(r)return{tool_name:"Bash",tool_input:{command:r,output:i?.output}}}let o={};return e.filePath&&(o.file_path=e.filePath),e.diff&&(o.diff=e.diff),e.rawInput&&(o.raw_input=e.rawInput),Object.keys(o).length>0?{tool_name:s||"Tool",tool_input:o}:{}}buildFallbackToolInput(e){let t={};return e.filePath&&(t.file_path=e.filePath),e.diff&&(t.diff=e.diff),e.rawInput&&(t.raw_input=e.rawInput),e.toolInput&&typeof e.toolInput=="object"&&(t.parsed_input=e.toolInput),Object.keys(t).length>0?t:void 0}mapToolNameForApproval(e){return e?{apply_patch:"Edit",shell_command:"Bash",shell:"Bash"}[e]||e:void 0}extractOldNewFromPatch(e){let t=[],s=[],i=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/,o=0,r=0,a=0,l,d;for(let u of e.split(`
|
|
16
16
|
`)){let h=u.match(i);if(h){o+=1,r=Number.parseInt(h[1],10),a=Number.parseInt(h[2],10);continue}if(!(u.startsWith("***")||u.startsWith("---")||u.startsWith("+++")||u.startsWith("*** End Patch"))){if(u.startsWith("-"))l===void 0&&(l=r),t.push(u.slice(1)),r+=1;else if(u.startsWith("+"))d===void 0&&(d=a),s.push(u.slice(1)),a+=1;else if(u.startsWith(" ")){let g=u.slice(1);t.push(g),s.push(g),r+=1,a+=1}}}return{oldString:t.join(`
|
|
17
17
|
`),newString:s.join(`
|
|
18
|
-
`),oldStartLine:o===1?l:void 0,newStartLine:o===1?d:void 0}}extractDiffLineAnchorsFromSnapshot(e){let t=(0,
|
|
19
|
-
`)){let r=o.match(/^\s*(\d+)\s+(.*)$/);if(!r)continue;let a=Number.parseInt(r[1],10),l=r[2];if(Number.isFinite(a)){if(l.startsWith("-")){s??=a;continue}if(l.startsWith("+")){i??=a;continue}s??=a,i??=a}}return n.debug("Recovered diff line anchors from tmux snapshot",{oldStartLine:s,newStartLine:i,snapshotPreview:this.summarizePromptSnapshot(e)}),{oldStartLine:s,newStartLine:i}}subscribeToMobileEvents(e){if(this.subscribedSessionId===e)return n.info("Already subscribed to mobile events, skipping",{sessionId:e}),!0;if(n.info("Subscribing to mobile events",{sessionId:e}),this.unsubscribe){try{this.unsubscribe()}catch(t){n.warn("Error cleaning up previous subscription (non-fatal)",{error:t})}this.subscribedSessionId=null}try{this.unsubscribe=this.appSyncClient.subscribeToEvents(e,async t=>{await this.handleMobileEvent(t)},t=>{n.error("Subscription error:",t)}),this.subscribedSessionId=e}catch(t){return n.error("Failed to subscribe to mobile events (non-fatal)",{sessionId:e,error:t}),!1}return this.sessionState&&(this.sessionState.subscriptionActive=!0),n.info("Subscribed to mobile events"),!0}async downloadAttachment(e,t,s){try{let i=e.isEncrypted??s??!1;n.info("Downloading attachment",{id:e.id,type:e.type,filename:e.filename,s3Key:e.s3Key,attachmentIsEncrypted:e.isEncrypted,eventIsEncrypted:s,shouldDecrypt:i});let{downloadUrl:o}=await this.appSyncClient.getAttachmentDownloadUrl(e.s3Key),r=await fetch(o);if(!r.ok)throw new Error(`Failed to download attachment: ${r.status} ${r.statusText}`);let a=Buffer.from(await r.arrayBuffer());if(i&&this.sessionKey)try{n.info("Decrypting attachment",{id:e.id}),a=c.cryptoService.decryptData(a,this.sessionKey),n.info("Attachment decrypted successfully",{id:e.id,decryptedSize:a.length})}catch(g){throw n.error("Failed to decrypt attachment:",{id:e.id,error:g}),new Error("Failed to decrypt attachment")}else i&&!this.sessionKey&&n.warn("Cannot decrypt attachment - no session key available",{id:e.id});let l=x.join(
|
|
20
|
-
`);s?s=`${
|
|
18
|
+
`),oldStartLine:o===1?l:void 0,newStartLine:o===1?d:void 0}}extractDiffLineAnchorsFromSnapshot(e){let t=(0,w.normalizeSnapshot)(e),s,i;for(let o of t.split(`
|
|
19
|
+
`)){let r=o.match(/^\s*(\d+)\s+(.*)$/);if(!r)continue;let a=Number.parseInt(r[1],10),l=r[2];if(Number.isFinite(a)){if(l.startsWith("-")){s??=a;continue}if(l.startsWith("+")){i??=a;continue}s??=a,i??=a}}return n.debug("Recovered diff line anchors from tmux snapshot",{oldStartLine:s,newStartLine:i,snapshotPreview:this.summarizePromptSnapshot(e)}),{oldStartLine:s,newStartLine:i}}subscribeToMobileEvents(e){if(this.subscribedSessionId===e)return n.info("Already subscribed to mobile events, skipping",{sessionId:e}),!0;if(n.info("Subscribing to mobile events",{sessionId:e}),this.unsubscribe){try{this.unsubscribe()}catch(t){n.warn("Error cleaning up previous subscription (non-fatal)",{error:t})}this.subscribedSessionId=null}try{this.unsubscribe=this.appSyncClient.subscribeToEvents(e,async t=>{await this.handleMobileEvent(t)},t=>{n.error("Subscription error:",t)}),this.subscribedSessionId=e}catch(t){return n.error("Failed to subscribe to mobile events (non-fatal)",{sessionId:e,error:t}),!1}return this.sessionState&&(this.sessionState.subscriptionActive=!0),n.info("Subscribed to mobile events"),!0}async downloadAttachment(e,t,s){try{let i=e.isEncrypted??s??!1;n.info("Downloading attachment",{id:e.id,type:e.type,filename:e.filename,s3Key:e.s3Key,attachmentIsEncrypted:e.isEncrypted,eventIsEncrypted:s,shouldDecrypt:i});let{downloadUrl:o}=await this.appSyncClient.getAttachmentDownloadUrl(e.s3Key),r=await fetch(o);if(!r.ok)throw new Error(`Failed to download attachment: ${r.status} ${r.statusText}`);let a=Buffer.from(await r.arrayBuffer());if(i&&this.sessionKey)try{n.info("Decrypting attachment",{id:e.id}),a=c.cryptoService.decryptData(a,this.sessionKey),n.info("Attachment decrypted successfully",{id:e.id,decryptedSize:a.length})}catch(g){throw n.error("Failed to decrypt attachment:",{id:e.id,error:g}),new Error("Failed to decrypt attachment")}else i&&!this.sessionKey&&n.warn("Cannot decrypt attachment - no session key available",{id:e.id});let l=x.join(ye.tmpdir(),"codevibe-codex",t);I.existsSync(l)||I.mkdirSync(l,{recursive:!0});let d="";if(e.filename){let g=x.extname(e.filename);g&&(d=g)}d||(d={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"}[e.type]||".bin");let u=`attachment-${e.id}${d}`,h=x.join(l,u);return I.writeFileSync(h,a),n.info("Attachment saved to temp file",{id:e.id,filePath:h,size:a.length}),h}catch(i){return n.error("Failed to download attachment:",{id:e.id,error:i}),null}}async handleMobileEvent(e){if(e.attachments&&e.attachments.length>0&&n.info("DEBUG: Raw attachment data from subscription",{attachments:JSON.stringify(e.attachments),eventIsEncrypted:e.isEncrypted}),n.info("Received mobile event",{eventId:e.eventId,type:e.type,content:e.content?.substring(0,50),attachmentCount:e.attachments?.length||0,isEncrypted:e.isEncrypted}),!this.sessionState){n.warn("Received mobile event but no active session");return}let t=e.content||"";if(e.isEncrypted&&this.sessionKey)try{t=c.cryptoService.decryptContent(e.content,this.sessionKey),n.debug("Event decrypted successfully",{eventId:e.eventId})}catch(s){n.error("Failed to decrypt event:",{eventId:e.eventId,error:s}),t=e.content}try{await this.appSyncClient.updateEventStatus({eventId:e.eventId,sessionId:e.sessionId,timestamp:e.timestamp,deliveryStatus:c.DeliveryStatus.DELIVERED})}catch(s){n.error("Failed to update delivery status:",s)}if(e.type===c.EventType.USER_PROMPT||e.type===c.EventType.PROMPT_RESPONSE){let s=t,i=e.attachments||[],o=[];if(i.length>0){n.info("Downloading attachments for prompt",{count:i.length});for(let d of i){let u=await this.downloadAttachment(d,this.sessionState.sessionId,e.isEncrypted);u&&o.push(u)}if(o.length>0){let d=o.map(u=>`[Attached file: ${u}]`).join(`
|
|
20
|
+
`);s?s=`${d}
|
|
21
21
|
|
|
22
|
-
${s}`:s=`${
|
|
22
|
+
${s}`:s=`${d}
|
|
23
23
|
|
|
24
|
-
Please analyze the attached file(s).`,n.info("Prompt updated with attachment paths",{attachmentCount:o.length,newPromptLength:s.length})}}let r=this.translatePromptResponse(s),a=await this.promptResponder.sendInput(
|
|
24
|
+
Please analyze the attached file(s).`,n.info("Prompt updated with attachment paths",{attachmentCount:o.length,newPromptLength:s.length})}}let r=this.translatePromptResponse(s),a=this.sessionState.sessionId;this.trackMobilePrompt(a,r.primaryInput);let l=await this.promptResponder.sendInput(a,r.primaryInput);if(l||this.forgetMobilePrompt(a,r.primaryInput),l&&r.followUpInput&&(this.trackMobilePrompt(a,r.followUpInput),await this.promptResponder.sendInput(a,r.followUpInput)||this.forgetMobilePrompt(a,r.followUpInput)),l&&this.pendingInteractivePrompt&&e.type===c.EventType.PROMPT_RESPONSE&&(this.pendingInteractivePrompt=null),l)try{await this.appSyncClient.updateEventStatus({eventId:e.eventId,sessionId:e.sessionId,timestamp:e.timestamp,deliveryStatus:c.DeliveryStatus.EXECUTED})}catch(d){n.error("Failed to update executed status:",d)}}}generateSessionId(e){return`codex-${e}`}startMobileEndWatcher(e){!this.sessionState||this.sessionState.sessionId!==e||(this.sessionState.mobileEndWatcher=this.appSyncClient.watchForMobileEnd(e,async()=>{n.info("Mobile ended session \u2014 sending desktop quit",{sessionId:e});let t=process.env[fe];if(!t){n.warn("No tmux session set; skipping desktop self-terminate",{sessionId:e,expectedEnv:fe});return}await We(t,$e)}))}async endActiveSession(e){if(this.sessionState){n.info("Ending active session",{sessionId:this.sessionState.sessionId,codexSessionId:this.sessionState.codexSessionId,reason:e}),this.sessionState.mobileEndWatcher&&(this.sessionState.mobileEndWatcher.stop(),this.sessionState.mobileEndWatcher=void 0),this.appSyncClient.stopHeartbeat(this.sessionState.sessionId),this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),await this.tmuxPaneObserver.stop(),this.pendingInteractivePrompt=null,this.isInitializingSession=!1,this.bufferedLogEntries=[],this.sessionKey&&(c.keychainManager.clearSessionKey(this.sessionState.sessionId),this.sessionKey=null);try{await this.appSyncClient.updateSession({sessionId:this.sessionState.sessionId,status:c.SessionStatus.INACTIVE})}catch(t){n.error("Failed to update session status:",t)}this.sessionState=null}}async stop(){n.info("Stopping CodeVibe Codex companion server"),await this.endActiveSession("shutdown"),this.sessionWatcher.stop(),this.approvalDetector.shutdown(),Q(),await this.httpApi.stop(),this.appSyncClient.cleanupSubscriptions(),n.info("CodeVibe Codex companion server stopped")}},B=new K;process.on("SIGINT",async()=>{n.info("Received SIGINT, shutting down..."),await B.stop(),process.exit(0)});process.on("SIGTERM",async()=>{n.info("Received SIGTERM, shutting down..."),await B.stop(),process.exit(0)});B.start().catch(p=>{n.error("Failed to start server:",p),process.exit(1)});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quantiya/codevibe-codex-plugin",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.34",
|
|
4
4
|
"description": "Control OpenAI Codex CLI from your iPhone and Android — real-time sync, approve file edits, send prompts by voice. Part of CodeVibe.",
|
|
5
5
|
"main": "dist/server.js",
|
|
6
6
|
"bin": {
|