@quantiya/codevibe-codex-plugin 1.0.13 → 1.0.14

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.
@@ -76,8 +76,22 @@ cleanup() {
76
76
  kill "$SERVER_PID" 2>/dev/null || true
77
77
  wait "$SERVER_PID" 2>/dev/null || true
78
78
  fi
79
- # Remove PID file
79
+ # Remove PID file and port file
80
80
  rm -f "${CODEVIBE_TMPDIR}/codevibe-codex-server-$$.pid"
81
+ rm -f "${CODEVIBE_TMPDIR}/codevibe-codex-${SESSION_NAME}.port"
82
+
83
+ # Remove our hooks from ~/.codex/hooks.json (idempotent, concurrent-safe)
84
+ if command -v jq &> /dev/null && [ -f "$HOME/.codex/hooks.json" ]; then
85
+ # Only remove if no other codevibe-codex sessions are running
86
+ if [ "$(pgrep -f 'codevibe-codex' | wc -l)" -le 1 ]; then
87
+ log "Removing CodeVibe hooks from $HOME/.codex/hooks.json"
88
+ jq 'del(.hooks[] | .[] | select(.hooks[]?.command | contains("codevibe-codex")))' \
89
+ "$HOME/.codex/hooks.json" > "$HOME/.codex/hooks.json.tmp" 2>/dev/null && \
90
+ mv "$HOME/.codex/hooks.json.tmp" "$HOME/.codex/hooks.json" || true
91
+ else
92
+ log "Other codevibe-codex sessions active, keeping hooks"
93
+ fi
94
+ fi
81
95
  }
82
96
 
83
97
  # Set up trap for cleanup
@@ -133,6 +147,64 @@ fi
133
147
  log "Starting session log watcher server..."
134
148
  export CODEX_WORKING_DIRECTORY="$WORKING_DIR"
135
149
  export CODEVIBE_CODEX_TMUX_SESSION="$SESSION_NAME"
150
+ export CODEVIBE_CODEX_PLUGIN_DIR="$PLUGIN_DIR"
151
+
152
+ # Install hooks.json for Codex CLI with absolute paths (idempotent)
153
+ # Codex CLI does NOT expand env vars in hook commands, so we must
154
+ # write absolute paths at runtime.
155
+ CODEX_HOOKS_FILE="$HOME/.codex/hooks.json"
156
+ HOOKS_DIR="$PLUGIN_DIR/hooks"
157
+
158
+ generate_hooks_json() {
159
+ cat <<HOOKEOF
160
+ {
161
+ "hooks": {
162
+ "SessionStart": [{"matcher": "*", "hooks": [{"type": "command", "command": "bash ${HOOKS_DIR}/session-start.sh"}]}],
163
+ "UserPromptSubmit": [{"matcher": "*", "hooks": [{"type": "command", "command": "bash ${HOOKS_DIR}/user-prompt.sh"}]}],
164
+ "PreToolUse": [{"matcher": "*", "hooks": [{"type": "command", "command": "bash ${HOOKS_DIR}/pre-tool-use.sh"}]}],
165
+ "PostToolUse": [{"matcher": "*", "hooks": [{"type": "command", "command": "bash ${HOOKS_DIR}/post-tool-use.sh"}]}],
166
+ "Stop": [{"matcher": "*", "hooks": [{"type": "command", "command": "bash ${HOOKS_DIR}/stop.sh"}]}]
167
+ }
168
+ }
169
+ HOOKEOF
170
+ }
171
+
172
+ # Ensure hooks feature flag is enabled in Codex config
173
+ CODEX_CONFIG="$HOME/.codex/config.toml"
174
+ if [ -f "$CODEX_CONFIG" ]; then
175
+ if ! grep -q "codex_hooks" "$CODEX_CONFIG" 2>/dev/null; then
176
+ echo -e '\n[features]\ncodex_hooks = true' >> "$CODEX_CONFIG"
177
+ log "Enabled codex_hooks feature flag in config.toml"
178
+ fi
179
+ else
180
+ mkdir -p "$HOME/.codex"
181
+ echo -e '[features]\ncodex_hooks = true' > "$CODEX_CONFIG"
182
+ log "Created config.toml with codex_hooks feature flag"
183
+ fi
184
+
185
+ mkdir -p "$HOME/.codex"
186
+ if [ -f "$CODEX_HOOKS_FILE" ]; then
187
+ if grep -q "codevibe-codex" "$CODEX_HOOKS_FILE" 2>/dev/null; then
188
+ log "CodeVibe hooks already installed in $CODEX_HOOKS_FILE"
189
+ elif command -v jq &> /dev/null; then
190
+ log "Merging CodeVibe hooks into existing $CODEX_HOOKS_FILE"
191
+ GENERATED=$(generate_hooks_json)
192
+ jq -s '.[0] as $existing | .[1] as $new |
193
+ $existing | .hooks = (
194
+ ($existing.hooks // {}) as $eh |
195
+ ($new.hooks // {}) as $nh |
196
+ ($eh | keys) + ($nh | keys) | unique | map(
197
+ { (.) : (($eh[.] // []) + ($nh[.] // [])) }
198
+ ) | add // {}
199
+ )' "$CODEX_HOOKS_FILE" <(echo "$GENERATED") > "${CODEX_HOOKS_FILE}.tmp" && \
200
+ mv "${CODEX_HOOKS_FILE}.tmp" "$CODEX_HOOKS_FILE"
201
+ else
202
+ log "WARN: jq not found and existing hooks.json exists — cannot merge safely"
203
+ fi
204
+ else
205
+ log "Installing CodeVibe hooks to $CODEX_HOOKS_FILE"
206
+ generate_hooks_json > "$CODEX_HOOKS_FILE"
207
+ fi
136
208
 
137
209
  # Start server and capture its PID
138
210
  node "$PLUGIN_DIR/dist/server.js" >> "$MCP_LOG_FILE" 2>&1 &
package/dist/server.js CHANGED
@@ -1,22 +1,22 @@
1
- "use strict";var st=Object.create;var O=Object.defineProperty;var rt=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var at=Object.getPrototypeOf,lt=Object.prototype.hasOwnProperty;var pt=(p,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ot(t))!lt.call(p,n)&&n!==e&&O(p,n,{get:()=>t[n],enumerable:!(i=rt(t,n))||i.enumerable});return p};var y=(p,t,e)=>(e=p!=null?st(at(p)):{},pt(t||!p||!p.__esModule?O(e,"default",{value:p,enumerable:!0}):e,p));var it=require("uuid"),w=y(require("fs")),x=y(require("path")),nt=y(require("os")),c=require("@quantiya/codevibe-core");var k=y(require("os")),W=y(require("path")),$=require("@quantiya/codevibe-core"),s=(0,$.createLogger)({name:"codevibe-codex",logFile:W.default.join(k.default.tmpdir(),"codevibe-codex-mcp.log"),level:"debug"});var U=require("events"),g=y(require("fs")),C=y(require("path")),K=y(require("readline")),z=require("chokidar"),j=require("@quantiya/codevibe-core");var T=class extends U.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){s.warn("Session log watcher already running");return}let e=(0,j.getConfig)().codex.sessionsDir;this.sessionsDir=e,s.info("Starting Codex session log watcher",{sessionsDir:e}),g.existsSync(e)||(s.info("Codex sessions directory does not exist yet, creating...",{sessionsDir:e}),g.mkdirSync(e,{recursive:!0})),this.startTime=Date.now(),this.watcher=(0,z.watch)(e,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},depth:4,ignored:i=>{let n=C.basename(i);return g.existsSync(i)&&g.statSync(i).isDirectory()?!1:!n.startsWith("rollout-")||!n.endsWith(".jsonl")}}),this.watcher.on("add",i=>{i.endsWith(".jsonl")&&this.onFileAdded(i)}),this.watcher.on("change",i=>{i.endsWith(".jsonl")&&this.onFileChanged(i)}),this.watcher.on("error",i=>{s.error("Watcher error:",i),this.emit("error",i)}),this.watcher.on("ready",()=>{s.info("Session log watcher ready"),this.bindRecentSessionFile()}),this.isWatching=!0,s.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,s.info("Session log watcher stopped")}getSessionId(){return this.sessionId}getActiveLogFile(){return this.activeLogFile}onFileAdded(e){try{let i=g.statSync(e),n=i.birthtimeMs||i.ctimeMs;if(n<this.startTime-5e3){s.debug("Ignoring old session file",{filePath:e,fileCreatedAt:new Date(n).toISOString(),startTime:new Date(this.startTime).toISOString()});return}}catch(i){s.warn("Could not check file creation time",{filePath:e,error:i})}if(this.activeLogFile){s.debug("Ignoring additional Codex session log for this server instance",{activeLogFile:this.activeLogFile,ignoredFile:e});return}s.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){s.debug("Ignoring change for non-active session log",{activeLogFile:this.activeLogFile,ignoredFile:e});return}if(!this.activeLogFile){try{let i=g.statSync(e),n=i.birthtimeMs||i.ctimeMs,r=i.mtimeMs;if(n<this.startTime-5e3&&r<this.startTime-5e3){s.debug("Ignoring change for pre-existing session file",{filePath:e,fileCreatedAt:new Date(n).toISOString(),fileModifiedAt:new Date(r).toISOString(),startTime:new Date(this.startTime).toISOString()});return}}catch(i){s.warn("Could not check file creation time during change event",{filePath:e,error:i})}this.activeLogFile=e,this.filePositions.set(e,0)}this.readNewLines(e)}bindRecentSessionFile(){if(!(this.activeLogFile||!this.sessionsDir))try{let i=this.collectRecentSessionFiles(this.sessionsDir).sort((n,r)=>r.modifiedAt-n.modifiedAt)[0];if(!i)return;s.info("Binding recent session file missed during initial watch scan",{filePath:i.filePath,fileCreatedAt:new Date(i.createdAt).toISOString(),fileModifiedAt:new Date(i.modifiedAt).toISOString(),watcherStartTime:new Date(this.startTime).toISOString()}),this.activeLogFile=i.filePath,this.filePositions.set(i.filePath,0),this.readNewLines(i.filePath)}catch(e){s.warn("Failed to backfill recent session file",{error:e})}}collectRecentSessionFiles(e){let i=[],n=[e];for(;n.length>0;){let r=n.pop();if(!r)continue;let o;try{o=g.readdirSync(r,{withFileTypes:!0})}catch{continue}for(let a of o){let l=C.join(r,a.name);if(a.isDirectory()){n.push(l);continue}if(!(!a.isFile()||!a.name.startsWith("rollout-")||!a.name.endsWith(".jsonl")))try{let d=g.statSync(l),u=d.birthtimeMs||d.ctimeMs,h=d.mtimeMs;(u>=this.startTime||h>=this.startTime-5e3)&&i.push({filePath:l,createdAt:u,modifiedAt:h})}catch{}}}return i}async readNewLines(e){let i=this.filePositions.get(e)||0;try{if(g.statSync(e).size<=i)return;let r=g.createReadStream(e,{start:i,encoding:"utf-8"}),o=K.createInterface({input:r,crlfDelay:1/0}),a=i;for await(let l of o)if(a+=Buffer.byteLength(l,"utf-8")+1,!!l.trim())try{let d=JSON.parse(l);this.processLogEntry(d)}catch(d){s.warn("Failed to parse log line",{filePath:e,line:l.substring(0,100),error:d})}this.filePositions.set(e,a)}catch(n){s.error("Error reading log file",{filePath:e,error:n}),this.emit("error",n)}}processLogEntry(e){if(s.debug("Processing log entry",{type:e.type}),e.type==="session_meta"){let i=e.payload;this.sessionId=i.id,s.info("Codex session started",{sessionId:i.id,cwd:i.cwd,cliVersion:i.cli_version}),this.emit("session-started",i);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)}};var A=require("uuid"),v=require("@quantiya/codevibe-core");var S=new Map;function B(p,t){let e={sessionId:t,source:v.EventSource.DESKTOP};if(p.type==="event_msg"&&p.payload){let i=p.payload.type;switch(i){case"user_message":return{...e,type:v.EventType.USER_PROMPT,content:p.payload.message||"",metadata:{images:p.payload.images||[]}};case"agent_message":return{...e,type:v.EventType.ASSISTANT_RESPONSE,content:p.payload.message||""};case"agent_reasoning":return{...e,type:v.EventType.REASONING,content:p.payload.text||""};case"token_count":return s.debug("Skipping token_count entry"),null;default:return s.debug("Unknown event_msg type",{type:i}),null}}if(p.type==="response_item"&&p.payload){let i=p.payload.type;if(i==="function_call"){let{name:n,arguments:r,call_id:o}=p.payload,a={};try{a=JSON.parse(r||"{}")}catch{a={raw:r}}let l=(0,A.v4)();S.set(o,{name:n,input:r,eventId:l});let d=D(n),u=ct(n,a);return{...e,type:v.EventType.TOOL_USE,content:u,metadata:{toolName:d,toolInput:a,callId:o,status:"running"}}}if(i==="function_call_output"){let{call_id:n,output:r}=p.payload,o=S.get(n);S.delete(n);let a=o?.name?D(o.name):"Tool",l=ht(r,500);return{...e,type:v.EventType.TOOL_USE,content:`${a} completed:
2
- ${l}`,metadata:{toolName:a,toolOutput:r,callId:n,status:"completed"}}}if(i==="custom_tool_call"){let{name:n,call_id:r,input:o,status:a}=p.payload;S.set(r,{name:n,input:o,eventId:(0,A.v4)()});let l=ut(o),{oldString:d,newString:u}=dt(o),h=l?`Editing: ${l.filePath}`:"Applying patch";return{...e,type:v.EventType.TOOL_USE,content:h,metadata:{tool_name:"Edit",tool_input:{file_path:l?.filePath||"",old_string:d,new_string:u},callId:r,status:a||"running"}}}if(i==="custom_tool_call_output"){let{call_id:n,output:r}=p.payload,o=S.get(n);S.delete(n);let a={};try{a=JSON.parse(r||"{}")}catch{a={raw:r}}let l=a.output?.includes("Success")||!a.error;return{...e,type:v.EventType.TOOL_USE,content:l?"File edit applied successfully":`Edit failed: ${a.error||"Unknown error"}`,metadata:{toolName:"Edit",toolOutput:a,callId:n,status:"completed",success:l}}}return s.debug("Unknown response_item type",{type:i}),null}return p.type==="turn_context"?(s.debug("Skipping turn_context entry"),null):(s.debug("Unhandled log entry type",{type:p.type}),null)}function D(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 ct(p,t){switch(p){case"shell_command":case"shell":return`Running: ${t.command||"command"}`;case"read_file":return`Reading: ${t.file_path||t.path||"file"}`;case"write_file":return`Writing: ${t.file_path||t.path||"file"}`;case"list_files":return`Listing: ${t.path||"."}`;case"search_files":return`Searching for: ${t.pattern||t.query||"pattern"}`;case"web_search":return`Searching web: ${t.query||"query"}`;default:return`Running ${D(p)}`}}function dt(p){let t=[],e=[],i=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;for(let n of p.split(`
3
- `))if(!(i.test(n)||n.startsWith("***")||n.startsWith("---")||n.startsWith("+++"))){if(n.startsWith("-"))t.push(n.slice(1));else if(n.startsWith("+"))e.push(n.slice(1));else if(n.startsWith(" ")){let r=n.slice(1);t.push(r),e.push(r)}}return{oldString:t.join(`
1
+ "use strict";var Pt=Object.create;var F=Object.defineProperty;var bt=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var It=Object.getPrototypeOf,_t=Object.prototype.hasOwnProperty;var Y=(l,t)=>()=>(l&&(t=l(l=0)),t);var Et=(l,t)=>{for(var e in t)F(l,e,{get:t[e],enumerable:!0})},Z=(l,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of wt(t))!_t.call(l,s)&&s!==e&&F(l,s,{get:()=>t[s],enumerable:!(i=bt(t,s))||i.enumerable});return l};var g=(l,t,e)=>(e=l!=null?Pt(It(l)):{},Z(t||!l||!l.__esModule?F(e,"default",{value:l,enumerable:!0}):e,l)),Tt=l=>Z(F({},"__esModule",{value:!0}),l);var Q,tt,et,n,I=Y(()=>{"use strict";Q=g(require("os")),tt=g(require("path")),et=require("@quantiya/codevibe-core"),n=(0,et.createLogger)({name:"codevibe-codex",logFile:tt.default.join(Q.default.tmpdir(),"codevibe-codex-mcp.log"),level:"debug"})});var pt={};Et(pt,{clearPendingCalls:()=>H,extractFileFromPatch:()=>at,extractOldNewFromPatch:()=>rt,getPendingCall:()=>Ot,getPendingCallsCount:()=>Ft,mapLogEntryToEvent:()=>K});function K(l,t){let e={sessionId:t,source:v.EventSource.DESKTOP};if(l.type==="event_msg"&&l.payload){let i=l.payload.type;switch(i){case"user_message":return{...e,type:v.EventType.USER_PROMPT,content:l.payload.message||"",metadata:{images:l.payload.images||[]}};case"agent_message":return{...e,type:v.EventType.ASSISTANT_RESPONSE,content:l.payload.message||""};case"agent_reasoning":return{...e,type:v.EventType.REASONING,content:l.payload.text||""};case"token_count":return n.debug("Skipping token_count entry"),null;default:return n.debug("Unknown event_msg type",{type:i}),null}}if(l.type==="response_item"&&l.payload){let i=l.payload.type;if(i==="function_call"){let{name:s,arguments:o,call_id:r}=l.payload,p={};try{p=JSON.parse(o||"{}")}catch{p={raw:o}}let a=(0,$.v4)();S.set(r,{name:s,input:o,eventId:a});let d=W(s),u=xt(s,p);return{...e,type:v.EventType.TOOL_USE,content:u,metadata:{toolName:d,toolInput:p,callId:r,status:"running"}}}if(i==="function_call_output"){let{call_id:s,output:o}=l.payload,r=S.get(s);S.delete(s);let p=r?.name?W(r.name):"Tool",a=Ct(o,500);return{...e,type:v.EventType.TOOL_USE,content:`${p} completed:
2
+ ${a}`,metadata:{toolName:p,toolOutput:o,callId:s,status:"completed"}}}if(i==="custom_tool_call"){let{name:s,call_id:o,input:r,status:p}=l.payload;S.set(o,{name:s,input:r,eventId:(0,$.v4)()});let a=at(r),{oldString:d,newString:u}=rt(r),h=a?`Editing: ${a.filePath}`:"Applying patch";return{...e,type:v.EventType.TOOL_USE,content:h,metadata:{tool_name:"Edit",tool_input:{file_path:a?.filePath||"",old_string:d,new_string:u},callId:o,status:p||"running"}}}if(i==="custom_tool_call_output"){let{call_id:s,output:o}=l.payload,r=S.get(s);S.delete(s);let p={};try{p=JSON.parse(o||"{}")}catch{p={raw:o}}let a=p.output?.includes("Success")||!p.error;return{...e,type:v.EventType.TOOL_USE,content:a?"File edit applied successfully":`Edit failed: ${p.error||"Unknown error"}`,metadata:{toolName:"Edit",toolOutput:p,callId:s,status:"completed",success:a}}}return n.debug("Unknown response_item type",{type:i}),null}return l.type==="turn_context"?(n.debug("Skipping turn_context entry"),null):(n.debug("Unhandled log entry type",{type:l.type}),null)}function W(l){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"}[l]||l}function xt(l,t){switch(l){case"shell_command":case"shell":return`Running: ${t.command||"command"}`;case"read_file":return`Reading: ${t.file_path||t.path||"file"}`;case"write_file":return`Writing: ${t.file_path||t.path||"file"}`;case"list_files":return`Listing: ${t.path||"."}`;case"search_files":return`Searching for: ${t.pattern||t.query||"pattern"}`;case"web_search":return`Searching web: ${t.query||"query"}`;default:return`Running ${W(l)}`}}function rt(l){let t=[],e=[],i=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;for(let s of l.split(`
3
+ `))if(!(i.test(s)||s.startsWith("***")||s.startsWith("---")||s.startsWith("+++"))){if(s.startsWith("-"))t.push(s.slice(1));else if(s.startsWith("+"))e.push(s.slice(1));else if(s.startsWith(" ")){let o=s.slice(1);t.push(o),e.push(o)}}return{oldString:t.join(`
4
4
  `),newString:e.join(`
5
- `)}}function ut(p){if(!p)return null;let t=p.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);return t?{filePath:t[1].trim()}:null}function ht(p,t){return p?p.length<=t?p:p.substring(0,t)+"...":""}function H(){S.clear()}var q=require("events"),V=require("@quantiya/codevibe-core");var E=class extends q.EventEmitter{constructor(){super();this.pendingCalls=new Map;this.timers=new Map;this.timeoutMs=(0,V.getConfig)().codex.approvalTimeoutMs,s.info("Approval detector initialized",{timeoutMs:this.timeoutMs})}onToolCallStart(e,i,n){s.debug("Tool call started",{callId:e,name:i});let r=this.parseInput(n),o=this.extractFilePath(i,n,r),a=this.extractDiff(i,n,r),l={callId:e,name:i,input:n,filePath:o,diff:a,parsedInput:r,timestamp:Date.now(),notificationSent:!1};this.pendingCalls.set(e,l);let d=setTimeout(()=>{this.checkPendingCall(e)},this.timeoutMs);this.timers.set(e,d)}onToolCallComplete(e){s.debug("Tool call completed",{callId:e}),this.pendingCalls.delete(e);let i=this.timers.get(e);i&&(clearTimeout(i),this.timers.delete(e))}checkPendingCall(e){let i=this.pendingCalls.get(e);if(!i||i.notificationSent)return;let n=Date.now()-i.timestamp;s.info("Tool call still pending after timeout",{callId:e,name:i.name,elapsedMs:n}),i.notificationSent=!0,this.pendingCalls.set(e,i),this.emit("approval-pending",{callId:e,toolName:i.name,hint:this.extractHint(i.name,i.input,i.filePath),filePath:i.filePath,diff:i.diff,toolInput:i.parsedInput,rawInput:i.input,elapsedMs:n})}extractHint(e,i,n){if(n)return`File: ${n}`;if(e==="apply_patch"&&i){let r=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(r)return`File: ${r[1].trim()}`}if(e==="shell_command"||e==="shell")try{let r=JSON.parse(i);if(r.command)return`Command: ${r.command.substring(0,50)}${r.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,i,n){if(e==="apply_patch"&&i){let o=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(o)return o[1].trim()}let r=n?.file_path||n?.path||n?.filePath;if(r&&typeof r=="string")return r}extractDiff(e,i,n){if(e==="apply_patch"&&i)return i;if(n?.diff&&typeof n.diff=="string")return n.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(),s.debug("Approval detector cleared")}shutdown(){this.clear(),this.removeAllListeners(),s.info("Approval detector shutdown")}};var J=require("child_process"),X=require("util");var G=(0,X.promisify)(J.exec),_=class{async sendInput(t,e){s.info("Attempting to send input to Codex",{sessionId:t,input:e});try{let i=process.env.CODEVIBE_CODEX_TMUX_SESSION;return i?(s.info("Using tmux send-keys",{tmuxSession:i}),await this.sendViaTmux(i,e),s.info("Successfully sent input to Codex",{sessionId:t,input:e}),!0):(s.error("No tmux session found - codevibe-codex wrapper is required",{sessionId:t,hint:"Start Codex CLI using the codevibe-codex wrapper script"}),!1)}catch(i){return s.error("Failed to send input to Codex",{sessionId:t,error:i instanceof Error?i.message:String(i)}),!1}}async sendViaTmux(t,e){let i=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");s.info("Sending via tmux",{sessionName:t,inputLength:e.length});try{let n=`tmux send-keys -t "${t}" -l "${i}"`;await G(n),await this.delay(500);let r=`tmux send-keys -t "${t}" Enter`;await G(r),s.info("tmux send-keys completed")}catch(n){throw s.error("tmux send-keys failed",{sessionName:t,error:n}),n}}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 f=y(require("fs")),Y=y(require("os")),L=y(require("path")),Z=require("crypto"),Q=require("child_process"),tt=require("events"),et=require("util");var R=(0,et.promisify)(Q.exec),F=class extends tt.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){s.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(Y.tmpdir(),`codevibe-codex-pane-${process.pid}.log`),f.mkdirSync(L.dirname(this.pipeFilePath),{recursive:!0}),f.writeFileSync(this.pipeFilePath,""),await this.enablePipePane(),this.startFileWatcher(),s.info("Tmux pane observer started",{sessionName:e})}async stop(){if(this.started){try{await this.disablePipePane()}catch(e){s.debug("Failed to disable tmux pipe-pane cleanly",{error:e})}if(this.watcher&&(this.watcher.close(),this.watcher=null),this.pipeFilePath)try{f.unlinkSync(this.pipeFilePath)}catch{}s.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 i=Math.max(1,Math.floor(e)),n=this.escapeShellArg(this.sessionName),r=`tmux capture-pane -p -e -S -${i} -t '${n}'`;try{let{stdout:o}=await R(r);return o}catch(o){throw s.error("Failed to capture tmux pane snapshot",{sessionName:this.sessionName,error:o}),this.emit("observer-error",o),o}}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),i=this.escapeShellArg(this.pipeFilePath),n=`tmux pipe-pane -O -t '${e}' "cat >> '${i}'"`;await R(n),s.debug("Enabled tmux pipe-pane mirroring",{sessionName:this.sessionName,pipeFilePath:this.pipeFilePath})}async disablePipePane(){if(!this.sessionName)return;let i=`tmux pipe-pane -t '${this.escapeShellArg(this.sessionName)}'`;await R(i)}startFileWatcher(){this.pipeFilePath&&(this.watcher=f.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 i=await this.captureSnapshot();if(!i||!this.looksLikePromptSnapshot(i))continue;let n=this.hashPromptSnapshot(i);n!==this.lastPromptHash&&(this.lastPromptHash=n,this.emit("prompt-candidate",{rawDelta:e,snapshot:i,detectedAt:Date.now()}))}while(this.pendingRead)}catch(e){s.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=f.statSync(this.pipeFilePath);if(e.size<=this.filePosition)return"";let i=f.openSync(this.pipeFilePath,"r");try{let n=e.size-this.filePosition,r=Buffer.alloc(n);return f.readSync(i,r,0,n,this.filePosition),this.filePosition=e.size,r.toString("utf-8")}finally{f.closeSync(i)}}looksLikePromptDelta(e){return/\[(?:y\/n|Y\/n|y\/N)\]|\b(?:apply|approve|allow|reject|deny|continue)\b/i.test(e)}looksLikePromptSnapshot(e){let i=e.split(`
5
+ `)}}function at(l){if(!l)return null;let t=l.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);return t?{filePath:t[1].trim()}:null}function Ct(l,t){return l?l.length<=t?l:l.substring(0,t)+"...":""}function H(){S.clear()}function Ft(){return S.size}function Ot(l){return S.get(l)}var $,v,S,j=Y(()=>{"use strict";$=require("uuid"),v=require("@quantiya/codevibe-core");I();S=new Map});var X=require("uuid"),T=g(require("fs")),C=g(require("path")),St=g(require("os")),c=require("@quantiya/codevibe-core");I();var it=require("events"),y=g(require("fs")),R=g(require("path")),st=g(require("readline")),nt=require("chokidar"),ot=require("@quantiya/codevibe-core");I();var O=class extends it.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,ot.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,nt.watch)(e,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},depth:4,ignored:i=>{let s=R.basename(i);return y.existsSync(i)&&y.statSync(i).isDirectory()?!1:!s.startsWith("rollout-")||!s.endsWith(".jsonl")}}),this.watcher.on("add",i=>{i.endsWith(".jsonl")&&this.onFileAdded(i)}),this.watcher.on("change",i=>{i.endsWith(".jsonl")&&this.onFileChanged(i)}),this.watcher.on("error",i=>{n.error("Watcher error:",i),this.emit("error",i)}),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 i=y.statSync(e),s=i.birthtimeMs||i.ctimeMs;if(s<this.startTime-5e3){n.debug("Ignoring old session file",{filePath:e,fileCreatedAt:new Date(s).toISOString(),startTime:new Date(this.startTime).toISOString()});return}}catch(i){n.warn("Could not check file creation time",{filePath:e,error:i})}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 i=y.statSync(e),s=i.birthtimeMs||i.ctimeMs,o=i.mtimeMs;if(s<this.startTime-5e3&&o<this.startTime-5e3){n.debug("Ignoring change for pre-existing session file",{filePath:e,fileCreatedAt:new Date(s).toISOString(),fileModifiedAt:new Date(o).toISOString(),startTime:new Date(this.startTime).toISOString()});return}}catch(i){n.warn("Could not check file creation time during change event",{filePath:e,error:i})}this.activeLogFile=e,this.filePositions.set(e,0)}this.readNewLines(e)}bindRecentSessionFile(){if(!(this.activeLogFile||!this.sessionsDir))try{let i=this.collectRecentSessionFiles(this.sessionsDir).sort((s,o)=>o.modifiedAt-s.modifiedAt)[0];if(!i)return;n.info("Binding recent session file missed during initial watch scan",{filePath:i.filePath,fileCreatedAt:new Date(i.createdAt).toISOString(),fileModifiedAt:new Date(i.modifiedAt).toISOString(),watcherStartTime:new Date(this.startTime).toISOString()}),this.activeLogFile=i.filePath,this.filePositions.set(i.filePath,0),this.readNewLines(i.filePath)}catch(e){n.warn("Failed to backfill recent session file",{error:e})}}collectRecentSessionFiles(e){let i=[],s=[e];for(;s.length>0;){let o=s.pop();if(!o)continue;let r;try{r=y.readdirSync(o,{withFileTypes:!0})}catch{continue}for(let p of r){let a=R.join(o,p.name);if(p.isDirectory()){s.push(a);continue}if(!(!p.isFile()||!p.name.startsWith("rollout-")||!p.name.endsWith(".jsonl")))try{let d=y.statSync(a),u=d.birthtimeMs||d.ctimeMs,h=d.mtimeMs;(u>=this.startTime||h>=this.startTime-5e3)&&i.push({filePath:a,createdAt:u,modifiedAt:h})}catch{}}}return i}async readNewLines(e){let i=this.filePositions.get(e)||0;try{if(y.statSync(e).size<=i)return;let o=y.createReadStream(e,{start:i,encoding:"utf-8"}),r=st.createInterface({input:o,crlfDelay:1/0}),p=i;for await(let a of r)if(p+=Buffer.byteLength(a,"utf-8")+1,!!a.trim())try{let d=JSON.parse(a);this.processLogEntry(d)}catch(d){n.warn("Failed to parse log line",{filePath:e,line:a.substring(0,100),error:d})}this.filePositions.set(e,p)}catch(s){n.error("Error reading log file",{filePath:e,error:s}),this.emit("error",s)}}processLogEntry(e){if(n.debug("Processing log entry",{type:e.type}),e.type==="session_meta"){let i=e.payload;this.sessionId=i.id,n.info("Codex session started",{sessionId:i.id,cwd:i.cwd,cliVersion:i.cli_version}),this.emit("session-started",i);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)}};j();var lt=require("events"),ct=require("@quantiya/codevibe-core");I();var A=class extends lt.EventEmitter{constructor(){super();this.pendingCalls=new Map;this.timers=new Map;this.timeoutMs=(0,ct.getConfig)().codex.approvalTimeoutMs,n.info("Approval detector initialized",{timeoutMs:this.timeoutMs})}onToolCallStart(e,i,s){n.debug("Tool call started",{callId:e,name:i});let o=this.parseInput(s),r=this.extractFilePath(i,s,o),p=this.extractDiff(i,s,o),a={callId:e,name:i,input:s,filePath:r,diff:p,parsedInput:o,timestamp:Date.now(),notificationSent:!1};this.pendingCalls.set(e,a);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 i=this.timers.get(e);i&&(clearTimeout(i),this.timers.delete(e))}checkPendingCall(e){let i=this.pendingCalls.get(e);if(!i||i.notificationSent)return;let s=Date.now()-i.timestamp;n.info("Tool call still pending after timeout",{callId:e,name:i.name,elapsedMs:s}),i.notificationSent=!0,this.pendingCalls.set(e,i),this.emit("approval-pending",{callId:e,toolName:i.name,hint:this.extractHint(i.name,i.input,i.filePath),filePath:i.filePath,diff:i.diff,toolInput:i.parsedInput,rawInput:i.input,elapsedMs:s})}extractHint(e,i,s){if(s)return`File: ${s}`;if(e==="apply_patch"&&i){let o=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(o)return`File: ${o[1].trim()}`}if(e==="shell_command"||e==="shell")try{let o=JSON.parse(i);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,i,s){if(e==="apply_patch"&&i){let r=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(r)return r[1].trim()}let o=s?.file_path||s?.path||s?.filePath;if(o&&typeof o=="string")return o}extractDiff(e,i,s){if(e==="apply_patch"&&i)return i;if(s?.diff&&typeof s.diff=="string")return s.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 ut=require("child_process"),ht=require("util");I();var dt=(0,ht.promisify)(ut.exec),N=class{async sendInput(t,e){n.info("Attempting to send input to Codex",{sessionId:t,input:e});try{let i=process.env.CODEVIBE_CODEX_TMUX_SESSION;return i?(n.info("Using tmux send-keys",{tmuxSession:i}),await this.sendViaTmux(i,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(i){return n.error("Failed to send input to Codex",{sessionId:t,error:i instanceof Error?i.message:String(i)}),!1}}async sendViaTmux(t,e){let i=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`");n.info("Sending via tmux",{sessionName:t,inputLength:e.length});try{let s=`tmux send-keys -t "${t}" -l "${i}"`;await dt(s),await this.delay(500);let o=`tmux send-keys -t "${t}" Enter`;await dt(o),n.info("tmux send-keys completed")}catch(s){throw n.error("tmux send-keys failed",{sessionName:t,error:s}),s}}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 f=g(require("fs")),mt=g(require("os")),k=g(require("path")),ft=require("crypto"),gt=require("child_process"),yt=require("events"),vt=require("util");I();var B=(0,vt.promisify)(gt.exec),M=class extends yt.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=k.join(mt.tmpdir(),`codevibe-codex-pane-${process.pid}.log`),f.mkdirSync(k.dirname(this.pipeFilePath),{recursive:!0}),f.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{f.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 i=Math.max(1,Math.floor(e)),s=this.escapeShellArg(this.sessionName),o=`tmux capture-pane -p -e -S -${i} -t '${s}'`;try{let{stdout:r}=await B(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),i=this.escapeShellArg(this.pipeFilePath),s=`tmux pipe-pane -O -t '${e}' "cat >> '${i}'"`;await B(s),n.debug("Enabled tmux pipe-pane mirroring",{sessionName:this.sessionName,pipeFilePath:this.pipeFilePath})}async disablePipePane(){if(!this.sessionName)return;let i=`tmux pipe-pane -t '${this.escapeShellArg(this.sessionName)}'`;await B(i)}startFileWatcher(){this.pipeFilePath&&(this.watcher=f.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 i=await this.captureSnapshot();if(!i||!this.looksLikePromptSnapshot(i))continue;let s=this.hashPromptSnapshot(i);s!==this.lastPromptHash&&(this.lastPromptHash=s,this.emit("prompt-candidate",{rawDelta:e,snapshot:i,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=f.statSync(this.pipeFilePath);if(e.size<=this.filePosition)return"";let i=f.openSync(this.pipeFilePath,"r");try{let s=e.size-this.filePosition,o=Buffer.alloc(s);return f.readSync(i,o,0,s,this.filePosition),this.filePosition=e.size,o.toString("utf-8")}finally{f.closeSync(i)}}looksLikePromptDelta(e){return/\[(?:y\/n|Y\/n|y\/N)\]|\b(?:apply|approve|allow|reject|deny|continue)\b/i.test(e)}looksLikePromptSnapshot(e){let i=e.split(`
6
6
  `).slice(-20).join(`
7
7
  `);return/\[(?:y\/n|Y\/n|y\/N)\]|^\s*\d+\.\s+/im.test(i)}hashPromptSnapshot(e){let i=e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"").replace(/\r/g,`
8
8
  `).replace(/[ \t]+\n/g,`
9
- `).trim();return(0,Z.createHash)("sha256").update(i).digest("hex")}};var b=require("@quantiya/codevibe-core");var M=class{constructor(){this.sessionState=null;this.unsubscribe=null;this.sessionKey=null;this.pendingInteractivePrompt=null;this.isInitializingSession=!1;this.bufferedLogEntries=[];this.sessionWatcher=new T,this.approvalDetector=new E,this.promptResponder=new _,this.tmuxPaneObserver=new F}async start(){s.info("Starting CodeVibe Codex companion server",{environment:(0,c.getEnvironment)()}),this.appSyncClient=new c.AppSyncClient,await this.appSyncClient.authenticateWithStoredTokens()||(s.error('Authentication failed. Run "codevibe-codex login" first.'),console.error('Not authenticated. Run "codevibe-codex login" to sign in.'),process.exit(1)),s.info("Authenticated successfully",{userId:this.appSyncClient.getCurrentUserId(),email:this.appSyncClient.getCurrentUserEmail()}),await(0,c.registerDeviceEncryptionKey)(this.appSyncClient,s),(0,c.startDeviceKeyWatcher)(this.appSyncClient,s),this.setupEventHandlers(),this.sessionWatcher.start(),s.info("CodeVibe Codex companion server started")}setupEventHandlers(){this.sessionWatcher.on("session-started",async t=>{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=>{s.debug("Tmux pane observer error",{error:t})}),this.sessionWatcher.on("error",t=>{s.error("Session watcher error:",t)})}async handleSessionStarted(t){s.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(),i=this.generateSessionId(t.id),n=this.appSyncClient.getCurrentUserId(),r={codexSessionId:t.id,cliVersion:t.cli_version,modelProvider:t.model_provider};try{let o=await(0,c.resumeOrCreateSession)({sessionId:i,userId:n,agentType:c.AgentType.CODEX,projectPath:e,metadata:r},this.appSyncClient,s);this.sessionKey=o.sessionKey}catch(o){throw s.error("Failed to create/resume session:",o),o}try{this.sessionState={sessionId:i,userId:n,projectPath:e,cwd:t.cwd,createdAt:new Date,subscriptionActive:!1,metadata:r,codexSessionId:t.id,codexLogFile:this.sessionWatcher.getActiveLogFile()||void 0},await this.flushBufferedLogEntries(),await this.startTmuxObserver(),this.subscribeToMobileEvents(i),this.appSyncClient.startHeartbeat(i)}catch(o){s.error("Failed to create session:",o),this.bufferedLogEntries=[]}finally{this.isInitializingSession=!1}}async flushBufferedLogEntries(){if(this.bufferedLogEntries.length===0)return;let t=this.bufferedLogEntries;this.bufferedLogEntries=[],s.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),s.debug("Buffering log entry until session initialization completes",{type:t.type,bufferedCount:this.bufferedLogEntries.length});return}s.warn("Received log entry but no active session");return}if(t.type==="response_item"&&t.payload){let i=t.payload.type;i==="function_call"||i==="custom_tool_call"?this.approvalDetector.onToolCallStart(t.payload.call_id,t.payload.name,t.payload.arguments||t.payload.input||""):(i==="function_call_output"||i==="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)try{if(this.sessionKey){if(e.content=c.cryptoService.encryptContent(e.content,this.sessionKey),e.metadata){let i=c.cryptoService.encryptMetadata(e.metadata,this.sessionKey);e.metadata={encrypted:i}}e.isEncrypted=!0,s.debug("Event encrypted",{type:e.type})}await this.appSyncClient.createEvent(e),s.debug("Event synced to backend",{type:e.type,encrypted:!!this.sessionKey})}catch(i){s.error("Failed to sync event:",i)}}async handleApprovalPending(t){if(this.sessionState){s.info("Sending approval pending interactive prompt",t);try{let e=await this.tryParseInteractivePromptFromTmux(),i=e?.parsedPrompt??null;if(i&&this.pendingInteractivePrompt&&this.pendingInteractivePrompt.source==="tmux"&&this.pendingInteractivePrompt.promptText===i.promptText){s.debug("Skipping heuristic prompt because tmux prompt is already active",{promptText:i.promptText});return}let n=this.buildToolDetailsForInteractivePrompt(t,e?.snapshot),r=n.tool_name||this.mapToolNameForApproval(t.toolName),o=n.tool_input||this.buildFallbackToolInput(t),a=!!(r&&o),l=this.buildPromptPresentation(i),d=l.options,u=t.filePath?`File: ${t.filePath}`:void 0,h=l.content||`Codex is waiting for approval.
9
+ `).trim();return(0,ft.createHash)("sha256").update(i).digest("hex")}};var _=require("@quantiya/codevibe-core");var z=g(require("express")),E=g(require("fs")),V=g(require("path")),q=g(require("os"));I();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((t,e,i)=>{n.debug(`${t.method} ${t.path}`,{body:t.body}),i()})}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 i=t.body;if(!i.session_id||!i.hook_event_name){e.status(400).json({success:!1,error:"Missing session_id or hook_event_name"});return}let s=this.transformHookToEvent(i);n.info("Received hook event",{sessionId:i.session_id,hookEvent:i.hook_event_name,type:s.type}),this.eventHandler&&await this.eventHandler(s),e.json({success:!0})}catch(i){n.error("Error handling event:",i),e.status(500).json({success:!1,error:i instanceof Error?i.message:"Unknown error"})}}transformHookToEvent(t){let e={cwd:t.cwd,hook_event_name:t.hook_event_name,...t.metadata||{}},i,s;switch(t.hook_event_name){case"SessionStart":i="NOTIFICATION",s="Session started",e.source=t.source;break;case"UserPromptSubmit":i="USER_PROMPT",s=t.prompt||"";break;case"PreToolUse":i="INTERACTIVE_PROMPT",s=`${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":i="TOOL_USE",s=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":i="ASSISTANT_RESPONSE",s=t.last_assistant_message||"";break;default:i="NOTIFICATION",s=`Hook: ${t.hook_event_name}`}return{session_id:t.session_id,hook_event_name:t.hook_event_name,type:i,source:"DESKTOP",content:s,metadata:e}}onEvent(t){this.eventHandler=t}async start(){return new Promise((t,e)=>{try{this.server=this.app.listen(0,"localhost",()=>{let i=this.server.address();this.assignedPort=i.port,n.info(`HTTP API listening on http://localhost:${this.assignedPort}`),this.writePortFile(this.assignedPort),t(this.assignedPort)}),this.server.on("error",i=>{n.error("HTTP server error:",i),e(i)})}catch(i){e(i)}})}writePortFile(t){if(!this.tmuxSession){n.warn("No CODEVIBE_CODEX_TMUX_SESSION set, skipping port file");return}let e=V.join(q.tmpdir(),`codevibe-codex-${this.tmuxSession}.port`);try{E.writeFileSync(e,t.toString()),n.info(`Port file written: ${e} -> ${t}`)}catch(i){n.error(`Failed to write port file: ${e}`,i)}}removePortFile(){if(!this.tmuxSession)return;let t=V.join(q.tmpdir(),`codevibe-codex-${this.tmuxSession}.port`);try{E.existsSync(t)&&(E.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 G=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 L,this.sessionWatcher=new O,this.approvalDetector=new A,this.promptResponder=new N,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),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(),i=this.generateSessionId(t),s=this.appSyncClient.getCurrentUserId();n.info("Creating launch session",{sessionId:i,projectPath:e});try{let o=await(0,c.resumeOrCreateSession)({sessionId:i,userId:s,agentType:c.AgentType.CODEX,projectPath:e,metadata:{launchSession:!0}},this.appSyncClient,n);this.sessionKey=o.sessionKey,this.sessionState={sessionId:i,userId:s,projectPath:e,cwd:e,createdAt:new Date,subscriptionActive:!1,metadata:{launchSession:!0},codexSessionId:t,codexLogFile:void 0},this.subscribeToMobileEvents(i),this.appSyncClient.startHeartbeat(i),n.info("Launch session created",{sessionId:i})}catch(o){n.error("Failed to create launch session (non-fatal)",{error:o})}}async handleEventFromHook(t){let{session_id:e,hook_event_name:i,type:s,content:o,metadata:r}=t;if(this.hooksActive=!0,n.info("[Hooks] Received event",{sessionId:e,hookEvent:i,type:s,contentLength:o?.length}),i==="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(a=>n.warn("Failed to update session metadata",{error:a}));else{let a={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(a)}return}if(!this.sessionState){n.warn("[Hooks] Session not initialized, buffering event",{hook_event_name:i});return}let p=this.sessionState.sessionId;if(s==="USER_PROMPT"&&o&&this.isRecentMobilePrompt(o)){n.info("[Hooks] Skipping duplicate USER_PROMPT from mobile");return}if(i==="PreToolUse"){let a=r?.tool_name||"unknown",d=r?.tool_input,u={tool_name:this.mapToolName(a),tool_input:d||{}};if(a==="apply_patch"&&typeof d=="string"){let{extractOldNewFromPatch:x,extractFileFromPatch:D}=(j(),Tt(pt)),w=x(d),U=D(d);w&&(u.tool_input={file_path:U||"",old_string:w.oldString,new_string:w.newString})}let h=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(h)try{await new Promise(U=>setTimeout(U,500));let{execSync:x}=require("child_process"),D=x(`tmux capture-pane -p -e -S -30 -t '${h}'`,{timeout:5e3,encoding:"utf8"}),w=(0,_.parseInteractivePrompt)(D);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,P=u,b=!1;this.sessionKey&&(m=c.cryptoService.encryptContent(o,this.sessionKey),P={encrypted:c.cryptoService.encryptMetadata(u,this.sessionKey)},b=!0),await this.appSyncClient.createEvent({sessionId:p,type:c.EventType.INTERACTIVE_PROMPT,source:c.EventSource.DESKTOP,content:m,metadata:P,isEncrypted:b}),this.pendingInteractivePrompt={promptId:(0,X.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:a,sessionId:p});return}if(i==="PostToolUse"){let a=o,d=r,u=!1;this.sessionKey&&(a=c.cryptoService.encryptContent(o,this.sessionKey),r&&(d={encrypted:c.cryptoService.encryptMetadata(r,this.sessionKey)}),u=!0),await this.appSyncClient.createEvent({sessionId:p,type:c.EventType.TOOL_USE,source:c.EventSource.DESKTOP,content:a,metadata:d,isEncrypted:u});return}if(s==="ASSISTANT_RESPONSE"||s==="USER_PROMPT"){let a=o,d=!1;this.sessionKey&&o&&(a=c.cryptoService.encryptContent(o,this.sessionKey),d=!0),await this.appSyncClient.createEvent({sessionId:p,type:s==="ASSISTANT_RESPONSE"?c.EventType.ASSISTANT_RESPONSE:c.EventType.USER_PROMPT,source:c.EventSource.DESKTOP,content:a,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(),i=this.generateSessionId(t.id),s=this.appSyncClient.getCurrentUserId(),o={codexSessionId:t.id,cliVersion:t.cli_version,modelProvider:t.model_provider};try{let r=await(0,c.resumeOrCreateSession)({sessionId:i,userId:s,agentType:c.AgentType.CODEX,projectPath:e,metadata:o},this.appSyncClient,n);this.sessionKey=r.sessionKey}catch(r){throw n.error("Failed to create/resume session:",r),r}try{this.sessionState={sessionId:i,userId:s,projectPath:e,cwd:t.cwd,createdAt:new Date,subscriptionActive:!1,metadata:o,codexSessionId:t.id,codexLogFile:this.sessionWatcher.getActiveLogFile()||void 0},await this.flushBufferedLogEntries(),await this.startTmuxObserver(),this.subscribeToMobileEvents(i),this.appSyncClient.startHeartbeat(i)}catch(r){n.error("Failed to create session:",r),this.bufferedLogEntries=[]}finally{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 i=t.payload.type;i==="function_call"||i==="custom_tool_call"?this.approvalDetector.onToolCallStart(t.payload.call_id,t.payload.name,t.payload.arguments||t.payload.input||""):(i==="function_call_output"||i==="custom_tool_call_output")&&(this.approvalDetector.onToolCallComplete(t.payload.call_id),this.pendingInteractivePrompt?.callId===t.payload.call_id&&(this.pendingInteractivePrompt=null))}let e=K(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 i=t.payload?.type;if((i==="function_call"||i==="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 i=c.cryptoService.encryptMetadata(e.metadata,this.sessionKey);e.metadata={encrypted:i}}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(i){n.error("Failed to sync event:",i)}}}async handleApprovalPending(t){if(this.sessionState){n.info("Sending approval pending interactive prompt",t);try{let e=await this.tryParseInteractivePromptFromTmux(),i=e?.parsedPrompt??null;if(i&&this.pendingInteractivePrompt&&this.pendingInteractivePrompt.source==="tmux"&&this.pendingInteractivePrompt.promptText===i.promptText){n.debug("Skipping heuristic prompt because tmux prompt is already active",{promptText:i.promptText});return}let s=this.buildToolDetailsForInteractivePrompt(t,e?.snapshot),o=s.tool_name||this.mapToolNameForApproval(t.toolName),r=s.tool_input||this.buildFallbackToolInput(t),p=!!(o&&r),a=this.buildPromptPresentation(i),d=a.options,u=t.filePath?`File: ${t.filePath}`:void 0,h=a.content||`Codex is waiting for approval.
10
10
  ${t.hint}`;u&&!h.includes(u)&&(h=`${h}
11
- ${u}`),this.pendingInteractivePrompt={promptId:t.callId,callId:t.callId,kind:l.kind,options:d,submitMap:l.submitMap,promptText:l.promptText,createdAt:Date.now(),source:i?"tmux":"heuristic",requiresFollowUpText:l.requiresFollowUpText};let m={isApprovalHint:!0,toolName:t.toolName,toolInput:t.toolInput,hint:t.hint,callId:t.callId,filePath:t.filePath,diff:t.diff,rawInput:t.rawInput,tool_name:r,tool_input:o,has_details:a,options:d,instructions:l.instructions,prompt_source:i?"tmux":"heuristic"},P=!1;s.debug("Interactive prompt (pre-encryption)",{sessionId:this.sessionState.sessionId,callId:t.callId,contentPreview:h.substring(0,200),toolDetails:n,metadata:m}),this.sessionKey&&(h=c.cryptoService.encryptContent(h,this.sessionKey),m={encrypted:c.cryptoService.encryptMetadata(m,this.sessionKey)},P=!0),await this.appSyncClient.createEvent({sessionId:this.sessionState.sessionId,type:c.EventType.INTERACTIVE_PROMPT,source:c.EventSource.DESKTOP,content:h,metadata:m,promptId:t.callId,...P?{isEncrypted:!0}:{}})}catch(e){s.error("Failed to send approval interactive prompt:",e)}}}async handleTmuxPromptCandidate(t){if(!this.sessionState)return;let e=(0,b.parseInteractivePrompt)(t);if(!e||this.pendingInteractivePrompt&&this.pendingInteractivePrompt.source==="tmux"&&this.pendingInteractivePrompt.promptText===e.promptText)return;let i=this.buildPromptPresentation(e),n=this.getMostRecentPendingToolCall();n||(await new Promise(I=>setTimeout(I,500)),n=this.getMostRecentPendingToolCall());let r=n?this.buildApprovalPromptContextFromPendingCall(n):null,o=r?this.buildToolDetailsForInteractivePrompt(r,t):{},a=o.tool_name||this.mapToolNameForApproval(n?.name),l=o.tool_input||(r?this.buildFallbackToolInput(r):void 0),d=!!(a&&l),u=this.pendingInteractivePrompt?.callId||n?.callId||(0,it.v4)();this.pendingInteractivePrompt={promptId:u,callId:this.pendingInteractivePrompt?.callId||n?.callId,kind:i.kind,options:i.options,submitMap:i.submitMap,promptText:i.promptText,createdAt:Date.now(),source:"tmux",requiresFollowUpText:i.requiresFollowUpText};let h={options:i.options,instructions:i.instructions,prompt_source:"tmux_live",tool_name:a,tool_input:l,has_details:d},m=i.content,P=!1;this.sessionKey&&(m=c.cryptoService.encryptContent(m,this.sessionKey),h={encrypted:c.cryptoService.encryptMetadata(h,this.sessionKey)},P=!0);try{await this.appSyncClient.createEvent({sessionId:this.sessionState.sessionId,type:c.EventType.INTERACTIVE_PROMPT,source:c.EventSource.DESKTOP,content:m,metadata:h,promptId:u,...P?{isEncrypted:!0}:{}}),s.info("Sent tmux-detected interactive prompt",{sessionId:this.sessionState.sessionId,promptText:e.promptText,kind:e.kind})}catch(I){s.error("Failed to send tmux-detected interactive prompt",{error:I})}}async startTmuxObserver(){let t=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!t){s.debug("Skipping tmux pane observer start - no tmux session in environment");return}try{await this.tmuxPaneObserver.start(t)}catch(e){s.warn("Failed to start tmux pane observer",{tmuxSession:t,error:e})}}async tryParseInteractivePromptFromTmux(){try{let t=await this.tmuxPaneObserver.captureSnapshot(),e=(0,b.parseInteractivePrompt)(t);return s.debug("tmux prompt parse result",{parsed:!!e,kind:e?.kind,promptText:e?.promptText,snapshotPreview:this.summarizePromptSnapshot(t)}),{parsedPrompt:e,snapshot:t}}catch(t){return s.debug("tmux prompt parsing unavailable",{error:t}),null}}buildPromptPresentation(t){return t?{content:t.promptText,promptText:t.promptText,kind:t.kind,options:t.options,submitMap:t.submitMap,instructions:this.buildPromptInstructions(t),requiresFollowUpText:t.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 t=this.approvalDetector.getPendingCalls();return t.length===0?null:t.reduce((e,i)=>i.timestamp>e.timestamp?i:e)}buildApprovalPromptContextFromPendingCall(t){return{toolName:t.name,filePath:t.filePath,diff:t.diff,toolInput:t.parsedInput,rawInput:t.input,hint:t.filePath?`File: ${t.filePath}`:`Tool: ${this.mapToolNameForApproval(t.name)||t.name}`}}buildPromptInstructions(t){return t.kind==="yes_no"&&t.requiresFollowUpText?"Reply with 1 to approve, or 2 followed by what to change":t.kind==="yes_no"?"Reply with 1 for yes or 2 for no":t.kind==="numbered"?"Reply with the number of the option you want":"Reply with your response"}summarizePromptSnapshot(t){return t.split(`
11
+ ${u}`),this.pendingInteractivePrompt={promptId:t.callId,callId:t.callId,kind:a.kind,options:d,submitMap:a.submitMap,promptText:a.promptText,createdAt:Date.now(),source:i?"tmux":"heuristic",requiresFollowUpText:a.requiresFollowUpText};let m={isApprovalHint:!0,toolName:t.toolName,toolInput:t.toolInput,hint:t.hint,callId:t.callId,filePath:t.filePath,diff:t.diff,rawInput:t.rawInput,tool_name:o,tool_input:r,has_details:p,options:d,instructions:a.instructions,prompt_source:i?"tmux":"heuristic"},P=!1;n.debug("Interactive prompt (pre-encryption)",{sessionId:this.sessionState.sessionId,callId:t.callId,contentPreview:h.substring(0,200),toolDetails:s,metadata:m}),this.sessionKey&&(h=c.cryptoService.encryptContent(h,this.sessionKey),m={encrypted:c.cryptoService.encryptMetadata(m,this.sessionKey)},P=!0),await this.appSyncClient.createEvent({sessionId:this.sessionState.sessionId,type:c.EventType.INTERACTIVE_PROMPT,source:c.EventSource.DESKTOP,content:h,metadata:m,promptId:t.callId,...P?{isEncrypted:!0}:{}})}catch(e){n.error("Failed to send approval interactive prompt:",e)}}}async handleTmuxPromptCandidate(t){if(!this.sessionState)return;let e=(0,_.parseInteractivePrompt)(t);if(!e||this.pendingInteractivePrompt&&this.pendingInteractivePrompt.source==="tmux"&&this.pendingInteractivePrompt.promptText===e.promptText)return;let i=this.buildPromptPresentation(e),s=this.getMostRecentPendingToolCall();s||(await new Promise(b=>setTimeout(b,500)),s=this.getMostRecentPendingToolCall());let o=s?this.buildApprovalPromptContextFromPendingCall(s):null,r=o?this.buildToolDetailsForInteractivePrompt(o,t):{},p=r.tool_name||this.mapToolNameForApproval(s?.name),a=r.tool_input||(o?this.buildFallbackToolInput(o):void 0),d=!!(p&&a),u=this.pendingInteractivePrompt?.callId||s?.callId||(0,X.v4)();this.pendingInteractivePrompt={promptId:u,callId:this.pendingInteractivePrompt?.callId||s?.callId,kind:i.kind,options:i.options,submitMap:i.submitMap,promptText:i.promptText,createdAt:Date.now(),source:"tmux",requiresFollowUpText:i.requiresFollowUpText};let h={options:i.options,instructions:i.instructions,prompt_source:"tmux_live",tool_name:p,tool_input:a,has_details:d},m=i.content,P=!1;this.sessionKey&&(m=c.cryptoService.encryptContent(m,this.sessionKey),h={encrypted:c.cryptoService.encryptMetadata(h,this.sessionKey)},P=!0);try{await this.appSyncClient.createEvent({sessionId:this.sessionState.sessionId,type:c.EventType.INTERACTIVE_PROMPT,source:c.EventSource.DESKTOP,content:m,metadata:h,promptId:u,...P?{isEncrypted:!0}:{}}),n.info("Sent tmux-detected interactive prompt",{sessionId:this.sessionState.sessionId,promptText:e.promptText,kind:e.kind})}catch(b){n.error("Failed to send tmux-detected interactive prompt",{error:b})}}async startTmuxObserver(){let t=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!t){n.debug("Skipping tmux pane observer start - no tmux session in environment");return}try{await this.tmuxPaneObserver.start(t)}catch(e){n.warn("Failed to start tmux pane observer",{tmuxSession:t,error:e})}}async tryParseInteractivePromptFromTmux(){try{let t=await this.tmuxPaneObserver.captureSnapshot(),e=(0,_.parseInteractivePrompt)(t);return n.debug("tmux prompt parse result",{parsed:!!e,kind:e?.kind,promptText:e?.promptText,snapshotPreview:this.summarizePromptSnapshot(t)}),{parsedPrompt:e,snapshot:t}}catch(t){return n.debug("tmux prompt parsing unavailable",{error:t}),null}}buildPromptPresentation(t){return t?{content:t.promptText,promptText:t.promptText,kind:t.kind,options:t.options,submitMap:t.submitMap,instructions:this.buildPromptInstructions(t),requiresFollowUpText:t.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 t=this.approvalDetector.getPendingCalls();return t.length===0?null:t.reduce((e,i)=>i.timestamp>e.timestamp?i:e)}buildApprovalPromptContextFromPendingCall(t){return{toolName:t.name,filePath:t.filePath,diff:t.diff,toolInput:t.parsedInput,rawInput:t.input,hint:t.filePath?`File: ${t.filePath}`:`Tool: ${this.mapToolNameForApproval(t.name)||t.name}`}}buildPromptInstructions(t){return t.kind==="yes_no"&&t.requiresFollowUpText?"Reply with 1 to approve, or 2 followed by what to change":t.kind==="yes_no"?"Reply with 1 for yes or 2 for no":t.kind==="numbered"?"Reply with the number of the option you want":"Reply with your response"}summarizePromptSnapshot(t){return t.split(`
12
12
  `).map(e=>e.trimEnd()).filter(e=>e.length>0).slice(-12).map(e=>e.slice(0,160)).join(`
13
- `)}translatePromptResponse(t){let e=this.pendingInteractivePrompt;if(!e)return{primaryInput:t};let n=t.trim().match(/^(\d+)(?:[,.:;\-\s]+([\s\S]+))?$/);if(!n)return{primaryInput:t};let r=n[1],o=n[2]?.trim(),a=e.submitMap[r];return a?e.requiresFollowUpText&&o?{primaryInput:a,followUpInput:o}:{primaryInput:a}:{primaryInput:t}}buildToolDetailsForInteractivePrompt(t,e){let i=t.toolName,n=t.toolInput&&typeof t.toolInput=="object"?t.toolInput:void 0;if(i==="apply_patch"){let o=t.diff||t.rawInput;if(o){let{oldString:a,newString:l,oldStartLine:d,newStartLine:u}=this.extractOldNewFromPatch(o),h=e?this.extractDiffLineAnchorsFromSnapshot(e):{};return{tool_name:"Edit",tool_input:{file_path:t.filePath,content:o,diff:t.diff,raw_patch:t.rawInput,old_string:a,new_string:l,old_start_line:d??h.oldStartLine,new_start_line:u??h.newStartLine}}}}if(i==="shell_command"||i==="shell"){let o=n?.command||t.rawInput||t.hint;if(o)return{tool_name:"Bash",tool_input:{command:o,output:n?.output}}}let r={};return t.filePath&&(r.file_path=t.filePath),t.diff&&(r.diff=t.diff),t.rawInput&&(r.raw_input=t.rawInput),Object.keys(r).length>0?{tool_name:i||"Tool",tool_input:r}:{}}buildFallbackToolInput(t){let e={};return t.filePath&&(e.file_path=t.filePath),t.diff&&(e.diff=t.diff),t.rawInput&&(e.raw_input=t.rawInput),t.toolInput&&typeof t.toolInput=="object"&&(e.parsed_input=t.toolInput),Object.keys(e).length>0?e:void 0}mapToolNameForApproval(t){return t?{apply_patch:"Edit",shell_command:"Bash",shell:"Bash"}[t]||t:void 0}extractOldNewFromPatch(t){let e=[],i=[],n=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/,r=0,o=0,a=0,l,d;for(let u of t.split(`
14
- `)){let h=u.match(n);if(h){r+=1,o=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=o),e.push(u.slice(1)),o+=1;else if(u.startsWith("+"))d===void 0&&(d=a),i.push(u.slice(1)),a+=1;else if(u.startsWith(" ")){let m=u.slice(1);e.push(m),i.push(m),o+=1,a+=1}}}return{oldString:e.join(`
13
+ `)}translatePromptResponse(t){let e=this.pendingInteractivePrompt;if(!e)return{primaryInput:t};let s=t.trim().match(/^(\d+)(?:[,.:;\-\s]+([\s\S]+))?$/);if(!s)return{primaryInput:t};let o=s[1],r=s[2]?.trim(),p=e.submitMap[o];return p?e.requiresFollowUpText&&r?{primaryInput:p,followUpInput:r}:{primaryInput:p}:{primaryInput:t}}buildToolDetailsForInteractivePrompt(t,e){let i=t.toolName,s=t.toolInput&&typeof t.toolInput=="object"?t.toolInput:void 0;if(i==="apply_patch"){let r=t.diff||t.rawInput;if(r){let{oldString:p,newString:a,oldStartLine:d,newStartLine:u}=this.extractOldNewFromPatch(r),h=e?this.extractDiffLineAnchorsFromSnapshot(e):{};return{tool_name:"Edit",tool_input:{file_path:t.filePath,content:r,diff:t.diff,raw_patch:t.rawInput,old_string:p,new_string:a,old_start_line:d??h.oldStartLine,new_start_line:u??h.newStartLine}}}}if(i==="shell_command"||i==="shell"){let r=s?.command||t.rawInput||t.hint;if(r)return{tool_name:"Bash",tool_input:{command:r,output:s?.output}}}let o={};return t.filePath&&(o.file_path=t.filePath),t.diff&&(o.diff=t.diff),t.rawInput&&(o.raw_input=t.rawInput),Object.keys(o).length>0?{tool_name:i||"Tool",tool_input:o}:{}}buildFallbackToolInput(t){let e={};return t.filePath&&(e.file_path=t.filePath),t.diff&&(e.diff=t.diff),t.rawInput&&(e.raw_input=t.rawInput),t.toolInput&&typeof t.toolInput=="object"&&(e.parsed_input=t.toolInput),Object.keys(e).length>0?e:void 0}mapToolNameForApproval(t){return t?{apply_patch:"Edit",shell_command:"Bash",shell:"Bash"}[t]||t:void 0}extractOldNewFromPatch(t){let e=[],i=[],s=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/,o=0,r=0,p=0,a,d;for(let u of t.split(`
14
+ `)){let h=u.match(s);if(h){o+=1,r=Number.parseInt(h[1],10),p=Number.parseInt(h[2],10);continue}if(!(u.startsWith("***")||u.startsWith("---")||u.startsWith("+++")||u.startsWith("*** End Patch"))){if(u.startsWith("-"))a===void 0&&(a=r),e.push(u.slice(1)),r+=1;else if(u.startsWith("+"))d===void 0&&(d=p),i.push(u.slice(1)),p+=1;else if(u.startsWith(" ")){let m=u.slice(1);e.push(m),i.push(m),r+=1,p+=1}}}return{oldString:e.join(`
15
15
  `),newString:i.join(`
16
- `),oldStartLine:r===1?l:void 0,newStartLine:r===1?d:void 0}}extractDiffLineAnchorsFromSnapshot(t){let e=(0,b.normalizeSnapshot)(t),i,n;for(let r of e.split(`
17
- `)){let o=r.match(/^\s*(\d+)\s+(.*)$/);if(!o)continue;let a=Number.parseInt(o[1],10),l=o[2];if(Number.isFinite(a)){if(l.startsWith("-")){i??=a;continue}if(l.startsWith("+")){n??=a;continue}i??=a,n??=a}}return s.debug("Recovered diff line anchors from tmux snapshot",{oldStartLine:i,newStartLine:n,snapshotPreview:this.summarizePromptSnapshot(t)}),{oldStartLine:i,newStartLine:n}}subscribeToMobileEvents(t){s.info("Subscribing to mobile events",{sessionId:t}),this.unsubscribe&&this.unsubscribe(),this.unsubscribe=this.appSyncClient.subscribeToEvents(t,async e=>{await this.handleMobileEvent(e)},e=>{s.error("Subscription error:",e)}),this.sessionState&&(this.sessionState.subscriptionActive=!0),s.info("Subscribed to mobile events")}async downloadAttachment(t,e,i){try{let n=t.isEncrypted??i??!1;s.info("Downloading attachment",{id:t.id,type:t.type,filename:t.filename,s3Key:t.s3Key,attachmentIsEncrypted:t.isEncrypted,eventIsEncrypted:i,shouldDecrypt:n});let{downloadUrl:r}=await this.appSyncClient.getAttachmentDownloadUrl(t.s3Key),o=await fetch(r);if(!o.ok)throw new Error(`Failed to download attachment: ${o.status} ${o.statusText}`);let a=Buffer.from(await o.arrayBuffer());if(n&&this.sessionKey)try{s.info("Decrypting attachment",{id:t.id}),a=c.cryptoService.decryptData(a,this.sessionKey),s.info("Attachment decrypted successfully",{id:t.id,decryptedSize:a.length})}catch(m){throw s.error("Failed to decrypt attachment:",{id:t.id,error:m}),new Error("Failed to decrypt attachment")}else n&&!this.sessionKey&&s.warn("Cannot decrypt attachment - no session key available",{id:t.id});let l=x.join(nt.tmpdir(),"codevibe-codex",e);w.existsSync(l)||w.mkdirSync(l,{recursive:!0});let d="";if(t.filename){let m=x.extname(t.filename);m&&(d=m)}d||(d={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"}[t.type]||".bin");let u=`attachment-${t.id}${d}`,h=x.join(l,u);return w.writeFileSync(h,a),s.info("Attachment saved to temp file",{id:t.id,filePath:h,size:a.length}),h}catch(n){return s.error("Failed to download attachment:",{id:t.id,error:n}),null}}async handleMobileEvent(t){if(t.attachments&&t.attachments.length>0&&s.info("DEBUG: Raw attachment data from subscription",{attachments:JSON.stringify(t.attachments),eventIsEncrypted:t.isEncrypted}),s.info("Received mobile event",{eventId:t.eventId,type:t.type,content:t.content?.substring(0,50),attachmentCount:t.attachments?.length||0,isEncrypted:t.isEncrypted}),!this.sessionState){s.warn("Received mobile event but no active session");return}let e=t.content||"";if(t.isEncrypted&&this.sessionKey)try{e=c.cryptoService.decryptContent(t.content,this.sessionKey),s.debug("Event decrypted successfully",{eventId:t.eventId})}catch(i){s.error("Failed to decrypt event:",{eventId:t.eventId,error:i}),e=t.content}try{await this.appSyncClient.updateEventStatus({eventId:t.eventId,sessionId:t.sessionId,timestamp:t.timestamp,deliveryStatus:c.DeliveryStatus.DELIVERED})}catch(i){s.error("Failed to update delivery status:",i)}if(t.type===c.EventType.USER_PROMPT||t.type===c.EventType.PROMPT_RESPONSE){let i=e,n=t.attachments||[],r=[];if(n.length>0){s.info("Downloading attachments for prompt",{count:n.length});for(let l of n){let d=await this.downloadAttachment(l,this.sessionState.sessionId,t.isEncrypted);d&&r.push(d)}if(r.length>0){let l=r.map(d=>`[Attached file: ${d}]`).join(`
18
- `);i?i=`${l}
16
+ `),oldStartLine:o===1?a:void 0,newStartLine:o===1?d:void 0}}extractDiffLineAnchorsFromSnapshot(t){let e=(0,_.normalizeSnapshot)(t),i,s;for(let o of e.split(`
17
+ `)){let r=o.match(/^\s*(\d+)\s+(.*)$/);if(!r)continue;let p=Number.parseInt(r[1],10),a=r[2];if(Number.isFinite(p)){if(a.startsWith("-")){i??=p;continue}if(a.startsWith("+")){s??=p;continue}i??=p,s??=p}}return n.debug("Recovered diff line anchors from tmux snapshot",{oldStartLine:i,newStartLine:s,snapshotPreview:this.summarizePromptSnapshot(t)}),{oldStartLine:i,newStartLine:s}}subscribeToMobileEvents(t){if(this.subscribedSessionId===t){n.info("Already subscribed to mobile events, skipping",{sessionId:t});return}if(n.info("Subscribing to mobile events",{sessionId:t}),this.unsubscribe){try{this.unsubscribe()}catch(e){n.warn("Error cleaning up previous subscription (non-fatal)",{error:e})}this.subscribedSessionId=null}try{this.unsubscribe=this.appSyncClient.subscribeToEvents(t,async e=>{await this.handleMobileEvent(e)},e=>{n.error("Subscription error:",e)}),this.subscribedSessionId=t}catch(e){n.error("Failed to subscribe to mobile events (non-fatal)",{sessionId:t,error:e});return}this.sessionState&&(this.sessionState.subscriptionActive=!0),n.info("Subscribed to mobile events")}async downloadAttachment(t,e,i){try{let s=t.isEncrypted??i??!1;n.info("Downloading attachment",{id:t.id,type:t.type,filename:t.filename,s3Key:t.s3Key,attachmentIsEncrypted:t.isEncrypted,eventIsEncrypted:i,shouldDecrypt:s});let{downloadUrl:o}=await this.appSyncClient.getAttachmentDownloadUrl(t.s3Key),r=await fetch(o);if(!r.ok)throw new Error(`Failed to download attachment: ${r.status} ${r.statusText}`);let p=Buffer.from(await r.arrayBuffer());if(s&&this.sessionKey)try{n.info("Decrypting attachment",{id:t.id}),p=c.cryptoService.decryptData(p,this.sessionKey),n.info("Attachment decrypted successfully",{id:t.id,decryptedSize:p.length})}catch(m){throw n.error("Failed to decrypt attachment:",{id:t.id,error:m}),new Error("Failed to decrypt attachment")}else s&&!this.sessionKey&&n.warn("Cannot decrypt attachment - no session key available",{id:t.id});let a=C.join(St.tmpdir(),"codevibe-codex",e);T.existsSync(a)||T.mkdirSync(a,{recursive:!0});let d="";if(t.filename){let m=C.extname(t.filename);m&&(d=m)}d||(d={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"}[t.type]||".bin");let u=`attachment-${t.id}${d}`,h=C.join(a,u);return T.writeFileSync(h,p),n.info("Attachment saved to temp file",{id:t.id,filePath:h,size:p.length}),h}catch(s){return n.error("Failed to download attachment:",{id:t.id,error:s}),null}}async handleMobileEvent(t){if(t.attachments&&t.attachments.length>0&&n.info("DEBUG: Raw attachment data from subscription",{attachments:JSON.stringify(t.attachments),eventIsEncrypted:t.isEncrypted}),n.info("Received mobile event",{eventId:t.eventId,type:t.type,content:t.content?.substring(0,50),attachmentCount:t.attachments?.length||0,isEncrypted:t.isEncrypted}),!this.sessionState){n.warn("Received mobile event but no active session");return}let e=t.content||"";if(t.isEncrypted&&this.sessionKey)try{e=c.cryptoService.decryptContent(t.content,this.sessionKey),n.debug("Event decrypted successfully",{eventId:t.eventId})}catch(i){n.error("Failed to decrypt event:",{eventId:t.eventId,error:i}),e=t.content}try{await this.appSyncClient.updateEventStatus({eventId:t.eventId,sessionId:t.sessionId,timestamp:t.timestamp,deliveryStatus:c.DeliveryStatus.DELIVERED})}catch(i){n.error("Failed to update delivery status:",i)}if(t.type===c.EventType.USER_PROMPT||t.type===c.EventType.PROMPT_RESPONSE){let i=e,s=t.attachments||[],o=[];if(s.length>0){n.info("Downloading attachments for prompt",{count:s.length});for(let a of s){let d=await this.downloadAttachment(a,this.sessionState.sessionId,t.isEncrypted);d&&o.push(d)}if(o.length>0){let a=o.map(d=>`[Attached file: ${d}]`).join(`
18
+ `);i?i=`${a}
19
19
 
20
- ${i}`:i=`${l}
20
+ ${i}`:i=`${a}
21
21
 
22
- Please analyze the attached file(s).`,s.info("Prompt updated with attachment paths",{attachmentCount:r.length,newPromptLength:i.length})}}let o=this.translatePromptResponse(i),a=await this.promptResponder.sendInput(this.sessionState.sessionId,o.primaryInput);if(a&&o.followUpInput&&await this.promptResponder.sendInput(this.sessionState.sessionId,o.followUpInput),a&&this.pendingInteractivePrompt&&t.type===c.EventType.PROMPT_RESPONSE&&(this.pendingInteractivePrompt=null),a)try{await this.appSyncClient.updateEventStatus({eventId:t.eventId,sessionId:t.sessionId,timestamp:t.timestamp,deliveryStatus:c.DeliveryStatus.EXECUTED})}catch(l){s.error("Failed to update executed status:",l)}}}generateSessionId(t){return`codex-${t}`}async endActiveSession(t){if(this.sessionState){s.info("Ending active session",{sessionId:this.sessionState.sessionId,codexSessionId:this.sessionState.codexSessionId,reason:t}),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(e){s.error("Failed to update session status:",e)}this.sessionState=null}}async stop(){s.info("Stopping CodeVibe Codex companion server"),await this.endActiveSession("shutdown"),this.sessionWatcher.stop(),this.approvalDetector.shutdown(),H(),this.appSyncClient.cleanupSubscriptions(),s.info("CodeVibe Codex companion server stopped")}},N=new M;process.on("SIGINT",async()=>{s.info("Received SIGINT, shutting down..."),await N.stop(),process.exit(0)});process.on("SIGTERM",async()=>{s.info("Received SIGTERM, shutting down..."),await N.stop(),process.exit(0)});N.start().catch(p=>{s.error("Failed to start server:",p),process.exit(1)});
22
+ Please analyze the attached file(s).`,n.info("Prompt updated with attachment paths",{attachmentCount:o.length,newPromptLength:i.length})}}let r=this.translatePromptResponse(i),p=await this.promptResponder.sendInput(this.sessionState.sessionId,r.primaryInput);if(p&&r.followUpInput&&await this.promptResponder.sendInput(this.sessionState.sessionId,r.followUpInput),p&&this.pendingInteractivePrompt&&t.type===c.EventType.PROMPT_RESPONSE&&(this.pendingInteractivePrompt=null),p)try{await this.appSyncClient.updateEventStatus({eventId:t.eventId,sessionId:t.sessionId,timestamp:t.timestamp,deliveryStatus:c.DeliveryStatus.EXECUTED})}catch(a){n.error("Failed to update executed status:",a)}}}generateSessionId(t){return`codex-${t}`}async endActiveSession(t){if(this.sessionState){n.info("Ending active session",{sessionId:this.sessionState.sessionId,codexSessionId:this.sessionState.codexSessionId,reason:t}),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(e){n.error("Failed to update session status:",e)}this.sessionState=null}}async stop(){n.info("Stopping CodeVibe Codex companion server"),await this.endActiveSession("shutdown"),this.sessionWatcher.stop(),this.approvalDetector.shutdown(),H(),await this.httpApi.stop(),this.appSyncClient.cleanupSubscriptions(),n.info("CodeVibe Codex companion server stopped")}},J=new G;process.on("SIGINT",async()=>{n.info("Received SIGINT, shutting down..."),await J.stop(),process.exit(0)});process.on("SIGTERM",async()=>{n.info("Received SIGTERM, shutting down..."),await J.stop(),process.exit(0)});J.start().catch(l=>{n.error("Failed to start server:",l),process.exit(1)});
@@ -0,0 +1,69 @@
1
+ #!/bin/bash
2
+
3
+ # Common utilities for CodeVibe Codex hooks
4
+ # Adapted from codevibe-claude-plugin/hooks/common.sh
5
+
6
+ CODEVIBE_TMPDIR="${TMPDIR:-/tmp}"
7
+ LOG_FILE="${LOG_FILE:-${CODEVIBE_TMPDIR}/codevibe-codex-hooks.log}"
8
+
9
+ log() {
10
+ local level="$1"
11
+ shift
12
+ echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] [$level] $*" >> "$LOG_FILE"
13
+ }
14
+
15
+ get_server_url() {
16
+ local port=""
17
+ local port_file="${CODEVIBE_TMPDIR}/codevibe-codex-${CODEVIBE_CODEX_TMUX_SESSION}.port"
18
+ if [ -f "$port_file" ]; then
19
+ port=$(cat "$port_file")
20
+ fi
21
+ if [ -z "$port" ]; then
22
+ log "WARN" "Port file not found: $port_file"
23
+ echo ""
24
+ return 1
25
+ fi
26
+ echo "http://localhost:${port}"
27
+ }
28
+
29
+ read_json_input() {
30
+ cat
31
+ }
32
+
33
+ send_to_server() {
34
+ local endpoint="$1"
35
+ local json_data="$2"
36
+
37
+ local server_url
38
+ server_url=$(get_server_url)
39
+ if [ -z "$server_url" ]; then
40
+ log "ERROR" "No server URL — cannot send event"
41
+ return 1
42
+ fi
43
+
44
+ log "DEBUG" "POST $server_url/$endpoint"
45
+
46
+ local response
47
+ response=$(curl -s -w "\n%{http_code}" \
48
+ -X POST \
49
+ -H "Content-Type: application/json" \
50
+ -d "$json_data" \
51
+ "$server_url/$endpoint" 2>&1)
52
+
53
+ local http_code
54
+ http_code=$(echo "$response" | tail -n 1)
55
+
56
+ if [ "$http_code" = "200" ]; then
57
+ log "INFO" "Sent successfully (HTTP $http_code)"
58
+ return 0
59
+ else
60
+ log "ERROR" "Failed (HTTP $http_code)"
61
+ return 1
62
+ fi
63
+ }
64
+
65
+ export CODEVIBE_TMPDIR
66
+ export -f log
67
+ export -f get_server_url
68
+ export -f read_json_input
69
+ export -f send_to_server
@@ -0,0 +1,59 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ {
5
+ "matcher": "*",
6
+ "hooks": [
7
+ {
8
+ "type": "command",
9
+ "command": "bash $CODEVIBE_CODEX_PLUGIN_DIR/hooks/session-start.sh"
10
+ }
11
+ ]
12
+ }
13
+ ],
14
+ "UserPromptSubmit": [
15
+ {
16
+ "matcher": "*",
17
+ "hooks": [
18
+ {
19
+ "type": "command",
20
+ "command": "bash $CODEVIBE_CODEX_PLUGIN_DIR/hooks/user-prompt.sh"
21
+ }
22
+ ]
23
+ }
24
+ ],
25
+ "PreToolUse": [
26
+ {
27
+ "matcher": "*",
28
+ "hooks": [
29
+ {
30
+ "type": "command",
31
+ "command": "bash $CODEVIBE_CODEX_PLUGIN_DIR/hooks/pre-tool-use.sh"
32
+ }
33
+ ]
34
+ }
35
+ ],
36
+ "PostToolUse": [
37
+ {
38
+ "matcher": "*",
39
+ "hooks": [
40
+ {
41
+ "type": "command",
42
+ "command": "bash $CODEVIBE_CODEX_PLUGIN_DIR/hooks/post-tool-use.sh"
43
+ }
44
+ ]
45
+ }
46
+ ],
47
+ "Stop": [
48
+ {
49
+ "matcher": "*",
50
+ "hooks": [
51
+ {
52
+ "type": "command",
53
+ "command": "bash $CODEVIBE_CODEX_PLUGIN_DIR/hooks/stop.sh"
54
+ }
55
+ ]
56
+ }
57
+ ]
58
+ }
59
+ }
@@ -0,0 +1,10 @@
1
+ #!/bin/bash
2
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
3
+ source "$SCRIPT_DIR/common.sh"
4
+
5
+ log "INFO" "PostToolUse hook triggered"
6
+
7
+ INPUT=$(read_json_input)
8
+ log "DEBUG" "Payload: $INPUT"
9
+
10
+ send_to_server "event" "$INPUT"
@@ -0,0 +1,10 @@
1
+ #!/bin/bash
2
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
3
+ source "$SCRIPT_DIR/common.sh"
4
+
5
+ log "INFO" "PreToolUse hook triggered"
6
+
7
+ INPUT=$(read_json_input)
8
+ log "DEBUG" "Payload: $INPUT"
9
+
10
+ send_to_server "event" "$INPUT"
@@ -0,0 +1,10 @@
1
+ #!/bin/bash
2
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
3
+ source "$SCRIPT_DIR/common.sh"
4
+
5
+ log "INFO" "SessionStart hook triggered"
6
+
7
+ INPUT=$(read_json_input)
8
+ log "DEBUG" "Payload: $INPUT"
9
+
10
+ send_to_server "event" "$INPUT"
package/hooks/stop.sh ADDED
@@ -0,0 +1,10 @@
1
+ #!/bin/bash
2
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
3
+ source "$SCRIPT_DIR/common.sh"
4
+
5
+ log "INFO" "Stop hook triggered"
6
+
7
+ INPUT=$(read_json_input)
8
+ log "DEBUG" "Payload: $INPUT"
9
+
10
+ send_to_server "event" "$INPUT"
@@ -0,0 +1,10 @@
1
+ #!/bin/bash
2
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
3
+ source "$SCRIPT_DIR/common.sh"
4
+
5
+ log "INFO" "UserPromptSubmit hook triggered"
6
+
7
+ INPUT=$(read_json_input)
8
+ log "DEBUG" "Payload: $INPUT"
9
+
10
+ send_to_server "event" "$INPUT"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quantiya/codevibe-codex-plugin",
3
- "version": "1.0.13",
3
+ "version": "1.0.14",
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": {