@quantiya/codevibe-codex-plugin 1.0.25 → 1.0.27
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 +17 -17
- package/package.json +2 -2
package/dist/server.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
${
|
|
3
|
-
`))if(!(s.test(i)||i.startsWith("***")||i.startsWith("---")||i.startsWith("+++"))){if(i.startsWith("-"))
|
|
4
|
-
`),newString:
|
|
5
|
-
`)}}function lt(a){if(!a)return null;let t=a.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);return t?{filePath:t[1].trim()}:null}function At(a,t){return a?a.length<=t?a:a.substring(0,t)+"...":""}function j(){_.clear()}function Nt(){return _.size}function Mt(a){return _.get(a)}var W,S,_,z=Z(()=>{"use strict";W=require("uuid"),S=require("@quantiya/codevibe-core");E();_=new Map});var J=require("uuid"),x=f(require("fs")),F=f(require("path")),wt=f(require("os")),c=require("@quantiya/codevibe-core");E();var nt=require("events"),y=f(require("fs")),A=f(require("path")),rt=f(require("readline")),ot=require("chokidar"),at=require("@quantiya/codevibe-core");E();var R=class extends nt.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}start(){if(this.isWatching){n.warn("Session log watcher already running");return}let e=(0,at.getConfig)().codex.sessionsDir;this.sessionsDir=e,n.info("Starting Codex session log watcher",{sessionsDir:e}),y.existsSync(e)||(n.info("Codex sessions directory does not exist yet, creating...",{sessionsDir:e}),y.mkdirSync(e,{recursive:!0})),this.startTime=Date.now(),this.watcher=(0,ot.watch)(e,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},depth:4,ignored:s=>{let i=A.basename(s);return y.existsSync(s)&&y.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.filePositions.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(e){try{let s=y.statSync(e),i=s.birthtimeMs||s.ctimeMs;if(i<this.startTime-5e3){n.debug("Ignoring old session file",{filePath:e,fileCreatedAt:new Date(i).toISOString(),startTime:new Date(this.startTime).toISOString()});return}}catch(s){n.warn("Could not check file creation time",{filePath:e,error:s})}if(this.activeLogFile){n.debug("Ignoring additional Codex session log for this server instance",{activeLogFile:this.activeLogFile,ignoredFile:e});return}n.info("New Codex session log detected",{filePath:e}),this.activeLogFile=e,this.filePositions.set(e,0),this.readNewLines(e)}onFileChanged(e){if(this.activeLogFile&&e!==this.activeLogFile){n.debug("Ignoring change for non-active session log",{activeLogFile:this.activeLogFile,ignoredFile:e});return}if(!this.activeLogFile){try{let s=y.statSync(e),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:e,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:e,error:s})}this.activeLogFile=e,this.filePositions.set(e,0)}this.readNewLines(e)}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.readNewLines(s.filePath)}catch(e){n.warn("Failed to backfill recent session file",{error:e})}}collectRecentSessionFiles(e){let s=[],i=[e];for(;i.length>0;){let o=i.pop();if(!o)continue;let r;try{r=y.readdirSync(o,{withFileTypes:!0})}catch{continue}for(let l of r){let p=A.join(o,l.name);if(l.isDirectory()){i.push(p);continue}if(!(!l.isFile()||!l.name.startsWith("rollout-")||!l.name.endsWith(".jsonl")))try{let d=y.statSync(p),u=d.birthtimeMs||d.ctimeMs,h=d.mtimeMs;(u>=this.startTime||h>=this.startTime-5e3)&&s.push({filePath:p,createdAt:u,modifiedAt:h})}catch{}}}return s}async readNewLines(e){let s=this.filePositions.get(e)||0;try{if(y.statSync(e).size<=s)return;let o=y.createReadStream(e,{start:s,encoding:"utf-8"}),r=rt.createInterface({input:o,crlfDelay:1/0}),l=s;for await(let p of r)if(l+=Buffer.byteLength(p,"utf-8")+1,!!p.trim())try{let d=JSON.parse(p);this.processLogEntry(d)}catch(d){n.warn("Failed to parse log line",{filePath:e,line:p.substring(0,100),error:d})}this.filePositions.set(e,l)}catch(i){n.error("Error reading log file",{filePath:e,error:i}),this.emit("error",i)}}processLogEntry(e){if(n.debug("Processing log entry",{type:e.type}),e.type==="session_meta"){let s=e.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",e),e.type==="event_msg"&&e.payload?.type?this.emit(`event:${e.payload.type}`,e):e.type==="response_item"&&e.payload?.type&&this.emit(`response:${e.payload.type}`,e)}};z();var dt=require("events"),ut=require("@quantiya/codevibe-core");E();var N=class extends dt.EventEmitter{constructor(){super();this.pendingCalls=new Map;this.timers=new Map;this.timeoutMs=(0,ut.getConfig)().codex.approvalTimeoutMs,n.info("Approval detector initialized",{timeoutMs:this.timeoutMs})}onToolCallStart(e,s,i){n.debug("Tool call started",{callId:e,name:s});let o=this.parseInput(i),r=this.extractFilePath(s,i,o),l=this.extractDiff(s,i,o),p={callId:e,name:s,input:i,filePath:r,diff:l,parsedInput:o,timestamp:Date.now(),notificationSent:!1};this.pendingCalls.set(e,p);let d=setTimeout(()=>{this.checkPendingCall(e)},this.timeoutMs);this.timers.set(e,d)}onToolCallComplete(e){n.debug("Tool call completed",{callId:e}),this.pendingCalls.delete(e);let s=this.timers.get(e);s&&(clearTimeout(s),this.timers.delete(e))}checkPendingCall(e){let s=this.pendingCalls.get(e);if(!s||s.notificationSent)return;let i=Date.now()-s.timestamp;n.info("Tool call still pending after timeout",{callId:e,name:s.name,elapsedMs:i}),s.notificationSent=!0,this.pendingCalls.set(e,s),this.emit("approval-pending",{callId:e,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(e,s,i){if(i)return`File: ${i}`;if(e==="apply_patch"&&s){let o=s.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(o)return`File: ${o[1].trim()}`}if(e==="shell_command"||e==="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(e)}`}mapToolName(e){return{shell_command:"Bash",shell:"Bash",apply_patch:"File Edit",write_file:"Write File",read_file:"Read File"}[e]||e}parseInput(e){if(e)try{return JSON.parse(e)}catch{return}}extractFilePath(e,s,i){if(e==="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(e,s,i){if(e==="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 e of this.timers.values())clearTimeout(e);this.timers.clear(),this.pendingCalls.clear(),n.debug("Approval detector cleared")}shutdown(){this.clear(),this.removeAllListeners(),n.info("Approval detector shutdown")}};var mt=require("child_process"),ft=require("util");E();var ht=(0,ft.promisify)(mt.exec),M=class{async sendInput(t,e){n.info("Attempting to send input to Codex",{sessionId:t,input:e});try{let s=process.env.CODEVIBE_CODEX_TMUX_SESSION;return s?(n.info("Using tmux send-keys",{tmuxSession:s}),await this.sendViaTmux(s,e),n.info("Successfully sent input to Codex",{sessionId:t,input:e}),!0):(n.error("No tmux session found - codevibe-codex wrapper is required",{sessionId:t,hint:"Start Codex CLI using the codevibe-codex wrapper script"}),!1)}catch(s){return n.error("Failed to send input to Codex",{sessionId:t,error:s instanceof Error?s.message:String(s)}),!1}}async sendViaTmux(t,e){let s=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");n.info("Sending via tmux",{sessionName:t,inputLength:e.length});try{let i=`tmux send-keys -t "${t}" -l "${s}"`;await ht(i),await this.delay(500);let o=`tmux send-keys -t "${t}" Enter`;await ht(o),n.info("tmux send-keys completed")}catch(i){throw n.error("tmux send-keys failed",{sessionName:t,error:i}),i}}delay(t){return new Promise(e=>setTimeout(e,t))}isApprovalResponse(t){let e=t.trim().toLowerCase();return["y","n","a","q","e","yes","no"].includes(e)||/^[0-9]+$/.test(e)}};var g=f(require("fs")),gt=f(require("os")),L=f(require("path")),yt=require("crypto"),vt=require("child_process"),St=require("events"),_t=require("util");E();var V=(0,_t.promisify)(vt.exec),k=class extends St.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(e){if(this.started&&this.sessionName===e){n.debug("Tmux pane observer already started",{sessionName:e});return}this.started&&await this.stop(),this.sessionName=e,this.started=!0,this.filePosition=0,this.lastPromptHash=null,this.pipeFilePath=L.join(gt.tmpdir(),`codevibe-codex-pane-${process.pid}.log`),g.mkdirSync(L.dirname(this.pipeFilePath),{recursive:!0}),g.writeFileSync(this.pipeFilePath,""),await this.enablePipePane(),this.startFileWatcher(),n.info("Tmux pane observer started",{sessionName:e})}async stop(){if(this.started){try{await this.disablePipePane()}catch(e){n.debug("Failed to disable tmux pipe-pane cleanly",{error:e})}if(this.watcher&&(this.watcher.close(),this.watcher=null),this.pipeFilePath)try{g.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(e=120){if(!this.sessionName)throw new Error("Tmux pane observer is not started");let s=Math.max(1,Math.floor(e)),i=this.escapeShellArg(this.sessionName),o=`tmux capture-pane -p -e -S -${s} -t '${i}'`;try{let{stdout:r}=await V(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(e){return e.replace(/'/g,"'\\''")}async enablePipePane(){if(!this.sessionName||!this.pipeFilePath)throw new Error("Tmux pane observer is not initialized");let e=this.escapeShellArg(this.sessionName),s=this.escapeShellArg(this.pipeFilePath),i=`tmux pipe-pane -O -t '${e}' "cat >> '${s}'"`;await V(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 V(s)}startFileWatcher(){this.pipeFilePath&&(this.watcher=g.watch(this.pipeFilePath,e=>{e==="change"&&this.processFileChanges()}))}async processFileChanges(){if(this.pipeFilePath){if(this.processing){this.pendingRead=!0;return}this.processing=!0;try{do{this.pendingRead=!1;let e=this.readAppendedChunk();if(!e||!this.looksLikePromptDelta(e))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:e,snapshot:s,detectedAt:Date.now()}))}while(this.pendingRead)}catch(e){n.error("Failed to process tmux pane changes",{error:e}),this.emit("observer-error",e)}finally{this.processing=!1}}}readAppendedChunk(){if(!this.pipeFilePath)return"";let e=g.statSync(this.pipeFilePath);if(e.size<=this.filePosition)return"";let s=g.openSync(this.pipeFilePath,"r");try{let i=e.size-this.filePosition,o=Buffer.alloc(i);return g.readSync(s,o,0,i,this.filePosition),this.filePosition=e.size,o.toString("utf-8")}finally{g.closeSync(s)}}looksLikePromptDelta(e){return/\[(?:y\/n|Y\/n|y\/N)\]|\b(?:apply|approve|allow|reject|deny|continue)\b/i.test(e)}looksLikePromptSnapshot(e){let s=e.split(`
|
|
1
|
+
"use strict";var Fe=Object.create;var F=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var Me=Object.getPrototypeOf,Ne=Object.prototype.hasOwnProperty;var Z=(p,e)=>()=>(p&&(e=p(p=0)),e);var ke=(p,e)=>{for(var t in e)F(p,t,{get:e[t],enumerable:!0})},ee=(p,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ae(e))!Ne.call(p,i)&&i!==t&&F(p,i,{get:()=>e[i],enumerable:!(s=Re(e,i))||s.enumerable});return p};var g=(p,e,t)=>(t=p!=null?Fe(Me(p)):{},ee(e||!p||!p.__esModule?F(t,"default",{value:p,enumerable:!0}):t,p)),Le=p=>ee(F({},"__esModule",{value:!0}),p);var te,se,ie,n,E=Z(()=>{"use strict";te=g(require("os")),se=g(require("path")),ie=require("@quantiya/codevibe-core"),n=(0,ie.createLogger)({name:"codevibe-codex",logFile:se.default.join(te.default.tmpdir(),"codevibe-codex-mcp.log"),level:"debug"})});var ce={};ke(ce,{clearPendingCalls:()=>j,extractFileFromPatch:()=>le,extractOldNewFromPatch:()=>pe,getPendingCall:()=>We,getPendingCallsCount:()=>$e,mapLogEntryToEvent:()=>B});function B(p,e){let t={sessionId:e,source:S.EventSource.DESKTOP};if(p.type==="event_msg"&&p.payload){let s=p.payload.type;switch(s){case"user_message":return{...t,type:S.EventType.USER_PROMPT,content:p.payload.message||"",metadata:{images:p.payload.images||[]}};case"agent_message":return{...t,type:S.EventType.ASSISTANT_RESPONSE,content:p.payload.message||""};case"agent_reasoning":return{...t,type:S.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,H.v4)();_.set(r,{name:i,input:o,eventId:l});let d=K(i),u=De(i,a);return{...t,type:S.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=_.get(i);_.delete(i);let a=r?.name?K(r.name):"Tool",l=Ue(o,500);return{...t,type:S.EventType.TOOL_USE,content:`${a} completed:
|
|
2
|
+
${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;_.set(o,{name:i,input:r,eventId:(0,H.v4)()});let l=le(r),{oldString:d,newString:u}=pe(r),h=l?`Editing: ${l.filePath}`:"Applying patch";return{...t,type:S.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=_.get(i);_.delete(i);let a={};try{a=JSON.parse(o||"{}")}catch{a={raw:o}}let l=a.output?.includes("Success")||!a.error;return{...t,type:S.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 K(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 De(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 ${K(p)}`}}function pe(p){let e=[],t=[],s=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;for(let i of p.split(`
|
|
3
|
+
`))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(`
|
|
4
|
+
`),newString:t.join(`
|
|
5
|
+
`)}}function le(p){if(!p)return null;let e=p.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);return e?{filePath:e[1].trim()}:null}function Ue(p,e){return p?p.length<=e?p:p.substring(0,e)+"...":""}function j(){_.clear()}function $e(){return _.size}function We(p){return _.get(p)}var H,S,_,V=Z(()=>{"use strict";H=require("uuid"),S=require("@quantiya/codevibe-core");E();_=new Map});var J=require("uuid"),x=g(require("fs")),O=g(require("path")),xe=g(require("os")),Ce=require("util"),Oe=require("child_process"),c=require("@quantiya/codevibe-core");E();var ne=require("events"),v=g(require("fs")),A=g(require("path")),re=g(require("readline")),oe=require("chokidar"),ae=require("@quantiya/codevibe-core");E();var R=class extends ne.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}start(){if(this.isWatching){n.warn("Session log watcher already running");return}let t=(0,ae.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.watcher=(0,oe.watch)(t,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},depth:4,ignored:s=>{let i=A.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.filePositions.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.readNewLines(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.readNewLines(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.readNewLines(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=A.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}async readNewLines(t){let s=this.filePositions.get(t)||0;try{if(v.statSync(t).size<=s)return;let o=v.createReadStream(t,{start:s,encoding:"utf-8"}),r=re.createInterface({input:o,crlfDelay:1/0}),a=s;for await(let l of r)if(a+=Buffer.byteLength(l,"utf-8")+1,!!l.trim())try{let d=JSON.parse(l);this.processLogEntry(d)}catch(d){n.warn("Failed to parse log line",{filePath:t,line:l.substring(0,100),error:d})}this.filePositions.set(t,a)}catch(i){n.error("Error reading log file",{filePath:t,error:i}),this.emit("error",i)}}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)}};V();var de=require("events"),ue=require("@quantiya/codevibe-core");E();var M=class extends de.EventEmitter{constructor(){super();this.pendingCalls=new Map;this.timers=new Map;this.timeoutMs=(0,ue.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};this.pendingCalls.set(t,l);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}}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 me=require("child_process"),fe=require("util");E();var he=(0,fe.promisify)(me.exec),N=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 he(i),await this.delay(500);let o=`tmux send-keys -t "${e}" Enter`;await he(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=g(require("fs")),ge=g(require("os")),L=g(require("path")),ye=require("crypto"),ve=require("child_process"),Se=require("events"),_e=require("util");E();var z=(0,_e.promisify)(ve.exec),k=class extends Se.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=L.join(ge.tmpdir(),`codevibe-codex-pane-${process.pid}.log`),y.mkdirSync(L.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 z(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 z(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 z(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(`
|
|
6
6
|
`).slice(-20).join(`
|
|
7
|
-
`);return/\[(?:y\/n|Y\/n|y\/N)\]|^\s*\d+\.\s+/im.test(s)}hashPromptSnapshot(
|
|
7
|
+
`);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,`
|
|
8
8
|
`).replace(/[ \t]+\n/g,`
|
|
9
|
-
`).trim();return(0,yt.createHash)("sha256").update(s).digest("hex")}};var I=require("@quantiya/codevibe-core");var q=f(require("express")),T=f(require("fs")),X=f(require("path")),G=f(require("os"));E();var D=class{constructor(){this.assignedPort=0;this.app=(0,q.default)(),this.setupMiddleware(),this.setupRoutes(),this.tmuxSession=process.env.CODEVIBE_CODEX_TMUX_SESSION}getPort(){return this.assignedPort}setupMiddleware(){this.app.use(q.default.json({limit:"1mb"})),this.app.use((t,e,s)=>{n.debug(`${t.method} ${t.path}`,{body:t.body}),s()})}setupRoutes(){this.app.get("/health",(t,e)=>{e.json({success:!0,data:{status:"healthy",uptime:process.uptime()}})}),this.app.post("/event",this.handleEvent.bind(this))}async handleEvent(t,e){try{let s=t.body;if(!s.session_id||!s.hook_event_name){e.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),e.json({success:!0})}catch(s){n.error("Error handling event:",s),e.status(500).json({success:!1,error:s instanceof Error?s.message:"Unknown error"})}}transformHookToEvent(t){let e={cwd:t.cwd,hook_event_name:t.hook_event_name,...t.metadata||{}},s,i;switch(t.hook_event_name){case"SessionStart":s="NOTIFICATION",i="Session started",e.source=t.source;break;case"UserPromptSubmit":s="USER_PROMPT",i=t.prompt||"";break;case"PreToolUse":s="INTERACTIVE_PROMPT",i=`${t.tool_name||"Tool"} requires approval`,e.tool_name=t.tool_name,e.tool_input=t.tool_input,e.tool_use_id=t.tool_use_id;break;case"PostToolUse":s="TOOL_USE",i=JSON.stringify({tool_name:t.tool_name,tool_input:t.tool_input,tool_response:t.tool_response}),e.tool_name=t.tool_name;break;case"Stop":s="ASSISTANT_RESPONSE",i=t.last_assistant_message||"";break;default:s="NOTIFICATION",i=`Hook: ${t.hook_event_name}`}return{session_id:t.session_id,hook_event_name:t.hook_event_name,type:s,source:"DESKTOP",content:i,metadata:e}}onEvent(t){this.eventHandler=t}async start(){return new Promise((t,e)=>{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),t(this.assignedPort)}),this.server.on("error",s=>{n.error("HTTP server error:",s),e(s)})}catch(s){e(s)}})}writePortFile(t){if(!this.tmuxSession){n.warn("No CODEVIBE_CODEX_TMUX_SESSION set, skipping port file");return}let e=X.join(G.tmpdir(),`codevibe-codex-${this.tmuxSession}.port`);try{T.writeFileSync(e,t.toString()),n.info(`Port file written: ${e} -> ${t}`)}catch(s){n.error(`Failed to write port file: ${e}`,s)}}removePortFile(){if(!this.tmuxSession)return;let t=X.join(G.tmpdir(),`codevibe-codex-${this.tmuxSession}.port`);try{T.existsSync(t)&&(T.unlinkSync(t),n.info(`Port file removed: ${t}`))}catch(e){n.warn(`Failed to remove port file: ${t}`,e)}}async stop(){return this.removePortFile(),new Promise(t=>{this.server?this.server.close(()=>{n.info("HTTP API stopped"),t()}):t()})}};var bt=f(require("crypto")),Pt=f(require("https")),U=f(require("os")),kt="G-GS74YEQTB8",Lt="lAfOF6OxRzSQ-NsLBRjhAg",Dt="www.google-analytics.com",Ut=`/mp/collect?measurement_id=${kt}&api_secret=${Lt}`;function $t(){let a=typeof process.getuid=="function"?process.getuid():0;return bt.createHash("sha256").update(`${U.hostname()}-${a}`).digest("hex").substring(0,36)}function Ht(a){if(!a)return"";let t=U.homedir(),e=a.replace(/[\n\r\t]/g," ");if(t&&t.length>0){let s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");e=e.replace(new RegExp(s,"g"),"~")}return e=e.replace(/\/Users\/[^/\s"'`]+/g,"/Users/<user>").replace(/\/home\/[^/\s"'`]+/g,"/home/<user>").replace(/[^\x20-\x7E]/g,""),e.trim().substring(0,100)}function v(a,t){try{let e={...t};typeof e.error_message=="string"&&(e.error_message=Ht(e.error_message));let s=JSON.stringify({client_id:$t(),events:[{name:a,params:{agent:"codex",platform:process.platform,source:process.env.CODEVIBE_TELEMETRY_SOURCE||"production",...e}}]}),i=Pt.request({hostname:Dt,path:Ut,method:"POST",headers:{"Content-Type":"application/json"},timeout:2e3},o=>{o.resume()});i.on("error",()=>{}),i.on("timeout",()=>{try{i.destroy()}catch{}}),i.write(s),i.end()}catch{}}var Y=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.httpApi=new D,this.sessionWatcher=new R,this.approvalDetector=new N,this.promptResponder=new M,this.tmuxPaneObserver=new k}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 e=await this.httpApi.start();n.info("HTTP API started for hooks",{port:e}),await this.createLaunchSession(),this.setupEventHandlers(),this.sessionWatcher.start(),n.info("CodeVibe Codex companion server started")}async createLaunchSession(){let t=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!t){n.warn("No CODEVIBE_CODEX_TMUX_SESSION \u2014 skipping launch session");return}let e=process.env.CODEX_WORKING_DIRECTORY||process.cwd(),s=this.generateSessionId(t),i=this.appSyncClient.getCurrentUserId();n.info("Creating launch session",{sessionId:s,projectPath:e});try{let o=await(0,c.resumeOrCreateSession)({sessionId:s,userId:i,agentType:c.AgentType.CODEX,projectPath:e,metadata:{launchSession:!0}},this.appSyncClient,n);this.sessionKey=o.sessionKey,this.sessionState={sessionId:s,userId:i,projectPath:e,cwd:e,createdAt:new Date,subscriptionActive:!1,metadata:{launchSession:!0},codexSessionId:t,codexLogFile:void 0},this.subscribeToMobileEvents(s),this.appSyncClient.startHeartbeat(s),n.info("Launch session created",{sessionId:s})}catch(o){n.error("Failed to create launch session (non-fatal)",{error:o})}}async handleEventFromHook(t){let{session_id:e,hook_event_name:s,type:i,content:o,metadata:r}=t;if(this.hooksActive=!0,n.info("[Hooks] Received event",{sessionId:e,hookEvent:s,type:i,contentLength:o?.length}),s==="SessionStart"){if(this.sessionState)n.info("[Hooks] SessionStart \u2014 launch session already exists, updating codexSessionId",{existingSessionId:this.sessionState.sessionId,codexSessionId:e}),this.sessionState.codexSessionId=e,this.sessionState.metadata={...this.sessionState.metadata,codexSessionId:e,cliVersion:r?.model||"unknown",modelProvider:r?.model||"unknown",launchSession:void 0},this.appSyncClient.updateSession({sessionId:this.sessionState.sessionId,metadata:this.sessionState.metadata}).catch(p=>n.warn("Failed to update session metadata",{error:p}));else{let p={id:e,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.handleSessionStarted(p)}return}if(!this.sessionState){n.warn("[Hooks] Session not initialized, buffering event",{hook_event_name:s});return}let l=this.sessionState.sessionId;if(i==="USER_PROMPT"&&o&&this.isRecentMobilePrompt(o)){n.info("[Hooks] Skipping duplicate USER_PROMPT from mobile");return}if(s==="PreToolUse"){let p=r?.tool_name||"unknown",d=r?.tool_input,u={tool_name:this.mapToolName(p),tool_input:d||{}};if(p==="apply_patch"&&typeof d=="string"){let{extractOldNewFromPatch:C,extractFileFromPatch:$}=(z(),Ot(ct)),w=C(d),H=$(d);w&&(u.tool_input={file_path:H||"",old_string:w.oldString,new_string:w.newString})}let h=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(h)try{await new Promise(H=>setTimeout(H,500));let{execSync:C}=require("child_process"),$=C(`tmux capture-pane -p -e -S -30 -t '${h}'`,{timeout:5e3,encoding:"utf8"}),w=(0,I.parseInteractivePrompt)($);w&&w.options.length>0&&(u.options=w.options,u.submitMap=w.submitMap)}catch{n.debug("[Hooks] Tmux capture failed, using default options")}let m=o,b=u,P=!1;this.sessionKey&&(m=c.cryptoService.encryptContent(o,this.sessionKey),b={encrypted:c.cryptoService.encryptMetadata(u,this.sessionKey)},P=!0),await this.appSyncClient.createEvent({sessionId:l,type:c.EventType.INTERACTIVE_PROMPT,source:c.EventSource.DESKTOP,content:m,metadata:b,isEncrypted:P}),this.pendingInteractivePrompt={promptId:(0,J.v4)(),kind:"yes_no",options:u.options||[],submitMap:u.submitMap||{},promptText:o,createdAt:Date.now(),source:"tmux",requiresFollowUpText:!1},n.info("[Hooks] INTERACTIVE_PROMPT sent",{toolName:p,sessionId:l});return}if(s==="PostToolUse"){let p=o,d=r,u=!1;this.sessionKey&&(p=c.cryptoService.encryptContent(o,this.sessionKey),r&&(d={encrypted:c.cryptoService.encryptMetadata(r,this.sessionKey)}),u=!0),await this.appSyncClient.createEvent({sessionId:l,type:c.EventType.TOOL_USE,source:c.EventSource.DESKTOP,content:p,metadata:d,isEncrypted:u});return}if(i==="ASSISTANT_RESPONSE"||i==="USER_PROMPT"){let p=o,d=!1;this.sessionKey&&o&&(p=c.cryptoService.encryptContent(o,this.sessionKey),d=!0),await this.appSyncClient.createEvent({sessionId:l,type:i==="ASSISTANT_RESPONSE"?c.EventType.ASSISTANT_RESPONSE:c.EventType.USER_PROMPT,source:c.EventSource.DESKTOP,content:p,isEncrypted:d});return}}mapToolName(t){return{shell_command:"Bash",shell:"Bash",apply_patch:"Edit",create_file:"Write",read_file:"Read"}[t]||t}isRecentMobilePrompt(t){return!1}setupEventHandlers(){this.sessionWatcher.on("session-started",async t=>{if(this.sessionState){n.info("[JSONL] Session already active, skipping",{currentSessionId:this.sessionState.sessionId,codexSessionId:t.id});return}await this.handleSessionStarted(t)}),this.sessionWatcher.on("log-entry",async t=>{await this.handleLogEntry(t)}),this.approvalDetector.on("approval-pending",async t=>{await this.handleApprovalPending(t)}),this.tmuxPaneObserver.on("prompt-candidate",async t=>{await this.handleTmuxPromptCandidate(t.snapshot)}),this.tmuxPaneObserver.on("observer-error",t=>{n.debug("Tmux pane observer error",{error:t})}),this.sessionWatcher.on("error",t=>{n.error("Session watcher error:",t)})}async handleSessionStarted(t){n.info("Handling new Codex session",{codexSessionId:t.id}),this.isInitializingSession=!0,this.bufferedLogEntries=[],this.sessionState&&await this.endActiveSession("new-codex-session-started");let e=process.env.CODEX_WORKING_DIRECTORY||t.cwd||process.cwd(),s=this.generateSessionId(t.id),i=this.appSyncClient.getCurrentUserId(),o={codexSessionId:t.id,cliVersion:t.cli_version,modelProvider:t.model_provider};try{let r=await(0,c.resumeOrCreateSession)({sessionId:s,userId:i,agentType:c.AgentType.CODEX,projectPath:e,metadata:o},this.appSyncClient,n);this.sessionKey=r.sessionKey,v("daemon_init_step_completed",{step:"session_resume_or_create"})}catch(r){throw this.isInitializingSession=!1,v("daemon_init_step_failed",{step:"session_resume_or_create",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:e,cwd:t.cwd,createdAt:new Date,subscriptionActive:!1,metadata:o,codexSessionId:t.id,codexLogFile:this.sessionWatcher.getActiveLogFile()||void 0},v("daemon_init_step_completed",{step:"session_state_set"})}catch(r){v("daemon_init_step_failed",{step:"session_state_set",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to set session state:",r)}try{this.subscribeToMobileEvents(s),v("daemon_init_step_completed",{step:"subscribe_mobile_events"})}catch(r){v("daemon_init_step_failed",{step:"subscribe_mobile_events",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),v("daemon_init_step_completed",{step:"heartbeat_start"})}catch(r){v("daemon_init_step_failed",{step:"heartbeat_start",error_class:r?.name||"Error",error_message:r?.message||String(r)}),n.error("Failed to start heartbeat:",r)}try{await this.flushBufferedLogEntries(),v("daemon_init_step_completed",{step:"flush_buffered_entries"})}catch(r){v("daemon_init_step_failed",{step:"flush_buffered_entries",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(),v("daemon_init_step_completed",{step:"tmux_observer_start"})}catch(r){v("daemon_init_step_failed",{step:"tmux_observer_start",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 t=this.bufferedLogEntries;this.bufferedLogEntries=[],n.info("Flushing buffered log entries after session initialization",{count:t.length,sessionId:this.sessionState?.sessionId});for(let e of t)await this.handleLogEntry(e)}async handleLogEntry(t){if(!this.sessionState){if(this.isInitializingSession){this.bufferedLogEntries.push(t),n.debug("Buffering log entry until session initialization completes",{type:t.type,bufferedCount:this.bufferedLogEntries.length});return}n.warn("Received log entry but no active session");return}if(t.type==="response_item"&&t.payload){let s=t.payload.type;s==="function_call"||s==="custom_tool_call"?this.approvalDetector.onToolCallStart(t.payload.call_id,t.payload.name,t.payload.arguments||t.payload.input||""):(s==="function_call_output"||s==="custom_tool_call_output")&&(this.approvalDetector.onToolCallComplete(t.payload.call_id),this.pendingInteractivePrompt?.callId===t.payload.call_id&&(this.pendingInteractivePrompt=null))}let e=B(t,this.sessionState.sessionId);if(e){if(this.hooksActive){if(e.type===c.EventType.USER_PROMPT||e.type===c.EventType.ASSISTANT_RESPONSE){n.debug("[JSONL] Skipping \u2014 hooks deliver this event type",{type:e.type});return}let s=t.payload?.type;if((s==="function_call"||s==="function_call_output")&&(e.type===c.EventType.TOOL_USE||e.type===c.EventType.INTERACTIVE_PROMPT)){n.debug("[JSONL] Skipping function_call \u2014 hooks deliver this",{type:e.type,tool:t.payload?.name});return}}try{if(this.sessionKey){if(e.content=c.cryptoService.encryptContent(e.content,this.sessionKey),e.metadata){let s=c.cryptoService.encryptMetadata(e.metadata,this.sessionKey);e.metadata={encrypted:s}}e.isEncrypted=!0,n.debug("Event encrypted",{type:e.type})}await this.appSyncClient.createEvent(e),n.debug("Event synced to backend",{type:e.type,encrypted:!!this.sessionKey})}catch(s){n.error("Failed to sync event:",s)}}}async handleApprovalPending(t){if(this.sessionState){n.info("Sending approval pending interactive prompt",t);try{let e=await this.tryParseInteractivePromptFromTmux(),s=e?.parsedPrompt??null;if(s&&this.pendingInteractivePrompt&&this.pendingInteractivePrompt.source==="tmux"&&this.pendingInteractivePrompt.promptText===s.promptText){n.debug("Skipping heuristic prompt because tmux prompt is already active",{promptText:s.promptText});return}let i=this.buildToolDetailsForInteractivePrompt(t,e?.snapshot),o=i.tool_name||this.mapToolNameForApproval(t.toolName),r=i.tool_input||this.buildFallbackToolInput(t),l=!!(o&&r),p=this.buildPromptPresentation(s),d=p.options,u=t.filePath?`File: ${t.filePath}`:void 0,h=p.content||`Codex is waiting for approval.
|
|
10
|
-
${
|
|
11
|
-
${u}`),this.pendingInteractivePrompt={promptId:
|
|
12
|
-
`).map(
|
|
13
|
-
`)}translatePromptResponse(
|
|
14
|
-
`)){let h=u.match(i);if(h){o+=1,r=Number.parseInt(h[1],10),
|
|
9
|
+
`).trim();return(0,ye.createHash)("sha256").update(s).digest("hex")}};var I=require("@quantiya/codevibe-core");var q=g(require("express")),T=g(require("fs")),X=g(require("path")),G=g(require("os"));E();var D=class{constructor(){this.assignedPort=0;this.app=(0,q.default)(),this.setupMiddleware(),this.setupRoutes(),this.tmuxSession=process.env.CODEVIBE_CODEX_TMUX_SESSION}getPort(){return this.assignedPort}setupMiddleware(){this.app.use(q.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="INTERACTIVE_PROMPT",i=`${e.tool_name||"Tool"} requires approval`,t.tool_name=e.tool_name,t.tool_input=e.tool_input,t.tool_use_id=e.tool_use_id;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=X.join(G.tmpdir(),`codevibe-codex-${this.tmuxSession}.port`);try{T.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=X.join(G.tmpdir(),`codevibe-codex-${this.tmuxSession}.port`);try{T.existsSync(e)&&(T.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 we=g(require("crypto")),Pe=g(require("fs")),Ee=g(require("https")),U=g(require("os")),Ie=g(require("path")),He="G-GS74YEQTB8",Ke="lAfOF6OxRzSQ-NsLBRjhAg",Be="www.google-analytics.com",je=`/mp/collect?measurement_id=${He}&api_secret=${Ke}`,be=800;function Ve(){try{let p=Ie.resolve(__dirname,"..","package.json"),e=Pe.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 ze=Ve();function qe(){let p=typeof process.getuid=="function"?process.getuid():0;return we.createHash("sha256").update(`${U.hostname()}-${p}`).digest("hex").substring(0,36)}function Xe(p){if(!p)return"";let e=U.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()},be);typeof r.unref=="function"&&r.unref();try{let a={...e};typeof a.error_message=="string"&&(a.error_message=Xe(a.error_message));let l=JSON.stringify({client_id:qe(),events:[{name:p,params:{agent:"codex",plugin_version:ze,platform:process.platform,source:process.env.CODEVIBE_TELEMETRY_SOURCE||"production",...a}}]});s=Ee.request({hostname:Be,path:je,method:"POST",headers:{"Content-Type":"application/json"},timeout:be},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 Ge=(0,Ce.promisify)(Oe.exec),Je="/quit",Te="CODEVIBE_CODEX_TMUX_SESSION";async function Ye(p,e){let t=async(s,i)=>{try{await Ge(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 Y=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 D,this.sessionWatcher=new R,this.approvalDetector=new M,this.promptResponder=new N,this.tmuxPaneObserver=new k}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"){let l=r?.tool_name||"unknown",d=r?.tool_input,u={tool_name:this.mapToolName(l),tool_input:d||{}};if(l==="apply_patch"&&typeof d=="string"){let{extractOldNewFromPatch:C,extractFileFromPatch:$}=(V(),Le(ce)),P=C(d),W=$(d);P&&(u.tool_input={file_path:W||"",old_string:P.oldString,new_string:P.newString})}let h=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(h)try{await new Promise(W=>setTimeout(W,500));let{execSync:C}=require("child_process"),$=C(`tmux capture-pane -p -e -S -30 -t '${h}'`,{timeout:5e3,encoding:"utf8"}),P=(0,I.parseInteractivePrompt)($);P&&P.options.length>0&&(u.options=P.options,u.submitMap=P.submitMap)}catch{n.debug("[Hooks] Tmux capture failed, using default options")}let f=o,b=u,w=!1;this.sessionKey&&(f=c.cryptoService.encryptContent(o,this.sessionKey),b={encrypted:c.cryptoService.encryptMetadata(u,this.sessionKey)},w=!0),await this.appSyncClient.createEvent({sessionId:a,type:c.EventType.INTERACTIVE_PROMPT,source:c.EventSource.DESKTOP,content:f,metadata:b,isEncrypted:w}),this.pendingInteractivePrompt={promptId:(0,J.v4)(),kind:"yes_no",options:u.options||[],submitMap:u.submitMap||{},promptText:o,createdAt:Date.now(),source:"tmux",requiresFollowUpText:!1},n.info("[Hooks] INTERACTIVE_PROMPT sent",{toolName:l,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=B(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;if(s&&this.pendingInteractivePrompt&&this.pendingInteractivePrompt.source==="tmux"&&this.pendingInteractivePrompt.promptText===s.promptText){n.debug("Skipping heuristic prompt because tmux prompt is already active",{promptText:s.promptText});return}let 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.
|
|
10
|
+
${e.hint}`;u&&!h.includes(u)&&(h=`${h}
|
|
11
|
+
${u}`),this.pendingInteractivePrompt={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};let f={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:f}),this.sessionKey&&(h=c.cryptoService.encryptContent(h,this.sessionKey),f={encrypted:c.cryptoService.encryptMetadata(f,this.sessionKey)},b=!0),await this.appSyncClient.createEvent({sessionId:this.sessionState.sessionId,type:c.EventType.INTERACTIVE_PROMPT,source:c.EventSource.DESKTOP,content:h,metadata:f,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,I.parseInteractivePrompt)(e);if(!t||this.pendingInteractivePrompt&&this.pendingInteractivePrompt.source==="tmux"&&this.pendingInteractivePrompt.promptText===t.promptText)return;let s=this.buildPromptPresentation(t),i=this.getMostRecentPendingToolCall();i||(await new Promise(w=>setTimeout(w,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=this.pendingInteractivePrompt?.callId||i?.callId||(0,J.v4)();this.pendingInteractivePrompt={promptId:u,callId:this.pendingInteractivePrompt?.callId||i?.callId,kind:s.kind,options:s.options,submitMap:s.submitMap,promptText:s.promptText,createdAt:Date.now(),source:"tmux",requiresFollowUpText:s.requiresFollowUpText};let h={options:s.options,instructions:s.instructions,prompt_source:"tmux_live",tool_name:a,tool_input:l,has_details:d},f=s.content,b=!1;this.sessionKey&&(f=c.cryptoService.encryptContent(f,this.sessionKey),h={encrypted:c.cryptoService.encryptMetadata(h,this.sessionKey)},b=!0);try{await this.appSyncClient.createEvent({sessionId:this.sessionState.sessionId,type:c.EventType.INTERACTIVE_PROMPT,source:c.EventSource.DESKTOP,content:f,metadata:h,promptId:u,...b?{isEncrypted:!0}:{}}),n.info("Sent tmux-detected interactive prompt",{sessionId:this.sessionState.sessionId,promptText:t.promptText,kind:t.kind})}catch(w){n.error("Failed to send tmux-detected interactive prompt",{error:w})}}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,I.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(`
|
|
12
|
+
`).map(t=>t.trimEnd()).filter(t=>t.length>0).slice(-12).map(t=>t.slice(0,160)).join(`
|
|
13
|
+
`)}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(`
|
|
14
|
+
`)){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 f=u.slice(1);t.push(f),s.push(f),r+=1,a+=1}}}return{oldString:t.join(`
|
|
15
15
|
`),newString:s.join(`
|
|
16
|
-
`),oldStartLine:o===1?
|
|
17
|
-
`)){let r=o.match(/^\s*(\d+)\s+(.*)$/);if(!r)continue;let
|
|
18
|
-
`);s?s=`${
|
|
16
|
+
`),oldStartLine:o===1?l:void 0,newStartLine:o===1?d:void 0}}extractDiffLineAnchorsFromSnapshot(e){let t=(0,I.normalizeSnapshot)(e),s,i;for(let o of t.split(`
|
|
17
|
+
`)){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(f){throw n.error("Failed to decrypt attachment:",{id:e.id,error:f}),new Error("Failed to decrypt attachment")}else i&&!this.sessionKey&&n.warn("Cannot decrypt attachment - no session key available",{id:e.id});let l=O.join(xe.tmpdir(),"codevibe-codex",t);x.existsSync(l)||x.mkdirSync(l,{recursive:!0});let d="";if(e.filename){let f=O.extname(e.filename);f&&(d=f)}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=O.join(l,u);return x.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 l of i){let d=await this.downloadAttachment(l,this.sessionState.sessionId,e.isEncrypted);d&&o.push(d)}if(o.length>0){let l=o.map(d=>`[Attached file: ${d}]`).join(`
|
|
18
|
+
`);s?s=`${l}
|
|
19
19
|
|
|
20
|
-
${s}`:s=`${
|
|
20
|
+
${s}`:s=`${l}
|
|
21
21
|
|
|
22
|
-
Please analyze the attached file(s).`,n.info("Prompt updated with attachment paths",{attachmentCount:o.length,newPromptLength:s.length})}}let r=this.translatePromptResponse(s),
|
|
22
|
+
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(this.sessionState.sessionId,r.primaryInput);if(a&&r.followUpInput&&await this.promptResponder.sendInput(this.sessionState.sessionId,r.followUpInput),a&&this.pendingInteractivePrompt&&e.type===c.EventType.PROMPT_RESPONSE&&(this.pendingInteractivePrompt=null),a)try{await this.appSyncClient.updateEventStatus({eventId:e.eventId,sessionId:e.sessionId,timestamp:e.timestamp,deliveryStatus:c.DeliveryStatus.EXECUTED})}catch(l){n.error("Failed to update executed status:",l)}}}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[Te];if(!t){n.warn("No tmux session set; skipping desktop self-terminate",{sessionId:e,expectedEnv:Te});return}await Ye(t,Je)}))}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(),j(),await this.httpApi.stop(),this.appSyncClient.cleanupSubscriptions(),n.info("CodeVibe Codex companion server stopped")}},Q=new Y;process.on("SIGINT",async()=>{n.info("Received SIGINT, shutting down..."),await Q.stop(),process.exit(0)});process.on("SIGTERM",async()=>{n.info("Received SIGTERM, shutting down..."),await Q.stop(),process.exit(0)});Q.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.27",
|
|
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": {
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"node": ">=18.0.0"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@quantiya/codevibe-core": "^1.0.
|
|
50
|
+
"@quantiya/codevibe-core": "^1.0.19",
|
|
51
51
|
"chokidar": "^4.0.0",
|
|
52
52
|
"dotenv": "^16.6.1",
|
|
53
53
|
"express": "^5.1.0",
|