@quantiya/codevibe-codex-plugin 2.0.11 → 2.0.13
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 +31 -24
- package/libexec/codex-hook-config.js +190 -0
- package/libexec/companion-launcher +9 -158
- package/node_modules/fs-ext/build/Makefile +2 -2
- package/node_modules/fs-ext/build/Release/fs_ext.node +0 -0
- package/node_modules/fs-ext/build/Release/obj.target/fs_ext/fs-ext.o +0 -0
- package/node_modules/fs-ext/build/config.gypi +1 -1
- package/package.json +4 -1
- package/node_modules/@iarna/toml/CHANGELOG.md +0 -278
- package/node_modules/color-convert/CHANGELOG.md +0 -54
- package/node_modules/deep-extend/CHANGELOG.md +0 -46
- package/node_modules/es-toolkit/CHANGELOG.md +0 -810
- package/node_modules/es-toolkit/src/compat/_internal/Equals.d.ts +0 -1
- package/node_modules/es-toolkit/src/compat/_internal/IsWritable.d.ts +0 -3
- package/node_modules/es-toolkit/src/compat/_internal/MutableList.d.ts +0 -4
- package/node_modules/es-toolkit/src/compat/_internal/RejectReadonly.d.ts +0 -4
- package/node_modules/keytar/build/Release/keytar.node +0 -0
- package/node_modules/which/CHANGELOG.md +0 -166
package/dist/server.js
CHANGED
|
@@ -1,36 +1,43 @@
|
|
|
1
|
-
"use strict";var tt=Object.create;var W=Object.defineProperty;var it=Object.getOwnPropertyDescriptor;var st=Object.getOwnPropertyNames;var rt=Object.getPrototypeOf,nt=Object.prototype.hasOwnProperty;var ot=(p,t)=>{for(var e in t)W(p,e,{get:t[e],enumerable:!0})},we=(p,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of st(t))!nt.call(p,s)&&s!==e&&W(p,s,{get:()=>t[s],enumerable:!(i=it(t,s))||i.enumerable});return p};var E=(p,t,e)=>(e=p!=null?tt(rt(p)):{},we(t||!p||!p.__esModule?W(e,"default",{value:p,enumerable:!0}):e,p)),at=p=>we(W({},"__esModule",{value:!0}),p);var Xt={};ot(Xt,{CodexCompanionServer:()=>se,extractShellCommandFromPromptText:()=>et,extractShellCommandPartsFromPromptText:()=>Se});module.exports=at(Xt);var Je=require("uuid"),ye=E(require("crypto")),D=E(require("fs")),z=E(require("path")),Qe=E(require("os")),ve=require("util"),re=require("child_process"),u=require("@quantiya/codevibe-core");var Ie=E(require("os")),Pe=E(require("path")),_e=require("@quantiya/codevibe-core"),n=(0,_e.createLogger)({name:"codevibe-codex",logFile:Pe.default.join(Ie.default.tmpdir(),"codevibe-codex-mcp.log"),level:"debug"});var Ee=require("events"),b=E(require("fs")),C=E(require("path")),Te=require("string_decoder"),xe=require("chokidar"),Re=require("@quantiya/codevibe-core");var le=256*1024,lt=64*1024*1024,ct=16*1024*1024,pt=64*1024,j=class extends Ee.EventEmitter{constructor(e={}){super();this.watcher=null;this.filePositions=new Map;this.activeLogFile=null;this.sessionId=null;this.isWatching=!1;this.startTime=0;this.sessionsDir=null;this.activeReads=new Map;this.pendingReads=new Set;this.readGeneration=0;this.oversizedRecordFiles=new Set;this.fileIdentities=new Map;this.bindSource=null;this.authoritativeSessionId=null;this.pendingTranscriptBind=null;this.transcriptBindGeneration=0;this.transcriptBindingsClosed=!1;this.activeTranscriptAdmissions=new Set;this.startBaselines=new Map;if(this.maxBacklogBytes=e.maxBacklogBytes??lt,this.maxRecordBytes=e.maxRecordBytes??ct,!Number.isSafeInteger(this.maxBacklogBytes)||this.maxBacklogBytes<=0)throw new RangeError("maxBacklogBytes must be a positive safe integer");if(!Number.isSafeInteger(this.maxRecordBytes)||this.maxRecordBytes<=0)throw new RangeError("maxRecordBytes must be a positive safe integer")}start(){if(this.isWatching){n.warn("Session log watcher already running");return}this.transcriptBindGeneration++,this.transcriptBindingsClosed=!1;let e=(0,Re.getConfig)().codex.sessionsDir;this.sessionsDir=e,n.info("Starting Codex session log watcher",{sessionsDir:e}),b.existsSync(e)||(n.info("Codex sessions directory does not exist yet, creating...",{sessionsDir:e}),b.mkdirSync(e,{recursive:!0})),this.startTime=Date.now(),this.readGeneration++,this.bindSource=null,this.authoritativeSessionId=null,this.snapshotStartBaselines(e),this.drainPendingTranscriptBind(),this.watcher=(0,xe.watch)(e,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},depth:4,ignored:i=>{let s=C.basename(i);return b.existsSync(i)&&b.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.activeLogFile||n.debug("No authoritative transcript hook received yet; rollout watcher remains fail-closed")}),this.isWatching=!0,n.info("Session log watcher started")}stop(){this.transcriptBindingsClosed=!0,this.transcriptBindGeneration++,this.watcher&&(this.watcher.close(),this.watcher=null),this.isWatching=!1,this.readGeneration++,this.filePositions.clear(),this.activeReads.clear(),this.pendingReads.clear(),this.oversizedRecordFiles.clear(),this.activeLogFile=null,this.sessionId=null,this.sessionsDir=null,this.bindSource=null,this.authoritativeSessionId=null,this.pendingTranscriptBind&&(this.pendingTranscriptBind.resolve({status:"rejected",reason:"watcher_stopped"}),this.pendingTranscriptBind=null),this.startBaselines.clear(),this.fileIdentities.clear(),n.info("Session log watcher stopped")}async waitForTranscriptAdmissions(){for(;this.activeTranscriptAdmissions.size>0;)await Promise.all(Array.from(this.activeTranscriptAdmissions,e=>e.then(()=>{},()=>{})))}getSessionId(){return this.sessionId}getActiveLogFile(){return this.activeLogFile}getBindSource(){return this.bindSource}getAuthoritativeSessionId(){return this.authoritativeSessionId}tryRealpath(e){try{return b.realpathSync(e)}catch{return null}}isInteractiveRollout(e){return!(!e||e.originator==="codex_exec"||e.threadSource==="subagent"||e.sourceSubagent)}identityOf(e){return{dev:e.dev,ino:e.ino}}identitiesEqual(e,i){return e.dev===i.dev&&e.ino===i.ino}computeSeedOffset(e){let i;try{i=b.statSync(e)}catch{return 0}if(this.getSessionAgeMs(e,i)>=this.startTime)return 0;let r=this.startBaselines.get(e);return r&&this.identitiesEqual(r.identity,this.identityOf(i))?r.size:i.size}applyBind(e,i){this.readGeneration++,this.activeReads.delete(e),this.pendingReads.delete(e),this.activeLogFile=e,this.bindSource=i,i==="heuristic"&&(this.authoritativeSessionId=null),this.filePositions.has(e)||this.filePositions.set(e,this.computeSeedOffset(e));try{this.fileIdentities.set(e,this.identityOf(b.statSync(e)))}catch{this.fileIdentities.delete(e)}this.scheduleReadNewLines(e)}bindToFile(e){let i=this.tryRealpath(e);if(!i){n.warn("bindToFile: could not canonicalize path; skipping",{filePath:e});return}if(i===this.activeLogFile){this.bindSource="authoritative";return}n.info("bindToFile: authoritative bind to session rollout",{filePath:i}),this.applyBind(i,"authoritative")}async bindToSessionTranscript(e,i){if(typeof e!="string"||e.length===0)return{status:"rejected",reason:"missing_transcript_path"};if(this.transcriptBindingsClosed)return{status:"rejected",reason:"watcher_stopped"};if(!this.sessionsDir){let s=this.pendingTranscriptBind;if(s)return s.transcriptPath===e&&s.expectedSessionId===i?{status:"pending",completion:s.completion}:(n.warn("bindToSessionTranscript: conflicting startup bind rejected",{transcriptPath:e,expectedSessionId:i,pendingExpectedSessionId:s.expectedSessionId}),{status:"rejected",reason:"conflicting_startup_bind"});let r,o=new Promise(a=>{r=a});return this.pendingTranscriptBind={transcriptPath:e,expectedSessionId:i,completion:o,resolve:r},n.debug("bindToSessionTranscript: watcher not started yet; queued pending authoritative bind",{transcriptPath:e,expectedSessionId:i}),{status:"pending",completion:o}}return this.trackTranscriptAdmission(this.validateAndBindSessionTranscript(e,i,this.transcriptBindGeneration))}trackTranscriptAdmission(e){let i;return i=e.finally(()=>{this.activeTranscriptAdmissions.delete(i)}),this.activeTranscriptAdmissions.add(i),i}isTranscriptAdmissionCurrent(e,i){return!this.transcriptBindingsClosed&&this.transcriptBindGeneration===e&&this.sessionsDir===i}async validateAndBindSessionTranscript(e,i,s){let r=this.sessionsDir;if(!r||!this.isTranscriptAdmissionCurrent(s,r))return{status:"rejected",reason:"watcher_not_started"};let o=this.tryRealpath(e),a=this.tryRealpath(r);if(!o||!a)return{status:"rejected",reason:"canonicalization_failed"};let l=C.relative(a,o);if(l===".."||l.startsWith(".."+C.sep)||C.isAbsolute(l))return n.warn("bindToSessionTranscript: path not under sessionsDir; rejecting",{transcriptPath:o}),{status:"rejected",reason:"outside_sessions_directory"};let c=C.basename(o);if(!c.startsWith("rollout-")||!c.endsWith(".jsonl"))return{status:"rejected",reason:"invalid_rollout_filename"};let d=null;for(let h=0;h<3;h++){if(!this.isTranscriptAdmissionCurrent(s,r))return{status:"rejected",reason:"watcher_stopped"};if(d=this.readSessionMeta(o),d)break;if(await new Promise(g=>setTimeout(g,20)),!this.isTranscriptAdmissionCurrent(s,r))return{status:"rejected",reason:"watcher_stopped"}}return!d||d.id!==i?(n.debug("bindToSessionTranscript: meta missing or id mismatch; not binding",{transcriptPath:o,metaId:d?.id,expectedSessionId:i}),{status:"rejected",reason:"session_metadata_mismatch"}):this.isInteractiveRollout(d)?this.isTranscriptAdmissionCurrent(s,r)?(this.bindToFile(o),this.authoritativeSessionId=i,{status:"bound"}):{status:"rejected",reason:"watcher_stopped"}:(n.debug("bindToSessionTranscript: non-interactive rollout (codex_exec/subagent); not binding",{transcriptPath:o,originator:d.originator,threadSource:d.threadSource}),{status:"rejected",reason:"non_interactive_rollout"})}async drainPendingTranscriptBind(){let e=this.pendingTranscriptBind;if(!e)return;this.pendingTranscriptBind=null;let i;try{this.transcriptBindingsClosed?i={status:"rejected",reason:"watcher_stopped"}:i=await this.trackTranscriptAdmission(this.validateAndBindSessionTranscript(e.transcriptPath,e.expectedSessionId,this.transcriptBindGeneration))}catch(s){n.warn("bindToSessionTranscript: pending startup bind failed",{expectedSessionId:e.expectedSessionId,error:s instanceof Error?s.message:String(s)}),i={status:"rejected",reason:"startup_bind_failed"}}e.resolve(i)}onFileAdded(e){let i=this.tryRealpath(e);i&&(i===this.activeLogFile?this.scheduleReadNewLines(i):n.debug("Ignoring unowned rollout add; awaiting authoritative hook binding",{filePath:i}))}onFileChanged(e){let i=this.tryRealpath(e);i&&(this.activeLogFile&&i!==this.activeLogFile||this.activeLogFile&&this.scheduleReadNewLines(i))}readSessionMeta(e){let i=this.readFirstLogEntry(e);if(!i)return null;let s=i.payload||{};return{id:typeof s.id=="string"?s.id:void 0,timestamp:typeof i.timestamp=="string"?i.timestamp:void 0,originator:typeof s.originator=="string"?s.originator:void 0,cwd:typeof s.cwd=="string"?s.cwd:void 0,threadSource:typeof s.thread_source=="string"?s.thread_source:void 0,sourceSubagent:!!(s.source&&typeof s.source=="object"&&s.source.subagent)}}readFirstLogEntry(e){let i=null;try{i=b.openSync(e,"r");let s=new Te.StringDecoder("utf8"),r=Buffer.alloc(64*1024),o="",a=0,l=-1;for(;a<le;){let d=b.readSync(i,r,0,r.length,a);if(d<=0||(a+=d,o+=s.write(r.subarray(0,d)),l=o.indexOf(`
|
|
2
|
-
`),l!==-1))break}
|
|
3
|
-
`).trim()}function
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
"use strict";var ot=Object.create;var G=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var pt=Object.getPrototypeOf,ct=Object.prototype.hasOwnProperty;var dt=(c,t)=>{for(var e in t)G(c,e,{get:t[e],enumerable:!0})},Ee=(c,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of lt(t))!ct.call(c,s)&&s!==e&&G(c,s,{get:()=>t[s],enumerable:!(i=at(t,s))||i.enumerable});return c};var T=(c,t,e)=>(e=c!=null?ot(pt(c)):{},Ee(t||!c||!c.__esModule?G(e,"default",{value:c,enumerable:!0}):e,c)),ut=c=>Ee(G({},"__esModule",{value:!0}),c);var oi={};dt(oi,{CodexCompanionServer:()=>ae,extractShellCommandFromPromptText:()=>st,extractShellCommandPartsFromPromptText:()=>be,restoreCodexPersistOptionCommand:()=>nt,shellCommandPartsMatchExpected:()=>rt});module.exports=ut(oi);var et=require("uuid"),oe=T(require("crypto")),K=T(require("fs")),M=T(require("path")),tt=T(require("os")),Ie=require("util"),le=require("child_process"),Pe=require("shell-quote"),m=require("@quantiya/codevibe-core");var _e=T(require("os")),Te=T(require("path")),xe=require("@quantiya/codevibe-core"),o=(0,xe.createLogger)({name:"codevibe-codex",logFile:Te.default.join(_e.default.tmpdir(),"codevibe-codex-mcp.log"),level:"debug"});var Re=require("events"),I=T(require("fs")),F=T(require("path")),Ce=require("string_decoder"),Fe=require("chokidar"),Oe=require("@quantiya/codevibe-core");var de=256*1024,ht=64*1024*1024,mt=16*1024*1024,ft=64*1024,V=class extends Re.EventEmitter{constructor(e={}){super();this.watcher=null;this.filePositions=new Map;this.activeLogFile=null;this.sessionId=null;this.isWatching=!1;this.startTime=0;this.sessionsDir=null;this.activeReads=new Map;this.pendingReads=new Set;this.readGeneration=0;this.oversizedRecordFiles=new Set;this.fileIdentities=new Map;this.bindSource=null;this.authoritativeSessionId=null;this.pendingTranscriptBind=null;this.transcriptBindGeneration=0;this.transcriptBindingsClosed=!1;this.activeTranscriptAdmissions=new Set;this.startBaselines=new Map;if(this.maxBacklogBytes=e.maxBacklogBytes??ht,this.maxRecordBytes=e.maxRecordBytes??mt,!Number.isSafeInteger(this.maxBacklogBytes)||this.maxBacklogBytes<=0)throw new RangeError("maxBacklogBytes must be a positive safe integer");if(!Number.isSafeInteger(this.maxRecordBytes)||this.maxRecordBytes<=0)throw new RangeError("maxRecordBytes must be a positive safe integer")}start(){if(this.isWatching){o.warn("Session log watcher already running");return}this.transcriptBindGeneration++,this.transcriptBindingsClosed=!1;let e=(0,Oe.getConfig)().codex.sessionsDir;this.sessionsDir=e,o.info("Starting Codex session log watcher",{sessionsDir:e}),I.existsSync(e)||(o.info("Codex sessions directory does not exist yet, creating...",{sessionsDir:e}),I.mkdirSync(e,{recursive:!0})),this.startTime=Date.now(),this.readGeneration++,this.bindSource=null,this.authoritativeSessionId=null,this.snapshotStartBaselines(e),this.drainPendingTranscriptBind(),this.watcher=(0,Fe.watch)(e,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},depth:4,ignored:i=>{let s=F.basename(i);return I.existsSync(i)&&I.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=>{o.error("Watcher error:",i),this.emit("error",i)}),this.watcher.on("ready",()=>{o.info("Session log watcher ready"),this.activeLogFile||o.debug("No authoritative transcript hook received yet; rollout watcher remains fail-closed")}),this.isWatching=!0,o.info("Session log watcher started")}stop(){this.transcriptBindingsClosed=!0,this.transcriptBindGeneration++,this.watcher&&(this.watcher.close(),this.watcher=null),this.isWatching=!1,this.readGeneration++,this.filePositions.clear(),this.activeReads.clear(),this.pendingReads.clear(),this.oversizedRecordFiles.clear(),this.activeLogFile=null,this.sessionId=null,this.sessionsDir=null,this.bindSource=null,this.authoritativeSessionId=null,this.pendingTranscriptBind&&(this.pendingTranscriptBind.resolve({status:"rejected",reason:"watcher_stopped"}),this.pendingTranscriptBind=null),this.startBaselines.clear(),this.fileIdentities.clear(),o.info("Session log watcher stopped")}async waitForTranscriptAdmissions(){for(;this.activeTranscriptAdmissions.size>0;)await Promise.all(Array.from(this.activeTranscriptAdmissions,e=>e.then(()=>{},()=>{})))}getSessionId(){return this.sessionId}getActiveLogFile(){return this.activeLogFile}getBindSource(){return this.bindSource}getAuthoritativeSessionId(){return this.authoritativeSessionId}tryRealpath(e){try{return I.realpathSync(e)}catch{return null}}isInteractiveRollout(e){return!(!e||e.originator==="codex_exec"||e.threadSource==="subagent"||e.sourceSubagent)}identityOf(e){return{dev:e.dev,ino:e.ino}}identitiesEqual(e,i){return e.dev===i.dev&&e.ino===i.ino}computeSeedOffset(e){let i;try{i=I.statSync(e)}catch{return 0}if(this.getSessionAgeMs(e,i)>=this.startTime)return 0;let r=this.startBaselines.get(e);return r&&this.identitiesEqual(r.identity,this.identityOf(i))?r.size:i.size}applyBind(e,i){this.readGeneration++,this.activeReads.delete(e),this.pendingReads.delete(e),this.activeLogFile=e,this.bindSource=i,i==="heuristic"&&(this.authoritativeSessionId=null),this.filePositions.has(e)||this.filePositions.set(e,this.computeSeedOffset(e));try{this.fileIdentities.set(e,this.identityOf(I.statSync(e)))}catch{this.fileIdentities.delete(e)}this.scheduleReadNewLines(e)}bindToFile(e){let i=this.tryRealpath(e);if(!i){o.warn("bindToFile: could not canonicalize path; skipping",{filePath:e});return}if(i===this.activeLogFile){this.bindSource="authoritative";return}o.info("bindToFile: authoritative bind to session rollout",{filePath:i}),this.applyBind(i,"authoritative")}async bindToSessionTranscript(e,i){if(typeof e!="string"||e.length===0)return{status:"rejected",reason:"missing_transcript_path"};if(this.transcriptBindingsClosed)return{status:"rejected",reason:"watcher_stopped"};if(!this.sessionsDir){let s=this.pendingTranscriptBind;if(s)return s.transcriptPath===e&&s.expectedSessionId===i?{status:"pending",completion:s.completion}:(o.warn("bindToSessionTranscript: conflicting startup bind rejected",{transcriptPath:e,expectedSessionId:i,pendingExpectedSessionId:s.expectedSessionId}),{status:"rejected",reason:"conflicting_startup_bind"});let r,n=new Promise(a=>{r=a});return this.pendingTranscriptBind={transcriptPath:e,expectedSessionId:i,completion:n,resolve:r},o.debug("bindToSessionTranscript: watcher not started yet; queued pending authoritative bind",{transcriptPath:e,expectedSessionId:i}),{status:"pending",completion:n}}return this.trackTranscriptAdmission(this.validateAndBindSessionTranscript(e,i,this.transcriptBindGeneration))}trackTranscriptAdmission(e){let i;return i=e.finally(()=>{this.activeTranscriptAdmissions.delete(i)}),this.activeTranscriptAdmissions.add(i),i}isTranscriptAdmissionCurrent(e,i){return!this.transcriptBindingsClosed&&this.transcriptBindGeneration===e&&this.sessionsDir===i}async validateAndBindSessionTranscript(e,i,s){let r=this.sessionsDir;if(!r||!this.isTranscriptAdmissionCurrent(s,r))return{status:"rejected",reason:"watcher_not_started"};let n=this.tryRealpath(e),a=this.tryRealpath(r);if(!n||!a)return{status:"rejected",reason:"canonicalization_failed"};let l=F.relative(a,n);if(l===".."||l.startsWith(".."+F.sep)||F.isAbsolute(l))return o.warn("bindToSessionTranscript: path not under sessionsDir; rejecting",{transcriptPath:n}),{status:"rejected",reason:"outside_sessions_directory"};let p=F.basename(n);if(!p.startsWith("rollout-")||!p.endsWith(".jsonl"))return{status:"rejected",reason:"invalid_rollout_filename"};let d=null;for(let u=0;u<3;u++){if(!this.isTranscriptAdmissionCurrent(s,r))return{status:"rejected",reason:"watcher_stopped"};if(d=this.readSessionMeta(n),d)break;if(await new Promise(f=>setTimeout(f,20)),!this.isTranscriptAdmissionCurrent(s,r))return{status:"rejected",reason:"watcher_stopped"}}return!d||d.id!==i?(o.debug("bindToSessionTranscript: meta missing or id mismatch; not binding",{transcriptPath:n,metaId:d?.id,expectedSessionId:i}),{status:"rejected",reason:"session_metadata_mismatch"}):this.isInteractiveRollout(d)?this.isTranscriptAdmissionCurrent(s,r)?(this.bindToFile(n),this.authoritativeSessionId=i,{status:"bound"}):{status:"rejected",reason:"watcher_stopped"}:(o.debug("bindToSessionTranscript: non-interactive rollout (codex_exec/subagent); not binding",{transcriptPath:n,originator:d.originator,threadSource:d.threadSource}),{status:"rejected",reason:"non_interactive_rollout"})}async drainPendingTranscriptBind(){let e=this.pendingTranscriptBind;if(!e)return;this.pendingTranscriptBind=null;let i;try{this.transcriptBindingsClosed?i={status:"rejected",reason:"watcher_stopped"}:i=await this.trackTranscriptAdmission(this.validateAndBindSessionTranscript(e.transcriptPath,e.expectedSessionId,this.transcriptBindGeneration))}catch(s){o.warn("bindToSessionTranscript: pending startup bind failed",{expectedSessionId:e.expectedSessionId,error:s instanceof Error?s.message:String(s)}),i={status:"rejected",reason:"startup_bind_failed"}}e.resolve(i)}onFileAdded(e){let i=this.tryRealpath(e);i&&(i===this.activeLogFile?this.scheduleReadNewLines(i):o.debug("Ignoring unowned rollout add; awaiting authoritative hook binding",{filePath:i}))}onFileChanged(e){let i=this.tryRealpath(e);i&&(this.activeLogFile&&i!==this.activeLogFile||this.activeLogFile&&this.scheduleReadNewLines(i))}readSessionMeta(e){let i=this.readFirstLogEntry(e);if(!i)return null;let s=i.payload||{};return{id:typeof s.id=="string"?s.id:void 0,timestamp:typeof i.timestamp=="string"?i.timestamp:void 0,originator:typeof s.originator=="string"?s.originator:void 0,cwd:typeof s.cwd=="string"?s.cwd:void 0,threadSource:typeof s.thread_source=="string"?s.thread_source:void 0,sourceSubagent:!!(s.source&&typeof s.source=="object"&&s.source.subagent)}}readFirstLogEntry(e){let i=null;try{i=I.openSync(e,"r");let s=new Ce.StringDecoder("utf8"),r=Buffer.alloc(64*1024),n="",a=0,l=-1;for(;a<de;){let d=I.readSync(i,r,0,r.length,a);if(d<=0||(a+=d,n+=s.write(r.subarray(0,d)),l=n.indexOf(`
|
|
2
|
+
`),l!==-1))break}n+=s.end();let p=l===-1?n:n.slice(0,l);return p.trim()?JSON.parse(p):null}catch{return null}finally{if(i!==null)try{I.closeSync(i)}catch{}}}snapshotStartBaselines(e){this.startBaselines.clear();try{for(let{filePath:i,size:s}of this.collectRecentSessionFiles(e,!0)){let r=this.tryRealpath(i);if(r)try{let n=I.statSync(r);this.startBaselines.set(r,{size:s,identity:this.identityOf(n)})}catch{}}}catch{}}getSessionAgeMs(e,i){let s=this.readSessionMeta(e);if(s?.timestamp){let r=Date.parse(s.timestamp);if(!Number.isNaN(r))return r}return i.birthtimeMs||i.ctimeMs}collectRecentSessionFiles(e,i=!1){let s=[],r=[e];for(;r.length>0;){let n=r.pop();if(!n)continue;let a;try{a=I.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let l of a){let p=F.join(n,l.name);if(l.isDirectory()){r.push(p);continue}if(!(!l.isFile()||!l.name.startsWith("rollout-")||!l.name.endsWith(".jsonl")))try{let d=I.statSync(p),u=d.birthtimeMs||d.ctimeMs,f=d.mtimeMs;(i||u>=this.startTime||f>=this.startTime-5e3)&&s.push({filePath:p,createdAt:u,modifiedAt:f,size:d.size})}catch{}}}return s}scheduleReadNewLines(e){let i=this.activeReads.get(e);if(i)return this.pendingReads.add(e),i;let s=this.readGeneration,r=Promise.resolve().then(()=>this.drainReadQueue(e,s));return this.activeReads.set(e,r),r.finally(()=>{this.activeReads.get(e)===r&&(this.activeReads.delete(e),this.pendingReads.delete(e))}),r}async drainReadQueue(e,i){do this.pendingReads.delete(e),await this.readNewLines(e,i);while(i===this.readGeneration&&this.pendingReads.has(e))}async readNewLines(e,i){if(i!==this.readGeneration)return;let s=this.filePositions.get(e)||0,r=null;try{r=I.openSync(e,I.constants.O_RDONLY|(I.constants.O_NOFOLLOW??0));let n=I.fstatSync(r),a=this.identityOf(n),l=this.fileIdentities.get(e);if(l&&!this.identitiesEqual(l,a)){let y=this.readFirstLogEntryFromFd(r),S=y?.type==="session_meta"?y.payload.id:void 0;if(this.authoritativeSessionId&&S!==this.authoritativeSessionId){let w=new Error("Authoritative Codex rollout path was replaced by a different session");o.error("Refusing replaced rollout with mismatched session identity",{filePath:e,expectedSessionId:this.authoritativeSessionId,replacementSessionId:S}),this.emit("error",w);return}o.info("Session log inode replaced; resetting byte and decoder state",{filePath:e,oldPosition:s,oldIdentity:l,newIdentity:a}),s=0,this.filePositions.set(e,0),this.oversizedRecordFiles.delete(e)}if(this.fileIdentities.set(e,a),n.size<s&&(o.info("Session log truncated/rotated; resetting cursor to 0",{filePath:e,oldPosition:s,size:n.size}),s=0,this.filePositions.set(e,0),this.oversizedRecordFiles.delete(e)),n.size<=s)return;if(n.size-s>this.maxBacklogBytes){if(s===0&&this.sessionId===null){let S=this.readFirstLogEntryFromFd(r);S?.type==="session_meta"&&this.processLogEntry(S)}let y=this.findRecentRecordBoundary(r,n.size);if(o.warn("Codex rollout backlog exceeded live-mirror limit; skipping archival prefix",{filePath:e,oldPosition:s,newPosition:y.position,size:n.size,maxBacklogBytes:this.maxBacklogBytes,discardUntilNewline:y.discardUntilNewline}),s=y.position,this.filePositions.set(e,s),y.discardUntilNewline?this.oversizedRecordFiles.add(e):this.oversizedRecordFiles.delete(e),n.size<=s)return}let p=n.size,d=Buffer.allocUnsafe(64*1024),u=s,f=[],v=0,h=this.oversizedRecordFiles.has(e);for(;u<p;){if(i!==this.readGeneration)return;let y=Math.min(d.length,p-u),S=I.readSync(r,d,0,y,u);if(S<=0)break;let w=0;for(;w<S;){if(i!==this.readGeneration)return;let P=d.subarray(0,S).indexOf(10,w),_=P!==-1,x=_?P:S,O=x-w,we=O+(_?1:0);if(h){u+=we,this.filePositions.set(e,u),_&&(h=!1,this.oversizedRecordFiles.delete(e)),w=_?P+1:S;continue}if(O>0&&(f.push(Buffer.from(d.subarray(w,x))),v+=O),u+=we,v>this.maxRecordBytes){o.warn("Discarding oversized Codex rollout JSONL record",{filePath:e,recordEnd:u,maxRecordBytes:this.maxRecordBytes}),this.filePositions.set(e,u),f=[],v=0,h=!_,h?this.oversizedRecordFiles.add(e):this.oversizedRecordFiles.delete(e),w=_?P+1:S;continue}if(!_){w=S;continue}let N=Buffer.concat(f,v);f=[],v=0,N.length>0&&N[N.length-1]===13&&(N=N.subarray(0,N.length-1));let pe=N.toString("utf8");if(pe.trim())try{let ce=JSON.parse(pe);this.processLogEntry(ce)}catch(ce){o.warn("Failed to parse log line",{filePath:e,line:pe.substring(0,100),error:ce})}if(i===this.readGeneration&&this.filePositions.set(e,u),i!==this.readGeneration)return;w=P+1}}}catch(n){o.error("Error reading log file",{filePath:e,error:n}),this.emit("error",n)}finally{if(r!==null)try{I.closeSync(r)}catch{}}}findRecentRecordBoundary(e,i){let s=Math.max(0,i-this.maxBacklogBytes),r=s+Math.min(i-s,this.maxRecordBytes);{if(s===0)return{position:0,discardUntilNewline:!1};let n=Buffer.allocUnsafe(1);if(I.readSync(e,n,0,1,s-1)===1&&n[0]===10)return{position:s,discardUntilNewline:!1};let a=Buffer.allocUnsafe(ft),l=s;for(;l<r;){let p=Math.min(a.length,r-l),d=I.readSync(e,a,0,p,l);if(d<=0)break;let u=a.subarray(0,d).indexOf(10);if(u!==-1)return{position:l+u+1,discardUntilNewline:!1};l+=d}if(l===r&&l<i&&r-s===this.maxRecordBytes){let p=Buffer.allocUnsafe(1);if(I.readSync(e,p,0,1,l)===1&&p[0]===10)return{position:l+1,discardUntilNewline:!1}}return{position:s,discardUntilNewline:!0}}}readFirstLogEntryFromFd(e){try{let i=[],s=0,r=Buffer.allocUnsafe(64*1024);for(;s<de;){let a=Math.min(r.length,de-s),l=I.readSync(e,r,0,a,s);if(l<=0)break;let p=r.subarray(0,l).indexOf(10);if(p!==-1){i.push(Buffer.from(r.subarray(0,p)));break}i.push(Buffer.from(r.subarray(0,l))),s+=l}if(i.length===0)return null;let n=Buffer.concat(i).toString("utf8");return n.trim()?JSON.parse(n):null}catch{return null}}processLogEntry(e){if(o.debug("Processing log entry",{type:e.type}),e.type==="session_meta"){let i=e.payload;this.sessionId=i.id,o.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 he=require("uuid"),R=require("@quantiya/codevibe-core");var D=new Map,L=[],gt=24;function U(c){return typeof c=="string"?c.trim():""}function Me(c){return typeof c=="string"?c:""}function ke(c,t,e){let i=U(e);if(!i)return!1;let s=Me(t);return L.some(r=>r.text===i&&r.phase===s&&r.carrier!==c)}function yt(c){let t=U(c);return t.length>0&&L.some(e=>e.text===t&&e.phase==="final_answer")}function ue(c,t,e){let i=U(e);if(i)for(L.push({carrier:c,phase:Me(t),text:i});L.length>gt;)L.shift()}function Y(){L.length=0}function vt(c){let t=c?.content;return Array.isArray(t)?t.filter(e=>e&&(e.type==="output_text"||e.type==="text")).map(e=>typeof e?.text=="string"?e.text:"").join(""):""}function St(c){let t=c?.summary;return!Array.isArray(t)||t.length===0?"":t.map(e=>typeof e=="string"?e:typeof e?.text=="string"?e.text:"").join(`
|
|
3
|
+
`).trim()}function It(c){if(typeof c!="string")return"";let t=c.match(/"cmd"\s*:\s*"((?:\\.|[^"\\])*)"/);if(t)try{return JSON.parse(`"${t[1]}"`)}catch{return t[1]}return""}function J(c){if(typeof c!="string"||!c.startsWith(`*** Begin Patch
|
|
4
|
+
`)||!c.endsWith(`
|
|
5
|
+
*** End Patch`))return"";let t=c.split(`
|
|
6
|
+
`);return t[0]!=="*** Begin Patch"||t[t.length-1]!=="*** End Patch"||t.filter(e=>e==="*** Begin Patch").length!==1||t.filter(e=>e==="*** End Patch").length!==1||!/^\*\*\* (?:Add|Update|Delete) File: [^\r\n]+$/.test(t[1]??"")?"":c}function q(c){if(typeof c!="string")return"";let t="[A-Za-z_$][\\w$]*",e='"(?:\\\\.|[^"\\\\])*"',i=c.match(new RegExp(`^\\s*(?:const|let|var)\\s+(${t})\\s*=\\s*await\\s+tools\\.apply_patch\\(\\s*(${e})\\s*\\)\\s*;\\s*(?:text\\(\\s*(${t})\\s*\\)\\s*;\\s*)?$`,"s")),s=c.match(new RegExp(`^\\s*(?:const|let|var)\\s+(${t})\\s*=\\s*(${e})\\s*;\\s*(?:const|let|var)\\s+(${t})\\s*=\\s*await\\s+tools\\.apply_patch\\(\\s*(${t})\\s*\\)\\s*;\\s*(?:text\\(\\s*(${t})\\s*\\)\\s*;\\s*)?$`,"s")),r;if(i&&(!i[3]||i[3]===i[1])?r=i[2]:s&&s[4]===s[1]&&(!s[5]||s[5]===s[3])&&(r=s[2]),!r)return"";try{return J(JSON.parse(r))}catch{return""}}var Pt=new Set(["exec","shell","shell_command","bash","run_command","run_cmd"]);function Ae(c,t){return typeof t!="string"?"":c==="apply_patch"?t:c==="exec"?q(t):typeof c=="string"&&Pt.has(c)?"":t.includes("*** Begin Patch")?t:""}function Ne(c,t){let e={sessionId:t,source:R.EventSource.DESKTOP};if(c.type==="event_msg"&&c.payload){let i=c.payload.type;switch(i){case"user_message":return Y(),{...e,type:R.EventType.USER_PROMPT,content:c.payload.message||"",metadata:{images:c.payload.images||[]}};case"agent_message":{let s=c.payload.message||"",r=c.payload.phase;return ke("agent_message",r,s)?null:(ue("agent_message",r,s),{...e,type:R.EventType.ASSISTANT_RESPONSE,content:s,metadata:{phase:r}})}case"agent_reasoning":return{...e,type:R.EventType.REASONING,content:c.payload.text||""};case"task_started":return Y(),o.debug("Skipping task_started entry (turn boundary)"),null;case"task_complete":{let s=U(c.payload.last_agent_message),r=null;return s&&!yt(s)?(ue("task_complete","final_answer",s),r={...e,type:R.EventType.ASSISTANT_RESPONSE,content:s,metadata:{phase:"final_answer"}}):o.debug("Skipping task_complete (final already emitted or empty)"),Y(),r}case"token_count":return o.debug("Skipping token_count entry"),null;default:return o.debug("Unknown event_msg type",{type:i}),null}}if(c.type==="response_item"&&c.payload){let i=c.payload.type;if(i==="message"){if(c.payload.role!=="assistant")return o.debug("Skipping non-assistant response_item/message",{role:c.payload.role}),null;let s=vt(c.payload),r=c.payload.phase;return!U(s)||ke("response_item",r,s)?null:(ue("response_item",r,s),{...e,type:R.EventType.ASSISTANT_RESPONSE,content:s,metadata:{phase:r}})}if(i==="reasoning"){let s=St(c.payload);return s?{...e,type:R.EventType.REASONING,content:s}:(o.debug("Skipping reasoning response_item (no readable summary)"),null)}if(i==="function_call"){let{name:s,arguments:r,call_id:n}=c.payload,a={};try{a=JSON.parse(r||"{}")}catch{a={raw:r}}let l=(0,he.v4)();D.set(n,{name:s,input:r,eventId:l});let p=$(s),d=bt(s,a);return{...e,type:R.EventType.TOOL_USE,content:d,metadata:{toolName:p,toolInput:a,callId:n,status:"running"}}}if(i==="function_call_output"){let{call_id:s,output:r}=c.payload,n=D.get(s);D.delete(s);let a=n?.name?$(n.name):"Tool",l=me(X(r),500);return{...e,type:R.EventType.TOOL_USE,content:`${a} completed:
|
|
7
|
+
${l}`,metadata:{toolName:a,toolOutput:r,callId:s,status:"completed"}}}if(i==="custom_tool_call"){let{name:s,call_id:r,input:n,status:a}=c.payload;D.set(r,{name:s,input:n,eventId:(0,he.v4)()});let l=Ae(s,n);if(l){let u=Et(l),{oldString:f,newString:v}=wt(l),h=u?`Editing: ${u.filePath}`:"Applying patch";return{...e,type:R.EventType.TOOL_USE,content:h,metadata:{tool_name:"Edit",tool_input:{file_path:u?.filePath||"",old_string:f,new_string:v},callId:r,status:a||"running"}}}let p=It(n),d=$(s==="exec"?"shell":s||"tool");return{...e,type:R.EventType.TOOL_USE,content:p?`Running: ${p}`:`Running ${d}`,metadata:{toolName:d,toolInput:p?{command:p}:{raw:typeof n=="string"?n:""},callId:r,status:a||"running"}}}if(i==="custom_tool_call_output"){let{call_id:s,output:r}=c.payload,n=D.get(s);if(D.delete(s),Ae(n?.name,n?.input)){let p={};if(typeof r=="string")try{p=JSON.parse(r||"{}")}catch{p={raw:r}}else if(Array.isArray(r)){let y=X(r);try{p=JSON.parse(y)}catch{p={raw:r,text:y}}}else p=r??{};let d=p!==null&&typeof p=="object"&&!Array.isArray(p)?p:null,u=typeof d?.output=="string"?d.output:void 0,f=d?.error,v=u!==void 0&&u.includes("Success"),h=typeof f=="string"?f:f!==void 0?JSON.stringify(f):"Unknown error";return{...e,type:R.EventType.TOOL_USE,content:v?"File edit applied successfully":`Edit failed: ${h}`,metadata:{toolName:"Edit",toolOutput:p,callId:s,status:"completed",success:v}}}let a=n?.name?$(n.name==="exec"?"shell":n.name):"Tool",l=X(r);return{...e,type:R.EventType.TOOL_USE,content:`${a} completed:
|
|
8
|
+
${me(l,500)}`,metadata:{toolName:a,toolOutput:r,callId:s,status:"completed"}}}return o.debug("Unknown response_item type",{type:i}),null}return c.type==="turn_context"?(o.debug("Skipping turn_context entry"),null):(o.debug("Unhandled log entry type",{type:c.type}),null)}function $(c){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"}[c]||c}function bt(c,t){switch(c){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 ${$(c)}`}}function wt(c){let t=[],e=[],i=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;for(let s of c.split(`
|
|
6
9
|
`))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 r=s.slice(1);t.push(r),e.push(r)}}return{oldString:t.join(`
|
|
7
10
|
`),newString:e.join(`
|
|
8
|
-
`)}}function
|
|
9
|
-
`);if(typeof p=="object"&&typeof p.text=="string")return p.text;try{return JSON.stringify(p)??""}catch{return String(p)}}function de(p,t){return typeof p!="string"?de(V(p),t):p?p.length<=t?p:p.substring(0,t)+"...":""}function ue(){k.clear(),G()}var _=require("@quantiya/codevibe-core"),Ae=3e3,bt=8,wt=10,It=100;function Me(p){let t=Buffer.byteLength(p.carryover);return{status:"partial",progressKey:`${p.fileIdentity.dev}:${p.fileIdentity.ino}:${p.size}:${p.endOfComplete}:${t}`,size:p.size,carryoverBytes:t,endOfComplete:p.endOfComplete}}var Pt="tool_activity",U=class{constructor(t){this.consolidator=null;this.ledger=null;this.sessionMap=null;this.ownership=null;this.cursor=null;this.backendSessionId=null;this.rolloutId=null;this.transcriptPath=null;this.backstopTimer=null;this.backstopInFlight=null;this.cursorReady=Promise.resolve();this.cursorRepaired=!1;this.deps=t}static mintBackendSessionId(){return _.ToolActivitySessionMap.mintCodexBackendSessionId()}async recordedBackendSessionId(t){return new _.ToolActivitySessionMap({agent:"codex",logger:this.deps.logger,lock:new _.InProcessRolloutLock,root:this.deps.root}).ownerBackendSessionId(t)}get sessionId(){return this.backendSessionId}get rollout(){return this.rolloutId}isActive(){return this.consolidator!==null}async start(t,e,i){this.backendSessionId=t,this.rolloutId=e;let s=(0,_.createRolloutLock)({agent:"codex",logger:this.deps.logger,socketDir:this.deps.socketDir,root:this.deps.root});this.sessionMap=new _.ToolActivitySessionMap({agent:"codex",logger:this.deps.logger,lock:s,root:this.deps.root}),this.ownership=await this.sessionMap.claimOwnership(e,t);let r=new _.ToolActivityOutbox({agent:"codex",logger:this.deps.logger,root:this.deps.root});this.ledger=new _.ToolActivityLedger({agent:"codex",sessionId:t,logger:this.deps.logger,root:this.deps.root}),this.consolidator=new _.ToolActivityConsolidator({agent:"codex",sessionId:t,logger:this.deps.logger,outbox:r,ledger:this.ledger,transport:this.buildTransport()}),await this.consolidator.init(),i&&this.bindTranscript(i),this.deps.logger.info("[tool-activity] codex consolidator started",{sessionId:t,rollout:e,hasTranscript:!!i})}bindTranscript(t){if(!this.consolidator||!t||this.transcriptPath===t)return;this.transcriptPath=t;let e=new _.ToolReplayCursor({agent:"codex",sessionId:this.backendSessionId,canonicalPath:t,logger:this.deps.logger,root:this.deps.root,readBytes:this.deps.replayReadBytes,maxFrameBytes:this.deps.replayMaxFrameBytes});this.cursor=e,this.cursorRepaired=!1,this.cursorReady=e.load().catch(s=>this.deps.logger.warn("[tool-activity] codex cursor load failed (rescanning fresh)",{sessionId:this.backendSessionId,err:String(s)}));let i=this.deps.backstopIntervalMs??3e3;i>0&&!this.backstopTimer&&(this.backstopTimer=setInterval(()=>{this.runTranscriptBackstop().catch(s=>this.deps.logger.warn("[tool-activity] codex transcript backstop failed",{sessionId:this.backendSessionId,err:String(s)}))},i),this.backstopTimer.unref?.())}async observeCall(t,e){if(!this.consolidator||!this.sessionMap||!this.ownership||!t.callId||!t.toolName)return;let i=this.consolidator;await this.sessionMap.bindCall(this.ownership,t.callId);let s={id:t.callId,tool:t.toolName,normalizedTarget:xt(t.toolName,t.toolInput),ts:t.ts??new Date().toISOString(),byteOffset:t.byteOffset??0,...t.toolInput!==void 0?{digest:(0,_.digestOf)(t.toolInput)}:{}},r=await i.observe(s,e);return r==="closed"?await i.captureTerminal(s,this.deps.shutdownDrainMs??Ae)?"sealed-terminal":"closed":r}async runTranscriptBackstop(t=!1){await this.runTranscriptBackstopTurn(t)}runTranscriptBackstopTurn(t=!1){if(this.backstopInFlight)return this.backstopInFlight;let e=this.cursor,i=this.cursorReady,s=this.consolidator;if(!s||!e)return Promise.resolve("caught-up");let o=(async()=>{if(await i,this.cursor!==e)return"more";if(!this.cursorRepaired){if(await s.repairLostWindows(e),this.cursor!==e)return"more";this.cursorRepaired=!0}return this.doTranscriptBackstop(e,t)})().finally(()=>{this.backstopInFlight===o&&(this.backstopInFlight=null)});return this.backstopInFlight=o,o}async doTranscriptBackstop(t,e=!1){let i=this.consolidator;if(!i)return"caught-up";this.ledger&&await this.ledger.reloadLegacyOwned();for(let s=0;s<bt;s+=1){if(this.cursor!==t)return"caught-up";let r=await t.readFrames();if(r.missing)return"caught-up";if(r.frames.length===0)return r.carryover.length>0?Me(r):"caught-up";let o=Number.POSITIVE_INFINITY,a=e?{includeInFlight:!0}:void 0;for(let l of r.frames)for(let c of _t(l.line,l.startOffset))await this.observeCall(c,a)==="deferred-in-flight"&&(o=Math.min(o,l.startOffset));if(await i.flush(),o<r.endOfComplete)return await t.checkpoint(o,{fileIdentity:r.fileIdentity,size:r.size,carryover:""}),"more";if(await t.checkpoint(r.endOfComplete,{fileIdentity:r.fileIdentity,size:r.size,carryover:r.carryover}),!r.hasMore)return r.carryover.length>0?Me(r):"caught-up"}return"more"}async flush(){await this.consolidator?.flush()}async stop(){this.backstopTimer&&(clearInterval(this.backstopTimer),this.backstopTimer=null),await this.runTranscriptBackstop().catch(()=>{});let t=Math.max(1,Math.trunc(this.deps.shutdownPartialNoProgressTurns??It)),e=null,i=0;for(;;){let s=await this.runTranscriptBackstopTurn(!0);if(s==="caught-up")break;if(typeof s!="string"){if(s.progressKey===e?i+=1:(e=s.progressKey,i=1),i>=t){this.deps.logger.warn("[tool-activity] deferring unchanged incomplete rollout suffix during shutdown; the next owner will re-read it from the durable complete-line boundary",{size:s.size,carryoverBytes:s.carryoverBytes,endOfComplete:s.endOfComplete,unchangedTurns:i});break}await new Promise(r=>setTimeout(r,wt))}else e=null,i=0,await new Promise(r=>setImmediate(r))}await this.consolidator?.drainSends(this.deps.shutdownDrainMs??Ae).catch(()=>{});try{await this.consolidator?.shutdown()}finally{await this.ownership?.release().catch(()=>{}),this.ownership=null,this.consolidator=null,this.ledger=null,this.sessionMap=null,this.cursor=null}}buildTransport(){let t=async(e,i,s)=>{let r=s?s.sessionKey:this.deps.getSessionKey();if(!r)throw new Error("[tool-activity] no session key at send (retryable)");let o=s?s.sessionKeyGen:this.deps.getSessionKeyGen();await this.deps.createEvent({sessionId:e,type:_.EventType.TOOL_ACTIVITY,source:_.EventSource.DESKTOP,content:this.deps.encryptContent(Pt,r),metadata:{encrypted:this.deps.encryptMetadata({manifest:i.manifest},r)},timestamp:i.windowStart,isEncrypted:!0,clientEventId:i.clientEventId,...o?{expectedSessionKeyGen:o}:{}})};return{send:async(e,i)=>{try{await t(e,i)}catch(s){if((0,_.isSessionKeyStaleError)(s)&&this.deps.refreshSessionKey){let r=await this.deps.refreshSessionKey(e);if(!r)throw s;await t(e,i,r);return}throw s}}}}};function _t(p,t){let e;try{e=JSON.parse(p)}catch{return[]}if(e?.type!=="response_item"||!e.payload)return[];let i=e.payload,s=typeof e.timestamp=="string"?e.timestamp:new Date(0).toISOString();if(i.type==="function_call"&&typeof i.call_id=="string"&&typeof i.name=="string"){let r;try{r=JSON.parse(i.arguments||"{}")}catch{r={raw:i.arguments}}return[{callId:i.call_id,toolName:Et(i.name),toolInput:r,ts:s,byteOffset:t}]}if(i.type==="custom_tool_call"&&typeof i.call_id=="string"){let r=Tt(typeof i.input=="string"?i.input:""),o=r?{file_path:r,patch:i.input}:{patch:i.input};return[{callId:i.call_id,toolName:"Edit",toolInput:o,ts:s,byteOffset:t}]}return[]}function Et(p){return p==="shell"||p==="shell_command"||p==="local_shell"?"Bash":p==="apply_patch"?"Edit":p}function Tt(p){let t=p.match(/^\*\*\* (?:Update|Add|Delete) File: (.+)$/m);return t?t[1].trim():void 0}function xt(p,t){if(!t||typeof t!="object")return;let e=t,i=r=>typeof r=="string"&&r.length>0?r:void 0,s=Array.isArray(e.command)?e.command.filter(r=>typeof r=="string").join(" ").trim().split(/\s+/)[0]:typeof e.command=="string"?e.command.trim().split(/\s+/)[0]:void 0;return i(e.file_path)??i(e.path)??i(e.pattern)??i(e.url)??(s&&s.length>0?s:void 0)}var Ne=require("events"),De=require("@quantiya/codevibe-core");var Y=class p extends Ne.EventEmitter{constructor(){super();this.pendingCalls=new Map;this.timers=new Map;this.timeoutMs=(0,De.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 r=this.parseInput(s),o=this.extractFilePath(i,s,r),a=this.extractDiff(i,s,r),l={callId:e,name:i,input:s,filePath:o,diff:a,parsedInput:r,timestamp:Date.now(),notificationSent:!1};if(this.pendingCalls.set(e,l),!this.shouldScheduleApprovalTimeout(i,r)){n.debug("Skipping approval timeout for non-escalated tool call",{callId:e,name:i});return}let c=setTimeout(()=>{this.checkPendingCall(e)},this.timeoutMs);this.timers.set(e,c)}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 r=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(r)return`File: ${r[1].trim()}`}if(p.SHELL_TOOL_NAMES.has(e))try{let r=JSON.parse(i),o=typeof r.command=="string"?r.command:typeof r.cmd=="string"?r.cmd:void 0;if(o)return`Command: ${o.substring(0,50)}${o.length>50?"...":""}`}catch{}return`Tool: ${this.mapToolName(e)}`}mapToolName(e){return{exec_command:"Bash",shell_command:"Bash",shell:"Bash",exec:"Bash",local_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}}static{this.SHELL_TOOL_NAMES=new Set(["exec_command","shell_command","shell","exec","local_shell"])}shouldScheduleApprovalTimeout(e,i){return p.SHELL_TOOL_NAMES.has(e)?i?.sandbox_permissions==="require_escalated":!1}extractFilePath(e,i,s){if(e==="apply_patch"&&i){let o=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(o)return o[1].trim()}let r=s?.file_path||s?.path||s?.filePath;if(r&&typeof r=="string")return r}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 Be=require("child_process"),Le=require("util");var he=(0,Le.promisify)(Be.exec),K="__CODEVIBE_CODEX_KEY_ESCAPE__",X=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}),e===K?await this.sendKeyViaTmux(i,"Escape"):await this.sendViaTmux(i,e),n.info("Successfully sent input to Codex",{sessionId:t,input:e}),!0):(n.error("No tmux session found - CodeVibe Companion launch is required",{sessionId:t,hint:"Start Codex CLI using `codevibe --agent codex`"}),!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 he(s),await this.delay(500);let r=`tmux send-keys -t "${t}" Enter`;await he(r),n.info("tmux send-keys completed")}catch(s){throw n.error("tmux send-keys failed",{sessionName:t,error:s}),s}}async sendKeyViaTmux(t,e){n.info("Sending special key via tmux",{sessionName:t,key:e});try{let i=`tmux send-keys -t "${t}" ${e}`;await he(i),n.info("tmux special-key send completed")}catch(i){throw n.error("tmux special-key send failed",{sessionName:t,key:e,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 f=E(require("fs")),Q=E(require("os")),R=E(require("path")),q=require("crypto"),Ke=require("child_process"),qe=require("events"),$e=require("util");var me=(0,$e.promisify)(Ke.execFile),Ue=512*1024,A="writer.state",Rt=2e3,Ct=10,Ot=16*1024*1024,Ft=10080*60*1e3,J=class extends qe.EventEmitter{constructor(e={}){super();this.sessionName=null;this.started=!1;this.pipeDirPath=null;this.pipeDirIdentity=null;this.pipeFilePath=null;this.pipeFileFd=null;this.pipeFileIdentity=null;this.writerStatePath=null;this.writerStateFd=null;this.writerStateIdentity=null;this.writerGeneration=null;this.pipeEnabled=!1;this.filePosition=0;this.pollTimer=null;this.processing=!1;this.pendingRead=!1;this.promptInspectionChain=Promise.resolve();this.lastPromptHash=null;this.lifecycleGeneration=0;this.retainedMirrors=[];this.retainedMirrorContainmentLost=!1;this.maxPaneFileBytes=e.maxPaneFileBytes??Ot,this.stalePaneRetentionMs=e.stalePaneRetentionMs??Ft,this.tempDir=e.tempDir??Q.tmpdir(),this.writerPath=R.resolve(__dirname,"..","libexec","pane-mirror-writer.js");let i=e.runtimePlatform??process.platform,s=e.runtimeRelease??Q.release();if(this.wslDetected=i==="linux"&&(/microsoft/i.test(s)||!!process.env.WSL_DISTRO_NAME||!!process.env.WSL_INTEROP),!Number.isSafeInteger(this.maxPaneFileBytes)||this.maxPaneFileBytes<=0)throw new RangeError("maxPaneFileBytes must be a positive safe integer");if(!Number.isSafeInteger(this.stalePaneRetentionMs)||this.stalePaneRetentionMs<0)throw new RangeError("stalePaneRetentionMs must be a non-negative safe integer")}async start(e){if(this.wslDetected)throw new Error("Tmux pane mirror fallback is disabled on unqualified WSL; using hook-based prompts only");if(this.started&&this.sessionName===e&&this.pipeEnabled){n.debug("Tmux pane observer already started",{sessionName:e});return}this.started&&await this.stop(),this.lifecycleGeneration++,this.sessionName=e,this.filePosition=0,this.lastPromptHash=null;try{if(this.cleanupStalePipeFiles(),this.reapOwnedRetainedMirrors(),this.retainedMirrorContainmentLost||this.retainedMirrors.length>0)throw new Error("Prior bounded tmux pane writer is still unconfirmed; refusing another mirror");this.createSecureMirror(),this.started=!0,await this.enablePipePane(),this.pipeEnabled=!0,this.startPolling()}catch(i){this.started=!1,this.lifecycleGeneration++;let s=this.writerGeneration===null;if(!s)try{await this.disablePipePane(),s=!0}catch(r){n.error("Failed to confirm tmux pane writer quiescence after startup failure",{disableError:r})}throw s&&(this.pipeEnabled=!1),this.clearPolling(),s?this.releaseSecureMirror():this.abandonSecureMirror(),this.resetLifecycleState(),i}n.info("Tmux pane observer started",{sessionName:e})}async stop(){if(!this.started&&this.pipeFileFd===null)return;this.started=!1,this.lifecycleGeneration++;let e=!1;try{await this.disablePipePane(),e=!0}catch(i){n.error("Failed to confirm tmux pane writer quiescence during stop",{error:i}),this.emit("observer-error",i)}e&&(this.pipeEnabled=!1),this.clearPolling(),e?this.releaseSecureMirror():this.abandonSecureMirror(),n.info("Tmux pane observer stopped",{sessionName:this.sessionName,writerQuiesced:e}),this.resetLifecycleState()}identityOf(e){return{dev:e.dev,ino:e.ino}}identitiesEqual(e,i){return e.dev===i.dev&&e.ino===i.ino}openMirrorFile(e){return f.openSync(e,f.constants.O_RDWR|f.constants.O_CREAT|f.constants.O_EXCL|(f.constants.O_NOFOLLOW??0),384)}truncateMirror(e){f.ftruncateSync(e,0)}createSecureMirror(){f.mkdirSync(this.tempDir,{recursive:!0,mode:448});let e=f.mkdtempSync(R.join(this.tempDir,`codevibe-codex-pane-${process.pid}-`));f.chmodSync(e,448);let i=R.join(e,"pane.log"),s=R.join(e,A),r=null,o=null;try{r=this.openMirrorFile(i),f.fchmodSync(r,384);let a=f.fstatSync(r);if(!a.isFile())throw new Error("Tmux pane mirror is not a regular file");o=this.openMirrorFile(s),f.fchmodSync(o,384);let l=f.fstatSync(o);if(!l.isFile())throw new Error("Tmux pane writer state is not a regular file");f.writeSync(o,Buffer.from(`idle
|
|
10
|
-
`),0,5,0),this.pipeDirPath=e,this.pipeDirIdentity=this.identityOf(
|
|
11
|
-
`);let i=[process.execPath,this.writerPath,this.pipeFilePath,String(this.pipeFileIdentity.dev),String(this.pipeFileIdentity.ino),this.writerStatePath,String(this.writerStateIdentity.dev),String(this.writerStateIdentity.ino),e,String(this.maxPaneFileBytes)].map(r=>this.quoteShellArg(r)).join(" ");try{await
|
|
12
|
-
`).slice(-6).join("\\n")});return}let r=this.hashPromptSnapshot(s);r!==this.lastPromptHash&&(this.lastPromptHash=r,this.emit("prompt-candidate",{rawDelta:i,snapshot:s,detectedAt:Date.now()}))}queueCurrentSnapshotInspection(e){this.promptInspectionChain=this.promptInspectionChain.then(async()=>{if(!(!this.started||this.lifecycleGeneration!==e))try{let i=await this.captureSnapshot();this.inspectSnapshotForPrompt(i,"")}catch(i){
|
|
13
|
-
`).map(
|
|
14
|
-
`)}let v=-1;for(let
|
|
15
|
-
`):null}if(
|
|
11
|
+
`)}}function Et(c){if(!c)return null;let t=c.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);return t?{filePath:t[1].trim()}:null}function X(c){if(c==null)return"";if(typeof c=="string")return c;if(Array.isArray(c))return c.map(t=>typeof t?.text=="string"?t.text:t?.type==="input_image"||typeof t?.image_url=="string"?"[image]":JSON.stringify(t??null)).join(`
|
|
12
|
+
`);if(typeof c=="object"&&typeof c.text=="string")return c.text;try{return JSON.stringify(c)??""}catch{return String(c)}}function me(c,t){return typeof c!="string"?me(X(c),t):c?c.length<=t?c:c.substring(0,t)+"...":""}function fe(){D.clear(),Y()}var E=require("@quantiya/codevibe-core"),De=3e3,_t=8,Tt=10,xt=100;function Be(c){let t=Buffer.byteLength(c.carryover);return{status:"partial",progressKey:`${c.fileIdentity.dev}:${c.fileIdentity.ino}:${c.size}:${c.endOfComplete}:${t}`,size:c.size,carryoverBytes:t,endOfComplete:c.endOfComplete}}var Rt="tool_activity",z=class{constructor(t){this.consolidator=null;this.ledger=null;this.sessionMap=null;this.ownership=null;this.cursor=null;this.backendSessionId=null;this.rolloutId=null;this.transcriptPath=null;this.backstopTimer=null;this.backstopInFlight=null;this.cursorReady=Promise.resolve();this.cursorRepaired=!1;this.deps=t}static mintBackendSessionId(){return E.ToolActivitySessionMap.mintCodexBackendSessionId()}async recordedBackendSessionId(t){return new E.ToolActivitySessionMap({agent:"codex",logger:this.deps.logger,lock:new E.InProcessRolloutLock,root:this.deps.root}).ownerBackendSessionId(t)}get sessionId(){return this.backendSessionId}get rollout(){return this.rolloutId}isActive(){return this.consolidator!==null}async start(t,e,i){this.backendSessionId=t,this.rolloutId=e;let s=(0,E.createRolloutLock)({agent:"codex",logger:this.deps.logger,socketDir:this.deps.socketDir,root:this.deps.root});this.sessionMap=new E.ToolActivitySessionMap({agent:"codex",logger:this.deps.logger,lock:s,root:this.deps.root}),this.ownership=await this.sessionMap.claimOwnership(e,t);let r=new E.ToolActivityOutbox({agent:"codex",logger:this.deps.logger,root:this.deps.root});this.ledger=new E.ToolActivityLedger({agent:"codex",sessionId:t,logger:this.deps.logger,root:this.deps.root}),this.consolidator=new E.ToolActivityConsolidator({agent:"codex",sessionId:t,logger:this.deps.logger,outbox:r,ledger:this.ledger,transport:this.buildTransport()}),await this.consolidator.init(),i&&this.bindTranscript(i),this.deps.logger.info("[tool-activity] codex consolidator started",{sessionId:t,rollout:e,hasTranscript:!!i})}bindTranscript(t){if(!this.consolidator||!t||this.transcriptPath===t)return;this.transcriptPath=t;let e=new E.ToolReplayCursor({agent:"codex",sessionId:this.backendSessionId,canonicalPath:t,logger:this.deps.logger,root:this.deps.root,readBytes:this.deps.replayReadBytes,maxFrameBytes:this.deps.replayMaxFrameBytes});this.cursor=e,this.cursorRepaired=!1,this.cursorReady=e.load().catch(s=>this.deps.logger.warn("[tool-activity] codex cursor load failed (rescanning fresh)",{sessionId:this.backendSessionId,err:String(s)}));let i=this.deps.backstopIntervalMs??3e3;i>0&&!this.backstopTimer&&(this.backstopTimer=setInterval(()=>{this.runTranscriptBackstop().catch(s=>this.deps.logger.warn("[tool-activity] codex transcript backstop failed",{sessionId:this.backendSessionId,err:String(s)}))},i),this.backstopTimer.unref?.())}async observeCall(t,e){if(!this.consolidator||!this.sessionMap||!this.ownership||!t.callId||!t.toolName)return;let i=this.consolidator;await this.sessionMap.bindCall(this.ownership,t.callId);let s={id:t.callId,tool:t.toolName,normalizedTarget:kt(t.toolName,t.toolInput),ts:t.ts??new Date().toISOString(),byteOffset:t.byteOffset??0,...t.toolInput!==void 0?{digest:(0,E.digestOf)(t.toolInput)}:{}},r=await i.observe(s,e);return r==="closed"?await i.captureTerminal(s,this.deps.shutdownDrainMs??De)?"sealed-terminal":"closed":r}async runTranscriptBackstop(t=!1){await this.runTranscriptBackstopTurn(t)}runTranscriptBackstopTurn(t=!1){if(this.backstopInFlight)return this.backstopInFlight;let e=this.cursor,i=this.cursorReady,s=this.consolidator;if(!s||!e)return Promise.resolve("caught-up");let n=(async()=>{if(await i,this.cursor!==e)return"more";if(!this.cursorRepaired){if(await s.repairLostWindows(e),this.cursor!==e)return"more";this.cursorRepaired=!0}return this.doTranscriptBackstop(e,t)})().finally(()=>{this.backstopInFlight===n&&(this.backstopInFlight=null)});return this.backstopInFlight=n,n}async doTranscriptBackstop(t,e=!1){let i=this.consolidator;if(!i)return"caught-up";this.ledger&&await this.ledger.reloadLegacyOwned();for(let s=0;s<_t;s+=1){if(this.cursor!==t)return"caught-up";let r=await t.readFrames();if(r.missing)return"caught-up";if(r.frames.length===0)return r.carryover.length>0?Be(r):"caught-up";let n=Number.POSITIVE_INFINITY,a=e?{includeInFlight:!0}:void 0;for(let l of r.frames)for(let p of Ct(l.line,l.startOffset))await this.observeCall(p,a)==="deferred-in-flight"&&(n=Math.min(n,l.startOffset));if(await i.flush(),n<r.endOfComplete)return await t.checkpoint(n,{fileIdentity:r.fileIdentity,size:r.size,carryover:""}),"more";if(await t.checkpoint(r.endOfComplete,{fileIdentity:r.fileIdentity,size:r.size,carryover:r.carryover}),!r.hasMore)return r.carryover.length>0?Be(r):"caught-up"}return"more"}async flush(){await this.consolidator?.flush()}async stop(){this.backstopTimer&&(clearInterval(this.backstopTimer),this.backstopTimer=null),await this.runTranscriptBackstop().catch(()=>{});let t=Math.max(1,Math.trunc(this.deps.shutdownPartialNoProgressTurns??xt)),e=null,i=0;for(;;){let s=await this.runTranscriptBackstopTurn(!0);if(s==="caught-up")break;if(typeof s!="string"){if(s.progressKey===e?i+=1:(e=s.progressKey,i=1),i>=t){this.deps.logger.warn("[tool-activity] deferring unchanged incomplete rollout suffix during shutdown; the next owner will re-read it from the durable complete-line boundary",{size:s.size,carryoverBytes:s.carryoverBytes,endOfComplete:s.endOfComplete,unchangedTurns:i});break}await new Promise(r=>setTimeout(r,Tt))}else e=null,i=0,await new Promise(r=>setImmediate(r))}await this.consolidator?.drainSends(this.deps.shutdownDrainMs??De).catch(()=>{});try{await this.consolidator?.shutdown()}finally{await this.ownership?.release().catch(()=>{}),this.ownership=null,this.consolidator=null,this.ledger=null,this.sessionMap=null,this.cursor=null}}buildTransport(){let t=async(e,i,s)=>{let r=s?s.sessionKey:this.deps.getSessionKey();if(!r)throw new Error("[tool-activity] no session key at send (retryable)");let n=s?s.sessionKeyGen:this.deps.getSessionKeyGen();await this.deps.createEvent({sessionId:e,type:E.EventType.TOOL_ACTIVITY,source:E.EventSource.DESKTOP,content:this.deps.encryptContent(Rt,r),metadata:{encrypted:this.deps.encryptMetadata({manifest:i.manifest},r)},timestamp:i.windowStart,isEncrypted:!0,clientEventId:i.clientEventId,...n?{expectedSessionKeyGen:n}:{}})};return{send:async(e,i)=>{try{await t(e,i)}catch(s){if((0,E.isSessionKeyStaleError)(s)&&this.deps.refreshSessionKey){let r=await this.deps.refreshSessionKey(e);if(!r)throw s;await t(e,i,r);return}throw s}}}}};function Ct(c,t){let e;try{e=JSON.parse(c)}catch{return[]}if(e?.type!=="response_item"||!e.payload)return[];let i=e.payload,s=typeof e.timestamp=="string"?e.timestamp:new Date(0).toISOString();if(i.type==="function_call"&&typeof i.call_id=="string"&&typeof i.name=="string"){let r;try{r=JSON.parse(i.arguments||"{}")}catch{r={raw:i.arguments}}return[{callId:i.call_id,toolName:Ft(i.name),toolInput:r,ts:s,byteOffset:t}]}if(i.type==="custom_tool_call"&&typeof i.call_id=="string"){let r=Ot(typeof i.input=="string"?i.input:""),n=r?{file_path:r,patch:i.input}:{patch:i.input};return[{callId:i.call_id,toolName:"Edit",toolInput:n,ts:s,byteOffset:t}]}return[]}function Ft(c){return c==="shell"||c==="shell_command"||c==="local_shell"?"Bash":c==="apply_patch"?"Edit":c}function Ot(c){let t=c.match(/^\*\*\* (?:Update|Add|Delete) File: (.+)$/m);return t?t[1].trim():void 0}function kt(c,t){if(!t||typeof t!="object")return;let e=t,i=r=>typeof r=="string"&&r.length>0?r:void 0,s=Array.isArray(e.command)?e.command.filter(r=>typeof r=="string").join(" ").trim().split(/\s+/)[0]:typeof e.command=="string"?e.command.trim().split(/\s+/)[0]:void 0;return i(e.file_path)??i(e.path)??i(e.pattern)??i(e.url)??(s&&s.length>0?s:void 0)}var Le=require("events"),Ke=require("@quantiya/codevibe-core");var Q=class c extends Le.EventEmitter{constructor(){super();this.pendingCalls=new Map;this.timers=new Map;this.timeoutMs=(0,Ke.getConfig)().codex.approvalTimeoutMs,o.info("Approval detector initialized",{timeoutMs:this.timeoutMs})}onToolCallStart(e,i,s){o.debug("Tool call started",{callId:e,name:i});let r=this.parseInput(s),n=this.extractFilePath(i,s,r),a=this.extractDiff(i,s,r),l={callId:e,name:i,input:s,filePath:n,diff:a,parsedInput:r,timestamp:Date.now(),notificationSent:!1};if(this.pendingCalls.set(e,l),!this.shouldScheduleApprovalTimeout(i,r)){o.debug("Skipping approval timeout for non-escalated tool call",{callId:e,name:i});return}let p=setTimeout(()=>{this.checkPendingCall(e)},this.timeoutMs);this.timers.set(e,p)}onToolCallComplete(e){o.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;o.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 r=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(r)return`File: ${r[1].trim()}`}if(c.SHELL_TOOL_NAMES.has(e))try{let r=JSON.parse(i),n=typeof r.command=="string"?r.command:typeof r.cmd=="string"?r.cmd:void 0;if(n)return`Command: ${n.substring(0,50)}${n.length>50?"...":""}`}catch{}return`Tool: ${this.mapToolName(e)}`}mapToolName(e){return{exec_command:"Bash",shell_command:"Bash",shell:"Bash",exec:"Bash",local_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}}static{this.SHELL_TOOL_NAMES=new Set(["exec_command","shell_command","shell","exec","local_shell"])}shouldScheduleApprovalTimeout(e,i){return c.SHELL_TOOL_NAMES.has(e)?i?.sandbox_permissions==="require_escalated":!1}extractFilePath(e,i,s){if(e==="apply_patch"&&i){let n=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(n)return n[1].trim()}let r=s?.file_path||s?.path||s?.filePath;if(r&&typeof r=="string")return r}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(),o.debug("Approval detector cleared")}shutdown(){this.clear(),this.removeAllListeners(),o.info("Approval detector shutdown")}};var $e=require("child_process"),Ue=require("util");var ge=(0,Ue.promisify)($e.exec),H="__CODEVIBE_CODEX_KEY_ESCAPE__",Z=class{async sendInput(t,e){o.info("Attempting to send input to Codex",{sessionId:t,input:e});try{let i=process.env.CODEVIBE_CODEX_TMUX_SESSION;return i?(o.info("Using tmux send-keys",{tmuxSession:i}),e===H?await this.sendKeyViaTmux(i,"Escape"):await this.sendViaTmux(i,e),o.info("Successfully sent input to Codex",{sessionId:t,input:e}),!0):(o.error("No tmux session found - CodeVibe Companion launch is required",{sessionId:t,hint:"Start Codex CLI using `codevibe --agent codex`"}),!1)}catch(i){return o.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,"\\`");o.info("Sending via tmux",{sessionName:t,inputLength:e.length});try{let s=`tmux send-keys -t "${t}" -l "${i}"`;await ge(s),await this.delay(500);let r=`tmux send-keys -t "${t}" Enter`;await ge(r),o.info("tmux send-keys completed")}catch(s){throw o.error("tmux send-keys failed",{sessionName:t,error:s}),s}}async sendKeyViaTmux(t,e){o.info("Sending special key via tmux",{sessionName:t,key:e});try{let i=`tmux send-keys -t "${t}" ${e}`;await ge(i),o.info("tmux special-key send completed")}catch(i){throw o.error("tmux special-key send failed",{sessionName:t,key:e,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=T(require("fs")),te=T(require("os")),C=T(require("path")),W=require("crypto"),ze=require("child_process"),He=require("events"),We=require("util");var ye=(0,We.promisify)(ze.execFile),qe=512*1024,B="writer.state",At=2e3,Mt=10,Nt=16*1024*1024,Dt=10080*60*1e3,ee=class extends He.EventEmitter{constructor(e={}){super();this.sessionName=null;this.started=!1;this.pipeDirPath=null;this.pipeDirIdentity=null;this.pipeFilePath=null;this.pipeFileFd=null;this.pipeFileIdentity=null;this.writerStatePath=null;this.writerStateFd=null;this.writerStateIdentity=null;this.writerGeneration=null;this.pipeEnabled=!1;this.filePosition=0;this.pollTimer=null;this.processing=!1;this.pendingRead=!1;this.promptInspectionChain=Promise.resolve();this.lastPromptHash=null;this.lifecycleGeneration=0;this.retainedMirrors=[];this.retainedMirrorContainmentLost=!1;this.maxPaneFileBytes=e.maxPaneFileBytes??Nt,this.stalePaneRetentionMs=e.stalePaneRetentionMs??Dt,this.tempDir=e.tempDir??te.tmpdir(),this.writerPath=C.resolve(__dirname,"..","libexec","pane-mirror-writer.js");let i=e.runtimePlatform??process.platform,s=e.runtimeRelease??te.release();if(this.wslDetected=i==="linux"&&(/microsoft/i.test(s)||!!process.env.WSL_DISTRO_NAME||!!process.env.WSL_INTEROP),!Number.isSafeInteger(this.maxPaneFileBytes)||this.maxPaneFileBytes<=0)throw new RangeError("maxPaneFileBytes must be a positive safe integer");if(!Number.isSafeInteger(this.stalePaneRetentionMs)||this.stalePaneRetentionMs<0)throw new RangeError("stalePaneRetentionMs must be a non-negative safe integer")}async start(e){if(this.wslDetected)throw new Error("Tmux pane mirror fallback is disabled on unqualified WSL; using hook-based prompts only");if(this.started&&this.sessionName===e&&this.pipeEnabled){o.debug("Tmux pane observer already started",{sessionName:e});return}this.started&&await this.stop(),this.lifecycleGeneration++,this.sessionName=e,this.filePosition=0,this.lastPromptHash=null;try{if(this.cleanupStalePipeFiles(),this.reapOwnedRetainedMirrors(),this.retainedMirrorContainmentLost||this.retainedMirrors.length>0)throw new Error("Prior bounded tmux pane writer is still unconfirmed; refusing another mirror");this.createSecureMirror(),this.started=!0,await this.enablePipePane(),this.pipeEnabled=!0,this.startPolling()}catch(i){this.started=!1,this.lifecycleGeneration++;let s=this.writerGeneration===null;if(!s)try{await this.disablePipePane(),s=!0}catch(r){o.error("Failed to confirm tmux pane writer quiescence after startup failure",{disableError:r})}throw s&&(this.pipeEnabled=!1),this.clearPolling(),s?this.releaseSecureMirror():this.abandonSecureMirror(),this.resetLifecycleState(),i}o.info("Tmux pane observer started",{sessionName:e})}async stop(){if(!this.started&&this.pipeFileFd===null)return;this.started=!1,this.lifecycleGeneration++;let e=!1;try{await this.disablePipePane(),e=!0}catch(i){o.error("Failed to confirm tmux pane writer quiescence during stop",{error:i}),this.emit("observer-error",i)}e&&(this.pipeEnabled=!1),this.clearPolling(),e?this.releaseSecureMirror():this.abandonSecureMirror(),o.info("Tmux pane observer stopped",{sessionName:this.sessionName,writerQuiesced:e}),this.resetLifecycleState()}identityOf(e){return{dev:e.dev,ino:e.ino}}identitiesEqual(e,i){return e.dev===i.dev&&e.ino===i.ino}openMirrorFile(e){return g.openSync(e,g.constants.O_RDWR|g.constants.O_CREAT|g.constants.O_EXCL|(g.constants.O_NOFOLLOW??0),384)}truncateMirror(e){g.ftruncateSync(e,0)}createSecureMirror(){g.mkdirSync(this.tempDir,{recursive:!0,mode:448});let e=g.mkdtempSync(C.join(this.tempDir,`codevibe-codex-pane-${process.pid}-`));g.chmodSync(e,448);let i=C.join(e,"pane.log"),s=C.join(e,B),r=null,n=null;try{r=this.openMirrorFile(i),g.fchmodSync(r,384);let a=g.fstatSync(r);if(!a.isFile())throw new Error("Tmux pane mirror is not a regular file");n=this.openMirrorFile(s),g.fchmodSync(n,384);let l=g.fstatSync(n);if(!l.isFile())throw new Error("Tmux pane writer state is not a regular file");g.writeSync(n,Buffer.from(`idle
|
|
13
|
+
`),0,5,0),this.pipeDirPath=e,this.pipeDirIdentity=this.identityOf(g.lstatSync(e)),this.pipeFilePath=i,this.pipeFileFd=r,this.pipeFileIdentity=this.identityOf(a),this.writerStatePath=s,this.writerStateFd=n,this.writerStateIdentity=this.identityOf(l),r=null,n=null}catch(a){if(r!==null)try{g.closeSync(r)}catch{}if(n!==null)try{g.closeSync(n)}catch{}try{g.unlinkSync(i)}catch{}try{g.unlinkSync(s)}catch{}try{g.rmdirSync(e)}catch{}throw a}}pathMatchesMirrorIdentity(){if(!this.pipeFilePath||!this.pipeFileIdentity)return!1;try{let e=g.lstatSync(this.pipeFilePath);return e.isFile()&&!e.isSymbolicLink()&&this.identitiesEqual(this.pipeFileIdentity,this.identityOf(e))}catch{return!1}}quarantineIfIdentityMatches(e,i){let s=`${e}.reap-${process.pid}-${(0,W.randomBytes)(6).toString("hex")}`;try{g.renameSync(e,s);let r=g.lstatSync(s);return this.identitiesEqual(i,this.identityOf(r))?s:(g.existsSync(e)||g.renameSync(s,e),null)}catch{return null}}restoreQuarantine(e,i){try{g.existsSync(i)||g.renameSync(e,i)}catch{}}pathMatchesIdentity(e,i){if(!e||!i)return!1;try{let s=g.lstatSync(e);return s.isFile()&&!s.isSymbolicLink()&&this.identitiesEqual(i,this.identityOf(s))}catch{return!1}}closeOwnedDescriptors(){if(this.pipeFileFd!==null)try{g.closeSync(this.pipeFileFd)}catch{}if(this.writerStateFd!==null)try{g.closeSync(this.writerStateFd)}catch{}this.pipeFileFd=null,this.writerStateFd=null}unlinkOwnedFile(e,i){if(!e||!i||!this.pathMatchesIdentity(e,i))return;let s=this.quarantineIfIdentityMatches(e,i);s&&g.unlinkSync(s)}releaseSecureMirror(){let e=this.pipeFilePath,i=this.writerStatePath,s=this.pipeDirPath,r=this.pipeFileIdentity,n=this.writerStateIdentity;this.closeOwnedDescriptors();try{this.unlinkOwnedFile(e,r)}catch{}try{this.unlinkOwnedFile(i,n)}catch{}if(s)try{g.rmdirSync(s)}catch{}this.pipeDirPath=null,this.pipeDirIdentity=null,this.pipeFilePath=null,this.pipeFileIdentity=null,this.writerStatePath=null,this.writerStateIdentity=null,this.writerGeneration=null}abandonSecureMirror(){let e=this.pipeDirPath,i=this.pipeFilePath;e&&this.pipeDirIdentity&&i&&this.pipeFileIdentity&&this.writerStatePath&&this.writerStateIdentity&&this.writerGeneration?this.retainedMirrors.push({dirPath:e,dirIdentity:this.pipeDirIdentity,panePath:i,paneIdentity:this.pipeFileIdentity,statePath:this.writerStatePath,stateIdentity:this.writerStateIdentity,writerGeneration:this.writerGeneration}):(e||i)&&(this.retainedMirrorContainmentLost=!0),this.closeOwnedDescriptors(),o.warn("Retaining bounded tmux pane mirror because writer quiescence is unconfirmed",{retainedDir:e,retainedFile:i,maxBytes:this.maxPaneFileBytes}),this.pipeDirPath=null,this.pipeDirIdentity=null,this.pipeFilePath=null,this.pipeFileIdentity=null,this.writerStatePath=null,this.writerStateIdentity=null,this.writerGeneration=null}resetLifecycleState(){this.sessionName=null,this.pipeDirPath=null,this.pipeDirIdentity=null,this.pipeFilePath=null,this.pipeFileFd=null,this.pipeFileIdentity=null,this.writerStatePath=null,this.writerStateFd=null,this.writerStateIdentity=null,this.writerGeneration=null,this.pipeEnabled=!1,this.filePosition=0,this.processing=!1,this.pendingRead=!1,this.lastPromptHash=null}async failClosedPipe(e){let i=!1;try{await this.disablePipePane(),i=!0}catch(s){o.error("Failed to confirm unsafe tmux pane writer quiescence",{disableError:s})}i&&(this.pipeEnabled=!1),this.clearPolling(),o.error("Tmux pane mirror entered fail-closed containment after integrity/cap failure",{error:e,writerQuiesced:i,independentlyBounded:!0}),this.emit("observer-error",e)}resetLastPromptHash(){this.lastPromptHash=null}async captureSnapshot(e=120){if(!this.sessionName)throw new Error("Tmux pane observer is not started");let i=Math.max(1,Math.floor(e));try{let{stdout:s}=await ye("tmux",["capture-pane","-p","-e","-J","-S",`-${i}`,"-t",this.sessionName],{timeout:5e3,maxBuffer:2097152});return s}catch(s){throw o.error("Failed to capture tmux pane snapshot",{sessionName:this.sessionName,error:s}),this.emit("observer-error",s),s}}quoteShellArg(e){return`'${e.replace(/'/g,"'\\''")}'`}writerStatePathMatchesIdentity(){return this.pathMatchesIdentity(this.writerStatePath,this.writerStateIdentity)}writeWriterState(e){if(this.writerStateFd===null||!this.writerStateIdentity||!this.writerStatePathMatchesIdentity())throw new Error("Tmux pane writer state identity is not valid");let i=g.fstatSync(this.writerStateFd);if(!this.identitiesEqual(this.writerStateIdentity,this.identityOf(i)))throw new Error("Tmux pane writer state descriptor identity changed");let s=Buffer.from(e,"utf8");g.ftruncateSync(this.writerStateFd,0);let r=0;for(;r<s.length;){let n=g.writeSync(this.writerStateFd,s,r,s.length-r,r);if(n<=0)throw new Error("Short tmux pane writer-state write");r+=n}g.fsyncSync(this.writerStateFd)}readWriterState(){if(this.writerStateFd===null||!this.writerStateIdentity||!this.writerStatePathMatchesIdentity())throw new Error("Tmux pane writer state identity is not valid");let e=g.fstatSync(this.writerStateFd);if(!this.identitiesEqual(this.writerStateIdentity,this.identityOf(e)))throw new Error("Tmux pane writer state descriptor identity changed");let i=Math.min(e.size,512);if(i===0)return"";let s=Buffer.alloc(i),r=g.readSync(this.writerStateFd,s,0,i,0);return s.subarray(0,r).toString("utf8").trim()}async waitForWriterState(e,i,s=At){let r=Date.now()+s;do{let n=this.readWriterState();if(i.some(a=>n.startsWith(`${a} ${e} `)))return n;if(Date.now()>=r)return null;await new Promise(a=>setTimeout(a,Mt))}while(!0)}async enablePipePane(){if(!this.sessionName||!this.pipeFilePath||!this.writerStatePath)throw new Error("Tmux pane observer is not initialized");if(this.pipeFileFd===null||!this.pipeFileIdentity||!this.pathMatchesMirrorIdentity()||this.writerStateFd===null||!this.writerStateIdentity||!this.writerStatePathMatchesIdentity())throw new Error("Tmux pane mirror identity is not valid");let e=(0,W.randomBytes)(16).toString("hex");this.writerGeneration=e,this.writeWriterState(`starting ${e}
|
|
14
|
+
`);let i=[process.execPath,this.writerPath,this.pipeFilePath,String(this.pipeFileIdentity.dev),String(this.pipeFileIdentity.ino),this.writerStatePath,String(this.writerStateIdentity.dev),String(this.writerStateIdentity.ino),e,String(this.maxPaneFileBytes)].map(r=>this.quoteShellArg(r)).join(" ");try{await ye("tmux",["pipe-pane","-O","-t",this.sessionName,i])}catch(r){throw this.writerGeneration=null,r}let s=await this.waitForWriterState(e,["ready","done"]);if(!s)throw new Error("Tmux pane writer did not confirm startup");if(s.startsWith(`done ${e} `))throw new Error("Tmux pane writer terminated during startup");o.debug("Enabled tmux pipe-pane mirroring",{sessionName:this.sessionName,pipeFilePath:this.pipeFilePath,writerGeneration:e})}async disablePipePane(){let e=this.writerGeneration;if(!this.sessionName||!e)return;let i=null;try{await ye("tmux",["pipe-pane","-t",this.sessionName])}catch(n){i=n}if(!e){if(i)throw i;return}if(await this.waitForWriterState(e,["done"])){this.writerGeneration=null;return}let r=i instanceof Error?`: ${i.message}`:"";throw new Error(`Tmux pane writer quiescence was not confirmed${r}`)}startPolling(){this.clearPolling(),this.pollTimer=setInterval(()=>{this.processFileChanges()},100),this.pollTimer.unref?.()}clearPolling(){this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null}async processFileChanges(){if(!(!this.started||!this.pipeFilePath)){if(this.processing){this.pendingRead=!0;return}this.processing=!0;try{do{this.pendingRead=!1;let e="";try{e=this.readAppendedChunk()}catch(i){o.error("Failed to read bounded tmux pane mirror",{error:i}),await this.failClosedPipe(i);return}await this.rotatePipeFileIfNeeded(),e&&this.queuePromptInspection(e,this.lifecycleGeneration)}while(this.pendingRead)}catch(e){o.error("Failed to process tmux pane changes",{error:e}),this.emit("observer-error",e)}finally{this.processing=!1}}}queuePromptInspection(e,i){this.promptInspectionChain=this.promptInspectionChain.then(async()=>{if(!(!this.started||this.lifecycleGeneration!==i))try{await this.inspectChunkForPrompt(e)}catch(s){o.error("Failed to inspect tmux pane delta",{error:s}),this.emit("observer-error",s)}})}async inspectChunkForPrompt(e){if(!this.looksLikePromptDelta(e))return;let i=await this.captureSnapshot();this.inspectSnapshotForPrompt(i,e)}inspectSnapshotForPrompt(e,i){let s=e?this.extractActiveApprovalBlock(e):null;if(!s){e&&o.debug("tmux delta cue matched but no active dialog isolated (no candidate emitted)",{snapshotTail:e.split(`
|
|
15
|
+
`).slice(-6).join("\\n")});return}let r=this.hashPromptSnapshot(s);r!==this.lastPromptHash&&(this.lastPromptHash=r,this.emit("prompt-candidate",{rawDelta:i,snapshot:s,detectedAt:Date.now()}))}queueCurrentSnapshotInspection(e){this.promptInspectionChain=this.promptInspectionChain.then(async()=>{if(!(!this.started||this.lifecycleGeneration!==e))try{let i=await this.captureSnapshot();this.inspectSnapshotForPrompt(i,"")}catch(i){o.error("Failed to inspect tmux pane snapshot after rotation",{error:i}),this.emit("observer-error",i)}})}async rotatePipeFileIfNeeded(){let e=this.pipeFilePath,i=this.pipeFileFd,s=this.pipeFileIdentity,r=this.sessionName,n=this.lifecycleGeneration;if(!e||i===null||!s||!r||!this.started)return;let a;try{let p=g.fstatSync(i);if(!this.identitiesEqual(s,this.identityOf(p)))throw new Error("Tmux pane mirror descriptor identity changed");a=p.size}catch(p){await this.failClosedPipe(p);return}if(a<this.maxPaneFileBytes)return;let l="";try{await this.disablePipePane(),this.pipeEnabled=!1}catch(p){o.error("Tmux pane mirror rotation deferred because writer quiescence is unconfirmed",{error:p}),this.emit("observer-error",p),this.clearPolling();return}if(!(!this.started||this.lifecycleGeneration!==n||this.pipeFilePath!==e)){try{l=this.readAppendedChunk()}catch(p){o.error("Failed to drain final tmux pane suffix during rotation; mirror remains intact and disabled",{error:p}),this.emit("observer-error",p),this.clearPolling();return}try{this.truncateMirror(i);let p=g.fstatSync(i);if(!this.identitiesEqual(s,this.identityOf(p))||p.size!==0)throw new Error("Tmux pane mirror truncation could not be verified");if(!this.pathMatchesMirrorIdentity())throw new Error("Tmux pane mirror path was replaced during rotation")}catch(p){o.error("Tmux pane mirror remains disabled after truncation verification failure",{error:p}),this.emit("observer-error",p),this.clearPolling();return}if(this.filePosition=0,o.info("Rotated bounded tmux pane mirror",{sessionName:r,priorBytes:a,maxBytes:this.maxPaneFileBytes}),this.started&&this.lifecycleGeneration===n&&this.pipeFilePath===e&&this.sessionName===r)try{await this.enablePipePane(),this.pipeEnabled=!0}catch(p){this.pipeEnabled=!1,o.error("Tmux pane mirror remains disabled after re-enable failure",{error:p}),this.emit("observer-error",p),this.clearPolling()}l&&this.queuePromptInspection(l,n),this.pipeEnabled&&this.queueCurrentSnapshotInspection(n)}}retainedPathMatchesIdentity(e,i,s){try{let r=g.lstatSync(e);return(s==="file"?r.isFile():r.isDirectory())&&!r.isSymbolicLink()&&(typeof process.getuid!="function"||r.uid===process.getuid())&&this.identitiesEqual(i,this.identityOf(r))}catch{return!1}}readRetainedWriterState(e,i){let s=null;try{s=g.openSync(e,g.constants.O_RDONLY|(g.constants.O_NOFOLLOW??0));let r=g.fstatSync(s);if(!r.isFile()||typeof process.getuid=="function"&&r.uid!==process.getuid()||!this.identitiesEqual(i,this.identityOf(r))||r.size>512)return null;let n=Buffer.alloc(r.size),a=r.size===0?0:g.readSync(s,n,0,r.size,0);return n.subarray(0,a).toString("utf8").trim()}catch{return null}finally{if(s!==null)try{g.closeSync(s)}catch{}}}reapOwnedRetainedMirror(e){if(!this.retainedPathMatchesIdentity(e.dirPath,e.dirIdentity,"directory"))return!1;let i;try{i=g.readdirSync(e.dirPath).sort()}catch{return!1}if(i.length!==2||i[0]!=="pane.log"||i[1]!==B||!this.retainedPathMatchesIdentity(e.panePath,e.paneIdentity,"file")||!this.retainedPathMatchesIdentity(e.statePath,e.stateIdentity,"file"))return!1;let s=new RegExp(`^done ${e.writerGeneration} \\d+ \\d+$`);if(!s.test(this.readRetainedWriterState(e.statePath,e.stateIdentity)??""))return!1;let r=this.quarantineIfIdentityMatches(e.dirPath,e.dirIdentity);if(!r)return!1;let n=!1;try{let a=C.join(r,"pane.log"),l=C.join(r,B);if(!this.retainedPathMatchesIdentity(a,e.paneIdentity,"file"))throw new Error("pane identity changed");if(!this.retainedPathMatchesIdentity(l,e.stateIdentity,"file"))throw new Error("state identity changed");if(!s.test(this.readRetainedWriterState(l,e.stateIdentity)??""))throw new Error("writer generation is no longer done");if(this.unlinkOwnedFile(a,e.paneIdentity),this.unlinkOwnedFile(l,e.stateIdentity),g.existsSync(a)||g.existsSync(l))throw new Error("retained mirror unlink was incomplete");g.rmdirSync(r),n=!0,o.info("Removed completed same-owner tmux pane mirror",{retainedDir:e.dirPath})}catch{g.existsSync(r)&&this.restoreQuarantine(r,e.dirPath)}return n}reapOwnedRetainedMirrors(){this.retainedMirrors=this.retainedMirrors.filter(e=>!this.reapOwnedRetainedMirror(e))}cleanupStalePipeFiles(){let e=Date.now()-this.stalePaneRetentionMs,i;try{i=g.readdirSync(this.tempDir,{withFileTypes:!0})}catch{return}for(let s of i){let r=/^codevibe-codex-pane-(\d+)\.log$/.exec(s.name);if(r){let p=C.join(this.tempDir,s.name),d=null;try{let u=g.lstatSync(p);if(!u.isFile()||u.isSymbolicLink()||u.mtimeMs>e||typeof process.getuid=="function"&&u.uid!==process.getuid()||this.isProcessAlive(Number(r[1]))||(d=this.quarantineIfIdentityMatches(p,this.identityOf(u)),!d))continue;g.unlinkSync(d),d=null,o.info("Removed stale legacy tmux pane mirror",{candidate:p,ageMs:Date.now()-u.mtimeMs})}catch{d&&this.restoreQuarantine(d,p)}continue}let n=/^codevibe-codex-pane-(\d+)-[A-Za-z0-9_-]+$/.exec(s.name);if(!n||!s.isDirectory())continue;let a=C.join(this.tempDir,s.name),l=null;try{let p=g.lstatSync(a);if(!p.isDirectory()||p.isSymbolicLink()||p.mtimeMs>e||typeof process.getuid=="function"&&p.uid!==process.getuid())continue;let d=Number(n[1]);if(this.isProcessAlive(d)||(l=this.quarantineIfIdentityMatches(a,this.identityOf(p)),!l))continue;let u=C.join(l,"pane.log"),f=C.join(l,B),v=g.readdirSync(l);if(v.some(h=>h!=="pane.log"&&h!==B)){this.restoreQuarantine(l,a);continue}for(let h of v.map(y=>C.join(l,y))){let y=g.lstatSync(h);if(!y.isFile()||y.isSymbolicLink()||typeof process.getuid=="function"&&y.uid!==process.getuid()){this.restoreQuarantine(l,a),l=null;break}}if(!l)continue;if(v.includes(B)){let h=g.readFileSync(f,"utf8").trim(),y=/^ready [a-f0-9]{32} (\d+)$/.exec(h);if(!(h==="idle"||/^done [a-f0-9]{32} \d+ \d+$/.test(h)||!!y)||y&&this.isProcessAlive(Number(y[1]))){this.restoreQuarantine(l,a);continue}}v.includes("pane.log")&&g.unlinkSync(u),v.includes(B)&&g.unlinkSync(f),g.rmdirSync(l),l=null,o.info("Removed stale tmux pane mirror directory",{candidate:a,ageMs:Date.now()-p.mtimeMs})}catch{l&&this.restoreQuarantine(l,a)}}}isProcessAlive(e){try{return process.kill(e,0),!0}catch(i){return i?.code==="EPERM"}}readAppendedChunk(){if(!this.pipeFilePath||this.pipeFileFd===null||!this.pipeFileIdentity)return"";if(!this.pathMatchesMirrorIdentity())throw new Error("Tmux pane mirror path was replaced");let e=g.fstatSync(this.pipeFileFd);if(!this.identitiesEqual(this.pipeFileIdentity,this.identityOf(e)))throw new Error("Tmux pane mirror descriptor identity changed");if(e.size<=this.filePosition)return"";{let s=e.size-this.filePosition>qe?e.size-qe:this.filePosition,r=e.size-s,n=Buffer.alloc(r),a=0;for(;a<r;){let l=g.readSync(this.pipeFileFd,n,a,r-a,s+a);if(l===0)break;a+=l}return this.filePosition=s+a,n.subarray(0,a).toString("utf-8")}}looksLikePromptDelta(e){return/Would you like to run/i.test(e)||/Press enter to confirm/i.test(e)||/\besc to cancel\b/i.test(e)||/\bYes,\s+proceed\b/i.test(e)||/\bNo,\s+and tell Codex\b/i.test(e)||/don't ask again/i.test(e)||/Requesting permission for:|Do you want to proceed\?/i.test(e)||/\[(?:y\/n|Y\/n|y\/N)\]|\b(?:apply|approve|allow|reject|deny|continue)\b/i.test(e)}looksLikePromptSnapshot(e){return this.extractActiveApprovalBlock(e)!==null}extractActiveApprovalBlock(e){let s=e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"").split(`
|
|
16
|
+
`).map(h=>h.replace(/\s+$/,"")),r=h=>h.trim().length>0,n=h=>{let y=h.trim();return/^(?:[>›❯]\s*)?press enter to confirm(?: or esc to cancel)?$/i.test(y)||/^(?:[>›❯]\s*)?(?:press )?esc to cancel$/i.test(y)},a=h=>/Would you like to |Do you want to |The model would like to |Allow .+ to run|Requesting permission for:/i.test(h),l=h=>/^[>›❯\s]*[1-9][.)]\s+\S/.test(h),p=h=>/\[(?:y\/n|Y\/n|y\/N)\]/i.test(h),d=h=>{let y=new Set;for(let S of h)l(S)&&(/\bYes,\s+proceed\b/i.test(S)&&y.add("proceed"),/\bNo,\s+and tell Codex\b/i.test(S)&&y.add("reject"),/don't ask again/i.test(S)&&y.add("dont-ask"));return y.size},u=h=>l(h)&&(/\bYes,\s+proceed\b/i.test(h)||/\bNo,\s+and tell Codex\b/i.test(h)||/don't ask again/i.test(h)),f=-1;for(let h=s.length-1;h>=0;h--)if(r(s[h])){f=h;break}if(f===-1)return null;if(p(s[f])){let h=f;for(let y=f-1;y>=0&&f-y<=8&&!(!r(s[y])||n(s[y])||l(s[y]));y--)h=y;return s.slice(h,f+1).join(`
|
|
17
|
+
`)}let v=-1;for(let h=s.length-1;h>=0;h--)if(n(s[h])){v=h;break}if(v===f){let h=-1;for(let S=v-1;S>=0&&!n(s[S]);S--)if(a(s[S])){h=S;break}if(h===-1)return null;let y=s.slice(h,v+1);return y.some(l)?y.join(`
|
|
18
|
+
`):null}if(u(s[f])){let h=-1;for(let P=f-1;P>=0;P--){if(n(s[P]))return null;if(a(s[P])){h=P;break}}if(h===-1)return null;let y=P=>{let _=P.match(/^[>›❯\s]*([1-9])[.)]\s/);return _?parseInt(_[1],10):null},S=[],w=Number.POSITIVE_INFINITY;for(let P=f;P>h&&l(s[P]);P--){let _=y(s[P]);if(_===null||_>=w)break;S.push(s[P]),w=_}return d(S)<2?null:s.slice(h,f+1).join(`
|
|
16
19
|
`)}return null}hashPromptSnapshot(e){let i=e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"").replace(/\r/g,`
|
|
17
20
|
`).replace(/[ \t]+\n/g,`
|
|
18
|
-
`).trim();return(0,
|
|
19
|
-
`),e=o=>/^[\s>]*\d+\.\s/.test(o),i=-1;for(let o=t.length-1;o>=0;o-=1)if(/^\s*\$\s+/.test(t[o])){i=o;break}if(i===-1)return;let s=t[i].trim().match(/^\$\s+(.+)$/);if(!s?.[1]?.trim())return;let r=[s[1].trim()];for(let o=i+1;o<t.length;o+=1){let a=t[o];if(e(a)||/^\s*$/.test(a)||/^\s*\$\s+/.test(a))break;r.push(a.trim())}return r.length>0?r:void 0}function et(p){let t=Se(p);if(!t)return;let e=t.join(" ").trim();return e.length>0?e:void 0}var se=class p{constructor(){this.sessionState=null;this.unsubscribe=null;this.sessionKey=null;this.sessionIsEncrypted=!1;this.sessionKeyGen=null;this.e1PromptRaises=new Map;this.e1NeedsReRaise=new Set;this.e1RetirementOrphans=new Map;this.e1ContentKeyIndex=new Map;this.e1TtlRefreshTimer=null;this.toolActivity=null;this.toolActivityStartPromise=null;this.toolActivityLegacyRecorders=new Map;this.pendingInteractivePrompt=null;this.queuedInteractivePrompts=[];this.isInitializingSession=!1;this.bufferedLogEntries=[];this.logEntryChain=Promise.resolve();this.hookEventChain=Promise.resolve();this.hooksActive=!1;this.hooksCompatibilityNoticeSent=!1;this.resolvedApprovalDedupeKeys=new Map;this.subscribedSessionId=null;this.subscribedSessionState=null;this.terminalInputChain=Promise.resolve();this.terminalInputBlockedStates=new WeakSet;this.mobilePromptDeduper=new ee({expiryMs:1e4});this.launchSessionInitPromise=null;this.sessionStartedInitPromise=null;this.bootstrapSessionId=null;this.recoveryBootstrapOwnerBound=!1;this.resumeBackendSession=u.resumeOrCreateSession;this.sessionBootstrapFailureCount=0;this.sessionBootstrapRetryAt=0;this.retiredSessionRecoveryPromise=null;this.lifecycleGeneration=0;this.isStopping=!1;this.tmuxLifecycleTimer=null;this.tmuxLifecycleCheckInFlight=!1;this.tmuxLifecycleObservedAlive=!1;this.v1Bridge=new ie;this.orchestrationClient=null;this.userDecisionUnsubscribe=null;this.httpApi=new Z,this.sessionWatcher=new j,this.approvalDetector=new Y,this.promptResponder=new X,this.tmuxPaneObserver=new J}static{this.E1_TTL_REFRESH_MS=300*1e3}async start(){n.info("Starting CodeVibe Codex companion server",{environment:(0,u.getEnvironment)()}),this.appSyncClient=new u.AppSyncClient,await this.appSyncClient.authenticateWithStoredTokens()||(n.error('Authentication failed. Run "codevibe login" first.'),console.error('Not authenticated. Run "codevibe login" to sign in.'),process.exit(1)),n.info("Authenticated successfully",{userId:this.appSyncClient.getCurrentUserId(),email:this.appSyncClient.getCurrentUserEmail()}),await(0,u.registerDeviceEncryptionKey)(this.appSyncClient,n),(0,u.startDeviceKeyWatcher)(this.appSyncClient,n),(0,u.pushDetectedAgents)(this.appSyncClient,n).catch(i=>{n.warn("Failed to update available agents (non-fatal)",{error:i?.message})});try{let i=await this.appSyncClient.sweepOrphanSessions({agentType:"CODEX"});i>0&&n.info("Orphan sweep: marked stale Codex sessions INACTIVE",{swept:i})}catch(i){n.warn("Orphan sweep failed, continuing startup",{error:i instanceof Error?i.message:String(i)})}this.httpApi.onEvent(this.handleEventFromHook.bind(this));let e=await this.httpApi.start();n.info("HTTP API started for hooks",{port:e}),this.startTmuxLifecycleMonitor(),await this.createLaunchSession(),this.setupEventHandlers(),this.sessionWatcher.start(),n.info("CodeVibe Codex companion server started")}async createLaunchSession(){if(this.isStopping)return;if(process.env[ge]==="1"){n.info("Recovery daemon deferring backend bootstrap until the native rollout is known");return}let t=this.lifecycleGeneration,e=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!e){n.warn("No CODEVIBE_CODEX_TMUX_SESSION \u2014 skipping launch session");return}let i;this.launchSessionInitPromise=new Promise(s=>{i=s});try{let s=process.env.CODEX_WORKING_DIRECTORY||process.cwd(),r=this.getOrCreateBootstrapSessionId(),o=this.appSyncClient.getCurrentUserId();n.info("Creating launch session",{sessionId:r,projectPath:s});let a=!1;try{let l=await(0,u.resumeOrCreateSession)({sessionId:r,userId:o,agentType:u.AgentType.CODEX,projectPath:s,metadata:{launchSession:!0}},this.appSyncClient,n);if(r=l.sessionId,!this.isLifecycleCurrent(t)){await this.retireCancelledBootstrap(r,"launch_session");return}this.sessionKey=l.sessionKey,this.sessionKeyGen=l.sessionKeyGen,this.sessionIsEncrypted=!!l.sessionKey,a=!0,this.sessionState={sessionId:r,userId:o,projectPath:s,cwd:s,createdAt:new Date,subscriptionActive:!1,metadata:{launchSession:!0},encryptionSnapshot:{sessionKey:l.sessionKey,sessionIsEncrypted:!!l.sessionKey},codexSessionId:e,codexLogFile:void 0},this.clearSessionBootstrapFailure(),this.bootstrapSessionId=null,await P("daemon_init_step_completed",{step:"session_resume_or_create",path:"launch_session"})}catch(l){if(!this.isLifecycleCurrent(t)){let c=this.authoritativeSessionIdFromError(l)??r;await this.retireCancelledBootstrap(c,"launch_session_error");return}await P("daemon_init_step_failed",{step:"session_resume_or_create",path:"launch_session",error_class:l?.name||"Error",error_message:l?.message||String(l)}),l?.code==="ENCRYPTED_SESSION_NO_KEY"&&(this.sessionIsEncrypted=!0,this.sessionKey=null),this.bindBootstrapIdentityFromError(l),this.recordSessionBootstrapFailure(l,"launch_session"),n.error("Failed to create/resume launch session (non-fatal)",{error:l})}if(!a)return;await P("daemon_init_step_completed",{step:"session_state_set",path:"launch_session"});try{this.subscribeToMobileEvents(r)?await P("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"launch_session"}):await P("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(l){await P("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:l?.name||"Error",error_message:l?.message||String(l)}),n.error("Failed to subscribe to mobile events for launch session",{error:l})}try{await this.appSyncClient.startHeartbeat(r)?await P("daemon_init_step_completed",{step:"heartbeat_start",path:"launch_session"}):(await P("daemon_init_step_failed",{step:"heartbeat_start",path:"launch_session",error_class:"InitialHeartbeatNotPersisted",error_message:"Backend did not confirm the initial heartbeat mutation"}),n.error("Initial launch-session heartbeat was not persisted",{sessionId:r}))}catch(l){await P("daemon_init_step_failed",{step:"heartbeat_start",path:"launch_session",error_class:l?.name||"Error",error_message:l?.message||String(l)}),n.error("Failed to start heartbeat for launch session",{error:l})}try{await this.subscribeToOnApplyUserDecision(r)}catch(l){n.error("Failed to subscribe to onApplyUserDecision for launch session (non-fatal)",{error:l})}this.startMobileEndWatcher(r),n.info("Launch session created",{sessionId:r})}finally{i()}}encryptForEmit(t,e,i,s){let r=this.sessionState;if(!r||r.sessionId!==s||!r.encryptionSnapshot)return n.warn("Dropping event from stale or unresolved session generation (#638)",{type:i,sessionId:s,currentSessionId:r?.sessionId}),null;let{sessionKey:o,sessionIsEncrypted:a}=r.encryptionSnapshot,l=(0,u.encryptForEmit)(o,a,t,e);return l===null&&n.error("No session key for ENCRYPTED session \u2014 dropping event (fail-closed, #638)",{type:i,sessionId:s}),l}newE1Raise(t,e,i){let{record:s}=(0,u.newPromptRaise)({sessionId:t,producerKind:"PLUGIN_APPROVAL",mobileActionable:e,agentType:"CODEX",...i!==void 0&&{title:i}});return this.e1PromptRaises.set(s.promptId,{record:s}),this.e1TtlRefreshTimer||this.startE1TtlRefresh(),s}stashE1RaiseContent(t,e,i){let s=this.e1PromptRaises.get(t);s&&(s.contentPlain=e,s.metadataPlain=i)}async emitSuppressedPromptCarrier(t,e){let i="\u26A0\uFE0F A prompt is waiting in your desktop terminal, but its options could not be shown here. Please answer it on your desktop.",s=this.encryptForEmit(i,{e1SuppressedPrompt:!0},u.EventType.NOTIFICATION,t);return s?(await this.appSyncClient.createEvent({sessionId:t,type:u.EventType.NOTIFICATION,source:u.EventSource.DESKTOP,content:s.content,metadata:s.metadata,...(0,u.raiseFieldsFromRecord)(e),notificationText:i,timestamp:(0,u.prepareEventTimestamp)({orderingKey:t}),isEncrypted:s.isEncrypted?!0:void 0}),n.info("E1: emitted suppressed-prompt badge carrier (mobileActionable=false)",{sessionId:t,promptId:e.promptId}),!0):!1}raiseSuppressedBadge(t,e){if(e){let s=`${t}::${e}`,r=this.e1ContentKeyIndex.get(s);if(r&&this.e1PromptRaises.has(r))return;r&&this.e1ContentKeyIndex.delete(s)}let i=this.newE1Raise(t,!1);e&&this.e1ContentKeyIndex.set(`${t}::${e}`,i.promptId),this.emitSuppressedPromptCarrier(t,i).catch(s=>{n.error("E1: failed to emit suppressed-prompt badge carrier",{sessionId:t,promptId:i.promptId,error:s instanceof Error?s.message:String(s)})})}snapshotOpenE1(t){return[...this.e1PromptRaises.values()].filter(e=>e.record.sessionId===t).map(e=>({record:{...e.record},...e.contentPlain!==void 0&&{contentPlain:e.contentPlain},...e.metadataPlain!==void 0&&{metadataPlain:e.metadataPlain}}))}parkRetirementOrphans(t){for(let e of this.snapshotOpenE1(t))this.e1RetirementOrphans.set(e.record.promptId,e)}async drainRetirementOrphans(t){if(this.e1RetirementOrphans.size!==0){n.info("E1 (\xA76a-4): re-homing parked retirement-orphan prompts onto replacement session",{replacementSessionId:t,count:this.e1RetirementOrphans.size});for(let[e,i]of[...this.e1RetirementOrphans]){let r=this.e1PromptRaises.get(e)??{record:{...i.record},...i.contentPlain!==void 0&&{contentPlain:i.contentPlain},...i.metadataPlain!==void 0&&{metadataPlain:i.metadataPlain}};if(r.record.sessionId=t,this.e1PromptRaises.set(e,r),!await this.reRaiseOneE1(t,r,{untilAck:!0}))break;this.e1RetirementOrphans.delete(e)}this.e1TtlRefreshTimer||this.startE1TtlRefresh()}}isReRaiseTargetCurrent(t){return!this.isStopping&&this.sessionState!==null&&this.sessionState.sessionId===t}async reRaiseOneE1(t,e,i){let s=e.record,r=s.mobileActionable&&e.contentPlain!==void 0,o=i?.untilAck??!1,a=4,l=4e3;for(let c=1;o||c<=a;c++){if(o&&!this.isReRaiseTargetCurrent(t))return this.e1NeedsReRaise.add(s.promptId),n.warn("E1: retirement re-raise aborted (stopping/superseded) \u2014 parked",{sessionId:t,promptId:s.promptId}),!1;try{if(r){let d=this.encryptForEmit(e.contentPlain,e.metadataPlain??{},u.EventType.INTERACTIVE_PROMPT,t);if(!d)return!1;await this.appSyncClient.createEvent({sessionId:t,type:u.EventType.INTERACTIVE_PROMPT,source:u.EventSource.DESKTOP,content:d.content,metadata:d.metadata,...(0,u.raiseFieldsFromRecord)(s),timestamp:(0,u.prepareEventTimestamp)({orderingKey:t}),...d.isEncrypted?{isEncrypted:!0}:{}})}else if(s.mobileActionable=!1,!await this.emitSuppressedPromptCarrier(t,s))return!1;return this.e1NeedsReRaise.delete(s.promptId),n.info("E1: re-raised prompt onto replacement session",{sessionId:t,promptId:s.promptId,actionable:r}),!0}catch(d){if(!o&&c===a)return this.e1NeedsReRaise.add(s.promptId),n.error("E1: re-raise unacked after backoff \u2014 parked for retry-until-ack",{sessionId:t,promptId:s.promptId,error:d instanceof Error?d.message:String(d)}),!1;if(o){let h=Date.now()+Math.min(250*2**(c-1),l);for(;Date.now()<h&&this.isReRaiseTargetCurrent(t);)await new Promise(g=>setTimeout(g,Math.min(50,h-Date.now())))}else await new Promise(h=>setTimeout(h,250*c))}}return!1}async drainPendingE1ReRaises(){if(this.e1NeedsReRaise.size!==0)for(let t of[...this.e1NeedsReRaise]){let e=this.e1PromptRaises.get(t);if(!e){this.e1NeedsReRaise.delete(t);continue}!this.sessionState||e.record.sessionId!==this.sessionState.sessionId||await this.reRaiseOneE1(e.record.sessionId,e)}}async refreshE1Ttls(){await this.drainPendingE1ReRaises();let t=this.sessionState?.sessionId;if(!t)return;let e=[...this.e1PromptRaises.values()].filter(i=>i.record.sessionId===t).map(i=>i.record.promptId);if(e.length!==0)try{let i=await this.appSyncClient.refreshOpenPromptTtl(e);for(let s of i){let r=this.e1PromptRaises.get(s);r&&r.record.sessionId===t&&await this.reRaiseOneE1(t,r)}}catch(i){n.warn("E1: TTL-refresh tick failed (non-fatal, retries next tick)",{error:i instanceof Error?i.message:String(i)})}}startE1TtlRefresh(){this.e1TtlRefreshTimer&&clearInterval(this.e1TtlRefreshTimer),this.e1TtlRefreshTimer=setInterval(()=>{this.refreshE1Ttls()},p.E1_TTL_REFRESH_MS)}stopE1TtlRefresh(){this.e1TtlRefreshTimer&&(clearInterval(this.e1TtlRefreshTimer),this.e1TtlRefreshTimer=null)}isExpectedSessionStateCurrent(t){return!this.isStopping&&this.sessionState===t&&!this.terminalInputBlockedStates.has(t)}sendSessionPinnedInput(t,e){if(!this.isExpectedSessionStateCurrent(t)||this.terminalInputBlockedStates.has(t))return Promise.resolve(!1);let i=this.terminalInputChain.then(async()=>!this.isExpectedSessionStateCurrent(t)||this.terminalInputBlockedStates.has(t)?!1:this.promptResponder.sendInput(t.sessionId,e));return this.terminalInputChain=i.then(()=>{},()=>{}),i}handleEventFromHook(t){if(this.isStopping)return Promise.resolve();let e=this.lifecycleGeneration,i=this.hookEventChain.then(()=>this.processHookEvent(t,e));return this.hookEventChain=i.catch(s=>{n.error("[Hooks] event handler failed",{hookEvent:t.hook_event_name,sessionId:t.session_id,error:s instanceof Error?s.message:String(s)})}),i}async processHookEvent(t,e){if(!this.isLifecycleCurrent(e))return;let{session_id:i,hook_event_name:s,type:r,content:o,metadata:a}=t;n.info("[Hooks] Received event",{sessionId:i,hookEvent:s,type:r,contentLength:o?.length});let l=this.sessionWatcher.getAuthoritativeSessionId();if(l&&l!==i){n.warn("[Hooks] Rejecting event for foreign native session",{hookEvent:s,sessionId:i,authoritativeSessionId:l});return}if(a?.transcript_path){let h=await this.sessionWatcher.bindToSessionTranscript(a.transcript_path,i);if(!this.isLifecycleCurrent(e))return;let g=h.status==="pending"?await h.completion:h;if(!this.isLifecycleCurrent(e))return;if(g.status!=="bound"){n.warn("[Hooks] Rejecting event whose transcript ownership was not proven",{hookEvent:s,sessionId:i,reason:g.reason});return}}else if(l!==i){n.warn("[Hooks] Rejecting event without an owned transcript",{hookEvent:s,sessionId:i});return}if(!this.isLifecycleCurrent(e)||this.sessionWatcher.getAuthoritativeSessionId()!==i){n.warn("[Hooks] Rejecting event after ownership changed during admission",{hookEvent:s,sessionId:i,authoritativeSessionId:this.sessionWatcher.getAuthoritativeSessionId()});return}if(this.hooksActive=!0,s==="SessionStart"){if(this.launchSessionInitPromise&&(await this.launchSessionInitPromise,!this.isLifecycleCurrent(e)))return;if(this.sessionState){if(n.info("[Hooks] SessionStart \u2014 launch session already exists, updating codexSessionId",{existingSessionId:this.sessionState.sessionId,codexSessionId:i}),this.sessionState.codexSessionId=i,this.sessionState.metadata={...this.sessionState.metadata,codexSessionId:i,cliVersion:a?.model||"unknown",modelProvider:a?.model||"unknown",launchSession:void 0},this.appSyncClient.updateSession({sessionId:this.sessionState.sessionId,metadata:this.sessionState.metadata}).catch(h=>n.warn("Failed to update session metadata",{error:h})),await this.startTmuxObserverWithBeacon("session_start_existing"),!this.isLifecycleCurrent(e))return;await this.ensureToolActivityStarted(i)}else{let h={id:i,timestamp:new Date().toISOString(),cwd:a?.cwd||process.cwd(),originator:"hook",cli_version:a?.model||"unknown",instructions:null,source:a?.source||"startup",model_provider:a?.model||"unknown"};await this.ensureSessionStarted(h)}return}if(!this.sessionState){n.warn("[Hooks] Hook event for un-bootstrapped session \u2014 self-healing via session bootstrap (#638)",{hookEvent:s,sessionId:i});let h={id:i,timestamp:new Date().toISOString(),cwd:a?.cwd||process.cwd(),originator:"hook",cli_version:a?.model||"unknown",instructions:null,source:a?.source||"startup",model_provider:a?.model||"unknown"};if(await this.ensureSessionStarted(h),!this.isLifecycleCurrent(e))return;if(!this.sessionState){n.warn("[Hooks] Session still not initialized after self-heal, dropping event",{hook_event_name:s});return}}let c=this.sessionState,d=c.sessionId;if(r==="USER_PROMPT"&&o){let h=this.consumeRecentMobilePrompt(d,o);if(h){n.info("[Hooks] Skipping duplicate USER_PROMPT from mobile",{sessionId:d,matchType:h.matchType,originalLength:h.originalLength,echoLength:h.echoLength});return}}if(s==="PreToolUse"){n.debug("[Hooks] PreToolUse observed; AppSync emission suppressed",{toolName:a?.tool_name||"unknown",sessionId:d});return}if(s==="PermissionRequest"){await this.handlePermissionRequestHook(t,c);return}if(s==="PostToolUse"){if(this.toolActivity?.isActive()&&await this.toolActivity.observeCall({callId:a?.tool_use_id??a?.call_id??a?.callId,toolName:a?.tool_name,toolInput:a?.tool_input})!=="closed")return;let h=this.encryptForEmit(o,a,u.EventType.TOOL_USE,d);if(!h)return;let g=h.content,v=h.metadata,m=h.isEncrypted,y=a?.tool_use_id??a?.call_id??a?.callId,S=typeof y=="string"&&y.length>0&&!!this.sessionKey,I=S?this.getToolActivityLegacyRecorder(d):void 0;I&&S&&I.markLegacyInFlight(y);try{let w=await this.appSyncClient.createEvent({sessionId:d,type:u.EventType.TOOL_USE,source:u.EventSource.DESKTOP,content:g,metadata:v,isEncrypted:m,timestamp:(0,u.prepareEventTimestamp)({orderingKey:d})});I&&S&&((0,u.isPersistedEventResult)(w)?await I.finalizeLegacyOwned([y]):I.clearLegacyInFlight(y))}catch(w){throw I&&S&&I.clearLegacyInFlight(y),w}return}if(r==="ASSISTANT_RESPONSE"||r==="USER_PROMPT"){if(r==="ASSISTANT_RESPONSE"){this.sessionWatcher.getBindSource()==="authoritative"&&this.sessionWatcher.getAuthoritativeSessionId()===i?n.debug("[Hooks] Suppressing Stop final \u2014 JSONL watcher authoritatively bound to this session (Bug #2)"):n.warn("[Hooks] Dropping Stop final after authoritative ownership changed",{authoritativeSessionId:this.sessionWatcher.getAuthoritativeSessionId()});return}let h=this.encryptForEmit(o,void 0,u.EventType.USER_PROMPT,d);if(!h)return;await this.appSyncClient.createEvent({sessionId:d,type:u.EventType.USER_PROMPT,source:u.EventSource.DESKTOP,content:h.content,isEncrypted:h.isEncrypted,timestamp:(0,u.prepareEventTimestamp)({orderingKey:d})});return}}mapToolName(t){return{shell_command:"Bash",shell:"Bash",apply_patch:"Edit",create_file:"Write",read_file:"Read"}[t]||t}trackMobilePrompt(t,e){this.mobilePromptDeduper.track(t,e),n.debug("Tracking mobile prompt for USER_PROMPT echo deduplication",{sessionId:t,promptLength:e.trim().length})}forgetMobilePrompt(t,e){this.mobilePromptDeduper.forget(t,e)}consumeRecentMobilePrompt(t,e){return this.mobilePromptDeduper.consumeIfDuplicate(t,e)}setupEventHandlers(){this.sessionWatcher.on("session-started",async t=>{try{if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionState){n.info("[JSONL] Session already active, skipping",{currentSessionId:this.sessionState.sessionId,codexSessionId:t.id}),await this.ensureToolActivityStarted(t.id);return}await this.ensureSessionStarted(t)}catch(e){n.error("[JSONL] session-started handler failed (non-fatal) \u2014 next event retries",{codexSessionId:t?.id,error:String(e)})}}),this.sessionWatcher.on("log-entry",t=>{this.enqueueLogEntry(t)}),this.approvalDetector.on("approval-pending",async t=>{try{await this.handleApprovalPending(t)}catch(e){n.error("approval-pending handler failed (non-fatal)",{error:String(e)})}}),this.tmuxPaneObserver.on("prompt-candidate",async t=>{try{await this.handleTmuxPromptCandidate(t.snapshot)}catch(e){n.error("prompt-candidate handler failed (non-fatal)",{error:String(e)})}}),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 ensureSessionStarted(t,e){if(this.isStopping||(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.isStopping)||this.sessionState)return;process.env[ge]==="1"&&await this.bindRecoveryBootstrapIdentity(t.id);let i=this.sessionBootstrapRetryAt-Date.now();if(i>0){n.warn("Session bootstrap is in retry backoff; hook will be retried later",{codexSessionId:t.id,retryDelayMs:i,failureCount:this.sessionBootstrapFailureCount});return}if(this.sessionStartedInitPromise){try{await this.sessionStartedInitPromise}catch{}return}let s=this.handleSessionStarted(t,e);this.sessionStartedInitPromise=s.catch(()=>{});try{await s}finally{this.sessionStartedInitPromise=null}}async handleSessionStarted(t,e){if(this.isStopping)return;let i=this.lifecycleGeneration;n.info("Handling new Codex session",{codexSessionId:t.id}),this.isInitializingSession=!0,this.bufferedLogEntries=[],this.sessionState&&await this.endActiveSession("new-codex-session-started");let s=process.env.CODEX_WORKING_DIRECTORY||t.cwd||process.cwd(),r=this.getOrCreateBootstrapSessionId(),o=this.appSyncClient.getCurrentUserId(),a={codexSessionId:t.id,cliVersion:t.cli_version,modelProvider:t.model_provider},l={sessionKey:null,sessionIsEncrypted:!0};try{let c={sessionId:r,userId:o,agentType:u.AgentType.CODEX,projectPath:s,metadata:a},d=await this.resumeOrCreateBootstrapSession(c);if(r=d.sessionId,!this.isLifecycleCurrent(i)){this.isInitializingSession=!1,await this.retireCancelledBootstrap(r,"session_started");return}this.sessionKey=d.sessionKey,this.sessionKeyGen=d.sessionKeyGen,this.sessionIsEncrypted=!!d.sessionKey,l={sessionKey:d.sessionKey,sessionIsEncrypted:!!d.sessionKey},await P("daemon_init_step_completed",{step:"session_resume_or_create",path:"session_started"})}catch(c){if(this.isInitializingSession=!1,!this.isLifecycleCurrent(i)){let d=this.authoritativeSessionIdFromError(c)??r;await this.retireCancelledBootstrap(d,"session_started_error");return}throw await P("daemon_init_step_failed",{step:"session_resume_or_create",path:"session_started",error_class:c?.name||"Error",error_message:c?.message||String(c)}),c?.code==="ENCRYPTED_SESSION_NO_KEY"&&(this.sessionIsEncrypted=!0,this.sessionKey=null),this.bindBootstrapIdentityFromError(c),this.recordSessionBootstrapFailure(c,"session_started"),n.error("Failed to create/resume session:",c),c}try{this.sessionState={sessionId:r,userId:o,projectPath:s,cwd:t.cwd,createdAt:new Date,subscriptionActive:!1,metadata:a,encryptionSnapshot:l,codexSessionId:t.id,codexLogFile:this.sessionWatcher.getActiveLogFile()||void 0},this.clearSessionBootstrapFailure(),this.bootstrapSessionId=null,this.recoveryBootstrapOwnerBound=!1,await P("daemon_init_step_completed",{step:"session_state_set",path:"session_started"})}catch(c){await P("daemon_init_step_failed",{step:"session_state_set",path:"session_started",error_class:c?.name||"Error",error_message:c?.message||String(c)}),n.error("Failed to set session state:",c)}await this.ensureToolActivityStarted(t.id);try{this.subscribeToMobileEvents(r)?await P("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"session_started"}):await P("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(c){await P("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:c?.name||"Error",error_message:c?.message||String(c)}),n.error("Failed to subscribe to mobile events:",c)}if(e)try{await e()}catch(c){n.error("E1: pre-heartbeat re-raise hook failed (non-fatal)",{sessionId:r,error:c instanceof Error?c.message:String(c)})}try{await this.drainRetirementOrphans(r)}catch(c){n.error("E1: retirement-orphan drain failed (non-fatal)",{sessionId:r,error:c instanceof Error?c.message:String(c)})}try{await this.appSyncClient.startHeartbeat(r)?await P("daemon_init_step_completed",{step:"heartbeat_start",path:"session_started"}):(await P("daemon_init_step_failed",{step:"heartbeat_start",path:"session_started",error_class:"InitialHeartbeatNotPersisted",error_message:"Backend did not confirm the initial heartbeat mutation"}),n.error("Initial session heartbeat was not persisted",{sessionId:r}))}catch(c){await P("daemon_init_step_failed",{step:"heartbeat_start",path:"session_started",error_class:c?.name||"Error",error_message:c?.message||String(c)}),n.error("Failed to start heartbeat:",c)}try{await this.subscribeToOnApplyUserDecision(r)}catch(c){n.error("Failed to subscribe to onApplyUserDecision (non-fatal)",{error:c})}this.startMobileEndWatcher(r);try{await this.flushBufferedLogEntries(),await P("daemon_init_step_completed",{step:"flush_buffered_entries",path:"session_started"})}catch(c){await P("daemon_init_step_failed",{step:"flush_buffered_entries",path:"session_started",error_class:c?.name||"Error",error_message:c?.message||String(c)}),n.error("Failed to flush buffered log entries:",c),this.bufferedLogEntries=[]}await this.startTmuxObserverWithBeacon("session_started"),this.isInitializingSession=!1}getOrCreateBootstrapSessionId(){return this.bootstrapSessionId||(this.bootstrapSessionId=U.mintBackendSessionId()),this.bootstrapSessionId}async bindRecoveryBootstrapIdentity(t){if(!(process.env[ge]!=="1"||this.bootstrapSessionId||this.sessionState||!t))try{let e=await this.buildToolActivityIntegration().recordedBackendSessionId(t);if(!e){n.warn("Recovery daemon found no durable backend owner; a new session will be created",{rolloutId:t});return}if(!/^codex-[A-Za-z0-9_-]{1,180}$/.test(e)){n.warn("Recovery daemon ignored invalid durable backend owner",{rolloutId:t});return}this.bootstrapSessionId=e,this.recoveryBootstrapOwnerBound=!0,n.info("Recovery daemon reclaiming existing backend session",{rolloutId:t,sessionId:e})}catch(e){n.warn("Recovery daemon could not read the durable rollout owner; a new session will be created",{rolloutId:t,error:e instanceof Error?e.message:String(e)})}}isSessionIdReservedRejection(t){return(t instanceof Error?t.message:String(t)).includes("SESSION_ID_RESERVED")}async resumeOrCreateBootstrapSession(t){try{return await this.resumeBackendSession(t,this.appSyncClient,n)}catch(e){if(!this.recoveryBootstrapOwnerBound||!this.isSessionIdReservedRejection(e))throw e;return n.warn("Recovery discarded a permanently reserved pending create; retrying the durable rollout owner",{sessionId:t.sessionId}),this.resumeBackendSession(t,this.appSyncClient,n)}}startTmuxLifecycleMonitor(){if(this.tmuxLifecycleTimer)return;let t=process.env[$];t&&(this.tmuxLifecycleTimer=setInterval(()=>{this.checkTmuxLifecycle(t)},Wt),this.tmuxLifecycleTimer.unref?.(),this.checkTmuxLifecycle(t))}async tmuxSessionExists(t){try{return await zt("tmux",["has-session","-t",t]),!0}catch{return!1}}async checkTmuxLifecycle(t){if(!(this.isStopping||this.tmuxLifecycleCheckInFlight)){this.tmuxLifecycleCheckInFlight=!0;try{if(await this.tmuxSessionExists(t)){this.tmuxLifecycleObservedAlive=!0;return}if(!this.tmuxLifecycleObservedAlive||this.isStopping)return;this.stopTmuxLifecycleMonitor(),n.info("Native Codex tmux session ended; stopping companion daemon",{tmuxSession:t}),this.stop().then(()=>process.exit(0),e=>{n.error("Failed to stop companion daemon after native session end",{error:e instanceof Error?e.message:String(e)}),process.exit(1)})}finally{this.tmuxLifecycleCheckInFlight=!1}}}stopTmuxLifecycleMonitor(){this.tmuxLifecycleTimer&&(clearInterval(this.tmuxLifecycleTimer),this.tmuxLifecycleTimer=null)}isLifecycleCurrent(t){return!this.isStopping&&this.lifecycleGeneration===t}authoritativeSessionIdFromError(t){let e=t?.authoritativeSessionId;return typeof e=="string"&&e.length>0?e:null}async retireCancelledBootstrap(t,e){this.appSyncClient.stopHeartbeat(t),this.appSyncClient.cleanupSubscription(t);try{await this.appSyncClient.updateSession({sessionId:t,status:u.SessionStatus.INACTIVE}),n.info("Cancelled bootstrap row marked INACTIVE",{sessionId:t,path:e})}catch(i){n.warn("Cancelled bootstrap row could not be marked INACTIVE",{sessionId:t,path:e,error:i instanceof Error?i.message:String(i)})}}bindBootstrapIdentityFromError(t){let e=t?.authoritativeSessionId;typeof e!="string"||e.length===0||(this.bootstrapSessionId=e,n.info("Retained authoritative backend identity from failed bootstrap",{sessionId:e}))}recoverRetiredBackendSession(t){if(this.retiredSessionRecoveryPromise)return this.retiredSessionRecoveryPromise;if(this.isStopping)return Promise.resolve();let e=(async()=>{if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionStartedInitPromise&&await this.sessionStartedInitPromise,this.isStopping)return;let i=this.sessionState;if(!i||i.sessionId!==t)return;let s={id:i.codexSessionId||t,timestamp:new Date().toISOString(),cwd:i.cwd||i.projectPath,originator:"codevibe-retired-session-recovery",cli_version:String(i.metadata?.cliVersion??"unknown"),instructions:null,source:"codevibe",model_provider:String(i.metadata?.modelProvider??"unknown")};n.warn("Backend retired live Codex session; creating replacement row",{sessionId:t,codexSessionId:s.id}),this.parkRetirementOrphans(t),await this.endActiveSession("backend-generation-retired"),this.bootstrapSessionId=null,this.clearSessionBootstrapFailure(),await this.ensureSessionStarted(s)})();return this.retiredSessionRecoveryPromise=e.finally(()=>{this.retiredSessionRecoveryPromise=null}),this.retiredSessionRecoveryPromise}recordSessionBootstrapFailure(t,e){this.sessionBootstrapFailureCount+=1;let i=t instanceof Error?t.message:String(t),r=i.includes("SESSION_LIMIT_EXCEEDED")?6e4:Math.min(5e3*2**(this.sessionBootstrapFailureCount-1),6e4);this.sessionBootstrapRetryAt=Date.now()+r,n.warn("Session bootstrap retry scheduled",{path:e,requestedSessionId:this.bootstrapSessionId,failureCount:this.sessionBootstrapFailureCount,delayMs:r,error:i})}clearSessionBootstrapFailure(){this.sessionBootstrapFailureCount=0,this.sessionBootstrapRetryAt=0}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});let e=Promise.resolve();for(let i of t)e=this.enqueueLogEntry(i);await e.catch(()=>{})}enqueueLogEntry(t){let e=this.logEntryChain.then(()=>this.handleLogEntry(t));return this.logEntryChain=e.catch(i=>{n.error("[JSONL] log entry handler failed",{type:t.type,err:String(i)})}),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}let e=this.sessionState,i=e.sessionId,{sessionKey:s,sessionIsEncrypted:r}=e.encryptionSnapshot;if(t.type==="response_item"&&t.payload){let m=t.payload.type;if(m==="function_call"||m==="custom_tool_call")this.approvalDetector.onToolCallStart(t.payload.call_id,t.payload.name,t.payload.arguments||t.payload.input||"");else if(m==="function_call_output"||m==="custom_tool_call_output"){let y=this.approvalDetector.getPendingCalls().find(I=>I.callId===t.payload.call_id),S=y?this.buildApprovalDedupeKey(this.buildApprovalPromptContextFromPendingCall(y)):void 0;if(this.approvalDetector.onToolCallComplete(t.payload.call_id),await this.clearResolvedInteractivePrompt(t.payload.call_id,S),!this.isExpectedSessionStateCurrent(e))return}}let o=ke(t,i);if(!o)return;o.timestamp=(0,u.prepareEventTimestamp)({orderingKey:i,agentClock:t.timestamp});let a=t.payload?.type,l=!1;if(this.toolActivity?.isActive()&&o.type===u.EventType.TOOL_USE){let m=a==="function_call"||a==="custom_tool_call",y=a==="function_call_output"||a==="custom_tool_call_output";if(m&&typeof t.payload?.call_id=="string"){let S=this.sessionWatcher.getActiveLogFile();S&&this.toolActivity.bindTranscript(S);let I=await this.toolActivity.observeCall({callId:t.payload.call_id,toolName:o.metadata?.toolName??o.metadata?.tool_name,toolInput:o.metadata?.toolInput??o.metadata?.tool_input,ts:t.timestamp});if(!this.isExpectedSessionStateCurrent(e)||I!=="closed")return;l=!0}if(y)return}if(this.toolActivity?.isActive()&&(a==="user_message"||a==="agent_message")&&(await this.toolActivity.flush().catch(m=>n.warn("[tool-activity] codex boundary flush failed",{sessionId:i,err:String(m)})),!this.isExpectedSessionStateCurrent(e)))return;let c=a==="function_call"||a==="function_call_output",d=o.type===u.EventType.USER_PROMPT||o.type===u.EventType.ASSISTANT_RESPONSE||c&&(o.type===u.EventType.TOOL_USE||o.type===u.EventType.INTERACTIVE_PROMPT);if(!this.hooksActive&&d&&(await this.emitHooksCompatibilityModeNotice(e),!this.isExpectedSessionStateCurrent(e)))return;if(this.hooksActive){if(o.type===u.EventType.USER_PROMPT){n.debug("[JSONL] Skipping USER_PROMPT \u2014 hooks deliver it",{type:o.type});return}if(c&&(o.type===u.EventType.TOOL_USE||o.type===u.EventType.INTERACTIVE_PROMPT)&&!l){n.debug("[JSONL] Skipping function_call \u2014 hooks deliver this",{type:o.type,tool:t.payload?.name});return}}if(o.type===u.EventType.USER_PROMPT&&o.source===u.EventSource.DESKTOP){let m=this.consumeRecentMobilePrompt(i,o.content);if(m){n.info("[JSONL] Skipping duplicate USER_PROMPT from mobile",{sessionId:i,matchType:m.matchType,originalLength:m.originalLength,echoLength:m.echoLength});return}}if(this.sessionState!==e){n.warn("[JSONL] Dropping event from stale session generation (#638)",{sessionId:i,currentSessionId:this.sessionState?.sessionId});return}let h=t.payload?.call_id,g=o.type===u.EventType.TOOL_USE&&typeof h=="string"&&h.length>0&&!!s,v=g?this.getToolActivityLegacyRecorder(i):void 0;v&&g&&v.markLegacyInFlight(h);try{let m=(0,u.encryptForEmit)(s,r,o.content,o.metadata);if(!m){n.error("No session key for ENCRYPTED session \u2014 dropping JSONL event (fail-closed, #638)",{type:o.type,sessionId:i});return}o.content=m.content,o.metadata=m.metadata,m.isEncrypted&&(o.isEncrypted=!0,n.debug("Event encrypted",{type:o.type}));let y=await this.appSyncClient.createEvent(o);n.debug("Event synced to backend",{type:o.type,encrypted:m.isEncrypted}),v&&g&&((0,u.isPersistedEventResult)(y)?await v.finalizeLegacyOwned([h]):v.clearLegacyInFlight(h))}catch(m){v&&g&&v.clearLegacyInFlight(h),n.error("Failed to sync event:",m)}}async handlePermissionRequestHook(t,e){if(!this.isExpectedSessionStateCurrent(e))return;let i=t.metadata||{},s=typeof i.tool_name=="string"?i.tool_name:"Tool",r=i.tool_input,o=this.stringifyToolInput(r),a={toolName:s,toolInput:r,rawInput:o,filePath:this.extractFilePathFromToolInput(s,r,o),diff:s==="apply_patch"?o:void 0,hint:this.buildPermissionRequestHint(s,r,o)},l=this.buildToolDetailsForInteractivePrompt(a),c=l.tool_name||this.mapToolNameForApproval(s),d=l.tool_input||this.buildFallbackToolInput(a),h=!!(c&&d),g=await this.tryParsePermissionRequestPromptFromTmux(H=>this.parsedPromptMatchesApprovalContext(H,a));if(!this.isExpectedSessionStateCurrent(e)){n.warn("[Hooks] Dropping stale PermissionRequest after session generation changed",{sessionId:e.sessionId,currentSessionId:this.sessionState?.sessionId});return}let v=g?.parsedPrompt??null;if(!v){n.warn("[Hooks] Suppressing PermissionRequest mobile prompt because exact Codex options are unavailable",{sessionId:e.sessionId,toolName:s,hint:a.hint}),this.raiseSuppressedBadge(e.sessionId,this.buildApprovalDedupeKey({toolName:s,toolInput:r,filePath:a.filePath,rawInput:o,hint:a.hint}));return}let m=this.buildApprovalDedupeKey({toolName:s,toolInput:r,filePath:a.filePath,rawInput:o,hint:a.hint});if(m&&this.hasRecentlyResolvedApprovalDedupeKey(e.sessionId,m)){n.info("[Hooks] Skipping PermissionRequest prompt; same approval was already answered recently",{sessionId:e.sessionId,toolName:s,dedupeKey:m});return}let y=this.buildCodexPromptPresentation(v);if(!y){n.warn("[Hooks] Suppressing PermissionRequest mobile prompt because Codex option hotkeys are unavailable",{sessionId:e.sessionId,toolName:s,hint:a.hint}),this.raiseSuppressedBadge(e.sessionId,m);return}let S=this.buildPermissionPromptId(i,s,r,o),I=this.buildApprovalPromptContent(y.content,{toolName:c,toolInput:d,hint:a.hint,filePath:a.filePath}),w={promptId:S,kind:y.kind,options:y.options,submitMap:y.submitMap,promptText:I,createdAt:Date.now(),source:"permission_hook",dedupeKey:m,requiresFollowUpText:y.requiresFollowUpText},T={isApprovalHint:!0,toolName:s,toolInput:r,hint:a.hint,filePath:a.filePath,diff:a.diff,rawInput:o,tool_name:c,tool_input:d,has_details:h,options:y.options,instructions:y.instructions,prompt_source:v?"permission_hook_tmux":"permission_hook",permission_mode:i.permission_mode,turn_id:i.turn_id,dedupe_key:m};n.info("[Hooks] Sending PermissionRequest interactive prompt",{sessionId:e.sessionId,toolName:s,promptId:S,promptSource:T.prompt_source,dedupeKey:m}),await this.enqueueOrEmitInteractivePrompt({prompt:w,content:I,metadata:T,ownerState:e})}async emitHooksCompatibilityModeNotice(t){if(this.hooksCompatibilityNoticeSent||!this.isExpectedSessionStateCurrent(t))return;this.hooksCompatibilityNoticeSent=!0;let e="Codex hooks are not active. CodeVibe is using compatibility mode: mobile approvals still mirror the desktop prompt, but timeline events may be delayed or incomplete. Open Codex /hooks and trust/enable CodeVibe hooks for full fidelity.",i={compatibility_mode:!0,reason:"codex_hooks_inactive",action:"trust_enable_codevibe_hooks"};n.warn("Codex hooks inactive; running in compatibility mode",{sessionId:t.sessionId});let s=this.encryptForEmit(e,i,u.EventType.NOTIFICATION,t.sessionId);if(s)try{await this.appSyncClient.createEvent({sessionId:t.sessionId,type:u.EventType.NOTIFICATION,source:u.EventSource.DESKTOP,content:s.content,metadata:s.metadata,timestamp:(0,u.prepareEventTimestamp)({orderingKey:t.sessionId}),...s.isEncrypted?{isEncrypted:!0}:{}})}catch(r){n.warn("Failed to emit hooks compatibility mode notification",{error:r})}}async handleApprovalPending(t){let e=this.sessionState;if(!e)return;let i=this.buildApprovalDedupeKey(t);if(i&&this.hasRecentlyResolvedApprovalDedupeKey(e.sessionId,i)){n.info("Skipping heuristic approval prompt; same approval was already answered recently",{callId:t.callId,toolName:t.toolName,dedupeKey:i});return}if(i&&this.hasActiveOrQueuedPermissionHookPrompt(i)){this.mergeCallIdIntoPromptByDedupeKey(i,t.callId),n.info("Skipping heuristic approval prompt; PermissionRequest hook already emitted it",{callId:t.callId,toolName:t.toolName,dedupeKey:i});return}n.info("Sending approval pending interactive prompt",t);try{let s=await this.tryParseInteractivePromptFromTmux(),r=s?.parsedPrompt??null,o=this.buildToolDetailsForInteractivePrompt(t,s?.snapshot),a=o.tool_name||this.mapToolNameForApproval(t.toolName),l=o.tool_input||this.buildFallbackToolInput(t),c=!!(a&&l);if(!r){n.warn("Suppressing heuristic approval prompt because exact Codex options are unavailable",{callId:t.callId,toolName:t.toolName,hint:t.hint}),this.raiseSuppressedBadge(e.sessionId,i);return}if(!this.parsedPromptMatchesApprovalContext(r,t)){n.warn("Suppressing heuristic approval prompt because parsed tmux prompt does not match the active tool",{callId:t.callId,toolName:t.toolName,hint:t.hint,parsedPromptText:r.promptText}),this.raiseSuppressedBadge(e.sessionId,i);return}let d=this.buildCodexPromptPresentation(r);if(!d){n.warn("Suppressing heuristic approval prompt because Codex option hotkeys are unavailable",{callId:t.callId,toolName:t.toolName,hint:t.hint}),this.raiseSuppressedBadge(e.sessionId,i);return}let h=d.options,g=this.buildApprovalPromptContent(d.content,{toolName:a,toolInput:l,hint:t.hint,filePath:t.filePath}),v={promptId:t.callId,callId:t.callId,kind:d.kind,options:h,submitMap:d.submitMap,promptText:d.promptText,createdAt:Date.now(),source:r?"tmux":"heuristic",dedupeKey:i,requiresFollowUpText:d.requiresFollowUpText},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:a,tool_input:l,has_details:c,options:h,instructions:d.instructions,prompt_source:r?"tmux":"heuristic",dedupe_key:i};n.debug("Interactive prompt (pre-encryption)",{sessionId:e.sessionId,callId:t.callId,contentPreview:g.substring(0,200),toolDetails:o,metadata:m}),await this.enqueueOrEmitInteractivePrompt({prompt:v,content:g,metadata:m,ownerState:e})}catch(s){n.error("Failed to send approval interactive prompt:",s)}}async handleTmuxPromptCandidate(t){let e=this.sessionState;if(!e){this.tmuxPaneObserver.resetLastPromptHash();return}let i=(0,M.parseInteractivePrompt)(t);if(!i){this.raiseSuppressedBadge(e.sessionId,null);return}let s=this.buildCodexPromptPresentation(i);if(!s){n.warn("Skipping tmux-detected prompt because Codex option hotkeys are unavailable",{parsedPromptText:i.promptText}),this.raiseSuppressedBadge(e.sessionId,null);return}let r=this.getMostRecentPendingToolCall();if(!r){if(await new Promise(w=>setTimeout(w,500)),!this.isExpectedSessionStateCurrent(e)){n.warn("Dropping tmux prompt candidate after session generation changed",{sessionId:e.sessionId,currentSessionId:this.sessionState?.sessionId});return}r=this.getMostRecentPendingToolCall()}let o=r?this.buildApprovalPromptContextFromPendingCall(r):null;if(o&&!this.parsedPromptMatchesApprovalContext(i,o)){n.warn("Skipping tmux-detected prompt because parsed prompt does not match pending tool call",{callId:r?.callId,toolName:r?.name,parsedPromptText:i.promptText}),this.raiseSuppressedBadge(e.sessionId,null);return}let a=o?null:this.buildApprovalPromptContextFromParsedPrompt(i),l=o||a;if(!l){n.warn("Skipping tmux-detected prompt because no tool context could be derived from the parsed prompt",{parsedPromptText:i.promptText}),this.raiseSuppressedBadge(e.sessionId,null);return}let c=l?this.buildApprovalDedupeKey(l):void 0;if(c&&this.hasRecentlyResolvedApprovalDedupeKey(e.sessionId,c)){n.info("Skipping tmux-detected prompt; same approval was already answered recently",{promptText:i.promptText,dedupeKey:c});return}if(c&&this.hasActiveOrQueuedPermissionHookPrompt(c)){r?.callId&&this.mergeCallIdIntoPromptByDedupeKey(c,r.callId),n.info("Skipping tmux-detected prompt; PermissionRequest hook already emitted it",{promptText:i.promptText,dedupeKey:c});return}let d=l?this.buildToolDetailsForInteractivePrompt(l,t):{},h=d.tool_name||this.mapToolNameForApproval(r?.name),g=d.tool_input||(l?this.buildFallbackToolInput(l):void 0),v=!!(h&&g),y={promptId:r?.callId||(0,Je.v4)(),callId:r?.callId,kind:s.kind,options:s.options,submitMap:s.submitMap,promptText:s.promptText,createdAt:Date.now(),source:"tmux",dedupeKey:c,requiresFollowUpText:s.requiresFollowUpText},S={options:s.options,instructions:s.instructions,prompt_source:"tmux_live",tool_name:h,tool_input:g,has_details:v,dedupe_key:c},I=this.buildApprovalPromptContent(s.content,{toolName:h,toolInput:g,hint:l?.hint,filePath:l?.filePath});try{await this.enqueueOrEmitInteractivePrompt({prompt:y,content:I,metadata:S,ownerState:e})&&n.info("Sent tmux-detected interactive prompt",{sessionId:e.sessionId,promptText:i.promptText,kind:i.kind})}catch(w){n.error("Failed to send tmux-detected interactive prompt",{error:w})}}async enqueueOrEmitInteractivePrompt(t){if(!this.isExpectedSessionStateCurrent(t.ownerState))return n.warn("Dropping interactive prompt from stale session generation",{sessionId:t.ownerState.sessionId,currentSessionId:this.sessionState?.sessionId,source:t.prompt.source}),!1;if(t.prompt.dedupeKey&&this.hasRecentlyResolvedApprovalDedupeKey(t.ownerState.sessionId,t.prompt.dedupeKey))return n.debug("Skipping interactive prompt emission; same approval was already answered recently",{source:t.prompt.source,callId:t.prompt.callId,dedupeKey:t.prompt.dedupeKey}),!1;let e=this.pendingInteractivePrompt;if(!e){this.pendingInteractivePrompt=t.prompt;try{return await this.emitInteractivePromptEvent(t),!0}catch(i){throw this.pendingInteractivePrompt?.promptId===t.prompt.promptId&&(this.pendingInteractivePrompt=null),i}}return this.isSameInteractivePrompt(e,t.prompt)?(!e.callId&&t.prompt.callId&&(e.callId=t.prompt.callId,n.debug("Merged callId into existing interactive prompt",{source:e.source,callId:t.prompt.callId,promptText:e.promptText})),n.debug("Skipping duplicate interactive prompt emission",{existingSource:e.source,candidateSource:t.prompt.source,existingCallId:e.callId,candidateCallId:t.prompt.callId,promptText:t.prompt.promptText}),!1):this.queuedInteractivePrompts.some(i=>this.isSameInteractivePrompt(i.prompt,t.prompt))?(n.debug("Skipping duplicate queued interactive prompt",{candidateSource:t.prompt.source,candidateCallId:t.prompt.callId,promptText:t.prompt.promptText}),!1):(this.queuedInteractivePrompts.push(t),n.info("Queued interactive prompt behind active prompt",{activeCallId:e.callId,queuedCallId:t.prompt.callId,queueLength:this.queuedInteractivePrompts.length}),!1)}async emitInteractivePromptEvent(t){if(!this.isExpectedSessionStateCurrent(t.ownerState))return;let e=t.ownerState.sessionId,i=this.e1PromptRaises.get(t.prompt.promptId),s=i?i.record:this.newE1Raise(e,!0);t.prompt.promptId=s.promptId,t.prompt.dedupeKey&&this.e1ContentKeyIndex.set(`${e}::${t.prompt.dedupeKey}`,s.promptId),this.stashE1RaiseContent(s.promptId,t.content,t.metadata??{});let r=this.encryptForEmit(t.content,t.metadata,u.EventType.INTERACTIVE_PROMPT,e);r&&await this.appSyncClient.createEvent({sessionId:e,type:u.EventType.INTERACTIVE_PROMPT,source:u.EventSource.DESKTOP,content:r.content,metadata:r.metadata,...(0,u.raiseFieldsFromRecord)(s),timestamp:(0,u.prepareEventTimestamp)({orderingKey:e}),...r.isEncrypted?{isEncrypted:!0}:{}})}async emitNextQueuedInteractivePrompt(){if(this.pendingInteractivePrompt||this.queuedInteractivePrompts.length===0)return;let t=this.queuedInteractivePrompts.shift();if(t){if(!this.isExpectedSessionStateCurrent(t.ownerState)){n.warn("Discarding queued prompt from stale session generation",{sessionId:t.ownerState.sessionId,currentSessionId:this.sessionState?.sessionId}),await this.emitNextQueuedInteractivePrompt();return}this.pendingInteractivePrompt=t.prompt;try{await this.emitInteractivePromptEvent(t),n.info("Emitted next queued interactive prompt",{callId:t.prompt.callId,queueLength:this.queuedInteractivePrompts.length})}catch(e){this.pendingInteractivePrompt=null,n.error("Failed to emit queued interactive prompt",{error:e}),await this.emitNextQueuedInteractivePrompt()}}}removeQueuedInteractivePromptByCallId(t){let e=this.queuedInteractivePrompts.length,i=this.queuedInteractivePrompts.filter(s=>s.prompt.callId===t);for(let s of i)this.rememberResolvedApprovalDedupeKey(s.ownerState.sessionId,s.prompt.dedupeKey);this.queuedInteractivePrompts=this.queuedInteractivePrompts.filter(s=>s.prompt.callId!==t),this.queuedInteractivePrompts.length!==e&&n.debug("Removed resolved tool call from interactive prompt queue",{callId:t,removed:e-this.queuedInteractivePrompts.length})}async clearResolvedInteractivePrompt(t,e){let i=this.pendingInteractivePrompt;if(i&&(i.callId===t||e!==void 0&&i.dedupeKey===e)){this.rememberResolvedApprovalDedupeKey(this.sessionState?.sessionId,i.dedupeKey),this.pendingInteractivePrompt=null,await this.emitNextQueuedInteractivePrompt();return}this.removeQueuedInteractivePromptByCallId(t),e!==void 0&&this.removeQueuedInteractivePromptByDedupeKey(e)}removeQueuedInteractivePromptByDedupeKey(t){let e=this.queuedInteractivePrompts.length,i=this.queuedInteractivePrompts.filter(s=>s.prompt.dedupeKey===t);for(let s of i)this.rememberResolvedApprovalDedupeKey(s.ownerState.sessionId,s.prompt.dedupeKey);this.queuedInteractivePrompts=this.queuedInteractivePrompts.filter(s=>s.prompt.dedupeKey!==t),this.queuedInteractivePrompts.length!==e&&n.debug("Removed resolved deduped tool call from interactive prompt queue",{dedupeKey:t,removed:e-this.queuedInteractivePrompts.length})}mergeCallIdIntoPromptByDedupeKey(t,e){let i=this.pendingInteractivePrompt;if(i?.dedupeKey===t&&!i.callId){i.callId=e,n.debug("Merged callId into active deduped interactive prompt",{source:i.source,callId:e,dedupeKey:t});return}let s=this.queuedInteractivePrompts.find(r=>r.prompt.dedupeKey===t&&!r.prompt.callId);s&&(s.prompt.callId=e,n.debug("Merged callId into queued deduped interactive prompt",{source:s.prompt.source,callId:e,dedupeKey:t}))}isSameInteractivePrompt(t,e){return Date.now()-t.createdAt>jt?!1:t.callId&&e.callId?t.callId===e.callId:t.dedupeKey&&e.dedupeKey?t.dedupeKey===e.dedupeKey:t.kind===e.kind&&this.normalizePromptDedupeText(t.promptText)===this.normalizePromptDedupeText(e.promptText)}normalizePromptDedupeText(t){return t.replace(/\s+/g," ").trim().toLowerCase()}async startTmuxObserver(){let t=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!t)return n.debug("Skipping tmux pane observer start - no tmux session in environment"),!0;try{return await this.tmuxPaneObserver.start(t),!0}catch(e){return n.warn("Failed to start tmux pane observer",{tmuxSession:t,error:e}),!1}}async startTmuxObserverWithBeacon(t){try{await this.startTmuxObserver()?await P("daemon_init_step_completed",{step:"tmux_observer_start",path:t}):await P("daemon_init_step_failed",{step:"tmux_observer_start",path:t,error_class:"TmuxObserverStartFailed",error_message:"tmuxPaneObserver.start threw (see plugin log)"})}catch(e){await P("daemon_init_step_failed",{step:"tmux_observer_start",path:t,error_class:e?.name||"Error",error_message:e?.message||String(e)}),n.error("Failed to start tmux observer:",e)}}async tryParseInteractivePromptFromTmux(){try{let t=await this.tmuxPaneObserver.captureSnapshot(),e=this.tmuxPaneObserver.extractActiveApprovalBlock(t),i=e?(0,M.parseInteractivePrompt)(e):null;return n.debug("tmux prompt parse result",{parsed:!!i,kind:i?.kind,promptText:i?.promptText,isolated:!!e,snapshotPreview:this.summarizePromptSnapshot(e??t)}),{parsedPrompt:i,snapshot:e??t}}catch(t){return n.debug("tmux prompt parsing unavailable",{error:t}),null}}async tryParsePermissionRequestPromptFromTmux(t){let e=await this.tryParseInteractivePromptFromTmux();if(e?.parsedPrompt&&(!t||t(e.parsedPrompt,e.snapshot)))return e;e?.parsedPrompt&&n.warn("Ignoring parsed PermissionRequest prompt because it does not match the active tool",{promptText:e.parsedPrompt.promptText}),await new Promise(s=>setTimeout(s,250));let i=await this.tryParseInteractivePromptFromTmux();return i?.parsedPrompt&&(!t||t(i.parsedPrompt,i.snapshot))?i:(i?.parsedPrompt&&n.warn("Ignoring retried PermissionRequest prompt because it does not match the active tool",{promptText:i.parsedPrompt.promptText}),i?.snapshot||e?.snapshot?{parsedPrompt:null,snapshot:i?.snapshot||e?.snapshot||""}: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}}buildCodexPromptPresentation(t){let e=this.buildPromptPresentation(t),i=this.buildSubmitMapFromCodexOptionHotkeys(e.options);return i?{...e,submitMap:i,instructions:this.buildCodexPermissionInstructions(e.options),requiresFollowUpText:this.optionsRequireFollowUpText(e.options)}:null}buildSubmitMapFromCodexOptionHotkeys(t){let e={};for(let i of t){let s=i.text.match(/\(([^)]+)\)\s*$/)?.[1]?.trim().toLowerCase();if(!s||!Vt.test(s))return null;s==="esc"||s==="escape"?e[i.number]=K:e[i.number]=s}return e}buildCodexPermissionInstructions(t){let e=t.find(o=>/\((?:y|yes)\)\s*$/i.test(o.text)),i=t.find(o=>/\(p\)\s*$/i.test(o.text)),s=t.find(o=>/\((?:esc|escape)\)\s*$/i.test(o.text)),r=[];return e&&r.push(`${e.number} to approve`),i&&r.push(`${i.number} to persist the desktop allow rule`),s&&r.push(`${s.number} followed by what to change`),r.length>0?`Reply with ${r.join(", ")}`:"Reply with the number of the option you want"}optionsRequireFollowUpText(t){return t.some(e=>/what to (?:do differently|change)|instructions/i.test(e.text))}getMostRecentPendingToolCall(){let t=this.approvalDetector.getPendingCalls();return t.length===0?null:t.reduce((e,i)=>i.timestamp>e.timestamp?i:e)}hasActiveOrQueuedPermissionHookPrompt(t){let e=this.pendingInteractivePrompt;return e?.source==="permission_hook"&&e.dedupeKey===t?!0:this.queuedInteractivePrompts.some(i=>i.prompt.source==="permission_hook"&&i.prompt.dedupeKey===t)}hasRecentlyResolvedApprovalDedupeKey(t,e){return t?(this.pruneResolvedApprovalDedupeKeys(),this.resolvedApprovalDedupeKeys.has(`${t}::${e}`)):!1}rememberResolvedApprovalDedupeKey(t,e){!t||!e||(this.pruneResolvedApprovalDedupeKeys(),this.resolvedApprovalDedupeKeys.set(`${t}::${e}`,Date.now()))}pruneResolvedApprovalDedupeKeys(){let t=Date.now()-Gt;for(let[e,i]of this.resolvedApprovalDedupeKeys.entries())i<t&&this.resolvedApprovalDedupeKeys.delete(e)}buildApprovalDedupeKey(t){let e=t.toolName||"Tool",i=this.firstString(t.toolInput?.command,t.toolInput?.cmd,t.rawInput);if(i)return`command:${this.hashDedupeValue(`${this.mapToolNameForApproval(e)||e}:${i.trim()}`)}`;let s=this.firstString(t.filePath,t.toolInput?.file_path,t.toolInput?.path,t.toolInput?.filePath);if(s)return`file:${this.hashDedupeValue(`${e}:${s}`)}`;let r=this.firstString(t.hint);if(r)return`hint:${this.hashDedupeValue(`${e}:${r}`)}`}hashDedupeValue(t){return ye.createHash("sha256").update(t.replace(/\s+/g," ").trim().toLowerCase()).digest("hex").slice(0,16)}buildPermissionPromptId(t,e,i,s){let r=typeof t.turn_id=="string"&&t.turn_id.trim().length>0?t.turn_id.trim():void 0,o=ye.createHash("sha256").update(`${e}:${s||this.stringifyToolInput(i)}`).digest("hex").slice(0,12);return`permission-${r||"turn"}-${o}`}buildPermissionRequestHint(t,e,i){let s=this.firstString(e?.command,e?.cmd);if(s)return`Command: ${this.truncateApprovalDetail(s,80)}`;let r=this.extractFilePathFromToolInput(t,e,i);return r?`File: ${r}`:`Tool: ${this.mapToolNameForApproval(t)||t}`}extractFilePathFromToolInput(t,e,i){let s=this.firstString(e?.file_path,e?.path,e?.filePath);if(s)return s;if(t==="apply_patch"&&i){let r=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(r)return r[1].trim()}}stringifyToolInput(t){if(t!=null){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}}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}`}}buildApprovalPromptContextFromParsedPrompt(t){let e=this.extractShellCommandFromPromptText(t.promptText);return e?{toolName:"Bash",toolInput:{command:e},rawInput:e,hint:`Command: ${this.truncateApprovalDetail(e,80)}`}:null}parsedPromptMatchesApprovalContext(t,e){let i=this.firstString(e.toolInput?.command,e.toolInput?.cmd);if(i){let r=Se(t.promptText);if(!r||r.length===0)return!1;let o=this.normalizeApprovalCommand(i);return this.normalizeApprovalCommand(r.join(" "))===o||r.length>1&&this.normalizeApprovalCommand(r.join(""))===o}let s=this.firstString(e.filePath,e.toolInput?.file_path,e.toolInput?.path,e.toolInput?.filePath);return s?t.promptText.includes(s):!1}normalizeApprovalCommand(t){return t.replace(/\s+/g," ").trim()}extractShellCommandFromPromptText(t){return et(t)}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"}buildApprovalPromptContent(t,e){let i=t.trim(),s=i==="Codex is waiting for approval.",r=/^\$\s+/.test(i),o=e.toolName?`${e.toolName} requires approval.`:"Codex is waiting for approval.",a=[s||r||!i?o:i],l=typeof e.toolInput?.command=="string"?e.toolInput.command.trim():void 0;if(l&&!a.join(`
|
|
21
|
+
`).trim();return(0,W.createHash)("sha256").update(i).digest("hex")}};var k=require("@quantiya/codevibe-core");var ve=T(require("express")),A=T(require("fs")),je=T(require("path")),Ge=T(require("os"));var Bt=1800*1e3,Lt=60*1e3,Kt=1440*60*1e3;var ie=class{constructor(){this.assignedPort=0;this.portRefreshTimer=null;this.app=(0,ve.default)(),this.setupMiddleware(),this.setupRoutes(),this.tmuxSession=process.env.CODEVIBE_CODEX_TMUX_SESSION}getPort(){return this.assignedPort}setupMiddleware(){this.app.use(ve.default.json({limit:"1mb"})),this.app.use((t,e,i)=>{o.debug(`${t.method} ${t.path}`,{body:t.body}),i()})}setupRoutes(){this.app.get("/health",(t,e)=>{e.json({success:!0,service:"codevibe-codex",pid:process.pid,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);if(o.info("Received hook event",{sessionId:i.session_id,hookEvent:i.hook_event_name,type:s.type}),this.eventHandler){let r=this.eventHandler(s);if(i.hook_event_name==="PermissionRequest"){r.catch(n=>{o.error("Error resolving PermissionRequest after acknowledgement:",n)}),e.json({success:!0});return}await r}e.json({success:!0})}catch(i){o.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,transcript_path:t.transcript_path,...t.metadata||{}},i,s;switch(t.hook_event_name){case"SessionStart":i="NOTIFICATION",s="Session started",e.source=t.source,e.model=t.model;break;case"UserPromptSubmit":i="USER_PROMPT",s=t.prompt||"";break;case"PreToolUse":i="NOTIFICATION",s="PreToolUse observed",e.tool_name=t.tool_name,e.tool_input=t.tool_input,e.tool_use_id=t.tool_use_id,e.approval_status="observed_pre_tool",e.requires_user_action=!1;break;case"PermissionRequest":i="NOTIFICATION",s="PermissionRequest observed",e.tool_name=t.tool_name,e.tool_input=t.tool_input,e.permission_mode=t.permission_mode,e.turn_id=t.turn_id,e.requires_user_action=!0;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,e.tool_input=t.tool_input,e.tool_use_id=t.tool_use_id;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,o.info(`HTTP API listening on http://localhost:${this.assignedPort}`),this.writePortFile(this.assignedPort),this.startPortFileKeepalive(),t(this.assignedPort)}),this.server.on("error",i=>{o.error("HTTP server error:",i),e(i)})}catch(i){e(i)}})}portFilePath(){return this.tmuxSession?je.join(Ge.tmpdir(),`codevibe-codex-${this.tmuxSession}.port`):null}writePortFile(t){let e=this.portFilePath();if(!e){o.warn("No CODEVIBE_CODEX_TMUX_SESSION set, skipping port file");return}try{A.writeFileSync(e,t.toString()),o.info(`Port file written: ${e} -> ${t}`)}catch(i){o.error(`Failed to write port file: ${e}`,i)}}removePortFile(){let t=this.portFilePath();if(t)try{A.existsSync(t)&&(A.unlinkSync(t),o.info(`Port file removed: ${t}`))}catch(e){o.warn(`Failed to remove port file: ${t}`,e)}}startPortFileKeepalive(){this.portRefreshTimer&&(clearInterval(this.portRefreshTimer),this.portRefreshTimer=null);let t=Number(process.env.CODEVIBE_PORTFILE_REFRESH_MS),e=Number.isFinite(t)&&t>0?Math.min(Kt,Math.max(Lt,t)):Bt;this.portRefreshTimer=setInterval(()=>this.refreshPortFile(),e)}refreshPortFile(){let t=this.portFilePath();if(t)try{let e=new Date;A.utimesSync(t,e,e)}catch(e){e?.code==="ENOENT"?this.writePortFile(this.assignedPort):o.warn(`Port-file refresh failed: ${t}`,e)}}async stop(){return this.portRefreshTimer&&(clearInterval(this.portRefreshTimer),this.portRefreshTimer=null),this.removePortFile(),new Promise(t=>{this.server?this.server.close(()=>{o.info("HTTP API stopped"),t()}):t()})}};var se=class{constructor(t={}){this.pendingBySession=new Map;this.expiryMs=t.expiryMs??1e4,this.minFuzzyEchoLength=t.minFuzzyEchoLength??16,this.minFuzzyEchoRatio=t.minFuzzyEchoRatio??.35,this.now=t.now??Date.now}track(t,e){let i=this.normalize(e);if(!i)return;let s=this.validEntries(t);s.push({normalized:i,timestamp:this.now()}),this.pendingBySession.set(t,s)}forget(t,e){let i=this.normalize(e);if(!i)return;let s=!1,r=this.validEntries(t).filter(n=>!s&&n.normalized===i?(s=!0,!1):!0);this.replaceEntries(t,r)}consumeIfDuplicate(t,e){let i=this.normalize(e);if(!i)return null;let s=null,r=this.validEntries(t).filter(n=>{if(!s){let a=this.matchType(n.normalized,i);if(a)return s={matchType:a,originalLength:n.normalized.length,echoLength:i.length},!1}return!0});return this.replaceEntries(t,r),s}validEntries(t){let e=this.now()-this.expiryMs;return(this.pendingBySession.get(t)||[]).filter(i=>i.timestamp>=e)}replaceEntries(t,e){e.length>0?this.pendingBySession.set(t,e):this.pendingBySession.delete(t)}matchType(t,e){if(t===e)return"exact";let i=e.length>=this.minFuzzyEchoLength,s=e.length/t.length>=this.minFuzzyEchoRatio;return i&&s&&t.endsWith(e)?"suffix":null}normalize(t){return t.replace(/\s+/g," ").trim()}};var Ye=T(require("crypto")),Xe=T(require("fs")),Je=T(require("https")),re=T(require("os")),Qe=T(require("path")),$t="G-GS74YEQTB8",Ut="lAfOF6OxRzSQ-NsLBRjhAg",qt="www.google-analytics.com",zt=`/mp/collect?measurement_id=${$t}&api_secret=${Ut}`,Ve=800;function Ht(){try{let c=Qe.resolve(__dirname,"..","package.json"),t=Xe.readFileSync(c,"utf-8"),e=JSON.parse(t);if(typeof e.version=="string"&&e.version.length>0&&e.version.length<30)return e.version}catch{}return"unknown"}var Wt=Ht();function jt(){let c=typeof process.getuid=="function"?process.getuid():0;return Ye.createHash("sha256").update(`${re.hostname()}-${c}`).digest("hex").substring(0,36)}function Gt(c){if(!c)return"";let t=re.homedir(),e=c.replace(/[\n\r\t]/g," ");if(t&&t.length>0){let i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");e=e.replace(new RegExp(i,"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 b(c,t){return new Promise(e=>{let i,s=!1,r=()=>{s||(s=!0,clearTimeout(n),e())},n=setTimeout(()=>{try{i?.destroy()}catch{}r()},Ve);typeof n.unref=="function"&&n.unref();try{let a={...t};typeof a.error_message=="string"&&(a.error_message=Gt(a.error_message));let l=JSON.stringify({client_id:jt(),events:[{name:c,params:{agent:"codex",plugin_version:Wt,platform:process.platform,source:process.env.CODEVIBE_TELEMETRY_SOURCE||"production",...a}}]});i=Je.request({hostname:qt,path:zt,method:"POST",headers:{"Content-Type":"application/json"},timeout:Ve},p=>{p.resume(),p.on("end",r),p.on("close",r),p.on("error",r)}),i.on("error",r),i.on("timeout",()=>{try{i?.destroy()}catch{}r()}),i.on("close",r),i.write(l),i.end()}catch{r()}})}var ne=class{constructor(){this.originated=new Set;this.externallyResolved=new Set}markOriginated(t){this.originated.add(t)}clearOriginated(t){this.originated.delete(t)}getOriginated(){return new Set(this.originated)}getExternallyResolved(){return new Set(this.externallyResolved)}isExternallyResolved(t){return this.externallyResolved.has(t)}dispatch(t){let{gateId:e}=t;return this.originated.has(e)?(this.originated.delete(e),this.externallyResolved.add(e),"self_echo"):(this.externallyResolved.add(e),"foreign")}clear(){this.originated.clear(),this.externallyResolved.clear()}};function Ze(c){return`[CodeVibe] Decision recorded on another device: ${c} \u2014 type any number to dismiss the open AskUserQuestion`}var it=(0,Ie.promisify)(le.exec),Vt=(0,Ie.promisify)(le.execFile),Yt="/quit",j="CODEVIBE_CODEX_TMUX_SESSION",Se="CODEVIBE_CODEX_DAEMON_RECOVERY",Xt=1e3,Jt=600*1e3,Qt=30*1e3,Zt=/^(?:[a-z0-9]|esc|escape)$/;async function ei(c,t){let e=async(i,s)=>{try{await it(i)}catch(r){o.warn("tmux send-keys failed during self-terminate",{sessionName:c,label:s,error:String(r)})}};await e(`tmux send-keys -t "${c}" C-c`,"ctrl-c"),await new Promise(i=>setTimeout(i,200)),await e(`tmux send-keys -t "${c}" -l "${t}"`,"quit-text"),await new Promise(i=>setTimeout(i,500)),await e(`tmux send-keys -t "${c}" Enter`,"enter")}function be(c){let t=c.split(`
|
|
22
|
+
`),e=n=>/^[\s>]*\d+\.\s/.test(n),i=-1;for(let n=t.length-1;n>=0;n-=1)if(/^\s*\$\s+/.test(t[n])){i=n;break}if(i===-1)return;let s=t[i].trim().match(/^\$\s+(.+)$/);if(!s?.[1]?.trim())return;let r=[s[1].trim()];for(let n=i+1;n<t.length;n+=1){let a=t[n];if(e(a)||/^\s*$/.test(a)||/^\s*\$\s+/.test(a))break;r.push(a.trim())}return r.length>0?r:void 0}function st(c){let t=be(c);if(!t)return;let e=t.join(" ").trim();return e.length>0?e:void 0}function rt(c,t){if(c.length===0)return!1;let e=t,i=new Set([c[0]]);for(let s of c.slice(1)){let r=s,n=new Set;for(let a of i)for(let l of[""," "]){let p=`${a}${l}${r}`;e.startsWith(p)&&n.add(p)}if(n.size===0)return!1;i=n}return i.has(e)}function nt(c,t,e){if(!c.find(u=>u.number==="2"&&/\(p\)\s*$/i.test(u.text)))return c;let s="Yes, and don't ask again for commands that start with",r="Yes, and don't ask again (p)",n=ti(e,"2");if(!n)return null;let a=ii(n);if(a.has(r))return c.map(u=>u.number==="2"?{...u,text:r}:u);if(!t)return null;let l=new Map;for(let u of a){let f=u.match(/^Yes, and don't ask again for commands that start with `([^`]*)`\s*\(p\)$/);if(!f)continue;let v=si(f[1]);!v||!ni(v,t)||l.set(JSON.stringify(v),v)}if(l.size!==1)return null;let p=[...l.values()][0],d=ri(p);return c.map(u=>u.number==="2"?{...u,text:`${s} \`${d}\` (p)`}:u)}function ti(c,t){if(!c)return null;let e=(0,k.normalizeSnapshot)(c).split(`
|
|
23
|
+
`).map(a=>a.trim()),i=new RegExp(`^(?:[>\u203A\u276F\u25B8\u25B6\u279C\u27A4*\u25CF]\\s*)?${t}\\.\\s+(.*)$`),s=-1,r="";for(let a=e.length-1;a>=0;a-=1){let l=e[a].match(i);if(l){s=a,r=l[1];break}}if(s<0)return null;let n=[r];for(let a=s+1;a<e.length&&!(/^(?:[>›❯▸▶➜➤*●]\s*)?\d+\.\s+/.test(e[a])||!e[a]||(n.push(e[a]),/\(p\)\s*$/i.test(e[a])));a+=1);return n.some(a=>/\(p\)\s*$/i.test(a))?n:null}function ii(c){if(c.length===0||c.length>13)return new Set;let t=new Set([c[0]]);for(let e of c.slice(1)){let i=new Set;for(let s of t)i.add(`${s}${e}`),i.add(`${s} ${e}`);t=i}return t}function si(c){try{let t=(0,Pe.parse)(c,e=>`\${${e}}`);return t.every(e=>typeof e=="string")?t:null}catch{return null}}function ri(c){return c.map(t=>/^[A-Za-z0-9_@%+=:,./-]+$/.test(t)?t:`'${t.replace(/'/g,`'"'"'`)}'`).join(" ")}function ni(c,t){if(c.length===0)return!1;let e;try{e=(0,Pe.parse)(t,s=>`\${${s}}`)}catch{return!1}let i=[[]];for(let s of e){if(typeof s=="string"){i[i.length-1].push(s);continue}if("op"in s&&["&&","||",";","|","|&","&"].includes(s.op)){i.push([]);continue}return!1}return i.some(s=>c.every((r,n)=>s[n]===r))}var ae=class c{constructor(){this.sessionState=null;this.unsubscribe=null;this.sessionKey=null;this.sessionIsEncrypted=!1;this.sessionKeyGen=null;this.e1PromptRaises=new Map;this.e1PendingResolutions=new Map;this.e1ResolutionInFlight=new Set;this.e1RaiseInFlight=new Map;this.e1NeedsReRaise=new Set;this.e1RetirementOrphans=new Map;this.e1ContentKeyIndex=new Map;this.e1TtlRefreshTimer=null;this.toolActivity=null;this.toolActivityStartPromise=null;this.toolActivityLegacyRecorders=new Map;this.pendingInteractivePrompt=null;this.queuedInteractivePrompts=[];this.isInitializingSession=!1;this.bufferedLogEntries=[];this.logEntryChain=Promise.resolve();this.hookEventChain=Promise.resolve();this.hooksActive=!1;this.hooksCompatibilityNoticeSent=!1;this.permissionRequestHookInFlight=null;this.queuedPermissionRequestDedupeKeys=new Map;this.resolvedApprovalDedupeKeys=new Map;this.subscribedSessionId=null;this.subscribedSessionState=null;this.terminalInputChain=Promise.resolve();this.terminalInputBlockedStates=new WeakSet;this.mobilePromptDeduper=new se({expiryMs:1e4});this.launchSessionInitPromise=null;this.sessionStartedInitPromise=null;this.bootstrapSessionId=null;this.recoveryBootstrapOwnerBound=!1;this.resumeBackendSession=m.resumeOrCreateSession;this.sessionBootstrapFailureCount=0;this.sessionBootstrapRetryAt=0;this.retiredSessionRecoveryPromise=null;this.lifecycleGeneration=0;this.isStopping=!1;this.tmuxLifecycleTimer=null;this.tmuxLifecycleCheckInFlight=!1;this.tmuxLifecycleObservedAlive=!1;this.v1Bridge=new ne;this.orchestrationClient=null;this.userDecisionUnsubscribe=null;this.httpApi=new ie,this.sessionWatcher=new V,this.approvalDetector=new Q,this.promptResponder=new Z,this.tmuxPaneObserver=new ee}static{this.E1_TTL_REFRESH_MS=300*1e3}async start(){o.info("Starting CodeVibe Codex companion server",{environment:(0,m.getEnvironment)()}),this.appSyncClient=new m.AppSyncClient,await this.appSyncClient.authenticateWithStoredTokens()||(o.error('Authentication failed. Run "codevibe login" first.'),console.error('Not authenticated. Run "codevibe login" to sign in.'),process.exit(1)),o.info("Authenticated successfully",{userId:this.appSyncClient.getCurrentUserId(),email:this.appSyncClient.getCurrentUserEmail()}),await(0,m.registerDeviceEncryptionKey)(this.appSyncClient,o),(0,m.startDeviceKeyWatcher)(this.appSyncClient,o),(0,m.pushDetectedAgents)(this.appSyncClient,o).catch(i=>{o.warn("Failed to update available agents (non-fatal)",{error:i?.message})});try{let i=await this.appSyncClient.sweepOrphanSessions({agentType:"CODEX"});i>0&&o.info("Orphan sweep: marked stale Codex sessions INACTIVE",{swept:i})}catch(i){o.warn("Orphan sweep failed, continuing startup",{error:i instanceof Error?i.message:String(i)})}this.httpApi.onEvent(this.handleEventFromHook.bind(this));let e=await this.httpApi.start();o.info("HTTP API started for hooks",{port:e}),this.startTmuxLifecycleMonitor(),await this.createLaunchSession(),this.setupEventHandlers(),this.sessionWatcher.start(),o.info("CodeVibe Codex companion server started")}async createLaunchSession(){if(this.isStopping)return;if(process.env[Se]==="1"){o.info("Recovery daemon deferring backend bootstrap until the native rollout is known");return}let t=this.lifecycleGeneration,e=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!e){o.warn("No CODEVIBE_CODEX_TMUX_SESSION \u2014 skipping launch session");return}let i;this.launchSessionInitPromise=new Promise(s=>{i=s});try{let s=process.env.CODEX_WORKING_DIRECTORY||process.cwd(),r=this.getOrCreateBootstrapSessionId(),n=this.appSyncClient.getCurrentUserId();o.info("Creating launch session",{sessionId:r,projectPath:s});let a=!1;try{let l=await(0,m.resumeOrCreateSession)({sessionId:r,userId:n,agentType:m.AgentType.CODEX,projectPath:s,metadata:{launchSession:!0}},this.appSyncClient,o);if(r=l.sessionId,!this.isLifecycleCurrent(t)){await this.retireCancelledBootstrap(r,"launch_session");return}this.sessionKey=l.sessionKey,this.sessionKeyGen=l.sessionKeyGen,this.sessionIsEncrypted=!!l.sessionKey,a=!0,this.sessionState={sessionId:r,userId:n,projectPath:s,cwd:s,createdAt:new Date,subscriptionActive:!1,metadata:{launchSession:!0},encryptionSnapshot:{sessionKey:l.sessionKey,sessionIsEncrypted:!!l.sessionKey},codexSessionId:e,codexLogFile:void 0},this.clearSessionBootstrapFailure(),this.bootstrapSessionId=null,await b("daemon_init_step_completed",{step:"session_resume_or_create",path:"launch_session"})}catch(l){if(!this.isLifecycleCurrent(t)){let p=this.authoritativeSessionIdFromError(l)??r;await this.retireCancelledBootstrap(p,"launch_session_error");return}await b("daemon_init_step_failed",{step:"session_resume_or_create",path:"launch_session",error_class:l?.name||"Error",error_message:l?.message||String(l)}),l?.code==="ENCRYPTED_SESSION_NO_KEY"&&(this.sessionIsEncrypted=!0,this.sessionKey=null),this.bindBootstrapIdentityFromError(l),this.recordSessionBootstrapFailure(l,"launch_session"),o.error("Failed to create/resume launch session (non-fatal)",{error:l})}if(!a)return;await b("daemon_init_step_completed",{step:"session_state_set",path:"launch_session"});try{this.subscribeToMobileEvents(r)?await b("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"launch_session"}):await b("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(l){await b("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:l?.name||"Error",error_message:l?.message||String(l)}),o.error("Failed to subscribe to mobile events for launch session",{error:l})}try{await this.appSyncClient.startHeartbeat(r)?await b("daemon_init_step_completed",{step:"heartbeat_start",path:"launch_session"}):(await b("daemon_init_step_failed",{step:"heartbeat_start",path:"launch_session",error_class:"InitialHeartbeatNotPersisted",error_message:"Backend did not confirm the initial heartbeat mutation"}),o.error("Initial launch-session heartbeat was not persisted",{sessionId:r}))}catch(l){await b("daemon_init_step_failed",{step:"heartbeat_start",path:"launch_session",error_class:l?.name||"Error",error_message:l?.message||String(l)}),o.error("Failed to start heartbeat for launch session",{error:l})}try{await this.subscribeToOnApplyUserDecision(r)}catch(l){o.error("Failed to subscribe to onApplyUserDecision for launch session (non-fatal)",{error:l})}this.startMobileEndWatcher(r),o.info("Launch session created",{sessionId:r})}finally{i()}}encryptForEmit(t,e,i,s){let r=this.sessionState;if(!r||r.sessionId!==s||!r.encryptionSnapshot)return o.warn("Dropping event from stale or unresolved session generation (#638)",{type:i,sessionId:s,currentSessionId:r?.sessionId}),null;let{sessionKey:n,sessionIsEncrypted:a}=r.encryptionSnapshot,l=(0,m.encryptForEmit)(n,a,t,e);return l===null&&o.error("No session key for ENCRYPTED session \u2014 dropping event (fail-closed, #638)",{type:i,sessionId:s}),l}newE1Raise(t,e,i,s){let{record:r}=(0,m.newPromptRaise)({sessionId:t,producerKind:"PLUGIN_APPROVAL",mobileActionable:e,agentType:"CODEX",...i!==void 0&&{title:i}});return this.e1PromptRaises.set(r.promptId,{record:r,...s?.dedupeKey!==void 0?{resolutionDedupeKey:s.dedupeKey}:{},...s?.callId!==void 0?{resolutionCallId:s.callId}:{}}),this.e1TtlRefreshTimer||this.startE1TtlRefresh(),r}stashE1RaiseContent(t,e,i){let s=this.e1PromptRaises.get(t);s&&(s.contentPlain=e,s.metadataPlain=i)}async emitSuppressedPromptCarrier(t,e){let i="\u26A0\uFE0F A prompt is waiting in your desktop terminal, but its options could not be shown here. Please answer it on your desktop.",s=this.encryptForEmit(i,{e1SuppressedPrompt:!0},m.EventType.NOTIFICATION,t);return s?(await this.trackE1Raise(e.promptId,this.appSyncClient.createEvent({sessionId:t,type:m.EventType.NOTIFICATION,source:m.EventSource.DESKTOP,content:s.content,metadata:s.metadata,...(0,m.raiseFieldsFromRecord)(e),notificationText:i,timestamp:(0,m.prepareEventTimestamp)({orderingKey:t}),isEncrypted:s.isEncrypted?!0:void 0})),o.info("E1: emitted suppressed-prompt badge carrier (mobileActionable=false)",{sessionId:t,promptId:e.promptId}),!0):!1}raiseSuppressedBadge(t,e){if(e){if(this.hasRecentlyResolvedApprovalDedupeKey(t,e)){o.debug("Skipping suppressed-prompt carrier; approval completed while producer was in flight",{sessionId:t,dedupeKey:e});return}let s=`${t}::${e}`,r=this.e1ContentKeyIndex.get(s);if(r&&this.e1PromptRaises.has(r))return;r&&this.e1ContentKeyIndex.delete(s)}let i=this.newE1Raise(t,!1,void 0,e?{dedupeKey:e}:void 0);e&&this.e1ContentKeyIndex.set(`${t}::${e}`,i.promptId),this.emitSuppressedPromptCarrier(t,i).catch(s=>{o.error("E1: failed to emit suppressed-prompt badge carrier",{sessionId:t,promptId:i.promptId,error:s instanceof Error?s.message:String(s)})})}snapshotOpenE1(t){return[...this.e1PromptRaises.values()].filter(e=>e.record.sessionId===t).map(e=>({record:{...e.record},...e.contentPlain!==void 0&&{contentPlain:e.contentPlain},...e.metadataPlain!==void 0&&{metadataPlain:e.metadataPlain},...e.resolutionDedupeKey!==void 0&&{resolutionDedupeKey:e.resolutionDedupeKey},...e.resolutionCallId!==void 0&&{resolutionCallId:e.resolutionCallId}}))}parkRetirementOrphans(t){for(let e of this.snapshotOpenE1(t))this.e1RetirementOrphans.set(e.record.promptId,e)}async drainRetirementOrphans(t){if(this.e1RetirementOrphans.size===0){this.e1PendingResolutions.size>0&&!this.e1TtlRefreshTimer&&this.startE1TtlRefresh();return}o.info("E1 (\xA76a-4): re-homing parked retirement-orphan prompts onto replacement session",{replacementSessionId:t,count:this.e1RetirementOrphans.size});for(let[e,i]of[...this.e1RetirementOrphans]){let r=this.e1PromptRaises.get(e)??{record:{...i.record},...i.contentPlain!==void 0&&{contentPlain:i.contentPlain},...i.metadataPlain!==void 0&&{metadataPlain:i.metadataPlain},...i.resolutionDedupeKey!==void 0&&{resolutionDedupeKey:i.resolutionDedupeKey},...i.resolutionCallId!==void 0&&{resolutionCallId:i.resolutionCallId}};for(let[a,l]of this.e1ContentKeyIndex.entries())l===e&&this.e1ContentKeyIndex.delete(a);if(r.record.sessionId=t,this.e1PromptRaises.set(e,r),r.resolutionDedupeKey&&this.e1ContentKeyIndex.set(`${t}::${r.resolutionDedupeKey}`,e),!await this.reRaiseOneE1(t,r,{untilAck:!0}))break;this.e1RetirementOrphans.delete(e)}this.e1TtlRefreshTimer||this.startE1TtlRefresh()}isReRaiseTargetCurrent(t){return!this.isStopping&&this.sessionState!==null&&this.sessionState.sessionId===t}async reRaiseOneE1(t,e,i){let s=e.record,r=s.mobileActionable&&e.contentPlain!==void 0,n=i?.untilAck??!1,a=4,l=4e3;for(let p=1;n||p<=a;p++){if(n&&!this.isReRaiseTargetCurrent(t))return this.e1NeedsReRaise.add(s.promptId),o.warn("E1: retirement re-raise aborted (stopping/superseded) \u2014 parked",{sessionId:t,promptId:s.promptId}),!1;try{if(r){let d=this.encryptForEmit(e.contentPlain,e.metadataPlain??{},m.EventType.INTERACTIVE_PROMPT,t);if(!d)return!1;await this.trackE1Raise(s.promptId,this.appSyncClient.createEvent({sessionId:t,type:m.EventType.INTERACTIVE_PROMPT,source:m.EventSource.DESKTOP,content:d.content,metadata:d.metadata,...(0,m.raiseFieldsFromRecord)(s),timestamp:(0,m.prepareEventTimestamp)({orderingKey:t}),...d.isEncrypted?{isEncrypted:!0}:{}}))}else if(s.mobileActionable=!1,!await this.emitSuppressedPromptCarrier(t,s))return!1;return this.e1NeedsReRaise.delete(s.promptId),o.info("E1: re-raised prompt onto replacement session",{sessionId:t,promptId:s.promptId,actionable:r}),!0}catch(d){if(!n&&p===a)return this.e1NeedsReRaise.add(s.promptId),o.error("E1: re-raise unacked after backoff \u2014 parked for retry-until-ack",{sessionId:t,promptId:s.promptId,error:d instanceof Error?d.message:String(d)}),!1;if(n){let u=Date.now()+Math.min(250*2**(p-1),l);for(;Date.now()<u&&this.isReRaiseTargetCurrent(t);)await new Promise(f=>setTimeout(f,Math.min(50,u-Date.now())))}else await new Promise(u=>setTimeout(u,250*p))}}return!1}async drainPendingE1ReRaises(){if(this.e1NeedsReRaise.size!==0)for(let t of[...this.e1NeedsReRaise]){let e=this.e1PromptRaises.get(t);if(!e){this.e1NeedsReRaise.delete(t);continue}!this.sessionState||e.record.sessionId!==this.sessionState.sessionId||await this.reRaiseOneE1(e.record.sessionId,e)}}beginE1Resolution(t,e){if(this.e1PendingResolutions.has(t))return!0;let i=this.e1PromptRaises.get(t);if(!i||i.record.sessionId!==e)return!1;this.e1PromptRaises.delete(t),this.e1NeedsReRaise.delete(t),this.e1RetirementOrphans.delete(t);for(let[s,r]of this.e1ContentKeyIndex.entries())r===t&&this.e1ContentKeyIndex.delete(s);return this.e1PendingResolutions.set(t,{record:{...i.record},resolutionAt:new Date().toISOString(),attempts:0}),this.e1TtlRefreshTimer||this.startE1TtlRefresh(),!0}async emitE1Resolution(t){let e=this.e1PendingResolutions.get(t);if(!(!e||this.e1ResolutionInFlight.has(t))){this.e1ResolutionInFlight.add(t);try{let i=this.e1RaiseInFlight.get(t);if(i&&await i,e=this.e1PendingResolutions.get(t),!e)return;if((await this.appSyncClient.createEvent({sessionId:e.record.sessionId,type:m.EventType.NOTIFICATION,source:m.EventSource.DESKTOP,resolvedPromptId:e.record.promptId,ownerToken:e.record.ownerToken,resolutionAt:e.resolutionAt,timestamp:(0,m.prepareEventTimestamp)({orderingKey:e.record.sessionId})}))?.promptId!==e.record.promptId)throw new Error("E1_PLUGIN_RESOLUTION_NOT_ACKNOWLEDGED: exact prompt id was not returned");this.e1PendingResolutions.delete(t),o.info("E1: plugin approval resolution acknowledged",{sessionId:e.record.sessionId,promptId:t})}catch(i){let s=this.e1PendingResolutions.get(t);o.warn("E1: plugin approval resolution unacknowledged; parked for retry",{sessionId:s?.record.sessionId,promptId:t,error:i instanceof Error?i.message:String(i)})}finally{this.e1ResolutionInFlight.delete(t)}}}trackE1Raise(t,e){let i=e.then(()=>{},()=>{});return this.e1RaiseInFlight.set(t,i),i.then(()=>{this.e1RaiseInFlight.get(t)===i&&this.e1RaiseInFlight.delete(t)}),e}async drainPendingE1Resolutions(){for(let[t,e]of[...this.e1PendingResolutions.entries()])e.attempts+=1,await this.emitE1Resolution(t)}beginE1PromptResolutions(t,e){let i=[];for(let s of new Set(t))this.beginE1Resolution(s,e)&&i.push(s);return i}launchE1Resolutions(t){Promise.all([...t].map(e=>this.emitE1Resolution(e)))}async refreshE1Ttls(){await this.drainPendingE1Resolutions(),await this.drainPendingE1ReRaises();let t=this.sessionState?.sessionId;if(!t)return;let e=[...this.e1PromptRaises.values()].filter(i=>i.record.sessionId===t).map(i=>i.record.promptId);if(e.length!==0)try{let i=await this.appSyncClient.refreshOpenPromptTtl(e);for(let s of i){let r=this.e1PromptRaises.get(s);r&&r.record.sessionId===t&&await this.reRaiseOneE1(t,r)}}catch(i){o.warn("E1: TTL-refresh tick failed (non-fatal, retries next tick)",{error:i instanceof Error?i.message:String(i)})}}startE1TtlRefresh(){this.e1TtlRefreshTimer&&clearInterval(this.e1TtlRefreshTimer),this.e1TtlRefreshTimer=setInterval(()=>{this.refreshE1Ttls()},c.E1_TTL_REFRESH_MS)}stopE1TtlRefresh(){this.e1TtlRefreshTimer&&(clearInterval(this.e1TtlRefreshTimer),this.e1TtlRefreshTimer=null)}isExpectedSessionStateCurrent(t){return!this.isStopping&&this.sessionState===t&&!this.terminalInputBlockedStates.has(t)}sendSessionPinnedInput(t,e){if(!this.isExpectedSessionStateCurrent(t)||this.terminalInputBlockedStates.has(t))return Promise.resolve(!1);let i=this.terminalInputChain.then(async()=>!this.isExpectedSessionStateCurrent(t)||this.terminalInputBlockedStates.has(t)?!1:this.promptResponder.sendInput(t.sessionId,e));return this.terminalInputChain=i.then(()=>{},()=>{}),i}handleEventFromHook(t){if(this.isStopping)return Promise.resolve();let e=this.lifecycleGeneration,i=this.registerQueuedPermissionRequest(t),s=this.hookEventChain.then(()=>this.processHookEvent(t,e)),r=i?s.finally(()=>this.unregisterQueuedPermissionRequest(i)):s;return this.hookEventChain=r.catch(n=>{o.error("[Hooks] event handler failed",{hookEvent:t.hook_event_name,sessionId:t.session_id,error:n instanceof Error?n.message:String(n)})}),r}registerQueuedPermissionRequest(t){if(t.hook_event_name!=="PermissionRequest"||!this.sessionState||this.sessionWatcher.getAuthoritativeSessionId()!==t.session_id)return null;let e=this.buildApprovalPromptContextFromHookPayload(t),i=this.buildApprovalDedupeKey(e);if(!i)return null;let s=`${this.sessionState.sessionId}::${i}`;return this.queuedPermissionRequestDedupeKeys.set(s,(this.queuedPermissionRequestDedupeKeys.get(s)??0)+1),s}unregisterQueuedPermissionRequest(t){let e=this.queuedPermissionRequestDedupeKeys.get(t)??0;e<=1?this.queuedPermissionRequestDedupeKeys.delete(t):this.queuedPermissionRequestDedupeKeys.set(t,e-1)}async processHookEvent(t,e){if(!this.isLifecycleCurrent(e))return;let{session_id:i,hook_event_name:s,type:r,content:n,metadata:a}=t;o.info("[Hooks] Received event",{sessionId:i,hookEvent:s,type:r,contentLength:n?.length});let l=this.sessionWatcher.getAuthoritativeSessionId();if(l&&l!==i){o.warn("[Hooks] Rejecting event for foreign native session",{hookEvent:s,sessionId:i,authoritativeSessionId:l});return}if(a?.transcript_path){let u=await this.sessionWatcher.bindToSessionTranscript(a.transcript_path,i);if(!this.isLifecycleCurrent(e))return;let f=u.status==="pending"?await u.completion:u;if(!this.isLifecycleCurrent(e))return;if(f.status!=="bound"){o.warn("[Hooks] Rejecting event whose transcript ownership was not proven",{hookEvent:s,sessionId:i,reason:f.reason});return}}else if(l!==i){o.warn("[Hooks] Rejecting event without an owned transcript",{hookEvent:s,sessionId:i});return}if(!this.isLifecycleCurrent(e)||this.sessionWatcher.getAuthoritativeSessionId()!==i){o.warn("[Hooks] Rejecting event after ownership changed during admission",{hookEvent:s,sessionId:i,authoritativeSessionId:this.sessionWatcher.getAuthoritativeSessionId()});return}if(this.hooksActive=!0,s==="SessionStart"){if(this.launchSessionInitPromise&&(await this.launchSessionInitPromise,!this.isLifecycleCurrent(e)))return;if(this.sessionState){if(o.info("[Hooks] SessionStart \u2014 launch session already exists, updating codexSessionId",{existingSessionId:this.sessionState.sessionId,codexSessionId:i}),this.sessionState.codexSessionId=i,this.sessionState.metadata={...this.sessionState.metadata,codexSessionId:i,cliVersion:a?.model||"unknown",modelProvider:a?.model||"unknown",launchSession:void 0},this.appSyncClient.updateSession({sessionId:this.sessionState.sessionId,metadata:this.sessionState.metadata}).catch(u=>o.warn("Failed to update session metadata",{error:u})),await this.startTmuxObserverWithBeacon("session_start_existing"),!this.isLifecycleCurrent(e))return;await this.ensureToolActivityStarted(i)}else{let u={id:i,timestamp:new Date().toISOString(),cwd:a?.cwd||process.cwd(),originator:"hook",cli_version:a?.model||"unknown",instructions:null,source:a?.source||"startup",model_provider:a?.model||"unknown"};await this.ensureSessionStarted(u)}return}if(!this.sessionState){o.warn("[Hooks] Hook event for un-bootstrapped session \u2014 self-healing via session bootstrap (#638)",{hookEvent:s,sessionId:i});let u={id:i,timestamp:new Date().toISOString(),cwd:a?.cwd||process.cwd(),originator:"hook",cli_version:a?.model||"unknown",instructions:null,source:a?.source||"startup",model_provider:a?.model||"unknown"};if(await this.ensureSessionStarted(u),!this.isLifecycleCurrent(e))return;if(!this.sessionState){o.warn("[Hooks] Session still not initialized after self-heal, dropping event",{hook_event_name:s});return}}let p=this.sessionState,d=p.sessionId;if(r==="USER_PROMPT"&&n){let u=this.consumeRecentMobilePrompt(d,n);if(u){o.info("[Hooks] Skipping duplicate USER_PROMPT from mobile",{sessionId:d,matchType:u.matchType,originalLength:u.originalLength,echoLength:u.echoLength});return}}if(s==="PreToolUse"){o.debug("[Hooks] PreToolUse observed; AppSync emission suppressed",{toolName:a?.tool_name||"unknown",sessionId:d});return}if(s==="PermissionRequest"){await this.handlePermissionRequestHook(t,p);return}if(s==="PostToolUse"){let u=this.buildApprovalPromptContextFromHookPayload(t),f=this.buildApprovalDedupeKey(u),v=this.firstString(a?.tool_use_id,a?.call_id,a?.callId)??"";if(await this.clearResolvedInteractivePrompt(v,f),!this.isExpectedSessionStateCurrent(p)||this.toolActivity?.isActive()&&await this.toolActivity.observeCall({callId:a?.tool_use_id??a?.call_id??a?.callId,toolName:a?.tool_name,toolInput:a?.tool_input})!=="closed")return;let h=this.encryptForEmit(n,a,m.EventType.TOOL_USE,d);if(!h)return;let y=h.content,S=h.metadata,w=h.isEncrypted,P=a?.tool_use_id??a?.call_id??a?.callId,_=typeof P=="string"&&P.length>0&&!!this.sessionKey,x=_?this.getToolActivityLegacyRecorder(d):void 0;x&&_&&x.markLegacyInFlight(P);try{let O=await this.appSyncClient.createEvent({sessionId:d,type:m.EventType.TOOL_USE,source:m.EventSource.DESKTOP,content:y,metadata:S,isEncrypted:w,timestamp:(0,m.prepareEventTimestamp)({orderingKey:d})});x&&_&&((0,m.isPersistedEventResult)(O)?await x.finalizeLegacyOwned([P]):x.clearLegacyInFlight(P))}catch(O){throw x&&_&&x.clearLegacyInFlight(P),O}return}if(r==="ASSISTANT_RESPONSE"||r==="USER_PROMPT"){if(r==="ASSISTANT_RESPONSE"){this.sessionWatcher.getBindSource()==="authoritative"&&this.sessionWatcher.getAuthoritativeSessionId()===i?o.debug("[Hooks] Suppressing Stop final \u2014 JSONL watcher authoritatively bound to this session (Bug #2)"):o.warn("[Hooks] Dropping Stop final after authoritative ownership changed",{authoritativeSessionId:this.sessionWatcher.getAuthoritativeSessionId()});return}let u=this.encryptForEmit(n,void 0,m.EventType.USER_PROMPT,d);if(!u)return;await this.appSyncClient.createEvent({sessionId:d,type:m.EventType.USER_PROMPT,source:m.EventSource.DESKTOP,content:u.content,isEncrypted:u.isEncrypted,timestamp:(0,m.prepareEventTimestamp)({orderingKey:d})});return}}mapToolName(t){return{shell_command:"Bash",shell:"Bash",apply_patch:"Edit",create_file:"Write",read_file:"Read"}[t]||t}trackMobilePrompt(t,e){this.mobilePromptDeduper.track(t,e),o.debug("Tracking mobile prompt for USER_PROMPT echo deduplication",{sessionId:t,promptLength:e.trim().length})}forgetMobilePrompt(t,e){this.mobilePromptDeduper.forget(t,e)}consumeRecentMobilePrompt(t,e){return this.mobilePromptDeduper.consumeIfDuplicate(t,e)}setupEventHandlers(){this.sessionWatcher.on("session-started",async t=>{try{if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionState){o.info("[JSONL] Session already active, skipping",{currentSessionId:this.sessionState.sessionId,codexSessionId:t.id}),await this.ensureToolActivityStarted(t.id);return}await this.ensureSessionStarted(t)}catch(e){o.error("[JSONL] session-started handler failed (non-fatal) \u2014 next event retries",{codexSessionId:t?.id,error:String(e)})}}),this.sessionWatcher.on("log-entry",t=>{this.enqueueLogEntry(t)}),this.approvalDetector.on("approval-pending",async t=>{try{await this.handleApprovalPending(t)}catch(e){o.error("approval-pending handler failed (non-fatal)",{error:String(e)})}}),this.tmuxPaneObserver.on("prompt-candidate",async t=>{try{await this.handleTmuxPromptCandidate(t.snapshot)}catch(e){o.error("prompt-candidate handler failed (non-fatal)",{error:String(e)})}}),this.tmuxPaneObserver.on("observer-error",t=>{o.debug("Tmux pane observer error",{error:t})}),this.sessionWatcher.on("error",t=>{o.error("Session watcher error:",t)})}async ensureSessionStarted(t,e){if(this.isStopping||(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.isStopping)||this.sessionState)return;process.env[Se]==="1"&&await this.bindRecoveryBootstrapIdentity(t.id);let i=this.sessionBootstrapRetryAt-Date.now();if(i>0){o.warn("Session bootstrap is in retry backoff; hook will be retried later",{codexSessionId:t.id,retryDelayMs:i,failureCount:this.sessionBootstrapFailureCount});return}if(this.sessionStartedInitPromise){try{await this.sessionStartedInitPromise}catch{}return}let s=this.handleSessionStarted(t,e);this.sessionStartedInitPromise=s.catch(()=>{});try{await s}finally{this.sessionStartedInitPromise=null}}async handleSessionStarted(t,e){if(this.isStopping)return;let i=this.lifecycleGeneration;o.info("Handling new Codex session",{codexSessionId:t.id}),this.isInitializingSession=!0,this.bufferedLogEntries=[],this.sessionState&&await this.endActiveSession("new-codex-session-started");let s=process.env.CODEX_WORKING_DIRECTORY||t.cwd||process.cwd(),r=this.getOrCreateBootstrapSessionId(),n=this.appSyncClient.getCurrentUserId(),a={codexSessionId:t.id,cliVersion:t.cli_version,modelProvider:t.model_provider},l={sessionKey:null,sessionIsEncrypted:!0};try{let p={sessionId:r,userId:n,agentType:m.AgentType.CODEX,projectPath:s,metadata:a},d=await this.resumeOrCreateBootstrapSession(p);if(r=d.sessionId,!this.isLifecycleCurrent(i)){this.isInitializingSession=!1,await this.retireCancelledBootstrap(r,"session_started");return}this.sessionKey=d.sessionKey,this.sessionKeyGen=d.sessionKeyGen,this.sessionIsEncrypted=!!d.sessionKey,l={sessionKey:d.sessionKey,sessionIsEncrypted:!!d.sessionKey},await b("daemon_init_step_completed",{step:"session_resume_or_create",path:"session_started"})}catch(p){if(this.isInitializingSession=!1,!this.isLifecycleCurrent(i)){let d=this.authoritativeSessionIdFromError(p)??r;await this.retireCancelledBootstrap(d,"session_started_error");return}throw await b("daemon_init_step_failed",{step:"session_resume_or_create",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),p?.code==="ENCRYPTED_SESSION_NO_KEY"&&(this.sessionIsEncrypted=!0,this.sessionKey=null),this.bindBootstrapIdentityFromError(p),this.recordSessionBootstrapFailure(p,"session_started"),o.error("Failed to create/resume session:",p),p}try{this.sessionState={sessionId:r,userId:n,projectPath:s,cwd:t.cwd,createdAt:new Date,subscriptionActive:!1,metadata:a,encryptionSnapshot:l,codexSessionId:t.id,codexLogFile:this.sessionWatcher.getActiveLogFile()||void 0},this.clearSessionBootstrapFailure(),this.bootstrapSessionId=null,this.recoveryBootstrapOwnerBound=!1,await b("daemon_init_step_completed",{step:"session_state_set",path:"session_started"})}catch(p){await b("daemon_init_step_failed",{step:"session_state_set",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),o.error("Failed to set session state:",p)}await this.ensureToolActivityStarted(t.id);try{this.subscribeToMobileEvents(r)?await b("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"session_started"}):await b("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(p){await b("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),o.error("Failed to subscribe to mobile events:",p)}if(e)try{await e()}catch(p){o.error("E1: pre-heartbeat re-raise hook failed (non-fatal)",{sessionId:r,error:p instanceof Error?p.message:String(p)})}try{await this.drainRetirementOrphans(r)}catch(p){o.error("E1: retirement-orphan drain failed (non-fatal)",{sessionId:r,error:p instanceof Error?p.message:String(p)})}try{await this.appSyncClient.startHeartbeat(r)?await b("daemon_init_step_completed",{step:"heartbeat_start",path:"session_started"}):(await b("daemon_init_step_failed",{step:"heartbeat_start",path:"session_started",error_class:"InitialHeartbeatNotPersisted",error_message:"Backend did not confirm the initial heartbeat mutation"}),o.error("Initial session heartbeat was not persisted",{sessionId:r}))}catch(p){await b("daemon_init_step_failed",{step:"heartbeat_start",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),o.error("Failed to start heartbeat:",p)}try{await this.subscribeToOnApplyUserDecision(r)}catch(p){o.error("Failed to subscribe to onApplyUserDecision (non-fatal)",{error:p})}this.startMobileEndWatcher(r);try{await this.flushBufferedLogEntries(),await b("daemon_init_step_completed",{step:"flush_buffered_entries",path:"session_started"})}catch(p){await b("daemon_init_step_failed",{step:"flush_buffered_entries",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),o.error("Failed to flush buffered log entries:",p),this.bufferedLogEntries=[]}await this.startTmuxObserverWithBeacon("session_started"),this.isInitializingSession=!1}getOrCreateBootstrapSessionId(){return this.bootstrapSessionId||(this.bootstrapSessionId=z.mintBackendSessionId()),this.bootstrapSessionId}async bindRecoveryBootstrapIdentity(t){if(!(process.env[Se]!=="1"||this.bootstrapSessionId||this.sessionState||!t))try{let e=await this.buildToolActivityIntegration().recordedBackendSessionId(t);if(!e){o.warn("Recovery daemon found no durable backend owner; a new session will be created",{rolloutId:t});return}if(!/^codex-[A-Za-z0-9_-]{1,180}$/.test(e)){o.warn("Recovery daemon ignored invalid durable backend owner",{rolloutId:t});return}this.bootstrapSessionId=e,this.recoveryBootstrapOwnerBound=!0,o.info("Recovery daemon reclaiming existing backend session",{rolloutId:t,sessionId:e})}catch(e){o.warn("Recovery daemon could not read the durable rollout owner; a new session will be created",{rolloutId:t,error:e instanceof Error?e.message:String(e)})}}isSessionIdReservedRejection(t){return(t instanceof Error?t.message:String(t)).includes("SESSION_ID_RESERVED")}async resumeOrCreateBootstrapSession(t){try{return await this.resumeBackendSession(t,this.appSyncClient,o)}catch(e){if(!this.recoveryBootstrapOwnerBound||!this.isSessionIdReservedRejection(e))throw e;return o.warn("Recovery discarded a permanently reserved pending create; retrying the durable rollout owner",{sessionId:t.sessionId}),this.resumeBackendSession(t,this.appSyncClient,o)}}startTmuxLifecycleMonitor(){if(this.tmuxLifecycleTimer)return;let t=process.env[j];t&&(this.tmuxLifecycleTimer=setInterval(()=>{this.checkTmuxLifecycle(t)},Xt),this.tmuxLifecycleTimer.unref?.(),this.checkTmuxLifecycle(t))}async tmuxSessionExists(t){try{return await Vt("tmux",["has-session","-t",t]),!0}catch{return!1}}async checkTmuxLifecycle(t){if(!(this.isStopping||this.tmuxLifecycleCheckInFlight)){this.tmuxLifecycleCheckInFlight=!0;try{if(await this.tmuxSessionExists(t)){this.tmuxLifecycleObservedAlive=!0;return}if(!this.tmuxLifecycleObservedAlive||this.isStopping)return;this.stopTmuxLifecycleMonitor(),o.info("Native Codex tmux session ended; stopping companion daemon",{tmuxSession:t}),this.stop().then(()=>process.exit(0),e=>{o.error("Failed to stop companion daemon after native session end",{error:e instanceof Error?e.message:String(e)}),process.exit(1)})}finally{this.tmuxLifecycleCheckInFlight=!1}}}stopTmuxLifecycleMonitor(){this.tmuxLifecycleTimer&&(clearInterval(this.tmuxLifecycleTimer),this.tmuxLifecycleTimer=null)}isLifecycleCurrent(t){return!this.isStopping&&this.lifecycleGeneration===t}authoritativeSessionIdFromError(t){let e=t?.authoritativeSessionId;return typeof e=="string"&&e.length>0?e:null}async retireCancelledBootstrap(t,e){this.appSyncClient.stopHeartbeat(t),this.appSyncClient.cleanupSubscription(t);try{await this.appSyncClient.updateSession({sessionId:t,status:m.SessionStatus.INACTIVE}),o.info("Cancelled bootstrap row marked INACTIVE",{sessionId:t,path:e})}catch(i){o.warn("Cancelled bootstrap row could not be marked INACTIVE",{sessionId:t,path:e,error:i instanceof Error?i.message:String(i)})}}bindBootstrapIdentityFromError(t){let e=t?.authoritativeSessionId;typeof e!="string"||e.length===0||(this.bootstrapSessionId=e,o.info("Retained authoritative backend identity from failed bootstrap",{sessionId:e}))}recoverRetiredBackendSession(t){if(this.retiredSessionRecoveryPromise)return this.retiredSessionRecoveryPromise;if(this.isStopping)return Promise.resolve();let e=(async()=>{if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionStartedInitPromise&&await this.sessionStartedInitPromise,this.isStopping)return;let i=this.sessionState;if(!i||i.sessionId!==t)return;let s={id:i.codexSessionId||t,timestamp:new Date().toISOString(),cwd:i.cwd||i.projectPath,originator:"codevibe-retired-session-recovery",cli_version:String(i.metadata?.cliVersion??"unknown"),instructions:null,source:"codevibe",model_provider:String(i.metadata?.modelProvider??"unknown")};o.warn("Backend retired live Codex session; creating replacement row",{sessionId:t,codexSessionId:s.id}),this.parkRetirementOrphans(t),await this.endActiveSession("backend-generation-retired"),this.bootstrapSessionId=null,this.clearSessionBootstrapFailure(),await this.ensureSessionStarted(s)})();return this.retiredSessionRecoveryPromise=e.finally(()=>{this.retiredSessionRecoveryPromise=null}),this.retiredSessionRecoveryPromise}recordSessionBootstrapFailure(t,e){this.sessionBootstrapFailureCount+=1;let i=t instanceof Error?t.message:String(t),r=i.includes("SESSION_LIMIT_EXCEEDED")?6e4:Math.min(5e3*2**(this.sessionBootstrapFailureCount-1),6e4);this.sessionBootstrapRetryAt=Date.now()+r,o.warn("Session bootstrap retry scheduled",{path:e,requestedSessionId:this.bootstrapSessionId,failureCount:this.sessionBootstrapFailureCount,delayMs:r,error:i})}clearSessionBootstrapFailure(){this.sessionBootstrapFailureCount=0,this.sessionBootstrapRetryAt=0}async flushBufferedLogEntries(){if(this.bufferedLogEntries.length===0)return;let t=this.bufferedLogEntries;this.bufferedLogEntries=[],o.info("Flushing buffered log entries after session initialization",{count:t.length,sessionId:this.sessionState?.sessionId});let e=Promise.resolve();for(let i of t)e=this.enqueueLogEntry(i);await e.catch(()=>{})}enqueueLogEntry(t){let e=this.logEntryChain.then(()=>this.handleLogEntry(t));return this.logEntryChain=e.catch(i=>{o.error("[JSONL] log entry handler failed",{type:t.type,err:String(i)})}),e}async handleLogEntry(t){if(!this.sessionState){if(this.isInitializingSession){this.bufferedLogEntries.push(t),o.debug("Buffering log entry until session initialization completes",{type:t.type,bufferedCount:this.bufferedLogEntries.length});return}o.warn("Received log entry but no active session");return}let e=this.sessionState,i=e.sessionId,{sessionKey:s,sessionIsEncrypted:r}=e.encryptionSnapshot;if(t.type==="response_item"&&t.payload){let h=t.payload.type;if(h==="function_call"||h==="custom_tool_call")this.approvalDetector.onToolCallStart(t.payload.call_id,t.payload.name,t.payload.arguments||t.payload.input||"");else if(h==="function_call_output"||h==="custom_tool_call_output"){let y=this.approvalDetector.getPendingCalls().find(w=>w.callId===t.payload.call_id),S=y?this.buildApprovalDedupeKey(this.buildApprovalPromptContextFromPendingCall(y)):void 0;if(this.approvalDetector.onToolCallComplete(t.payload.call_id),await this.clearResolvedInteractivePrompt(t.payload.call_id,S),!this.isExpectedSessionStateCurrent(e))return}}let n=Ne(t,i);if(!n)return;n.timestamp=(0,m.prepareEventTimestamp)({orderingKey:i,agentClock:t.timestamp});let a=t.payload?.type,l=!1;if(this.toolActivity?.isActive()&&n.type===m.EventType.TOOL_USE){let h=a==="function_call"||a==="custom_tool_call",y=a==="function_call_output"||a==="custom_tool_call_output";if(h&&typeof t.payload?.call_id=="string"){let S=this.sessionWatcher.getActiveLogFile();S&&this.toolActivity.bindTranscript(S);let w=await this.toolActivity.observeCall({callId:t.payload.call_id,toolName:n.metadata?.toolName??n.metadata?.tool_name,toolInput:n.metadata?.toolInput??n.metadata?.tool_input,ts:t.timestamp});if(!this.isExpectedSessionStateCurrent(e)||w!=="closed")return;l=!0}if(y)return}if(this.toolActivity?.isActive()&&(a==="user_message"||a==="agent_message")&&(await this.toolActivity.flush().catch(h=>o.warn("[tool-activity] codex boundary flush failed",{sessionId:i,err:String(h)})),!this.isExpectedSessionStateCurrent(e)))return;let p=a==="function_call"||a==="function_call_output",d=n.type===m.EventType.USER_PROMPT||n.type===m.EventType.ASSISTANT_RESPONSE||p&&(n.type===m.EventType.TOOL_USE||n.type===m.EventType.INTERACTIVE_PROMPT);if(!this.hooksActive&&d&&(await this.emitHooksCompatibilityModeNotice(e),!this.isExpectedSessionStateCurrent(e)))return;if(this.hooksActive){if(n.type===m.EventType.USER_PROMPT){o.debug("[JSONL] Skipping USER_PROMPT \u2014 hooks deliver it",{type:n.type});return}if(p&&(n.type===m.EventType.TOOL_USE||n.type===m.EventType.INTERACTIVE_PROMPT)&&!l){o.debug("[JSONL] Skipping function_call \u2014 hooks deliver this",{type:n.type,tool:t.payload?.name});return}}if(n.type===m.EventType.USER_PROMPT&&n.source===m.EventSource.DESKTOP){let h=this.consumeRecentMobilePrompt(i,n.content);if(h){o.info("[JSONL] Skipping duplicate USER_PROMPT from mobile",{sessionId:i,matchType:h.matchType,originalLength:h.originalLength,echoLength:h.echoLength});return}}if(this.sessionState!==e){o.warn("[JSONL] Dropping event from stale session generation (#638)",{sessionId:i,currentSessionId:this.sessionState?.sessionId});return}let u=t.payload?.call_id,f=n.type===m.EventType.TOOL_USE&&typeof u=="string"&&u.length>0&&!!s,v=f?this.getToolActivityLegacyRecorder(i):void 0;v&&f&&v.markLegacyInFlight(u);try{let h=(0,m.encryptForEmit)(s,r,n.content,n.metadata);if(!h){o.error("No session key for ENCRYPTED session \u2014 dropping JSONL event (fail-closed, #638)",{type:n.type,sessionId:i});return}n.content=h.content,n.metadata=h.metadata,h.isEncrypted&&(n.isEncrypted=!0,o.debug("Event encrypted",{type:n.type}));let y=await this.appSyncClient.createEvent(n);o.debug("Event synced to backend",{type:n.type,encrypted:h.isEncrypted}),v&&f&&((0,m.isPersistedEventResult)(y)?await v.finalizeLegacyOwned([u]):v.clearLegacyInFlight(u))}catch(h){v&&f&&v.clearLegacyInFlight(u),o.error("Failed to sync event:",h)}}async handlePermissionRequestHook(t,e){if(!this.isExpectedSessionStateCurrent(e))return;let i=this.buildApprovalPromptContextFromHookPayload(t),s=this.buildApprovalDedupeKey(i),r={ownerState:e,context:i,dedupeKey:s};this.permissionRequestHookInFlight=r;try{await this.handlePermissionRequestHookWhileTracked(t,e,i)}finally{this.permissionRequestHookInFlight===r&&(this.permissionRequestHookInFlight=null)}}buildApprovalPromptContextFromHookPayload(t){let e=t.metadata||{},i=typeof e.tool_name=="string"?e.tool_name:"Tool",s=e.tool_input,r=this.firstString(s?.command,s?.cmd),n=J(r)||q(r),l=(i==="apply_patch"?this.firstString(s?.patch,r,typeof s=="string"?s:void 0):void 0)||n,p=l?"apply_patch":i,d=l||this.stringifyToolInput(s);return{toolName:p,toolInput:s,rawInput:d,filePath:this.extractFilePathFromToolInput(p,s,d),diff:p==="apply_patch"?d:void 0,hint:this.buildPermissionRequestHint(p,s,d)}}async handlePermissionRequestHookWhileTracked(t,e,i=this.buildApprovalPromptContextFromHookPayload(t)){let s=t.metadata||{},{toolName:r,toolInput:n,rawInput:a}=i,l=this.buildToolDetailsForInteractivePrompt(i),p=l.tool_name||this.mapToolNameForApproval(r),d=l.tool_input||this.buildFallbackToolInput(i),u=!!(p&&d),f=this.buildApprovalDedupeKey({toolName:r,toolInput:n,filePath:i.filePath,rawInput:a,hint:i.hint});if(f&&this.hasRecentlyResolvedApprovalDedupeKey(e.sessionId,f))return;let v=await this.tryParsePermissionRequestPromptFromTmux(O=>this.parsedPromptMatchesApprovalContext(O,i),()=>this.isExpectedSessionStateCurrent(e));if(!this.isExpectedSessionStateCurrent(e)){o.warn("[Hooks] Dropping stale PermissionRequest after session generation changed",{sessionId:e.sessionId,currentSessionId:this.sessionState?.sessionId});return}if(f&&this.hasRecentlyResolvedApprovalDedupeKey(e.sessionId,f)){o.info("[Hooks] Dropping PermissionRequest completed while terminal options were being parsed",{sessionId:e.sessionId,toolName:r,dedupeKey:f});return}let h=v?.parsedPrompt??null;if(!h){o.warn("[Hooks] Suppressing PermissionRequest mobile prompt because exact Codex options are unavailable",{sessionId:e.sessionId,toolName:r,hint:i.hint}),this.raiseSuppressedBadge(e.sessionId,f);return}let y=this.mapToolNameForApproval(r)==="Bash"?this.firstString(n?.command,n?.cmd):void 0,S=this.buildCodexPromptPresentation(h,y,v?.snapshot);if(!S){o.warn("[Hooks] Suppressing PermissionRequest mobile prompt because Codex option hotkeys are unavailable",{sessionId:e.sessionId,toolName:r,hint:i.hint}),this.raiseSuppressedBadge(e.sessionId,f);return}let w=this.buildPermissionPromptId(s,r,n,a),P=this.buildApprovalPromptContent(S.content,{toolName:p,toolInput:d,hint:i.hint,filePath:i.filePath}),_={promptId:w,kind:S.kind,options:S.options,submitMap:S.submitMap,promptText:P,createdAt:Date.now(),source:"permission_hook",dedupeKey:f,ownerSessionId:e.sessionId,observerMatchKey:this.buildObserverPromptMatchKey(h),requiresFollowUpText:S.requiresFollowUpText},x={isApprovalHint:!0,toolName:r,toolInput:n,hint:i.hint,filePath:i.filePath,diff:i.diff,rawInput:a,tool_name:p,tool_input:d,has_details:u,options:S.options,instructions:S.instructions,prompt_source:h?"permission_hook_tmux":"permission_hook",permission_mode:s.permission_mode,turn_id:s.turn_id,dedupe_key:f};o.info("[Hooks] Sending PermissionRequest interactive prompt",{sessionId:e.sessionId,toolName:r,promptId:w,promptSource:x.prompt_source,dedupeKey:f}),await this.enqueueOrEmitInteractivePrompt({prompt:_,content:P,metadata:x,ownerState:e})}async emitHooksCompatibilityModeNotice(t){if(this.hooksCompatibilityNoticeSent||!this.isExpectedSessionStateCurrent(t))return;this.hooksCompatibilityNoticeSent=!0;let e="Codex hooks are not active. CodeVibe is using compatibility mode: mobile approvals still mirror the desktop prompt, but timeline events may be delayed or incomplete. Open Codex /hooks and trust/enable CodeVibe hooks for full fidelity.",i={compatibility_mode:!0,reason:"codex_hooks_inactive",action:"trust_enable_codevibe_hooks"};o.warn("Codex hooks inactive; running in compatibility mode",{sessionId:t.sessionId});let s=this.encryptForEmit(e,i,m.EventType.NOTIFICATION,t.sessionId);if(s)try{await this.appSyncClient.createEvent({sessionId:t.sessionId,type:m.EventType.NOTIFICATION,source:m.EventSource.DESKTOP,content:s.content,metadata:s.metadata,timestamp:(0,m.prepareEventTimestamp)({orderingKey:t.sessionId}),...s.isEncrypted?{isEncrypted:!0}:{}})}catch(r){o.warn("Failed to emit hooks compatibility mode notification",{error:r})}}async handleApprovalPending(t){let e=this.sessionState;if(!e)return;let i=this.buildApprovalDedupeKey(t);if(i&&this.hasRecentlyResolvedApprovalDedupeKey(e.sessionId,i)){o.info("Skipping heuristic approval prompt; same approval was already answered recently",{callId:t.callId,toolName:t.toolName,dedupeKey:i});return}if(i&&this.hasActiveOrQueuedPermissionHookPrompt(e.sessionId,i)){this.mergeCallIdIntoPromptByDedupeKey(e.sessionId,i,t.callId),o.info("Skipping heuristic approval prompt; PermissionRequest hook already emitted it",{callId:t.callId,toolName:t.toolName,dedupeKey:i});return}o.info("Sending approval pending interactive prompt",t);try{let s=await this.tryParseInteractivePromptFromTmux(),r=s?.parsedPrompt??null,n=this.buildToolDetailsForInteractivePrompt(t,s?.snapshot),a=n.tool_name||this.mapToolNameForApproval(t.toolName),l=n.tool_input||this.buildFallbackToolInput(t),p=!!(a&&l);if(!r){o.warn("Suppressing heuristic approval prompt because exact Codex options are unavailable",{callId:t.callId,toolName:t.toolName,hint:t.hint}),this.raiseSuppressedBadge(e.sessionId,i);return}if(!this.parsedPromptMatchesApprovalContext(r,t)){o.warn("Suppressing heuristic approval prompt because parsed tmux prompt does not match the active tool",{callId:t.callId,toolName:t.toolName,hint:t.hint,parsedPromptText:r.promptText}),this.raiseSuppressedBadge(e.sessionId,i);return}let d=this.mapToolNameForApproval(t.toolName)==="Bash"?this.firstString(t.toolInput?.command,t.toolInput?.cmd):void 0,u=this.buildCodexPromptPresentation(r,d,s?.snapshot);if(!u){o.warn("Suppressing heuristic approval prompt because Codex option hotkeys are unavailable",{callId:t.callId,toolName:t.toolName,hint:t.hint}),this.raiseSuppressedBadge(e.sessionId,i);return}let f=u.options,v=this.buildApprovalPromptContent(u.content,{toolName:a,toolInput:l,hint:t.hint,filePath:t.filePath}),h={promptId:t.callId,callId:t.callId,kind:u.kind,options:f,submitMap:u.submitMap,promptText:u.promptText,createdAt:Date.now(),source:r?"tmux":"heuristic",dedupeKey:i,ownerSessionId:e.sessionId,requiresFollowUpText:u.requiresFollowUpText},y={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:a,tool_input:l,has_details:p,options:f,instructions:u.instructions,prompt_source:r?"tmux":"heuristic",dedupe_key:i};o.debug("Interactive prompt (pre-encryption)",{sessionId:e.sessionId,callId:t.callId,contentPreview:v.substring(0,200),toolDetails:n,metadata:y}),await this.enqueueOrEmitInteractivePrompt({prompt:h,content:v,metadata:y,ownerState:e})}catch(s){o.error("Failed to send approval interactive prompt:",s)}}async handleTmuxPromptCandidate(t){let e=this.sessionState;if(!e){this.tmuxPaneObserver.resetLastPromptHash();return}let i=(0,k.parseInteractivePrompt)(t);if(!i){this.raiseSuppressedBadge(e.sessionId,null);return}let s=this.permissionRequestHookInFlight;if(s&&s.ownerState===e&&this.parsedPromptMatchesApprovalContext(i,s.context)){o.debug("Skipping matching tmux prompt candidate while PermissionRequest is resolving",{sessionId:e.sessionId,toolName:s.context.toolName});return}if(this.hasMatchingPermissionHookPrompt(i,e.sessionId)){o.debug("Skipping tmux prompt candidate already owned by PermissionRequest",{sessionId:e.sessionId,promptText:i.promptText});return}let r=this.getMostRecentPendingToolCall();if(!r){if(await new Promise(x=>setTimeout(x,500)),!this.isExpectedSessionStateCurrent(e)){o.warn("Dropping tmux prompt candidate after session generation changed",{sessionId:e.sessionId,currentSessionId:this.sessionState?.sessionId});return}r=this.getMostRecentPendingToolCall()}let n=r?this.buildApprovalPromptContextFromPendingCall(r):null;if(n&&!this.parsedPromptMatchesApprovalContext(i,n)){o.warn("Skipping tmux-detected prompt because parsed prompt does not match pending tool call",{callId:r?.callId,toolName:r?.name,parsedPromptText:i.promptText}),this.raiseSuppressedBadge(e.sessionId,null);return}let a=n?null:this.buildApprovalPromptContextFromParsedPrompt(i),l=n||a;if(!l){o.warn("Skipping tmux-detected prompt because no tool context could be derived from the parsed prompt",{parsedPromptText:i.promptText}),this.raiseSuppressedBadge(e.sessionId,null);return}let p=this.mapToolNameForApproval(l.toolName)==="Bash"?this.firstString(l.toolInput?.command,l.toolInput?.cmd):void 0,d=this.buildCodexPromptPresentation(i,p,t);if(!d){o.warn("Skipping tmux-detected prompt because Codex option hotkeys are unavailable",{parsedPromptText:i.promptText}),this.raiseSuppressedBadge(e.sessionId,null);return}let u=l?this.buildApprovalDedupeKey(l):void 0;if(u&&this.hasRecentlyResolvedApprovalDedupeKey(e.sessionId,u)){o.info("Skipping tmux-detected prompt; same approval was already answered recently",{promptText:i.promptText,dedupeKey:u});return}if(u&&this.hasActiveOrQueuedPermissionHookPrompt(e.sessionId,u)){r?.callId&&this.mergeCallIdIntoPromptByDedupeKey(e.sessionId,u,r.callId),o.info("Skipping tmux-detected prompt; PermissionRequest hook already emitted it",{promptText:i.promptText,dedupeKey:u});return}let f=l?this.buildToolDetailsForInteractivePrompt(l,t):{},v=f.tool_name||this.mapToolNameForApproval(r?.name),h=f.tool_input||(l?this.buildFallbackToolInput(l):void 0),y=!!(v&&h),w={promptId:r?.callId||(0,et.v4)(),callId:r?.callId,kind:d.kind,options:d.options,submitMap:d.submitMap,promptText:d.promptText,createdAt:Date.now(),source:"tmux",dedupeKey:u,ownerSessionId:e.sessionId,observerMatchKey:this.buildObserverPromptMatchKey(i),requiresFollowUpText:d.requiresFollowUpText},P={options:d.options,instructions:d.instructions,prompt_source:"tmux_live",toolName:l?.toolName,toolInput:l?.toolInput,hint:l?.hint,filePath:l?.filePath,diff:l?.diff,rawInput:l?.rawInput,tool_name:v,tool_input:h,has_details:y,dedupe_key:u},_=this.buildApprovalPromptContent(d.content,{toolName:v,toolInput:h,hint:l?.hint,filePath:l?.filePath});try{await this.enqueueOrEmitInteractivePrompt({prompt:w,content:_,metadata:P,ownerState:e})&&o.info("Sent tmux-detected interactive prompt",{sessionId:e.sessionId,promptText:i.promptText,kind:i.kind})}catch(x){o.error("Failed to send tmux-detected interactive prompt",{error:x})}}async enqueueOrEmitInteractivePrompt(t){if(!this.isExpectedSessionStateCurrent(t.ownerState))return o.warn("Dropping interactive prompt from stale session generation",{sessionId:t.ownerState.sessionId,currentSessionId:this.sessionState?.sessionId,source:t.prompt.source}),!1;if(t.prompt.ownerSessionId??=t.ownerState.sessionId,t.prompt.dedupeKey&&this.hasRecentlyResolvedApprovalDedupeKey(t.ownerState.sessionId,t.prompt.dedupeKey))return o.debug("Skipping interactive prompt emission; same approval was already answered recently",{source:t.prompt.source,callId:t.prompt.callId,dedupeKey:t.prompt.dedupeKey}),!1;let e=this.pendingInteractivePrompt;if(e&&e.ownerSessionId!==t.ownerState.sessionId&&(o.warn("Discarding active prompt from a stale session generation",{activeSessionId:e.ownerSessionId,candidateSessionId:t.ownerState.sessionId}),this.pendingInteractivePrompt=null,e=null),!e){this.pendingInteractivePrompt=t.prompt;try{return await this.emitInteractivePromptEvent(t),!0}catch(i){throw this.pendingInteractivePrompt?.promptId===t.prompt.promptId&&(this.pendingInteractivePrompt=null),i}}return this.isSameInteractivePrompt(e,t.prompt)?(!e.callId&&t.prompt.callId&&(e.callId=t.prompt.callId,o.debug("Merged callId into existing interactive prompt",{source:e.source,callId:t.prompt.callId,promptText:e.promptText})),o.debug("Skipping duplicate interactive prompt emission",{existingSource:e.source,candidateSource:t.prompt.source,existingCallId:e.callId,candidateCallId:t.prompt.callId,promptText:t.prompt.promptText}),!1):this.queuedInteractivePrompts.some(i=>this.isSameInteractivePrompt(i.prompt,t.prompt))?(o.debug("Skipping duplicate queued interactive prompt",{candidateSource:t.prompt.source,candidateCallId:t.prompt.callId,promptText:t.prompt.promptText}),!1):(this.queuedInteractivePrompts.push(t),o.info("Queued interactive prompt behind active prompt",{activeCallId:e.callId,queuedCallId:t.prompt.callId,queueLength:this.queuedInteractivePrompts.length}),!1)}async emitInteractivePromptEvent(t){if(!this.isExpectedSessionStateCurrent(t.ownerState))return;let e=t.ownerState.sessionId,i=this.e1PromptRaises.get(t.prompt.promptId),s=i?i.record:this.newE1Raise(e,!0,void 0,{...t.prompt.dedupeKey!==void 0?{dedupeKey:t.prompt.dedupeKey}:{},...t.prompt.callId!==void 0?{callId:t.prompt.callId}:{}});t.prompt.promptId=s.promptId;let r=this.e1PromptRaises.get(s.promptId);r&&(r.resolutionDedupeKey??=t.prompt.dedupeKey,r.resolutionCallId??=t.prompt.callId),t.prompt.dedupeKey&&this.e1ContentKeyIndex.set(`${e}::${t.prompt.dedupeKey}`,s.promptId),this.stashE1RaiseContent(s.promptId,t.content,t.metadata??{});let n=this.encryptForEmit(t.content,t.metadata,m.EventType.INTERACTIVE_PROMPT,e);n&&await this.trackE1Raise(s.promptId,this.appSyncClient.createEvent({sessionId:e,type:m.EventType.INTERACTIVE_PROMPT,source:m.EventSource.DESKTOP,content:n.content,metadata:n.metadata,...(0,m.raiseFieldsFromRecord)(s),timestamp:(0,m.prepareEventTimestamp)({orderingKey:e}),...n.isEncrypted?{isEncrypted:!0}:{}}))}async emitNextQueuedInteractivePrompt(){if(this.pendingInteractivePrompt||this.queuedInteractivePrompts.length===0)return;let t=this.queuedInteractivePrompts.shift();if(t){if(!this.isExpectedSessionStateCurrent(t.ownerState)){o.warn("Discarding queued prompt from stale session generation",{sessionId:t.ownerState.sessionId,currentSessionId:this.sessionState?.sessionId}),await this.emitNextQueuedInteractivePrompt();return}this.pendingInteractivePrompt=t.prompt;try{await this.emitInteractivePromptEvent(t),o.info("Emitted next queued interactive prompt",{callId:t.prompt.callId,queueLength:this.queuedInteractivePrompts.length})}catch(e){this.pendingInteractivePrompt=null,o.error("Failed to emit queued interactive prompt",{error:e}),await this.emitNextQueuedInteractivePrompt()}}}async clearResolvedInteractivePrompt(t,e){if(!e){o.debug("Interactive prompt completion had no comparable dialog identity",{callId:t});return}let i=this.pendingInteractivePrompt,s=i?.dedupeKey===e,r=this.sessionState?.sessionId??i?.ownerSessionId,n=new Set;if(s&&i&&n.add(i.promptId),r){let u=this.e1ContentKeyIndex.get(`${r}::${e}`);u&&n.add(u)}for(let[u,f]of this.e1PromptRaises.entries())f.record.sessionId===r&&f.resolutionDedupeKey===e&&n.add(u);let a=this.permissionRequestHookInFlight,l=a?.ownerState.sessionId===r&&a?.dedupeKey===e,p=!!r&&this.queuedPermissionRequestDedupeKeys.has(`${r}::${e}`);(s||l||p||n.size>0)&&this.rememberResolvedApprovalDedupeKey(r,e),s&&i&&(this.pendingInteractivePrompt=null);for(let u of this.removeQueuedInteractivePromptByDedupeKey(e))n.add(u);let d=r?this.beginE1PromptResolutions(n,r):[];this.launchE1Resolutions(d),s&&await this.emitNextQueuedInteractivePrompt()}removeQueuedInteractivePromptByDedupeKey(t){let e=this.queuedInteractivePrompts.length,i=this.queuedInteractivePrompts.filter(s=>s.prompt.dedupeKey===t);for(let s of i)this.rememberResolvedApprovalDedupeKey(s.ownerState.sessionId,s.prompt.dedupeKey);return this.queuedInteractivePrompts=this.queuedInteractivePrompts.filter(s=>s.prompt.dedupeKey!==t),this.queuedInteractivePrompts.length!==e&&o.debug("Removed resolved deduped tool call from interactive prompt queue",{dedupeKey:t,removed:e-this.queuedInteractivePrompts.length}),i.map(s=>s.prompt.promptId)}mergeCallIdIntoPromptByDedupeKey(t,e,i){let s=this.pendingInteractivePrompt;if(s?.ownerSessionId===t&&s.dedupeKey===e&&!s.callId){s.callId=i;let n=this.e1PromptRaises.get(s.promptId);n&&(n.resolutionCallId??=i),o.debug("Merged callId into active deduped interactive prompt",{source:s.source,callId:i,dedupeKey:e});return}let r=this.queuedInteractivePrompts.find(n=>n.prompt.ownerSessionId===t&&n.prompt.dedupeKey===e&&!n.prompt.callId);r&&(r.prompt.callId=i,o.debug("Merged callId into queued deduped interactive prompt",{source:r.prompt.source,callId:i,dedupeKey:e}))}isSameInteractivePrompt(t,e){return t.ownerSessionId!==e.ownerSessionId||Date.now()-t.createdAt>Jt?!1:t.callId&&e.callId?t.callId===e.callId:t.dedupeKey&&e.dedupeKey?t.dedupeKey===e.dedupeKey:t.kind===e.kind&&this.normalizePromptDedupeText(t.promptText)===this.normalizePromptDedupeText(e.promptText)}normalizePromptDedupeText(t){return t.replace(/\s+/g," ").trim().toLowerCase()}async startTmuxObserver(){let t=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!t)return o.debug("Skipping tmux pane observer start - no tmux session in environment"),!0;try{return await this.tmuxPaneObserver.start(t),!0}catch(e){return o.warn("Failed to start tmux pane observer",{tmuxSession:t,error:e}),!1}}async startTmuxObserverWithBeacon(t){try{await this.startTmuxObserver()?await b("daemon_init_step_completed",{step:"tmux_observer_start",path:t}):await b("daemon_init_step_failed",{step:"tmux_observer_start",path:t,error_class:"TmuxObserverStartFailed",error_message:"tmuxPaneObserver.start threw (see plugin log)"})}catch(e){await b("daemon_init_step_failed",{step:"tmux_observer_start",path:t,error_class:e?.name||"Error",error_message:e?.message||String(e)}),o.error("Failed to start tmux observer:",e)}}async tryParseInteractivePromptFromTmux(){try{let t=await this.tmuxPaneObserver.captureSnapshot(),e=this.tmuxPaneObserver.extractActiveApprovalBlock(t),i=e?(0,k.parseInteractivePrompt)(e):null;return o.debug("tmux prompt parse result",{parsed:!!i,kind:i?.kind,promptText:i?.promptText,isolated:!!e,snapshotPreview:this.summarizePromptSnapshot(e??t)}),{parsedPrompt:i,snapshot:e??t}}catch(t){return o.debug("tmux prompt parsing unavailable",{error:t}),null}}async tryParsePermissionRequestPromptFromTmux(t,e){let r=null;for(let n=0;n<25;n+=1){if(e&&!e()||n>0&&(await new Promise(l=>setTimeout(l,125)),e&&!e()))return null;let a=await this.tryParseInteractivePromptFromTmux();if(a&&(r=a),a?.parsedPrompt&&(!t||t(a.parsedPrompt,a.snapshot)))return a;a?.parsedPrompt&&o.warn("Ignoring parsed PermissionRequest prompt because it does not match the active tool",{attempt:n+1,promptText:a.parsedPrompt.promptText})}return r?.snapshot?{parsedPrompt:null,snapshot:r.snapshot}: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}}buildCodexPromptPresentation(t,e,i){let s=this.buildPromptPresentation(t),r=nt(s.options,e,i);if(!r)return null;let n=this.buildSubmitMapFromCodexOptionHotkeys(r);return n?{...s,options:r,submitMap:n,instructions:this.buildCodexPermissionInstructions(r),requiresFollowUpText:this.optionsRequireFollowUpText(r)}:null}buildSubmitMapFromCodexOptionHotkeys(t){let e={};for(let i of t){let s=i.text.match(/\(([^)]+)\)\s*$/)?.[1]?.trim().toLowerCase();if(!s||!Zt.test(s))return null;s==="esc"||s==="escape"?e[i.number]=H:e[i.number]=s}return e}buildCodexPermissionInstructions(t){let e=t.find(n=>/\((?:y|yes)\)\s*$/i.test(n.text)),i=t.find(n=>/\(p\)\s*$/i.test(n.text)),s=t.find(n=>/\((?:esc|escape)\)\s*$/i.test(n.text)),r=[];return e&&r.push(`${e.number} to approve`),i&&r.push(`${i.number} to persist the desktop allow rule`),s&&r.push(`${s.number} followed by what to change`),r.length>0?`Reply with ${r.join(", ")}`:"Reply with the number of the option you want"}optionsRequireFollowUpText(t){return t.some(e=>/what to (?:do differently|change)|instructions/i.test(e.text))}getMostRecentPendingToolCall(){let t=this.approvalDetector.getPendingCalls();return t.length===0?null:t.reduce((e,i)=>i.timestamp>e.timestamp?i:e)}hasActiveOrQueuedPermissionHookPrompt(t,e){let i=this.pendingInteractivePrompt;return i?.ownerSessionId===t&&i.source==="permission_hook"&&i.dedupeKey===e?!0:this.queuedInteractivePrompts.some(s=>s.prompt.ownerSessionId===t&&s.prompt.source==="permission_hook"&&s.prompt.dedupeKey===e)}hasMatchingPermissionHookPrompt(t,e){let i=this.buildObserverPromptMatchKey(t);return[this.pendingInteractivePrompt,...this.queuedInteractivePrompts.map(r=>r.prompt)].some(r=>r?.source==="permission_hook"&&r.ownerSessionId===e&&r.observerMatchKey===i)}buildObserverPromptMatchKey(t){let e=t.options.map(s=>`${s.number}:${this.normalizeObserverPromptText(s.text)}`).join("|"),i=[t.kind,this.normalizeObserverPromptText(t.promptText),e].join("::");return`observer:${oe.createHash("sha256").update(i).digest("hex").slice(0,16)}`}normalizeObserverPromptText(t){return t.replace(/\r\n?/g,`
|
|
24
|
+
`).split(`
|
|
25
|
+
`).map(e=>e.replace(/[ \t]+$/g,"")).join(`
|
|
26
|
+
`).trim()}hasRecentlyResolvedApprovalDedupeKey(t,e){return t?(this.pruneResolvedApprovalDedupeKeys(),this.resolvedApprovalDedupeKeys.has(`${t}::${e}`)):!1}rememberResolvedApprovalDedupeKey(t,e){!t||!e||(this.pruneResolvedApprovalDedupeKeys(),this.resolvedApprovalDedupeKeys.set(`${t}::${e}`,Date.now()))}pruneResolvedApprovalDedupeKeys(){let t=Date.now()-Qt;for(let[e,i]of this.resolvedApprovalDedupeKeys.entries())i<t&&this.resolvedApprovalDedupeKeys.delete(e)}buildApprovalDedupeKey(t){let e=t.toolName||"Tool",i=this.firstString(t.toolInput?.command,t.toolInput?.cmd,t.rawInput);if(i)return`command:${this.hashDedupeValue(`${this.mapToolNameForApproval(e)||e}:${i}`)}`;let s=this.firstString(t.filePath,t.toolInput?.file_path,t.toolInput?.path,t.toolInput?.filePath);if(s)return`file:${this.hashDedupeValue(`${e}:${s}`)}`;let r=this.firstString(t.hint);if(r)return`hint:${this.hashDedupeValue(`${e}:${r}`)}`}hashDedupeValue(t){return oe.createHash("sha256").update(t).digest("hex").slice(0,16)}buildPermissionPromptId(t,e,i,s){let r=typeof t.turn_id=="string"&&t.turn_id.trim().length>0?t.turn_id.trim():void 0,n=oe.createHash("sha256").update(`${e}:${s||this.stringifyToolInput(i)}`).digest("hex").slice(0,12);return`permission-${r||"turn"}-${n}`}buildPermissionRequestHint(t,e,i){let s=this.extractFilePathFromToolInput(t,e,i);if(this.mapToolNameForApproval(t)==="Edit"&&s)return`File: ${s}`;let r=this.firstString(e?.command,e?.cmd);return r?`Command: ${this.truncateApprovalDetail(r,80)}`:s?`File: ${s}`:`Tool: ${this.mapToolNameForApproval(t)||t}`}extractFilePathFromToolInput(t,e,i){let s=this.firstString(e?.file_path,e?.path,e?.filePath);if(s)return s;if(t==="apply_patch"){let n=this.firstString(e?.command,e?.cmd,i)?.match(/\*\*\* (?:Update|Add|Delete) File: ([^\r\n]+)/);if(n)return n[1].trim()}}stringifyToolInput(t){if(t!=null){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}}buildApprovalPromptContextFromPendingCall(t){let e=this.firstString(t.parsedInput?.command,t.parsedInput?.cmd),i=q(t.input),s=J(e)||q(e),n=(t.name==="apply_patch"?t.input:"")||i||s,a=!!n,l=a?"apply_patch":t.name,p=a?n:t.input,d=a?t.parsedInput||{command:n}:t.parsedInput,u=a?this.extractFilePathFromToolInput(l,d,p):t.filePath;return{toolName:l,filePath:u,diff:a?p:t.diff,toolInput:d,rawInput:p,hint:u?`File: ${u}`:`Tool: ${this.mapToolNameForApproval(l)||l}`}}buildApprovalPromptContextFromParsedPrompt(t){let e=this.extractShellCommandFromPromptText(t.promptText);if(e)return{toolName:"Bash",toolInput:{command:e},rawInput:e,hint:`Command: ${this.truncateApprovalDetail(e,80)}`};let i=t.promptText.match(/^(?:Destination|File):\s*([^\r\n]+)$/mi)?.[1]?.trim();return i?{toolName:"apply_patch",filePath:i,toolInput:{file_path:i},hint:`File: ${i}`}:null}parsedPromptMatchesApprovalContext(t,e){let i=this.buildApprovalPromptContextFromParsedPrompt(t),s=this.mapToolNameForApproval(e.toolName)==="Bash"?this.firstString(e.toolInput?.command,e.toolInput?.cmd):void 0;if(s){if(this.mapToolNameForApproval(i?.toolName)!=="Bash")return!1;let n=be(t.promptText);return!n||n.length===0?!1:rt(n,s)}let r=this.firstString(e.filePath,e.toolInput?.file_path,e.toolInput?.path,e.toolInput?.filePath);return r?i?.toolName!=="apply_patch"||!i.filePath?!1:M.normalize(i.filePath)===M.normalize(r):!1}extractShellCommandFromPromptText(t){return st(t)}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"}buildApprovalPromptContent(t,e){let i=t.trim(),s=i==="Codex is waiting for approval.",r=/^\$\s+/.test(i),n=e.toolName?`${e.toolName} requires approval.`:"Codex is waiting for approval.",a=[s||r||!i?n:i],l=typeof e.toolInput?.command=="string"?e.toolInput.command.trim():void 0;if(l&&!a.join(`
|
|
20
27
|
`).includes(l))return a.push("Command:",this.truncateApprovalDetail(l,240)),a.join(`
|
|
21
|
-
`);let
|
|
22
|
-
`).includes(
|
|
28
|
+
`);let p=e.filePath||e.toolInput?.file_path;return typeof p=="string"&&p.length>0&&!a.join(`
|
|
29
|
+
`).includes(p)?(a.push(`File: ${p}`),a.join(`
|
|
23
30
|
`)):(e.hint&&!a.join(`
|
|
24
31
|
`).includes(e.hint)&&a.push(e.hint),a.join(`
|
|
25
32
|
`))}truncateApprovalDetail(t,e){return t.length>e?`${t.slice(0,e-3)}...`:t}summarizePromptSnapshot(t){return t.split(`
|
|
26
33
|
`).map(e=>e.trimEnd()).filter(e=>e.length>0).slice(-12).map(e=>e.slice(0,160)).join(`
|
|
27
|
-
`)}translatePromptResponse(t
|
|
28
|
-
`)){let
|
|
34
|
+
`)}translatePromptResponse(t,e=this.pendingInteractivePrompt){if(!e)return{primaryInput:t};let s=t.trim().match(/^(\d+)(?:[,.:;\-\s]+([\s\S]+))?$/);if(!s)return{primaryInput:t};let r=s[1],n=s[2]?.trim(),a=e.submitMap[r];return a?e.requiresFollowUpText&&n?{primaryInput:a,followUpInput:n}:{primaryInput:a}:{primaryInput:t}}getEventPromptId(t){let e=t.promptId;return typeof e=="string"&&e.trim().length>0?e.trim():null}isApprovalResponseLike(t){let e=t.trim().toLowerCase();return/^(?:\d+|y|yes|n|no)(?:[\s,.:;-].*)?$/.test(e)}async emitRejectedPromptResponseNotification(t,e,i){if(!this.isExpectedSessionStateCurrent(i))return;let s=i.sessionId,r="Response ignored because it was not tied to the current prompt. Please reply to the latest prompt again.",n={prompt_response_rejected:!0,reason:t,eventId:e.eventId,eventPromptId:this.getEventPromptId(e),activePromptId:this.pendingInteractivePrompt?.promptId},a=this.encryptForEmit(r,n,m.EventType.NOTIFICATION,s);if(a)try{await this.appSyncClient.createEvent({sessionId:s,type:m.EventType.NOTIFICATION,source:m.EventSource.DESKTOP,content:a.content,metadata:a.metadata,timestamp:(0,m.prepareEventTimestamp)({orderingKey:s}),...a.isEncrypted?{isEncrypted:!0}:{}})}catch(l){o.warn("Failed to emit rejected prompt response notification",{reason:t,error:l})}}buildToolDetailsForInteractivePrompt(t,e){let i=t.toolName,s=t.toolInput&&typeof t.toolInput=="object"?t.toolInput:void 0;if(i==="apply_patch"){let n=t.diff||t.rawInput;if(n){let{oldString:a,newString:l,oldStartLine:p,newStartLine:d}=this.extractOldNewFromPatch(n),u=e?this.extractDiffLineAnchorsFromSnapshot(e):{};return{tool_name:"Edit",tool_input:{file_path:t.filePath,content:n,diff:t.diff,raw_patch:t.rawInput,old_string:a,new_string:l,old_start_line:p??u.oldStartLine,new_start_line:d??u.newStartLine}}}}if(this.mapToolNameForApproval(i)==="Bash"){let n=this.firstString(s?.command,s?.cmd,t.rawInput,t.hint);if(n)return{tool_name:"Bash",tool_input:{command:n,output:s?.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}:{}}firstString(...t){for(let e of t)if(typeof e=="string"&&e.trim().length>0)return e}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?{exec_command:"Bash",exec:"Bash",local_shell:"Bash",Bash:"Bash",apply_patch:"Edit",shell_command:"Bash",shell:"Bash",Edit:"Edit",Write:"Write"}[t]||t:void 0}extractOldNewFromPatch(t){let e=[],i=[],s=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/,r=0,n=0,a=0,l,p;for(let d of t.split(`
|
|
35
|
+
`)){let u=d.match(s);if(u){r+=1,n=Number.parseInt(u[1],10),a=Number.parseInt(u[2],10);continue}if(!(d.startsWith("***")||d.startsWith("---")||d.startsWith("+++")||d.startsWith("*** End Patch"))){if(d.startsWith("-"))l===void 0&&(l=n),e.push(d.slice(1)),n+=1;else if(d.startsWith("+"))p===void 0&&(p=a),i.push(d.slice(1)),a+=1;else if(d.startsWith(" ")){let f=d.slice(1);e.push(f),i.push(f),n+=1,a+=1}}}return{oldString:e.join(`
|
|
29
36
|
`),newString:i.join(`
|
|
30
|
-
`),oldStartLine:r===1?l:void 0,newStartLine:r===1?
|
|
31
|
-
`)){let
|
|
32
|
-
`);
|
|
37
|
+
`),oldStartLine:r===1?l:void 0,newStartLine:r===1?p:void 0}}extractDiffLineAnchorsFromSnapshot(t){let e=(0,k.normalizeSnapshot)(t),i,s;for(let r of e.split(`
|
|
38
|
+
`)){let n=r.match(/^\s*(\d+)\s+(.*)$/);if(!n)continue;let a=Number.parseInt(n[1],10),l=n[2];if(Number.isFinite(a)){if(l.startsWith("-")){i??=a;continue}if(l.startsWith("+")){s??=a;continue}i??=a,s??=a}}return o.debug("Recovered diff line anchors from tmux snapshot",{oldStartLine:i,newStartLine:s,snapshotPreview:this.summarizePromptSnapshot(t)}),{oldStartLine:i,newStartLine:s}}subscribeToMobileEvents(t){let e=this.sessionState;if(!e||e.sessionId!==t)return o.warn("Refusing mobile subscription without matching session generation",{sessionId:t,currentSessionId:e?.sessionId}),!1;if(this.subscribedSessionId===t&&this.subscribedSessionState===e)return o.info("Already subscribed to mobile events, skipping",{sessionId:t}),!0;if(o.info("Subscribing to mobile events",{sessionId:t}),this.unsubscribe){try{this.unsubscribe()}catch(i){o.warn("Error cleaning up previous subscription (non-fatal)",{error:i})}this.subscribedSessionId=null,this.subscribedSessionState=null}try{this.unsubscribe=this.appSyncClient.subscribeToEvents(t,async i=>{await this.handleMobileEvent(i,e)},i=>{o.error("Subscription error:",i)},{onSessionRetired:()=>this.recoverRetiredBackendSession(t)}),this.subscribedSessionId=t,this.subscribedSessionState=e}catch(i){return o.error("Failed to subscribe to mobile events (non-fatal)",{sessionId:t,error:i}),!1}return this.isExpectedSessionStateCurrent(e)&&(e.subscriptionActive=!0),o.info("Subscribed to mobile events"),!0}async ensureOrchestrationClient(t){let{OrchestrationClient:e}=await import("@quantiya/quorum-core"),i=await m.keychainManager.getTokens((0,m.getEnvironment)());if(!i?.idToken)throw new Error("No Cognito ID token available \u2014 plugin must be logged in");let s=(0,m.getConfig)(),r=this.sessionKey??Buffer.alloc(32).toString("base64"),n=require("ws");return await e.connect({appsyncUrl:s.aws.appsyncUrl,cognitoIdToken:i.idToken,tokenProvider:async()=>(await m.keychainManager.getTokens((0,m.getEnvironment)()))?.idToken??i.idToken,sessionId:t,sessionKeyB64:r,webSocketFactory:((l,p)=>new n(l,p))})}async subscribeToOnApplyUserDecision(t){if(this.userDecisionUnsubscribe){try{this.userDecisionUnsubscribe()}catch(e){o.warn("Error invoking previous onApplyUserDecision unsubscribe (non-fatal)",{error:e})}this.userDecisionUnsubscribe=null}if(this.orchestrationClient){try{await this.orchestrationClient.destroy()}catch(e){o.warn("Error destroying previous OrchestrationClient (non-fatal)",{error:e})}this.orchestrationClient=null}try{let e=await this.ensureOrchestrationClient(t);this.orchestrationClient=e;let i=await e.onApplyUserDecision(s=>{this.handleApplyUserDecisionEvent(s)});return this.userDecisionUnsubscribe=i,o.info("[v1-bridge] Subscribed to onApplyUserDecision via OrchestrationClient",{sessionId:t}),!0}catch(e){if(o.error("Failed to subscribe to onApplyUserDecision (non-fatal)",{sessionId:t,error:e}),this.orchestrationClient){try{await this.orchestrationClient.destroy()}catch{}this.orchestrationClient=null}return!1}}handleApplyUserDecisionEvent(t){let{gateId:e,decision:i,sessionId:s,taskId:r}=t;if(this.v1Bridge.dispatch(t)==="self_echo"){o.debug("[v1-bridge] Self-origin decision echo absorbed",{gateId:e,decision:i,sessionId:s,taskId:r});return}o.info("[v1-bridge] cross-device decision recorded",{gateId:e,decision:i,sessionId:s,taskId:r});let a=String(i).toUpperCase();this.emitOrchestrationBanner(a)}async emitOrchestrationBanner(t){let e=process.env[j];if(!e){o.warn("[v1-bridge] No tmux session set; cannot emit cross-device banner",{expectedEnv:j});return}let s=Ze(t).replace(/"/g,'\\"'),r=`tmux display-message -d 8000 -t "${e}" "${s}"`;try{await it(r),o.info("[v1-bridge] Cross-device decision banner emitted",{decision:t})}catch(n){o.warn("[v1-bridge] tmux display-message failed (non-fatal)",{error:n instanceof Error?n.message:String(n)})}}async originateUserDecision(t){this.v1Bridge.markOriginated(t.gateId);let e=this.sessionState?.sessionId;if(!e)throw this.v1Bridge.clearOriginated(t.gateId),new Error("No active session \u2014 cannot originate user decision");let i=this.orchestrationClient,s=!1;i||(i=await this.ensureOrchestrationClient(e),s=!0);try{await i.applyUserDecision(t),o.info("[v1-bridge] originated user decision",{gateId:t.gateId,decision:t.decision,sessionId:e})}catch(r){throw this.v1Bridge.clearOriginated(t.gateId),o.error("[v1-bridge] applyUserDecision failed (rolled back originator marker)",{gateId:t.gateId,decision:t.decision,error:r instanceof Error?r.message:String(r)}),r}finally{if(s&&i)try{await i.destroy()}catch{}}}_v1BridgeStateForTest(){return this.v1Bridge}_v1BridgeHandleEventForTest(t){this.handleApplyUserDecisionEvent(t)}async downloadAttachment(t,e,i,s){try{let r=t.isEncrypted??s??!1;o.info("Downloading attachment",{id:t.id,type:t.type,filename:t.filename,s3Key:t.s3Key,attachmentIsEncrypted:t.isEncrypted,eventIsEncrypted:s,shouldDecrypt:r});let{downloadUrl:n}=await this.appSyncClient.getAttachmentDownloadUrl(t.s3Key),a=await fetch(n);if(!a.ok)throw new Error(`Failed to download attachment: ${a.status} ${a.statusText}`);let l=Buffer.from(await a.arrayBuffer());if(r&&i)try{o.info("Decrypting attachment",{id:t.id}),l=m.cryptoService.decryptData(l,i),o.info("Attachment decrypted successfully",{id:t.id,decryptedSize:l.length})}catch(v){throw o.error("Failed to decrypt attachment:",{id:t.id,error:v}),new Error("Failed to decrypt attachment")}else if(r&&!i)return o.warn("Cannot decrypt attachment - no session key available",{id:t.id}),null;let p=M.join(tt.tmpdir(),"codevibe-codex",e);K.existsSync(p)||K.mkdirSync(p,{recursive:!0});let d="";if(t.filename){let v=M.extname(t.filename);v&&(d=v)}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}`,f=M.join(p,u);return K.writeFileSync(f,l),o.info("Attachment saved to temp file",{id:t.id,filePath:f,size:l.length}),f}catch(r){return o.error("Failed to download attachment:",{id:t.id,error:r}),null}}async handleMobileEvent(t,e=this.sessionState){if(t.attachments&&t.attachments.length>0&&o.info("DEBUG: Raw attachment data from subscription",{attachments:JSON.stringify(t.attachments),eventIsEncrypted:t.isEncrypted}),o.info("Received mobile event",{eventId:t.eventId,type:t.type,content:t.content?.substring(0,50),attachmentCount:t.attachments?.length||0,isEncrypted:t.isEncrypted}),!e||!this.isExpectedSessionStateCurrent(e)||t.sessionId!==e.sessionId){o.warn("Dropping mobile event for stale or mismatched session generation",{eventSessionId:t.sessionId,expectedSessionId:e?.sessionId,currentSessionId:this.sessionState?.sessionId});return}let i=e.sessionId,{sessionKey:s}=e.encryptionSnapshot,r=t.content||"";if(t.isEncrypted){if(!s){o.error("Dropping encrypted mobile event without its session-pinned key",{eventId:t.eventId,sessionId:i});return}try{r=m.cryptoService.decryptContent(t.content,s),o.debug("Event decrypted successfully",{eventId:t.eventId})}catch(a){o.error("Failed to decrypt event:",{eventId:t.eventId,error:a});return}}let n=this.pendingInteractivePrompt;try{await this.appSyncClient.updateEventStatus({eventId:t.eventId,sessionId:t.sessionId,timestamp:t.timestamp,deliveryStatus:m.DeliveryStatus.DELIVERED})}catch(a){o.error("Failed to update delivery status:",a)}if(this.isExpectedSessionStateCurrent(e)&&(t.type===m.EventType.USER_PROMPT||t.type===m.EventType.PROMPT_RESPONSE)){let a=r,l=t.attachments||[],p=t.type===m.EventType.PROMPT_RESPONSE,d=null;if(t.type===m.EventType.PROMPT_RESPONSE){let h=this.getEventPromptId(t),y=n,S=y?.promptId;if(!h||!S||h!==S){o.warn("Rejecting stale or unbound PROMPT_RESPONSE",{eventId:t.eventId,eventPromptId:h,activePromptId:S}),await this.emitRejectedPromptResponseNotification("prompt_id_mismatch",t,e);return}d=y}else n&&this.isApprovalResponseLike(a)&&(p=!0,d=n,o.info("Treating approval-shaped USER_PROMPT as active prompt response",{eventId:t.eventId,activePromptId:n.promptId,promptPreview:a.slice(0,20)}));let u=[];if(l.length>0){o.info("Downloading attachments for prompt",{count:l.length});for(let h of l){let y=await this.downloadAttachment(h,i,s,t.isEncrypted);if(!this.isExpectedSessionStateCurrent(e))return;y&&u.push(y)}if(u.length>0){let h=u.map(y=>`[Attached file: ${y}]`).join(`
|
|
39
|
+
`);a?a=`${h}
|
|
33
40
|
|
|
34
|
-
${
|
|
41
|
+
${a}`:a=`${h}
|
|
35
42
|
|
|
36
|
-
Please analyze the attached file(s).`,
|
|
43
|
+
Please analyze the attached file(s).`,o.info("Prompt updated with attachment paths",{attachmentCount:u.length,newPromptLength:a.length})}}if(p&&this.pendingInteractivePrompt!==d){o.info("Ignoring mobile prompt response already settled by a concurrent completion",{eventId:t.eventId,boundPromptId:d?.promptId,activePromptId:this.pendingInteractivePrompt?.promptId});return}let f=this.translatePromptResponse(a,d);if(!this.isExpectedSessionStateCurrent(e)||(f.primaryInput!==H&&this.trackMobilePrompt(i,f.primaryInput),!this.isExpectedSessionStateCurrent(e)))return;let v=await this.sendSessionPinnedInput(e,f.primaryInput);if(!this.isExpectedSessionStateCurrent(e))return;if(!v&&f.primaryInput!==H&&this.forgetMobilePrompt(i,f.primaryInput),v&&f.followUpInput){if(this.trackMobilePrompt(i,f.followUpInput),!this.isExpectedSessionStateCurrent(e))return;let h=await this.sendSessionPinnedInput(e,f.followUpInput);if(!this.isExpectedSessionStateCurrent(e))return;h||this.forgetMobilePrompt(i,f.followUpInput)}if(v&&p&&d&&this.pendingInteractivePrompt===d){let h=d;this.rememberResolvedApprovalDedupeKey(e.sessionId,h.dedupeKey),this.pendingInteractivePrompt=null;let y=this.beginE1PromptResolutions([h.promptId],e.sessionId);if(this.launchE1Resolutions(y),!this.isExpectedSessionStateCurrent(e)||(await this.emitNextQueuedInteractivePrompt(),!this.isExpectedSessionStateCurrent(e)))return}if(v){if(!this.isExpectedSessionStateCurrent(e))return;try{await this.appSyncClient.updateEventStatus({eventId:t.eventId,sessionId:t.sessionId,timestamp:t.timestamp,deliveryStatus:m.DeliveryStatus.EXECUTED})}catch(h){o.error("Failed to update executed status:",h)}}}}buildToolActivityIntegration(){return new z({logger:o,createEvent:t=>this.appSyncClient.createEvent(t),encryptContent:(t,e)=>m.cryptoService.encryptContent(t,e),encryptMetadata:(t,e)=>m.cryptoService.encryptMetadata(t,e),getSessionKey:()=>this.sessionKey,getSessionKeyGen:()=>this.sessionKeyGen,refreshSessionKey:t=>this.refreshToolActivitySessionKey(t)})}async refreshToolActivitySessionKey(t){try{let e=await this.appSyncClient.getSession(t);if(!e||!e.isEncrypted)return null;let i=e.sessionKeyGen??null,s=e.encryptedKeys??[];if(s.length===0)return null;let r=await m.keychainManager.getSessionKey(t,s,i);return r?(o.info("[tool-activity] refreshed session key for SessionKeyStale retry (live key untouched)",{sessionId:t,sessionKeyGen:i}),{sessionKey:r,sessionKeyGen:i}):null}catch(e){return o.warn("[tool-activity] session key refresh failed after SessionKeyStale (staying retryable)",{sessionId:t,error:String(e)}),null}}getToolActivityLegacyRecorder(t){let e=this.toolActivityLegacyRecorders.get(t);return e||(e=new m.ToolActivityLedger({agent:"codex",sessionId:t,logger:o}),this.toolActivityLegacyRecorders.set(t,e)),e}async ensureToolActivityStarted(t){if(!this.sessionState||!t)return;let e=this.sessionWatcher.getActiveLogFile()||this.sessionState.codexLogFile||void 0,i=this.toolActivity;if(i){e&&i.bindTranscript(e);return}if(this.toolActivityStartPromise){await this.toolActivityStartPromise,e&&this.toolActivity?.bindTranscript(e);return}if(!this.sessionKey)return;let s=this.sessionState.sessionId;this.toolActivityStartPromise=(async()=>{let r=this.buildToolActivityIntegration();try{await r.start(s,t,e),this.toolActivity=r}catch(n){throw await r.stop().catch(()=>{}),this.toolActivityStartPromise=null,n}})().catch(r=>{o.warn("[tool-activity] failed to start codex consolidator (non-fatal)",{backendSessionId:s,rolloutId:t,error:String(r)})}),await this.toolActivityStartPromise}startMobileEndWatcher(t){!this.sessionState||this.sessionState.sessionId!==t||(this.sessionState.mobileEndWatcher=this.appSyncClient.watchForMobileEnd(t,async()=>{o.info("Mobile ended session \u2014 sending desktop quit",{sessionId:t}),this.appSyncClient.stopHeartbeat(t),this.appSyncClient.cleanupSubscription(t);try{await this.appSyncClient.updateSession({sessionId:t,status:m.SessionStatus.INACTIVE}),o.info("Marked session INACTIVE on mobile-end (before tmux terminate)",{sessionId:t})}catch(i){o.warn("Failed to mark session INACTIVE on mobile-end",{sessionId:t,error:i})}let e=process.env[j];if(!e){o.warn("No tmux session set; skipping desktop self-terminate",{sessionId:t,expectedEnv:j});return}await ei(e,Yt)}))}async endActiveSession(t){if(!this.sessionState)return;let e=this.sessionState;if(this.terminalInputBlockedStates.add(e),await this.terminalInputChain.catch(()=>{}),this.sessionState!==e){o.warn("Session changed while waiting for terminal-input teardown barrier",{endingSessionId:e.sessionId,currentSessionId:this.sessionState?.sessionId,reason:t});return}if(o.info("Ending active session",{sessionId:e.sessionId,codexSessionId:e.codexSessionId,reason:t}),this.sessionState.mobileEndWatcher&&(this.sessionState.mobileEndWatcher.stop(),this.sessionState.mobileEndWatcher=void 0),this.userDecisionUnsubscribe){try{this.userDecisionUnsubscribe()}catch(i){o.warn("Error invoking onApplyUserDecision unsubscribe (non-fatal)",{error:i})}this.userDecisionUnsubscribe=null}if(this.orchestrationClient){try{await this.orchestrationClient.destroy()}catch(i){o.warn("Error destroying OrchestrationClient (non-fatal)",{error:i})}this.orchestrationClient=null}this.v1Bridge.clear(),this.appSyncClient.stopHeartbeat(this.sessionState.sessionId),this.stopE1TtlRefresh(),this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null,this.subscribedSessionId=null,this.subscribedSessionState=null),await this.tmuxPaneObserver.stop(),this.pendingInteractivePrompt=null,this.queuedInteractivePrompts=[],this.isInitializingSession=!1,this.bufferedLogEntries=[],fe(),t==="shutdown"&&this.sessionWatcher.stop(),this.toolActivityStartPromise&&(await this.toolActivityStartPromise.catch(()=>{}),this.toolActivityStartPromise=null),await this.logEntryChain.catch(()=>{}),this.toolActivity&&(await this.toolActivity.stop(),this.toolActivity=null);for(let i of this.toolActivityLegacyRecorders.values())i.disposeLegacyCoordination();this.toolActivityLegacyRecorders.clear(),this.sessionKey&&(m.keychainManager.clearSessionKey(this.sessionState.sessionId),this.sessionKey=null,this.sessionKeyGen=null);try{await this.appSyncClient.updateSession({sessionId:this.sessionState.sessionId,status:m.SessionStatus.INACTIVE})}catch(i){o.error("Failed to update session status:",i)}this.sessionState=null}async stop(){o.info("Stopping CodeVibe Codex companion server"),this.stopTmuxLifecycleMonitor(),this.isStopping=!0,this.lifecycleGeneration+=1,this.sessionWatcher.stop();let t=this.launchSessionInitPromise,e=this.sessionStartedInitPromise,i=this.retiredSessionRecoveryPromise,s=this.hookEventChain,r=typeof this.sessionWatcher.waitForTranscriptAdmissions=="function"?this.sessionWatcher.waitForTranscriptAdmissions():Promise.resolve();await Promise.all([t?.catch(()=>{}),e?.catch(()=>{}),i?.catch(()=>{}),r.catch(()=>{}),s.catch(()=>{})]);try{await this.endActiveSession("shutdown"),this.sessionWatcher.stop(),this.approvalDetector.shutdown(),fe()}finally{await this.httpApi.stop(),this.appSyncClient.cleanupSubscriptions()}o.info("CodeVibe Codex companion server stopped")}};if(require.main===module){let c=new ae;process.on("SIGINT",async()=>{o.info("Received SIGINT, shutting down..."),await c.stop(),process.exit(0)}),process.on("SIGTERM",async()=>{o.info("Received SIGTERM, shutting down..."),await c.stop(),process.exit(0)}),(0,m.installDaemonProcessGuards)(o,{onFatal:()=>{c.stop().finally(()=>process.exit(1))}}),c.start().catch(t=>{o.error("Failed to start server:",t),process.exit(1)})}0&&(module.exports={CodexCompanionServer,extractShellCommandFromPromptText,extractShellCommandPartsFromPromptText,restoreCodexPersistOptionCommand,shellCommandPartsMatchExpected});
|