@quantiya/codevibe-codex-plugin 2.0.70 → 2.0.72
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 +64 -43
- package/node_modules/@quantiya/codevibe-core/dist/appsync/appsync-client.d.ts +7 -0
- package/node_modules/@quantiya/codevibe-core/dist/index.js +206 -206
- package/node_modules/@quantiya/codevibe-core/dist/orchestration-shell/cli.js +36 -11
- package/node_modules/@quantiya/codevibe-core/package.json +1 -1
- package/package.json +2 -2
package/dist/server.js
CHANGED
|
@@ -1,48 +1,69 @@
|
|
|
1
|
-
"use strict";var ei=Object.create;var he=Object.defineProperty;var ti=Object.getOwnPropertyDescriptor;var ii=Object.getOwnPropertyNames;var si=Object.getPrototypeOf,ri=Object.prototype.hasOwnProperty;var ni=(a,t)=>{for(var e in t)he(a,e,{get:t[e],enumerable:!0})},it=(a,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ii(t))!ri.call(a,s)&&s!==e&&he(a,s,{get:()=>t[s],enumerable:!(i=ti(t,s))||i.enumerable});return a};var T=(a,t,e)=>(e=a!=null?ei(si(a)):{},it(t||!a||!a.__esModule?he(e,"default",{value:a,enumerable:!0}):e,a)),oi=a=>it(he({},"__esModule",{value:!0}),a);var us={};ni(us,{CodexCompanionServer:()=>Ae,TERMINAL_SHUTDOWN_SIGNALS:()=>Gt,classifyTmuxHasSessionError:()=>jt,extractShellCommandFromPromptText:()=>Vt,extractShellCommandPartsFromPromptText:()=>et,restoreCodexPersistOptionCommand:()=>Xt,shellCommandPartsMatchExpected:()=>Yt});module.exports=oi(us);var se=require("uuid"),de=T(require("crypto")),Y=T(require("fs")),F=T(require("path")),Xe=T(require("os")),Qe=require("util"),Ne=require("child_process"),Ze=require("shell-quote"),h=require("@quantiya/codevibe-core");var st=T(require("os")),rt=T(require("path")),nt=require("@quantiya/codevibe-core"),l=(0,nt.createLogger)({name:"codevibe-codex",logFile:rt.default.join(st.default.tmpdir(),"codevibe-codex-mcp.log"),level:"debug"});var at=require("events"),R=T(require("fs")),L=T(require("path")),lt=require("string_decoder"),me=require("crypto"),ct=require("chokidar"),J=require("@quantiya/codevibe-core");var Me=256*1024,ai=64*1024*1024,li=16*1024*1024,ci=64*1024,ot=100,di=250,pi=["CHOKIDAR_USEPOLLING","CHOKIDAR_INTERVAL"];function ui(a,t){let e=pi.map(s=>[s,process.env[s]]);for(let[s]of e)delete process.env[s];let i;try{i=(0,ct.watch)(a,{...t,usePolling:!0})}finally{for(let[s,r]of e)r===void 0?delete process.env[s]:process.env[s]=r}if(i.options?.usePolling!==!0)throw i.close().catch(()=>{}),new Error("chokidar did not honour usePolling; refusing a native fs.watch");return i}function hi(a=process.env){let t=a.CODEX_HOME?.trim();return t?L.resolve(t,"sessions"):(0,J.getConfig)().codex.sessionsDir}var fe=class extends at.EventEmitter{constructor(e={}){super();this.watcher=null;this.catchUpReadTimer=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.ownedReads=new Set;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??ai,this.maxRecordBytes=e.maxRecordBytes??li,this.beforeEntry=e.beforeEntry,this.restoreCursor=e.restoreCursor,this.beforeGap=e.beforeGap,this.beforeEntry!==void 0&&typeof this.beforeEntry!="function")throw new TypeError("beforeEntry must be a function");if(this.restoreCursor!==void 0&&typeof this.restoreCursor!="function"||this.beforeGap!==void 0&&typeof this.beforeGap!="function"||this.restoreCursor&&(!this.beforeEntry||!this.beforeGap))throw new TypeError("durable source restore requires entry and gap admission callbacks");if(!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){l.warn("Session log watcher already running");return}this.transcriptBindGeneration++,this.transcriptBindingsClosed=!1;let e=hi();this.sessionsDir=e,l.info("Starting Codex session log watcher",{sessionsDir:e}),R.existsSync(e)||(l.info("Codex sessions directory does not exist yet, creating...",{sessionsDir:e}),R.mkdirSync(e,{recursive:!0})),this.startTime=Date.now(),this.readGeneration++,this.bindSource=null,this.authoritativeSessionId=null,this.snapshotStartBaselines(e),this.isWatching=!0,this.activeLogFile&&this.watchBoundRollout(this.activeLogFile),this.drainPendingTranscriptBind(),l.info("Session log watcher started; awaiting the SessionStart transcript bind")}stop(){this.transcriptBindingsClosed=!0,this.transcriptBindGeneration++,this.closeBoundRolloutWatch(),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(),l.info("Session log watcher stopped")}async waitForTranscriptAdmissions(){for(;this.activeTranscriptAdmissions.size>0;)await Promise.all(Array.from(this.activeTranscriptAdmissions,e=>e.then(()=>{},()=>{})))}async waitForReads(){await Promise.all([...this.ownedReads])}retryActiveRead(){this.isWatching&&this.activeLogFile&&this.scheduleReadNewLines(this.activeLogFile)}getSessionId(){return this.sessionId}getActiveLogFile(){return this.activeLogFile}getBindSource(){return this.bindSource}getAuthoritativeSessionId(){return this.authoritativeSessionId}tryRealpath(e){try{return R.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=R.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(R.statSync(e)))}catch{this.fileIdentities.delete(e)}this.watchBoundRollout(e),this.scheduleReadNewLines(e)}watchBoundRollout(e){if(this.closeBoundRolloutWatch(),!this.isWatching||this.transcriptBindingsClosed)return;let i;try{i=ui(e,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:ot,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}})}catch(s){l.error("Could not follow bound rollout by polling",{filePath:e,error:s instanceof Error?s.message:String(s)}),this.emit("error",s);return}this.watcher=i,i.on("add",s=>this.onFileAdded(s)),i.on("change",s=>this.onFileChanged(s)),i.on("error",s=>{l.error("Watcher error:",s),this.emit("error",s)}),i.on("ready",()=>{this.watcher===i&&(this.catchUpReadTimer=setTimeout(()=>{this.catchUpReadTimer=null,this.watcher===i&&this.activeLogFile===e&&this.scheduleReadNewLines(e)},di),this.catchUpReadTimer.unref?.())}),l.info("Following bound rollout",{filePath:e,pollIntervalMs:ot})}closeBoundRolloutWatch(){this.catchUpReadTimer&&(clearTimeout(this.catchUpReadTimer),this.catchUpReadTimer=null);let e=this.watcher;e&&(this.watcher=null,e.close().catch(i=>{l.warn("Bound rollout watcher close failed",{error:i instanceof Error?i.message:String(i)})}))}bindToFile(e){let i=this.tryRealpath(e);if(!i){l.warn("bindToFile: could not canonicalize path; skipping",{filePath:e});return}if(i===this.activeLogFile){this.bindSource="authoritative";return}l.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}:(l.warn("bindToSessionTranscript: conflicting startup bind rejected",{transcriptPath:e,expectedSessionId:i,pendingExpectedSessionId:s.expectedSessionId}),{status:"rejected",reason:"conflicting_startup_bind"});let r,n=new Promise(o=>{r=o});return this.pendingTranscriptBind={transcriptPath:e,expectedSessionId:i,completion:n,resolve:r},l.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),o=this.tryRealpath(r);if(!n||!o)return{status:"rejected",reason:"canonicalization_failed"};let c=L.relative(o,n);if(c===".."||c.startsWith(".."+L.sep)||L.isAbsolute(c))return l.warn("bindToSessionTranscript: path not under sessionsDir; rejecting",{transcriptPath:n}),{status:"rejected",reason:"outside_sessions_directory"};let d=L.basename(n);if(!d.startsWith("rollout-")||!d.endsWith(".jsonl"))return{status:"rejected",reason:"invalid_rollout_filename"};let p=null;for(let u=0;u<3;u++){if(!this.isTranscriptAdmissionCurrent(s,r))return{status:"rejected",reason:"watcher_stopped"};if(p=this.readSessionMeta(n),p)break;if(await new Promise(f=>setTimeout(f,20)),!this.isTranscriptAdmissionCurrent(s,r))return{status:"rejected",reason:"watcher_stopped"}}return!p||p.id!==i?(l.debug("bindToSessionTranscript: meta missing or id mismatch; not binding",{transcriptPath:n,metaId:p?.id,expectedSessionId:i}),{status:"rejected",reason:"session_metadata_mismatch"}):this.isInteractiveRollout(p)?this.isTranscriptAdmissionCurrent(s,r)?(this.bindToFile(n),this.authoritativeSessionId=i,{status:"bound"}):{status:"rejected",reason:"watcher_stopped"}:(l.debug("bindToSessionTranscript: non-interactive rollout (codex_exec/subagent); not binding",{transcriptPath:n,originator:p.originator,threadSource:p.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){l.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):l.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=R.openSync(e,"r");let s=new lt.StringDecoder("utf8"),r=Buffer.alloc(64*1024),n="",o=0,c=-1;for(;o<Me;){let p=R.readSync(i,r,0,r.length,o);if(p<=0||(o+=p,n+=s.write(r.subarray(0,p)),c=n.indexOf(`
|
|
2
|
-
`),
|
|
3
|
-
`).digest("hex"),anchor:Object.freeze(this.framedSourceAnchor(
|
|
4
|
-
`).digest("hex")}}readSourceAnchor(
|
|
5
|
-
`).trim()}function
|
|
6
|
-
`)||!
|
|
7
|
-
*** End Patch`))return"";let
|
|
8
|
-
`);return
|
|
9
|
-
${
|
|
10
|
-
${
|
|
11
|
-
`))if(!(i.test(s)||s.startsWith("***")||s.startsWith("---")||s.startsWith("+++"))){if(s.startsWith("-"))
|
|
12
|
-
`),newString:
|
|
13
|
-
`)}}function
|
|
14
|
-
`);if(typeof a=="object"&&typeof a.text=="string")return a.text;try{return JSON.stringify(a)??""}catch{return String(a)}}function Ke(a,t){return typeof a!="string"?Ke(ge(a),t):a?a.length<=t?a:a.substring(0,t)+"...":""}function Ue(){H.clear(),Q()}var C=require("@quantiya/codevibe-core"),ft=3e3,Ii=8,bi=10,Ei=100;function gt(a){let t=Buffer.byteLength(a.carryover);return{status:"partial",progressKey:`${a.fileIdentity.dev}:${a.fileIdentity.ino}:${a.size}:${a.endOfComplete}:${t}`,size:a.size,carryoverBytes:t,endOfComplete:a.endOfComplete}}var Ri="tool_activity",ee=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 C.ToolActivitySessionMap.mintCodexBackendSessionId()}async recordedBackendSessionId(t){return new C.ToolActivitySessionMap({agent:"codex",logger:this.deps.logger,lock:new C.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,C.createRolloutLock)({agent:"codex",logger:this.deps.logger,socketDir:this.deps.socketDir,root:this.deps.root});this.sessionMap=new C.ToolActivitySessionMap({agent:"codex",logger:this.deps.logger,lock:s,root:this.deps.root}),this.ownership=await this.sessionMap.claimOwnership(e,t);let r=new C.ToolActivityOutbox({agent:"codex",logger:this.deps.logger,root:this.deps.root});this.ledger=new C.ToolActivityLedger({agent:"codex",sessionId:t,logger:this.deps.logger,root:this.deps.root}),await this.deps.recoverPending?.(t,r,this.ledger);let n=this.buildTransport(),o=this.deps.selectTransport?await this.deps.selectTransport(t,n):n;this.consolidator=new C.ToolActivityConsolidator({agent:"codex",sessionId:t,logger:this.deps.logger,outbox:r,ledger:this.ledger,transport:o}),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 C.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:Oi(t.toolName,t.toolInput),ts:t.ts??new Date().toISOString(),byteOffset:t.byteOffset??0,...t.toolInput!==void 0?{digest:(0,C.digestOf)(t.toolInput)}:{}},r=await i.observe(s,e);return r==="closed"?await i.captureTerminal(s,this.deps.shutdownDrainMs??ft)?"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<Ii;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?gt(r):"caught-up";let n=Number.POSITIVE_INFINITY,o=e?{includeInFlight:!0}:void 0;for(let c of r.frames)for(let d of _i(c.line,c.startOffset))await this.observeCall(d,o)==="deferred-in-flight"&&(n=Math.min(n,c.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?gt(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??Ei)),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,bi))}else e=null,i=0,await new Promise(r=>setImmediate(r))}await this.consolidator?.drainSends(this.deps.shutdownDrainMs??ft).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:C.EventType.TOOL_ACTIVITY,source:C.EventSource.DESKTOP,content:this.deps.encryptContent(Ri,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,C.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 _i(a,t){let e;try{e=JSON.parse(a)}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:Ti(i.name),toolInput:r,ts:s,byteOffset:t}]}if(i.type==="custom_tool_call"&&typeof i.call_id=="string"){let r=xi(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 Ti(a){return a==="shell"||a==="shell_command"||a==="local_shell"?"Bash":a==="apply_patch"?"Edit":a}function xi(a){let t=a.match(/^\*\*\* (?:Update|Add|Delete) File: (.+)$/m);return t?t[1].trim():void 0}function Oi(a,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 yt=require("events"),vt=require("@quantiya/codevibe-core");var ve=class a extends yt.EventEmitter{constructor(){super();this.pendingCalls=new Map;this.timers=new Map;this.timeoutMs=(0,vt.getConfig)().codex.approvalTimeoutMs,l.info("Approval detector initialized",{timeoutMs:this.timeoutMs})}onToolCallStart(e,i,s){l.debug("Tool call started",{callId:e,name:i});let r=this.parseInput(s),n=this.extractFilePath(i,s,r),o=this.extractDiff(i,s,r),c={callId:e,name:i,input:s,filePath:n,diff:o,parsedInput:r,timestamp:Date.now(),notificationSent:!1};if(this.pendingCalls.set(e,c),!this.shouldScheduleApprovalTimeout(i,r)){l.debug("Skipping approval timeout for non-escalated tool call",{callId:e,name:i});return}let d=setTimeout(()=>{this.checkPendingCall(e)},this.timeoutMs);this.timers.set(e,d)}onToolCallComplete(e){l.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;l.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(a.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 a.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(),l.debug("Approval detector cleared")}shutdown(){this.clear(),this.removeAllListeners(),l.info("Approval detector shutdown")}};var St=require("child_process"),Pt=require("util");var He=(0,Pt.promisify)(St.exec),te="__CODEVIBE_CODEX_KEY_ESCAPE__",Se=class{async sendLiteral(t,e){return this.sendTerminalOperation(t,async i=>{await this.sendLiteralViaTmux(i,e)})}async sendKey(t,e){return this.sendTerminalOperation(t,async i=>{await this.sendKeyViaTmux(i,e)})}async sendInput(t,e){l.info("Attempting to send input to Codex",{sessionId:t,input:e});try{let i=process.env.CODEVIBE_CODEX_TMUX_SESSION;return i?(l.info("Using tmux send-keys",{tmuxSession:i}),e===te?await this.sendKeyViaTmux(i,"Escape"):await this.sendViaTmux(i,e),l.info("Successfully sent input to Codex",{sessionId:t,input:e}),!0):(l.error("No tmux session found - CodeVibe Companion launch is required",{sessionId:t,hint:"Start Codex CLI using `codevibe --agent codex`"}),!1)}catch(i){return l.error("Failed to send input to Codex",{sessionId:t,error:i instanceof Error?i.message:String(i)}),!1}}async sendTerminalOperation(t,e){let i=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!i)return l.error("No tmux session found - CodeVibe Companion launch is required",{sessionId:t,hint:"Start Codex CLI using `codevibe --agent codex`"}),!1;try{return await e(i),!0}catch(s){return l.error("Failed to send terminal input to Codex",{sessionId:t,error:s instanceof Error?s.message:String(s)}),!1}}async sendViaTmux(t,e){l.info("Sending via tmux",{sessionName:t,inputLength:e.length});try{await this.sendLiteralViaTmux(t,e),await this.delay(500);let i=`tmux send-keys -t "${t}" Enter`;await He(i),l.info("tmux send-keys completed")}catch(i){throw l.error("tmux send-keys failed",{sessionName:t,error:i}),i}}async sendLiteralViaTmux(t,e){let i=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),s=`tmux send-keys -t "${t}" -l "${i}"`;await He(s)}async sendKeyViaTmux(t,e){l.info("Sending special key via tmux",{sessionName:t,key:e});try{let i=`tmux send-keys -t "${t}" ${e}`;await He(i),l.info("tmux special-key send completed")}catch(i){throw l.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 y=T(require("fs")),we=T(require("os")),M=T(require("path")),ie=require("crypto"),It=require("child_process"),bt=require("events"),Et=require("util");var ae=require("@quantiya/codevibe-core"),$e=(0,Et.promisify)(It.execFile),wt=512*1024,X="writer.state",Ci=2e3,Ai=10,Ni=16*1024*1024,ki=10080*60*1e3,Pe=class extends bt.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.lastPromptWasMenu=!1;this.lifecycleGeneration=0;this.retainedMirrors=[];this.retainedMirrorContainmentLost=!1;this.maxPaneFileBytes=e.maxPaneFileBytes??Ni,this.stalePaneRetentionMs=e.stalePaneRetentionMs??ki,this.tempDir=e.tempDir??we.tmpdir(),this.writerPath=M.resolve(__dirname,"..","libexec","pane-mirror-writer.js");let i=e.runtimePlatform??process.platform,s=e.runtimeRelease??we.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){l.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){l.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}l.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){l.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(),l.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 y.openSync(e,y.constants.O_RDWR|y.constants.O_CREAT|y.constants.O_EXCL|(y.constants.O_NOFOLLOW??0),384)}truncateMirror(e){y.ftruncateSync(e,0)}createSecureMirror(){y.mkdirSync(this.tempDir,{recursive:!0,mode:448});let e=y.mkdtempSync(M.join(this.tempDir,`codevibe-codex-pane-${process.pid}-`));y.chmodSync(e,448);let i=M.join(e,"pane.log"),s=M.join(e,X),r=null,n=null;try{r=this.openMirrorFile(i),y.fchmodSync(r,384);let o=y.fstatSync(r);if(!o.isFile())throw new Error("Tmux pane mirror is not a regular file");n=this.openMirrorFile(s),y.fchmodSync(n,384);let c=y.fstatSync(n);if(!c.isFile())throw new Error("Tmux pane writer state is not a regular file");y.writeSync(n,Buffer.from(`idle
|
|
15
|
-
`),0,5,0),this.pipeDirPath=
|
|
16
|
-
`);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),
|
|
17
|
-
`).slice(-6).join("\\n")});return}let r=this.hashPromptSnapshot(s);r!==this.lastPromptHash&&(this.lastPromptHash&&(this.lastPromptWasMenu||(0,
|
|
18
|
-
`).map(
|
|
19
|
-
`)}let
|
|
20
|
-
`):null}if(u(s[
|
|
21
|
-
`)}return null}hashPromptSnapshot(
|
|
1
|
+
"use strict";var si=Object.create;var ve=Object.defineProperty;var ri=Object.getOwnPropertyDescriptor;var ni=Object.getOwnPropertyNames;var oi=Object.getPrototypeOf,ai=Object.prototype.hasOwnProperty;var di=(d,e)=>{for(var t in e)ve(d,t,{get:e[t],enumerable:!0})},rt=(d,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ni(e))!ai.call(d,s)&&s!==t&&ve(d,s,{get:()=>e[s],enumerable:!(i=ri(e,s))||i.enumerable});return d};var A=(d,e,t)=>(t=d!=null?si(oi(d)):{},rt(e||!d||!d.__esModule?ve(t,"default",{value:d,enumerable:!0}):t,d)),li=d=>rt(ve({},"__esModule",{value:!0}),d);var fs={};di(fs,{CodexCompanionServer:()=>Me,TERMINAL_SHUTDOWN_SIGNALS:()=>Vt,classifyTmuxHasSessionError:()=>Yt,extractShellCommandFromPromptText:()=>Xt,extractShellCommandPartsFromPromptText:()=>it,restoreCodexPersistOptionCommand:()=>Zt,shellCommandPartsMatchExpected:()=>Jt});module.exports=li(fs);var de=require("uuid"),fe=A(require("crypto")),J=A(require("fs")),L=A(require("path")),Je=A(require("os")),et=require("util"),Le=require("child_process"),tt=require("shell-quote"),m=require("@quantiya/codevibe-core");var nt=A(require("os")),ot=A(require("path")),at=require("@quantiya/codevibe-core"),a=(0,at.createLogger)({name:"codevibe-codex",logFile:ot.default.join(nt.default.tmpdir(),"codevibe-codex-mcp.log"),level:"debug"});var lt=require("events"),x=A(require("fs")),H=A(require("path")),pt=require("string_decoder"),Se=require("crypto"),ct=require("chokidar"),ie=require("@quantiya/codevibe-core");var qe=256*1024,pi=64*1024*1024,ci=16*1024*1024,ui=64*1024,dt=100,hi=250,mi=["CHOKIDAR_USEPOLLING","CHOKIDAR_INTERVAL"];function fi(d,e){let t=mi.map(s=>[s,process.env[s]]);for(let[s]of t)delete process.env[s];let i;try{i=(0,ct.watch)(d,{...e,usePolling:!0})}finally{for(let[s,r]of t)r===void 0?delete process.env[s]:process.env[s]=r}if(i.options?.usePolling!==!0)throw i.close().catch(()=>{}),new Error("chokidar did not honour usePolling; refusing a native fs.watch");return i}function gi(d=process.env){let e=d.CODEX_HOME?.trim();return e?H.resolve(e,"sessions"):(0,ie.getConfig)().codex.sessionsDir}var Ie=class extends lt.EventEmitter{constructor(t={}){super();this.watcher=null;this.catchUpReadTimer=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.ownedReads=new Set;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=t.maxBacklogBytes??pi,this.maxRecordBytes=t.maxRecordBytes??ci,this.beforeEntry=t.beforeEntry,this.restoreCursor=t.restoreCursor,this.beforeGap=t.beforeGap,this.beforeEntry!==void 0&&typeof this.beforeEntry!="function")throw new TypeError("beforeEntry must be a function");if(this.restoreCursor!==void 0&&typeof this.restoreCursor!="function"||this.beforeGap!==void 0&&typeof this.beforeGap!="function"||this.restoreCursor&&(!this.beforeEntry||!this.beforeGap))throw new TypeError("durable source restore requires entry and gap admission callbacks");if(!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){a.warn("Session log watcher already running");return}this.transcriptBindGeneration++,this.transcriptBindingsClosed=!1;let t=gi();this.sessionsDir=t,a.info("Starting Codex session log watcher",{sessionsDir:t}),x.existsSync(t)||(a.info("Codex sessions directory does not exist yet, creating...",{sessionsDir:t}),x.mkdirSync(t,{recursive:!0})),this.startTime=Date.now(),this.readGeneration++,this.bindSource=null,this.authoritativeSessionId=null,this.snapshotStartBaselines(t),this.isWatching=!0,this.activeLogFile&&this.watchBoundRollout(this.activeLogFile),this.drainPendingTranscriptBind(),a.info("Session log watcher started; awaiting the SessionStart transcript bind")}stop(){this.transcriptBindingsClosed=!0,this.transcriptBindGeneration++,this.closeBoundRolloutWatch(),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(),a.info("Session log watcher stopped")}async waitForTranscriptAdmissions(){for(;this.activeTranscriptAdmissions.size>0;)await Promise.all(Array.from(this.activeTranscriptAdmissions,t=>t.then(()=>{},()=>{})))}async waitForReads(){await Promise.all([...this.ownedReads])}retryActiveRead(){this.isWatching&&this.activeLogFile&&this.scheduleReadNewLines(this.activeLogFile)}getSessionId(){return this.sessionId}getActiveLogFile(){return this.activeLogFile}getBindSource(){return this.bindSource}getAuthoritativeSessionId(){return this.authoritativeSessionId}tryRealpath(t){try{return x.realpathSync(t)}catch{return null}}isInteractiveRollout(t){return!(!t||t.originator==="codex_exec"||t.threadSource==="subagent"||t.sourceSubagent)}identityOf(t){return{dev:t.dev,ino:t.ino}}identitiesEqual(t,i){return t.dev===i.dev&&t.ino===i.ino}computeSeedOffset(t){let i;try{i=x.statSync(t)}catch{return 0}if(this.getSessionAgeMs(t,i)>=this.startTime)return 0;let r=this.startBaselines.get(t);return r&&this.identitiesEqual(r.identity,this.identityOf(i))?r.size:i.size}applyBind(t,i){this.readGeneration++,this.activeReads.delete(t),this.pendingReads.delete(t),this.activeLogFile=t,this.bindSource=i,i==="heuristic"&&(this.authoritativeSessionId=null),this.filePositions.has(t)||this.filePositions.set(t,this.computeSeedOffset(t));try{this.fileIdentities.set(t,this.identityOf(x.statSync(t)))}catch{this.fileIdentities.delete(t)}this.watchBoundRollout(t),this.scheduleReadNewLines(t)}watchBoundRollout(t){if(this.closeBoundRolloutWatch(),!this.isWatching||this.transcriptBindingsClosed)return;let i;try{i=fi(t,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:dt,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}})}catch(s){a.error("Could not follow bound rollout by polling",{filePath:t,error:s instanceof Error?s.message:String(s)}),this.emit("error",s);return}this.watcher=i,i.on("add",s=>this.onFileAdded(s)),i.on("change",s=>this.onFileChanged(s)),i.on("error",s=>{a.error("Watcher error:",s),this.emit("error",s)}),i.on("ready",()=>{this.watcher===i&&(this.catchUpReadTimer=setTimeout(()=>{this.catchUpReadTimer=null,this.watcher===i&&this.activeLogFile===t&&this.scheduleReadNewLines(t)},hi),this.catchUpReadTimer.unref?.())}),a.info("Following bound rollout",{filePath:t,pollIntervalMs:dt})}closeBoundRolloutWatch(){this.catchUpReadTimer&&(clearTimeout(this.catchUpReadTimer),this.catchUpReadTimer=null);let t=this.watcher;t&&(this.watcher=null,t.close().catch(i=>{a.warn("Bound rollout watcher close failed",{error:i instanceof Error?i.message:String(i)})}))}bindToFile(t){let i=this.tryRealpath(t);if(!i){a.warn("bindToFile: could not canonicalize path; skipping",{filePath:t});return}if(i===this.activeLogFile){this.bindSource="authoritative";return}a.info("bindToFile: authoritative bind to session rollout",{filePath:i}),this.applyBind(i,"authoritative")}async bindToSessionTranscript(t,i){if(typeof t!="string"||t.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===t&&s.expectedSessionId===i?{status:"pending",completion:s.completion}:(a.warn("bindToSessionTranscript: conflicting startup bind rejected",{transcriptPath:t,expectedSessionId:i,pendingExpectedSessionId:s.expectedSessionId}),{status:"rejected",reason:"conflicting_startup_bind"});let r,n=new Promise(o=>{r=o});return this.pendingTranscriptBind={transcriptPath:t,expectedSessionId:i,completion:n,resolve:r},a.debug("bindToSessionTranscript: watcher not started yet; queued pending authoritative bind",{transcriptPath:t,expectedSessionId:i}),{status:"pending",completion:n}}return this.trackTranscriptAdmission(this.validateAndBindSessionTranscript(t,i,this.transcriptBindGeneration))}trackTranscriptAdmission(t){let i;return i=t.finally(()=>{this.activeTranscriptAdmissions.delete(i)}),this.activeTranscriptAdmissions.add(i),i}isTranscriptAdmissionCurrent(t,i){return!this.transcriptBindingsClosed&&this.transcriptBindGeneration===t&&this.sessionsDir===i}async validateAndBindSessionTranscript(t,i,s){let r=this.sessionsDir;if(!r||!this.isTranscriptAdmissionCurrent(s,r))return{status:"rejected",reason:"watcher_not_started"};let n=this.tryRealpath(t),o=this.tryRealpath(r);if(!n||!o)return{status:"rejected",reason:"canonicalization_failed"};let l=H.relative(o,n);if(l===".."||l.startsWith(".."+H.sep)||H.isAbsolute(l))return a.warn("bindToSessionTranscript: path not under sessionsDir; rejecting",{transcriptPath:n}),{status:"rejected",reason:"outside_sessions_directory"};let p=H.basename(n);if(!p.startsWith("rollout-")||!p.endsWith(".jsonl"))return{status:"rejected",reason:"invalid_rollout_filename"};let c=null;for(let u=0;u<3;u++){if(!this.isTranscriptAdmissionCurrent(s,r))return{status:"rejected",reason:"watcher_stopped"};if(c=this.readSessionMeta(n),c)break;if(await new Promise(h=>setTimeout(h,20)),!this.isTranscriptAdmissionCurrent(s,r))return{status:"rejected",reason:"watcher_stopped"}}return!c||c.id!==i?(a.debug("bindToSessionTranscript: meta missing or id mismatch; not binding",{transcriptPath:n,metaId:c?.id,expectedSessionId:i}),{status:"rejected",reason:"session_metadata_mismatch"}):this.isInteractiveRollout(c)?this.isTranscriptAdmissionCurrent(s,r)?(this.bindToFile(n),this.authoritativeSessionId=i,{status:"bound"}):{status:"rejected",reason:"watcher_stopped"}:(a.debug("bindToSessionTranscript: non-interactive rollout (codex_exec/subagent); not binding",{transcriptPath:n,originator:c.originator,threadSource:c.threadSource}),{status:"rejected",reason:"non_interactive_rollout"})}async drainPendingTranscriptBind(){let t=this.pendingTranscriptBind;if(!t)return;this.pendingTranscriptBind=null;let i;try{this.transcriptBindingsClosed?i={status:"rejected",reason:"watcher_stopped"}:i=await this.trackTranscriptAdmission(this.validateAndBindSessionTranscript(t.transcriptPath,t.expectedSessionId,this.transcriptBindGeneration))}catch(s){a.warn("bindToSessionTranscript: pending startup bind failed",{expectedSessionId:t.expectedSessionId,error:s instanceof Error?s.message:String(s)}),i={status:"rejected",reason:"startup_bind_failed"}}t.resolve(i)}onFileAdded(t){let i=this.tryRealpath(t);i&&(i===this.activeLogFile?this.scheduleReadNewLines(i):a.debug("Ignoring unowned rollout add; awaiting authoritative hook binding",{filePath:i}))}onFileChanged(t){let i=this.tryRealpath(t);i&&(this.activeLogFile&&i!==this.activeLogFile||this.activeLogFile&&this.scheduleReadNewLines(i))}readSessionMeta(t){let i=this.readFirstLogEntry(t);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(t){let i=null;try{i=x.openSync(t,"r");let s=new pt.StringDecoder("utf8"),r=Buffer.alloc(64*1024),n="",o=0,l=-1;for(;o<qe;){let c=x.readSync(i,r,0,r.length,o);if(c<=0||(o+=c,n+=s.write(r.subarray(0,c)),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{x.closeSync(i)}catch{}}}snapshotStartBaselines(t){this.startBaselines.clear();try{for(let{filePath:i,size:s}of this.collectRecentSessionFiles(t,!0)){let r=this.tryRealpath(i);if(r)try{let n=x.statSync(r);this.startBaselines.set(r,{size:s,identity:this.identityOf(n)})}catch{}}}catch{}}getSessionAgeMs(t,i){let s=this.readSessionMeta(t);if(s?.timestamp){let r=Date.parse(s.timestamp);if(!Number.isNaN(r))return r}return i.birthtimeMs||i.ctimeMs}collectRecentSessionFiles(t,i=!1){let s=[],r=[t];for(;r.length>0;){let n=r.pop();if(!n)continue;let o;try{o=x.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let l of o){let p=H.join(n,l.name);if(l.isDirectory()){r.push(p);continue}if(!(!l.isFile()||!l.name.startsWith("rollout-")||!l.name.endsWith(".jsonl")))try{let c=x.statSync(p),u=c.birthtimeMs||c.ctimeMs,h=c.mtimeMs;(i||u>=this.startTime||h>=this.startTime-5e3)&&s.push({filePath:p,createdAt:u,modifiedAt:h,size:c.size})}catch{}}}return s}scheduleReadNewLines(t){let i=this.activeReads.get(t);if(i)return this.pendingReads.add(t),i;let s=this.readGeneration,r=Promise.resolve().then(()=>this.drainReadQueue(t,s));return this.activeReads.set(t,r),this.ownedReads.add(r),r.finally(()=>{this.ownedReads.delete(r),this.activeReads.get(t)===r&&(this.activeReads.delete(t),this.pendingReads.delete(t))}),r}async drainReadQueue(t,i){do this.pendingReads.delete(t),await this.readNewLines(t,i);while(i===this.readGeneration&&this.pendingReads.has(t))}async readNewLines(t,i){if(i!==this.readGeneration)return;let s=this.filePositions.get(t)||0,r=null;try{r=x.openSync(t,x.constants.O_RDONLY|(x.constants.O_NOFOLLOW??0));let n=x.fstatSync(r),o=this.identityOf(n),l=this.fileIdentities.get(t);if(l&&!this.identitiesEqual(l,o)){let w=this.readFirstLogEntryFromFd(r),R=w?.type==="session_meta"?w.payload.id:void 0;if(this.authoritativeSessionId&&R!==this.authoritativeSessionId){let T=new Error("Authoritative Codex rollout path was replaced by a different session");a.error("Refusing replaced rollout with mismatched session identity",{filePath:t,expectedSessionId:this.authoritativeSessionId,replacementSessionId:R}),this.emit("error",T);return}a.info("Session log inode replaced; resetting byte and decoder state",{filePath:t,oldPosition:s,oldIdentity:l,newIdentity:o}),s=0,this.filePositions.set(t,0),this.oversizedRecordFiles.delete(t)}if(this.fileIdentities.set(t,o),this.restoreCursor&&this.sessionId===null){let w=this.readFirstLogEntryFromFd(r);w?.type==="session_meta"&&this.processLogEntry(w)}let p=Object.freeze({transcriptPath:t,nativeSessionId:this.authoritativeSessionId??this.sessionId,fileIdentity:Object.freeze({...o})}),c=!1;if(this.restoreCursor){let w=s<=n.size?s:0,R=this.readSourceAnchor(r,w),T=await this.restoreCursor(p,{byteOffset:w,anchor:R,discardUntilNewline:w>0&&!this.isNewlineBoundary(r,w)});if(i!==this.readGeneration)return;T!==null&&(this.verifySourcePosition(r,n.size,T),s=T.byteOffset,c=!0,this.filePositions.set(t,s),T.discardUntilNewline?this.oversizedRecordFiles.add(t):this.oversizedRecordFiles.delete(t))}let u=async(w,R,T,b)=>(c&&await this.beforeGap({startOffset:w,endOffset:R,reason:T,discardUntilNewline:b,anchor:this.readSourceAnchor(r,R,w)},p),i===this.readGeneration);if(n.size<s&&(a.info("Session log truncated/rotated; resetting cursor to 0",{filePath:t,oldPosition:s,size:n.size}),s=0,this.filePositions.set(t,0),this.oversizedRecordFiles.delete(t)),n.size<=s)return;if(n.size-s>this.maxBacklogBytes){if(s===0&&this.sessionId===null){let R=this.readFirstLogEntryFromFd(r);R?.type==="session_meta"&&this.processLogEntry(R)}let w=this.findRecentRecordBoundary(r,n.size);if(!await u(s,w.position,"BACKLOG_LIMIT",w.discardUntilNewline)||(a.warn("Codex rollout backlog exceeded live-mirror limit; skipping archival prefix",{filePath:t,oldPosition:s,newPosition:w.position,size:n.size,maxBacklogBytes:this.maxBacklogBytes,discardUntilNewline:w.discardUntilNewline}),s=w.position,this.filePositions.set(t,s),w.discardUntilNewline?this.oversizedRecordFiles.add(t):this.oversizedRecordFiles.delete(t),n.size<=s))return}let h=n.size,g=Buffer.allocUnsafe(64*1024),f=s,y=s,I=[],S=0,v=this.oversizedRecordFiles.has(t);for(;f<h;){if(i!==this.readGeneration)return;let w=Math.min(g.length,h-f),R=x.readSync(r,g,0,w,f);if(R<=0)break;let T=0;for(;T<R;){if(i!==this.readGeneration)return;let b=g.subarray(0,R).indexOf(10,T),E=b!==-1,C=E?b:R,M=C-T,K=M+(E?1:0);if(v){if(f+=K,!await u(y,f,"PARTIAL_RECORD",!E))return;this.filePositions.set(t,f),y=f,E&&(v=!1,this.oversizedRecordFiles.delete(t)),T=E?b+1:R;continue}if(M>0&&(I.push(Buffer.from(g.subarray(T,C))),S+=M),f+=K,S>this.maxRecordBytes){if(a.warn("Discarding oversized Codex rollout JSONL record",{filePath:t,recordEnd:f,maxRecordBytes:this.maxRecordBytes}),!await u(y,f,"OVERSIZED_RECORD",!E))return;this.filePositions.set(t,f),y=f,I=[],S=0,v=!E,v?this.oversizedRecordFiles.add(t):this.oversizedRecordFiles.delete(t),T=E?b+1:R;continue}if(!E){T=R;continue}let W=Buffer.concat(I,S),Z=W;I=[],S=0,W.length>0&&W[W.length-1]===13&&(W=W.subarray(0,W.length-1));let ye=W.toString("utf8");if(ye.trim()){let q;try{let B=JSON.parse(ye);if(!B||typeof B!="object"||Array.isArray(B)||typeof B.type!="string")throw new Error("Invalid Codex log entry shape");q=B}catch(B){if(a.warn("Failed to parse log line",{filePath:t,line:ye.substring(0,100),error:B}),!await u(y,f,"MALFORMED_RECORD",!1))return}if(q!==void 0){let B=!1;if(this.beforeEntry&&(B=await this.beforeEntry(q,Object.freeze({...p,startOffset:f-Z.length-1,endOffset:f,sha256:(0,Se.createHash)("sha256").update(Z).update(`
|
|
3
|
+
`).digest("hex"),anchor:Object.freeze(this.framedSourceAnchor(Z,f))}))==="handled",i!==this.readGeneration))return;try{B||this.processLogEntry(q)}catch(st){a.warn("Failed to process log line",{filePath:t,error:st})}}}else if(!await u(y,f,"EMPTY_RECORD",!1))return;if(i===this.readGeneration&&(this.filePositions.set(t,f),y=f),i!==this.readGeneration)return;T=b+1}}}catch(n){a.error("Error reading log file",{filePath:t,error:n}),this.emit("error",n)}finally{if(r!==null)try{x.closeSync(r)}catch{}}}framedSourceAnchor(t,i){let s=t.subarray(Math.max(0,t.length-(ie.MAX_SYNC_SOURCE_ANCHOR_BYTES-1)));return{startOffset:i-s.length-1,endOffset:i,sha256:(0,Se.createHash)("sha256").update(s).update(`
|
|
4
|
+
`).digest("hex")}}readSourceAnchor(t,i,s=0){if(i===0)return null;let r=Math.max(s,i-ie.MAX_SYNC_SOURCE_ANCHOR_BYTES);if(r>=i)throw new Error("SYNC_SOURCE_POSITION_INVALID");let n=Buffer.allocUnsafe(i-r),o=0;for(;o<n.length;){let l=x.readSync(t,n,o,n.length-o,r+o);if(l<=0)throw new Error("SYNC_SOURCE_ANCHOR_UNAVAILABLE");o+=l}return{startOffset:r,endOffset:i,sha256:(0,Se.createHash)("sha256").update(n).digest("hex")}}isNewlineBoundary(t,i){if(i===0)return!0;let s=Buffer.allocUnsafe(1);return x.readSync(t,s,0,1,i-1)===1&&s[0]===10}verifySourcePosition(t,i,s){let{byteOffset:r,anchor:n,discardUntilNewline:o}=s;if(!Number.isSafeInteger(r)||r<0||r>i||typeof o!="boolean")throw new Error("SYNC_SOURCE_POSITION_INVALID");if(r===0){if(n!==null||o)throw new Error("SYNC_SOURCE_POSITION_INVALID");return}if(!n||!Number.isSafeInteger(n.startOffset)||n.startOffset<0||n.endOffset!==r||n.startOffset>=r||r-n.startOffset>ie.MAX_SYNC_SOURCE_ANCHOR_BYTES||!/^[a-f0-9]{64}$/.test(n.sha256)||o===this.isNewlineBoundary(t,r))throw new Error("SYNC_SOURCE_POSITION_INVALID");if(this.readSourceAnchor(t,r,n.startOffset).sha256!==n.sha256)throw new Error("SYNC_SOURCE_ANCHOR_CHANGED")}findRecentRecordBoundary(t,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(x.readSync(t,n,0,1,s-1)===1&&n[0]===10)return{position:s,discardUntilNewline:!1};let o=Buffer.allocUnsafe(ui),l=s;for(;l<r;){let p=Math.min(o.length,r-l),c=x.readSync(t,o,0,p,l);if(c<=0)break;let u=o.subarray(0,c).indexOf(10);if(u!==-1)return{position:l+u+1,discardUntilNewline:!1};l+=c}if(l===r&&l<i&&r-s===this.maxRecordBytes){let p=Buffer.allocUnsafe(1);if(x.readSync(t,p,0,1,l)===1&&p[0]===10)return{position:l+1,discardUntilNewline:!1}}return{position:s,discardUntilNewline:!0}}}readFirstLogEntryFromFd(t){try{let i=[],s=0,r=Buffer.allocUnsafe(64*1024);for(;s<qe;){let o=Math.min(r.length,qe-s),l=x.readSync(t,r,0,o,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(t){if(a.debug("Processing log entry",{type:t.type}),t.type==="session_meta"){let i=t.payload;this.sessionId=i.id,a.info("Codex session started",{sessionId:i.id,cwd:i.cwd,cliVersion:i.cli_version}),this.emit("session-started",i);return}this.emit("log-entry",t),t.type==="event_msg"&&t.payload?.type?this.emit(`event:${t.payload.type}`,t):t.type==="response_item"&&t.payload?.type&&this.emit(`response:${t.payload.type}`,t)}};var Be=require("uuid"),we=require("crypto"),N=require("@quantiya/codevibe-core");var G=new Map,$=[],mt=24;function pe(d){return typeof d=="string"?d.trim():""}function ft(d){return typeof d=="string"?d:""}function ut(d,e,t){let i=pe(t);if(!i)return!1;let s=ft(e),r=(0,we.createHash)("sha256").update(i).digest("hex");return $.some(n=>n.textHash===r&&n.phase===s&&n.carrier!==d)}function yi(d){let e=pe(d),t=(0,we.createHash)("sha256").update(e).digest("hex");return e.length>0&&$.some(i=>i.textHash===t&&i.phase==="final_answer")}function Ke(d,e,t){let i=pe(t);if(i)for($.push({carrier:d,phase:ft(e),textHash:(0,we.createHash)("sha256").update(i).digest("hex")});$.length>mt;)$.shift()}function se(){$.length=0}function gt(d,e,t){let i=[];if(t!==null){if(typeof t!="string"||Buffer.byteLength(t)>16*1024)throw new Error("INVALID_CODEX_SOURCE_PROJECTION");try{i=JSON.parse(t)}catch{throw new Error("INVALID_CODEX_SOURCE_PROJECTION")}if(!Array.isArray(i)||i.length>mt||i.some(n=>!n||Object.keys(n).sort().join(",")!=="carrier,phase,textHash"||!["agent_message","response_item","task_complete"].includes(n.carrier)||typeof n.phase!="string"||typeof n.textHash!="string"||!/^[a-f0-9]{64}$/.test(n.textHash)))throw new Error("INVALID_CODEX_SOURCE_PROJECTION")}let s=$.slice(),r=new Map(G);$.splice(0,$.length,...i);try{let n=He(d,e),o=JSON.stringify($);if(Buffer.byteLength(o)>16*1024)throw new Error("INVALID_CODEX_SOURCE_PROJECTION");return{event:n,projection:o}}finally{$.splice(0,$.length,...s),G.clear();for(let[n,o]of r)G.set(n,o)}}function vi(d){let e=d?.content;return Array.isArray(e)?e.filter(t=>t&&(t.type==="output_text"||t.type==="text")).map(t=>typeof t?.text=="string"?t.text:"").join(""):""}function Si(d){let e=d?.summary;return!Array.isArray(e)||e.length===0?"":e.map(t=>typeof t=="string"?t:typeof t?.text=="string"?t.text:"").join(`
|
|
5
|
+
`).trim()}function Ii(d){if(typeof d!="string")return"";let e=d.match(/"cmd"\s*:\s*"((?:\\.|[^"\\])*)"/);if(e)try{return JSON.parse(`"${e[1]}"`)}catch{return e[1]}return""}function re(d){if(typeof d!="string"||!d.startsWith(`*** Begin Patch
|
|
6
|
+
`)||!d.endsWith(`
|
|
7
|
+
*** End Patch`))return"";let e=d.split(`
|
|
8
|
+
`);return e[0]!=="*** Begin Patch"||e[e.length-1]!=="*** End Patch"||e.filter(t=>t==="*** Begin Patch").length!==1||e.filter(t=>t==="*** End Patch").length!==1||!/^\*\*\* (?:Add|Update|Delete) File: [^\r\n]+$/.test(e[1]??"")?"":d}function ce(d){if(typeof d!="string")return"";let e="[A-Za-z_$][\\w$]*",t='"(?:\\\\.|[^"\\\\])*"',i=d.match(new RegExp(`^\\s*(?:const|let|var)\\s+(${e})\\s*=\\s*await\\s+tools\\.apply_patch\\(\\s*(${t})\\s*\\)\\s*;\\s*(?:text\\(\\s*(${e})\\s*\\)\\s*;\\s*)?$`,"s")),s=d.match(new RegExp(`^\\s*(?:const|let|var)\\s+(${e})\\s*=\\s*(${t})\\s*;\\s*(?:const|let|var)\\s+(${e})\\s*=\\s*await\\s+tools\\.apply_patch\\(\\s*(${e})\\s*\\)\\s*;\\s*(?:text\\(\\s*(${e})\\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 re(JSON.parse(r))}catch{return""}}var Pi=new Set(["exec","shell","shell_command","bash","run_command","run_cmd"]);function ht(d,e){return typeof e!="string"?"":d==="apply_patch"?e:d==="exec"?ce(e):typeof d=="string"&&Pi.has(d)?"":e.includes("*** Begin Patch")?e:""}function He(d,e){let t={sessionId:e,source:N.EventSource.DESKTOP};if(d.type==="event_msg"&&d.payload){let i=d.payload.type;switch(i){case"user_message":return se(),{...t,type:N.EventType.USER_PROMPT,content:d.payload.message||"",metadata:{images:d.payload.images||[]}};case"agent_message":{let s=d.payload.message||"",r=d.payload.phase;return ut("agent_message",r,s)?null:(Ke("agent_message",r,s),{...t,type:N.EventType.ASSISTANT_RESPONSE,content:s,metadata:{phase:r}})}case"agent_reasoning":return{...t,type:N.EventType.REASONING,content:d.payload.text||""};case"task_started":return se(),a.debug("Skipping task_started entry (turn boundary)"),null;case"task_complete":{let s=d.payload.error,r=typeof s?.message=="string"?s.message.trim():"";if(r){d.payload.last_agent_message&&a.warn("task_complete carried BOTH an error and a final message; relaying the error",{turnId:d.payload.turn_id});let l=typeof s?.codex_error_info=="string"?s.codex_error_info.trim():"",p=l!==""&&new RegExp(`(^|[^A-Za-z0-9_])${l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}($|[^A-Za-z0-9_])`).test(r);return se(),{...t,type:N.EventType.NOTIFICATION,content:l&&!p?`${r} (${l})`:r,metadata:{phase:"turn_error",turnId:d.payload.turn_id,...l?{codexErrorInfo:l}:{}}}}s!=null&&a.warn("task_complete carried an error with no extractable message; falling through to the message path",{turnId:d.payload.turn_id,errorShape:typeof s});let n=pe(d.payload.last_agent_message),o=null;return n&&!yi(n)?(Ke("task_complete","final_answer",n),o={...t,type:N.EventType.ASSISTANT_RESPONSE,content:n,metadata:{phase:"final_answer"}}):a.debug("Skipping task_complete (final already emitted or empty)"),se(),o}case"turn_aborted":{let s=typeof d.payload.reason=="string"?d.payload.reason.trim():"";return se(),{...t,type:N.EventType.NOTIFICATION,content:s?`Turn aborted (${s})`:"Turn aborted",metadata:{phase:"turn_aborted",turnId:d.payload.turn_id,...s?{reason:s}:{}}}}case"token_count":return a.debug("Skipping token_count entry"),null;default:return a.debug("Unknown event_msg type",{type:i}),null}}if(d.type==="response_item"&&d.payload){let i=d.payload.type;if(i==="message"){if(d.payload.role!=="assistant")return a.debug("Skipping non-assistant response_item/message",{role:d.payload.role}),null;let s=vi(d.payload),r=d.payload.phase;return!pe(s)||ut("response_item",r,s)?null:(Ke("response_item",r,s),{...t,type:N.EventType.ASSISTANT_RESPONSE,content:s,metadata:{phase:r}})}if(i==="reasoning"){let s=Si(d.payload);return s?{...t,type:N.EventType.REASONING,content:s}:(a.debug("Skipping reasoning response_item (no readable summary)"),null)}if(i==="function_call"){let{name:s,arguments:r,call_id:n}=d.payload,o={};try{o=JSON.parse(r||"{}")}catch{o={raw:r}}let l=(0,Be.v4)();G.set(n,{name:s,input:r,eventId:l});let p=le(s),c=wi(s,o);return{...t,type:N.EventType.TOOL_USE,content:c,metadata:{toolName:p,toolInput:o,callId:n,status:"running"}}}if(i==="function_call_output"){let{call_id:s,output:r}=d.payload,n=G.get(s);G.delete(s);let o=n?.name?le(n.name):"Tool",l=Ue(Pe(r),500);return{...t,type:N.EventType.TOOL_USE,content:`${o} completed:
|
|
9
|
+
${l}`,metadata:{toolName:o,toolOutput:r,callId:s,status:"completed"}}}if(i==="custom_tool_call"){let{name:s,call_id:r,input:n,status:o}=d.payload;G.set(r,{name:s,input:n,eventId:(0,Be.v4)()});let l=ht(s,n);if(l){let u=Ei(l),{oldString:h,newString:g}=bi(l),f=u?`Editing: ${u.filePath}`:"Applying patch";return{...t,type:N.EventType.TOOL_USE,content:f,metadata:{tool_name:"Edit",tool_input:{file_path:u?.filePath||"",old_string:h,new_string:g},callId:r,status:o||"running"}}}let p=Ii(n),c=le(s==="exec"?"shell":s||"tool");return{...t,type:N.EventType.TOOL_USE,content:p?`Running: ${p}`:`Running ${c}`,metadata:{toolName:c,toolInput:p?{command:p}:{raw:typeof n=="string"?n:""},callId:r,status:o||"running"}}}if(i==="custom_tool_call_output"){let{call_id:s,output:r}=d.payload,n=G.get(s);if(G.delete(s),ht(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=Pe(r);try{p=JSON.parse(y)}catch{p={raw:r,text:y}}}else p=r??{};let c=p!==null&&typeof p=="object"&&!Array.isArray(p)?p:null,u=typeof c?.output=="string"?c.output:void 0,h=c?.error,g=u!==void 0&&u.includes("Success"),f=typeof h=="string"?h:h!==void 0?JSON.stringify(h):"Unknown error";return{...t,type:N.EventType.TOOL_USE,content:g?"File edit applied successfully":`Edit failed: ${f}`,metadata:{toolName:"Edit",toolOutput:p,callId:s,status:"completed",success:g}}}let o=n?.name?le(n.name==="exec"?"shell":n.name):"Tool",l=Pe(r);return{...t,type:N.EventType.TOOL_USE,content:`${o} completed:
|
|
10
|
+
${Ue(l,500)}`,metadata:{toolName:o,toolOutput:r,callId:s,status:"completed"}}}return a.debug("Unknown response_item type",{type:i}),null}return d.type==="turn_context"?(a.debug("Skipping turn_context entry"),null):(a.debug("Unhandled log entry type",{type:d.type}),null)}function le(d){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"}[d]||d}function wi(d,e){switch(d){case"shell_command":case"shell":return`Running: ${e.command||"command"}`;case"read_file":return`Reading: ${e.file_path||e.path||"file"}`;case"write_file":return`Writing: ${e.file_path||e.path||"file"}`;case"list_files":return`Listing: ${e.path||"."}`;case"search_files":return`Searching for: ${e.pattern||e.query||"pattern"}`;case"web_search":return`Searching web: ${e.query||"query"}`;default:return`Running ${le(d)}`}}function bi(d){let e=[],t=[],i=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;for(let s of d.split(`
|
|
11
|
+
`))if(!(i.test(s)||s.startsWith("***")||s.startsWith("---")||s.startsWith("+++"))){if(s.startsWith("-"))e.push(s.slice(1));else if(s.startsWith("+"))t.push(s.slice(1));else if(s.startsWith(" ")){let r=s.slice(1);e.push(r),t.push(r)}}return{oldString:e.join(`
|
|
12
|
+
`),newString:t.join(`
|
|
13
|
+
`)}}function Ei(d){if(!d)return null;let e=d.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);return e?{filePath:e[1].trim()}:null}function Pe(d){if(d==null)return"";if(typeof d=="string")return d;if(Array.isArray(d))return d.map(e=>typeof e?.text=="string"?e.text:e?.type==="input_image"||typeof e?.image_url=="string"?"[image]":JSON.stringify(e??null)).join(`
|
|
14
|
+
`);if(typeof d=="object"&&typeof d.text=="string")return d.text;try{return JSON.stringify(d)??""}catch{return String(d)}}function Ue(d,e){return typeof d!="string"?Ue(Pe(d),e):d?d.length<=e?d:d.substring(0,e)+"...":""}function $e(){G.clear(),se()}var F=require("@quantiya/codevibe-core"),yt=3e3,Ri=8,_i=10,Ti=100;function vt(d){let e=Buffer.byteLength(d.carryover);return{status:"partial",progressKey:`${d.fileIdentity.dev}:${d.fileIdentity.ino}:${d.size}:${d.endOfComplete}:${e}`,size:d.size,carryoverBytes:e,endOfComplete:d.endOfComplete}}var xi="tool_activity",ne=class{constructor(e){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=e}static mintBackendSessionId(){return F.ToolActivitySessionMap.mintCodexBackendSessionId()}async recordedBackendSessionId(e){return new F.ToolActivitySessionMap({agent:"codex",logger:this.deps.logger,lock:new F.InProcessRolloutLock,root:this.deps.root}).ownerBackendSessionId(e)}get sessionId(){return this.backendSessionId}get rollout(){return this.rolloutId}isActive(){return this.consolidator!==null}async start(e,t,i){this.backendSessionId=e,this.rolloutId=t;let s=(0,F.createRolloutLock)({agent:"codex",logger:this.deps.logger,socketDir:this.deps.socketDir,root:this.deps.root});this.sessionMap=new F.ToolActivitySessionMap({agent:"codex",logger:this.deps.logger,lock:s,root:this.deps.root}),this.ownership=await this.sessionMap.claimOwnership(t,e);let r=new F.ToolActivityOutbox({agent:"codex",logger:this.deps.logger,root:this.deps.root});this.ledger=new F.ToolActivityLedger({agent:"codex",sessionId:e,logger:this.deps.logger,root:this.deps.root}),await this.deps.recoverPending?.(e,r,this.ledger);let n=this.buildTransport(),o=this.deps.selectTransport?await this.deps.selectTransport(e,n):n;this.consolidator=new F.ToolActivityConsolidator({agent:"codex",sessionId:e,logger:this.deps.logger,outbox:r,ledger:this.ledger,transport:o}),await this.consolidator.init(),i&&this.bindTranscript(i),this.deps.logger.info("[tool-activity] codex consolidator started",{sessionId:e,rollout:t,hasTranscript:!!i})}bindTranscript(e){if(!this.consolidator||!e||this.transcriptPath===e)return;this.transcriptPath=e;let t=new F.ToolReplayCursor({agent:"codex",sessionId:this.backendSessionId,canonicalPath:e,logger:this.deps.logger,root:this.deps.root,readBytes:this.deps.replayReadBytes,maxFrameBytes:this.deps.replayMaxFrameBytes});this.cursor=t,this.cursorRepaired=!1,this.cursorReady=t.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(e,t){if(!this.consolidator||!this.sessionMap||!this.ownership||!e.callId||!e.toolName)return;let i=this.consolidator;await this.sessionMap.bindCall(this.ownership,e.callId);let s={id:e.callId,tool:e.toolName,normalizedTarget:ki(e.toolName,e.toolInput),ts:e.ts??new Date().toISOString(),byteOffset:e.byteOffset??0,...e.toolInput!==void 0?{digest:(0,F.digestOf)(e.toolInput)}:{}},r=await i.observe(s,t);return r==="closed"?await i.captureTerminal(s,this.deps.shutdownDrainMs??yt)?"sealed-terminal":"closed":r}async runTranscriptBackstop(e=!1){await this.runTranscriptBackstopTurn(e)}runTranscriptBackstopTurn(e=!1){if(this.backstopInFlight)return this.backstopInFlight;let t=this.cursor,i=this.cursorReady,s=this.consolidator;if(!s||!t)return Promise.resolve("caught-up");let n=(async()=>{if(await i,this.cursor!==t)return"more";if(!this.cursorRepaired){if(await s.repairLostWindows(t),this.cursor!==t)return"more";this.cursorRepaired=!0}return this.doTranscriptBackstop(t,e)})().finally(()=>{this.backstopInFlight===n&&(this.backstopInFlight=null)});return this.backstopInFlight=n,n}async doTranscriptBackstop(e,t=!1){let i=this.consolidator;if(!i)return"caught-up";this.ledger&&await this.ledger.reloadLegacyOwned();for(let s=0;s<Ri;s+=1){if(this.cursor!==e)return"caught-up";let r=await e.readFrames();if(r.missing)return"caught-up";if(r.frames.length===0)return r.carryover.length>0?vt(r):"caught-up";let n=Number.POSITIVE_INFINITY,o=t?{includeInFlight:!0}:void 0;for(let l of r.frames)for(let p of Ci(l.line,l.startOffset))await this.observeCall(p,o)==="deferred-in-flight"&&(n=Math.min(n,l.startOffset));if(await i.flush(),n<r.endOfComplete)return await e.checkpoint(n,{fileIdentity:r.fileIdentity,size:r.size,carryover:""}),"more";if(await e.checkpoint(r.endOfComplete,{fileIdentity:r.fileIdentity,size:r.size,carryover:r.carryover}),!r.hasMore)return r.carryover.length>0?vt(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 e=Math.max(1,Math.trunc(this.deps.shutdownPartialNoProgressTurns??Ti)),t=null,i=0;for(;;){let s=await this.runTranscriptBackstopTurn(!0);if(s==="caught-up")break;if(typeof s!="string"){if(s.progressKey===t?i+=1:(t=s.progressKey,i=1),i>=e){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,_i))}else t=null,i=0,await new Promise(r=>setImmediate(r))}await this.consolidator?.drainSends(this.deps.shutdownDrainMs??yt).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 e=async(t,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:t,type:F.EventType.TOOL_ACTIVITY,source:F.EventSource.DESKTOP,content:this.deps.encryptContent(xi,r),metadata:{encrypted:this.deps.encryptMetadata({manifest:i.manifest},r)},timestamp:i.windowStart,isEncrypted:!0,clientEventId:i.clientEventId,...n?{expectedSessionKeyGen:n}:{}})};return{send:async(t,i)=>{try{await e(t,i)}catch(s){if((0,F.isSessionKeyStaleError)(s)&&this.deps.refreshSessionKey){let r=await this.deps.refreshSessionKey(t);if(!r)throw s;await e(t,i,r);return}throw s}}}}};function Ci(d,e){let t;try{t=JSON.parse(d)}catch{return[]}if(t?.type!=="response_item"||!t.payload)return[];let i=t.payload,s=typeof t.timestamp=="string"?t.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:Oi(i.name),toolInput:r,ts:s,byteOffset:e}]}if(i.type==="custom_tool_call"&&typeof i.call_id=="string"){let r=Ai(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:e}]}return[]}function Oi(d){return d==="shell"||d==="shell_command"||d==="local_shell"?"Bash":d==="apply_patch"?"Edit":d}function Ai(d){let e=d.match(/^\*\*\* (?:Update|Add|Delete) File: (.+)$/m);return e?e[1].trim():void 0}function ki(d,e){if(!e||typeof e!="object")return;let t=e,i=r=>typeof r=="string"&&r.length>0?r:void 0,s=Array.isArray(t.command)?t.command.filter(r=>typeof r=="string").join(" ").trim().split(/\s+/)[0]:typeof t.command=="string"?t.command.trim().split(/\s+/)[0]:void 0;return i(t.file_path)??i(t.path)??i(t.pattern)??i(t.url)??(s&&s.length>0?s:void 0)}var St=require("events"),It=require("@quantiya/codevibe-core");var be=class d extends St.EventEmitter{constructor(){super();this.pendingCalls=new Map;this.timers=new Map;this.timeoutMs=(0,It.getConfig)().codex.approvalTimeoutMs,a.info("Approval detector initialized",{timeoutMs:this.timeoutMs})}onToolCallStart(t,i,s){a.debug("Tool call started",{callId:t,name:i});let r=this.parseInput(s),n=this.extractFilePath(i,s,r),o=this.extractDiff(i,s,r),l={callId:t,name:i,input:s,filePath:n,diff:o,parsedInput:r,timestamp:Date.now(),notificationSent:!1};if(this.pendingCalls.set(t,l),!this.shouldScheduleApprovalTimeout(i,r)){a.debug("Skipping approval timeout for non-escalated tool call",{callId:t,name:i});return}let p=setTimeout(()=>{this.checkPendingCall(t)},this.timeoutMs);this.timers.set(t,p)}onToolCallComplete(t){a.debug("Tool call completed",{callId:t}),this.pendingCalls.delete(t);let i=this.timers.get(t);i&&(clearTimeout(i),this.timers.delete(t))}checkPendingCall(t){let i=this.pendingCalls.get(t);if(!i||i.notificationSent)return;let s=Date.now()-i.timestamp;a.info("Tool call still pending after timeout",{callId:t,name:i.name,elapsedMs:s}),i.notificationSent=!0,this.pendingCalls.set(t,i),this.emit("approval-pending",{callId:t,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(t,i,s){if(s)return`File: ${s}`;if(t==="apply_patch"&&i){let r=i.match(/\*\*\* (?:Update|Add|Delete) File: (.+)/);if(r)return`File: ${r[1].trim()}`}if(d.SHELL_TOOL_NAMES.has(t))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(t)}`}mapToolName(t){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"}[t]||t}parseInput(t){if(t)try{return JSON.parse(t)}catch{return}}static{this.SHELL_TOOL_NAMES=new Set(["exec_command","shell_command","shell","exec","local_shell"])}shouldScheduleApprovalTimeout(t,i){return d.SHELL_TOOL_NAMES.has(t)?i?.sandbox_permissions==="require_escalated":!1}extractFilePath(t,i,s){if(t==="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(t,i,s){if(t==="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 t of this.timers.values())clearTimeout(t);this.timers.clear(),this.pendingCalls.clear(),a.debug("Approval detector cleared")}shutdown(){this.clear(),this.removeAllListeners(),a.info("Approval detector shutdown")}};var Pt=require("child_process"),wt=require("util");var Qe=(0,wt.promisify)(Pt.exec),oe="__CODEVIBE_CODEX_KEY_ESCAPE__",Ee=class{async sendLiteral(e,t){return this.sendTerminalOperation(e,async i=>{await this.sendLiteralViaTmux(i,t)})}async sendKey(e,t){return this.sendTerminalOperation(e,async i=>{await this.sendKeyViaTmux(i,t)})}async sendInput(e,t){a.info("Attempting to send input to Codex",{sessionId:e,input:t});try{let i=process.env.CODEVIBE_CODEX_TMUX_SESSION;return i?(a.info("Using tmux send-keys",{tmuxSession:i}),t===oe?await this.sendKeyViaTmux(i,"Escape"):await this.sendViaTmux(i,t),a.info("Successfully sent input to Codex",{sessionId:e,input:t}),!0):(a.error("No tmux session found - CodeVibe Companion launch is required",{sessionId:e,hint:"Start Codex CLI using `codevibe --agent codex`"}),!1)}catch(i){return a.error("Failed to send input to Codex",{sessionId:e,error:i instanceof Error?i.message:String(i)}),!1}}async sendTerminalOperation(e,t){let i=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!i)return a.error("No tmux session found - CodeVibe Companion launch is required",{sessionId:e,hint:"Start Codex CLI using `codevibe --agent codex`"}),!1;try{return await t(i),!0}catch(s){return a.error("Failed to send terminal input to Codex",{sessionId:e,error:s instanceof Error?s.message:String(s)}),!1}}async sendViaTmux(e,t){a.info("Sending via tmux",{sessionName:e,inputLength:t.length});try{await this.sendLiteralViaTmux(e,t),await this.delay(500);let i=`tmux send-keys -t "${e}" Enter`;await Qe(i),a.info("tmux send-keys completed")}catch(i){throw a.error("tmux send-keys failed",{sessionName:e,error:i}),i}}async sendLiteralViaTmux(e,t){let i=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\$/g,"\\$").replace(/`/g,"\\`"),s=`tmux send-keys -t "${e}" -l "${i}"`;await Qe(s)}async sendKeyViaTmux(e,t){a.info("Sending special key via tmux",{sessionName:e,key:t});try{let i=`tmux send-keys -t "${e}" ${t}`;await Qe(i),a.info("tmux special-key send completed")}catch(i){throw a.error("tmux special-key send failed",{sessionName:e,key:t,error:i}),i}}delay(e){return new Promise(t=>setTimeout(t,e))}isApprovalResponse(e){let t=e.trim().toLowerCase();return["y","n","a","q","e","yes","no"].includes(t)||/^[0-9]+$/.test(t)}};var P=A(require("fs")),_e=A(require("os")),U=A(require("path")),ae=require("crypto"),Et=require("child_process"),Rt=require("events"),_t=require("util");var ue=require("@quantiya/codevibe-core"),We=(0,_t.promisify)(Et.execFile),bt=512*1024,ee="writer.state",Fi=2e3,Ni=10,Di=16*1024*1024,Mi=10080*60*1e3,Re=class extends Rt.EventEmitter{constructor(t={}){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.lastPromptWasMenu=!1;this.lifecycleGeneration=0;this.retainedMirrors=[];this.retainedMirrorContainmentLost=!1;this.maxPaneFileBytes=t.maxPaneFileBytes??Di,this.stalePaneRetentionMs=t.stalePaneRetentionMs??Mi,this.tempDir=t.tempDir??_e.tmpdir(),this.writerPath=U.resolve(__dirname,"..","libexec","pane-mirror-writer.js");let i=t.runtimePlatform??process.platform,s=t.runtimeRelease??_e.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(t){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===t&&this.pipeEnabled){a.debug("Tmux pane observer already started",{sessionName:t});return}this.started&&await this.stop(),this.lifecycleGeneration++,this.sessionName=t,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){a.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}a.info("Tmux pane observer started",{sessionName:t})}async stop(){if(!this.started&&this.pipeFileFd===null)return;this.started=!1,this.lifecycleGeneration++;let t=!1;try{await this.disablePipePane(),t=!0}catch(i){a.error("Failed to confirm tmux pane writer quiescence during stop",{error:i}),this.emit("observer-error",i)}t&&(this.pipeEnabled=!1),this.clearPolling(),t?this.releaseSecureMirror():this.abandonSecureMirror(),a.info("Tmux pane observer stopped",{sessionName:this.sessionName,writerQuiesced:t}),this.resetLifecycleState()}identityOf(t){return{dev:t.dev,ino:t.ino}}identitiesEqual(t,i){return t.dev===i.dev&&t.ino===i.ino}openMirrorFile(t){return P.openSync(t,P.constants.O_RDWR|P.constants.O_CREAT|P.constants.O_EXCL|(P.constants.O_NOFOLLOW??0),384)}truncateMirror(t){P.ftruncateSync(t,0)}createSecureMirror(){P.mkdirSync(this.tempDir,{recursive:!0,mode:448});let t=P.mkdtempSync(U.join(this.tempDir,`codevibe-codex-pane-${process.pid}-`));P.chmodSync(t,448);let i=U.join(t,"pane.log"),s=U.join(t,ee),r=null,n=null;try{r=this.openMirrorFile(i),P.fchmodSync(r,384);let o=P.fstatSync(r);if(!o.isFile())throw new Error("Tmux pane mirror is not a regular file");n=this.openMirrorFile(s),P.fchmodSync(n,384);let l=P.fstatSync(n);if(!l.isFile())throw new Error("Tmux pane writer state is not a regular file");P.writeSync(n,Buffer.from(`idle
|
|
15
|
+
`),0,5,0),this.pipeDirPath=t,this.pipeDirIdentity=this.identityOf(P.lstatSync(t)),this.pipeFilePath=i,this.pipeFileFd=r,this.pipeFileIdentity=this.identityOf(o),this.writerStatePath=s,this.writerStateFd=n,this.writerStateIdentity=this.identityOf(l),r=null,n=null}catch(o){if(r!==null)try{P.closeSync(r)}catch{}if(n!==null)try{P.closeSync(n)}catch{}try{P.unlinkSync(i)}catch{}try{P.unlinkSync(s)}catch{}try{P.rmdirSync(t)}catch{}throw o}}pathMatchesMirrorIdentity(){if(!this.pipeFilePath||!this.pipeFileIdentity)return!1;try{let t=P.lstatSync(this.pipeFilePath);return t.isFile()&&!t.isSymbolicLink()&&this.identitiesEqual(this.pipeFileIdentity,this.identityOf(t))}catch{return!1}}quarantineIfIdentityMatches(t,i){let s=`${t}.reap-${process.pid}-${(0,ae.randomBytes)(6).toString("hex")}`;try{P.renameSync(t,s);let r=P.lstatSync(s);return this.identitiesEqual(i,this.identityOf(r))?s:(P.existsSync(t)||P.renameSync(s,t),null)}catch{return null}}restoreQuarantine(t,i){try{P.existsSync(i)||P.renameSync(t,i)}catch{}}pathMatchesIdentity(t,i){if(!t||!i)return!1;try{let s=P.lstatSync(t);return s.isFile()&&!s.isSymbolicLink()&&this.identitiesEqual(i,this.identityOf(s))}catch{return!1}}closeOwnedDescriptors(){if(this.pipeFileFd!==null)try{P.closeSync(this.pipeFileFd)}catch{}if(this.writerStateFd!==null)try{P.closeSync(this.writerStateFd)}catch{}this.pipeFileFd=null,this.writerStateFd=null}unlinkOwnedFile(t,i){if(!t||!i||!this.pathMatchesIdentity(t,i))return;let s=this.quarantineIfIdentityMatches(t,i);s&&P.unlinkSync(s)}releaseSecureMirror(){let t=this.pipeFilePath,i=this.writerStatePath,s=this.pipeDirPath,r=this.pipeFileIdentity,n=this.writerStateIdentity;this.closeOwnedDescriptors();try{this.unlinkOwnedFile(t,r)}catch{}try{this.unlinkOwnedFile(i,n)}catch{}if(s)try{P.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 t=this.pipeDirPath,i=this.pipeFilePath;t&&this.pipeDirIdentity&&i&&this.pipeFileIdentity&&this.writerStatePath&&this.writerStateIdentity&&this.writerGeneration?this.retainedMirrors.push({dirPath:t,dirIdentity:this.pipeDirIdentity,panePath:i,paneIdentity:this.pipeFileIdentity,statePath:this.writerStatePath,stateIdentity:this.writerStateIdentity,writerGeneration:this.writerGeneration}):(t||i)&&(this.retainedMirrorContainmentLost=!0),this.closeOwnedDescriptors(),a.warn("Retaining bounded tmux pane mirror because writer quiescence is unconfirmed",{retainedDir:t,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(t){let i=!1;try{await this.disablePipePane(),i=!0}catch(s){a.error("Failed to confirm unsafe tmux pane writer quiescence",{disableError:s})}i&&(this.pipeEnabled=!1),this.clearPolling(),a.error("Tmux pane mirror entered fail-closed containment after integrity/cap failure",{error:t,writerQuiesced:i,independentlyBounded:!0}),this.emit("observer-error",t)}resetLastPromptHash(){this.lastPromptHash=null}async captureSnapshot(t=120){if(!this.sessionName)throw new Error("Tmux pane observer is not started");let i=Math.max(1,Math.floor(t));try{let{stdout:s}=await We("tmux",["capture-pane","-p","-e","-J","-S",`-${i}`,"-t",this.sessionName],{timeout:5e3,maxBuffer:2097152});return s}catch(s){throw a.error("Failed to capture tmux pane snapshot",{sessionName:this.sessionName,error:s}),this.emit("observer-error",s),s}}quoteShellArg(t){return`'${t.replace(/'/g,"'\\''")}'`}writerStatePathMatchesIdentity(){return this.pathMatchesIdentity(this.writerStatePath,this.writerStateIdentity)}writeWriterState(t){if(this.writerStateFd===null||!this.writerStateIdentity||!this.writerStatePathMatchesIdentity())throw new Error("Tmux pane writer state identity is not valid");let i=P.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(t,"utf8");P.ftruncateSync(this.writerStateFd,0);let r=0;for(;r<s.length;){let n=P.writeSync(this.writerStateFd,s,r,s.length-r,r);if(n<=0)throw new Error("Short tmux pane writer-state write");r+=n}P.fsyncSync(this.writerStateFd)}readWriterState(){if(this.writerStateFd===null||!this.writerStateIdentity||!this.writerStatePathMatchesIdentity())throw new Error("Tmux pane writer state identity is not valid");let t=P.fstatSync(this.writerStateFd);if(!this.identitiesEqual(this.writerStateIdentity,this.identityOf(t)))throw new Error("Tmux pane writer state descriptor identity changed");let i=Math.min(t.size,512);if(i===0)return"";let s=Buffer.alloc(i),r=P.readSync(this.writerStateFd,s,0,i,0);return s.subarray(0,r).toString("utf8").trim()}async waitForWriterState(t,i,s=Fi){let r=Date.now()+s;do{let n=this.readWriterState();if(i.some(o=>n.startsWith(`${o} ${t} `)))return n;if(Date.now()>=r)return null;await new Promise(o=>setTimeout(o,Ni))}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 t=(0,ae.randomBytes)(16).toString("hex");this.writerGeneration=t,this.writeWriterState(`starting ${t}
|
|
16
|
+
`);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),t,String(this.maxPaneFileBytes)].map(r=>this.quoteShellArg(r)).join(" ");try{await We("tmux",["pipe-pane","-O","-t",this.sessionName,i])}catch(r){throw this.writerGeneration=null,r}let s=await this.waitForWriterState(t,["ready","done"]);if(!s)throw new Error("Tmux pane writer did not confirm startup");if(s.startsWith(`done ${t} `))throw new Error("Tmux pane writer terminated during startup");a.debug("Enabled tmux pipe-pane mirroring",{sessionName:this.sessionName,pipeFilePath:this.pipeFilePath,writerGeneration:t})}async disablePipePane(){let t=this.writerGeneration;if(!this.sessionName||!t)return;let i=null;try{await We("tmux",["pipe-pane","-t",this.sessionName])}catch(n){i=n}if(!t){if(i)throw i;return}if(await this.waitForWriterState(t,["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 t="";try{t=this.readAppendedChunk()}catch(i){a.error("Failed to read bounded tmux pane mirror",{error:i}),await this.failClosedPipe(i);return}await this.rotatePipeFileIfNeeded(),t&&this.queuePromptInspection(t,this.lifecycleGeneration)}while(this.pendingRead)}catch(t){a.error("Failed to process tmux pane changes",{error:t}),this.emit("observer-error",t)}finally{this.processing=!1}}}queuePromptInspection(t,i){this.promptInspectionChain=this.promptInspectionChain.then(async()=>{if(!(!this.started||this.lifecycleGeneration!==i))try{await this.inspectChunkForPrompt(t)}catch(s){a.error("Failed to inspect tmux pane delta",{error:s}),this.emit("observer-error",s)}})}async inspectChunkForPrompt(t){if(!this.lastPromptHash&&!this.looksLikePromptDelta(t))return;let i=await this.captureSnapshot();this.inspectSnapshotForPrompt(i,t)}inspectSnapshotForPrompt(t,i){let s=t?this.extractActivePromptBlock(t):null;if(!s){if(this.lastPromptHash){let n=this.lastPromptHash;this.lastPromptHash=null,this.lastPromptWasMenu=!1,this.emit("prompt-cleared",{promptHash:n})}t&&a.debug("tmux delta cue matched but no active dialog isolated (no candidate emitted)",{snapshotTail:t.split(`
|
|
17
|
+
`).slice(-6).join("\\n")});return}let r=this.hashPromptSnapshot(s);r!==this.lastPromptHash&&(this.lastPromptHash&&(this.lastPromptWasMenu||(0,ue.parseActiveTerminalMenu)(s))&&this.emit("prompt-cleared",{promptHash:this.lastPromptHash}),this.lastPromptHash=r,this.lastPromptWasMenu=!!(0,ue.parseActiveTerminalMenu)(s),this.emit("prompt-candidate",{rawDelta:i,snapshot:s,promptHash:r,detectedAt:Date.now()}))}queueCurrentSnapshotInspection(t){this.promptInspectionChain=this.promptInspectionChain.then(async()=>{if(!(!this.started||this.lifecycleGeneration!==t))try{let i=await this.captureSnapshot();this.inspectSnapshotForPrompt(i,"")}catch(i){a.error("Failed to inspect tmux pane snapshot after rotation",{error:i}),this.emit("observer-error",i)}})}async rotatePipeFileIfNeeded(){let t=this.pipeFilePath,i=this.pipeFileFd,s=this.pipeFileIdentity,r=this.sessionName,n=this.lifecycleGeneration;if(!t||i===null||!s||!r||!this.started)return;let o;try{let p=P.fstatSync(i);if(!this.identitiesEqual(s,this.identityOf(p)))throw new Error("Tmux pane mirror descriptor identity changed");o=p.size}catch(p){await this.failClosedPipe(p);return}if(o<this.maxPaneFileBytes)return;let l="";try{await this.disablePipePane(),this.pipeEnabled=!1}catch(p){a.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!==t)){try{l=this.readAppendedChunk()}catch(p){a.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=P.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){a.error("Tmux pane mirror remains disabled after truncation verification failure",{error:p}),this.emit("observer-error",p),this.clearPolling();return}if(this.filePosition=0,a.info("Rotated bounded tmux pane mirror",{sessionName:r,priorBytes:o,maxBytes:this.maxPaneFileBytes}),this.started&&this.lifecycleGeneration===n&&this.pipeFilePath===t&&this.sessionName===r)try{await this.enablePipePane(),this.pipeEnabled=!0}catch(p){this.pipeEnabled=!1,a.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(t,i,s){try{let r=P.lstatSync(t);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(t,i){let s=null;try{s=P.openSync(t,P.constants.O_RDONLY|(P.constants.O_NOFOLLOW??0));let r=P.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),o=r.size===0?0:P.readSync(s,n,0,r.size,0);return n.subarray(0,o).toString("utf8").trim()}catch{return null}finally{if(s!==null)try{P.closeSync(s)}catch{}}}reapOwnedRetainedMirror(t){if(!this.retainedPathMatchesIdentity(t.dirPath,t.dirIdentity,"directory"))return!1;let i;try{i=P.readdirSync(t.dirPath).sort()}catch{return!1}if(i.length!==2||i[0]!=="pane.log"||i[1]!==ee||!this.retainedPathMatchesIdentity(t.panePath,t.paneIdentity,"file")||!this.retainedPathMatchesIdentity(t.statePath,t.stateIdentity,"file"))return!1;let s=new RegExp(`^done ${t.writerGeneration} \\d+ \\d+$`);if(!s.test(this.readRetainedWriterState(t.statePath,t.stateIdentity)??""))return!1;let r=this.quarantineIfIdentityMatches(t.dirPath,t.dirIdentity);if(!r)return!1;let n=!1;try{let o=U.join(r,"pane.log"),l=U.join(r,ee);if(!this.retainedPathMatchesIdentity(o,t.paneIdentity,"file"))throw new Error("pane identity changed");if(!this.retainedPathMatchesIdentity(l,t.stateIdentity,"file"))throw new Error("state identity changed");if(!s.test(this.readRetainedWriterState(l,t.stateIdentity)??""))throw new Error("writer generation is no longer done");if(this.unlinkOwnedFile(o,t.paneIdentity),this.unlinkOwnedFile(l,t.stateIdentity),P.existsSync(o)||P.existsSync(l))throw new Error("retained mirror unlink was incomplete");P.rmdirSync(r),n=!0,a.info("Removed completed same-owner tmux pane mirror",{retainedDir:t.dirPath})}catch{P.existsSync(r)&&this.restoreQuarantine(r,t.dirPath)}return n}reapOwnedRetainedMirrors(){this.retainedMirrors=this.retainedMirrors.filter(t=>!this.reapOwnedRetainedMirror(t))}cleanupStalePipeFiles(){let t=Date.now()-this.stalePaneRetentionMs,i;try{i=P.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=U.join(this.tempDir,s.name),c=null;try{let u=P.lstatSync(p);if(!u.isFile()||u.isSymbolicLink()||u.mtimeMs>t||typeof process.getuid=="function"&&u.uid!==process.getuid()||this.isProcessAlive(Number(r[1]))||(c=this.quarantineIfIdentityMatches(p,this.identityOf(u)),!c))continue;P.unlinkSync(c),c=null,a.info("Removed stale legacy tmux pane mirror",{candidate:p,ageMs:Date.now()-u.mtimeMs})}catch{c&&this.restoreQuarantine(c,p)}continue}let n=/^codevibe-codex-pane-(\d+)-[A-Za-z0-9_-]+$/.exec(s.name);if(!n||!s.isDirectory())continue;let o=U.join(this.tempDir,s.name),l=null;try{let p=P.lstatSync(o);if(!p.isDirectory()||p.isSymbolicLink()||p.mtimeMs>t||typeof process.getuid=="function"&&p.uid!==process.getuid())continue;let c=Number(n[1]);if(this.isProcessAlive(c)||(l=this.quarantineIfIdentityMatches(o,this.identityOf(p)),!l))continue;let u=U.join(l,"pane.log"),h=U.join(l,ee),g=P.readdirSync(l);if(g.some(f=>f!=="pane.log"&&f!==ee)){this.restoreQuarantine(l,o);continue}for(let f of g.map(y=>U.join(l,y))){let y=P.lstatSync(f);if(!y.isFile()||y.isSymbolicLink()||typeof process.getuid=="function"&&y.uid!==process.getuid()){this.restoreQuarantine(l,o),l=null;break}}if(!l)continue;if(g.includes(ee)){let f=P.readFileSync(h,"utf8").trim(),y=/^ready [a-f0-9]{32} (\d+)$/.exec(f);if(!(f==="idle"||/^done [a-f0-9]{32} \d+ \d+$/.test(f)||!!y)||y&&this.isProcessAlive(Number(y[1]))){this.restoreQuarantine(l,o);continue}}g.includes("pane.log")&&P.unlinkSync(u),g.includes(ee)&&P.unlinkSync(h),P.rmdirSync(l),l=null,a.info("Removed stale tmux pane mirror directory",{candidate:o,ageMs:Date.now()-p.mtimeMs})}catch{l&&this.restoreQuarantine(l,o)}}}isProcessAlive(t){try{return process.kill(t,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 t=P.fstatSync(this.pipeFileFd);if(!this.identitiesEqual(this.pipeFileIdentity,this.identityOf(t)))throw new Error("Tmux pane mirror descriptor identity changed");if(t.size<=this.filePosition)return"";{let s=t.size-this.filePosition>bt?t.size-bt:this.filePosition,r=t.size-s,n=Buffer.alloc(r),o=0;for(;o<r;){let l=P.readSync(this.pipeFileFd,n,o,r-o,s+o);if(l===0)break;o+=l}return this.filePosition=s+o,n.subarray(0,o).toString("utf-8")}}looksLikePromptDelta(t){return/Would you like to run/i.test(t)||/[>›❯▸▶]\s*[1-9]\d?\.\s/.test(t)||/\x1b\[[0-9;]*m[^\n]{0,80}[1-9]\d?\.\s/.test(t)||/Press enter to confirm/i.test(t)||/enter to (?:submit|confirm|select|continue)/i.test(t)||/\besc to cancel\b/i.test(t)||/\bYes,\s+proceed\b/i.test(t)||/\bNo,\s+and tell Codex\b/i.test(t)||/don't ask again/i.test(t)||/Requesting permission for:|Do you want to proceed\?/i.test(t)||/\[(?:y\/n|Y\/n|y\/N)\]|\b(?:apply|approve|allow|reject|deny|continue)\b/i.test(t)}looksLikePromptSnapshot(t){return this.extractActivePromptBlock(t)!==null}extractActivePromptBlock(t){return this.extractActiveApprovalBlock(t)??(0,ue.parseActiveTerminalMenu)(t)?.snapshot??null}extractActiveApprovalBlock(t){let s=t.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"").split(`
|
|
18
|
+
`).map(f=>f.replace(/\s+$/,"")),r=f=>f.trim().length>0,n=f=>{let y=f.trim();return/^(?:[>›❯]\s*)?press enter to confirm(?: or esc to cancel)?$/i.test(y)||/^(?:[>›❯]\s*)?(?:press )?esc to cancel$/i.test(y)},o=f=>/Would you like to |Do you want to |The model would like to |Allow .+ to run|Requesting permission for:/i.test(f),l=f=>/^[>›❯\s]*[1-9][.)]\s+\S/.test(f),p=f=>/\[(?:y\/n|Y\/n|y\/N)\]/i.test(f),c=f=>{let y=new Set;for(let I of f)l(I)&&(/\bYes,\s+proceed\b/i.test(I)&&y.add("proceed"),/\bNo,\s+and tell Codex\b/i.test(I)&&y.add("reject"),/don't ask again/i.test(I)&&y.add("dont-ask"));return y.size},u=f=>l(f)&&(/\bYes,\s+proceed\b/i.test(f)||/\bNo,\s+and tell Codex\b/i.test(f)||/don't ask again/i.test(f)),h=-1;for(let f=s.length-1;f>=0;f--)if(r(s[f])){h=f;break}if(h===-1)return null;if(p(s[h])){let f=h;for(let y=h-1;y>=0&&h-y<=8&&!(!r(s[y])||n(s[y])||l(s[y]));y--)f=y;return s.slice(f,h+1).join(`
|
|
19
|
+
`)}let g=-1;for(let f=s.length-1;f>=0;f--)if(n(s[f])){g=f;break}if(g===h){let f=-1;for(let I=g-1;I>=0&&!n(s[I]);I--)if(o(s[I])){f=I;break}if(f===-1)return null;let y=s.slice(f,g+1);return y.some(l)?y.join(`
|
|
20
|
+
`):null}if(u(s[h])){let f=-1;for(let v=h-1;v>=0;v--){if(n(s[v]))return null;if(o(s[v])){f=v;break}}if(f===-1)return null;let y=v=>{let w=v.match(/^[>›❯\s]*([1-9])[.)]\s/);return w?parseInt(w[1],10):null},I=[],S=Number.POSITIVE_INFINITY;for(let v=h;v>f&&l(s[v]);v--){let w=y(s[v]);if(w===null||w>=S)break;I.push(s[v]),S=w}return c(I)<2?null:s.slice(f,h+1).join(`
|
|
21
|
+
`)}return null}hashPromptSnapshot(t){let i=(0,ue.parseActiveTerminalMenu)(t);if(i)return(0,ae.createHash)("sha256").update(i.identity).digest("hex");let s=t.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"").replace(/\r/g,`
|
|
22
22
|
`).replace(/[ \t]+\n/g,`
|
|
23
|
-
`).trim();return(0,
|
|
24
|
-
`;if(Buffer.byteLength(i,"utf8")>
|
|
25
|
-
${
|
|
26
|
-
`),
|
|
27
|
-
`).map(r=>r.trim()).filter(Boolean);return s.length<2||!i.test(s[s.length-1])||!
|
|
28
|
-
`).map(o=>o.trim()),i=new RegExp(`^(?:[>\u203A\u276F\u25B8\u25B6\u279C\u27A4*\u25CF]\\s*)?${t}\\.\\s+(.*)$`),s=-1,r="";for(let o=e.length-1;o>=0;o-=1){let c=e[o].match(i);if(c){s=o,r=c[1];break}}if(s<0)return null;let n=[r];for(let o=s+1;o<e.length&&!(/^(?:[>›❯▸▶➜➤*●]\s*)?\d+\.\s+/.test(e[o])||!e[o]||(n.push(e[o]),/\(p\)\s*$/i.test(e[o])));o+=1);return n.some(o=>/\(p\)\s*$/i.test(o))?n:null}function Qt(a){if(a.length===0||a.length>13)return new Set;let t=new Set([a[0]]);for(let e of a.slice(1)){let i=new Set;for(let s of t)i.add(`${s}${e}`),i.add(`${s} ${e}`);t=i}return t}function Je(a){try{let t=(0,Ze.parse)(a,e=>`\${${e}}`);return t.every(e=>typeof e=="string")?t:null}catch{return null}}function ds(a){return a.map(t=>/^[A-Za-z0-9_@%+=:,./-]+$/.test(t)?t:`'${t.replace(/'/g,`'"'"'`)}'`).join(" ")}function ps(a,t){if(a.length===0)return!1;let e;try{e=(0,Ze.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=>a.every((r,n)=>s[n]===r))}var Ae=class a{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 Map;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.nativeSourceSelection=null;this.nativeSourceOwners=new Map;this.nativeSourceRetryTimer=null;this.hookEventChain=Promise.resolve();this.hooksActive=!1;this.hooksCompatibilityNoticeSent=!1;this.permissionRequestHookInFlight=null;this.queuedPermissionRequestDedupeKeys=new Map;this.queuedPermissionRequestSessionCounts=new Map;this.queuedPermissionRequestRegistrations=new Map;this.waitingPermissionRequests=new Map;this.permissionRequestOccurrencesByCompletionKey=new Map;this.deferredTmuxPromptCandidates=new Map;this.recoveryPermissionReplay=null;this.resolvedApprovalDedupeKeys=new Map;this.subscribedSessionId=null;this.subscribedSessionState=null;this.terminalInputChain=Promise.resolve();this.terminalInputBlockedStates=new WeakSet;this.mobilePromptDeduper=new be({expiryMs:1e4});this.launchSessionInitPromise=null;this.sessionStartedInitPromise=null;this.bootstrapSessionId=null;this.recoveryBootstrapOwnerBound=!1;this.resumeBackendSession=h.resumeOrCreateSession;this.sessionBootstrapFailureCount=0;this.sessionBootstrapRetryAt=0;this.retiredSessionRecoveryPromise=null;this.lifecycleGeneration=0;this.isStopping=!1;this.stopPromise=null;this.terminalRetirementRequested=!1;this.teardownStepsTimedOut=[];this.retirementOwed=!1;this.tmuxLifecycleTimer=null;this.tmuxLifecycleCheckInFlight=!1;this.tmuxLifecycleObservedAlive=!1;this.tmuxLifecycleInitDeadlineMs=Number.POSITIVE_INFINITY;this.v1Bridge=new Re;this.orchestrationClient=null;this.userDecisionUnsubscribe=null;this.httpApi=new Ie,this.sessionWatcher=new fe({restoreCursor:(t,e)=>this.retryNativeAdmission(()=>this.restoreNativeSource(t,e)),beforeGap:(t,e)=>this.retryNativeAdmission(()=>this.admitNativeSourceGap(t,e)),beforeEntry:(t,e)=>this.retryNativeAdmission(()=>this.admitNativeSourceEntry(t,e))}),this.approvalDetector=new ve,this.promptResponder=new Se,this.tmuxPaneObserver=new Pe,this.e1DurableState=new Te({handoffRoot:process.env.CODEVIBE_CODEX_HANDOFF_ROOT,resolutionRoot:process.env.CODEVIBE_CODEX_E1_OUTBOX_ROOT})}static{this.E1_TTL_REFRESH_MS=300*1e3}async start(){if(l.info("Starting CodeVibe Codex companion server",{environment:(0,h.getEnvironment)()}),this.appSyncClient=new h.AppSyncClient,!await this.appSyncClient.authenticateWithStoredTokens()){let i=(0,h.describeStoredAuthFailure)(this.appSyncClient.getLastAuthFailureKind(),this.appSyncClient.getLastAuthFailureDetail());l.error("Authentication with stored credentials failed",{kind:this.appSyncClient.getLastAuthFailureKind(),exitCode:i.exitCode}),console.error(i.message),process.exit(i.exitCode)}l.info("Authenticated successfully",{userId:this.appSyncClient.getCurrentUserId(),email:this.appSyncClient.getCurrentUserEmail()});try{let i=this.appSyncClient.getCurrentUserId(),s=AbortSignal.timeout(5e3),r=new Promise((c,d)=>s.addEventListener("abort",()=>d(new Error("status read timed out")),{once:!0})),n=await Promise.race([this.appSyncClient.getSubscriptionStatus(s),r]);if(this.appSyncClient.getCurrentUserId()!==i)throw new Error("account changed during read");let o=await Promise.race([this.appSyncClient.getCompanionSyncState(s),r]);if(this.appSyncClient.getCurrentUserId()!==i)throw new Error("account changed during read");if(n.tier!==o.tier)throw new Error("tier changed during read");l.info("Standalone Companion sync status",{tier:o.tier,protocol:o.protocol,syncState:o.usage?.syncState??null,resetAtEpochMs:o.resetAtEpochMs})}catch{l.warn("Standalone Companion sync status unavailable; cloud admission remains authoritative")}await this.restorePendingE1ResolutionsFromOutbox(),await(0,h.registerDeviceEncryptionKey)(this.appSyncClient,l),(0,h.startDeviceKeyWatcher)(this.appSyncClient,l),(0,h.pushDetectedAgents)(this.appSyncClient,l).catch(i=>{l.warn("Failed to update available agents (non-fatal)",{error:i?.message})});try{let i=await this.appSyncClient.sweepOrphanSessions({agentType:"CODEX"});i>0&&l.info("Orphan sweep: marked stale Codex sessions INACTIVE",{swept:i})}catch(i){l.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();l.info("HTTP API started for hooks",{port:e}),this.startTmuxLifecycleMonitor(),await this.createLaunchSession(),this.setupEventHandlers(),this.sessionWatcher.start(),l.info("CodeVibe Codex companion server started")}async createLaunchSession(){if(this.isStopping)return;if(process.env[Oe]==="1"){l.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){l.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();l.info("Creating launch session",{sessionId:r,projectPath:s});let o=!1;try{let c=await(0,h.resumeOrCreateSession)({sessionId:r,userId:n,agentType:h.AgentType.CODEX,projectPath:s,metadata:{launchSession:!0}},this.appSyncClient,l);if(r=c.sessionId,!this.isLifecycleCurrent(t)){await this.retireCancelledBootstrap(r,"launch_session");return}this.sessionKey=c.sessionKey,this.sessionKeyGen=c.sessionKeyGen,this.sessionIsEncrypted=!!c.sessionKey,o=!0,this.sessionState={sessionId:r,userId:n,projectPath:s,cwd:s,createdAt:new Date,subscriptionActive:!1,metadata:{launchSession:!0},encryptionSnapshot:{sessionKey:c.sessionKey,sessionIsEncrypted:!!c.sessionKey},codexSessionId:e,codexLogFile:void 0},this.clearSessionBootstrapFailure(),this.bootstrapSessionId=null,await x("daemon_init_step_completed",{step:"session_resume_or_create",path:"launch_session"})}catch(c){if(!this.isLifecycleCurrent(t)){let d=this.authoritativeSessionIdFromError(c)??r;await this.retireCancelledBootstrap(d,"launch_session_error");return}await x("daemon_init_step_failed",{step:"session_resume_or_create",path:"launch_session",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,"launch_session"),l.error("Failed to create/resume launch session (non-fatal)",{error:c})}if(!o)return;await x("daemon_init_step_completed",{step:"session_state_set",path:"launch_session"});try{this.subscribeToMobileEvents(r)?await x("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"launch_session"}):await x("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(c){await x("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:c?.name||"Error",error_message:c?.message||String(c)}),l.error("Failed to subscribe to mobile events for launch session",{error:c})}try{await this.appSyncClient.startHeartbeat(r)?await x("daemon_init_step_completed",{step:"heartbeat_start",path:"launch_session"}):(await x("daemon_init_step_failed",{step:"heartbeat_start",path:"launch_session",error_class:"InitialHeartbeatNotPersisted",error_message:"Backend did not confirm the initial heartbeat mutation"}),l.error("Initial launch-session heartbeat was not persisted",{sessionId:r}))}catch(c){await x("daemon_init_step_failed",{step:"heartbeat_start",path:"launch_session",error_class:c?.name||"Error",error_message:c?.message||String(c)}),l.error("Failed to start heartbeat for launch session",{error:c})}try{await this.subscribeToOnApplyUserDecision(r)}catch(c){l.error("Failed to subscribe to onApplyUserDecision for launch session (non-fatal)",{error:c})}this.startMobileEndWatcher(r),l.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 l.warn("Dropping event from stale or unresolved session generation (#638)",{type:i,sessionId:s,currentSessionId:r?.sessionId}),null;let{sessionKey:n,sessionIsEncrypted:o}=r.encryptionSnapshot,c=(0,h.encryptForEmit)(n,o,t,e);return c===null&&l.error("No session key for ENCRYPTED session \u2014 dropping event (fail-closed, #638)",{type:i,sessionId:s}),c}newE1Raise(t,e,i,s){let{record:r}=(0,h.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?.completionKey!==void 0?{resolutionCompletionKey:s.completionKey}:{},...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,i){return this.publishE1Prompt(t,e,h.EventType.NOTIFICATION,"\u26A0\uFE0F A prompt is waiting in your desktop terminal, but its options could not be shown here. Please answer it on your desktop.",{e1SuppressedPrompt:!0},i)}publishE1Prompt(t,e,i,s,r,n){let o=(0,h.prepareEventTimestamp)({orderingKey:t}),c={sessionId:t,type:i,source:h.EventSource.DESKTOP,content:s,metadata:r,...(0,h.raiseFieldsFromRecord)(e),timestamp:o},d=this.e1PromptRaises.get(e.promptId),p=()=>d?.record===e&&(0,h.isOpenPromptRaise)(d,this.e1PromptRaises.get(e.promptId));if(!p())return Promise.resolve("CLOSED");let u=f=>(p()&&(f==="RETRY"?this.e1NeedsReRaise.add(e.promptId):(f==="RERAISED"||f==="OMITTED")&&this.e1NeedsReRaise.delete(e.promptId)),f);return this.trackE1Raise(e.promptId,this.appSyncClient.publishCompanionPrompt(c,async()=>{let f=this.encryptForEmit(s,r,i,t);return f?(await this.appSyncClient.createEvent({...c,content:f.content,metadata:f.metadata,...i===h.EventType.NOTIFICATION&&{notificationText:s},...f.isEncrypted?{isEncrypted:!0}:{}}),!0):!1},{reRaiseToken:n}).then(u,f=>{throw u("RETRY"),f}))}raiseSuppressedBadge(t,e,i={}){if(e){if(this.hasRecentlyResolvedApprovalDedupeKey(t,e)){l.debug("Skipping suppressed-prompt carrier; approval completed while producer was in flight",{sessionId:t,dedupeKey:e});return}let r=`${t}::${e}`,n=this.e1ContentKeyIndex.get(r);if(n&&this.e1PromptRaises.has(n)){if(i.suppressTmuxObserverUntilResolved){let o=this.e1PromptRaises.get(n);o&&(o.suppressTmuxObserverUntilResolved=!0,i.observerSnapshot&&(o.suppressedObserverSnapshotKey=this.buildObserverSnapshotMatchKey(i.observerSnapshot)))}return}n&&this.e1ContentKeyIndex.delete(r)}let s=this.newE1Raise(t,!1,void 0,e?{dedupeKey:e,completionKey:i.completionKey}:void 0);if(i.suppressTmuxObserverUntilResolved){let r=this.e1PromptRaises.get(s.promptId);r&&(r.suppressTmuxObserverUntilResolved=!0,i.observerSnapshot&&(r.suppressedObserverSnapshotKey=this.buildObserverSnapshotMatchKey(i.observerSnapshot)))}e&&this.e1ContentKeyIndex.set(`${t}::${e}`,s.promptId),this.emitSuppressedPromptCarrier(t,s).catch(r=>{l.error("E1: failed to emit suppressed-prompt badge carrier",{sessionId:t,promptId:s.promptId,error:r instanceof Error?r.message:String(r)})})}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.resolutionCompletionKey!==void 0&&{resolutionCompletionKey:e.resolutionCompletionKey},...e.resolutionCallId!==void 0&&{resolutionCallId:e.resolutionCallId},...e.suppressTmuxObserverUntilResolved!==void 0&&{suppressTmuxObserverUntilResolved:e.suppressTmuxObserverUntilResolved},...e.suppressedObserverSnapshotKey!==void 0&&{suppressedObserverSnapshotKey:e.suppressedObserverSnapshotKey}}))}buildDaemonHandoffSnapshot(t){let e=process.env[j];if(!e)throw new Error("E1_DAEMON_HANDOFF_MISSING_TMUX_SESSION");return{version:1,createdAtMs:Date.now(),tmuxSession:e,backendSessionId:t.sessionId,openRaises:this.snapshotOpenE1(t.sessionId),pendingResolutions:[...this.e1PendingResolutions.values()].map(i=>({record:{...i.record},resolutionAt:i.resolutionAt,attempts:i.attempts})),needsReRaisePromptIds:[...this.e1NeedsReRaise],permissionOccurrences:[...this.permissionRequestOccurrencesByCompletionKey.entries()].map(([i,s])=>[i,s.map(r=>({...r}))]),waitingPermissionRequests:[...this.waitingPermissionRequests.values()].filter(i=>i.ownerState===t).map(({occurrenceKey:i,dedupeKey:s,payload:r})=>({occurrenceKey:i,dedupeKey:s,payload:r})),pendingInteractivePrompt:this.pendingInteractivePrompt?{...this.pendingInteractivePrompt}:null,queuedInteractivePrompts:this.queuedInteractivePrompts.map(i=>({prompt:{...i.prompt},content:i.content,metadata:{...i.metadata}})),resolvedApprovalDedupeKeys:[...this.resolvedApprovalDedupeKeys.entries()].filter(([,i])=>i>Date.now()-Ye)}}persistDaemonHandoffState(t){for(let i of this.e1PendingResolutions.values())this.e1DurableState.writeResolution(i);let e=this.buildDaemonHandoffSnapshot(t);this.e1DurableState.writeHandoff(e),l.info("E1: persisted daemon handoff state",{sessionId:t.sessionId,openPrompts:e.openRaises.length,pendingResolutions:e.pendingResolutions.length,completionQueues:e.permissionOccurrences.length})}async adoptDaemonHandoffState(t){if(process.env[Oe]!=="1")return!1;let e=process.env[j];if(!e)return!1;let i=this.e1DurableState.readHandoff(e);if(!i)return!1;let s=this.sessionState;if(!s||s.sessionId!==t)throw new Error("E1_DAEMON_HANDOFF_WITHOUT_CURRENT_SESSION");for(let c of i.pendingResolutions)this.e1PendingResolutions.has(c.record.promptId)||this.e1PendingResolutions.set(c.record.promptId,{record:{...c.record},resolutionAt:c.resolutionAt,attempts:c.attempts}),this.e1DurableState.writeResolution(c);for(let c of i.openRaises){let d={...c,record:{...c.record},...c.metadataPlain!==void 0&&{metadataPlain:{...c.metadataPlain}}};this.e1PromptRaises.set(d.record.promptId,d),i.backendSessionId!==t&&this.e1RetirementOrphans.set(d.record.promptId,{...d,record:{...d.record}}),d.resolutionDedupeKey&&this.e1ContentKeyIndex.set(`${t}::${d.resolutionDedupeKey}`,d.record.promptId)}this.permissionRequestOccurrencesByCompletionKey=new Map(i.permissionOccurrences.map(([c,d])=>[c,d.map(p=>({...p}))])),this.e1NeedsReRaise=new Set(i.needsReRaisePromptIds);for(let c of i.waitingPermissionRequests??[])this.waitingPermissionRequests.set(c.occurrenceKey,{...c,ownerState:s,context:this.buildApprovalPromptContextFromHookPayload(c.payload)});this.pendingInteractivePrompt=i.pendingInteractivePrompt?{...i.pendingInteractivePrompt,ownerSessionId:t}:null;let r=this.pendingInteractivePrompt,n=r?.completionKey?this.permissionRequestOccurrencesByCompletionKey.get(r.completionKey):void 0;this.recoveryPermissionReplay=r?.source==="permission_hook"&&r.completionKey&&r.dedupeKey&&this.isPermissionRequestOccurrenceKey(r.dedupeKey)&&n?.some(c=>c.occurrenceKey===r.dedupeKey)?{ownerSessionId:t,completionKey:r.completionKey,occurrenceKey:r.dedupeKey}:null,this.queuedInteractivePrompts=i.queuedInteractivePrompts.map(c=>({prompt:{...c.prompt,ownerSessionId:t},content:c.content,metadata:{...c.metadata},ownerState:s}));let o=Date.now()-Ye;for(let[c,d]of i.resolvedApprovalDedupeKeys){if(d<=o)continue;let p=`${i.backendSessionId}::`,u=c.startsWith(p)?`${t}::${c.slice(p.length)}`:c;this.resolvedApprovalDedupeKeys.set(u,d)}return i.backendSessionId!==t&&await this.drainRetirementOrphans(t),await this.drainPendingE1Resolutions(),await this.drainPendingE1ReRaises(),(this.e1PromptRaises.size>0||this.e1PendingResolutions.size>0)&&this.startE1TtlRefresh(),this.e1DurableState.removeHandoff(e),l.info("E1: adopted daemon handoff state",{fromSessionId:i.backendSessionId,replacementSessionId:t,openPrompts:i.openRaises.length,pendingResolutions:i.pendingResolutions.length,completionQueues:i.permissionOccurrences.length}),!0}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}l.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.resolutionCompletionKey!==void 0&&{resolutionCompletionKey:i.resolutionCompletionKey},...i.resolutionCallId!==void 0&&{resolutionCallId:i.resolutionCallId}};for(let[o,c]of this.e1ContentKeyIndex.entries())c===e&&this.e1ContentKeyIndex.delete(o);r.record.sessionId=t,this.e1PromptRaises.set(e,r),r.resolutionDedupeKey&&this.e1ContentKeyIndex.set(`${t}::${r.resolutionDedupeKey}`,e);let n=await this.reRaiseOneE1(t,r,{untilAck:!0});if(n!=="RERAISED"&&n!=="OMITTED"){if(!this.e1RetirementOrphans.has(e))continue;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;if(!(0,h.canRecoverPromptRaise)(e,this.e1RaiseInFlight.has(s.promptId)))return"RETRY";let r=s.mobileActionable&&e.contentPlain!==void 0,n=i?.untilAck??!1,o=4,c=4e3;for(let d=1;n||d<=o;d++){if(!(0,h.isOpenPromptRaise)(e,this.e1PromptRaises.get(s.promptId)))return"CLOSED";if(n&&!this.isReRaiseTargetCurrent(t))return this.e1NeedsReRaise.add(s.promptId),l.warn("E1: retirement re-raise aborted (stopping/superseded) \u2014 parked",{sessionId:t,promptId:s.promptId}),"RETRY";try{let p;return r?p=await this.publishE1Prompt(t,s,h.EventType.INTERACTIVE_PROMPT,e.contentPlain,e.metadataPlain??{},i?.reRaiseToken):(s.mobileActionable=!1,p=await this.emitSuppressedPromptCarrier(t,s,i?.reRaiseToken)),p==="RETRY"||p==="CLOSED"||(this.e1NeedsReRaise.delete(s.promptId),l.info("E1: prompt publication settled",{sessionId:t,promptId:s.promptId,actionable:r,disposition:p})),p}catch(p){if(!n&&d===o)return this.e1NeedsReRaise.add(s.promptId),l.error("E1: re-raise unacked after backoff \u2014 parked for retry-until-ack",{sessionId:t,promptId:s.promptId,error:p instanceof Error?p.message:String(p)}),"RETRY";if(n){let u=Date.now()+Math.min(250*2**(d-1),c);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*d))}}return"RETRY"}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.e1ResolutionInFlight.get(t);if(e)return e;if(!this.e1PendingResolutions.has(t))return;let i=(async()=>{let s=this.e1PendingResolutions.get(t);if(s){try{this.e1DurableState.writeResolution(s)}catch(r){l.error("E1: failed to persist exact-clear outbox record",{promptId:t,error:r instanceof Error?r.message:String(r)})}try{let r=this.e1RaiseInFlight.get(t);if(r&&await r,s=this.e1PendingResolutions.get(t),!s)return;if(!await this.appSyncClient.resolveCompanionPrompt({sessionId:s.record.sessionId,promptId:s.record.promptId,ownerToken:s.record.ownerToken,resolutionAt:s.resolutionAt}))throw new Error("E1_PLUGIN_RESOLUTION_NOT_ACKNOWLEDGED: exact prompt id was not returned");this.e1PendingResolutions.delete(t);try{this.e1DurableState.removeResolution(t)}catch(o){l.warn("E1: exact-clear ACKed but outbox cleanup failed",{promptId:t,error:o instanceof Error?o.message:String(o)})}l.info("E1: plugin approval resolution acknowledged",{sessionId:s.record.sessionId,promptId:t})}catch(r){let n=this.e1PendingResolutions.get(t);l.warn("E1: plugin approval resolution unacknowledged; parked for retry",{sessionId:n?.record.sessionId,promptId:t,error:r instanceof Error?r.message:String(r)})}}})();this.e1ResolutionInFlight.set(t,i);try{await i}finally{this.e1ResolutionInFlight.get(t)===i&&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)}async restorePendingE1ResolutionsFromOutbox(){let{records:t,rejected:e}=this.e1DurableState.readResolutions();for(let i of e)l.error("E1: rejected unsafe or invalid resolution outbox record",i);for(let i of t){let s=this.e1PendingResolutions.get(i.record.promptId);(!s||i.attempts>s.attempts)&&this.e1PendingResolutions.set(i.record.promptId,{record:{...i.record},resolutionAt:i.resolutionAt,attempts:i.attempts})}t.length>0&&(l.info("E1: recovered pending exact-clear outbox records",{count:t.length}),await this.drainPendingE1Resolutions(),this.e1PendingResolutions.size>0&&!this.e1TtlRefreshTimer&&this.startE1TtlRefresh())}async drainPendingE1ResolutionsForLifecycleEnd(t={}){let e=t.maxWaitMs??4e3,i=t.retryDelayMs??250,s=Date.now()+Math.max(0,e),r=0;do{if(await this.drainPendingE1Resolutions(),this.e1PendingResolutions.size===0)return;if(r+=1,Date.now()>=s)break;await new Promise(n=>setTimeout(n,Math.min(i*r,Math.max(0,s-Date.now()))))}while(Date.now()<s);for(let n of this.e1PendingResolutions.values())this.e1DurableState.writeResolution(n);l.warn("E1: graceful lifecycle ended with durable exact-clear work pending",{count:this.e1PendingResolutions.size})}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 exactClearOpenE1ForLifecycleEnd(t){let e=[...this.e1PromptRaises.values()].filter(s=>s.record.sessionId===t).map(s=>s.record.promptId),i=this.beginE1PromptResolutions(e,t);await Promise.all(i.map(s=>this.emitE1Resolution(s)))}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&&(0,h.canRecoverPromptRaise)(i,this.e1RaiseInFlight.has(i.record.promptId))).map(i=>i.record.promptId);if(e.length!==0)try{await this.appSyncClient.refreshSessionOpenPromptTtl({sessionId:t,promptIds:e},async(i,s)=>{let r=this.e1PromptRaises.get(i);return!r||r.record.sessionId!==t||this.sessionState?.sessionId!==t?"CLOSED":this.reRaiseOneE1(t,r,{reRaiseToken:s})})}catch(i){l.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()},a.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,i){if(!this.isExpectedSessionStateCurrent(t)||this.terminalInputBlockedStates.has(t))return Promise.resolve(!1);let s=this.terminalInputChain.then(async()=>!this.isExpectedSessionStateCurrent(t)||this.terminalInputBlockedStates.has(t)||!await this.verifyNoActiveCodexChooser(t.sessionId)||i&&(await i(),!this.isExpectedSessionStateCurrent(t)||!await this.verifyNoActiveCodexChooser(t.sessionId)||!this.isExpectedSessionStateCurrent(t))||!await this.promptResponder.sendLiteral(t.sessionId,e)||(await new Promise(r=>setTimeout(r,500)),!this.isExpectedSessionStateCurrent(t))||!await this.verifyNoActiveCodexChooser(t.sessionId)?!1:this.promptResponder.sendKey(t.sessionId,"Enter"));return this.terminalInputChain=s.then(()=>{},()=>{}),s}async verifyNoActiveCodexChooser(t){try{let e=await this.tmuxPaneObserver.captureSnapshot();return!this.tmuxPaneObserver.extractActivePromptBlock(e)}catch(e){return l.warn("Failed to verify that no Codex chooser is active",{sessionId:t,error:e instanceof Error?e.message:String(e)}),!1}}sendVerifiedPromptInput(t,e,i){if(!this.isExpectedSessionStateCurrent(t))return Promise.resolve("stale");let s=this.terminalInputChain.then(async()=>{if(!this.isExpectedSessionStateCurrent(t)||this.pendingInteractivePrompt!==e||e.ownerSessionId!==t.sessionId)return"stale";if(!e.observerMatchKey)return l.warn("Refusing mobile prompt input without a captured pane identity",{sessionId:t.sessionId,promptId:e.promptId}),"unverified";if(e.terminalMenuIdentity)try{return await(0,pe.selectTerminalMenuOption)(e.terminalMenuIdentity,i,{current:()=>this.isExpectedSessionStateCurrent(t)&&this.pendingInteractivePrompt===e,read:async()=>(0,pe.parseActiveTerminalMenu)(await this.tmuxPaneObserver.captureSnapshot()),key:o=>this.promptResponder.sendKey(t.sessionId,o),wait:()=>new Promise(o=>setTimeout(o,100))})}catch{return"unverified"}let r=null;try{let o=await this.tmuxPaneObserver.captureSnapshot(),c=this.tmuxPaneObserver.extractActiveApprovalBlock(o),d=c?(0,q.parseInteractivePrompt)(c):null;r=d?this.buildObserverPromptMatchKey(d):null}catch(o){return l.warn("Failed to re-probe Codex prompt before mobile input",{sessionId:t.sessionId,promptId:e.promptId,error:o instanceof Error?o.message:String(o)}),"unverified"}return!this.isExpectedSessionStateCurrent(t)||this.pendingInteractivePrompt!==e?"stale":!r||r!==e.observerMatchKey?(l.warn("Refusing mobile input because the live Codex prompt changed",{sessionId:t.sessionId,promptId:e.promptId,hasLiveIdentity:!!r}),"unverified"):(i===te?await this.promptResponder.sendKey(t.sessionId,"Escape"):await this.promptResponder.sendLiteral(t.sessionId,i))?"sent":"send_failed"});return this.terminalInputChain=s.then(()=>{},()=>{}),s}sendVerifiedFollowUpAfterDismissal(t,e,i,s){let r=this.terminalInputChain.then(async()=>{let n=()=>this.isExpectedSessionStateCurrent(t)&&e.ownerSessionId===t.sessionId;return n()?!await this.verifyNoActiveCodexChooser(t.sessionId)||!n()||s&&(await s(),!n()||!await this.verifyNoActiveCodexChooser(t.sessionId)||!n())?"unverified":await this.promptResponder.sendLiteral(t.sessionId,i)?(await new Promise(o=>setTimeout(o,500)),n()?!await this.verifyNoActiveCodexChooser(t.sessionId)||!n()?"unverified":await this.promptResponder.sendKey(t.sessionId,"Enter")?"sent":"send_failed":"stale"):"send_failed":"stale"});return this.terminalInputChain=r.then(()=>{},()=>{}),r}sendConversationContinuation(t,e,i){if(!this.isExpectedSessionStateCurrent(t))return Promise.resolve("stale");let s=this.terminalInputChain.then(async()=>{if(!this.isExpectedSessionStateCurrent(t))return"stale";try{let r=new Set;for(;;){let n=await this.tmuxPaneObserver.captureSnapshot();if(!this.isExpectedSessionStateCurrent(t))return"stale";let o=this.tmuxPaneObserver.extractActivePromptBlock(n);if(!o)break;let c=this.tmuxPaneObserver.hashPromptSnapshot(o);if(r.has(c)||r.size>=4)return"unverified";if(r.add(c),!await this.promptResponder.sendKey(t.sessionId,"Escape"))return"send_failed";if(await new Promise(d=>setTimeout(d,200)),!this.isExpectedSessionStateCurrent(t))return"stale"}}catch(r){return l.warn("Failed to inspect Codex chooser before conversation continuation",{sessionId:t.sessionId,error:r instanceof Error?r.message:String(r)}),"unverified"}return i&&(await i(),!this.isExpectedSessionStateCurrent(t)||!await this.verifyNoActiveCodexChooser(t.sessionId)||!this.isExpectedSessionStateCurrent(t))?"unverified":await this.promptResponder.sendLiteral(t.sessionId,e)?(await new Promise(r=>setTimeout(r,500)),this.isExpectedSessionStateCurrent(t)?await this.verifyNoActiveCodexChooser(t.sessionId)?await this.promptResponder.sendKey(t.sessionId,"Enter")?"sent":"send_failed":"unverified":"stale"):"send_failed"});return this.terminalInputChain=s.then(()=>{},()=>{}),s}handleEventFromHook(t){if(this.isStopping)return Promise.resolve();let e=this.lifecycleGeneration,i=this.registerQueuedPermissionRequest(t,e),s=this.hookEventChain.then(()=>this.processHookEvent(t,e,i??void 0)),r=i?s.finally(()=>this.unregisterQueuedPermissionRequest(i)):s;return this.hookEventChain=r.catch(n=>{l.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,e){if(t.hook_event_name!=="PermissionRequest"||!this.sessionState||this.sessionWatcher.getAuthoritativeSessionId()!==t.session_id)return null;let i=this.sessionState.sessionId;this.queuedPermissionRequestSessionCounts.set(i,(this.queuedPermissionRequestSessionCounts.get(i)??0)+1);let s=this.buildApprovalPromptContextFromHookPayload(t),r=this.buildApprovalDedupeKey(s),n=`permission:${(0,se.v4)()}`,o=r?`${i}::${r}`:void 0;o&&this.queuedPermissionRequestDedupeKeys.set(o,(this.queuedPermissionRequestDedupeKeys.get(o)??0)+1);let c={sessionId:i,lifecycleGeneration:e,context:s,dedupeKey:r,occurrenceKey:n,dedupeRegistryKey:o,disposition:"pending"};if(r){let p=this.permissionRequestOccurrencesByCompletionKey.get(r)??[];p.push({occurrenceKey:n,hookObserved:!1,jsonlObserved:!1}),this.permissionRequestOccurrencesByCompletionKey.set(r,p)}let d=this.queuedPermissionRequestRegistrations.get(i)??[];return d.push(c),this.queuedPermissionRequestRegistrations.set(i,d),c}async unregisterQueuedPermissionRequest(t){let e=this.queuedPermissionRequestSessionCounts.get(t.sessionId)??0;if(e<=1?this.queuedPermissionRequestSessionCounts.delete(t.sessionId):this.queuedPermissionRequestSessionCounts.set(t.sessionId,e-1),t.dedupeRegistryKey){let o=this.queuedPermissionRequestDedupeKeys.get(t.dedupeRegistryKey)??0;o<=1?this.queuedPermissionRequestDedupeKeys.delete(t.dedupeRegistryKey):this.queuedPermissionRequestDedupeKeys.set(t.dedupeRegistryKey,o-1)}let s=(this.queuedPermissionRequestRegistrations.get(t.sessionId)??[]).filter(o=>o!==t);s.length>0?this.queuedPermissionRequestRegistrations.set(t.sessionId,s):this.queuedPermissionRequestRegistrations.delete(t.sessionId),(t.disposition==="pending"||t.disposition==="dropped"||this.sessionState?.sessionId!==t.sessionId)&&this.removePermissionRequestOccurrence(t.dedupeKey,t.occurrenceKey);let r=this.deferredTmuxPromptCandidates.get(t);if(!r)return;if(this.deferredTmuxPromptCandidates.delete(t),!this.isLifecycleCurrent(t.lifecycleGeneration)){t.disposition="dropped",this.removePermissionRequestOccurrence(t.dedupeKey,t.occurrenceKey),l.debug("Discarding deferred tmux prompt after lifecycle invalidation",{sessionId:t.sessionId,lifecycleGeneration:t.lifecycleGeneration,currentLifecycleGeneration:this.lifecycleGeneration});return}let n=this.hasRecentlyResolvedApprovalDedupeKey(t.sessionId,t.occurrenceKey);if(t.disposition==="covered"||t.disposition==="resolved"||n){l.debug("Discarding deferred tmux prompt covered by its PermissionRequest",{sessionId:t.sessionId,dedupeKey:t.dedupeKey,disposition:t.disposition});return}if(!(t.disposition==="dropped"||this.sessionState?.sessionId!==t.sessionId)){l.debug("Replaying deferred tmux prompt after PermissionRequest produced no durable owner",{sessionId:t.sessionId,dedupeKey:t.dedupeKey});try{await this.handleTmuxPromptCandidate(r.snapshot,t,r.promptHash)}catch(o){l.error("Failed to replay deferred tmux prompt candidate",{sessionId:t.sessionId,error:o instanceof Error?o.message:String(o)})}}}removePermissionRequestOccurrence(t,e){if(!t||!e)return;let i=this.permissionRequestOccurrencesByCompletionKey.get(t);if(!i)return;let s=i.filter(r=>r.occurrenceKey!==e);s.length>0?this.permissionRequestOccurrencesByCompletionKey.set(t,s):this.permissionRequestOccurrencesByCompletionKey.delete(t)}observePermissionRequestCompletion(t,e){if(!t)return{shouldResolve:!0};let i=this.permissionRequestOccurrencesByCompletionKey.get(t);if(!i)return{shouldResolve:!0};let s=e==="hook"?"hookObserved":"jsonlObserved",r=i.find(o=>!o[s]);if(!r)return l.debug("Ignoring duplicate interactive-prompt completion observation",{completionKey:t,producer:e}),{shouldResolve:!1};let n=!r.hookObserved&&!r.jsonlObserved;return r[s]=!0,r.hookObserved&&r.jsonlObserved&&this.removePermissionRequestOccurrence(t,r.occurrenceKey),{shouldResolve:n,occurrenceKey:r.occurrenceKey}}isPermissionRequestOccurrenceKey(t){return t.startsWith("permission:")}consumeRecoveryPermissionReplay(t,e,i){let s=this.recoveryPermissionReplay,r=this.pendingInteractivePrompt;return!s||!e||s.ownerSessionId!==t.sessionId||s.completionKey!==e||r?.ownerSessionId!==t.sessionId||r.source!=="permission_hook"||r.dedupeKey!==s.occurrenceKey||r.completionKey!==s.completionKey?!1:(this.recoveryPermissionReplay=null,i&&(this.removePermissionRequestOccurrence(i.dedupeKey,i.occurrenceKey),i.occurrenceKey=s.occurrenceKey,i.disposition="covered"),l.info("[Hooks] Reused adopted PermissionRequest occurrence for one recovery replay",{sessionId:t.sessionId,completionKey:e,occurrenceKey:s.occurrenceKey}),!0)}async processHookEvent(t,e,i){if(!this.isLifecycleCurrent(e))return;let{session_id:s,hook_event_name:r,type:n,content:o,metadata:c}=t;l.info("[Hooks] Received event",{sessionId:s,hookEvent:r,type:n,contentLength:o?.length});let d=this.sessionWatcher.getAuthoritativeSessionId();if(d&&d!==s){l.warn("[Hooks] Rejecting event for foreign native session",{hookEvent:r,sessionId:s,authoritativeSessionId:d});return}if(c?.transcript_path){let f=await this.sessionWatcher.bindToSessionTranscript(c.transcript_path,s);if(!this.isLifecycleCurrent(e))return;let v=f.status==="pending"?await f.completion:f;if(!this.isLifecycleCurrent(e))return;if(v.status!=="bound"){l.warn("[Hooks] Rejecting event whose transcript ownership was not proven",{hookEvent:r,sessionId:s,reason:v.reason});return}}else if(d!==s){l.warn("[Hooks] Rejecting event without an owned transcript",{hookEvent:r,sessionId:s});return}if(!this.isLifecycleCurrent(e)||this.sessionWatcher.getAuthoritativeSessionId()!==s){l.warn("[Hooks] Rejecting event after ownership changed during admission",{hookEvent:r,sessionId:s,authoritativeSessionId:this.sessionWatcher.getAuthoritativeSessionId()});return}if(this.hooksActive=!0,r==="SessionStart"){if(this.launchSessionInitPromise&&(await this.launchSessionInitPromise,!this.isLifecycleCurrent(e)))return;if(this.sessionState){if(l.info("[Hooks] SessionStart \u2014 launch session already exists, updating codexSessionId",{existingSessionId:this.sessionState.sessionId,codexSessionId:s}),this.sessionState.codexSessionId=s,this.sessionState.metadata={...this.sessionState.metadata,codexSessionId:s,cliVersion:c?.model||"unknown",modelProvider:c?.model||"unknown",launchSession:void 0},this.appSyncClient.updateSession({sessionId:this.sessionState.sessionId,metadata:this.sessionState.metadata}).catch(f=>l.warn("Failed to update session metadata",{error:f})),await this.startTmuxObserverWithBeacon("session_start_existing"),!this.isLifecycleCurrent(e))return;await this.ensureToolActivityStarted(s)}else{let f={id:s,timestamp:new Date().toISOString(),cwd:c?.cwd||process.cwd(),originator:"hook",cli_version:c?.model||"unknown",instructions:null,source:c?.source||"startup",model_provider:c?.model||"unknown"};await this.ensureSessionStarted(f)}return}if(!this.sessionState){l.warn("[Hooks] Hook event for un-bootstrapped session \u2014 self-healing via session bootstrap (#638)",{hookEvent:r,sessionId:s});let f={id:s,timestamp:new Date().toISOString(),cwd:c?.cwd||process.cwd(),originator:"hook",cli_version:c?.model||"unknown",instructions:null,source:c?.source||"startup",model_provider:c?.model||"unknown"};if(await this.ensureSessionStarted(f),!this.isLifecycleCurrent(e))return;if(!this.sessionState){l.warn("[Hooks] Session still not initialized after self-heal, dropping event",{hook_event_name:r});return}}let p=this.sessionState,u=p.sessionId;if(!(n==="USER_PROMPT"&&(this.approvalDetector.clear(),this.clearInteractivePromptsForAcceptedInput(p),(await this.selectNativeSourceTransport(p)).protocol==="SYNC_V2"))){if(n==="USER_PROMPT"&&o){let f=this.consumeRecentMobilePrompt(u,o);if(f){l.info("[Hooks] Skipping duplicate USER_PROMPT from mobile",{sessionId:u,matchType:f.matchType,originalLength:f.originalLength,echoLength:f.echoLength});return}}if(r==="PreToolUse"){l.debug("[Hooks] PreToolUse observed; AppSync emission suppressed",{toolName:c?.tool_name||"unknown",sessionId:u});return}if(r==="PermissionRequest"){let f=i??this.registerQueuedPermissionRequest(t,e);if(!f){l.error("[Hooks] Dropping admitted PermissionRequest without occurrence registration",{sessionId:u,nativeSessionId:s});return}try{await this.handlePermissionRequestHook(t,p,f)}finally{i||await this.unregisterQueuedPermissionRequest(f)}return}if(r==="PostToolUse"){let f=this.buildApprovalPromptContextFromHookPayload(t),v=this.buildApprovalDedupeKey(f),m=this.firstString(c?.tool_use_id,c?.call_id,c?.callId)??"",g=this.observePermissionRequestCompletion(v,"hook");if(g.shouldResolve&&await this.clearResolvedInteractivePrompt(m,g.occurrenceKey??v),!this.isExpectedSessionStateCurrent(p)||this.toolActivity?.isActive()&&await this.toolActivity.observeCall({callId:c?.tool_use_id??c?.call_id??c?.callId,toolName:c?.tool_name,toolInput:c?.tool_input})!=="closed"||!this.isExpectedSessionStateCurrent(p))return;let w=await this.selectNativeSourceTransport(p);if(!this.isExpectedSessionStateCurrent(p))return;if(w.protocol==="SYNC_V2")throw new Error("SYNC_SOURCE_TOOL_NOT_ADMITTED");let E=this.encryptForEmit(o,c,h.EventType.TOOL_USE,u);if(!E)return;let S=E.content,P=E.metadata,b=E.isEncrypted,_=c?.tool_use_id??c?.call_id??c?.callId,N=typeof _=="string"&&_.length>0&&!!this.sessionKey,O=N?this.getToolActivityLegacyRecorder(u):void 0;O&&N&&O.markLegacyInFlight(_);try{let W=await this.appSyncClient.createEvent({sessionId:u,type:h.EventType.TOOL_USE,source:h.EventSource.DESKTOP,content:S,metadata:P,isEncrypted:b,timestamp:(0,h.prepareEventTimestamp)({orderingKey:u})});O&&N&&((0,h.isPersistedEventResult)(W)?await O.finalizeLegacyOwned([_]):O.clearLegacyInFlight(_))}catch(W){throw O&&N&&O.clearLegacyInFlight(_),W}return}if(n==="ASSISTANT_RESPONSE"||n==="USER_PROMPT"){if(n==="ASSISTANT_RESPONSE"){this.sessionWatcher.getBindSource()==="authoritative"&&this.sessionWatcher.getAuthoritativeSessionId()===s?l.debug("[Hooks] Suppressing Stop final \u2014 JSONL watcher authoritatively bound to this session (Bug #2)"):l.warn("[Hooks] Dropping Stop final after authoritative ownership changed",{authoritativeSessionId:this.sessionWatcher.getAuthoritativeSessionId()});return}let f=this.encryptForEmit(o,void 0,h.EventType.USER_PROMPT,u);if(!f)return;await this.appSyncClient.createEvent({sessionId:u,type:h.EventType.USER_PROMPT,source:h.EventSource.DESKTOP,content:f.content,isEncrypted:f.isEncrypted,timestamp:(0,h.prepareEventTimestamp)({orderingKey:u})});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),l.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)}async trackDurableMobileEcho(t,e,i,s){if(!(0,h.requiresSyncInputDeliveryReceipt)(e)){this.trackMobilePrompt(t.sessionId,i);return}let r=await this.selectNativeSourceTransport(t);if(r.protocol!=="SYNC_V2"||!this.isExpectedSessionStateCurrent(t)||e.sessionId!==r.sessionScope.sessionId||e.sessionGenerationId!==r.sessionScope.sessionGenerationId)throw Error("SYNC_ECHO_OWNER_CHANGED");i.trim()&&await r.writer.mobileEchoes("codex").arm({eventId:e.eventId,timestamp:e.timestamp,type:e.type,lane:s},i,{nowMs:Date.now(),windowMs:1e4,allowSuffix:!0,normalization:"whitespace"})}setupEventHandlers(){this.sessionWatcher.on("session-started",async t=>{try{if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionState){l.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){l.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){l.error("approval-pending handler failed (non-fatal)",{error:String(e)})}}),this.tmuxPaneObserver.on("prompt-candidate",async t=>{try{await this.handleTmuxPromptCandidate(t.snapshot,void 0,t.promptHash)}catch(e){l.error("prompt-candidate handler failed (non-fatal)",{error:String(e)})}}),this.tmuxPaneObserver.on("prompt-cleared",t=>{let e=this.sessionState;e&&this.clearObservedInteractivePrompt(e,t.promptHash).catch(i=>{l.error("prompt-cleared handler failed (non-fatal)",{error:String(i)})})}),this.tmuxPaneObserver.on("observer-error",t=>{l.debug("Tmux pane observer error",{error:t})}),this.sessionWatcher.on("error",t=>{l.error("Session watcher error:",t)})}async ensureSessionStarted(t,e){if(this.isStopping||(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.isStopping)||this.sessionState)return;process.env[Oe]==="1"&&await this.bindRecoveryBootstrapIdentity(t.id);let i=this.sessionBootstrapRetryAt-Date.now();if(i>0){l.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;l.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(),o={codexSessionId:t.id,cliVersion:t.cli_version,modelProvider:t.model_provider},c={sessionKey:null,sessionIsEncrypted:!0};try{let d={sessionId:r,userId:n,agentType:h.AgentType.CODEX,projectPath:s,metadata:o},p=await this.resumeOrCreateBootstrapSession(d);if(r=p.sessionId,!this.isLifecycleCurrent(i)){this.isInitializingSession=!1,await this.retireCancelledBootstrap(r,"session_started");return}this.sessionKey=p.sessionKey,this.sessionKeyGen=p.sessionKeyGen,this.sessionIsEncrypted=!!p.sessionKey,c={sessionKey:p.sessionKey,sessionIsEncrypted:!!p.sessionKey},await x("daemon_init_step_completed",{step:"session_resume_or_create",path:"session_started"})}catch(d){if(this.isInitializingSession=!1,!this.isLifecycleCurrent(i)){let p=this.authoritativeSessionIdFromError(d)??r;await this.retireCancelledBootstrap(p,"session_started_error");return}throw await x("daemon_init_step_failed",{step:"session_resume_or_create",path:"session_started",error_class:d?.name||"Error",error_message:d?.message||String(d)}),d?.code==="ENCRYPTED_SESSION_NO_KEY"&&(this.sessionIsEncrypted=!0,this.sessionKey=null),this.bindBootstrapIdentityFromError(d),this.recordSessionBootstrapFailure(d,"session_started"),l.error("Failed to create/resume session:",d),d}try{this.sessionState={sessionId:r,userId:n,projectPath:s,cwd:t.cwd,createdAt:new Date,subscriptionActive:!1,metadata:o,encryptionSnapshot:c,codexSessionId:t.id,codexLogFile:this.sessionWatcher.getActiveLogFile()||void 0},this.clearSessionBootstrapFailure(),this.bootstrapSessionId=null,this.recoveryBootstrapOwnerBound=!1,await x("daemon_init_step_completed",{step:"session_state_set",path:"session_started"})}catch(d){await x("daemon_init_step_failed",{step:"session_state_set",path:"session_started",error_class:d?.name||"Error",error_message:d?.message||String(d)}),l.error("Failed to set session state:",d)}await this.adoptDaemonHandoffState(r),this.sessionState&&this.rebindWaitingPermissionRequests(this.sessionState),await this.ensureToolActivityStarted(t.id);try{this.subscribeToMobileEvents(r)?await x("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"session_started"}):await x("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(d){await x("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:d?.name||"Error",error_message:d?.message||String(d)}),l.error("Failed to subscribe to mobile events:",d)}if(e)try{await e()}catch(d){l.error("E1: pre-heartbeat re-raise hook failed (non-fatal)",{sessionId:r,error:d instanceof Error?d.message:String(d)})}try{await this.drainRetirementOrphans(r)}catch(d){l.error("E1: retirement-orphan drain failed (non-fatal)",{sessionId:r,error:d instanceof Error?d.message:String(d)})}try{await this.appSyncClient.startHeartbeat(r)?await x("daemon_init_step_completed",{step:"heartbeat_start",path:"session_started"}):(await x("daemon_init_step_failed",{step:"heartbeat_start",path:"session_started",error_class:"InitialHeartbeatNotPersisted",error_message:"Backend did not confirm the initial heartbeat mutation"}),l.error("Initial session heartbeat was not persisted",{sessionId:r}))}catch(d){await x("daemon_init_step_failed",{step:"heartbeat_start",path:"session_started",error_class:d?.name||"Error",error_message:d?.message||String(d)}),l.error("Failed to start heartbeat:",d)}try{await this.subscribeToOnApplyUserDecision(r)}catch(d){l.error("Failed to subscribe to onApplyUserDecision (non-fatal)",{error:d})}this.startMobileEndWatcher(r);try{await this.flushBufferedLogEntries(),await x("daemon_init_step_completed",{step:"flush_buffered_entries",path:"session_started"})}catch(d){await x("daemon_init_step_failed",{step:"flush_buffered_entries",path:"session_started",error_class:d?.name||"Error",error_message:d?.message||String(d)}),l.error("Failed to flush buffered log entries:",d),this.bufferedLogEntries=[]}await this.startTmuxObserverWithBeacon("session_started"),this.isInitializingSession=!1}getOrCreateBootstrapSessionId(){return this.bootstrapSessionId||(this.bootstrapSessionId=ee.mintBackendSessionId()),this.bootstrapSessionId}async bindRecoveryBootstrapIdentity(t){if(!(process.env[Oe]!=="1"||this.bootstrapSessionId||this.sessionState||!t))try{let e=await this.buildToolActivityIntegration().recordedBackendSessionId(t);if(!e){l.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)){l.warn("Recovery daemon ignored invalid durable backend owner",{rolloutId:t});return}this.bootstrapSessionId=e,this.recoveryBootstrapOwnerBound=!0,l.info("Recovery daemon reclaiming existing backend session",{rolloutId:t,sessionId:e})}catch(e){l.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,l)}catch(e){if(!this.recoveryBootstrapOwnerBound||!this.isSessionIdReservedRejection(e))throw e;return l.warn("Recovery discarded a permanently reserved pending create; retrying the durable rollout owner",{sessionId:t.sessionId}),this.resumeBackendSession(t,this.appSyncClient,l)}}startTmuxLifecycleMonitor(){if(this.tmuxLifecycleTimer)return;let t=process.env[j];t&&(this.tmuxLifecycleInitDeadlineMs=Date.now()+is,this.tmuxLifecycleTimer=setInterval(()=>{this.checkTmuxLifecycle(t)},ts),this.tmuxLifecycleTimer.unref?.(),this.checkTmuxLifecycle(t))}async tmuxSessionState(t){try{return ze("stall-tmux-probe")&&(l.warn("[dev-fault] stall-tmux-probe: terminality probe will never settle",{tmuxSession:t}),await new Promise(()=>{})),await Zi("tmux",["has-session","-t",t],{timeout:5e3}),"alive"}catch(e){let i=jt(e);return i==="absent"?i:(l.warn("Could not inspect native Codex tmux session; preserving daemon",{tmuxSession:t,error:e instanceof Error?e.message:String(e)}),"unknown")}}async checkTmuxLifecycle(t){if(!(this.isStopping||this.tmuxLifecycleCheckInFlight)){this.tmuxLifecycleCheckInFlight=!0;try{let e=await this.tmuxSessionState(t);if(e==="alive"){this.tmuxLifecycleObservedAlive=!0;return}let i=this.tmuxLifecycleObservedAlive||Date.now()>=this.tmuxLifecycleInitDeadlineMs;if(e==="unknown"||!i||this.isStopping)return;this.stopTmuxLifecycleMonitor(),l.info("Native Codex tmux session ended; stopping companion daemon",{tmuxSession:t});let s=le(r=>process.exit(r),()=>l.error("Shutdown watchdog fired after native session end; exiting anyway",{watchdogMs:25e3,timedOutSteps:this.getTeardownStepsTimedOut(),durableObligationSettled:this.isDurableObligationSettledForExit()}),25e3,()=>this.isDurableObligationSettledForExit());this.stop().then(()=>{s(),process.exit(0)},r=>{s(),l.error("Failed to stop companion daemon after native session end",{error:r instanceof Error?r.message:String(r)}),process.exit(1)})}finally{this.tmuxLifecycleCheckInFlight=!1}}}stopTmuxLifecycleMonitor(){this.tmuxLifecycleTimer&&(clearInterval(this.tmuxLifecycleTimer),this.tmuxLifecycleTimer=null)}async shouldShutdownForTerminalSignal(t){if(t==="SIGHUP"){let e=process.env[j];if(e){let i=await this.tmuxSessionState(e);if(i!=="absent")return l.info("Ignoring SIGHUP while native Codex tmux session remains available",{tmuxSession:e,state:i}),!1}}return!0}async stopForTerminalSignal(t){return await this.shouldShutdownForTerminalSignal(t)?(await this.stop(),!0):!1}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:h.SessionStatus.INACTIVE}),l.info("Cancelled bootstrap row marked INACTIVE",{sessionId:t,path:e})}catch(i){l.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,l.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")};l.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=ee.mintBackendSessionId(),this.recoveryBootstrapOwnerBound=!1,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,l.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=[],l.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(async()=>{await this.handleLogEntry(t)});return this.logEntryChain=e.catch(i=>{l.error("[JSONL] log entry handler failed",{type:t.type,err:String(i)})}),e}selectNativeSourceTransport(t){if(this.sessionState!==t||this.isStopping)return Promise.reject(new Error("SYNC_SOURCE_OWNER_CHANGED"));if(this.nativeSourceSelection?.state===t)return this.nativeSourceSelection.pending;let e=this.appSyncClient.selectCompanionSourceTransport({sessionId:t.sessionId}),i={state:t,pending:e};return this.nativeSourceSelection=i,e.catch(()=>{this.nativeSourceSelection===i&&(this.nativeSourceSelection=null)}),e}async retryNativeAdmission(t){try{return await t()}catch(e){throw!this.isStopping&&!this.nativeSourceRetryTimer&&(this.nativeSourceRetryTimer=setTimeout(()=>{this.nativeSourceRetryTimer=null,this.sessionWatcher.retryActiveRead()},5e3),this.nativeSourceRetryTimer.unref()),e}}assertNativeSourceOwner(t){if(this.sessionState!==t.state||t.controller.signal.aborted)throw new Error("SYNC_SOURCE_OWNER_CHANGED")}async nativeSourceOwner(t){if(this.isStopping)throw new Error("SYNC_SOURCE_STOPPING");this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionStartedInitPromise&&await this.sessionStartedInitPromise;let e=this.sessionState;if(!e||!t.nativeSessionId||this.sessionWatcher.getActiveLogFile()!==t.transcriptPath||this.sessionWatcher.getAuthoritativeSessionId()!==null&&this.sessionWatcher.getAuthoritativeSessionId()!==t.nativeSessionId)throw new Error("SYNC_SOURCE_BOOTSTRAP_PENDING");let i=await this.selectNativeSourceTransport(e);if(this.sessionState!==e||this.isStopping)throw new Error("SYNC_SOURCE_OWNER_CHANGED");if(i.protocol==="LEGACY")return null;if(await this.ensureToolActivityStarted(t.nativeSessionId),this.sessionState!==e||this.isStopping||!this.toolActivity?.isActive())throw new Error("SYNC_SOURCE_OWNERSHIP_UNAVAILABLE");let s=de.createHash("sha256").update(JSON.stringify([t.transcriptPath,t.nativeSessionId])).digest("hex"),r=`${i.sessionScope.sessionGenerationId}:${s}`,n=this.nativeSourceOwners.get(r);if(n)return this.assertNativeSourceOwner(n),n;let o={state:e,selection:i,streamSha256:s,cursor:i.writer.sourceStream({provider:"codex",streamSha256:s}),controller:new AbortController,drain:null,drainRequested:!1,retryTimer:null,retryMs:5e3};return this.nativeSourceOwners.set(r,o),o}async restoreNativeSource(t,e){let i=await this.nativeSourceOwner(t);if(!i)return null;await i.cursor.recover();let s=await i.cursor.open(e);return await i.selection.writer.mobileEchoes("codex").reconcile(i.streamSha256,s.byteOffset),this.assertNativeSourceOwner(i),this.drainNativeSource(i),{byteOffset:s.byteOffset,anchor:s.anchor,discardUntilNewline:s.discardUntilNewline}}async admitNativeSourceGap(t,e){let i=await this.nativeSourceOwner(e);if(!i)throw new Error("SYNC_SOURCE_PROTOCOL_CHANGED");await i.cursor.skip(t),this.assertNativeSourceOwner(i)}async admitNativeSourceEntry(t,e){let i=await this.nativeSourceOwner(e);if(!i)return;let s=this.logEntryChain.then(async()=>{this.assertNativeSourceOwner(i);let r=await i.cursor.load();if(!r)throw new Error("SYNC_SOURCE_CURSOR_MISSING");if(e.endOffset<=r.byteOffset)return;let n=mt(t,i.state.sessionId,r.projection);if(n.event&&!["USER_PROMPT","ASSISTANT_RESPONSE","REASONING","TOOL_USE","NOTIFICATION"].includes(n.event.type))throw new Error("SYNC_NATIVE_SPECIALIZED_PRODUCER_REQUIRED");let o=await this.handleLogEntry(t,{event:n.event});if(this.assertNativeSourceOwner(i),!this.isExpectedSessionStateCurrent(i.state))throw new Error("SYNC_SOURCE_OWNER_STOPPING");let c={streamSha256:i.streamSha256,occurrence:`${e.startOffset}:${e.endOffset}`,sourceSha256:e.sha256,startOffset:e.startOffset,endOffset:e.endOffset},d=i.selection.writer.mobileEchoes("codex");o?.type===h.EventType.USER_PROMPT&&await d.claim(c,o.content,t.timestamp)&&(o=void 0),await i.cursor.admit({provider:"codex",streamSha256:i.streamSha256,occurrence:`${e.startOffset}:${e.endOffset}`,sourceSha256:e.sha256,startOffset:e.startOffset,endOffset:e.endOffset,anchor:e.anchor},o?p=>i.selection.prepareEvent(o,p):null,n.projection),await d.reconcile(i.streamSha256,e.endOffset),this.drainNativeSource(i)});return this.logEntryChain=s.catch(r=>{l.warn("[sync-source] native admission retained for retry",{error:String(r)})}),await s,"handled"}drainNativeSource(t){if(t.controller.signal.aborted||this.isStopping||(t.drainRequested=!0,t.drain||t.retryTimer))return;t.drainRequested=!1;let e=(async()=>{let i=!1;try{await t.cursor.drain(64,t.controller.signal)===64&&(t.drainRequested=!0),t.retryMs=5e3}catch(s){i=!0,t.controller.signal.aborted||l.warn("[sync-source] cloud drain retained for retry",{error:String(s)}),t.retryMs=Math.min(t.retryMs*2,6e4)}t.drain=null,!t.controller.signal.aborted&&!this.isStopping&&this.sessionState===t.state&&(i?(t.retryTimer=setTimeout(()=>{t.retryTimer=null,this.drainNativeSource(t)},t.retryMs),t.retryTimer.unref()):t.drainRequested&&this.drainNativeSource(t))})();t.drain=e,e.catch(i=>l.error("[sync-source] unexpected drain failure",{error:String(i)}))}async stopNativeSources(t){this.nativeSourceRetryTimer&&clearTimeout(this.nativeSourceRetryTimer),this.nativeSourceRetryTimer=null;let e=[...this.nativeSourceOwners].filter(([,i])=>i.state===t);for(let[,i]of e)i.retryTimer&&clearTimeout(i.retryTimer),i.retryTimer=null,i.controller.abort(new Error("SYNC_SOURCE_STOPPED"));await Promise.all(e.map(([,i])=>i.drain?.catch(()=>{})));for(let[i]of e)this.nativeSourceOwners.delete(i);this.nativeSourceSelection?.state===t&&(this.nativeSourceSelection=null)}async handleLogEntry(t,e){if(!this.sessionState){if(this.isInitializingSession){this.bufferedLogEntries.push(t),l.debug("Buffering log entry until session initialization completes",{type:t.type,bufferedCount:this.bufferedLogEntries.length});return}l.warn("Received log entry but no active session");return}let i=this.sessionState,s=i.sessionId,{sessionKey:r,sessionIsEncrypted:n}=i.encryptionSnapshot;if(t.type==="event_msg"&&t.payload?.type==="turn_aborted"&&(this.approvalDetector.clear(),this.clearInteractivePromptsForAcceptedInput(i)),t.type==="response_item"&&t.payload){let g=t.payload.type;if(g==="function_call"||g==="custom_tool_call")this.approvalDetector.onToolCallStart(t.payload.call_id,t.payload.name,t.payload.arguments||t.payload.input||"");else if(g==="function_call_output"||g==="custom_tool_call_output"){let w=this.approvalDetector.getPendingCalls().find(P=>P.callId===t.payload.call_id),E=w?this.buildApprovalDedupeKey(this.buildApprovalPromptContextFromPendingCall(w)):void 0;this.approvalDetector.onToolCallComplete(t.payload.call_id);let S=this.observePermissionRequestCompletion(E,"jsonl");if(S.shouldResolve&&await this.clearResolvedInteractivePrompt(t.payload.call_id,S.occurrenceKey??E),!this.isExpectedSessionStateCurrent(i))return}}let o=e?e.event:qe(t,s);if(!o)return;o.timestamp=(0,h.prepareEventTimestamp)({orderingKey:s,agentClock:t.timestamp});let c=t.payload?.type,d=!1;if(this.toolActivity?.isActive()&&o.type===h.EventType.TOOL_USE){let g=c==="function_call"||c==="custom_tool_call",w=c==="function_call_output"||c==="custom_tool_call_output";if(g&&typeof t.payload?.call_id=="string"){let E=this.sessionWatcher.getActiveLogFile();E&&this.toolActivity.bindTranscript(E);let S=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(i)||S!=="closed")return;d=!0}if(w)return}if(this.toolActivity?.isActive()&&(c==="user_message"||c==="agent_message")){let g=this.toolActivity.flush();if(e?await g:await g.catch(w=>l.warn("[tool-activity] codex boundary flush failed",{sessionId:s,err:String(w)})),!this.isExpectedSessionStateCurrent(i))return}let p=c==="function_call"||c==="function_call_output",u=o.type===h.EventType.USER_PROMPT||o.type===h.EventType.ASSISTANT_RESPONSE||p&&(o.type===h.EventType.TOOL_USE||o.type===h.EventType.INTERACTIVE_PROMPT);if(!e&&!this.hooksActive&&u&&(await this.emitHooksCompatibilityModeNotice(i),!this.isExpectedSessionStateCurrent(i)))return;if(!e&&this.hooksActive){if(o.type===h.EventType.USER_PROMPT){l.debug("[JSONL] Skipping USER_PROMPT \u2014 hooks deliver it",{type:o.type});return}if(p&&(o.type===h.EventType.TOOL_USE||o.type===h.EventType.INTERACTIVE_PROMPT)&&!d){l.debug("[JSONL] Skipping function_call \u2014 hooks deliver this",{type:o.type,tool:t.payload?.name});return}}if(o.type===h.EventType.USER_PROMPT&&o.source===h.EventSource.DESKTOP){let g=e?null:this.consumeRecentMobilePrompt(s,o.content);if(g){l.info("[JSONL] Skipping duplicate USER_PROMPT from mobile",{sessionId:s,matchType:g.matchType,originalLength:g.originalLength,echoLength:g.echoLength});return}}if(this.sessionState!==i){l.warn("[JSONL] Dropping event from stale session generation (#638)",{sessionId:s,currentSessionId:this.sessionState?.sessionId});return}if(e)return o;let f=t.payload?.call_id,v=o.type===h.EventType.TOOL_USE&&typeof f=="string"&&f.length>0&&!!r,m=v?this.getToolActivityLegacyRecorder(s):void 0;m&&v&&m.markLegacyInFlight(f);try{let g=(0,h.encryptForEmit)(r,n,o.content,o.metadata);if(!g){l.error("No session key for ENCRYPTED session \u2014 dropping JSONL event (fail-closed, #638)",{type:o.type,sessionId:s});return}o.content=g.content,o.metadata=g.metadata,g.isEncrypted&&(o.isEncrypted=!0,l.debug("Event encrypted",{type:o.type}));let w=await this.appSyncClient.createEvent(o);l.debug("Event synced to backend",{type:o.type,encrypted:g.isEncrypted}),m&&v&&((0,h.isPersistedEventResult)(w)?await m.finalizeLegacyOwned([f]):m.clearLegacyInFlight(f))}catch(g){m&&v&&m.clearLegacyInFlight(f),l.error("Failed to sync event:",g)}}async handlePermissionRequestHook(t,e,i){if(!this.isExpectedSessionStateCurrent(e)){i&&(i.disposition="dropped");return}let s=i?.context??this.buildApprovalPromptContextFromHookPayload(t),r=i?.dedupeKey??this.buildApprovalDedupeKey(s);if(this.consumeRecoveryPermissionReplay(e,r,i))return;let n=i?.occurrenceKey??`permission:${(0,se.v4)()}`,o={ownerState:e,context:s,dedupeKey:r,occurrenceKey:n,registration:i};this.permissionRequestHookInFlight=o;try{let c=await this.handlePermissionRequestHookWhileTracked(t,e,s,n,r);i&&(i.disposition=c)}finally{this.permissionRequestHookInFlight===o&&(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=Z(r)||oe(r),o=i==="apply_patch"?this.firstString(s?.patch,r,typeof s=="string"?s:void 0):void 0,d=Z(o)||n,p=!!d,u=d?"apply_patch":i,f=d||this.stringifyToolInput(s),v=d?this.extractFilePathFromToolInput("apply_patch",void 0,d):this.extractFilePathFromToolInput(u,s,f),m=d?this.resolveHookPatchPath(v,e.cwd):v;return{toolName:u,framedPatch:p,toolInput:s,rawInput:f,filePath:m,diff:p?f:void 0,hint:m&&this.mapToolNameForApproval(u)==="Edit"?`File: ${m}`:this.buildPermissionRequestHint(u,s,f)}}resolveHookPatchPath(t,e){if(!t||F.isAbsolute(t))return t;if(!(typeof e!="string"||!F.isAbsolute(e)))return F.resolve(e,t)}async handlePermissionRequestHookWhileTracked(t,e,i=this.buildApprovalPromptContextFromHookPayload(t),s=`permission:${(0,se.v4)()}`,r,n){let o=t.metadata||{},{toolName:c,toolInput:d,rawInput:p}=i,u=this.buildToolDetailsForInteractivePrompt(i),f=u.tool_name||this.mapToolNameForApproval(c),v=u.tool_input||this.buildFallbackToolInput(i),m=!!(f&&v);if(r??=this.buildApprovalDedupeKey({toolName:c,toolInput:d,filePath:i.filePath,rawInput:p,hint:i.hint}),this.hasRecentlyResolvedApprovalDedupeKey(e.sessionId,s))return"resolved";let g=n??await this.tryParsePermissionRequestPromptFromTmux((O,W)=>this.parsedPromptMatchesApprovalContext(O,i,W),()=>this.isExpectedSessionStateCurrent(e));if(!this.isExpectedSessionStateCurrent(e))return l.warn("[Hooks] Dropping stale PermissionRequest after session generation changed",{sessionId:e.sessionId,currentSessionId:this.sessionState?.sessionId}),"dropped";if(this.hasRecentlyResolvedApprovalDedupeKey(e.sessionId,s))return l.info("[Hooks] Dropping PermissionRequest completed while terminal options were being parsed",{sessionId:e.sessionId,toolName:c,occurrenceKey:s}),"resolved";let w=g?.parsedPrompt??null;if(!w)return g?.differentPrompt?(this.waitingPermissionRequests.set(s,{ownerState:e,context:i,occurrenceKey:s,dedupeKey:r,payload:t}),l.info("[Hooks] Queued PermissionRequest until its desktop dialog is visible",{sessionId:e.sessionId,occurrenceKey:s,toolName:c}),"waiting"):(l.warn("[Hooks] Suppressing PermissionRequest mobile prompt because exact Codex options are unavailable",{sessionId:e.sessionId,toolName:c,hint:i.hint}),this.raiseSuppressedBadge(e.sessionId,s,{suppressTmuxObserverUntilResolved:!0,observerSnapshot:g?.snapshot,completionKey:r}),"covered");let E=this.mapToolNameForApproval(c)==="Bash"?this.firstString(d?.command,d?.cmd):void 0,S=this.buildCodexPromptPresentation(w,E,g?.snapshot);if(!S)return l.warn("[Hooks] Suppressing PermissionRequest mobile prompt because Codex option hotkeys are unavailable",{sessionId:e.sessionId,toolName:c,hint:i.hint}),this.raiseSuppressedBadge(e.sessionId,s,{suppressTmuxObserverUntilResolved:!0,observerSnapshot:g?.snapshot,completionKey:r}),"covered";let P=s,b=this.buildApprovalPromptContent(S.content,{toolName:f,toolInput:v,hint:i.hint,filePath:i.filePath}),_={promptId:P,kind:S.kind,options:S.options,submitMap:S.submitMap,promptText:b,createdAt:Date.now(),source:"permission_hook",dedupeKey:s,completionKey:r,ownerSessionId:e.sessionId,observerMatchKey:this.buildObserverPromptMatchKey(w),observerPromptHash:g?.snapshot?this.tmuxPaneObserver.hashPromptSnapshot(g.snapshot):void 0,requiresFollowUpText:S.requiresFollowUpText},N={isApprovalHint:!0,toolName:c,toolInput:d,hint:i.hint,filePath:i.filePath,diff:i.diff,rawInput:p,tool_name:f,tool_input:v,has_details:m,options:S.options,instructions:S.instructions,prompt_source:w?"permission_hook_tmux":"permission_hook",permission_mode:o.permission_mode,turn_id:o.turn_id,dedupe_key:s};return l.info("[Hooks] Sending PermissionRequest interactive prompt",{sessionId:e.sessionId,toolName:c,promptId:P,promptSource:N.prompt_source,occurrenceKey:s}),await this.enqueueOrEmitInteractivePrompt({prompt:_,content:b,metadata:N,ownerState:e}),this.hasRecentlyResolvedApprovalDedupeKey(e.sessionId,s)?"resolved":"covered"}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"};l.warn("Codex hooks inactive; running in compatibility mode",{sessionId:t.sessionId});try{let s=(0,h.prepareEventTimestamp)({orderingKey:t.sessionId}),r=await this.appSyncClient.publishCompanionNotice({sessionId:t.sessionId,type:h.EventType.NOTIFICATION,source:h.EventSource.DESKTOP,content:e,metadata:i,timestamp:s},async()=>{if(!this.isExpectedSessionStateCurrent(t))return!1;let n=this.encryptForEmit(e,i,h.EventType.NOTIFICATION,t.sessionId);return n?(await this.appSyncClient.createEvent({sessionId:t.sessionId,type:h.EventType.NOTIFICATION,source:h.EventSource.DESKTOP,content:n.content,metadata:n.metadata,timestamp:s,...n.isEncrypted?{isEncrypted:!0}:{}}),!0):!1});l.debug("Hooks compatibility notice publication outcome",{sessionId:t.sessionId,result:r})}catch(s){l.warn("Failed to emit hooks compatibility mode notification",{error:s})}}async handleApprovalPending(t){let e=this.sessionState;if(!e)return;if((this.queuedPermissionRequestSessionCounts.get(e.sessionId)??0)>0){l.debug("Skipping heuristic approval prompt while PermissionRequest owns the session prompt",{sessionId:e.sessionId,callId:t.callId});return}let i=this.buildApprovalDedupeKey(t);if(i&&this.hasRecentlyResolvedApprovalDedupeKey(e.sessionId,i)){l.info("Skipping heuristic approval prompt; same approval was already answered recently",{callId:t.callId,toolName:t.toolName,dedupeKey:i});return}if(i&&this.hasDurablePermissionHookFallbackByDedupeKey(e.sessionId,i)){l.debug("Skipping heuristic approval prompt already owned by a hook fallback",{sessionId:e.sessionId,callId:t.callId,dedupeKey:i});return}if(i&&this.hasActiveOrQueuedPermissionHookPrompt(e.sessionId,i)){this.mergeCallIdIntoPromptByDedupeKey(e.sessionId,i,t.callId),l.info("Skipping heuristic approval prompt; PermissionRequest hook already emitted it",{callId:t.callId,toolName:t.toolName,dedupeKey:i});return}l.info("Sending approval pending interactive prompt",t);try{let s=await this.tryParseInteractivePromptFromTmux(),r=s?.parsedPrompt??null;if((this.queuedPermissionRequestSessionCounts.get(e.sessionId)??0)>0||r&&this.hasMatchingDurablePermissionHookFallback(r,e.sessionId,s?.snapshot)||r&&this.hasMatchingPermissionHookPrompt(r,e.sessionId)){l.debug("Skipping heuristic approval prompt after PermissionRequest claimed the terminal dialog",{sessionId:e.sessionId,callId:t.callId});return}let n=this.buildToolDetailsForInteractivePrompt(t,s?.snapshot),o=n.tool_name||this.mapToolNameForApproval(t.toolName),c=n.tool_input||this.buildFallbackToolInput(t),d=!!(o&&c);if(!r){l.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,s?.snapshot)){l.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 p=this.mapToolNameForApproval(t.toolName)==="Bash"?this.firstString(t.toolInput?.command,t.toolInput?.cmd):void 0,u=this.buildCodexPromptPresentation(r,p,s?.snapshot);if(!u){l.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:o,toolInput:c,hint:t.hint,filePath:t.filePath}),m={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,observerMatchKey:this.buildObserverPromptMatchKey(r),requiresFollowUpText:u.requiresFollowUpText},g={isApprovalHint:!0,toolName:t.toolName,toolInput:t.toolInput,hint:t.hint,callId:t.callId,filePath:t.filePath,diff:t.diff,rawInput:t.rawInput,tool_name:o,tool_input:c,has_details:d,options:f,instructions:u.instructions,prompt_source:r?"tmux":"heuristic",dedupe_key:i};l.debug("Interactive prompt (pre-encryption)",{sessionId:e.sessionId,callId:t.callId,contentPreview:v.substring(0,200),toolDetails:n,metadata:g}),await this.enqueueOrEmitInteractivePrompt({prompt:m,content:v,metadata:g,ownerState:e})}catch(s){l.error("Failed to send approval interactive prompt:",s)}}async handleTerminalMenu(t,e,i){if(!this.isExpectedSessionStateCurrent(e)||this.pendingInteractivePrompt?.terminalMenuIdentity===t.identity&&this.pendingInteractivePrompt.ownerSessionId===e.sessionId)return;let s=(0,se.v4)(),r={promptId:s,kind:"numbered",options:t.prompt.options,submitMap:t.prompt.submitMap,promptText:t.prompt.promptText,createdAt:Date.now(),source:"tmux",dedupeKey:`menu:${s}`,ownerSessionId:e.sessionId,observerMatchKey:this.buildObserverPromptMatchKey(t.prompt),observerPromptHash:i??this.tmuxPaneObserver.hashPromptSnapshot(t.snapshot),terminalMenuIdentity:t.identity};await this.enqueueOrEmitInteractivePrompt({prompt:r,ownerState:e,content:t.prompt.promptText,metadata:{options:t.prompt.options,instructions:"Reply with the number of the option you want",prompt_source:"tmux_live",dialog_kind:"terminal_menu",has_details:!1}}),l.info("Published live terminal menu",{sessionId:e.sessionId,promptId:r.promptId,optionsCount:r.options.length})}async handleTmuxPromptCandidate(t,e,i){let s=this.sessionState;if(!s){this.tmuxPaneObserver.resetLastPromptHash();return}let r=this.tmuxPaneObserver.extractActiveApprovalBlock(t)?null:(0,pe.parseActiveTerminalMenu)(t);if(r){await this.handleTerminalMenu(r,s,i);return}if(await this.promoteWaitingPermissionRequest(t,s)||!e&&this.deferTmuxPromptCandidateForPermissionHook(s.sessionId,t,i))return;let n=e?.occurrenceKey;if(n&&this.hasRecentlyResolvedApprovalDedupeKey(s.sessionId,n))return;let o=(0,q.parseInteractivePrompt)(t);if(!o){this.raiseSuppressedBadge(s.sessionId,n??null);return}if(this.hasMatchingPermissionHookPrompt(o,s.sessionId)){l.debug("Skipping tmux prompt candidate already owned by PermissionRequest",{sessionId:s.sessionId,promptText:o.promptText});return}let c=this.getMostRecentPendingToolCall();if(!c){if(await new Promise(O=>setTimeout(O,500)),!this.isExpectedSessionStateCurrent(s)){l.warn("Dropping tmux prompt candidate after session generation changed",{sessionId:s.sessionId,currentSessionId:this.sessionState?.sessionId});return}if(!e&&this.deferTmuxPromptCandidateForPermissionHook(s.sessionId,t,i))return;c=this.getMostRecentPendingToolCall()}let d=e?.context??(c?this.buildApprovalPromptContextFromPendingCall(c):null);if(d&&!this.parsedPromptMatchesApprovalContext(o,d,t)){l.warn("Skipping tmux-detected prompt because parsed prompt does not match pending tool call",{callId:c?.callId,toolName:c?.name,parsedPromptText:o.promptText}),this.raiseSuppressedBadge(s.sessionId,n??null);return}let p=d?null:this.buildApprovalPromptContextFromParsedPrompt(o),u=d||p;if(!u){l.warn("Skipping tmux-detected prompt because no tool context could be derived from the parsed prompt",{parsedPromptText:o.promptText}),this.raiseSuppressedBadge(s.sessionId,n??null);return}let f=this.mapToolNameForApproval(u.toolName)==="Bash"?this.firstString(u.toolInput?.command,u.toolInput?.cmd):void 0,v=this.buildCodexPromptPresentation(o,f,t);if(!v){l.warn("Skipping tmux-detected prompt because Codex option hotkeys are unavailable",{parsedPromptText:o.promptText}),this.raiseSuppressedBadge(s.sessionId,n??null);return}let m=u?this.buildApprovalDedupeKey(u):void 0;if(m&&this.hasRecentlyResolvedApprovalDedupeKey(s.sessionId,m)){l.info("Skipping tmux-detected prompt; same approval was already answered recently",{promptText:o.promptText,dedupeKey:m});return}if(m&&this.hasActiveOrQueuedPermissionHookPrompt(s.sessionId,m)){c?.callId&&this.mergeCallIdIntoPromptByDedupeKey(s.sessionId,m,c.callId),l.info("Skipping tmux-detected prompt; PermissionRequest hook already emitted it",{promptText:o.promptText,dedupeKey:m});return}let g=u?this.buildToolDetailsForInteractivePrompt(u,t):{},w=g.tool_name||this.mapToolNameForApproval(c?.name),E=g.tool_input||(u?this.buildFallbackToolInput(u):void 0),S=!!(w&&E),b={promptId:c?.callId||(0,se.v4)(),callId:c?.callId,kind:v.kind,options:v.options,submitMap:v.submitMap,promptText:v.promptText,createdAt:Date.now(),source:"tmux",dedupeKey:m,ownerSessionId:s.sessionId,observerMatchKey:this.buildObserverPromptMatchKey(o),observerPromptHash:i,requiresFollowUpText:v.requiresFollowUpText},_={options:v.options,instructions:v.instructions,prompt_source:"tmux_live",toolName:u?.toolName,toolInput:u?.toolInput,hint:u?.hint,filePath:u?.filePath,diff:u?.diff,rawInput:u?.rawInput,tool_name:w,tool_input:E,has_details:S,dedupe_key:m},N=this.buildApprovalPromptContent(v.content,{toolName:w,toolInput:E,hint:u?.hint,filePath:u?.filePath});try{await this.enqueueOrEmitInteractivePrompt({prompt:b,content:N,metadata:_,ownerState:s})&&l.info("Sent tmux-detected interactive prompt",{sessionId:s.sessionId,promptText:o.promptText,kind:o.kind})}catch(O){l.error("Failed to send tmux-detected interactive prompt",{error:O})}}async enqueueOrEmitInteractivePrompt(t){if(!this.isExpectedSessionStateCurrent(t.ownerState))return l.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 l.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&&(l.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}}if(this.isSameInteractivePrompt(e,t.prompt)){if(t.prompt.source==="permission_hook"&&e.source!=="permission_hook"){e.source="permission_hook",e.completionKey=t.prompt.completionKey??e.dedupeKey,e.dedupeKey=t.prompt.dedupeKey;let i=this.e1PromptRaises.get(e.promptId);i&&(i.resolutionDedupeKey=e.dedupeKey,i.resolutionCompletionKey=e.completionKey)}return!e.callId&&t.prompt.callId&&(e.callId=t.prompt.callId,l.debug("Merged callId into existing interactive prompt",{source:e.source,callId:t.prompt.callId,promptText:e.promptText})),l.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}return this.queuedInteractivePrompts.some(i=>this.isSameInteractivePrompt(i.prompt,t.prompt))?(l.debug("Skipping duplicate queued interactive prompt",{candidateSource:t.prompt.source,candidateCallId:t.prompt.callId,promptText:t.prompt.promptText}),!1):(this.queuedInteractivePrompts.push(t),l.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.completionKey!==void 0?{completionKey:t.prompt.completionKey}:{},...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.resolutionCompletionKey??=t.prompt.completionKey,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??{}),await this.publishE1Prompt(e,s,h.EventType.INTERACTIVE_PROMPT,t.content,t.metadata??{})}rebindWaitingPermissionRequests(t){for(let e of this.waitingPermissionRequests.values())e.ownerState.codexSessionId&&e.ownerState.codexSessionId===t.codexSessionId&&(e.ownerState=t)}async promoteWaitingPermissionRequest(t,e){if(!this.isExpectedSessionStateCurrent(e))return!1;let i=(0,q.parseInteractivePrompt)(t);if(!i||this.hasMatchingPermissionHookPrompt(i,e.sessionId))return!1;for(let[s,r]of this.waitingPermissionRequests)if(this.isExpectedSessionStateCurrent(r.ownerState)&&this.parsedPromptMatchesApprovalContext(i,r.context,t)){this.waitingPermissionRequests.delete(s);try{await this.handlePermissionRequestHookWhileTracked(r.payload,e,r.context,s,r.dedupeKey,{parsedPrompt:i,snapshot:t})}catch(n){throw this.isExpectedSessionStateCurrent(e)&&!this.hasRecentlyResolvedApprovalDedupeKey(e.sessionId,s)&&this.waitingPermissionRequests.set(s,r),this.tmuxPaneObserver.resetLastPromptHash(),n}return!0}return!1}async emitNextQueuedInteractivePrompt(){if(this.pendingInteractivePrompt)return;if(this.queuedInteractivePrompts.length===0){let e=this.sessionState;if(e&&this.waitingPermissionRequests.size>0){let i=await this.tmuxPaneObserver.captureSnapshot();!(i&&await this.promoteWaitingPermissionRequest(i,e))&&this.isExpectedSessionStateCurrent(e)&&!this.pendingInteractivePrompt&&this.waitingPermissionRequests.size>0&&this.tmuxPaneObserver.resetLastPromptHash()}return}let t=this.queuedInteractivePrompts.shift();if(t){if(!this.isExpectedSessionStateCurrent(t.ownerState)){l.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),l.info("Emitted next queued interactive prompt",{callId:t.prompt.callId,queueLength:this.queuedInteractivePrompts.length})}catch(e){this.pendingInteractivePrompt=null,l.error("Failed to emit queued interactive prompt",{error:e}),await this.emitNextQueuedInteractivePrompt()}}}async clearObservedInteractivePrompt(t,e){if(!this.isExpectedSessionStateCurrent(t))return;let i=this.pendingInteractivePrompt;if(!i||i.ownerSessionId!==t.sessionId||i.observerPromptHash!==e){l.debug("Ignoring prompt-cleared for a non-current chooser occurrence",{sessionId:t.sessionId,clearedPromptHash:e,activePromptId:i?.promptId,activePromptHash:i?.observerPromptHash});return}this.pendingInteractivePrompt=null,i.callId&&this.approvalDetector.onToolCallComplete(i.callId),this.rememberResolvedApprovalDedupeKey(t.sessionId,i.dedupeKey);for(let r of this.queuedPermissionRequestRegistrations.get(t.sessionId)??[])r.occurrenceKey===i.dedupeKey&&(r.disposition="resolved",this.deferredTmuxPromptCandidates.delete(r),this.removePermissionRequestOccurrence(r.dedupeKey,r.occurrenceKey));let s=this.beginE1PromptResolutions(new Set([i.promptId]),t.sessionId);this.launchE1Resolutions(s),await this.emitNextQueuedInteractivePrompt()}async clearResolvedInteractivePrompt(t,e){if(!e){l.debug("Interactive prompt completion had no comparable dialog identity",{callId:t});return}let i=this.isPermissionRequestOccurrenceKey(e),s=this.pendingInteractivePrompt,r=!!s&&(s.dedupeKey===e||s.completionKey===e||!i&&!!t&&s.callId===t),n=this.sessionState?.sessionId??s?.ownerSessionId,o=this.queuedInteractivePrompts.find(S=>!i&&!!t&&S.prompt.callId===t||S.prompt.dedupeKey===e||S.prompt.completionKey===e),c=this.permissionRequestHookInFlight,d=c?.ownerState.sessionId===n&&(c?.dedupeKey===e||c?.occurrenceKey===e),u=(n?this.queuedPermissionRequestRegistrations.get(n)??[]:[]).find(S=>S.dedupeKey===e||S.occurrenceKey===e),f=[...this.waitingPermissionRequests.values()].find(S=>S.ownerState.sessionId===n&&(S.occurrenceKey===e||S.dedupeKey===e)),v=r?s?.dedupeKey:o?.prompt.dedupeKey??(d?c?.occurrenceKey:void 0)??u?.occurrenceKey??f?.occurrenceKey??e,m=new Set;if(r&&s&&m.add(s.promptId),o&&m.add(o.prompt.promptId),n&&v){let S=this.e1ContentKeyIndex.get(`${n}::${v}`);S&&m.add(S)}let g=[...this.e1PromptRaises.entries()].find(([,S])=>S.record.sessionId===n&&(S.resolutionDedupeKey===v||!i&&!!t&&S.resolutionCallId===t||S.resolutionCompletionKey===e));if(g&&m.add(g[0]),(r||d||u||f||m.size>0)&&this.rememberResolvedApprovalDedupeKey(n,v),r&&s&&(this.pendingInteractivePrompt=null),u&&(u.disposition="resolved"),v)for(let S of this.removeQueuedInteractivePromptByDedupeKey(v))m.add(S);let E=n?this.beginE1PromptResolutions(m,n):[];this.launchE1Resolutions(E),(r||!this.pendingInteractivePrompt&&o)&&await this.emitNextQueuedInteractivePrompt()}clearInteractivePromptsForAcceptedInput(t){let e=t.sessionId,i=new Set,s=this.pendingInteractivePrompt;s?.ownerSessionId===e&&(i.add(s.promptId),this.rememberResolvedApprovalDedupeKey(e,s.dedupeKey),this.pendingInteractivePrompt=null);let r=[];for(let o of this.queuedInteractivePrompts)o.prompt.ownerSessionId===e?(i.add(o.prompt.promptId),this.rememberResolvedApprovalDedupeKey(e,o.prompt.dedupeKey)):r.push(o);this.queuedInteractivePrompts=r;for(let[o,c]of this.e1PromptRaises.entries())c.record.sessionId===e&&i.add(o);for(let o of this.queuedPermissionRequestRegistrations.get(e)??[])o.disposition="resolved",this.rememberResolvedApprovalDedupeKey(e,o.occurrenceKey),this.deferredTmuxPromptCandidates.delete(o);for(let[o,c]of this.waitingPermissionRequests)c.ownerState.sessionId===e&&(this.rememberResolvedApprovalDedupeKey(e,o),this.waitingPermissionRequests.delete(o));this.permissionRequestOccurrencesByCompletionKey.clear();let n=this.beginE1PromptResolutions(i,e);this.launchE1Resolutions(n)}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&&l.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.completionKey??s.dedupeKey)===e&&!s.callId){s.callId=i;let n=this.e1PromptRaises.get(s.promptId);n&&(n.resolutionCallId??=i),l.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.completionKey??n.prompt.dedupeKey)===e&&!n.prompt.callId);r&&(r.prompt.callId=i,l.debug("Merged callId into queued deduped interactive prompt",{source:r.prompt.source,callId:i,dedupeKey:e}))}isSameInteractivePrompt(t,e){if(t.ownerSessionId!==e.ownerSessionId||Date.now()-t.createdAt>rs)return!1;if(t.callId&&e.callId)return t.callId===e.callId;let s=t.completionKey??t.dedupeKey,r=e.completionKey??e.dedupeKey;return t.source!==e.source&&s&&s===r&&t.observerMatchKey&&t.observerMatchKey===e.observerMatchKey?!0: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 l.debug("Skipping tmux pane observer start - no tmux session in environment"),!0;try{return await this.tmuxPaneObserver.start(t),!0}catch(e){return l.warn("Failed to start tmux pane observer",{tmuxSession:t,error:e}),!1}}async startTmuxObserverWithBeacon(t){try{await this.startTmuxObserver()?await x("daemon_init_step_completed",{step:"tmux_observer_start",path:t}):await x("daemon_init_step_failed",{step:"tmux_observer_start",path:t,error_class:"TmuxObserverStartFailed",error_message:"tmuxPaneObserver.start threw (see plugin log)"})}catch(e){await x("daemon_init_step_failed",{step:"tmux_observer_start",path:t,error_class:e?.name||"Error",error_message:e?.message||String(e)}),l.error("Failed to start tmux observer:",e)}}async tryParseInteractivePromptFromTmux(){try{let t=await this.tmuxPaneObserver.captureSnapshot(),e=this.tmuxPaneObserver.extractActiveApprovalBlock(t),i=e?(0,q.parseInteractivePrompt)(e):null;return l.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 l.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(c=>setTimeout(c,125)),e&&!e()))return null;let o=await this.tryParseInteractivePromptFromTmux();if(o&&(r=o),o?.parsedPrompt&&(!t||t(o.parsedPrompt,o.snapshot)))return o}return r?.snapshot?{parsedPrompt:null,snapshot:r.snapshot,...r.parsedPrompt?{differentPrompt:!0}:{}}: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=Xt(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||!ns.test(s))return null;s==="esc"||s==="escape"?e[i.number]=te: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.completionKey??i.dedupeKey)===e?!0:this.queuedInteractivePrompts.some(s=>s.prompt.ownerSessionId===t&&s.prompt.source==="permission_hook"&&(s.prompt.completionKey??s.prompt.dedupeKey)===e)||[...this.waitingPermissionRequests.values()].some(s=>s.ownerState.sessionId===t&&s.dedupeKey===e)}hasDurablePermissionHookFallback(t){return[...this.e1PromptRaises.values()].some(e=>e.record.sessionId===t&&e.suppressTmuxObserverUntilResolved===!0)}hasDurablePermissionHookFallbackByDedupeKey(t,e){return[...this.e1PromptRaises.values()].some(i=>i.record.sessionId===t&&i.suppressTmuxObserverUntilResolved===!0&&(i.resolutionDedupeKey===e||i.resolutionCompletionKey===e))}hasMatchingDurablePermissionHookFallback(t,e,i){let s=this.buildApprovalPromptContextFromParsedPrompt(t),r=s?this.buildApprovalDedupeKey(s):void 0;if(r&&this.hasDurablePermissionHookFallbackByDedupeKey(e,r))return!0;if(!i)return!1;let n=this.buildObserverSnapshotMatchKey(i);return[...this.e1PromptRaises.values()].some(o=>o.record.sessionId===e&&o.suppressTmuxObserverUntilResolved===!0&&o.suppressedObserverSnapshotKey===n)}deferTmuxPromptCandidateForPermissionHook(t,e,i){let s=this.queuedPermissionRequestSessionCounts.get(t)??0,r=this.hasDurablePermissionHookFallback(t);if(s<=0&&!r)return!1;let n=(0,q.parseInteractivePrompt)(e);if(n&&this.hasMatchingDurablePermissionHookFallback(n,t,e))return l.debug("Skipping tmux repaint already owned by a durable PermissionRequest fallback",{sessionId:t,promptText:n.promptText}),!0;if(n&&this.hasMatchingPermissionHookPrompt(n,t))return l.debug("Skipping tmux repaint already owned by an actionable PermissionRequest",{sessionId:t,promptText:n.promptText}),!0;if(n&&s<=0)return!1;if(s>0){let o=this.queuedPermissionRequestRegistrations.get(t)??[],c=n?o.find(u=>this.parsedPromptMatchesApprovalContext(n,u.context,e)):void 0,d=!n&&this.permissionRequestHookInFlight?.ownerState.sessionId===t?this.permissionRequestHookInFlight.registration:void 0,p=c??d??(o.length===1&&(!n||!r)?o[0]:void 0);if(p&&this.deferredTmuxPromptCandidates.set(p,{snapshot:e,promptHash:i}),n&&!p)return!1}return l.debug("Skipping tmux prompt candidate while PermissionRequest owns the session prompt",{sessionId:t,toolName:this.permissionRequestHookInFlight?.context.toolName,ownership:s>0?"queued_or_in_flight":"durable_prompt"}),!0}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:${de.createHash("sha256").update(i).digest("hex").slice(0,16)}`}buildObserverSnapshotMatchKey(t){let e=this.normalizeObserverPromptText(t);return`snapshot:${de.createHash("sha256").update(e).digest("hex").slice(0,16)}`}normalizeObserverPromptText(t){return t.replace(/\r\n?/g,`
|
|
23
|
+
`).trim();return(0,ae.createHash)("sha256").update(s).digest("hex")}};var j=require("@quantiya/codevibe-core");var ge=require("@quantiya/codevibe-core");var je=A(require("express")),V=A(require("fs")),Tt=A(require("path")),xt=A(require("os"));var Li=1800*1e3,qi=60*1e3,Ki=1440*60*1e3;var Te=class{constructor(){this.assignedPort=0;this.portRefreshTimer=null;this.app=(0,je.default)(),this.setupMiddleware(),this.setupRoutes(),this.tmuxSession=process.env.CODEVIBE_CODEX_TMUX_SESSION}getPort(){return this.assignedPort}setupMiddleware(){this.app.use(je.default.json({limit:"1mb"})),this.app.use((e,t,i)=>{a.debug(`${e.method} ${e.path}`,{body:e.body}),i()})}setupRoutes(){this.app.get("/health",(e,t)=>{t.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(e,t){try{let i=e.body;if(!i.session_id||!i.hook_event_name){t.status(400).json({success:!1,error:"Missing session_id or hook_event_name"});return}let s=this.transformHookToEvent(i);if(a.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=>{a.error("Error resolving PermissionRequest after acknowledgement:",n)}),t.json({success:!0});return}await r}t.json({success:!0})}catch(i){a.error("Error handling event:",i),t.status(500).json({success:!1,error:i instanceof Error?i.message:"Unknown error"})}}transformHookToEvent(e){let t={cwd:e.cwd,hook_event_name:e.hook_event_name,transcript_path:e.transcript_path,...e.metadata||{}},i,s;switch(e.hook_event_name){case"SessionStart":i="NOTIFICATION",s="Session started",t.source=e.source,t.model=e.model;break;case"UserPromptSubmit":i="USER_PROMPT",s=e.prompt||"";break;case"PreToolUse":i="NOTIFICATION",s="PreToolUse observed",t.tool_name=e.tool_name,t.tool_input=e.tool_input,t.tool_use_id=e.tool_use_id,t.approval_status="observed_pre_tool",t.requires_user_action=!1;break;case"PermissionRequest":i="NOTIFICATION",s="PermissionRequest observed",t.tool_name=e.tool_name,t.tool_input=e.tool_input,t.permission_mode=e.permission_mode,t.turn_id=e.turn_id,t.requires_user_action=!0;break;case"PostToolUse":i="TOOL_USE",s=JSON.stringify({tool_name:e.tool_name,tool_input:e.tool_input,tool_response:e.tool_response}),t.tool_name=e.tool_name,t.tool_input=e.tool_input,t.tool_use_id=e.tool_use_id;break;case"Stop":i="ASSISTANT_RESPONSE",s=e.last_assistant_message||"";break;default:i="NOTIFICATION",s=`Hook: ${e.hook_event_name}`}return{session_id:e.session_id,hook_event_name:e.hook_event_name,type:i,source:"DESKTOP",content:s,metadata:t}}onEvent(e){this.eventHandler=e}async start(){return new Promise((e,t)=>{try{this.server=this.app.listen(0,"localhost",()=>{let i=this.server.address();this.assignedPort=i.port,a.info(`HTTP API listening on http://localhost:${this.assignedPort}`),this.writePortFile(this.assignedPort),this.startPortFileKeepalive(),e(this.assignedPort)}),this.server.on("error",i=>{a.error("HTTP server error:",i),t(i)})}catch(i){t(i)}})}portFilePath(){return this.tmuxSession?Tt.join(xt.tmpdir(),`codevibe-codex-${this.tmuxSession}.port`):null}writePortFile(e){let t=this.portFilePath();if(!t){a.warn("No CODEVIBE_CODEX_TMUX_SESSION set, skipping port file");return}try{V.writeFileSync(t,e.toString()),a.info(`Port file written: ${t} -> ${e}`)}catch(i){a.error(`Failed to write port file: ${t}`,i)}}removePortFile(){let e=this.portFilePath();if(e)try{V.existsSync(e)&&(V.unlinkSync(e),a.info(`Port file removed: ${e}`))}catch(t){a.warn(`Failed to remove port file: ${e}`,t)}}startPortFileKeepalive(){this.portRefreshTimer&&(clearInterval(this.portRefreshTimer),this.portRefreshTimer=null);let e=Number(process.env.CODEVIBE_PORTFILE_REFRESH_MS),t=Number.isFinite(e)&&e>0?Math.min(Ki,Math.max(qi,e)):Li;this.portRefreshTimer=setInterval(()=>this.refreshPortFile(),t)}refreshPortFile(){let e=this.portFilePath();if(e)try{let t=new Date;V.utimesSync(e,t,t)}catch(t){t?.code==="ENOENT"?this.writePortFile(this.assignedPort):a.warn(`Port-file refresh failed: ${e}`,t)}}async stop(){return this.portRefreshTimer&&(clearInterval(this.portRefreshTimer),this.portRefreshTimer=null),this.removePortFile(),new Promise(e=>{this.server?this.server.close(()=>{a.info("HTTP API stopped"),e()}):e()})}};var xe=class{constructor(e={}){this.pendingBySession=new Map;this.expiryMs=e.expiryMs??1e4,this.minFuzzyEchoLength=e.minFuzzyEchoLength??16,this.minFuzzyEchoRatio=e.minFuzzyEchoRatio??.35,this.now=e.now??Date.now}track(e,t){let i=this.normalize(t);if(!i)return;let s=this.validEntries(e);s.push({normalized:i,timestamp:this.now()}),this.pendingBySession.set(e,s)}forget(e,t){let i=this.normalize(t);if(!i)return;let s=!1,r=this.validEntries(e).filter(n=>!s&&n.normalized===i?(s=!0,!1):!0);this.replaceEntries(e,r)}consumeIfDuplicate(e,t){let i=this.normalize(t);if(!i)return null;let s=null,r=this.validEntries(e).filter(n=>{if(!s){let o=this.matchType(n.normalized,i);if(o)return s={matchType:o,originalLength:n.normalized.length,echoLength:i.length},!1}return!0});return this.replaceEntries(e,r),s}peekIfDuplicate(e,t){let i=this.normalize(t);if(!i)return null;for(let s of this.validEntries(e)){let r=this.matchType(s.normalized,i);if(r)return{matchType:r,originalLength:s.normalized.length,echoLength:i.length}}return null}validEntries(e){let t=this.now()-this.expiryMs;return(this.pendingBySession.get(e)||[]).filter(i=>i.timestamp>=t)}replaceEntries(e,t){t.length>0?this.pendingBySession.set(e,t):this.pendingBySession.delete(e)}matchType(e,t){if(e===t)return"exact";let i=t.length>=this.minFuzzyEchoLength,s=t.length/e.length>=this.minFuzzyEchoRatio;return i&&s&&e.endsWith(t)?"suffix":null}normalize(e){return e.replace(/\s+/g," ").trim()}};var Ot=A(require("crypto")),At=A(require("fs")),kt=A(require("https")),Ce=A(require("os")),Ft=A(require("path")),Bi="G-GS74YEQTB8",Ui="lAfOF6OxRzSQ-NsLBRjhAg",Hi="www.google-analytics.com",$i=`/mp/collect?measurement_id=${Bi}&api_secret=${Ui}`,Ct=800;function Qi(){try{let d=Ft.resolve(__dirname,"..","package.json"),e=At.readFileSync(d,"utf-8"),t=JSON.parse(e);if(typeof t.version=="string"&&t.version.length>0&&t.version.length<30)return t.version}catch{}return"unknown"}var Wi=Qi();function ji(){let d=typeof process.getuid=="function"?process.getuid():0;return Ot.createHash("sha256").update(`${Ce.hostname()}-${d}`).digest("hex").substring(0,36)}function zi(d){if(!d)return"";let e=Ce.homedir(),t=d.replace(/[\n\r\t]/g," ");if(e&&e.length>0){let i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replace(new RegExp(i,"g"),"~")}return t=t.replace(/\/Users\/[^/\s"'`]+/g,"/Users/<user>").replace(/\/home\/[^/\s"'`]+/g,"/home/<user>").replace(/[^\x20-\x7E]/g,""),t.trim().substring(0,100)}function k(d,e){return new Promise(t=>{let i,s=!1,r=()=>{s||(s=!0,clearTimeout(n),t())},n=setTimeout(()=>{try{i?.destroy()}catch{}r()},Ct);typeof n.unref=="function"&&n.unref();try{let o={...e};typeof o.error_message=="string"&&(o.error_message=zi(o.error_message));let l=JSON.stringify({client_id:ji(),events:[{name:d,params:{agent:"codex",plugin_version:Wi,platform:process.platform,source:process.env.CODEVIBE_TELEMETRY_SOURCE||"production",...o}}]});i=kt.request({hostname:Hi,path:$i,method:"POST",headers:{"Content-Type":"application/json"},timeout:Ct},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 Oe=class{constructor(){this.originated=new Set;this.externallyResolved=new Set}markOriginated(e){this.originated.add(e)}clearOriginated(e){this.originated.delete(e)}getOriginated(){return new Set(this.originated)}getExternallyResolved(){return new Set(this.externallyResolved)}isExternallyResolved(e){return this.externallyResolved.has(e)}dispatch(e){let{gateId:t}=e;return this.originated.has(t)?(this.originated.delete(t),this.externallyResolved.add(t),"self_echo"):(this.externallyResolved.add(t),"foreign")}clear(){this.originated.clear(),this.externallyResolved.clear()}};function Nt(d){return`[CodeVibe] Decision recorded on another device: ${d} \u2014 type any number to dismiss the open AskUserQuestion`}var Dt=require("@quantiya/codevibe-core"),Gi=new Set(["stall-retirement","stall-tmux-probe"]),Vi=1e3,Ae;function Yi(d=process.env){let e=new Map,t=d.CODEVIBE_DEV_FAULTS;if(t&&(0,Dt.getEnvironment)()==="development")for(let i of t.split(",")){let[s,r]=i.trim().split(":");if(!Gi.has(s))continue;let n=r===void 0?1:Number.parseInt(r,10);!Number.isSafeInteger(n)||n<=0||n>Vi||e.set(s,n)}return Ae=e,e}function ze(d){Ae||Yi();let e=Ae.get(d)??0;return e<=0?!1:(Ae.set(d,e-1),!0)}async function Ge(d,e,t){let i;try{let s=(()=>{try{return Promise.resolve(d())}catch(o){return Promise.reject(o)}})(),r=new Promise(o=>{i=setTimeout(()=>o("timeout"),e),i.unref&&i.unref()}),n=await Promise.race([s.then(()=>"settled",()=>"settled"),r]);if(n==="timeout"){s.catch(()=>{});try{t?.()}catch{}}return n}finally{i&&clearTimeout(i)}}function he(d,e,t=25e3,i=()=>!0){let s=setTimeout(()=>{try{e()}catch{}let r=!1;try{r=i()}catch{r=!1}d(r?0:1)},t);return()=>clearTimeout(s)}var me=A(require("crypto")),_=A(require("fs")),Fe=A(require("os")),Q=A(require("path")),qt=require("@quantiya/codevibe-core"),Ve=2*1024*1024,Xi=600*1e3,z=1e3;function Kt(){return typeof process.getuid=="function"?process.getuid():void 0}function Ye(d,e){let t=Kt();if(t!==void 0&&d.uid!==t)throw new Error(`E1_STATE_FOREIGN_OWNER: ${e}`)}function Bt(d){_.mkdirSync(d,{recursive:!0,mode:448});let e=_.lstatSync(d);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`E1_STATE_ROOT_NOT_PRIVATE_DIRECTORY: ${d}`);Ye(e,d),process.platform!=="win32"&&_.chmodSync(d,448)}function Mt(d,e){let t=Q.dirname(d);Bt(t);let i=`${JSON.stringify(e)}
|
|
24
|
+
`;if(Buffer.byteLength(i,"utf8")>Ve)throw new Error(`E1_STATE_TOO_LARGE: ${d}`);let s=Q.join(t,`.${Q.basename(d)}.${process.pid}.${me.randomUUID()}.tmp`),r=_.constants.O_NOFOLLOW??0,n=null;try{n=_.openSync(s,_.constants.O_WRONLY|_.constants.O_CREAT|_.constants.O_EXCL|r,384),_.writeFileSync(n,i,{encoding:"utf8"}),_.fsyncSync(n),_.closeSync(n),n=null,process.platform!=="win32"&&_.chmodSync(s,384),_.renameSync(s,d),process.platform!=="win32"&&_.chmodSync(d,384);try{let o=_.openSync(t,_.constants.O_RDONLY);try{_.fsyncSync(o)}finally{_.closeSync(o)}}catch{}}finally{n!==null&&_.closeSync(n);try{_.unlinkSync(s)}catch(o){if(o.code!=="ENOENT")throw o}}}function Lt(d){let e;try{e=_.lstatSync(d)}catch(s){if(s.code==="ENOENT")return null;throw s}if(!e.isFile()||e.isSymbolicLink())throw new Error(`E1_STATE_NOT_REGULAR_FILE: ${d}`);if(Ye(e,d),process.platform!=="win32"&&(e.mode&63)!==0)throw new Error(`E1_STATE_PERMISSIONS_LOOSE: ${d}`);if(e.size>Ve)throw new Error(`E1_STATE_TOO_LARGE: ${d}`);let t=_.constants.O_NOFOLLOW??0,i=_.openSync(d,_.constants.O_RDONLY|t);try{let s=_.fstatSync(i);if(Ye(s,d),!s.isFile()||e.dev!==s.dev||e.ino!==s.ino)throw new Error(`E1_STATE_FILE_CHANGED_DURING_OPEN: ${d}`);if(s.size>Ve)throw new Error(`E1_STATE_TOO_LARGE: ${d}`);return JSON.parse(_.readFileSync(i,{encoding:"utf8"}))}finally{_.closeSync(i)}}function D(d){return d!==null&&typeof d=="object"&&!Array.isArray(d)}function O(d,e=256*1024){return typeof d=="string"&&Buffer.byteLength(d,"utf8")<=e}function Ut(d){if(!D(d)||!O(d.promptId,512)||!O(d.ownerToken,512)||!O(d.sessionId,1024)||d.producerKind!=="PLUGIN_APPROVAL"||d.agentType!==void 0&&d.agentType!=="CODEX"||d.title!==void 0&&!O(d.title,4096)||typeof d.mobileActionable!="boolean"||typeof d.raisedAtMs!="number"||!Number.isFinite(d.raisedAtMs))return!1;try{return(0,qt.deriveOpenPromptId)(d.ownerToken)===d.promptId}catch{return!1}}function Ji(d){if(!D(d)||!Ut(d.record))return!1;for(let e of["contentPlain","resolutionDedupeKey","resolutionCompletionKey","resolutionCallId","suppressedObserverSnapshotKey"])if(d[e]!==void 0&&!O(d[e]))return!1;return!(d.metadataPlain!==void 0&&!D(d.metadataPlain)||d.suppressTmuxObserverUntilResolved!==void 0&&typeof d.suppressTmuxObserverUntilResolved!="boolean")}function Ht(d){return D(d)&&Ut(d.record)&&O(d.resolutionAt,128)&&!Number.isNaN(Date.parse(d.resolutionAt))&&typeof d.attempts=="number"&&Number.isSafeInteger(d.attempts)&&d.attempts>=0}function $t(d){if(!D(d)||!O(d.promptId,512)||!["yes_no","numbered","text","queued_question"].includes(String(d.kind))||!Array.isArray(d.options)||d.options.length>100||!d.options.every(i=>D(i)&&O(i.number,32)&&O(i.text,32*1024)&&(i.description===void 0||O(i.description,32*1024))&&(i.preview===void 0||O(i.preview,32*1024)))||!D(d.submitMap)||!Object.entries(d.submitMap).every(([i,s])=>O(i,128)&&O(s,32*1024))||!O(d.promptText)||typeof d.createdAt!="number"||!Number.isFinite(d.createdAt)||!["permission_hook","tmux","heuristic","queued_question"].includes(String(d.source)))return!1;for(let i of["callId","dedupeKey","completionKey","ownerSessionId","observerMatchKey","observerPromptHash","terminalMenuIdentity"])if(d[i]!==void 0&&!O(d[i],32*1024))return!1;if(d.requiresFollowUpText!==void 0&&typeof d.requiresFollowUpText!="boolean")return!1;let e=d.preemptedQueuedQuestionId!==void 0,t=d.preemptedQueuedQuestionAt!==void 0;if(e!==t||e&&(!O(d.preemptedQueuedQuestionId,512)||d.preemptedQueuedQuestionId.trim().length===0||typeof d.preemptedQueuedQuestionAt!="number"||!Number.isFinite(d.preemptedQueuedQuestionAt)||d.preemptedQueuedQuestionAt<=0))return!1;if(d.allQuestions!==void 0){if(!Array.isArray(d.allQuestions)||d.allQuestions.length>100)return!1;for(let i of d.allQuestions){if(!D(i)||!O(i.question,32*1024)||!Array.isArray(i.options)||i.options.length>100||i.header!==void 0&&!O(i.header,1024)||i.multiSelect!==void 0&&typeof i.multiSelect!="boolean")return!1;for(let s of i.options)if(typeof s=="string"){if(!O(s,32*1024))return!1}else if(D(s)){if(!O(s.label,32*1024)||s.description!==void 0&&!O(s.description,32*1024)||s.preview!==void 0&&!O(s.preview,32*1024))return!1}else return!1}}return!0}function Zi(d){return D(d)&&$t(d.prompt)&&O(d.content)&&D(d.metadata)}function es(d,e,t){if(!D(d)||d.version!==1)throw new Error("E1_HANDOFF_UNSUPPORTED_VERSION");if(d.tmuxSession!==e||!O(d.backendSessionId,1024))throw new Error("E1_HANDOFF_INSTANCE_MISMATCH");if(typeof d.createdAtMs!="number"||!Number.isFinite(d.createdAtMs))throw new Error("E1_HANDOFF_INVALID_TIMESTAMP");if(d.createdAtMs>t+6e4||t-d.createdAtMs>Xi)throw new Error("E1_HANDOFF_STALE");if(!Array.isArray(d.openRaises)||d.openRaises.length>z||!d.openRaises.every(Ji))throw new Error("E1_HANDOFF_INVALID_OPEN_RAISES");if(!Array.isArray(d.pendingResolutions)||d.pendingResolutions.length>z||!d.pendingResolutions.every(Ht))throw new Error("E1_HANDOFF_INVALID_PENDING_RESOLUTIONS");if(!Array.isArray(d.needsReRaisePromptIds)||d.needsReRaisePromptIds.length>z||!d.needsReRaisePromptIds.every(s=>O(s,512)))throw new Error("E1_HANDOFF_INVALID_RERAISE_IDS");if(!Array.isArray(d.permissionOccurrences)||d.permissionOccurrences.length>z)throw new Error("E1_HANDOFF_INVALID_OCCURRENCES");if(!d.permissionOccurrences.every(s=>Array.isArray(s)&&s.length===2&&O(s[0],256*1024)&&Array.isArray(s[1])&&s[1].length<=z&&s[1].every(r=>D(r)&&O(r.occurrenceKey,512)&&typeof r.hookObserved=="boolean"&&typeof r.jsonlObserved=="boolean")))throw new Error("E1_HANDOFF_INVALID_OCCURRENCES");if(d.waitingPermissionRequests!==void 0&&(!Array.isArray(d.waitingPermissionRequests)||d.waitingPermissionRequests.length>z||!d.waitingPermissionRequests.every(s=>D(s)&&O(s.occurrenceKey,512)&&(s.dedupeKey===void 0||O(s.dedupeKey))&&D(s.payload)&&s.payload.hook_event_name==="PermissionRequest"&&(s.payload.metadata===void 0||D(s.payload.metadata)))))throw new Error("E1_HANDOFF_INVALID_WAITING_REQUESTS");if(d.pendingInteractivePrompt!==null&&!$t(d.pendingInteractivePrompt))throw new Error("E1_HANDOFF_INVALID_ACTIVE_PROMPT");if(!Array.isArray(d.queuedInteractivePrompts)||d.queuedInteractivePrompts.length>z||!d.queuedInteractivePrompts.every(Zi))throw new Error("E1_HANDOFF_INVALID_QUEUED_PROMPTS");if(!Array.isArray(d.resolvedApprovalDedupeKeys)||d.resolvedApprovalDedupeKeys.length>z||!d.resolvedApprovalDedupeKeys.every(s=>Array.isArray(s)&&s.length===2&&O(s[0])&&typeof s[1]=="number"&&Number.isFinite(s[1])))throw new Error("E1_HANDOFF_INVALID_RESOLVED_KEYS");if(d.historicalQueuedQuestionPromptIds!==void 0&&(!Array.isArray(d.historicalQueuedQuestionPromptIds)||d.historicalQueuedQuestionPromptIds.length>z||!d.historicalQueuedQuestionPromptIds.every(s=>O(s,512))))throw new Error("E1_HANDOFF_INVALID_HISTORICAL_QUESTION_IDS");return d}function ts(d){if(!D(d)||d.version!==1||!Ht(d.pending))throw new Error("E1_RESOLUTION_OUTBOX_INVALID_RECORD");if(typeof d.updatedAtMs!="number"||!Number.isFinite(d.updatedAtMs))throw new Error("E1_RESOLUTION_OUTBOX_INVALID_TIMESTAMP");return d}var ke=class{constructor(e={}){let t=Kt()??"nouid";this.handoffRoot=e.handoffRoot??Q.join(Fe.tmpdir(),`codevibe-codex-handoff-${t}`),this.resolutionRoot=e.resolutionRoot??Q.join(Fe.homedir(),".codevibe","codex","e1-resolution-outbox"),this.now=e.now??Date.now}handoffPath(e){let t=me.createHash("sha256").update(e).digest("hex").slice(0,32);return Q.join(this.handoffRoot,`${t}.json`)}resolutionPath(e){let t=me.createHash("sha256").update(e).digest("hex");return Q.join(this.resolutionRoot,`${t}.json`)}writeHandoff(e){Mt(this.handoffPath(e.tmuxSession),e)}readHandoff(e){let t=Lt(this.handoffPath(e));if(t===null)return null;try{return es(t,e,this.now())}catch(i){if(i.message==="E1_HANDOFF_STALE")return this.removeHandoff(e),null;throw i}}removeHandoff(e){try{_.unlinkSync(this.handoffPath(e))}catch(t){if(t.code!=="ENOENT")throw t}}writeResolution(e){Mt(this.resolutionPath(e.record.promptId),{version:1,updatedAtMs:this.now(),pending:e})}removeResolution(e){try{_.unlinkSync(this.resolutionPath(e))}catch(t){if(t.code!=="ENOENT")throw t}}readResolutions(){let e;try{Bt(this.resolutionRoot),e=_.readdirSync(this.resolutionRoot).filter(s=>s.endsWith(".json"))}catch(s){if(s.code==="ENOENT")return{records:[],rejected:[]};throw s}let t=[],i=[];for(let s of e.slice(0,z)){let r=Q.join(this.resolutionRoot,s);try{let n=Lt(r);if(n!==null){let o=ts(n).pending;if(Q.basename(this.resolutionPath(o.record.promptId))!==s)throw new Error("E1_RESOLUTION_OUTBOX_IDENTITY_MISMATCH");t.push(o)}}catch(n){i.push({file:r,reason:n instanceof Error?n.message:String(n)})}}return e.length>z&&i.push({file:this.resolutionRoot,reason:`E1_RESOLUTION_OUTBOX_RECORD_LIMIT: ${e.length}`}),{records:t,rejected:i}}};var Gt=(0,et.promisify)(Le.exec),is=(0,et.promisify)(Le.execFile),ss="/quit",Y="CODEVIBE_CODEX_TMUX_SESSION",Ne="CODEVIBE_CODEX_DAEMON_RECOVERY",rs=1e3,ns=1e4,De=3,os=100,Vt=["SIGINT","SIGTERM","SIGHUP"],as=600*1e3,Xe=30*1e3,ds=/^(?:[a-z0-9]|esc|escape)$/;function jt(d,e){let t=d?.[e];return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("utf8"):""}function Yt(d){if(typeof d?.code!="number")return"unknown";let e=`${jt(d,"stderr")}
|
|
25
|
+
${jt(d,"stdout")}`;return/^can't find session:/m.test(e)||/^no server running on /m.test(e)||/^error connecting to .* \((?:No such file or directory|Connection refused)\)$/m.test(e)?"absent":"unknown"}async function ls(d,e){let t=async(i,s)=>{try{await Gt(i)}catch(r){a.warn("tmux send-keys failed during self-terminate",{sessionName:d,label:s,error:String(r)})}};await t(`tmux send-keys -t "${d}" C-c`,"ctrl-c"),await new Promise(i=>setTimeout(i,200)),await t(`tmux send-keys -t "${d}" -l "${e}"`,"quit-text"),await new Promise(i=>setTimeout(i,500)),await t(`tmux send-keys -t "${d}" Enter`,"enter")}function it(d){let e=d.split(`
|
|
26
|
+
`),t=n=>/^[\s>]*\d+\.\s/.test(n),i=-1;for(let n=e.length-1;n>=0;n-=1)if(/^\s*\$\s+/.test(e[n])){i=n;break}if(i===-1)return;let s=e[i].trim().match(/^\$\s+(.+)$/);if(!s?.[1]?.trim())return;let r=[s[1].trim()];for(let n=i+1;n<e.length;n+=1){let o=e[n];if(t(o)||/^\s*$/.test(o)||/^\s*\$\s+/.test(o))break;r.push(o.trim())}return r.length>0?r:void 0}function Xt(d){let e=it(d);if(!e)return;let t=e.join(" ").trim();return t.length>0?t:void 0}function Jt(d,e){return ps(d,e).has(e)}function ps(d,e){if(d.length===0)return new Set;let t=e,i=new Set([d[0]]);for(let s of d.slice(1)){let r=s,n=new Set;for(let o of i)for(let l of[""," "]){let p=`${o}${l}${r}`;t.startsWith(p)&&n.add(p)}if(n.size===0)return new Set;i=n}return i}function cs(d,e,t){let i=/^\[\u2026\s+\d+\s+lines\]\s+ctrl\s*\+\s*a\s+view\s+all$/i,s=d.split(`
|
|
27
|
+
`).map(r=>r.trim()).filter(Boolean);return s.length<2||!i.test(s[s.length-1])||!t?!1:us(t,e)}function us(d,e){let t=Ze(e),i=ei(d,"2");if(!t||!i)return!1;let s=new Set;for(let r of ti(i)){let n=r.match(/^Yes, and don't ask again for commands that start with `([^`]*)`\s*\(p\)$/);if(!n)continue;let o=Ze(n[1]);o&&JSON.stringify(o)===JSON.stringify(t)&&s.add(JSON.stringify(o))}return s.size===1}function Zt(d,e,t){if(!d.find(u=>u.number==="2"&&/\(p\)\s*$/i.test(u.text)))return d;let s="Yes, and don't ask again for commands that start with",r="Yes, and don't ask again (p)",n=ei(t,"2");if(!n)return null;let o=ti(n);if(o.has(r))return d.map(u=>u.number==="2"?{...u,text:r}:u);if(!e)return null;let l=new Map;for(let u of o){let h=u.match(/^Yes, and don't ask again for commands that start with `([^`]*)`\s*\(p\)$/);if(!h)continue;let g=Ze(h[1]);!g||!ms(g,e)||l.set(JSON.stringify(g),g)}if(l.size!==1)return null;let p=[...l.values()][0],c=hs(p);return d.map(u=>u.number==="2"?{...u,text:`${s} \`${c}\` (p)`}:u)}function ei(d,e){if(!d)return null;let t=(0,j.normalizeSnapshot)(d).split(`
|
|
28
|
+
`).map(o=>o.trim()),i=new RegExp(`^(?:[>\u203A\u276F\u25B8\u25B6\u279C\u27A4*\u25CF]\\s*)?${e}\\.\\s+(.*)$`),s=-1,r="";for(let o=t.length-1;o>=0;o-=1){let l=t[o].match(i);if(l){s=o,r=l[1];break}}if(s<0)return null;let n=[r];for(let o=s+1;o<t.length&&!(/^(?:[>›❯▸▶➜➤*●]\s*)?\d+\.\s+/.test(t[o])||!t[o]||(n.push(t[o]),/\(p\)\s*$/i.test(t[o])));o+=1);return n.some(o=>/\(p\)\s*$/i.test(o))?n:null}function ti(d){if(d.length===0||d.length>13)return new Set;let e=new Set([d[0]]);for(let t of d.slice(1)){let i=new Set;for(let s of e)i.add(`${s}${t}`),i.add(`${s} ${t}`);e=i}return e}function Ze(d){try{let e=(0,tt.parse)(d,t=>`\${${t}}`);return e.every(t=>typeof t=="string")?e:null}catch{return null}}function hs(d){return d.map(e=>/^[A-Za-z0-9_@%+=:,./-]+$/.test(e)?e:`'${e.replace(/'/g,`'"'"'`)}'`).join(" ")}function te(d){return d.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"")}function zt(d){return d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ms(d,e){if(d.length===0)return!1;let t;try{t=(0,tt.parse)(e,s=>`\${${s}}`)}catch{return!1}let i=[[]];for(let s of t){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=>d.every((r,n)=>s[n]===r))}var Me=class d{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 Map;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.nativeSourceSelection=null;this.nativeSourceOwners=new Map;this.nativeSourceRetryTimer=null;this.hookEventChain=Promise.resolve();this.hooksActive=!1;this.hooksCompatibilityNoticeSent=!1;this.permissionRequestHookInFlight=null;this.queuedPermissionRequestDedupeKeys=new Map;this.queuedPermissionRequestSessionCounts=new Map;this.queuedPermissionRequestRegistrations=new Map;this.waitingPermissionRequests=new Map;this.permissionRequestOccurrencesByCompletionKey=new Map;this.deferredTmuxPromptCandidates=new Map;this.recoveryPermissionReplay=null;this.resolvedApprovalDedupeKeys=new Map;this.queuedQuestionCallIds=new Set;this.historicalQueuedQuestionPromptIds=new Set;this.subscribedSessionId=null;this.subscribedSessionState=null;this.terminalInputChain=Promise.resolve();this.terminalInputBlockedStates=new WeakSet;this.mobilePromptDeduper=new xe({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.stopPromise=null;this.terminalRetirementRequested=!1;this.teardownStepsTimedOut=[];this.retirementOwed=!1;this.tmuxLifecycleTimer=null;this.tmuxLifecycleCheckInFlight=!1;this.tmuxLifecycleObservedAlive=!1;this.tmuxLifecycleInitDeadlineMs=Number.POSITIVE_INFINITY;this.v1Bridge=new Oe;this.orchestrationClient=null;this.userDecisionUnsubscribe=null;this.httpApi=new Te,this.sessionWatcher=new Ie({restoreCursor:(e,t)=>this.retryNativeAdmission(()=>this.restoreNativeSource(e,t)),beforeGap:(e,t)=>this.retryNativeAdmission(()=>this.admitNativeSourceGap(e,t)),beforeEntry:(e,t)=>this.retryNativeAdmission(()=>this.admitNativeSourceEntry(e,t))}),this.approvalDetector=new be,this.promptResponder=new Ee,this.tmuxPaneObserver=new Re,this.e1DurableState=new ke({handoffRoot:process.env.CODEVIBE_CODEX_HANDOFF_ROOT,resolutionRoot:process.env.CODEVIBE_CODEX_E1_OUTBOX_ROOT})}static{this.E1_TTL_REFRESH_MS=300*1e3}async start(){if(a.info("Starting CodeVibe Codex companion server",{environment:(0,m.getEnvironment)()}),this.appSyncClient=new m.AppSyncClient,!await this.appSyncClient.authenticateWithStoredTokens()){let i=(0,m.describeStoredAuthFailure)(this.appSyncClient.getLastAuthFailureKind(),this.appSyncClient.getLastAuthFailureDetail());a.error("Authentication with stored credentials failed",{kind:this.appSyncClient.getLastAuthFailureKind(),exitCode:i.exitCode}),console.error(i.message),process.exit(i.exitCode)}a.info("Authenticated successfully",{userId:this.appSyncClient.getCurrentUserId(),email:this.appSyncClient.getCurrentUserEmail()});try{let i=this.appSyncClient.getCurrentUserId(),s=AbortSignal.timeout(5e3),r=new Promise((l,p)=>s.addEventListener("abort",()=>p(new Error("status read timed out")),{once:!0})),n=await Promise.race([this.appSyncClient.getSubscriptionStatus(s),r]);if(this.appSyncClient.getCurrentUserId()!==i)throw new Error("account changed during read");let o=await Promise.race([this.appSyncClient.getCompanionSyncState(s),r]);if(this.appSyncClient.getCurrentUserId()!==i)throw new Error("account changed during read");if(n.tier!==o.tier)throw new Error("tier changed during read");a.info("Standalone Companion sync status",{tier:o.tier,protocol:o.protocol,syncState:o.usage?.syncState??null,resetAtEpochMs:o.resetAtEpochMs})}catch{a.warn("Standalone Companion sync status unavailable; cloud admission remains authoritative")}await this.restorePendingE1ResolutionsFromOutbox(),await(0,m.registerDeviceEncryptionKey)(this.appSyncClient,a),(0,m.startDeviceKeyWatcher)(this.appSyncClient,a),(0,m.pushDetectedAgents)(this.appSyncClient,a).catch(i=>{a.warn("Failed to update available agents (non-fatal)",{error:i?.message})});try{let i=await this.appSyncClient.sweepOrphanSessions({agentType:"CODEX"});i>0&&a.info("Orphan sweep: marked stale Codex sessions INACTIVE",{swept:i})}catch(i){a.warn("Orphan sweep failed, continuing startup",{error:i instanceof Error?i.message:String(i)})}this.httpApi.onEvent(this.handleEventFromHook.bind(this));let t=await this.httpApi.start();a.info("HTTP API started for hooks",{port:t}),this.startTmuxLifecycleMonitor(),await this.createLaunchSession(),this.setupEventHandlers(),this.sessionWatcher.start(),a.info("CodeVibe Codex companion server started")}async createLaunchSession(){if(this.isStopping)return;if(process.env[Ne]==="1"){a.info("Recovery daemon deferring backend bootstrap until the native rollout is known");return}let e=this.lifecycleGeneration,t=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!t){a.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();a.info("Creating launch session",{sessionId:r,projectPath:s});let o=!1;try{let l=await(0,m.resumeOrCreateSession)({sessionId:r,userId:n,agentType:m.AgentType.CODEX,projectPath:s,metadata:{launchSession:!0}},this.appSyncClient,a);if(r=l.sessionId,!this.isLifecycleCurrent(e)){await this.retireCancelledBootstrap(r,"launch_session");return}this.sessionKey=l.sessionKey,this.sessionKeyGen=l.sessionKeyGen,this.sessionIsEncrypted=!!l.sessionKey,o=!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:t,codexLogFile:void 0},this.clearSessionBootstrapFailure(),this.bootstrapSessionId=null,await k("daemon_init_step_completed",{step:"session_resume_or_create",path:"launch_session"})}catch(l){if(!this.isLifecycleCurrent(e)){let p=this.authoritativeSessionIdFromError(l)??r;await this.retireCancelledBootstrap(p,"launch_session_error");return}await k("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"),a.error("Failed to create/resume launch session (non-fatal)",{error:l})}if(!o)return;await k("daemon_init_step_completed",{step:"session_state_set",path:"launch_session"});try{this.subscribeToMobileEvents(r)?await k("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"launch_session"}):await k("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(l){await k("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"launch_session",error_class:l?.name||"Error",error_message:l?.message||String(l)}),a.error("Failed to subscribe to mobile events for launch session",{error:l})}try{await this.appSyncClient.startHeartbeat(r)?await k("daemon_init_step_completed",{step:"heartbeat_start",path:"launch_session"}):(await k("daemon_init_step_failed",{step:"heartbeat_start",path:"launch_session",error_class:"InitialHeartbeatNotPersisted",error_message:"Backend did not confirm the initial heartbeat mutation"}),a.error("Initial launch-session heartbeat was not persisted",{sessionId:r}))}catch(l){await k("daemon_init_step_failed",{step:"heartbeat_start",path:"launch_session",error_class:l?.name||"Error",error_message:l?.message||String(l)}),a.error("Failed to start heartbeat for launch session",{error:l})}try{await this.subscribeToOnApplyUserDecision(r)}catch(l){a.error("Failed to subscribe to onApplyUserDecision for launch session (non-fatal)",{error:l})}this.startMobileEndWatcher(r),a.info("Launch session created",{sessionId:r})}finally{i()}}encryptForEmit(e,t,i,s){let r=this.sessionState;if(!r||r.sessionId!==s||!r.encryptionSnapshot)return a.warn("Dropping event from stale or unresolved session generation (#638)",{type:i,sessionId:s,currentSessionId:r?.sessionId}),null;let{sessionKey:n,sessionIsEncrypted:o}=r.encryptionSnapshot,l=(0,m.encryptForEmit)(n,o,e,t);return l===null&&a.error("No session key for ENCRYPTED session \u2014 dropping event (fail-closed, #638)",{type:i,sessionId:s}),l}newE1Raise(e,t,i,s){let{record:r}=(0,m.newPromptRaise)({sessionId:e,producerKind:"PLUGIN_APPROVAL",mobileActionable:t,agentType:"CODEX",...i!==void 0&&{title:i}});return this.e1PromptRaises.set(r.promptId,{record:r,...s?.dedupeKey!==void 0?{resolutionDedupeKey:s.dedupeKey}:{},...s?.completionKey!==void 0?{resolutionCompletionKey:s.completionKey}:{},...s?.callId!==void 0?{resolutionCallId:s.callId}:{}}),this.e1TtlRefreshTimer||this.startE1TtlRefresh(),r}stashE1RaiseContent(e,t,i){let s=this.e1PromptRaises.get(e);s&&(s.contentPlain=t,s.metadataPlain=i)}async emitSuppressedPromptCarrier(e,t,i){return this.publishE1Prompt(e,t,m.EventType.NOTIFICATION,"\u26A0\uFE0F A prompt is waiting in your desktop terminal, but its options could not be shown here. Please answer it on your desktop.",{e1SuppressedPrompt:!0},i)}publishE1Prompt(e,t,i,s,r,n){let o=(0,m.prepareEventTimestamp)({orderingKey:e}),l={sessionId:e,type:i,source:m.EventSource.DESKTOP,content:s,metadata:r,...(0,m.raiseFieldsFromRecord)(t),timestamp:o},p=this.e1PromptRaises.get(t.promptId),c=()=>p?.record===t&&(0,m.isOpenPromptRaise)(p,this.e1PromptRaises.get(t.promptId));if(!c())return Promise.resolve("CLOSED");let u=h=>(c()&&(h==="RETRY"?this.e1NeedsReRaise.add(t.promptId):(h==="RERAISED"||h==="OMITTED")&&this.e1NeedsReRaise.delete(t.promptId)),h);return this.trackE1Raise(t.promptId,this.appSyncClient.publishCompanionPrompt(l,async()=>{let h=this.encryptForEmit(s,r,i,e);return h?(await this.appSyncClient.createEvent({...l,content:h.content,metadata:h.metadata,...i===m.EventType.NOTIFICATION&&{notificationText:s},...h.isEncrypted?{isEncrypted:!0}:{}}),!0):!1},{reRaiseToken:n}).then(u,h=>{throw u("RETRY"),h}))}raiseSuppressedBadge(e,t,i={}){if(t){if(this.hasRecentlyResolvedApprovalDedupeKey(e,t)){a.debug("Skipping suppressed-prompt carrier; approval completed while producer was in flight",{sessionId:e,dedupeKey:t});return}let r=`${e}::${t}`,n=this.e1ContentKeyIndex.get(r);if(n&&this.e1PromptRaises.has(n)){if(i.suppressTmuxObserverUntilResolved){let o=this.e1PromptRaises.get(n);o&&(o.suppressTmuxObserverUntilResolved=!0,i.observerSnapshot&&(o.suppressedObserverSnapshotKey=this.buildObserverSnapshotMatchKey(i.observerSnapshot)))}return}n&&this.e1ContentKeyIndex.delete(r)}let s=this.newE1Raise(e,!1,void 0,t?{dedupeKey:t,completionKey:i.completionKey}:void 0);if(i.suppressTmuxObserverUntilResolved){let r=this.e1PromptRaises.get(s.promptId);r&&(r.suppressTmuxObserverUntilResolved=!0,i.observerSnapshot&&(r.suppressedObserverSnapshotKey=this.buildObserverSnapshotMatchKey(i.observerSnapshot)))}t&&this.e1ContentKeyIndex.set(`${e}::${t}`,s.promptId),this.emitSuppressedPromptCarrier(e,s).catch(r=>{a.error("E1: failed to emit suppressed-prompt badge carrier",{sessionId:e,promptId:s.promptId,error:r instanceof Error?r.message:String(r)})})}snapshotOpenE1(e){return[...this.e1PromptRaises.values()].filter(t=>t.record.sessionId===e).map(t=>({record:{...t.record},...t.contentPlain!==void 0&&{contentPlain:t.contentPlain},...t.metadataPlain!==void 0&&{metadataPlain:t.metadataPlain},...t.resolutionDedupeKey!==void 0&&{resolutionDedupeKey:t.resolutionDedupeKey},...t.resolutionCompletionKey!==void 0&&{resolutionCompletionKey:t.resolutionCompletionKey},...t.resolutionCallId!==void 0&&{resolutionCallId:t.resolutionCallId},...t.suppressTmuxObserverUntilResolved!==void 0&&{suppressTmuxObserverUntilResolved:t.suppressTmuxObserverUntilResolved},...t.suppressedObserverSnapshotKey!==void 0&&{suppressedObserverSnapshotKey:t.suppressedObserverSnapshotKey}}))}buildDaemonHandoffSnapshot(e){let t=process.env[Y];if(!t)throw new Error("E1_DAEMON_HANDOFF_MISSING_TMUX_SESSION");return{version:1,createdAtMs:Date.now(),tmuxSession:t,backendSessionId:e.sessionId,openRaises:this.snapshotOpenE1(e.sessionId),pendingResolutions:[...this.e1PendingResolutions.values()].map(i=>({record:{...i.record},resolutionAt:i.resolutionAt,attempts:i.attempts})),needsReRaisePromptIds:[...this.e1NeedsReRaise],permissionOccurrences:[...this.permissionRequestOccurrencesByCompletionKey.entries()].map(([i,s])=>[i,s.map(r=>({...r}))]),waitingPermissionRequests:[...this.waitingPermissionRequests.values()].filter(i=>i.ownerState===e).map(({occurrenceKey:i,dedupeKey:s,payload:r})=>({occurrenceKey:i,dedupeKey:s,payload:r})),pendingInteractivePrompt:this.pendingInteractivePrompt?{...this.pendingInteractivePrompt}:null,queuedInteractivePrompts:this.queuedInteractivePrompts.map(i=>({prompt:{...i.prompt},content:i.content,metadata:{...i.metadata}})),resolvedApprovalDedupeKeys:[...this.resolvedApprovalDedupeKeys.entries()].filter(([,i])=>i>Date.now()-Xe),historicalQueuedQuestionPromptIds:[...this.historicalQueuedQuestionPromptIds].filter(i=>typeof i=="string"&&i.trim().length>0&&Buffer.byteLength(i,"utf8")<=512).slice(-1e3)}}persistDaemonHandoffState(e){for(let i of this.e1PendingResolutions.values())this.e1DurableState.writeResolution(i);let t=this.buildDaemonHandoffSnapshot(e);this.e1DurableState.writeHandoff(t),a.info("E1: persisted daemon handoff state",{sessionId:e.sessionId,openPrompts:t.openRaises.length,pendingResolutions:t.pendingResolutions.length,completionQueues:t.permissionOccurrences.length})}async adoptDaemonHandoffState(e){if(process.env[Ne]!=="1")return!1;let t=process.env[Y];if(!t)return!1;let i=this.e1DurableState.readHandoff(t);if(!i)return!1;let s=this.sessionState;if(!s||s.sessionId!==e)throw new Error("E1_DAEMON_HANDOFF_WITHOUT_CURRENT_SESSION");for(let l of i.pendingResolutions)this.e1PendingResolutions.has(l.record.promptId)||this.e1PendingResolutions.set(l.record.promptId,{record:{...l.record},resolutionAt:l.resolutionAt,attempts:l.attempts}),this.e1DurableState.writeResolution(l);for(let l of i.openRaises){let p={...l,record:{...l.record},...l.metadataPlain!==void 0&&{metadataPlain:{...l.metadataPlain}}};this.e1PromptRaises.set(p.record.promptId,p),i.backendSessionId!==e&&this.e1RetirementOrphans.set(p.record.promptId,{...p,record:{...p.record}}),p.resolutionDedupeKey&&this.e1ContentKeyIndex.set(`${e}::${p.resolutionDedupeKey}`,p.record.promptId)}this.permissionRequestOccurrencesByCompletionKey=new Map(i.permissionOccurrences.map(([l,p])=>[l,p.map(c=>({...c}))])),this.e1NeedsReRaise=new Set(i.needsReRaisePromptIds);for(let l of i.waitingPermissionRequests??[])this.waitingPermissionRequests.set(l.occurrenceKey,{...l,ownerState:s,context:this.buildApprovalPromptContextFromHookPayload(l.payload)});this.pendingInteractivePrompt=i.pendingInteractivePrompt?{...i.pendingInteractivePrompt,ownerSessionId:e}:null;let r=this.pendingInteractivePrompt,n=r?.completionKey?this.permissionRequestOccurrencesByCompletionKey.get(r.completionKey):void 0;this.recoveryPermissionReplay=r?.source==="permission_hook"&&r.completionKey&&r.dedupeKey&&this.isPermissionRequestOccurrenceKey(r.dedupeKey)&&n?.some(l=>l.occurrenceKey===r.dedupeKey)?{ownerSessionId:e,completionKey:r.completionKey,occurrenceKey:r.dedupeKey}:null,this.queuedInteractivePrompts=i.queuedInteractivePrompts.map(l=>({prompt:{...l.prompt,ownerSessionId:e},content:l.content,metadata:{...l.metadata},ownerState:s}));let o=Date.now()-Xe;for(let[l,p]of i.resolvedApprovalDedupeKeys){if(p<=o)continue;let c=`${i.backendSessionId}::`,u=l.startsWith(c)?`${e}::${l.slice(c.length)}`:l;this.resolvedApprovalDedupeKeys.set(u,p)}if(i.historicalQueuedQuestionPromptIds)for(let l of i.historicalQueuedQuestionPromptIds)this.recordHistoricalQueuedQuestionId(l);return i.backendSessionId!==e&&await this.drainRetirementOrphans(e),await this.drainPendingE1Resolutions(),await this.drainPendingE1ReRaises(),(this.e1PromptRaises.size>0||this.e1PendingResolutions.size>0)&&this.startE1TtlRefresh(),this.e1DurableState.removeHandoff(t),a.info("E1: adopted daemon handoff state",{fromSessionId:i.backendSessionId,replacementSessionId:e,openPrompts:i.openRaises.length,pendingResolutions:i.pendingResolutions.length,completionQueues:i.permissionOccurrences.length}),!0}parkRetirementOrphans(e){for(let t of this.snapshotOpenE1(e))this.e1RetirementOrphans.set(t.record.promptId,t)}async drainRetirementOrphans(e){if(this.e1RetirementOrphans.size===0){this.e1PendingResolutions.size>0&&!this.e1TtlRefreshTimer&&this.startE1TtlRefresh();return}a.info("E1 (\xA76a-4): re-homing parked retirement-orphan prompts onto replacement session",{replacementSessionId:e,count:this.e1RetirementOrphans.size});for(let[t,i]of[...this.e1RetirementOrphans]){let r=this.e1PromptRaises.get(t)??{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.resolutionCompletionKey!==void 0&&{resolutionCompletionKey:i.resolutionCompletionKey},...i.resolutionCallId!==void 0&&{resolutionCallId:i.resolutionCallId}};for(let[o,l]of this.e1ContentKeyIndex.entries())l===t&&this.e1ContentKeyIndex.delete(o);r.record.sessionId=e,this.e1PromptRaises.set(t,r),r.resolutionDedupeKey&&this.e1ContentKeyIndex.set(`${e}::${r.resolutionDedupeKey}`,t);let n=await this.reRaiseOneE1(e,r,{untilAck:!0});if(n!=="RERAISED"&&n!=="OMITTED"){if(!this.e1RetirementOrphans.has(t))continue;break}this.e1RetirementOrphans.delete(t)}this.e1TtlRefreshTimer||this.startE1TtlRefresh()}isReRaiseTargetCurrent(e){return!this.isStopping&&this.sessionState!==null&&this.sessionState.sessionId===e}async reRaiseOneE1(e,t,i){let s=t.record;if(!(0,m.canRecoverPromptRaise)(t,this.e1RaiseInFlight.has(s.promptId)))return"RETRY";let r=s.mobileActionable&&t.contentPlain!==void 0,n=i?.untilAck??!1,o=4,l=4e3;for(let p=1;n||p<=o;p++){if(!(0,m.isOpenPromptRaise)(t,this.e1PromptRaises.get(s.promptId)))return"CLOSED";if(n&&!this.isReRaiseTargetCurrent(e))return this.e1NeedsReRaise.add(s.promptId),a.warn("E1: retirement re-raise aborted (stopping/superseded) \u2014 parked",{sessionId:e,promptId:s.promptId}),"RETRY";try{let c;return r?c=await this.publishE1Prompt(e,s,m.EventType.INTERACTIVE_PROMPT,t.contentPlain,t.metadataPlain??{},i?.reRaiseToken):(s.mobileActionable=!1,c=await this.emitSuppressedPromptCarrier(e,s,i?.reRaiseToken)),c==="RETRY"||c==="CLOSED"||(this.e1NeedsReRaise.delete(s.promptId),a.info("E1: prompt publication settled",{sessionId:e,promptId:s.promptId,actionable:r,disposition:c})),c}catch(c){if(!n&&p===o)return this.e1NeedsReRaise.add(s.promptId),a.error("E1: re-raise unacked after backoff \u2014 parked for retry-until-ack",{sessionId:e,promptId:s.promptId,error:c instanceof Error?c.message:String(c)}),"RETRY";if(n){let u=Date.now()+Math.min(250*2**(p-1),l);for(;Date.now()<u&&this.isReRaiseTargetCurrent(e);)await new Promise(h=>setTimeout(h,Math.min(50,u-Date.now())))}else await new Promise(u=>setTimeout(u,250*p))}}return"RETRY"}async drainPendingE1ReRaises(){if(this.e1NeedsReRaise.size!==0)for(let e of[...this.e1NeedsReRaise]){let t=this.e1PromptRaises.get(e);if(!t){this.e1NeedsReRaise.delete(e);continue}!this.sessionState||t.record.sessionId!==this.sessionState.sessionId||await this.reRaiseOneE1(t.record.sessionId,t)}}beginE1Resolution(e,t){if(this.e1PendingResolutions.has(e))return!0;let i=this.e1PromptRaises.get(e);if(!i||i.record.sessionId!==t)return!1;this.e1PromptRaises.delete(e),this.e1NeedsReRaise.delete(e),this.e1RetirementOrphans.delete(e);for(let[s,r]of this.e1ContentKeyIndex.entries())r===e&&this.e1ContentKeyIndex.delete(s);return this.e1PendingResolutions.set(e,{record:{...i.record},resolutionAt:new Date().toISOString(),attempts:0}),this.e1TtlRefreshTimer||this.startE1TtlRefresh(),!0}async emitE1Resolution(e){let t=this.e1ResolutionInFlight.get(e);if(t)return t;if(!this.e1PendingResolutions.has(e))return;let i=(async()=>{let s=this.e1PendingResolutions.get(e);if(s){try{this.e1DurableState.writeResolution(s)}catch(r){a.error("E1: failed to persist exact-clear outbox record",{promptId:e,error:r instanceof Error?r.message:String(r)})}try{let r=this.e1RaiseInFlight.get(e);if(r&&await r,s=this.e1PendingResolutions.get(e),!s)return;if(!await this.appSyncClient.resolveCompanionPrompt({sessionId:s.record.sessionId,promptId:s.record.promptId,ownerToken:s.record.ownerToken,resolutionAt:s.resolutionAt}))throw new Error("E1_PLUGIN_RESOLUTION_NOT_ACKNOWLEDGED: exact prompt id was not returned");this.e1PendingResolutions.delete(e);try{this.e1DurableState.removeResolution(e)}catch(o){a.warn("E1: exact-clear ACKed but outbox cleanup failed",{promptId:e,error:o instanceof Error?o.message:String(o)})}a.info("E1: plugin approval resolution acknowledged",{sessionId:s.record.sessionId,promptId:e})}catch(r){let n=this.e1PendingResolutions.get(e);a.warn("E1: plugin approval resolution unacknowledged; parked for retry",{sessionId:n?.record.sessionId,promptId:e,error:r instanceof Error?r.message:String(r)})}}})();this.e1ResolutionInFlight.set(e,i);try{await i}finally{this.e1ResolutionInFlight.get(e)===i&&this.e1ResolutionInFlight.delete(e)}}trackE1Raise(e,t){let i=t.then(()=>{},()=>{});return this.e1RaiseInFlight.set(e,i),i.then(()=>{this.e1RaiseInFlight.get(e)===i&&this.e1RaiseInFlight.delete(e)}),t}async drainPendingE1Resolutions(){for(let[e,t]of[...this.e1PendingResolutions.entries()])t.attempts+=1,await this.emitE1Resolution(e)}async restorePendingE1ResolutionsFromOutbox(){let{records:e,rejected:t}=this.e1DurableState.readResolutions();for(let i of t)a.error("E1: rejected unsafe or invalid resolution outbox record",i);for(let i of e){let s=this.e1PendingResolutions.get(i.record.promptId);(!s||i.attempts>s.attempts)&&this.e1PendingResolutions.set(i.record.promptId,{record:{...i.record},resolutionAt:i.resolutionAt,attempts:i.attempts})}e.length>0&&(a.info("E1: recovered pending exact-clear outbox records",{count:e.length}),await this.drainPendingE1Resolutions(),this.e1PendingResolutions.size>0&&!this.e1TtlRefreshTimer&&this.startE1TtlRefresh())}async drainPendingE1ResolutionsForLifecycleEnd(e={}){let t=e.maxWaitMs??4e3,i=e.retryDelayMs??250,s=Date.now()+Math.max(0,t),r=0;do{if(await this.drainPendingE1Resolutions(),this.e1PendingResolutions.size===0)return;if(r+=1,Date.now()>=s)break;await new Promise(n=>setTimeout(n,Math.min(i*r,Math.max(0,s-Date.now()))))}while(Date.now()<s);for(let n of this.e1PendingResolutions.values())this.e1DurableState.writeResolution(n);a.warn("E1: graceful lifecycle ended with durable exact-clear work pending",{count:this.e1PendingResolutions.size})}beginE1PromptResolutions(e,t){let i=[];for(let s of new Set(e))this.beginE1Resolution(s,t)&&i.push(s);return i}launchE1Resolutions(e){Promise.all([...e].map(t=>this.emitE1Resolution(t)))}async exactClearOpenE1ForLifecycleEnd(e){let t=[...this.e1PromptRaises.values()].filter(s=>s.record.sessionId===e).map(s=>s.record.promptId),i=this.beginE1PromptResolutions(t,e);await Promise.all(i.map(s=>this.emitE1Resolution(s)))}async refreshE1Ttls(){await this.drainPendingE1Resolutions(),await this.drainPendingE1ReRaises();let e=this.sessionState?.sessionId;if(!e)return;let t=[...this.e1PromptRaises.values()].filter(i=>i.record.sessionId===e&&(0,m.canRecoverPromptRaise)(i,this.e1RaiseInFlight.has(i.record.promptId))).map(i=>i.record.promptId);if(t.length!==0)try{await this.appSyncClient.refreshSessionOpenPromptTtl({sessionId:e,promptIds:t},async(i,s)=>{let r=this.e1PromptRaises.get(i);return!r||r.record.sessionId!==e||this.sessionState?.sessionId!==e?"CLOSED":this.reRaiseOneE1(e,r,{reRaiseToken:s})})}catch(i){a.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()},d.E1_TTL_REFRESH_MS)}stopE1TtlRefresh(){this.e1TtlRefreshTimer&&(clearInterval(this.e1TtlRefreshTimer),this.e1TtlRefreshTimer=null)}isExpectedSessionStateCurrent(e){return!this.isStopping&&this.sessionState===e&&!this.terminalInputBlockedStates.has(e)}sendSessionPinnedInput(e,t,i){if(!this.isExpectedSessionStateCurrent(e)||this.terminalInputBlockedStates.has(e))return Promise.resolve(!1);let s=this.terminalInputChain.then(async()=>!this.isExpectedSessionStateCurrent(e)||this.terminalInputBlockedStates.has(e)||!await this.verifyNoActiveCodexChooser(e.sessionId)||i&&(await i(),!this.isExpectedSessionStateCurrent(e)||!await this.verifyNoActiveCodexChooser(e.sessionId)||!this.isExpectedSessionStateCurrent(e))||!await this.promptResponder.sendLiteral(e.sessionId,t)||(await new Promise(r=>setTimeout(r,500)),!this.isExpectedSessionStateCurrent(e))||!await this.verifyNoActiveCodexChooser(e.sessionId)?!1:this.promptResponder.sendKey(e.sessionId,"Enter"));return this.terminalInputChain=s.then(()=>{},()=>{}),s}async verifyNoActiveCodexChooser(e){try{let t=await this.tmuxPaneObserver.captureSnapshot();if(this.tmuxPaneObserver.extractActivePromptBlock(t))return!1;let s=te(t).split(`
|
|
29
|
+
`).slice(-25).join(`
|
|
30
|
+
`);return!/Press a number to choose/i.test(s)}catch(t){return a.warn("Failed to verify that no Codex chooser is active",{sessionId:e,error:t instanceof Error?t.message:String(t)}),!1}}sendVerifiedPromptInput(e,t,i){if(!this.isExpectedSessionStateCurrent(e))return Promise.resolve("stale");let s=this.terminalInputChain.then(async()=>{if(!this.isExpectedSessionStateCurrent(e)||this.pendingInteractivePrompt!==t||t.ownerSessionId!==e.sessionId)return"stale";if(t.kind==="queued_question"||t.source==="queued_question")try{return await this.deliverQueuedQuestionResponse(e,t,i)}catch(o){return a.error("Failed to deliver queued question response",{sessionId:e.sessionId,promptId:t.promptId,error:o instanceof Error?o.message:String(o)}),"unverified"}if(!t.observerMatchKey)return a.warn("Refusing mobile prompt input without a captured pane identity",{sessionId:e.sessionId,promptId:t.promptId}),"unverified";if(t.terminalMenuIdentity)try{return await(0,ge.selectTerminalMenuOption)(t.terminalMenuIdentity,i,{current:()=>this.isExpectedSessionStateCurrent(e)&&this.pendingInteractivePrompt===t,read:async()=>(0,ge.parseActiveTerminalMenu)(await this.tmuxPaneObserver.captureSnapshot()),key:o=>this.promptResponder.sendKey(e.sessionId,o),wait:()=>new Promise(o=>setTimeout(o,100))})}catch{return"unverified"}let r=null;try{let o=await this.tmuxPaneObserver.captureSnapshot(),l=this.tmuxPaneObserver.extractActiveApprovalBlock(o),p=l?(0,j.parseInteractivePrompt)(l):null;r=p?this.buildObserverPromptMatchKey(p):null}catch(o){return a.warn("Failed to re-probe Codex prompt before mobile input",{sessionId:e.sessionId,promptId:t.promptId,error:o instanceof Error?o.message:String(o)}),"unverified"}return!this.isExpectedSessionStateCurrent(e)||this.pendingInteractivePrompt!==t?"stale":!r||r!==t.observerMatchKey?(a.warn("Refusing mobile input because the live Codex prompt changed",{sessionId:e.sessionId,promptId:t.promptId,hasLiveIdentity:!!r}),"unverified"):(i===oe?await this.promptResponder.sendKey(e.sessionId,"Escape"):await this.promptResponder.sendLiteral(e.sessionId,i))?"sent":"send_failed"});return this.terminalInputChain=s.then(()=>{},()=>{}),s}sendVerifiedFollowUpAfterDismissal(e,t,i,s){let r=this.terminalInputChain.then(async()=>{let n=()=>this.isExpectedSessionStateCurrent(e)&&t.ownerSessionId===e.sessionId;return n()?!await this.verifyNoActiveCodexChooser(e.sessionId)||!n()||s&&(await s(),!n()||!await this.verifyNoActiveCodexChooser(e.sessionId)||!n())?"unverified":await this.promptResponder.sendLiteral(e.sessionId,i)?(await new Promise(o=>setTimeout(o,500)),n()?!await this.verifyNoActiveCodexChooser(e.sessionId)||!n()?"unverified":await this.promptResponder.sendKey(e.sessionId,"Enter")?"sent":"send_failed":"stale"):"send_failed":"stale"});return this.terminalInputChain=r.then(()=>{},()=>{}),r}sendConversationContinuation(e,t,i){if(!this.isExpectedSessionStateCurrent(e))return Promise.resolve("stale");let s=this.terminalInputChain.then(async()=>{if(!this.isExpectedSessionStateCurrent(e))return"stale";try{let r=new Set;for(;;){let n=await this.tmuxPaneObserver.captureSnapshot();if(!this.isExpectedSessionStateCurrent(e))return"stale";let o=this.tmuxPaneObserver.extractActivePromptBlock(n);if(!o)break;let l=this.tmuxPaneObserver.hashPromptSnapshot(o);if(r.has(l)||r.size>=4)return"unverified";if(r.add(l),!await this.promptResponder.sendKey(e.sessionId,"Escape"))return"send_failed";if(await new Promise(p=>setTimeout(p,200)),!this.isExpectedSessionStateCurrent(e))return"stale"}}catch(r){return a.warn("Failed to inspect Codex chooser before conversation continuation",{sessionId:e.sessionId,error:r instanceof Error?r.message:String(r)}),"unverified"}return i&&(await i(),!this.isExpectedSessionStateCurrent(e)||!await this.verifyNoActiveCodexChooser(e.sessionId)||!this.isExpectedSessionStateCurrent(e))?"unverified":await this.promptResponder.sendLiteral(e.sessionId,t)?(await new Promise(r=>setTimeout(r,500)),this.isExpectedSessionStateCurrent(e)?await this.verifyNoActiveCodexChooser(e.sessionId)?await this.promptResponder.sendKey(e.sessionId,"Enter")?"sent":"send_failed":"unverified":"stale"):"send_failed"});return this.terminalInputChain=s.then(()=>{},()=>{}),s}handleEventFromHook(e){if(this.isStopping)return Promise.resolve();let t=this.lifecycleGeneration,i=this.registerQueuedPermissionRequest(e,t),s=this.hookEventChain.then(()=>this.processHookEvent(e,t,i??void 0)),r=i?s.finally(()=>this.unregisterQueuedPermissionRequest(i)):s;return this.hookEventChain=r.catch(n=>{a.error("[Hooks] event handler failed",{hookEvent:e.hook_event_name,sessionId:e.session_id,error:n instanceof Error?n.message:String(n)})}),r}registerQueuedPermissionRequest(e,t){if(e.hook_event_name!=="PermissionRequest"||!this.sessionState||this.sessionWatcher.getAuthoritativeSessionId()!==e.session_id)return null;let i=this.sessionState.sessionId;this.queuedPermissionRequestSessionCounts.set(i,(this.queuedPermissionRequestSessionCounts.get(i)??0)+1);let s=this.buildApprovalPromptContextFromHookPayload(e),r=this.buildApprovalDedupeKey(s),n=`permission:${(0,de.v4)()}`,o=r?`${i}::${r}`:void 0;o&&this.queuedPermissionRequestDedupeKeys.set(o,(this.queuedPermissionRequestDedupeKeys.get(o)??0)+1);let l={sessionId:i,lifecycleGeneration:t,context:s,dedupeKey:r,occurrenceKey:n,dedupeRegistryKey:o,disposition:"pending"};if(r){let c=this.permissionRequestOccurrencesByCompletionKey.get(r)??[];c.push({occurrenceKey:n,hookObserved:!1,jsonlObserved:!1}),this.permissionRequestOccurrencesByCompletionKey.set(r,c)}let p=this.queuedPermissionRequestRegistrations.get(i)??[];return p.push(l),this.queuedPermissionRequestRegistrations.set(i,p),l}async unregisterQueuedPermissionRequest(e){let t=this.queuedPermissionRequestSessionCounts.get(e.sessionId)??0;if(t<=1?this.queuedPermissionRequestSessionCounts.delete(e.sessionId):this.queuedPermissionRequestSessionCounts.set(e.sessionId,t-1),e.dedupeRegistryKey){let o=this.queuedPermissionRequestDedupeKeys.get(e.dedupeRegistryKey)??0;o<=1?this.queuedPermissionRequestDedupeKeys.delete(e.dedupeRegistryKey):this.queuedPermissionRequestDedupeKeys.set(e.dedupeRegistryKey,o-1)}let s=(this.queuedPermissionRequestRegistrations.get(e.sessionId)??[]).filter(o=>o!==e);s.length>0?this.queuedPermissionRequestRegistrations.set(e.sessionId,s):this.queuedPermissionRequestRegistrations.delete(e.sessionId),(e.disposition==="pending"||e.disposition==="dropped"||this.sessionState?.sessionId!==e.sessionId)&&this.removePermissionRequestOccurrence(e.dedupeKey,e.occurrenceKey);let r=this.deferredTmuxPromptCandidates.get(e);if(!r)return;if(this.deferredTmuxPromptCandidates.delete(e),!this.isLifecycleCurrent(e.lifecycleGeneration)){e.disposition="dropped",this.removePermissionRequestOccurrence(e.dedupeKey,e.occurrenceKey),a.debug("Discarding deferred tmux prompt after lifecycle invalidation",{sessionId:e.sessionId,lifecycleGeneration:e.lifecycleGeneration,currentLifecycleGeneration:this.lifecycleGeneration});return}let n=this.hasRecentlyResolvedApprovalDedupeKey(e.sessionId,e.occurrenceKey);if(e.disposition==="covered"||e.disposition==="resolved"||n){a.debug("Discarding deferred tmux prompt covered by its PermissionRequest",{sessionId:e.sessionId,dedupeKey:e.dedupeKey,disposition:e.disposition});return}if(!(e.disposition==="dropped"||this.sessionState?.sessionId!==e.sessionId)){a.debug("Replaying deferred tmux prompt after PermissionRequest produced no durable owner",{sessionId:e.sessionId,dedupeKey:e.dedupeKey});try{await this.handleTmuxPromptCandidate(r.snapshot,e,r.promptHash)}catch(o){a.error("Failed to replay deferred tmux prompt candidate",{sessionId:e.sessionId,error:o instanceof Error?o.message:String(o)})}}}removePermissionRequestOccurrence(e,t){if(!e||!t)return;let i=this.permissionRequestOccurrencesByCompletionKey.get(e);if(!i)return;let s=i.filter(r=>r.occurrenceKey!==t);s.length>0?this.permissionRequestOccurrencesByCompletionKey.set(e,s):this.permissionRequestOccurrencesByCompletionKey.delete(e)}observePermissionRequestCompletion(e,t){if(!e)return{shouldResolve:!0};let i=this.permissionRequestOccurrencesByCompletionKey.get(e);if(!i)return{shouldResolve:!0};let s=t==="hook"?"hookObserved":"jsonlObserved",r=i.find(o=>!o[s]);if(!r)return a.debug("Ignoring duplicate interactive-prompt completion observation",{completionKey:e,producer:t}),{shouldResolve:!1};let n=!r.hookObserved&&!r.jsonlObserved;return r[s]=!0,r.hookObserved&&r.jsonlObserved&&this.removePermissionRequestOccurrence(e,r.occurrenceKey),{shouldResolve:n,occurrenceKey:r.occurrenceKey}}isPermissionRequestOccurrenceKey(e){return e.startsWith("permission:")}consumeRecoveryPermissionReplay(e,t,i){let s=this.recoveryPermissionReplay,r=this.pendingInteractivePrompt;return!s||!t||s.ownerSessionId!==e.sessionId||s.completionKey!==t||r?.ownerSessionId!==e.sessionId||r.source!=="permission_hook"||r.dedupeKey!==s.occurrenceKey||r.completionKey!==s.completionKey?!1:(this.recoveryPermissionReplay=null,i&&(this.removePermissionRequestOccurrence(i.dedupeKey,i.occurrenceKey),i.occurrenceKey=s.occurrenceKey,i.disposition="covered"),a.info("[Hooks] Reused adopted PermissionRequest occurrence for one recovery replay",{sessionId:e.sessionId,completionKey:t,occurrenceKey:s.occurrenceKey}),!0)}async processHookEvent(e,t,i){if(!this.isLifecycleCurrent(t))return;let{session_id:s,hook_event_name:r,type:n,content:o,metadata:l}=e;a.info("[Hooks] Received event",{sessionId:s,hookEvent:r,type:n,contentLength:o?.length});let p=this.sessionWatcher.getAuthoritativeSessionId();if(p&&p!==s){a.warn("[Hooks] Rejecting event for foreign native session",{hookEvent:r,sessionId:s,authoritativeSessionId:p});return}if(l?.transcript_path){let h=await this.sessionWatcher.bindToSessionTranscript(l.transcript_path,s);if(!this.isLifecycleCurrent(t))return;let g=h.status==="pending"?await h.completion:h;if(!this.isLifecycleCurrent(t))return;if(g.status!=="bound"){a.warn("[Hooks] Rejecting event whose transcript ownership was not proven",{hookEvent:r,sessionId:s,reason:g.reason});return}}else if(p!==s){a.warn("[Hooks] Rejecting event without an owned transcript",{hookEvent:r,sessionId:s});return}if(!this.isLifecycleCurrent(t)||this.sessionWatcher.getAuthoritativeSessionId()!==s){a.warn("[Hooks] Rejecting event after ownership changed during admission",{hookEvent:r,sessionId:s,authoritativeSessionId:this.sessionWatcher.getAuthoritativeSessionId()});return}if(this.hooksActive=!0,r==="SessionStart"){if(this.launchSessionInitPromise&&(await this.launchSessionInitPromise,!this.isLifecycleCurrent(t)))return;if(this.sessionState){if(a.info("[Hooks] SessionStart \u2014 launch session already exists, updating codexSessionId",{existingSessionId:this.sessionState.sessionId,codexSessionId:s}),this.sessionState.codexSessionId=s,this.sessionState.metadata={...this.sessionState.metadata,codexSessionId:s,cliVersion:l?.model||"unknown",modelProvider:l?.model||"unknown",launchSession:void 0},this.appSyncClient.updateSession({sessionId:this.sessionState.sessionId,metadata:this.sessionState.metadata}).catch(h=>a.warn("Failed to update session metadata",{error:h})),await this.startTmuxObserverWithBeacon("session_start_existing"),!this.isLifecycleCurrent(t))return;await this.ensureToolActivityStarted(s)}else{let h={id:s,timestamp:new Date().toISOString(),cwd:l?.cwd||process.cwd(),originator:"hook",cli_version:l?.model||"unknown",instructions:null,source:l?.source||"startup",model_provider:l?.model||"unknown"};await this.ensureSessionStarted(h)}return}if(!this.sessionState){a.warn("[Hooks] Hook event for un-bootstrapped session \u2014 self-healing via session bootstrap (#638)",{hookEvent:r,sessionId:s});let h={id:s,timestamp:new Date().toISOString(),cwd:l?.cwd||process.cwd(),originator:"hook",cli_version:l?.model||"unknown",instructions:null,source:l?.source||"startup",model_provider:l?.model||"unknown"};if(await this.ensureSessionStarted(h),!this.isLifecycleCurrent(t))return;if(!this.sessionState){a.warn("[Hooks] Session still not initialized after self-heal, dropping event",{hook_event_name:r});return}}let c=this.sessionState,u=c.sessionId;if(!(n==="USER_PROMPT"&&(this.approvalDetector.clear(),this.clearInteractivePromptsForAcceptedInput(c),(await this.selectNativeSourceTransport(c)).protocol==="SYNC_V2"))){if(n==="USER_PROMPT"&&o){let h=this.consumeRecentMobilePrompt(u,o);if(h){a.info("[Hooks] Skipping duplicate USER_PROMPT from mobile",{sessionId:u,matchType:h.matchType,originalLength:h.originalLength,echoLength:h.echoLength});return}}if(r==="PreToolUse"){a.debug("[Hooks] PreToolUse observed; AppSync emission suppressed",{toolName:l?.tool_name||"unknown",sessionId:u});return}if(r==="PermissionRequest"){let h=i??this.registerQueuedPermissionRequest(e,t);if(!h){a.error("[Hooks] Dropping admitted PermissionRequest without occurrence registration",{sessionId:u,nativeSessionId:s});return}try{await this.handlePermissionRequestHook(e,c,h)}finally{i||await this.unregisterQueuedPermissionRequest(h)}return}if(r==="PostToolUse"){let h=l?.tool_name;if(this.isQueuedQuestionTool(h)){await this.handleQueuedQuestionHook(e,c);return}let g=this.buildApprovalPromptContextFromHookPayload(e),f=this.buildApprovalDedupeKey(g),y=this.firstString(l?.tool_use_id,l?.call_id,l?.callId)??"",I=this.observePermissionRequestCompletion(f,"hook");if(I.shouldResolve&&await this.clearResolvedInteractivePrompt(y,I.occurrenceKey??f),!this.isExpectedSessionStateCurrent(c)||this.toolActivity?.isActive()&&await this.toolActivity.observeCall({callId:l?.tool_use_id??l?.call_id??l?.callId,toolName:l?.tool_name,toolInput:l?.tool_input})!=="closed"||!this.isExpectedSessionStateCurrent(c))return;let S=await this.selectNativeSourceTransport(c);if(!this.isExpectedSessionStateCurrent(c))return;if(S.protocol==="SYNC_V2")throw new Error("SYNC_SOURCE_TOOL_NOT_ADMITTED");let v=this.encryptForEmit(o,l,m.EventType.TOOL_USE,u);if(!v)return;let w=v.content,R=v.metadata,T=v.isEncrypted,b=l?.tool_use_id??l?.call_id??l?.callId,E=typeof b=="string"&&b.length>0&&!!this.sessionKey,C=E?this.getToolActivityLegacyRecorder(u):void 0;C&&E&&C.markLegacyInFlight(b);try{let M=await this.appSyncClient.createEvent({sessionId:u,type:m.EventType.TOOL_USE,source:m.EventSource.DESKTOP,content:w,metadata:R,isEncrypted:T,timestamp:(0,m.prepareEventTimestamp)({orderingKey:u})});C&&E&&((0,m.isPersistedEventResult)(M)?await C.finalizeLegacyOwned([b]):C.clearLegacyInFlight(b))}catch(M){throw C&&E&&C.clearLegacyInFlight(b),M}return}if(n==="ASSISTANT_RESPONSE"||n==="USER_PROMPT"){if(n==="ASSISTANT_RESPONSE"){this.sessionWatcher.getBindSource()==="authoritative"&&this.sessionWatcher.getAuthoritativeSessionId()===s?a.debug("[Hooks] Suppressing Stop final \u2014 JSONL watcher authoritatively bound to this session (Bug #2)"):a.warn("[Hooks] Dropping Stop final after authoritative ownership changed",{authoritativeSessionId:this.sessionWatcher.getAuthoritativeSessionId()});return}let h=this.encryptForEmit(o,void 0,m.EventType.USER_PROMPT,u);if(!h)return;await this.appSyncClient.createEvent({sessionId:u,type:m.EventType.USER_PROMPT,source:m.EventSource.DESKTOP,content:h.content,isEncrypted:h.isEncrypted,timestamp:(0,m.prepareEventTimestamp)({orderingKey:u})});return}}}mapToolName(e){return{shell_command:"Bash",shell:"Bash",apply_patch:"Edit",create_file:"Write",read_file:"Read"}[e]||e}trackMobilePrompt(e,t){this.mobilePromptDeduper.track(e,t),a.debug("Tracking mobile prompt for USER_PROMPT echo deduplication",{sessionId:e,promptLength:t.trim().length})}forgetMobilePrompt(e,t){this.mobilePromptDeduper.forget(e,t)}consumeRecentMobilePrompt(e,t){return this.mobilePromptDeduper.consumeIfDuplicate(e,t)}async trackDurableMobileEcho(e,t,i,s){if(!(0,m.requiresSyncInputDeliveryReceipt)(t)){this.trackMobilePrompt(e.sessionId,i);return}let r=await this.selectNativeSourceTransport(e);if(r.protocol!=="SYNC_V2"||!this.isExpectedSessionStateCurrent(e)||t.sessionId!==r.sessionScope.sessionId||t.sessionGenerationId!==r.sessionScope.sessionGenerationId)throw Error("SYNC_ECHO_OWNER_CHANGED");i.trim()&&await r.writer.mobileEchoes("codex").arm({eventId:t.eventId,timestamp:t.timestamp,type:t.type,lane:s},i,{nowMs:Date.now(),windowMs:1e4,allowSuffix:!0,normalization:"whitespace"})}setupEventHandlers(){this.sessionWatcher.on("session-started",async e=>{try{if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionState){a.info("[JSONL] Session already active, skipping",{currentSessionId:this.sessionState.sessionId,codexSessionId:e.id}),await this.ensureToolActivityStarted(e.id);return}await this.ensureSessionStarted(e)}catch(t){a.error("[JSONL] session-started handler failed (non-fatal) \u2014 next event retries",{codexSessionId:e?.id,error:String(t)})}}),this.sessionWatcher.on("log-entry",e=>{this.enqueueLogEntry(e)}),this.approvalDetector.on("approval-pending",async e=>{try{await this.handleApprovalPending(e)}catch(t){a.error("approval-pending handler failed (non-fatal)",{error:String(t)})}}),this.tmuxPaneObserver.on("prompt-candidate",async e=>{try{await this.handleTmuxPromptCandidate(e.snapshot,void 0,e.promptHash)}catch(t){a.error("prompt-candidate handler failed (non-fatal)",{error:String(t)})}}),this.tmuxPaneObserver.on("prompt-cleared",e=>{let t=this.sessionState;t&&this.clearObservedInteractivePrompt(t,e.promptHash).catch(i=>{a.error("prompt-cleared handler failed (non-fatal)",{error:String(i)})})}),this.tmuxPaneObserver.on("observer-error",e=>{a.debug("Tmux pane observer error",{error:e})}),this.sessionWatcher.on("error",e=>{a.error("Session watcher error:",e)})}async ensureSessionStarted(e,t){if(this.isStopping||(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.isStopping)||this.sessionState)return;process.env[Ne]==="1"&&await this.bindRecoveryBootstrapIdentity(e.id);let i=this.sessionBootstrapRetryAt-Date.now();if(i>0){a.warn("Session bootstrap is in retry backoff; hook will be retried later",{codexSessionId:e.id,retryDelayMs:i,failureCount:this.sessionBootstrapFailureCount});return}if(this.sessionStartedInitPromise){try{await this.sessionStartedInitPromise}catch{}return}let s=this.handleSessionStarted(e,t);this.sessionStartedInitPromise=s.catch(()=>{});try{await s}finally{this.sessionStartedInitPromise=null}}async handleSessionStarted(e,t){if(this.isStopping)return;let i=this.lifecycleGeneration;a.info("Handling new Codex session",{codexSessionId:e.id}),this.isInitializingSession=!0,this.bufferedLogEntries=[],this.sessionState&&await this.endActiveSession("new-codex-session-started");let s=process.env.CODEX_WORKING_DIRECTORY||e.cwd||process.cwd(),r=this.getOrCreateBootstrapSessionId(),n=this.appSyncClient.getCurrentUserId(),o={codexSessionId:e.id,cliVersion:e.cli_version,modelProvider:e.model_provider},l={sessionKey:null,sessionIsEncrypted:!0};try{let p={sessionId:r,userId:n,agentType:m.AgentType.CODEX,projectPath:s,metadata:o},c=await this.resumeOrCreateBootstrapSession(p);if(r=c.sessionId,!this.isLifecycleCurrent(i)){this.isInitializingSession=!1,await this.retireCancelledBootstrap(r,"session_started");return}this.sessionKey=c.sessionKey,this.sessionKeyGen=c.sessionKeyGen,this.sessionIsEncrypted=!!c.sessionKey,l={sessionKey:c.sessionKey,sessionIsEncrypted:!!c.sessionKey},await k("daemon_init_step_completed",{step:"session_resume_or_create",path:"session_started"})}catch(p){if(this.isInitializingSession=!1,!this.isLifecycleCurrent(i)){let c=this.authoritativeSessionIdFromError(p)??r;await this.retireCancelledBootstrap(c,"session_started_error");return}throw await k("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"),a.error("Failed to create/resume session:",p),p}try{this.sessionState={sessionId:r,userId:n,projectPath:s,cwd:e.cwd,createdAt:new Date,subscriptionActive:!1,metadata:o,encryptionSnapshot:l,codexSessionId:e.id,codexLogFile:this.sessionWatcher.getActiveLogFile()||void 0},this.clearSessionBootstrapFailure(),this.bootstrapSessionId=null,this.recoveryBootstrapOwnerBound=!1,await k("daemon_init_step_completed",{step:"session_state_set",path:"session_started"})}catch(p){await k("daemon_init_step_failed",{step:"session_state_set",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),a.error("Failed to set session state:",p)}await this.adoptDaemonHandoffState(r),this.sessionState&&this.rebindWaitingPermissionRequests(this.sessionState),await this.ensureToolActivityStarted(e.id);try{this.subscribeToMobileEvents(r)?await k("daemon_init_step_completed",{step:"subscribe_mobile_events",path:"session_started"}):await k("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:"SubscriptionSetupFailed",error_message:"subscribeToMobileEvents returned false"})}catch(p){await k("daemon_init_step_failed",{step:"subscribe_mobile_events",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),a.error("Failed to subscribe to mobile events:",p)}if(t)try{await t()}catch(p){a.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){a.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 k("daemon_init_step_completed",{step:"heartbeat_start",path:"session_started"}):(await k("daemon_init_step_failed",{step:"heartbeat_start",path:"session_started",error_class:"InitialHeartbeatNotPersisted",error_message:"Backend did not confirm the initial heartbeat mutation"}),a.error("Initial session heartbeat was not persisted",{sessionId:r}))}catch(p){await k("daemon_init_step_failed",{step:"heartbeat_start",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),a.error("Failed to start heartbeat:",p)}try{await this.subscribeToOnApplyUserDecision(r)}catch(p){a.error("Failed to subscribe to onApplyUserDecision (non-fatal)",{error:p})}this.startMobileEndWatcher(r);try{await this.flushBufferedLogEntries(),await k("daemon_init_step_completed",{step:"flush_buffered_entries",path:"session_started"})}catch(p){await k("daemon_init_step_failed",{step:"flush_buffered_entries",path:"session_started",error_class:p?.name||"Error",error_message:p?.message||String(p)}),a.error("Failed to flush buffered log entries:",p),this.bufferedLogEntries=[]}await this.startTmuxObserverWithBeacon("session_started"),this.isInitializingSession=!1}getOrCreateBootstrapSessionId(){return this.bootstrapSessionId||(this.bootstrapSessionId=ne.mintBackendSessionId()),this.bootstrapSessionId}async bindRecoveryBootstrapIdentity(e){if(!(process.env[Ne]!=="1"||this.bootstrapSessionId||this.sessionState||!e))try{let t=await this.buildToolActivityIntegration().recordedBackendSessionId(e);if(!t){a.warn("Recovery daemon found no durable backend owner; a new session will be created",{rolloutId:e});return}if(!/^codex-[A-Za-z0-9_-]{1,180}$/.test(t)){a.warn("Recovery daemon ignored invalid durable backend owner",{rolloutId:e});return}this.bootstrapSessionId=t,this.recoveryBootstrapOwnerBound=!0,a.info("Recovery daemon reclaiming existing backend session",{rolloutId:e,sessionId:t})}catch(t){a.warn("Recovery daemon could not read the durable rollout owner; a new session will be created",{rolloutId:e,error:t instanceof Error?t.message:String(t)})}}isSessionIdReservedRejection(e){return(e instanceof Error?e.message:String(e)).includes("SESSION_ID_RESERVED")}async resumeOrCreateBootstrapSession(e){try{return await this.resumeBackendSession(e,this.appSyncClient,a)}catch(t){if(!this.recoveryBootstrapOwnerBound||!this.isSessionIdReservedRejection(t))throw t;return a.warn("Recovery discarded a permanently reserved pending create; retrying the durable rollout owner",{sessionId:e.sessionId}),this.resumeBackendSession(e,this.appSyncClient,a)}}startTmuxLifecycleMonitor(){if(this.tmuxLifecycleTimer)return;let e=process.env[Y];e&&(this.tmuxLifecycleInitDeadlineMs=Date.now()+ns,this.tmuxLifecycleTimer=setInterval(()=>{this.checkTmuxLifecycle(e)},rs),this.tmuxLifecycleTimer.unref?.(),this.checkTmuxLifecycle(e))}async tmuxSessionState(e){try{return ze("stall-tmux-probe")&&(a.warn("[dev-fault] stall-tmux-probe: terminality probe will never settle",{tmuxSession:e}),await new Promise(()=>{})),await is("tmux",["has-session","-t",e],{timeout:5e3}),"alive"}catch(t){let i=Yt(t);return i==="absent"?i:(a.warn("Could not inspect native Codex tmux session; preserving daemon",{tmuxSession:e,error:t instanceof Error?t.message:String(t)}),"unknown")}}async checkTmuxLifecycle(e){if(!(this.isStopping||this.tmuxLifecycleCheckInFlight)){this.tmuxLifecycleCheckInFlight=!0;try{let t=await this.tmuxSessionState(e);if(t==="alive"){this.tmuxLifecycleObservedAlive=!0;return}let i=this.tmuxLifecycleObservedAlive||Date.now()>=this.tmuxLifecycleInitDeadlineMs;if(t==="unknown"||!i||this.isStopping)return;this.stopTmuxLifecycleMonitor(),a.info("Native Codex tmux session ended; stopping companion daemon",{tmuxSession:e});let s=he(r=>process.exit(r),()=>a.error("Shutdown watchdog fired after native session end; exiting anyway",{watchdogMs:25e3,timedOutSteps:this.getTeardownStepsTimedOut(),durableObligationSettled:this.isDurableObligationSettledForExit()}),25e3,()=>this.isDurableObligationSettledForExit());this.stop().then(()=>{s(),process.exit(0)},r=>{s(),a.error("Failed to stop companion daemon after native session end",{error:r instanceof Error?r.message:String(r)}),process.exit(1)})}finally{this.tmuxLifecycleCheckInFlight=!1}}}stopTmuxLifecycleMonitor(){this.tmuxLifecycleTimer&&(clearInterval(this.tmuxLifecycleTimer),this.tmuxLifecycleTimer=null)}async shouldShutdownForTerminalSignal(e){if(e==="SIGHUP"){let t=process.env[Y];if(t){let i=await this.tmuxSessionState(t);if(i!=="absent")return a.info("Ignoring SIGHUP while native Codex tmux session remains available",{tmuxSession:t,state:i}),!1}}return!0}async stopForTerminalSignal(e){return await this.shouldShutdownForTerminalSignal(e)?(await this.stop(),!0):!1}isLifecycleCurrent(e){return!this.isStopping&&this.lifecycleGeneration===e}authoritativeSessionIdFromError(e){let t=e?.authoritativeSessionId;return typeof t=="string"&&t.length>0?t:null}async retireCancelledBootstrap(e,t){this.appSyncClient.stopHeartbeat(e),this.appSyncClient.cleanupSubscription(e);try{await this.appSyncClient.updateSession({sessionId:e,status:m.SessionStatus.INACTIVE}),a.info("Cancelled bootstrap row marked INACTIVE",{sessionId:e,path:t})}catch(i){a.warn("Cancelled bootstrap row could not be marked INACTIVE",{sessionId:e,path:t,error:i instanceof Error?i.message:String(i)})}}bindBootstrapIdentityFromError(e){let t=e?.authoritativeSessionId;typeof t!="string"||t.length===0||(this.bootstrapSessionId=t,a.info("Retained authoritative backend identity from failed bootstrap",{sessionId:t}))}recoverRetiredBackendSession(e){if(this.retiredSessionRecoveryPromise)return this.retiredSessionRecoveryPromise;if(this.isStopping)return Promise.resolve();let t=(async()=>{if(this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionStartedInitPromise&&await this.sessionStartedInitPromise,this.isStopping)return;let i=this.sessionState;if(!i||i.sessionId!==e)return;let s={id:i.codexSessionId||e,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")};a.warn("Backend retired live Codex session; creating replacement row",{sessionId:e,codexSessionId:s.id}),this.parkRetirementOrphans(e),await this.endActiveSession("backend-generation-retired"),this.bootstrapSessionId=ne.mintBackendSessionId(),this.recoveryBootstrapOwnerBound=!1,this.clearSessionBootstrapFailure(),await this.ensureSessionStarted(s)})();return this.retiredSessionRecoveryPromise=t.finally(()=>{this.retiredSessionRecoveryPromise=null}),this.retiredSessionRecoveryPromise}recordSessionBootstrapFailure(e,t){this.sessionBootstrapFailureCount+=1;let i=e instanceof Error?e.message:String(e),r=i.includes("SESSION_LIMIT_EXCEEDED")?6e4:Math.min(5e3*2**(this.sessionBootstrapFailureCount-1),6e4);this.sessionBootstrapRetryAt=Date.now()+r,a.warn("Session bootstrap retry scheduled",{path:t,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 e=this.bufferedLogEntries;this.bufferedLogEntries=[],a.info("Flushing buffered log entries after session initialization",{count:e.length,sessionId:this.sessionState?.sessionId});let t=Promise.resolve();for(let i of e)t=this.enqueueLogEntry(i);await t.catch(()=>{})}enqueueLogEntry(e){let t=this.logEntryChain.then(async()=>{await this.handleLogEntry(e)});return this.logEntryChain=t.catch(i=>{a.error("[JSONL] log entry handler failed",{type:e.type,err:String(i)})}),t}selectNativeSourceTransport(e){if(this.sessionState!==e||this.isStopping)return Promise.reject(new Error("SYNC_SOURCE_OWNER_CHANGED"));if(this.nativeSourceSelection?.state===e)return this.nativeSourceSelection.pending;let t=this.appSyncClient.selectCompanionSourceTransport({sessionId:e.sessionId}),i={state:e,pending:t};return this.nativeSourceSelection=i,t.catch(()=>{this.nativeSourceSelection===i&&(this.nativeSourceSelection=null)}),t}async retryNativeAdmission(e){try{return await e()}catch(t){throw!this.isStopping&&!this.nativeSourceRetryTimer&&(this.nativeSourceRetryTimer=setTimeout(()=>{this.nativeSourceRetryTimer=null,this.sessionWatcher.retryActiveRead()},5e3),this.nativeSourceRetryTimer.unref()),t}}assertNativeSourceOwner(e){if(this.sessionState!==e.state||e.controller.signal.aborted)throw new Error("SYNC_SOURCE_OWNER_CHANGED")}async nativeSourceOwner(e){if(this.isStopping)throw new Error("SYNC_SOURCE_STOPPING");this.launchSessionInitPromise&&await this.launchSessionInitPromise,this.sessionStartedInitPromise&&await this.sessionStartedInitPromise;let t=this.sessionState;if(!t||!e.nativeSessionId||this.sessionWatcher.getActiveLogFile()!==e.transcriptPath||this.sessionWatcher.getAuthoritativeSessionId()!==null&&this.sessionWatcher.getAuthoritativeSessionId()!==e.nativeSessionId)throw new Error("SYNC_SOURCE_BOOTSTRAP_PENDING");let i=await this.selectNativeSourceTransport(t);if(this.sessionState!==t||this.isStopping)throw new Error("SYNC_SOURCE_OWNER_CHANGED");if(i.protocol==="LEGACY")return null;if(await this.ensureToolActivityStarted(e.nativeSessionId),this.sessionState!==t||this.isStopping||!this.toolActivity?.isActive())throw new Error("SYNC_SOURCE_OWNERSHIP_UNAVAILABLE");let s=fe.createHash("sha256").update(JSON.stringify([e.transcriptPath,e.nativeSessionId])).digest("hex"),r=`${i.sessionScope.sessionGenerationId}:${s}`,n=this.nativeSourceOwners.get(r);if(n)return this.assertNativeSourceOwner(n),n;let o={state:t,selection:i,streamSha256:s,cursor:i.writer.sourceStream({provider:"codex",streamSha256:s}),controller:new AbortController,drain:null,drainRequested:!1,retryTimer:null,retryMs:5e3};return this.nativeSourceOwners.set(r,o),o}async restoreNativeSource(e,t){let i=await this.nativeSourceOwner(e);if(!i)return null;await i.cursor.recover();let s=await i.cursor.open(t);return await i.selection.writer.mobileEchoes("codex").reconcile(i.streamSha256,s.byteOffset),this.assertNativeSourceOwner(i),this.drainNativeSource(i),{byteOffset:s.byteOffset,anchor:s.anchor,discardUntilNewline:s.discardUntilNewline}}async admitNativeSourceGap(e,t){let i=await this.nativeSourceOwner(t);if(!i)throw new Error("SYNC_SOURCE_PROTOCOL_CHANGED");await i.cursor.skip(e),this.assertNativeSourceOwner(i)}async admitNativeSourceEntry(e,t){let i=await this.nativeSourceOwner(t);if(!i)return;let s=this.logEntryChain.then(async()=>{this.assertNativeSourceOwner(i);let r=await i.cursor.load();if(!r)throw new Error("SYNC_SOURCE_CURSOR_MISSING");if(t.endOffset<=r.byteOffset)return;let n=gt(e,i.state.sessionId,r.projection);if(n.event&&!["USER_PROMPT","ASSISTANT_RESPONSE","REASONING","TOOL_USE","NOTIFICATION"].includes(n.event.type))throw new Error("SYNC_NATIVE_SPECIALIZED_PRODUCER_REQUIRED");let o=await this.handleLogEntry(e,{event:n.event});if(this.assertNativeSourceOwner(i),!this.isExpectedSessionStateCurrent(i.state))throw new Error("SYNC_SOURCE_OWNER_STOPPING");let l={streamSha256:i.streamSha256,occurrence:`${t.startOffset}:${t.endOffset}`,sourceSha256:t.sha256,startOffset:t.startOffset,endOffset:t.endOffset},p=i.selection.writer.mobileEchoes("codex");o?.type===m.EventType.USER_PROMPT&&await p.claim(l,o.content,e.timestamp)&&(o=void 0),await i.cursor.admit({provider:"codex",streamSha256:i.streamSha256,occurrence:`${t.startOffset}:${t.endOffset}`,sourceSha256:t.sha256,startOffset:t.startOffset,endOffset:t.endOffset,anchor:t.anchor},o?c=>i.selection.prepareEvent(o,c):null,n.projection),await p.reconcile(i.streamSha256,t.endOffset),this.drainNativeSource(i)});return this.logEntryChain=s.catch(r=>{a.warn("[sync-source] native admission retained for retry",{error:String(r)})}),await s,"handled"}drainNativeSource(e){if(e.controller.signal.aborted||this.isStopping||(e.drainRequested=!0,e.drain||e.retryTimer))return;e.drainRequested=!1;let t=(async()=>{let i=!1;try{await e.cursor.drain(64,e.controller.signal)===64&&(e.drainRequested=!0),e.retryMs=5e3}catch(s){i=!0,e.controller.signal.aborted||a.warn("[sync-source] cloud drain retained for retry",{error:String(s)}),e.retryMs=Math.min(e.retryMs*2,6e4)}e.drain=null,!e.controller.signal.aborted&&!this.isStopping&&this.sessionState===e.state&&(i?(e.retryTimer=setTimeout(()=>{e.retryTimer=null,this.drainNativeSource(e)},e.retryMs),e.retryTimer.unref()):e.drainRequested&&this.drainNativeSource(e))})();e.drain=t,t.catch(i=>a.error("[sync-source] unexpected drain failure",{error:String(i)}))}async stopNativeSources(e){this.nativeSourceRetryTimer&&clearTimeout(this.nativeSourceRetryTimer),this.nativeSourceRetryTimer=null;let t=[...this.nativeSourceOwners].filter(([,i])=>i.state===e);for(let[,i]of t)i.retryTimer&&clearTimeout(i.retryTimer),i.retryTimer=null,i.controller.abort(new Error("SYNC_SOURCE_STOPPED"));await Promise.all(t.map(([,i])=>i.drain?.catch(()=>{})));for(let[i]of t)this.nativeSourceOwners.delete(i);this.nativeSourceSelection?.state===e&&(this.nativeSourceSelection=null)}async handleLogEntry(e,t){if(!this.sessionState){if(this.isInitializingSession){this.bufferedLogEntries.push(e),a.debug("Buffering log entry until session initialization completes",{type:e.type,bufferedCount:this.bufferedLogEntries.length});return}a.warn("Received log entry but no active session");return}let i=this.sessionState,s=i.sessionId,{sessionKey:r,sessionIsEncrypted:n}=i.encryptionSnapshot;if(e.type==="event_msg"&&e.payload?.type==="turn_aborted"&&(this.approvalDetector.clear(),this.clearInteractivePromptsForAcceptedInput(i)),e.type==="response_item"&&e.payload){let y=e.payload.type;if(y==="function_call"||y==="custom_tool_call")this.isQueuedQuestionTool(e.payload.name)?this.queuedQuestionCallIds.add(e.payload.call_id):this.approvalDetector.onToolCallStart(e.payload.call_id,e.payload.name,e.payload.arguments||e.payload.input||"");else if(y==="function_call_output"||y==="custom_tool_call_output"){if(this.queuedQuestionCallIds.has(e.payload.call_id)){this.queuedQuestionCallIds.delete(e.payload.call_id),this.approvalDetector.onToolCallComplete(e.payload.call_id);return}let I=this.approvalDetector.getPendingCalls().find(w=>w.callId===e.payload.call_id);if(I&&this.isQueuedQuestionTool(I.name)){this.approvalDetector.onToolCallComplete(e.payload.call_id);return}let S=I?this.buildApprovalDedupeKey(this.buildApprovalPromptContextFromPendingCall(I)):void 0;this.approvalDetector.onToolCallComplete(e.payload.call_id);let v=this.observePermissionRequestCompletion(S,"jsonl");if(v.shouldResolve&&await this.clearResolvedInteractivePrompt(e.payload.call_id,v.occurrenceKey??S),!this.isExpectedSessionStateCurrent(i))return}}let o=t?t.event:He(e,s);if(!o)return;o.timestamp=(0,m.prepareEventTimestamp)({orderingKey:s,agentClock:e.timestamp});let l=e.payload?.type,p=!1;if(this.toolActivity?.isActive()&&o.type===m.EventType.TOOL_USE){let y=l==="function_call"||l==="custom_tool_call",I=l==="function_call_output"||l==="custom_tool_call_output";if(y&&typeof e.payload?.call_id=="string"){let S=this.sessionWatcher.getActiveLogFile();S&&this.toolActivity.bindTranscript(S);let v=await this.toolActivity.observeCall({callId:e.payload.call_id,toolName:o.metadata?.toolName??o.metadata?.tool_name,toolInput:o.metadata?.toolInput??o.metadata?.tool_input,ts:e.timestamp});if(!this.isExpectedSessionStateCurrent(i)||v!=="closed")return;p=!0}if(I)return}if(this.toolActivity?.isActive()&&(l==="user_message"||l==="agent_message")){let y=this.toolActivity.flush();if(t?await y:await y.catch(I=>a.warn("[tool-activity] codex boundary flush failed",{sessionId:s,err:String(I)})),!this.isExpectedSessionStateCurrent(i))return}let c=l==="function_call"||l==="function_call_output",u=o.type===m.EventType.USER_PROMPT||o.type===m.EventType.ASSISTANT_RESPONSE||c&&(o.type===m.EventType.TOOL_USE||o.type===m.EventType.INTERACTIVE_PROMPT);if(!t&&!this.hooksActive&&u&&(await this.emitHooksCompatibilityModeNotice(i),!this.isExpectedSessionStateCurrent(i)))return;if(!t&&this.hooksActive){if(o.type===m.EventType.USER_PROMPT){a.debug("[JSONL] Skipping USER_PROMPT \u2014 hooks deliver it",{type:o.type});return}if(c&&(o.type===m.EventType.TOOL_USE||o.type===m.EventType.INTERACTIVE_PROMPT)&&!p){a.debug("[JSONL] Skipping function_call \u2014 hooks deliver this",{type:o.type,tool:e.payload?.name});return}}if(o.type===m.EventType.USER_PROMPT&&o.source===m.EventSource.DESKTOP){let y=t?null:this.consumeRecentMobilePrompt(s,o.content);if(y){a.info("[JSONL] Skipping duplicate USER_PROMPT from mobile",{sessionId:s,matchType:y.matchType,originalLength:y.originalLength,echoLength:y.echoLength});return}}if(this.sessionState!==i){a.warn("[JSONL] Dropping event from stale session generation (#638)",{sessionId:s,currentSessionId:this.sessionState?.sessionId});return}if(t)return o;let h=e.payload?.call_id,g=o.type===m.EventType.TOOL_USE&&typeof h=="string"&&h.length>0&&!!r,f=g?this.getToolActivityLegacyRecorder(s):void 0;f&&g&&f.markLegacyInFlight(h);try{let y=(0,m.encryptForEmit)(r,n,o.content,o.metadata);if(!y){a.error("No session key for ENCRYPTED session \u2014 dropping JSONL event (fail-closed, #638)",{type:o.type,sessionId:s});return}o.content=y.content,o.metadata=y.metadata,y.isEncrypted&&(o.isEncrypted=!0,a.debug("Event encrypted",{type:o.type}));let I=await this.appSyncClient.createEvent(o);a.debug("Event synced to backend",{type:o.type,encrypted:y.isEncrypted}),f&&g&&((0,m.isPersistedEventResult)(I)?await f.finalizeLegacyOwned([h]):f.clearLegacyInFlight(h))}catch(y){f&&g&&f.clearLegacyInFlight(h),a.error("Failed to sync event:",y)}}async handlePermissionRequestHook(e,t,i){if(!this.isExpectedSessionStateCurrent(t)){i&&(i.disposition="dropped");return}let s=i?.context??this.buildApprovalPromptContextFromHookPayload(e),r=i?.dedupeKey??this.buildApprovalDedupeKey(s);if(this.consumeRecoveryPermissionReplay(t,r,i))return;let n=i?.occurrenceKey??`permission:${(0,de.v4)()}`,o={ownerState:t,context:s,dedupeKey:r,occurrenceKey:n,registration:i};this.permissionRequestHookInFlight=o;try{let l=await this.handlePermissionRequestHookWhileTracked(e,t,s,n,r);i&&(i.disposition=l)}finally{this.permissionRequestHookInFlight===o&&(this.permissionRequestHookInFlight=null)}}buildApprovalPromptContextFromHookPayload(e){let t=e.metadata||{},i=typeof t.tool_name=="string"?t.tool_name:"Tool",s=t.tool_input,r=this.firstString(s?.command,s?.cmd),n=re(r)||ce(r),o=i==="apply_patch"?this.firstString(s?.patch,r,typeof s=="string"?s:void 0):void 0,p=re(o)||n,c=!!p,u=p?"apply_patch":i,h=p||this.stringifyToolInput(s),g=p?this.extractFilePathFromToolInput("apply_patch",void 0,p):this.extractFilePathFromToolInput(u,s,h),f=p?this.resolveHookPatchPath(g,t.cwd):g;return{toolName:u,framedPatch:c,toolInput:s,rawInput:h,filePath:f,diff:c?h:void 0,hint:f&&this.mapToolNameForApproval(u)==="Edit"?`File: ${f}`:this.buildPermissionRequestHint(u,s,h)}}resolveHookPatchPath(e,t){if(!e||L.isAbsolute(e))return e;if(!(typeof t!="string"||!L.isAbsolute(t)))return L.resolve(t,e)}async handlePermissionRequestHookWhileTracked(e,t,i=this.buildApprovalPromptContextFromHookPayload(e),s=`permission:${(0,de.v4)()}`,r,n){let o=e.metadata||{},{toolName:l,toolInput:p,rawInput:c}=i,u=this.buildToolDetailsForInteractivePrompt(i),h=u.tool_name||this.mapToolNameForApproval(l),g=u.tool_input||this.buildFallbackToolInput(i),f=!!(h&&g);if(r??=this.buildApprovalDedupeKey({toolName:l,toolInput:p,filePath:i.filePath,rawInput:c,hint:i.hint}),this.hasRecentlyResolvedApprovalDedupeKey(t.sessionId,s))return"resolved";let y=n??await this.tryParsePermissionRequestPromptFromTmux((E,C)=>this.parsedPromptMatchesApprovalContext(E,i,C),()=>this.isExpectedSessionStateCurrent(t));if(!this.isExpectedSessionStateCurrent(t))return a.warn("[Hooks] Dropping stale PermissionRequest after session generation changed",{sessionId:t.sessionId,currentSessionId:this.sessionState?.sessionId}),"dropped";if(this.hasRecentlyResolvedApprovalDedupeKey(t.sessionId,s))return a.info("[Hooks] Dropping PermissionRequest completed while terminal options were being parsed",{sessionId:t.sessionId,toolName:l,occurrenceKey:s}),"resolved";let I=y?.parsedPrompt??null;if(!I)return y?.differentPrompt?(this.waitingPermissionRequests.set(s,{ownerState:t,context:i,occurrenceKey:s,dedupeKey:r,payload:e}),a.info("[Hooks] Queued PermissionRequest until its desktop dialog is visible",{sessionId:t.sessionId,occurrenceKey:s,toolName:l}),"waiting"):(a.warn("[Hooks] Suppressing PermissionRequest mobile prompt because exact Codex options are unavailable",{sessionId:t.sessionId,toolName:l,hint:i.hint}),this.raiseSuppressedBadge(t.sessionId,s,{suppressTmuxObserverUntilResolved:!0,observerSnapshot:y?.snapshot,completionKey:r}),"covered");let S=this.mapToolNameForApproval(l)==="Bash"?this.firstString(p?.command,p?.cmd):void 0,v=this.buildCodexPromptPresentation(I,S,y?.snapshot);if(!v)return a.warn("[Hooks] Suppressing PermissionRequest mobile prompt because Codex option hotkeys are unavailable",{sessionId:t.sessionId,toolName:l,hint:i.hint}),this.raiseSuppressedBadge(t.sessionId,s,{suppressTmuxObserverUntilResolved:!0,observerSnapshot:y?.snapshot,completionKey:r}),"covered";let w=s,R=this.buildApprovalPromptContent(v.content,{toolName:h,toolInput:g,hint:i.hint,filePath:i.filePath}),T={promptId:w,kind:v.kind,options:v.options,submitMap:v.submitMap,promptText:R,createdAt:Date.now(),source:"permission_hook",dedupeKey:s,completionKey:r,ownerSessionId:t.sessionId,observerMatchKey:this.buildObserverPromptMatchKey(I),observerPromptHash:y?.snapshot?this.tmuxPaneObserver.hashPromptSnapshot(y.snapshot):void 0,requiresFollowUpText:v.requiresFollowUpText},b={isApprovalHint:!0,toolName:l,toolInput:p,hint:i.hint,filePath:i.filePath,diff:i.diff,rawInput:c,tool_name:h,tool_input:g,has_details:f,options:v.options,instructions:v.instructions,prompt_source:I?"permission_hook_tmux":"permission_hook",permission_mode:o.permission_mode,turn_id:o.turn_id,dedupe_key:s};return a.info("[Hooks] Sending PermissionRequest interactive prompt",{sessionId:t.sessionId,toolName:l,promptId:w,promptSource:b.prompt_source,occurrenceKey:s}),await this.enqueueOrEmitInteractivePrompt({prompt:T,content:R,metadata:b,ownerState:t}),this.hasRecentlyResolvedApprovalDedupeKey(t.sessionId,s)?"resolved":"covered"}isQueuedQuestionTool(e){return typeof e=="string"&&e==="request_user_input_async"}recordHistoricalQueuedQuestionId(e){if(typeof e=="string"&&e.trim().length>0&&Buffer.byteLength(e,"utf8")<=512&&(this.historicalQueuedQuestionPromptIds.add(e),this.historicalQueuedQuestionPromptIds.size>2e3)){let t=this.historicalQueuedQuestionPromptIds.values();for(;this.historicalQueuedQuestionPromptIds.size>1e3;){let i=t.next();if(i.done)break;this.historicalQueuedQuestionPromptIds.delete(i.value)}}}isQueuedQuestionPromptId(e){if(!e)return!1;if(this.historicalQueuedQuestionPromptIds.has(e)||e.startsWith("q-")||e.startsWith("queued-question::")||this.queuedQuestionCallIds.has(e)||this.pendingInteractivePrompt?.kind==="queued_question"&&(this.pendingInteractivePrompt.promptId===e||this.pendingInteractivePrompt.callId===e||this.pendingInteractivePrompt.dedupeKey===e)||this.queuedInteractivePrompts.some(i=>i.prompt.kind==="queued_question"&&(i.prompt.promptId===e||i.prompt.callId===e||i.prompt.dedupeKey===e)))return!0;let t=this.e1PromptRaises.get(e);return!!(t&&(t.resolutionCallId&&(this.historicalQueuedQuestionPromptIds.has(t.resolutionCallId)||this.queuedQuestionCallIds.has(t.resolutionCallId))||t.resolutionDedupeKey&&(this.historicalQueuedQuestionPromptIds.has(t.resolutionDedupeKey)||t.resolutionDedupeKey.startsWith("queued-question::"))))}normalizeQueuedQuestions(e){return Array.isArray(e)?e.slice(0,100).map((t,i)=>{let s=typeof t=="object"&&t!==null?t.title||t.question||t.prompt||`Question ${i+1}`:String(t),r=String(s).slice(0,1024),o=(typeof t=="object"&&t!==null&&Array.isArray(t.options)?t.options:[]).slice(0,100).map(p=>{if(typeof p=="string")return p.slice(0,1024);if(typeof p=="object"&&p!==null){let c="label"in p?p.label:"text"in p?p.text:String(p),u=String(c).slice(0,1024),h=p.description?String(p.description).slice(0,1024):void 0,g=p.preview?String(p.preview).slice(0,1024):void 0;return{label:u,...h?{description:h}:{},...g?{preview:g}:{}}}return String(p).slice(0,1024)}).filter(p=>{let c=typeof p=="string"?p:p&&typeof p=="object"?p.label:"";return typeof c=="string"&&c.trim().length>0}),l=typeof t=="object"&&t!==null&&typeof t.header=="string"&&t.header.trim().length>0?t.header.trim().slice(0,1024):void 0;return{question:r,...l?{header:l}:{},options:o,multiSelect:typeof t=="object"&&t!==null?!!t.multiSelect:!1}}):[]}async emitQueuedQuestionDesktopNotice(e,t,i){let s={queued_question_desktop_only:!0,notice:t};try{let r=(0,m.prepareEventTimestamp)({orderingKey:e});await this.appSyncClient.publishCompanionNotice({sessionId:e,type:m.EventType.NOTIFICATION,source:m.EventSource.DESKTOP,content:t,metadata:s,timestamp:r},async()=>{if(!this.isExpectedSessionStateCurrent(i))return!1;let n=this.encryptForEmit(t,s,m.EventType.NOTIFICATION,e);return n?(await this.appSyncClient.createEvent({sessionId:e,type:m.EventType.NOTIFICATION,source:m.EventSource.DESKTOP,content:n.content,metadata:n.metadata,timestamp:r,...n.isEncrypted?{isEncrypted:!0}:{}}),!0):!1})}catch(r){a.warn("Failed to emit queued question desktop notice",{error:r})}}async handleQueuedQuestionHook(e,t){let i=e.metadata||{},s=i.tool_input,r=typeof s=="string"?(()=>{try{return JSON.parse(s)}catch{return{}}})():s||{},n=this.normalizeQueuedQuestions(r.questions);if(n.length===0){a.warn("[Hooks] Queued question tool called with empty questions array",{sessionId:t.sessionId,toolName:i.tool_name});return}if(n.length>1){a.info("Queued question has multiple questions; degrading to desktop notice",{sessionId:t.sessionId,questionCount:n.length}),await this.emitQueuedQuestionDesktopNotice(t.sessionId,"\u26A0\uFE0F Multiple questions queued in Codex TUI. Please answer them in your desktop terminal.",t);return}let o=n[0];if(o.multiSelect){a.info("Queued question uses multiSelect; degrading to desktop notice",{sessionId:t.sessionId}),await this.emitQueuedQuestionDesktopNotice(t.sessionId,"\u26A0\uFE0F This queued question uses multi-select, which cannot be answered from mobile. Please answer it in your desktop terminal.",t);return}if(!o.options||o.options.length===0){a.info("Queued question has no options; degrading to desktop notice",{sessionId:t.sessionId}),await this.emitQueuedQuestionDesktopNotice(t.sessionId,"\u26A0\uFE0F This queued question has no predefined options \u2014 please answer it in your desktop terminal.",t);return}let l=this.firstString(i.tool_use_id,i.call_id,i.callId)??`synth-${Date.now()}`;l.startsWith("synth-")||this.queuedQuestionCallIds.add(l);let p=`queued-question::${l}`,c=l;this.recordHistoricalQueuedQuestionId(l),this.recordHistoricalQueuedQuestionId(p);let u=o.question,h=o.options.map((v,w)=>{let R=String(w+1),T=typeof v=="string",b=T?v:v.label||"",E=T?void 0:v.description,C=T?void 0:v.preview;return{number:R,text:b,...E?{description:E}:{},...C?{preview:C}:{}}}),g=Object.fromEntries(h.map(v=>[v.number,v.number])),f="Reply with the number of your choice.",y=[{question:o.question,...o.header?{header:o.header}:{},multiSelect:!1,options:h,instructions:f}],I={promptId:c,callId:l,kind:"queued_question",options:h,submitMap:g,promptText:u,createdAt:Date.now(),source:"queued_question",dedupeKey:p,completionKey:p,ownerSessionId:t.sessionId,requiresFollowUpText:!1,allQuestions:n},S={isApprovalHint:!1,isQueuedQuestion:!0,tool_name:i.tool_name,tool_use_id:l,questions:y,options:h,submitMap:g,instructions:f,prompt_source:"queued_question",turn_id:i.turn_id,dedupe_key:p};a.info("[Hooks] Emitting queued question INTERACTIVE_PROMPT",{sessionId:t.sessionId,toolName:i.tool_name,promptId:c,optionsCount:h.length}),await this.enqueueOrEmitInteractivePrompt({prompt:I,content:u,metadata:S,ownerState:t})}isQueuedQuestionStrictHintLine(e){let t=e.trim();return/to answer$/i.test(t)?/^(?:⇥|->|<-|\bTab\b|[⇧⬆]?←|\b(?:Shift[+-]|S-)Left\b)\s+to answer$/i.test(t):!1}isQueuedQuestionHintLine(e){return this.isQueuedQuestionStrictHintLine(e)}hasQueuedQuestionHintLine(e){let t=e.split(`
|
|
31
|
+
`);return t.some((i,s)=>{let r=i.trim();if(this.isQueuedQuestionStrictHintLine(r))return!0;if(/^to answer$/i.test(r)){let n=Math.max(0,s-2),o=Math.min(t.length-1,s+2);for(let l=n;l<=o;l++)if(l!==s&&(/^\s*•?\s*Queued follow-up inputs\s*$/i.test(t[l])||/^\s*\?\s*\d+\s+questions?\s*$/i.test(t[l])))return!0}return!1})}hasQueuedInputsFragment(e){let t=e.split(`
|
|
32
|
+
`),i=t.some(n=>/^\s*•?\s*Queued follow-up inputs\s*$/i.test(n)),s=t.some(n=>/^\s*\?\s*\d+\s+questions?\s*$/i.test(n)),r=this.hasQueuedQuestionHintLine(e);return i||s||r}isModelStatusFooterLine(e){return/^[>›]/.test(e)?!1:/^(?:(?:GPT|Claude|Codex|DeepSeek)[-\s]\d[\w.-]*|o\d[\w.-]*)(?:\s+(?:xhigh|high|medium|low|fast|slow|default))*(?:\s+[·•|]\s+\S.*)?$/i.test(e)}isShortcutsOrStatusHintLine(e){if(/^[>›]/.test(e))return!1;let t=e.trim();if(t.length===0)return!0;let i="(?:esc to interrupt|\\?\\s+for\\s+(?:shortcuts|help)|\\d+%\\s+context\\s+left|\u26A0\\s+\\d+\\s+warning.*)";return new RegExp(`^${i}(?:\\s{2,}${i})?$`,"i").test(t)}validateTrailingFooterLines(e){return e.length===0?!0:e.length>2?!1:e.length===1?this.isModelStatusFooterLine(e[0])||this.isShortcutsOrStatusHintLine(e[0]):this.isModelStatusFooterLine(e[0])&&this.isShortcutsOrStatusHintLine(e[1])}isAssistantExecutionLine(e){let t=e.trim();return!!(/^•\s*Working(?:\s*\(.*?\))?\s*$/i.test(t)||/^•\s*(?:Ran|Read|Edited|Searched|Thinking|Explored)\b/i.test(t)||/^•\s*(?:Applied|Done|Finished|Plan completed|I have finished|I've finished)\b/i.test(t)||/^•\s*Failed\s*\(exit\s+\d+\)/i.test(t)||/^✔\s*You approved\b/i.test(t)||/^\+\s*\d+\s+lines?\b/i.test(t)||/^└\s*(?:exit code \d+|Tip:|Read|[+]\s*\d+\s+lines)/i.test(t))}isHistoricalFooter(e,t){if(t<0||t>=e.length)return{isFooter:!1,footerStartIdx:-1};if(t>=2){let i=e[t-2].trim(),s=e[t-1].trim(),r=e[t].trim();if(/^[>›]\s*(?:Ask Codex to do anything\s*)?$/i.test(i)&&s.length>0&&r.length>0&&this.isModelStatusFooterLine(s)&&this.isShortcutsOrStatusHintLine(r))return{isFooter:!0,footerStartIdx:t-1}}if(t>=1){let i=e[t-1].trim(),s=e[t].trim();if(/^[>›]\s*(?:Ask Codex to do anything\s*)?$/i.test(i)&&s.length>0&&this.isModelStatusFooterLine(s))return{isFooter:!0,footerStartIdx:t}}return{isFooter:!1,footerStartIdx:-1}}isHistoricalTurnBoundary(e,t){if(t<0||t>=e.length)return!1;let i=e[t];return/^[>›]\s*Ask Codex to do anything\s*$/i.test(i)?!0:this.isHistoricalFooter(e,t).isFooter}isDraftPromptLine(e){return!(!/^[>›]/.test(e)||/^[>›]\s*Ask Codex to do anything\s*$/i.test(e)||/^[>›]\s*$/.test(e))}extractLiveQueuedQuestionWidget(e){let s=te(e).split(`
|
|
33
|
+
`).slice(-25).join(`
|
|
29
34
|
`).split(`
|
|
30
|
-
`).map(
|
|
31
|
-
`).
|
|
32
|
-
`).
|
|
33
|
-
`);let
|
|
34
|
-
`).
|
|
35
|
-
`))
|
|
36
|
-
`).
|
|
37
|
-
`)
|
|
38
|
-
`).
|
|
39
|
-
`)
|
|
40
|
-
`)
|
|
35
|
+
`).map(I=>I.trim()).filter(I=>I.length>0);if(s.length<2)return null;let r=[];for(let I=0;I<=s.length-3;I++){let S=/^\s*•?\s*Queued follow-up inputs\s*$/i.test(s[I]),v=s[I+1].match(/^\s*\?\s*(\d+)\s+questions?\s*$/i),w=/^to answer$/i.test(s[I+2]),T=this.isQueuedQuestionStrictHintLine(s[I+2])||w&&S&&v!==null;S&&v&&T&&r.push({headerIdx:I,counterIdx:I+1,hintIdx:I+2,count:parseInt(v[1],10)})}if(r.length===0){for(let I=s.length-1;I>=0;I--)if(/^[>›]/.test(s[I])){let S=s.slice(I+1);if(this.validateTrailingFooterLines(S)&&!/^[>›]\s*(?:Ask Codex to do anything\s*)?$/i.test(s[I]))return{hintLineIdx:-1,composerIdx:-1,dirtyComposerFound:!0};break}return null}let n=r[r.length-1],o=n.hintIdx+1;if(o>=s.length)return null;let l=s[o],p=s.slice(o+1);if(!this.validateTrailingFooterLines(p))return p.some(S=>this.isAssistantExecutionLine(S))?null:{hintLineIdx:-1,composerIdx:-1,dirtyComposerFound:!0};if(this.isDraftPromptLine(l))return{hintLineIdx:-1,composerIdx:-1,dirtyComposerFound:!0};let h=/^[>›]\s*Ask Codex to do anything\s*$/i.test(l),g=/^[>›]\s*$/.test(l);if(!h&&!g)return{hintLineIdx:-1,composerIdx:-1,dirtyComposerFound:!0};let f=0;for(let I=n.headerIdx-1;I>=0;I--)if(this.isHistoricalTurnBoundary(s,I)){f=I+1;break}let y=s.slice(f,n.headerIdx);if(g){if(y.some(S=>/^[>›]\s*$/.test(S)))return{hintLineIdx:-1,composerIdx:-1,dirtyComposerFound:!0};for(let S=0;S<y.length;S++){let v=y[S];if(/^[>›]/.test(v)&&!/^[>›]\s*Ask Codex to do anything\s*$/i.test(v)&&!y.slice(S+1).some(T=>this.isAssistantExecutionLine(T)))return{hintLineIdx:-1,composerIdx:-1,dirtyComposerFound:!0}}}else for(let I=0;I<y.length;I++){let S=y[I];if(/^[>›]/.test(S)&&!/^[>›]\s*Ask Codex to do anything\s*$/i.test(S)&&!y.slice(I+1).some(R=>/^[•✔└+]/i.test(R.trim())))return{hintLineIdx:-1,composerIdx:-1,dirtyComposerFound:!0}}return{hintLineIdx:n.hintIdx,composerIdx:o,count:n.count,dirtyComposerFound:!1}}isQueuedQuestionCollapsed(e){let t=this.extractLiveQueuedQuestionWidget(e);return t!==null&&!t.dirtyComposerFound}isExpandedQuestionMatchingPrompt(e,t){let s=te(e).split(`
|
|
36
|
+
`).slice(-25).join(`
|
|
37
|
+
`);if(!/Press a number to choose/i.test(s))return!1;let r=s.split(`
|
|
38
|
+
`).map(S=>S.trim()).filter(S=>S.length>0),n=-1;for(let S=r.length-1;S>=0;S--)if(/Press a number to choose/i.test(r[S])){n=S;break}if(n===-1)return!1;let o=r.findIndex((S,v)=>v>n&&/^[>›❯▸▶]?\s*1\.\s+/i.test(S));if(o===-1)return!1;let l=r.slice(n+1,o);if(l.some(S=>/›\s*Ask Codex to do anything/i.test(S)||/•\s*Working/i.test(S)))return!1;let p=t.promptText.trim().replace(/\s+/g," ");if(!/^Question \d+$/i.test(p)&&p.length>0){let S="";if(o>n+1)S=l.join(" ").trim().replace(/\s+/g," ");else{let b=[];for(let E=n-1;E>=0;E--){let C=r[E];if(/›\s*Ask Codex/i.test(C)||/•\s*Working/i.test(C)||/Queued follow-up inputs/i.test(C)||(b.unshift(C),b.join(" ").length>=p.length))break}S=b.join(" ").trim().replace(/\s+/g," ")}if(S.length===0)return!1;let v=S.toLowerCase()===p.toLowerCase(),w=/(?:\.{2,}|…)$/.test(S),R=S.replace(/(?:\.{2,}|…)$/,"").trim().toLowerCase(),T=w&&R.length>=8&&p.toLowerCase().startsWith(R);if(!v&&!T)return!1}let u=[],h=o;for(let S=o;S<r.length;S++){let v=r[S];if(/^[>›]\s*(?:Ask Codex to do anything\s*)?$/i.test(v)||/^•\s*Working/i.test(v))break;/^[>›❯▸▶]?\s*\d+\./.test(v)?(u.push(v),h=S):u.length>0&&u.length<=t.options.length&&(u[u.length-1]+=" "+v,h=S)}let g=r.slice(h+1),f=g.findIndex(S=>/^[>›]/.test(S));if(f!==-1){if(f!==0)return!1;let S=g[f];if(!/^[>›]\s*(?:Ask Codex to do anything\s*)?$/i.test(S))return!1;let v=g.slice(f+1);if(!this.validateTrailingFooterLines(v))return!1}else if(!this.validateTrailingFooterLines(g))return!1;let y=u;if(u.length===t.options.length+1){let S=String(t.options.length+1),v=u[u.length-1].trim();if(new RegExp(`^[>\u203A\u276F\u25B8\u25B6]?\\s*${S}\\.\\s+Other(?:\\s*\\(write an answer\\))?\\s*$`,"i").test(v))y=u.slice(0,t.options.length);else return!1}else if(u.length!==t.options.length)return!1;let I=y.join(`
|
|
39
|
+
`);for(let S of t.options){let v=zt(S.text.trim()),w=new RegExp(`(?:^|\\n)\\s*[>\u203A\u276F\u25B8\u25B6]?\\s*${zt(S.number)}\\.\\s+${v}\\s*(?:\\r?\\n|$)`,"i"),R=I.match(w);if(!R||R.index===void 0)return!1;I=I.slice(R.index+R[0].length)}return!0}async deliverQueuedQuestionResponse(e,t,i,s){if(!this.isExpectedSessionStateCurrent(e)||this.pendingInteractivePrompt!==t)return"stale";let r=await this.tmuxPaneObserver.captureSnapshot();if(!this.isExpectedSessionStateCurrent(e)||this.pendingInteractivePrompt!==t)return"unverified";let o=te(r).split(`
|
|
40
|
+
`).slice(-25).join(`
|
|
41
|
+
`);if(!!this.tmuxPaneObserver.extractActiveApprovalBlock?.(r)||/Would you like to run\s+["`].*["`]/i.test(o)&&/Yes,\s+and\s+don't\s+ask\s+again/i.test(o)||!/Press a number to choose/i.test(o)&&/\[(?:y\/n|Y\/n|y\/N)\]/i.test(o))return a.warn("Refusing to deliver queued question input: active approval dialog or menu detected in pane",{sessionId:e.sessionId,promptId:t.promptId}),"unverified";if(!o||o.trim().length<10)return a.warn("Pane snapshot is empty or incomplete; failing closed as unverified",{sessionId:e.sessionId,promptId:t.promptId}),"unverified";let p=this.extractLiveQueuedQuestionWidget(o),c=p?.count??s,u=p!==null&&!p.dirtyComposerFound,h=this.isExpandedQuestionMatchingPrompt(o,t),g=this.hasQueuedInputsFragment(o);if(!u&&!h)return/Press a number to choose/i.test(o)||g?(a.warn("Unmatched chooser dialog or partial queued widget visible in pane; failing closed as unverified",{sessionId:e.sessionId,promptId:t.promptId}),"unverified"):/›\s*(?:Ask Codex to do anything|$)/m.test(o)&&!o.includes("Disconnected")?(a.info("Queued question already resolved on desktop; marking stale",{sessionId:e.sessionId,promptId:t.promptId}),await this.clearResolvedInteractivePrompt(t.callId??t.promptId,t.dedupeKey??t.promptId),"stale"):(a.warn("Queued question not found in pane but composer is unconfirmed; failing closed as unverified",{sessionId:e.sessionId,promptId:t.promptId}),"unverified");if(u&&!h){if(/Press a number to choose/i.test(o))return a.warn("Unrelated or mismatched chooser active before S-Left expansion; failing closed as unverified",{sessionId:e.sessionId,promptId:t.promptId}),"unverified";if(!p||p.dirtyComposerFound)return a.warn("No active clean queued question widget boundary identified before S-Left expansion; failing closed as unverified",{sessionId:e.sessionId,promptId:t.promptId}),"unverified";if(a.info("Queued question dialog is collapsed; sending S-Left to expand",{sessionId:e.sessionId,promptId:t.promptId,hintLineIdx:p.hintLineIdx,composerIdx:p.composerIdx}),!this.isExpectedSessionStateCurrent(e)||this.pendingInteractivePrompt!==t)return"unverified";if(!await this.promptResponder.sendKey(e.sessionId,"S-Left"))return"send_failed";let v=!1,w=Date.now();for(;Date.now()-w<350;){if(await new Promise(C=>setTimeout(C,50)),!this.isExpectedSessionStateCurrent(e)||this.pendingInteractivePrompt!==t)return"unverified";let R=await this.tmuxPaneObserver.captureSnapshot();if(!this.isExpectedSessionStateCurrent(e)||this.pendingInteractivePrompt!==t)return"unverified";let b=te(R).split(`
|
|
42
|
+
`).slice(-25).join(`
|
|
43
|
+
`);if(!!this.tmuxPaneObserver.extractActiveApprovalBlock?.(R)||/Would you like to run\s+["`].*["`]/i.test(b)&&/Yes,\s+and\s+don't\s+ask\s+again/i.test(b)||!/Press a number to choose/i.test(b)&&/\[(?:y\/n|Y\/n|y\/N)\]/i.test(b))return a.warn("Approval dialog appeared while expanding queued question; aborting",{sessionId:e.sessionId,promptId:t.promptId}),"unverified";if(this.isExpandedQuestionMatchingPrompt(b,t)){v=!0;break}}if(!v)return a.warn("Queued question failed to expand to expected prompt after S-Left; failing closed",{sessionId:e.sessionId,promptId:t.promptId}),"unverified"}if(!this.isExpectedSessionStateCurrent(e)||this.pendingInteractivePrompt!==t)return"unverified";if(a.info("Sending option selection for queued question",{sessionId:e.sessionId,promptId:t.promptId,input:i}),!await this.promptResponder.sendLiteral(e.sessionId,i))return"send_failed";let y=!1,I=Date.now();for(;Date.now()-I<500;){if(await new Promise(E=>setTimeout(E,50)),!this.isExpectedSessionStateCurrent(e))return"stale";let S=await this.tmuxPaneObserver.captureSnapshot(),w=te(S).split(`
|
|
44
|
+
`).slice(-25).join(`
|
|
45
|
+
`);if(!w||w.trim().length<10||w.includes("Disconnected"))continue;let R=this.isExpandedQuestionMatchingPrompt(w,t),T=!/Press a number to choose/i.test(w),b=/›\s*(?:Ask Codex to do anything|$)/m.test(w);if(T&&b){let E=this.extractLiveQueuedQuestionWidget(w);if(E&&E.count!==void 0&&c!==void 0&&E.count<c){y=!0;break}if(E===null){let C=w.split(`
|
|
46
|
+
`).map(K=>K.trim()).filter(K=>K.length>0),M=-1;for(let K=C.length-1;K>=0;K--)if(/^[>›]\s*(?:Ask Codex to do anything\s*)?$/i.test(C[K])){M=K;break}if(M!==-1){let K=C.slice(M+1);if(this.validateTrailingFooterLines(K)){let W=0;for(let q=M-1;q>=0;q--)if(this.isHistoricalTurnBoundary(C,q)){W=q+1;break}let Z=C.slice(W,M);if(!Z.some((q,B)=>!/^[>›]/.test(q)||/^[>›]\s*Ask Codex to do anything\s*$/i.test(q)?!1:!Z.slice(B+1).some(ii=>/^[•✔└+]/i.test(ii.trim())))){let q=Z.join(`
|
|
47
|
+
`);if(!this.hasQueuedInputsFragment(q)){y=!0;break}}}}}}else if(!R&&/Press a number to choose/i.test(w)&&b&&this.queuedInteractivePrompts.some(C=>C.prompt.kind==="queued_question"&&this.isExpandedQuestionMatchingPrompt(w,C.prompt))){y=!0;break}}return y?(await this.clearResolvedInteractivePrompt(t.callId??t.promptId,t.dedupeKey??t.promptId),"sent"):(a.warn("Queued question chooser did not transition after option key dispatch",{sessionId:e.sessionId,promptId:t.promptId,input:i}),"unverified")}async emitHooksCompatibilityModeNotice(e){if(this.hooksCompatibilityNoticeSent||!this.isExpectedSessionStateCurrent(e))return;this.hooksCompatibilityNoticeSent=!0;let t="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"};a.warn("Codex hooks inactive; running in compatibility mode",{sessionId:e.sessionId});try{let s=(0,m.prepareEventTimestamp)({orderingKey:e.sessionId}),r=await this.appSyncClient.publishCompanionNotice({sessionId:e.sessionId,type:m.EventType.NOTIFICATION,source:m.EventSource.DESKTOP,content:t,metadata:i,timestamp:s},async()=>{if(!this.isExpectedSessionStateCurrent(e))return!1;let n=this.encryptForEmit(t,i,m.EventType.NOTIFICATION,e.sessionId);return n?(await this.appSyncClient.createEvent({sessionId:e.sessionId,type:m.EventType.NOTIFICATION,source:m.EventSource.DESKTOP,content:n.content,metadata:n.metadata,timestamp:s,...n.isEncrypted?{isEncrypted:!0}:{}}),!0):!1});a.debug("Hooks compatibility notice publication outcome",{sessionId:e.sessionId,result:r})}catch(s){a.warn("Failed to emit hooks compatibility mode notification",{error:s})}}async handleApprovalPending(e){let t=this.sessionState;if(!t)return;if((this.queuedPermissionRequestSessionCounts.get(t.sessionId)??0)>0){a.debug("Skipping heuristic approval prompt while PermissionRequest owns the session prompt",{sessionId:t.sessionId,callId:e.callId});return}let i=this.buildApprovalDedupeKey(e);if(i&&this.hasRecentlyResolvedApprovalDedupeKey(t.sessionId,i)){a.info("Skipping heuristic approval prompt; same approval was already answered recently",{callId:e.callId,toolName:e.toolName,dedupeKey:i});return}if(i&&this.hasDurablePermissionHookFallbackByDedupeKey(t.sessionId,i)){a.debug("Skipping heuristic approval prompt already owned by a hook fallback",{sessionId:t.sessionId,callId:e.callId,dedupeKey:i});return}if(i&&this.hasActiveOrQueuedPermissionHookPrompt(t.sessionId,i)){this.mergeCallIdIntoPromptByDedupeKey(t.sessionId,i,e.callId),a.info("Skipping heuristic approval prompt; PermissionRequest hook already emitted it",{callId:e.callId,toolName:e.toolName,dedupeKey:i});return}a.info("Sending approval pending interactive prompt",e);try{let s=await this.tryParseInteractivePromptFromTmux(),r=s?.parsedPrompt??null;if((this.queuedPermissionRequestSessionCounts.get(t.sessionId)??0)>0||r&&this.hasMatchingDurablePermissionHookFallback(r,t.sessionId,s?.snapshot)||r&&this.hasMatchingPermissionHookPrompt(r,t.sessionId)){a.debug("Skipping heuristic approval prompt after PermissionRequest claimed the terminal dialog",{sessionId:t.sessionId,callId:e.callId});return}let n=this.buildToolDetailsForInteractivePrompt(e,s?.snapshot),o=n.tool_name||this.mapToolNameForApproval(e.toolName),l=n.tool_input||this.buildFallbackToolInput(e),p=!!(o&&l);if(!r){a.warn("Suppressing heuristic approval prompt because exact Codex options are unavailable",{callId:e.callId,toolName:e.toolName,hint:e.hint}),this.raiseSuppressedBadge(t.sessionId,i);return}if(!this.parsedPromptMatchesApprovalContext(r,e,s?.snapshot)){a.warn("Suppressing heuristic approval prompt because parsed tmux prompt does not match the active tool",{callId:e.callId,toolName:e.toolName,hint:e.hint,parsedPromptText:r.promptText}),this.raiseSuppressedBadge(t.sessionId,i);return}let c=this.mapToolNameForApproval(e.toolName)==="Bash"?this.firstString(e.toolInput?.command,e.toolInput?.cmd):void 0,u=this.buildCodexPromptPresentation(r,c,s?.snapshot);if(!u){a.warn("Suppressing heuristic approval prompt because Codex option hotkeys are unavailable",{callId:e.callId,toolName:e.toolName,hint:e.hint}),this.raiseSuppressedBadge(t.sessionId,i);return}let h=u.options,g=this.buildApprovalPromptContent(u.content,{toolName:o,toolInput:l,hint:e.hint,filePath:e.filePath}),f={promptId:e.callId,callId:e.callId,kind:u.kind,options:h,submitMap:u.submitMap,promptText:u.promptText,createdAt:Date.now(),source:r?"tmux":"heuristic",dedupeKey:i,ownerSessionId:t.sessionId,observerMatchKey:this.buildObserverPromptMatchKey(r),requiresFollowUpText:u.requiresFollowUpText},y={isApprovalHint:!0,toolName:e.toolName,toolInput:e.toolInput,hint:e.hint,callId:e.callId,filePath:e.filePath,diff:e.diff,rawInput:e.rawInput,tool_name:o,tool_input:l,has_details:p,options:h,instructions:u.instructions,prompt_source:r?"tmux":"heuristic",dedupe_key:i};a.debug("Interactive prompt (pre-encryption)",{sessionId:t.sessionId,callId:e.callId,contentPreview:g.substring(0,200),toolDetails:n,metadata:y}),await this.enqueueOrEmitInteractivePrompt({prompt:f,content:g,metadata:y,ownerState:t})}catch(s){a.error("Failed to send approval interactive prompt:",s)}}async handleTerminalMenu(e,t,i){if(!this.isExpectedSessionStateCurrent(t)||this.pendingInteractivePrompt?.terminalMenuIdentity===e.identity&&this.pendingInteractivePrompt.ownerSessionId===t.sessionId)return;let s=(0,de.v4)(),r={promptId:s,kind:"numbered",options:e.prompt.options,submitMap:e.prompt.submitMap,promptText:e.prompt.promptText,createdAt:Date.now(),source:"tmux",dedupeKey:`menu:${s}`,ownerSessionId:t.sessionId,observerMatchKey:this.buildObserverPromptMatchKey(e.prompt),observerPromptHash:i??this.tmuxPaneObserver.hashPromptSnapshot(e.snapshot),terminalMenuIdentity:e.identity};await this.enqueueOrEmitInteractivePrompt({prompt:r,ownerState:t,content:e.prompt.promptText,metadata:{options:e.prompt.options,instructions:"Reply with the number of the option you want",prompt_source:"tmux_live",dialog_kind:"terminal_menu",has_details:!1}}),a.info("Published live terminal menu",{sessionId:t.sessionId,promptId:r.promptId,optionsCount:r.options.length})}async handleTmuxPromptCandidate(e,t,i){let s=this.sessionState;if(!s){this.tmuxPaneObserver.resetLastPromptHash();return}let r=this.tmuxPaneObserver.extractActiveApprovalBlock(e)?null:(0,ge.parseActiveTerminalMenu)(e);if(r){await this.handleTerminalMenu(r,s,i);return}if(await this.promoteWaitingPermissionRequest(e,s)||!t&&this.deferTmuxPromptCandidateForPermissionHook(s.sessionId,e,i))return;let n=t?.occurrenceKey;if(n&&this.hasRecentlyResolvedApprovalDedupeKey(s.sessionId,n))return;let o=(0,j.parseInteractivePrompt)(e);if(!o){this.raiseSuppressedBadge(s.sessionId,n??null);return}if(this.hasMatchingPermissionHookPrompt(o,s.sessionId)){a.debug("Skipping tmux prompt candidate already owned by PermissionRequest",{sessionId:s.sessionId,promptText:o.promptText});return}let l=this.getMostRecentPendingToolCall();if(!l){if(await new Promise(E=>setTimeout(E,500)),!this.isExpectedSessionStateCurrent(s)){a.warn("Dropping tmux prompt candidate after session generation changed",{sessionId:s.sessionId,currentSessionId:this.sessionState?.sessionId});return}if(!t&&this.deferTmuxPromptCandidateForPermissionHook(s.sessionId,e,i))return;l=this.getMostRecentPendingToolCall()}let p=t?.context??(l?this.buildApprovalPromptContextFromPendingCall(l):null);if(p&&!this.parsedPromptMatchesApprovalContext(o,p,e)){a.warn("Skipping tmux-detected prompt because parsed prompt does not match pending tool call",{callId:l?.callId,toolName:l?.name,parsedPromptText:o.promptText}),this.raiseSuppressedBadge(s.sessionId,n??null);return}let c=p?null:this.buildApprovalPromptContextFromParsedPrompt(o),u=p||c;if(!u){a.warn("Skipping tmux-detected prompt because no tool context could be derived from the parsed prompt",{parsedPromptText:o.promptText}),this.raiseSuppressedBadge(s.sessionId,n??null);return}let h=this.mapToolNameForApproval(u.toolName)==="Bash"?this.firstString(u.toolInput?.command,u.toolInput?.cmd):void 0,g=this.buildCodexPromptPresentation(o,h,e);if(!g){a.warn("Skipping tmux-detected prompt because Codex option hotkeys are unavailable",{parsedPromptText:o.promptText}),this.raiseSuppressedBadge(s.sessionId,n??null);return}let f=u?this.buildApprovalDedupeKey(u):void 0;if(f&&this.hasRecentlyResolvedApprovalDedupeKey(s.sessionId,f)){a.info("Skipping tmux-detected prompt; same approval was already answered recently",{promptText:o.promptText,dedupeKey:f});return}if(f&&this.hasActiveOrQueuedPermissionHookPrompt(s.sessionId,f)){l?.callId&&this.mergeCallIdIntoPromptByDedupeKey(s.sessionId,f,l.callId),a.info("Skipping tmux-detected prompt; PermissionRequest hook already emitted it",{promptText:o.promptText,dedupeKey:f});return}let y=u?this.buildToolDetailsForInteractivePrompt(u,e):{},I=y.tool_name||this.mapToolNameForApproval(l?.name),S=y.tool_input||(u?this.buildFallbackToolInput(u):void 0),v=!!(I&&S),R={promptId:l?.callId||(0,de.v4)(),callId:l?.callId,kind:g.kind,options:g.options,submitMap:g.submitMap,promptText:g.promptText,createdAt:Date.now(),source:"tmux",dedupeKey:f,ownerSessionId:s.sessionId,observerMatchKey:this.buildObserverPromptMatchKey(o),observerPromptHash:i,requiresFollowUpText:g.requiresFollowUpText},T={options:g.options,instructions:g.instructions,prompt_source:"tmux_live",toolName:u?.toolName,toolInput:u?.toolInput,hint:u?.hint,filePath:u?.filePath,diff:u?.diff,rawInput:u?.rawInput,tool_name:I,tool_input:S,has_details:v,dedupe_key:f},b=this.buildApprovalPromptContent(g.content,{toolName:I,toolInput:S,hint:u?.hint,filePath:u?.filePath});try{await this.enqueueOrEmitInteractivePrompt({prompt:R,content:b,metadata:T,ownerState:s})&&a.info("Sent tmux-detected interactive prompt",{sessionId:s.sessionId,promptText:o.promptText,kind:o.kind})}catch(E){a.error("Failed to send tmux-detected interactive prompt",{error:E})}}async enqueueOrEmitInteractivePrompt(e){if(!this.isExpectedSessionStateCurrent(e.ownerState))return a.warn("Dropping interactive prompt from stale session generation",{sessionId:e.ownerState.sessionId,currentSessionId:this.sessionState?.sessionId,source:e.prompt.source}),!1;if(e.prompt.ownerSessionId??=e.ownerState.sessionId,e.prompt.dedupeKey&&this.hasRecentlyResolvedApprovalDedupeKey(e.ownerState.sessionId,e.prompt.dedupeKey))return a.debug("Skipping interactive prompt emission; same approval was already answered recently",{source:e.prompt.source,callId:e.prompt.callId,dedupeKey:e.prompt.dedupeKey}),!1;let t=this.pendingInteractivePrompt;if(t&&t.ownerSessionId!==e.ownerState.sessionId&&(a.warn("Discarding active prompt from a stale session generation",{activeSessionId:t.ownerSessionId,candidateSessionId:e.ownerState.sessionId}),this.pendingInteractivePrompt=null,t=null),t&&t.kind==="queued_question"&&e.prompt.kind!=="queued_question"){a.info("Preempting active queued question for higher-priority approval prompt",{queuedQuestionId:t.promptId,approvalCallId:e.prompt.callId});let i=Date.now();e.prompt.preemptedQueuedQuestionId=t.promptId,e.prompt.preemptedQueuedQuestionAt=i,e.prompt.createdAt=e.prompt.createdAt||i;let s={prompt:t,content:t.promptText,metadata:{isApprovalHint:!1,isQueuedQuestion:!0,options:t.options,submitMap:t.submitMap,instructions:"Reply with the number of your choice.",dedupe_key:t.dedupeKey,tool_name:"request_user_input_async",tool_use_id:t.callId,prompt_source:"queued_question",questions:t.allQuestions?[{question:t.promptText,multiSelect:!1,options:t.options,instructions:"Reply with the number of your choice."}]:void 0},ownerState:e.ownerState};this.queuedInteractivePrompts.unshift(s),this.pendingInteractivePrompt=e.prompt,t=e.prompt,this.emitQueuedQuestionDesktopNotice(e.ownerState.sessionId,"\u26A0\uFE0F Queued question paused \u2014 please answer the approval request first.",e.ownerState).catch(r=>{a.debug("Failed to emit queued question desktop notice",{err:r})})}if(!t||t===e.prompt){this.pendingInteractivePrompt=e.prompt;try{return await this.emitInteractivePromptEvent(e),!0}catch(i){throw this.pendingInteractivePrompt?.promptId===e.prompt.promptId&&(this.pendingInteractivePrompt=null),i}}if(this.isSameInteractivePrompt(t,e.prompt)){if(e.prompt.source==="permission_hook"&&t.source!=="permission_hook"){t.source="permission_hook",t.completionKey=e.prompt.completionKey??t.dedupeKey,t.dedupeKey=e.prompt.dedupeKey;let i=this.e1PromptRaises.get(t.promptId);i&&(i.resolutionDedupeKey=t.dedupeKey,i.resolutionCompletionKey=t.completionKey)}return!t.callId&&e.prompt.callId&&(t.callId=e.prompt.callId,a.debug("Merged callId into existing interactive prompt",{source:t.source,callId:e.prompt.callId,promptText:t.promptText})),a.debug("Skipping duplicate interactive prompt emission",{existingSource:t.source,candidateSource:e.prompt.source,existingCallId:t.callId,candidateCallId:e.prompt.callId,promptText:e.prompt.promptText}),!1}return this.queuedInteractivePrompts.some(i=>this.isSameInteractivePrompt(i.prompt,e.prompt))?(a.debug("Skipping duplicate queued interactive prompt",{candidateSource:e.prompt.source,candidateCallId:e.prompt.callId,promptText:e.prompt.promptText}),!1):((e.prompt.kind==="queued_question"||this.isQueuedQuestionPromptId(e.prompt.callId)||this.isQueuedQuestionPromptId(e.prompt.dedupeKey)||this.isQueuedQuestionPromptId(e.prompt.promptId))&&(this.recordHistoricalQueuedQuestionId(e.prompt.promptId),e.prompt.callId&&this.recordHistoricalQueuedQuestionId(e.prompt.callId),e.prompt.dedupeKey&&this.recordHistoricalQueuedQuestionId(e.prompt.dedupeKey)),this.queuedInteractivePrompts.push(e),a.info("Queued interactive prompt behind active prompt",{activeCallId:t.callId,queuedCallId:e.prompt.callId,queueLength:this.queuedInteractivePrompts.length}),!1)}async emitInteractivePromptEvent(e){if(!this.isExpectedSessionStateCurrent(e.ownerState))return;let t=e.ownerState.sessionId,i=this.e1PromptRaises.get(e.prompt.promptId),s=i?i.record:this.newE1Raise(t,!0,void 0,{...e.prompt.dedupeKey!==void 0?{dedupeKey:e.prompt.dedupeKey}:{},...e.prompt.completionKey!==void 0?{completionKey:e.prompt.completionKey}:{},...e.prompt.callId!==void 0?{callId:e.prompt.callId}:{}});e.prompt.promptId=s.promptId;let r=this.e1PromptRaises.get(s.promptId);r&&(r.resolutionDedupeKey??=e.prompt.dedupeKey,r.resolutionCompletionKey??=e.prompt.completionKey,r.resolutionCallId??=e.prompt.callId),(e.prompt.kind==="queued_question"||this.isQueuedQuestionPromptId(e.prompt.callId)||this.isQueuedQuestionPromptId(e.prompt.dedupeKey)||this.isQueuedQuestionPromptId(s.promptId))&&(this.recordHistoricalQueuedQuestionId(s.promptId),e.prompt.callId&&this.recordHistoricalQueuedQuestionId(e.prompt.callId),e.prompt.dedupeKey&&this.recordHistoricalQueuedQuestionId(e.prompt.dedupeKey)),e.prompt.dedupeKey&&this.e1ContentKeyIndex.set(`${t}::${e.prompt.dedupeKey}`,s.promptId),this.stashE1RaiseContent(s.promptId,e.content,e.metadata??{}),await this.publishE1Prompt(t,s,m.EventType.INTERACTIVE_PROMPT,e.content,e.metadata??{})}rebindWaitingPermissionRequests(e){for(let t of this.waitingPermissionRequests.values())t.ownerState.codexSessionId&&t.ownerState.codexSessionId===e.codexSessionId&&(t.ownerState=e)}async promoteWaitingPermissionRequest(e,t){if(!this.isExpectedSessionStateCurrent(t))return!1;let i=(0,j.parseInteractivePrompt)(e);if(!i||this.hasMatchingPermissionHookPrompt(i,t.sessionId))return!1;for(let[s,r]of this.waitingPermissionRequests)if(this.isExpectedSessionStateCurrent(r.ownerState)&&this.parsedPromptMatchesApprovalContext(i,r.context,e)){this.waitingPermissionRequests.delete(s);try{await this.handlePermissionRequestHookWhileTracked(r.payload,t,r.context,s,r.dedupeKey,{parsedPrompt:i,snapshot:e})}catch(n){throw this.isExpectedSessionStateCurrent(t)&&!this.hasRecentlyResolvedApprovalDedupeKey(t.sessionId,s)&&this.waitingPermissionRequests.set(s,r),this.tmuxPaneObserver.resetLastPromptHash(),n}return!0}return!1}async emitNextQueuedInteractivePrompt(){if(this.pendingInteractivePrompt)return;if(this.queuedInteractivePrompts.length===0){let t=this.sessionState;if(t&&this.waitingPermissionRequests.size>0){let i=await this.tmuxPaneObserver.captureSnapshot();!(i&&await this.promoteWaitingPermissionRequest(i,t))&&this.isExpectedSessionStateCurrent(t)&&!this.pendingInteractivePrompt&&this.waitingPermissionRequests.size>0&&this.tmuxPaneObserver.resetLastPromptHash()}return}let e=this.queuedInteractivePrompts.shift();if(e){if(!this.isExpectedSessionStateCurrent(e.ownerState)){a.warn("Discarding queued prompt from stale session generation",{sessionId:e.ownerState.sessionId,currentSessionId:this.sessionState?.sessionId}),await this.emitNextQueuedInteractivePrompt();return}if(e.prompt.kind==="queued_question")try{let t=await this.tmuxPaneObserver.captureSnapshot();if(!this.isExpectedSessionStateCurrent(e.ownerState)){a.warn("Session changed during snapshot capture; discarding queued prompt",{promptId:e.prompt.promptId,sessionId:e.ownerState.sessionId,currentSessionId:this.sessionState?.sessionId});return}if(this.pendingInteractivePrompt){this.queuedInteractivePrompts.unshift(e);return}let s=te(t).split(`
|
|
48
|
+
`).slice(-25).join(`
|
|
49
|
+
`),r=/Press a number to choose/i.test(s),n=this.isQueuedQuestionCollapsed(s),o=n||this.isExpandedQuestionMatchingPrompt(s,e.prompt),l=/›\s*(?:Ask Codex to do anything|$)/m.test(s),p=this.hasQueuedInputsFragment(s);if(!(r||n||p)){if(!o&&l&&s.trim().length>=10&&!s.includes("Disconnected")){a.info("Queued question resolved while queued behind approval; discarding",{promptId:e.prompt.promptId}),await this.clearResolvedInteractivePrompt(e.prompt.callId??e.prompt.promptId,e.prompt.dedupeKey??e.prompt.promptId),await this.emitNextQueuedInteractivePrompt();return}}}catch(t){a.debug("Failed to inspect pane before emitting queued question",{err:t})}if(this.isExpectedSessionStateCurrent(e.ownerState)){if(this.pendingInteractivePrompt){this.queuedInteractivePrompts.unshift(e);return}this.pendingInteractivePrompt=e.prompt;try{await this.emitInteractivePromptEvent(e),a.info("Emitted next queued interactive prompt",{callId:e.prompt.callId,queueLength:this.queuedInteractivePrompts.length})}catch(t){this.pendingInteractivePrompt===e.prompt&&this.isExpectedSessionStateCurrent(e.ownerState)?(this.pendingInteractivePrompt=null,a.error("Failed to emit queued interactive prompt",{error:t}),await this.emitNextQueuedInteractivePrompt()):a.warn("Failed to emit queued interactive prompt, but slot was preempted or session changed; preserving current state",{error:t,currentPromptId:this.pendingInteractivePrompt?.promptId})}}}}async clearObservedInteractivePrompt(e,t){if(!this.isExpectedSessionStateCurrent(e))return;let i=this.pendingInteractivePrompt;if(!i||i.ownerSessionId!==e.sessionId||i.observerPromptHash!==t){a.debug("Ignoring prompt-cleared for a non-current chooser occurrence",{sessionId:e.sessionId,clearedPromptHash:t,activePromptId:i?.promptId,activePromptHash:i?.observerPromptHash});return}this.pendingInteractivePrompt=null,i.callId&&this.approvalDetector.onToolCallComplete(i.callId),this.rememberResolvedApprovalDedupeKey(e.sessionId,i.dedupeKey);for(let r of this.queuedPermissionRequestRegistrations.get(e.sessionId)??[])r.occurrenceKey===i.dedupeKey&&(r.disposition="resolved",this.deferredTmuxPromptCandidates.delete(r),this.removePermissionRequestOccurrence(r.dedupeKey,r.occurrenceKey));let s=this.beginE1PromptResolutions(new Set([i.promptId]),e.sessionId);this.launchE1Resolutions(s),await this.emitNextQueuedInteractivePrompt()}async clearResolvedInteractivePrompt(e,t){if(!t){a.debug("Interactive prompt completion had no comparable dialog identity",{callId:e});return}let i=this.isPermissionRequestOccurrenceKey(t),s=this.pendingInteractivePrompt,r=!!s&&(s.dedupeKey===t||s.completionKey===t||s.kind!=="queued_question"&&!i&&!!e&&s.callId===e),n=this.sessionState?.sessionId??s?.ownerSessionId,o=this.queuedInteractivePrompts.find(v=>v.prompt.kind!=="queued_question"&&!i&&!!e&&v.prompt.callId===e||v.prompt.dedupeKey===t||v.prompt.completionKey===t),l=this.permissionRequestHookInFlight,p=l?.ownerState.sessionId===n&&(l?.dedupeKey===t||l?.occurrenceKey===t),u=(n?this.queuedPermissionRequestRegistrations.get(n)??[]:[]).find(v=>v.dedupeKey===t||v.occurrenceKey===t),h=[...this.waitingPermissionRequests.values()].find(v=>v.ownerState.sessionId===n&&(v.occurrenceKey===t||v.dedupeKey===t)),g=r?s?.dedupeKey:o?.prompt.dedupeKey??(p?l?.occurrenceKey:void 0)??u?.occurrenceKey??h?.occurrenceKey??t,f=new Set;if(r&&s&&f.add(s.promptId),o&&f.add(o.prompt.promptId),n&&g){let v=this.e1ContentKeyIndex.get(`${n}::${g}`);v&&f.add(v)}let y=[...this.e1PromptRaises.entries()].find(([,v])=>v.record.sessionId===n&&(v.resolutionDedupeKey===g||!i&&!!e&&v.resolutionCallId===e||v.resolutionCompletionKey===t));if(y&&f.add(y[0]),(r||p||u||h||f.size>0)&&this.rememberResolvedApprovalDedupeKey(n,g),r&&s&&(this.pendingInteractivePrompt=null),e&&this.queuedQuestionCallIds.has(e)&&this.queuedQuestionCallIds.delete(e),u&&(u.disposition="resolved"),g)for(let v of this.removeQueuedInteractivePromptByDedupeKey(g))f.add(v);let S=n?this.beginE1PromptResolutions(f,n):[];this.launchE1Resolutions(S),(r||!this.pendingInteractivePrompt&&o)&&await this.emitNextQueuedInteractivePrompt()}clearInteractivePromptsForAcceptedInput(e){let t=e.sessionId,i=new Set,s=this.pendingInteractivePrompt;s?.ownerSessionId===t&&s.kind!=="queued_question"&&(i.add(s.promptId),this.rememberResolvedApprovalDedupeKey(t,s.dedupeKey),this.pendingInteractivePrompt=null);let r=[];for(let l of this.queuedInteractivePrompts)l.prompt.ownerSessionId===t&&l.prompt.kind!=="queued_question"?(i.add(l.prompt.promptId),this.rememberResolvedApprovalDedupeKey(t,l.prompt.dedupeKey)):r.push(l);this.queuedInteractivePrompts=r;let n=new Set;s?.ownerSessionId===t&&s.kind==="queued_question"&&(n.add(s.promptId),s.callId&&n.add(s.callId),s.dedupeKey&&n.add(s.dedupeKey));for(let l of this.queuedInteractivePrompts)l.prompt.ownerSessionId===t&&l.prompt.kind==="queued_question"&&(n.add(l.prompt.promptId),l.prompt.callId&&n.add(l.prompt.callId),l.prompt.dedupeKey&&n.add(l.prompt.dedupeKey));for(let[l,p]of this.e1PromptRaises.entries())p.record.sessionId===t&&(n.has(l)||p.resolutionCallId&&n.has(p.resolutionCallId)||p.resolutionDedupeKey&&n.has(p.resolutionDedupeKey)||p.resolutionCompletionKey&&n.has(p.resolutionCompletionKey)||i.add(l));for(let l of this.queuedPermissionRequestRegistrations.get(t)??[])l.disposition="resolved",this.rememberResolvedApprovalDedupeKey(t,l.occurrenceKey),this.deferredTmuxPromptCandidates.delete(l);for(let[l,p]of this.waitingPermissionRequests)p.ownerState.sessionId===t&&(this.rememberResolvedApprovalDedupeKey(t,l),this.waitingPermissionRequests.delete(l));this.permissionRequestOccurrencesByCompletionKey.clear();let o=this.beginE1PromptResolutions(i,t);this.launchE1Resolutions(o)}removeQueuedInteractivePromptByDedupeKey(e){let t=this.queuedInteractivePrompts.length,i=this.queuedInteractivePrompts.filter(s=>s.prompt.dedupeKey===e);for(let s of i)this.rememberResolvedApprovalDedupeKey(s.ownerState.sessionId,s.prompt.dedupeKey);return this.queuedInteractivePrompts=this.queuedInteractivePrompts.filter(s=>s.prompt.dedupeKey!==e),this.queuedInteractivePrompts.length!==t&&a.debug("Removed resolved deduped tool call from interactive prompt queue",{dedupeKey:e,removed:t-this.queuedInteractivePrompts.length}),i.map(s=>s.prompt.promptId)}mergeCallIdIntoPromptByDedupeKey(e,t,i){let s=this.pendingInteractivePrompt;if(s?.ownerSessionId===e&&(s.completionKey??s.dedupeKey)===t&&!s.callId){s.callId=i;let n=this.e1PromptRaises.get(s.promptId);n&&(n.resolutionCallId??=i),a.debug("Merged callId into active deduped interactive prompt",{source:s.source,callId:i,dedupeKey:t});return}let r=this.queuedInteractivePrompts.find(n=>n.prompt.ownerSessionId===e&&(n.prompt.completionKey??n.prompt.dedupeKey)===t&&!n.prompt.callId);r&&(r.prompt.callId=i,a.debug("Merged callId into queued deduped interactive prompt",{source:r.prompt.source,callId:i,dedupeKey:t}))}isSameInteractivePrompt(e,t){if(e.ownerSessionId!==t.ownerSessionId||Date.now()-e.createdAt>as)return!1;if(e.callId&&t.callId)return e.callId===t.callId;let s=e.completionKey??e.dedupeKey,r=t.completionKey??t.dedupeKey;return e.source!==t.source&&s&&s===r&&e.observerMatchKey&&e.observerMatchKey===t.observerMatchKey?!0:e.dedupeKey&&t.dedupeKey?e.dedupeKey===t.dedupeKey:e.kind===t.kind&&this.normalizePromptDedupeText(e.promptText)===this.normalizePromptDedupeText(t.promptText)}normalizePromptDedupeText(e){return e.replace(/\s+/g," ").trim().toLowerCase()}async startTmuxObserver(){let e=process.env.CODEVIBE_CODEX_TMUX_SESSION;if(!e)return a.debug("Skipping tmux pane observer start - no tmux session in environment"),!0;try{return await this.tmuxPaneObserver.start(e),!0}catch(t){return a.warn("Failed to start tmux pane observer",{tmuxSession:e,error:t}),!1}}async startTmuxObserverWithBeacon(e){try{await this.startTmuxObserver()?await k("daemon_init_step_completed",{step:"tmux_observer_start",path:e}):await k("daemon_init_step_failed",{step:"tmux_observer_start",path:e,error_class:"TmuxObserverStartFailed",error_message:"tmuxPaneObserver.start threw (see plugin log)"})}catch(t){await k("daemon_init_step_failed",{step:"tmux_observer_start",path:e,error_class:t?.name||"Error",error_message:t?.message||String(t)}),a.error("Failed to start tmux observer:",t)}}async tryParseInteractivePromptFromTmux(){try{let e=await this.tmuxPaneObserver.captureSnapshot(),t=this.tmuxPaneObserver.extractActiveApprovalBlock(e),i=t?(0,j.parseInteractivePrompt)(t):null;return a.debug("tmux prompt parse result",{parsed:!!i,kind:i?.kind,promptText:i?.promptText,isolated:!!t,snapshotPreview:this.summarizePromptSnapshot(t??e)}),{parsedPrompt:i,snapshot:t??e}}catch(e){return a.debug("tmux prompt parsing unavailable",{error:e}),null}}async tryParsePermissionRequestPromptFromTmux(e,t){let r=null;for(let n=0;n<25;n+=1){if(t&&!t()||n>0&&(await new Promise(l=>setTimeout(l,125)),t&&!t()))return null;let o=await this.tryParseInteractivePromptFromTmux();if(o&&(r=o),o?.parsedPrompt&&(!e||e(o.parsedPrompt,o.snapshot)))return o}return r?.snapshot?{parsedPrompt:null,snapshot:r.snapshot,...r.parsedPrompt?{differentPrompt:!0}:{}}:null}buildPromptPresentation(e){return e?{content:e.promptText,promptText:e.promptText,kind:e.kind,options:e.options,submitMap:e.submitMap,instructions:this.buildPromptInstructions(e),requiresFollowUpText:e.requiresFollowUpText}:{content:"Codex is waiting for approval.",promptText:"Codex is waiting for approval.",kind:"yes_no",options:[{number:"1",text:'Yes (sends "y")'},{number:"2",text:'No, tell Codex what to change (sends "n <instructions>")'}],submitMap:{1:"y",2:"n"},instructions:"Reply with 1 to approve, or 2 followed by what to change",requiresFollowUpText:!0}}buildCodexPromptPresentation(e,t,i){let s=this.buildPromptPresentation(e),r=Zt(s.options,t,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(e){let t={};for(let i of e){let s=i.text.match(/\(([^)]+)\)\s*$/)?.[1]?.trim().toLowerCase();if(!s||!ds.test(s))return null;s==="esc"||s==="escape"?t[i.number]=oe:t[i.number]=s}return t}buildCodexPermissionInstructions(e){let t=e.find(n=>/\((?:y|yes)\)\s*$/i.test(n.text)),i=e.find(n=>/\(p\)\s*$/i.test(n.text)),s=e.find(n=>/\((?:esc|escape)\)\s*$/i.test(n.text)),r=[];return t&&r.push(`${t.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(e){return e.some(t=>/what to (?:do differently|change)|instructions/i.test(t.text))}getMostRecentPendingToolCall(){let e=this.approvalDetector.getPendingCalls();return e.length===0?null:e.reduce((t,i)=>i.timestamp>t.timestamp?i:t)}hasActiveOrQueuedPermissionHookPrompt(e,t){let i=this.pendingInteractivePrompt;return i?.ownerSessionId===e&&i.source==="permission_hook"&&(i.completionKey??i.dedupeKey)===t?!0:this.queuedInteractivePrompts.some(s=>s.prompt.ownerSessionId===e&&s.prompt.source==="permission_hook"&&(s.prompt.completionKey??s.prompt.dedupeKey)===t)||[...this.waitingPermissionRequests.values()].some(s=>s.ownerState.sessionId===e&&s.dedupeKey===t)}hasDurablePermissionHookFallback(e){return[...this.e1PromptRaises.values()].some(t=>t.record.sessionId===e&&t.suppressTmuxObserverUntilResolved===!0)}hasDurablePermissionHookFallbackByDedupeKey(e,t){return[...this.e1PromptRaises.values()].some(i=>i.record.sessionId===e&&i.suppressTmuxObserverUntilResolved===!0&&(i.resolutionDedupeKey===t||i.resolutionCompletionKey===t))}hasMatchingDurablePermissionHookFallback(e,t,i){let s=this.buildApprovalPromptContextFromParsedPrompt(e),r=s?this.buildApprovalDedupeKey(s):void 0;if(r&&this.hasDurablePermissionHookFallbackByDedupeKey(t,r))return!0;if(!i)return!1;let n=this.buildObserverSnapshotMatchKey(i);return[...this.e1PromptRaises.values()].some(o=>o.record.sessionId===t&&o.suppressTmuxObserverUntilResolved===!0&&o.suppressedObserverSnapshotKey===n)}deferTmuxPromptCandidateForPermissionHook(e,t,i){let s=this.queuedPermissionRequestSessionCounts.get(e)??0,r=this.hasDurablePermissionHookFallback(e);if(s<=0&&!r)return!1;let n=(0,j.parseInteractivePrompt)(t);if(n&&this.hasMatchingDurablePermissionHookFallback(n,e,t))return a.debug("Skipping tmux repaint already owned by a durable PermissionRequest fallback",{sessionId:e,promptText:n.promptText}),!0;if(n&&this.hasMatchingPermissionHookPrompt(n,e))return a.debug("Skipping tmux repaint already owned by an actionable PermissionRequest",{sessionId:e,promptText:n.promptText}),!0;if(n&&s<=0)return!1;if(s>0){let o=this.queuedPermissionRequestRegistrations.get(e)??[],l=n?o.find(u=>this.parsedPromptMatchesApprovalContext(n,u.context,t)):void 0,p=!n&&this.permissionRequestHookInFlight?.ownerState.sessionId===e?this.permissionRequestHookInFlight.registration:void 0,c=l??p??(o.length===1&&(!n||!r)?o[0]:void 0);if(c&&this.deferredTmuxPromptCandidates.set(c,{snapshot:t,promptHash:i}),n&&!c)return!1}return a.debug("Skipping tmux prompt candidate while PermissionRequest owns the session prompt",{sessionId:e,toolName:this.permissionRequestHookInFlight?.context.toolName,ownership:s>0?"queued_or_in_flight":"durable_prompt"}),!0}hasMatchingPermissionHookPrompt(e,t){let i=this.buildObserverPromptMatchKey(e);return[this.pendingInteractivePrompt,...this.queuedInteractivePrompts.map(r=>r.prompt)].some(r=>r?.source==="permission_hook"&&r.ownerSessionId===t&&r.observerMatchKey===i)}buildObserverPromptMatchKey(e){let t=e.options.map(s=>`${s.number}:${this.normalizeObserverPromptText(s.text)}`).join("|"),i=[e.kind,this.normalizeObserverPromptText(e.promptText),t].join("::");return`observer:${fe.createHash("sha256").update(i).digest("hex").slice(0,16)}`}buildObserverSnapshotMatchKey(e){let t=this.normalizeObserverPromptText(e);return`snapshot:${fe.createHash("sha256").update(t).digest("hex").slice(0,16)}`}normalizeObserverPromptText(e){return e.replace(/\r\n?/g,`
|
|
50
|
+
`).split(`
|
|
51
|
+
`).map(t=>t.replace(/[ \t]+$/g,"")).join(`
|
|
52
|
+
`).trim()}hasRecentlyResolvedApprovalDedupeKey(e,t){return e?(this.pruneResolvedApprovalDedupeKeys(),this.resolvedApprovalDedupeKeys.has(`${e}::${t}`)):!1}rememberResolvedApprovalDedupeKey(e,t){!e||!t||(this.pruneResolvedApprovalDedupeKeys(),this.waitingPermissionRequests.get(t)?.ownerState.sessionId===e&&this.waitingPermissionRequests.delete(t),this.resolvedApprovalDedupeKeys.set(`${e}::${t}`,Date.now()))}pruneResolvedApprovalDedupeKeys(){let e=Date.now()-Xe;for(let[t,i]of this.resolvedApprovalDedupeKeys.entries())i<e&&this.resolvedApprovalDedupeKeys.delete(t)}buildApprovalDedupeKey(e){let t=e.toolName||"Tool",i=this.firstString(e.toolInput?.command,e.toolInput?.cmd,e.rawInput);if(i)return`command:${this.hashDedupeValue(`${this.mapToolNameForApproval(t)||t}:${i}`)}`;let s=this.firstString(e.filePath,e.toolInput?.file_path,e.toolInput?.path,e.toolInput?.filePath);if(s)return`file:${this.hashDedupeValue(`${t}:${s}`)}`;let r=this.firstString(e.hint);if(r)return`hint:${this.hashDedupeValue(`${t}:${r}`)}`}hashDedupeValue(e){return fe.createHash("sha256").update(e).digest("hex").slice(0,16)}buildPermissionRequestHint(e,t,i){let s=this.extractFilePathFromToolInput(e,t,i);if(this.mapToolNameForApproval(e)==="Edit"&&s)return`File: ${s}`;let r=this.firstString(t?.command,t?.cmd);return r?`Command: ${this.truncateApprovalDetail(r,80)}`:s?`File: ${s}`:`Tool: ${this.mapToolNameForApproval(e)||e}`}extractFilePathFromToolInput(e,t,i){let s=this.firstString(t?.file_path,t?.path,t?.filePath);if(s)return s;if(e==="apply_patch"){let n=this.firstString(t?.command,t?.cmd,i)?.match(/\*\*\* (?:Update|Add|Delete) File: ([^\r\n]+)/);if(n)return n[1].trim()}}stringifyToolInput(e){if(e!=null){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}}buildApprovalPromptContextFromPendingCall(e){let t=this.firstString(e.parsedInput?.command,e.parsedInput?.cmd),i=ce(e.input),s=re(t)||ce(t),n=(e.name==="apply_patch"?re(e.input):"")||i||s,o=!!n,l=o?"apply_patch":e.name,p=o?n:e.input,c=o?e.parsedInput||{command:n}:e.parsedInput,u=o?this.extractFilePathFromToolInput("apply_patch",void 0,n):e.filePath;return{toolName:l,framedPatch:o,filePath:u,diff:o?p:e.diff,toolInput:c,rawInput:p,hint:u?`File: ${u}`:`Tool: ${this.mapToolNameForApproval(l)||l}`}}buildApprovalPromptContextFromParsedPrompt(e){let t=this.extractShellCommandFromPromptText(e.promptText);if(t)return{toolName:"Bash",toolInput:{command:t},rawInput:t,hint:`Command: ${this.truncateApprovalDetail(t,80)}`};let i=e.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(e,t,i){let s=this.buildApprovalPromptContextFromParsedPrompt(e),r=this.mapToolNameForApproval(t.toolName)==="Bash"?this.firstString(t.toolInput?.command,t.toolInput?.cmd):void 0;if(r){if(cs(e.promptText,r,i))return!0;if(this.mapToolNameForApproval(s?.toolName)!=="Bash")return!1;let o=it(e.promptText);return o?Jt(o,r):!1}if(t.framedPatch!==!0)return!1;let n=t.filePath;return n?s?.toolName!=="apply_patch"||!s.filePath?!1:L.normalize(s.filePath)===L.normalize(n):!1}extractShellCommandFromPromptText(e){return Xt(e)}buildPromptInstructions(e){return e.kind==="yes_no"&&e.requiresFollowUpText?"Reply with 1 to approve, or 2 followed by what to change":e.kind==="yes_no"?"Reply with 1 for yes or 2 for no":e.kind==="numbered"?"Reply with the number of the option you want":"Reply with your response"}buildApprovalPromptContent(e,t){let i=e.trim(),s=i==="Codex is waiting for approval.",r=/^\$\s+/.test(i),n=t.toolName?`${t.toolName} requires approval.`:"Codex is waiting for approval.",o=[s||r||!i?n:i],l=typeof t.toolInput?.command=="string"?t.toolInput.command.trim():void 0;if(l&&!o.join(`
|
|
53
|
+
`).includes(l))return o.push("Command:",this.truncateApprovalDetail(l,240)),o.join(`
|
|
54
|
+
`);let p=t.filePath||t.toolInput?.file_path;return typeof p=="string"&&p.length>0&&!o.join(`
|
|
55
|
+
`).includes(p)?(o.push(`File: ${p}`),o.join(`
|
|
56
|
+
`)):(t.hint&&!o.join(`
|
|
57
|
+
`).includes(t.hint)&&o.push(t.hint),o.join(`
|
|
58
|
+
`))}truncateApprovalDetail(e,t){return e.length>t?`${e.slice(0,t-3)}...`:e}summarizePromptSnapshot(e){return e.split(`
|
|
59
|
+
`).map(t=>t.trimEnd()).filter(t=>t.length>0).slice(-12).map(t=>t.slice(0,160)).join(`
|
|
60
|
+
`)}translatePromptResponse(e,t,i=this.pendingInteractivePrompt){if(!i||t.kind!=="option")return{primaryInput:e};let s=i.submitMap[t.option];return s?t.followUpText?{primaryInput:s,followUpInput:t.followUpText}:{primaryInput:s}:{primaryInput:e}}getEventPromptId(e){let t=e.promptId??e.metadata?.promptId;return typeof t=="string"&&t.trim().length>0?t.trim():null}async emitRejectedPromptResponseNotification(e,t,i){if(!this.isExpectedSessionStateCurrent(i))return;let s=i.sessionId,r=e==="no_safe_reject_option"?"Your message was not sent because the active desktop prompt has no verified reject option. Please resolve it on the desktop and send your message again.":e==="live_prompt_unverified"?"Your response was not sent because the desktop prompt changed or could not be verified. Please reply to the prompt currently shown on your device.":e==="follow_up_delivery_failed"?"Your option was accepted, but the accompanying text could not be sent. Please send the text again.":e==="stale_preempted_queued_question"?"\u26A0\uFE0F Queued question paused \u2014 please answer the approval request first.":e==="invalid_queued_question_input"?"Your response was not recognized for this question. Please reply with the number of your choice.":this.pendingInteractivePrompt?"Response ignored because it was not tied to the current prompt. Please reply to the latest prompt again.":"Response ignored because no prompt is currently active on the desktop.",n={prompt_response_rejected:!0,reason:e,eventId:t.eventId,eventPromptId:this.getEventPromptId(t),activePromptId:this.pendingInteractivePrompt?.promptId};try{let o=(0,m.prepareEventTimestamp)({orderingKey:s}),l=await this.appSyncClient.publishCompanionNotice({sessionId:s,type:m.EventType.NOTIFICATION,source:m.EventSource.DESKTOP,content:r,metadata:n,timestamp:o},async()=>{if(!this.isExpectedSessionStateCurrent(i))return!1;let p=this.encryptForEmit(r,n,m.EventType.NOTIFICATION,s);return p?(await this.appSyncClient.createEvent({sessionId:s,type:m.EventType.NOTIFICATION,source:m.EventSource.DESKTOP,content:p.content,metadata:p.metadata,timestamp:o,...p.isEncrypted?{isEncrypted:!0}:{}}),!0):!1});a.debug("Rejected prompt response notification publication outcome",{reason:e,result:l})}catch(o){a.warn("Failed to emit rejected prompt response notification",{reason:e,error:o})}}buildToolDetailsForInteractivePrompt(e,t){let i=e.toolName,s=e.toolInput&&typeof e.toolInput=="object"?e.toolInput:void 0;if(i==="apply_patch"){let n=e.diff||e.rawInput;if(n){let{oldString:o,newString:l,oldStartLine:p,newStartLine:c}=this.extractOldNewFromPatch(n),u=t?this.extractDiffLineAnchorsFromSnapshot(t):{};return{tool_name:"Edit",tool_input:{file_path:e.filePath,content:n,diff:e.diff,raw_patch:e.rawInput,old_string:o,new_string:l,old_start_line:p??u.oldStartLine,new_start_line:c??u.newStartLine}}}}if(this.mapToolNameForApproval(i)==="Bash"){let n=this.firstString(s?.command,s?.cmd,e.rawInput,e.hint);if(n)return{tool_name:"Bash",tool_input:{command:n,output:s?.output}}}let r={};return e.filePath&&(r.file_path=e.filePath),e.diff&&(r.diff=e.diff),e.rawInput&&(r.raw_input=e.rawInput),Object.keys(r).length>0?{tool_name:i||"Tool",tool_input:r}:{}}firstString(...e){for(let t of e)if(typeof t=="string"&&t.trim().length>0)return t}buildFallbackToolInput(e){let t={};return e.filePath&&(t.file_path=e.filePath),e.diff&&(t.diff=e.diff),e.rawInput&&(t.raw_input=e.rawInput),e.toolInput&&typeof e.toolInput=="object"&&(t.parsed_input=e.toolInput),Object.keys(t).length>0?t:void 0}mapToolNameForApproval(e){return e?{exec_command:"Bash",exec:"Bash",local_shell:"Bash",Bash:"Bash",apply_patch:"Edit",shell_command:"Bash",shell:"Bash",Edit:"Edit",Write:"Write"}[e]||e:void 0}extractOldNewFromPatch(e){let t=[],i=[],s=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/,r=0,n=0,o=0,l,p;for(let c of e.split(`
|
|
61
|
+
`)){let u=c.match(s);if(u){r+=1,n=Number.parseInt(u[1],10),o=Number.parseInt(u[2],10);continue}if(!(c.startsWith("***")||c.startsWith("---")||c.startsWith("+++")||c.startsWith("*** End Patch"))){if(c.startsWith("-"))l===void 0&&(l=n),t.push(c.slice(1)),n+=1;else if(c.startsWith("+"))p===void 0&&(p=o),i.push(c.slice(1)),o+=1;else if(c.startsWith(" ")){let h=c.slice(1);t.push(h),i.push(h),n+=1,o+=1}}}return{oldString:t.join(`
|
|
41
62
|
`),newString:i.join(`
|
|
42
|
-
`),oldStartLine:r===1?
|
|
43
|
-
`)){let n=r.match(/^\s*(\d+)\s+(.*)$/);if(!n)continue;let o=Number.parseInt(n[1],10),c=n[2];if(Number.isFinite(o)){if(c.startsWith("-")){i??=o;continue}if(c.startsWith("+")){s??=o;continue}i??=o,s??=o}}return l.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 l.warn("Refusing mobile subscription without matching session generation",{sessionId:t,currentSessionId:e?.sessionId}),!1;if(this.subscribedSessionId===t&&this.subscribedSessionState===e)return l.info("Already subscribed to mobile events, skipping",{sessionId:t}),!0;if(l.info("Subscribing to mobile events",{sessionId:t}),this.unsubscribe){try{this.unsubscribe()}catch(i){l.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=>{l.error("Subscription error:",i)},{onSessionRetired:()=>this.recoverRetiredBackendSession(t)}),this.subscribedSessionId=t,this.subscribedSessionState=e}catch(i){return l.error("Failed to subscribe to mobile events (non-fatal)",{sessionId:t,error:i}),!1}return this.isExpectedSessionStateCurrent(e)&&(e.subscriptionActive=!0),l.info("Subscribed to mobile events"),!0}async ensureOrchestrationClient(t){let{OrchestrationClient:e}=await import("@quantiya/quorum-core"),i=await h.keychainManager.getTokens((0,h.getEnvironment)());if(!i?.idToken)throw new Error("No Cognito ID token available \u2014 plugin must be logged in");let s=(0,h.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 h.keychainManager.getTokens((0,h.getEnvironment)()))?.idToken??i.idToken,sessionId:t,sessionKeyB64:r,webSocketFactory:((c,d)=>new n(c,d))})}async subscribeToOnApplyUserDecision(t){if(this.userDecisionUnsubscribe){try{this.userDecisionUnsubscribe()}catch(e){l.warn("Error invoking previous onApplyUserDecision unsubscribe (non-fatal)",{error:e})}this.userDecisionUnsubscribe=null}if(this.orchestrationClient){try{await this.orchestrationClient.destroy()}catch(e){l.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,l.info("[v1-bridge] Subscribed to onApplyUserDecision via OrchestrationClient",{sessionId:t}),!0}catch(e){if(l.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"){l.debug("[v1-bridge] Self-origin decision echo absorbed",{gateId:e,decision:i,sessionId:s,taskId:r});return}l.info("[v1-bridge] cross-device decision recorded",{gateId:e,decision:i,sessionId:s,taskId:r});let o=String(i).toUpperCase();this.emitOrchestrationBanner(o)}async emitOrchestrationBanner(t){let e=process.env[j];if(!e){l.warn("[v1-bridge] No tmux session set; cannot emit cross-device banner",{expectedEnv:j});return}let s=Nt(t).replace(/"/g,'\\"'),r=`tmux display-message -d 8000 -t "${e}" "${s}"`;try{await zt(r),l.info("[v1-bridge] Cross-device decision banner emitted",{decision:t})}catch(n){l.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),l.info("[v1-bridge] originated user decision",{gateId:t.gateId,decision:t.decision,sessionId:e})}catch(r){throw this.v1Bridge.clearOriginated(t.gateId),l.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;l.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),o=await fetch(n);if(!o.ok)throw new Error(`Failed to download attachment: ${o.status} ${o.statusText}`);let c=Buffer.from(await o.arrayBuffer());if(r&&i)try{l.info("Decrypting attachment",{id:t.id}),c=h.cryptoService.decryptData(c,i),l.info("Attachment decrypted successfully",{id:t.id,decryptedSize:c.length})}catch(v){throw l.error("Failed to decrypt attachment:",{id:t.id,error:v}),new Error("Failed to decrypt attachment")}else if(r&&!i)return l.warn("Cannot decrypt attachment - no session key available",{id:t.id}),null;let d=F.join(Xe.tmpdir(),"codevibe-codex",e);Y.existsSync(d)||Y.mkdirSync(d,{recursive:!0});let p="";if(t.filename){let v=F.extname(t.filename);v&&(p=v)}p||(p={"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}${p}`,f=F.join(d,u);return Y.writeFileSync(f,c),l.info("Attachment saved to temp file",{id:t.id,filePath:f,size:c.length}),f}catch(r){return l.error("Failed to download attachment:",{id:t.id,error:r}),null}}async handleMobileEvent(t,e=this.sessionState){if(t.attachments&&t.attachments.length>0&&l.info("DEBUG: Raw attachment data from subscription",{attachments:JSON.stringify(t.attachments),eventIsEncrypted:t.isEncrypted}),l.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){if(l.warn("Dropping mobile event for stale or mismatched session generation",{eventSessionId:t.sessionId,expectedSessionId:e?.sessionId,currentSessionId:this.sessionState?.sessionId}),(0,h.requiresSyncInputDeliveryReceipt)(t))throw new h.SyncEventClientError("SYNC_SESSION_GENERATION_CHANGED");return}let i=e.sessionId,{sessionKey:s}=e.encryptionSnapshot,r=t.content||"";if(t.isEncrypted){if(!s){if(l.error("Dropping encrypted mobile event without its session-pinned key",{eventId:t.eventId,sessionId:i}),(0,h.requiresSyncInputDeliveryReceipt)(t))throw new h.SyncEventClientError("SYNC_SESSION_KEY_UNAVAILABLE");return}try{r=h.cryptoService.decryptContent(t.content,s),l.debug("Event decrypted successfully",{eventId:t.eventId})}catch(o){if(l.error("Failed to decrypt event:",{eventId:t.eventId,error:o}),(0,h.requiresSyncInputDeliveryReceipt)(t))throw o;return}}let n=this.pendingInteractivePrompt;try{if(!await(0,h.acknowledgeMobileInputDelivery)(this.appSyncClient.updateEventStatus.bind(this.appSyncClient),t))return}catch(o){if(l.error("Failed to update delivery status:",o),(0,h.requiresSyncInputDeliveryReceipt)(t))throw o}if(this.isExpectedSessionStateCurrent(e)&&(t.type===h.EventType.USER_PROMPT||t.type===h.EventType.PROMPT_RESPONSE)){let o=r,c=t.attachments||[],d=t.type===h.EventType.PROMPT_RESPONSE,p=null,u=!1,f=(0,h.classifyMobilePromptInput)(o,n?Object.keys(n.submitMap):[]);if(f.kind==="option"){let P=n;if(!P)u=!0,d=!1;else if(t.type===h.EventType.PROMPT_RESPONSE){let b=this.getEventPromptId(t),_=P.promptId;if(!b||b!==_){l.warn("Rejecting stale or unbound PROMPT_RESPONSE",{eventId:t.eventId,eventPromptId:b,activePromptId:_}),await this.emitRejectedPromptResponseNotification("prompt_id_mismatch",t,e);return}p=P}else d=!0,p=P,l.info("Treating approval-shaped USER_PROMPT as active prompt response",{eventId:t.eventId,activePromptId:P.promptId,promptPreview:o.slice(0,20)})}else d=!1,u=!0,l.info("Treating mobile input as conversation continuation",{eventId:t.eventId,activePromptId:n?.promptId,attachmentCount:c.length});let v=[];if(c.length>0){l.info("Downloading attachments for prompt",{count:c.length});for(let P of c){let b=await this.downloadAttachment(P,i,s,t.isEncrypted);if(!this.isExpectedSessionStateCurrent(e))return;b&&v.push(b)}if(v.length>0){let P=v.map(b=>`[Attached file: ${b}]`).join(`
|
|
44
|
-
`);o?o=`${
|
|
63
|
+
`),oldStartLine:r===1?l:void 0,newStartLine:r===1?p:void 0}}extractDiffLineAnchorsFromSnapshot(e){let t=(0,j.normalizeSnapshot)(e),i,s;for(let r of t.split(`
|
|
64
|
+
`)){let n=r.match(/^\s*(\d+)\s+(.*)$/);if(!n)continue;let o=Number.parseInt(n[1],10),l=n[2];if(Number.isFinite(o)){if(l.startsWith("-")){i??=o;continue}if(l.startsWith("+")){s??=o;continue}i??=o,s??=o}}return a.debug("Recovered diff line anchors from tmux snapshot",{oldStartLine:i,newStartLine:s,snapshotPreview:this.summarizePromptSnapshot(e)}),{oldStartLine:i,newStartLine:s}}subscribeToMobileEvents(e){let t=this.sessionState;if(!t||t.sessionId!==e)return a.warn("Refusing mobile subscription without matching session generation",{sessionId:e,currentSessionId:t?.sessionId}),!1;if(this.subscribedSessionId===e&&this.subscribedSessionState===t)return a.info("Already subscribed to mobile events, skipping",{sessionId:e}),!0;if(a.info("Subscribing to mobile events",{sessionId:e}),this.unsubscribe){try{this.unsubscribe()}catch(i){a.warn("Error cleaning up previous subscription (non-fatal)",{error:i})}this.subscribedSessionId=null,this.subscribedSessionState=null}try{this.unsubscribe=this.appSyncClient.subscribeToEvents(e,async i=>{await this.handleMobileEvent(i,t)},i=>{a.error("Subscription error:",i)},{onSessionRetired:()=>this.recoverRetiredBackendSession(e)}),this.subscribedSessionId=e,this.subscribedSessionState=t}catch(i){return a.error("Failed to subscribe to mobile events (non-fatal)",{sessionId:e,error:i}),!1}return this.isExpectedSessionStateCurrent(t)&&(t.subscriptionActive=!0),a.info("Subscribed to mobile events"),!0}async ensureOrchestrationClient(e){let{OrchestrationClient:t}=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 t.connect({appsyncUrl:s.aws.appsyncUrl,cognitoIdToken:i.idToken,tokenProvider:async()=>(await m.keychainManager.getTokens((0,m.getEnvironment)()))?.idToken??i.idToken,sessionId:e,sessionKeyB64:r,webSocketFactory:((l,p)=>new n(l,p))})}async subscribeToOnApplyUserDecision(e){if(this.userDecisionUnsubscribe){try{this.userDecisionUnsubscribe()}catch(t){a.warn("Error invoking previous onApplyUserDecision unsubscribe (non-fatal)",{error:t})}this.userDecisionUnsubscribe=null}if(this.orchestrationClient){try{await this.orchestrationClient.destroy()}catch(t){a.warn("Error destroying previous OrchestrationClient (non-fatal)",{error:t})}this.orchestrationClient=null}try{let t=await this.ensureOrchestrationClient(e);this.orchestrationClient=t;let i=await t.onApplyUserDecision(s=>{this.handleApplyUserDecisionEvent(s)});return this.userDecisionUnsubscribe=i,a.info("[v1-bridge] Subscribed to onApplyUserDecision via OrchestrationClient",{sessionId:e}),!0}catch(t){if(a.error("Failed to subscribe to onApplyUserDecision (non-fatal)",{sessionId:e,error:t}),this.orchestrationClient){try{await this.orchestrationClient.destroy()}catch{}this.orchestrationClient=null}return!1}}handleApplyUserDecisionEvent(e){let{gateId:t,decision:i,sessionId:s,taskId:r}=e;if(this.v1Bridge.dispatch(e)==="self_echo"){a.debug("[v1-bridge] Self-origin decision echo absorbed",{gateId:t,decision:i,sessionId:s,taskId:r});return}a.info("[v1-bridge] cross-device decision recorded",{gateId:t,decision:i,sessionId:s,taskId:r});let o=String(i).toUpperCase();this.emitOrchestrationBanner(o)}async emitOrchestrationBanner(e){let t=process.env[Y];if(!t){a.warn("[v1-bridge] No tmux session set; cannot emit cross-device banner",{expectedEnv:Y});return}let s=Nt(e).replace(/"/g,'\\"'),r=`tmux display-message -d 8000 -t "${t}" "${s}"`;try{await Gt(r),a.info("[v1-bridge] Cross-device decision banner emitted",{decision:e})}catch(n){a.warn("[v1-bridge] tmux display-message failed (non-fatal)",{error:n instanceof Error?n.message:String(n)})}}async originateUserDecision(e){this.v1Bridge.markOriginated(e.gateId);let t=this.sessionState?.sessionId;if(!t)throw this.v1Bridge.clearOriginated(e.gateId),new Error("No active session \u2014 cannot originate user decision");let i=this.orchestrationClient,s=!1;i||(i=await this.ensureOrchestrationClient(t),s=!0);try{await i.applyUserDecision(e),a.info("[v1-bridge] originated user decision",{gateId:e.gateId,decision:e.decision,sessionId:t})}catch(r){throw this.v1Bridge.clearOriginated(e.gateId),a.error("[v1-bridge] applyUserDecision failed (rolled back originator marker)",{gateId:e.gateId,decision:e.decision,error:r instanceof Error?r.message:String(r)}),r}finally{if(s&&i)try{await i.destroy()}catch{}}}_v1BridgeStateForTest(){return this.v1Bridge}_v1BridgeHandleEventForTest(e){this.handleApplyUserDecisionEvent(e)}async downloadAttachment(e,t,i,s){try{let r=e.isEncrypted??s??!1;a.info("Downloading attachment",{id:e.id,type:e.type,filename:e.filename,s3Key:e.s3Key,attachmentIsEncrypted:e.isEncrypted,eventIsEncrypted:s,shouldDecrypt:r});let{downloadUrl:n}=await this.appSyncClient.getAttachmentDownloadUrl(e.s3Key),o=await fetch(n);if(!o.ok)throw new Error(`Failed to download attachment: ${o.status} ${o.statusText}`);let l=Buffer.from(await o.arrayBuffer());if(r&&i)try{a.info("Decrypting attachment",{id:e.id}),l=m.cryptoService.decryptData(l,i),a.info("Attachment decrypted successfully",{id:e.id,decryptedSize:l.length})}catch(g){throw a.error("Failed to decrypt attachment:",{id:e.id,error:g}),new Error("Failed to decrypt attachment")}else if(r&&!i)return a.warn("Cannot decrypt attachment - no session key available",{id:e.id}),null;let p=L.join(Je.tmpdir(),"codevibe-codex",t);J.existsSync(p)||J.mkdirSync(p,{recursive:!0});let c="";if(e.filename){let g=L.extname(e.filename);g&&(c=g)}c||(c={"image/jpeg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/heic":".heic","application/pdf":".pdf"}[e.type]||".bin");let u=`attachment-${e.id}${c}`,h=L.join(p,u);return J.writeFileSync(h,l),a.info("Attachment saved to temp file",{id:e.id,filePath:h,size:l.length}),h}catch(r){return a.error("Failed to download attachment:",{id:e.id,error:r}),null}}async handleMobileEvent(e,t=this.sessionState){if(e.attachments&&e.attachments.length>0&&a.info("DEBUG: Raw attachment data from subscription",{attachments:JSON.stringify(e.attachments),eventIsEncrypted:e.isEncrypted}),a.info("Received mobile event",{eventId:e.eventId,type:e.type,content:e.content?.substring(0,50),attachmentCount:e.attachments?.length||0,isEncrypted:e.isEncrypted}),!t||!this.isExpectedSessionStateCurrent(t)||e.sessionId!==t.sessionId){if(a.warn("Dropping mobile event for stale or mismatched session generation",{eventSessionId:e.sessionId,expectedSessionId:t?.sessionId,currentSessionId:this.sessionState?.sessionId}),(0,m.requiresSyncInputDeliveryReceipt)(e))throw new m.SyncEventClientError("SYNC_SESSION_GENERATION_CHANGED");return}let i=t.sessionId,{sessionKey:s}=t.encryptionSnapshot,r=e.content||"";if(e.isEncrypted){if(!s){if(a.error("Dropping encrypted mobile event without its session-pinned key",{eventId:e.eventId,sessionId:i}),(0,m.requiresSyncInputDeliveryReceipt)(e))throw new m.SyncEventClientError("SYNC_SESSION_KEY_UNAVAILABLE");return}try{r=m.cryptoService.decryptContent(e.content,s),a.debug("Event decrypted successfully",{eventId:e.eventId})}catch(o){if(a.error("Failed to decrypt event:",{eventId:e.eventId,error:o}),(0,m.requiresSyncInputDeliveryReceipt)(e))throw o;return}}let n=this.pendingInteractivePrompt;try{if(!await(0,m.acknowledgeMobileInputDelivery)(this.appSyncClient.updateEventStatus.bind(this.appSyncClient),e))return}catch(o){if(a.error("Failed to update delivery status:",o),(0,m.requiresSyncInputDeliveryReceipt)(e))throw o}if(this.isExpectedSessionStateCurrent(t)&&(e.type===m.EventType.USER_PROMPT||e.type===m.EventType.PROMPT_RESPONSE)){let o=r,l=e.attachments||[],p=e.type===m.EventType.PROMPT_RESPONSE,c=null,u=!1,h=this.getEventPromptId(e),g=n,f=(0,m.classifyMobilePromptInput)(o,g?Object.keys(g.submitMap):[]);if(g?.preemptedQueuedQuestionId&&h===g.preemptedQueuedQuestionId){a.warn("Rejecting mobile event explicitly bound to preempted queued question",{eventId:e.eventId,eventPromptId:h,activePromptId:g.promptId}),await this.emitRejectedPromptResponseNotification("stale_preempted_queued_question",e,t);return}let y=f.kind==="option"||/^\s*\d+(?:\s|$|[.,:])/.test(o.trim())||/^\s*(?:y|n|yes|no)\s*$/i.test(o.trim());if(h)if(g){if(h!==g.promptId){a.warn("Rejecting mobile event with mismatched promptId",{eventId:e.eventId,eventPromptId:h,activePromptId:g.promptId}),await this.emitRejectedPromptResponseNotification("prompt_id_mismatch",e,t);return}}else{a.warn("Rejecting prompt-bound mobile event with no active prompt",{eventId:e.eventId,eventPromptId:h}),await this.emitRejectedPromptResponseNotification("prompt_id_mismatch",e,t);return}else if(e.type===m.EventType.PROMPT_RESPONSE&&!g&&y){a.warn("Rejecting option-shaped PROMPT_RESPONSE with no active prompt",{eventId:e.eventId}),await this.emitRejectedPromptResponseNotification("prompt_id_mismatch",e,t);return}if(g?.kind==="queued_question"){let b=o.trim();if(o.includes(",")&&/^\s*\d+(?:\s*,\s*\d+)*\s*$/.test(b)){a.warn("Rejecting multi-option input for single-choice queued question",{eventId:e.eventId,prompt:o,activePromptId:g.promptId}),await this.emitRejectedPromptResponseNotification("invalid_queued_question_input",e,t);return}if(e.type===m.EventType.PROMPT_RESPONSE||h){if(!h||h!==g.promptId){a.warn("Rejecting mismatched promptId for queued question",{eventId:e.eventId,eventPromptId:h,activePromptId:g.promptId}),await this.emitRejectedPromptResponseNotification("prompt_id_mismatch",e,t);return}if(f.kind!=="option"||o.includes(",")||f.followUpText||!(b in g.submitMap)){a.warn("Rejecting invalid option for queued question",{eventId:e.eventId,prompt:o,activePromptId:g.promptId}),await this.emitRejectedPromptResponseNotification("invalid_queued_question_input",e,t);return}p=!0,c=g}else if(f.kind==="option"&&!o.includes(",")&&!f.followUpText&&b in g.submitMap)p=!0,c=g,a.info("Treating option-shaped unbound USER_PROMPT as queued question response",{eventId:e.eventId,activePromptId:g.promptId,promptPreview:o.slice(0,20)});else if(y){a.warn("Rejecting invalid option-shaped input beside queued question",{eventId:e.eventId,prompt:o,activePromptId:g.promptId}),await this.emitRejectedPromptResponseNotification("invalid_queued_question_input",e,t);return}else p=!1,u=!0,a.info("Treating mobile input as conversation continuation alongside queued question",{eventId:e.eventId,activePromptId:g.promptId,attachmentCount:l.length})}else if(f.kind==="option")if(!g)u=!0,p=!1;else if(e.type===m.EventType.PROMPT_RESPONSE){let b=g.promptId;if(!h||h!==b){a.warn("Rejecting stale or unbound PROMPT_RESPONSE",{eventId:e.eventId,eventPromptId:h,activePromptId:b}),await this.emitRejectedPromptResponseNotification("prompt_id_mismatch",e,t);return}c=g}else{if(h&&h!==g.promptId){a.warn("Rejecting USER_PROMPT with mismatched promptId during active approval",{eventId:e.eventId,eventPromptId:h,activePromptId:g.promptId}),await this.emitRejectedPromptResponseNotification("prompt_id_mismatch",e,t);return}let b=typeof e.timestamp=="number"?e.timestamp:(typeof e.timestamp=="string"?Date.parse(e.timestamp):0)||e.createdAt||0,E=g.preemptedQueuedQuestionAt||g.createdAt||0;if(g.preemptedQueuedQuestionId&&b>0&&E>0&&b<E){a.warn("Rejecting stale numeric USER_PROMPT composed before approval preempted queued question",{eventId:e.eventId,eventTime:b,preemptionThreshold:E,activePromptId:g.promptId}),await this.emitRejectedPromptResponseNotification("stale_preempted_queued_question",e,t);return}p=!0,c=g,a.info("Treating approval-shaped USER_PROMPT as active prompt response",{eventId:e.eventId,activePromptId:g.promptId,promptPreview:o.slice(0,20)})}else p=!1,u=!0,a.info("Treating mobile input as conversation continuation",{eventId:e.eventId,activePromptId:g?.promptId,attachmentCount:l.length});let I=[];if(l.length>0){a.info("Downloading attachments for prompt",{count:l.length});for(let b of l){let E=await this.downloadAttachment(b,i,s,e.isEncrypted);if(!this.isExpectedSessionStateCurrent(t))return;E&&I.push(E)}if(I.length>0){let b=I.map(E=>`[Attached file: ${E}]`).join(`
|
|
65
|
+
`);o?o=`${b}
|
|
45
66
|
|
|
46
|
-
${o}`:o=`${
|
|
67
|
+
${o}`:o=`${b}
|
|
47
68
|
|
|
48
|
-
Please analyze the attached file(s).`,l.info("Prompt updated with attachment paths",{attachmentCount:v.length,newPromptLength:o.length})}}if(d&&this.pendingInteractivePrompt!==p){l.info("Ignoring mobile prompt response already settled by a concurrent completion",{eventId:t.eventId,boundPromptId:p?.promptId,activePromptId:this.pendingInteractivePrompt?.promptId});return}let m=this.translatePromptResponse(o,f,p);if(!this.isExpectedSessionStateCurrent(e))return;p&&m.primaryInput!==te&&await this.trackDurableMobileEcho(e,t,m.primaryInput,"primary");let g=()=>this.trackDurableMobileEcho(e,t,m.primaryInput,"primary");if(!this.isExpectedSessionStateCurrent(e))return;let w=p?await this.sendVerifiedPromptInput(e,p,m.primaryInput):u?await this.sendConversationContinuation(e,m.primaryInput,g):await this.sendSessionPinnedInput(e,m.primaryInput,g)?"sent":"send_failed",E=w==="sent";if(!this.isExpectedSessionStateCurrent(e))return;E&&u&&(this.approvalDetector.clear(),this.clearInteractivePromptsForAcceptedInput(e)),(w==="stale"||w==="unverified")&&await this.emitRejectedPromptResponseNotification("live_prompt_unverified",t,e),!E&&m.primaryInput!==te&&!(0,h.requiresSyncInputDeliveryReceipt)(t)&&this.forgetMobilePrompt(i,m.primaryInput);let S=!0;if(E&&m.followUpInput){if(await new Promise(N=>setTimeout(N,200)),!this.isExpectedSessionStateCurrent(e))return;let P=m.followUpInput,b=()=>this.trackDurableMobileEcho(e,t,P,"follow_up");if(!this.isExpectedSessionStateCurrent(e)||(S=(p?await this.sendVerifiedFollowUpAfterDismissal(e,p,m.followUpInput,b):await this.sendSessionPinnedInput(e,m.followUpInput,b)?"sent":"send_failed")==="sent",!this.isExpectedSessionStateCurrent(e)))return;S||(await this.emitRejectedPromptResponseNotification("follow_up_delivery_failed",t,e),(0,h.requiresSyncInputDeliveryReceipt)(t)||this.forgetMobilePrompt(i,m.followUpInput))}if(E&&d&&p&&!p.terminalMenuIdentity&&this.pendingInteractivePrompt===p){let P=p;this.rememberResolvedApprovalDedupeKey(e.sessionId,P.dedupeKey),this.pendingInteractivePrompt=null;let b=this.beginE1PromptResolutions([P.promptId],e.sessionId);if(this.launchE1Resolutions(b),!this.isExpectedSessionStateCurrent(e)||(await this.emitNextQueuedInteractivePrompt(),!this.isExpectedSessionStateCurrent(e)))return}if(E&&S){if(!this.isExpectedSessionStateCurrent(e))return;try{await(0,h.acknowledgeMobileInputExecution)(this.appSyncClient.updateEventStatus.bind(this.appSyncClient),t)}catch(P){l.error("Failed to update executed status:",P)}}}}buildToolActivityIntegration(){return new ee({logger:l,selectTransport:async(t,e)=>{let i=this.sessionState;if(!i||i.sessionId!==t)throw new Error("SYNC_SOURCE_OWNER_CHANGED");let s=await this.selectNativeSourceTransport(i);return s.protocol==="LEGACY"?e:this.appSyncClient.toolActivitySyncTransport({sessionScope:s.sessionScope,getEncryptionContext:s.getEncryptionContext})},recoverPending:async(t,e,i)=>{await this.appSyncClient.recoverCompanionSyncSources({sessionId:t}),await this.appSyncClient.recoverToolActivityWindows({sessionId:t,outbox:e,ledger:i})},createEvent:t=>this.appSyncClient.createEvent(t),encryptContent:(t,e)=>h.cryptoService.encryptContent(t,e),encryptMetadata:(t,e)=>h.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.status===h.SessionStatus.INACTIVE){let n=new Error(`SESSION_TERMINAL: session ${t} is ${e.status}; stop retrying`);throw n.errorType="SessionTerminal",n}if(!e||e.status!==h.SessionStatus.ACTIVE||!e.isEncrypted)return null;let i=e.sessionKeyGen??null,s=e.encryptedKeys??[];if(s.length===0)return null;let r=await h.keychainManager.getSessionKey(t,s,i);return r?(l.info("[tool-activity] refreshed session key for SessionKeyStale retry (live key untouched)",{sessionId:t,sessionKeyGen:i}),{sessionKey:r,sessionKeyGen:i}):null}catch(e){if((0,h.isTerminalSessionError)(e))throw e;return l.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 h.ToolActivityLedger({agent:"codex",sessionId:t,logger:l}),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=>{l.warn("[tool-activity] failed to start codex consolidator (non-fatal)",{backendSessionId:s,rolloutId:t,error:String(r)})}),await this.toolActivityStartPromise,this.toolActivity?.isActive()&&this.sessionWatcher.retryActiveRead()}startMobileEndWatcher(t){!this.sessionState||this.sessionState.sessionId!==t||(this.sessionState.mobileEndWatcher=this.appSyncClient.watchForMobileEnd(t,async()=>{l.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:h.SessionStatus.INACTIVE}),l.info("Marked session INACTIVE on mobile-end (before tmux terminate)",{sessionId:t})}catch(i){l.warn("Failed to mark session INACTIVE on mobile-end",{sessionId:t,error:i})}let e=process.env[j];if(!e){l.warn("No tmux session set; skipping desktop self-terminate",{sessionId:t,expectedEnv:j});return}await os(e,es)}))}async endActiveSession(t,e=!0){if(!this.sessionState)return;let i=t,s=e,r=this.sessionState;if(this.terminalInputBlockedStates.add(r),await this.terminalInputChain.catch(()=>{}),this.sessionState!==r){l.warn("Session changed while waiting for terminal-input teardown barrier",{endingSessionId:r.sessionId,currentSessionId:this.sessionState?.sessionId,reason:i});return}if(l.info("Ending active session",{sessionId:r.sessionId,codexSessionId:r.codexSessionId,reason:i}),this.sessionState.mobileEndWatcher&&(this.sessionState.mobileEndWatcher.stop(),this.sessionState.mobileEndWatcher=void 0),this.userDecisionUnsubscribe){try{this.userDecisionUnsubscribe()}catch(n){l.warn("Error invoking onApplyUserDecision unsubscribe (non-fatal)",{error:n})}this.userDecisionUnsubscribe=null}if(this.orchestrationClient){try{await this.orchestrationClient.destroy()}catch(n){l.warn("Error destroying OrchestrationClient (non-fatal)",{error:n})}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();for(let n of this.deferredTmuxPromptCandidates.keys())n.sessionId===r.sessionId&&this.deferredTmuxPromptCandidates.delete(n);this.queuedPermissionRequestRegistrations.delete(r.sessionId),this.terminalRetirementRequested&&(i="shutdown",s=!0),i==="shutdown"&&this.sessionWatcher.stop(),this.toolActivityStartPromise&&(await this.toolActivityStartPromise.catch(()=>{}),this.toolActivityStartPromise=null),await this.logEntryChain.catch(()=>{}),await this.stopNativeSources(r),this.toolActivity&&(await this.toolActivity.stop(),this.toolActivity=null);for(let n of this.toolActivityLegacyRecorders.values())n.disposeLegacyCoordination();this.toolActivityLegacyRecorders.clear(),this.terminalRetirementRequested&&(i="shutdown",s=!0),i==="daemon-handoff"&&this.persistDaemonHandoffState(r),(i==="new-codex-session-started"||i==="shutdown")&&(await this.exactClearOpenE1ForLifecycleEnd(r.sessionId),await this.drainPendingE1ResolutionsForLifecycleEnd(),this.stopE1TtlRefresh()),i!=="backend-generation-retired"&&i!=="daemon-handoff"&&(this.permissionRequestOccurrencesByCompletionKey.clear(),this.waitingPermissionRequests.clear()),this.pendingInteractivePrompt=null,this.queuedInteractivePrompts=[],this.isInitializingSession=!1,this.bufferedLogEntries=[],Ue(),this.sessionKey&&(h.keychainManager.clearSessionKey(this.sessionState.sessionId),this.sessionKey=null,this.sessionKeyGen=null),this.terminalRetirementRequested&&(s=!0),s?await this.retireHostedSession(this.sessionState.sessionId,r):l.info("Preserving active backend session for daemon handoff",{sessionId:this.sessionState.sessionId}),this.sessionState=null}async boundedTeardownStep(t,e){await Ge(async()=>{try{await e()}catch(s){l.warn(`${t} failed`,{error:String(s)})}},3e3,()=>l.warn(`${t} timed out \u2014 continuing teardown without it`,{timeoutMs:3e3}))==="timeout"&&this.teardownStepsTimedOut.push(t)}isDurableObligationSettledForExit(){return!this.retirementOwed}getTeardownStepsTimedOut(){return[...this.teardownStepsTimedOut]}async retireHostedSession(t,e){ze("stall-retirement")&&(l.warn("[dev-fault] stall-retirement: this INACTIVE write will never settle",{sessionId:t}),await new Promise(()=>{}));let i;for(let s=1;s<=Ce;s+=1)try{let r=await this.appSyncClient.updateSession({sessionId:t,status:h.SessionStatus.INACTIVE});r?.sessionGenerationId&&await this.appSyncClient.completeDesktopSyncRetirement({sessionId:t,toolOutbox:new h.ToolActivityOutbox({agent:"codex",logger:l})},r,async()=>{await this.logEntryChain.catch(()=>{}),await this.stopNativeSources(e)});return}catch(r){i=r,l.warn("Failed to retire hosted Codex session",{sessionId:t,attempt:s,maxAttempts:Ce,error:r instanceof Error?r.message:String(r)}),s<Ce&&await new Promise(n=>setTimeout(n,ss*s))}throw new Error(`Failed to retire hosted Codex session ${t} after ${Ce} attempts: ${String(i)}`)}async cleanupDetachedWrapperArtifacts(){let t=process.env.CODEVIBE_CODEX_WRAPPER_PID;if(!t||!/^\d+$/.test(t))return;let e=process.env.TMPDIR||Xe.tmpdir(),i=[F.join(e,`codevibe-codex-server-${t}.pid`),F.join(e,`codevibe-codex-exit-${t}`),F.join(e,`codevibe-codex-tmux-session-${t}`)];for(let s of i)try{Y.unlinkSync(s)}catch(r){r?.code!=="ENOENT"&&l.warn("Failed to remove detached-wrapper artifact",{ownedPath:s,error:String(r)})}}stop(t={}){return t.retireBackendSession!==!1&&(this.terminalRetirementRequested=!0),this.stopPromise?this.stopPromise:(this.stopPromise=this.doStop(),this.stopPromise)}async doStop(){l.info("Stopping CodeVibe Codex companion server"),this.stopTmuxLifecycleMonitor(),this.isStopping=!0,this.nativeSourceRetryTimer&&clearTimeout(this.nativeSourceRetryTimer),this.nativeSourceRetryTimer=null,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();this.teardownStepsTimedOut=[],await this.boundedTeardownStep("inFlightChains.join",()=>Promise.all([t?.catch(()=>{}),e?.catch(()=>{}),i?.catch(()=>{}),r.catch(()=>{}),this.sessionWatcher.waitForReads().catch(()=>{}),s.catch(()=>{})]));try{let n=this.terminalRetirementRequested;this.retirementOwed=n&&this.sessionState!==null;let o,c=!1;if(await Ge(async()=>{try{await this.endActiveSession(n?"shutdown":"daemon-handoff",n),this.retirementOwed=!1}catch(p){c=!0,o=p}},1e4,()=>l.warn("endActiveSession timed out \u2014 continuing teardown without it",{timeoutMs:1e4,retirementOwed:this.retirementOwed}))==="timeout"&&this.teardownStepsTimedOut.push("endActiveSession"),c)throw o;this.sessionWatcher.stop(),this.approvalDetector.shutdown(),Ue()}finally{await this.boundedTeardownStep("httpApi.stop",()=>this.httpApi.stop()),this.appSyncClient.cleanupSubscriptions(),this.terminalRetirementRequested&&await this.boundedTeardownStep("cleanupDetachedWrapperArtifacts",()=>this.cleanupDetachedWrapperArtifacts())}if(l.info("CodeVibe Codex companion server stopped"),this.retirementOwed)throw new Error("Session teardown timed out with the INACTIVE write still owed; the backend row may be stranded ACTIVE")}};if(require.main===module){let a=new Ae;for(let t of Gt)process.on(t,()=>{l.info(`Received ${t}, evaluating terminal shutdown...`),(async()=>{let e;try{e=await a.shouldShutdownForTerminalSignal(t)}catch(s){l.error(`Failed to evaluate ${t} terminality; not shutting down`,{error:s instanceof Error?s.message:String(s)});return}if(!e)return;let i=le(s=>process.exit(s),()=>l.error("Shutdown watchdog fired \u2014 teardown did not complete in time; exiting anyway",{signal:t,watchdogMs:25e3,timedOutSteps:a.getTeardownStepsTimedOut(),durableObligationSettled:a.isDurableObligationSettledForExit()}),25e3,()=>a.isDurableObligationSettledForExit());try{await a.stop(),i(),process.exit(0)}catch(s){i(),l.error(`Failed to stop companion daemon after ${t}`,{error:s instanceof Error?s.message:String(s)}),process.exit(1)}})()});process.on("SIGUSR2",async()=>{l.info("Received SIGUSR2, handing off active session to replacement daemon...");let t=le(e=>process.exit(e),()=>l.error("Shutdown watchdog fired during SIGUSR2 handoff; exiting anyway",{watchdogMs:25e3,timedOutSteps:a.getTeardownStepsTimedOut()}),25e3,()=>a.isDurableObligationSettledForExit());try{await a.stop({retireBackendSession:!1})}catch(e){l.error("Handoff stop() failed; exiting anyway to free the session",{error:e instanceof Error?e.message:String(e)})}finally{t()}process.exit(0)}),(0,h.installDaemonProcessGuards)(l,{onFatal:()=>{let t=le(()=>process.exit(1),()=>l.error("Shutdown watchdog fired after a fatal guard; exiting anyway",{watchdogMs:25e3,timedOutSteps:a.getTeardownStepsTimedOut(),durableObligationSettled:a.isDurableObligationSettledForExit()}),25e3);a.stop().finally(()=>{t(),process.exit(1)})}}),a.start().catch(t=>{l.error("Failed to start server:",t),process.exit(1)})}0&&(module.exports={CodexCompanionServer,TERMINAL_SHUTDOWN_SIGNALS,classifyTmuxHasSessionError,extractShellCommandFromPromptText,extractShellCommandPartsFromPromptText,restoreCodexPersistOptionCommand,shellCommandPartsMatchExpected});
|
|
69
|
+
Please analyze the attached file(s).`,a.info("Prompt updated with attachment paths",{attachmentCount:I.length,newPromptLength:o.length})}}if(p&&this.pendingInteractivePrompt!==c){a.info("Ignoring mobile prompt response already settled by a concurrent completion",{eventId:e.eventId,boundPromptId:c?.promptId,activePromptId:this.pendingInteractivePrompt?.promptId});return}let S=this.translatePromptResponse(o,f,c);if(!this.isExpectedSessionStateCurrent(t))return;c&&S.primaryInput!==oe&&await this.trackDurableMobileEcho(t,e,S.primaryInput,"primary");let v=()=>this.trackDurableMobileEcho(t,e,S.primaryInput,"primary");if(!this.isExpectedSessionStateCurrent(t))return;let w=c?await this.sendVerifiedPromptInput(t,c,S.primaryInput):u?await this.sendConversationContinuation(t,S.primaryInput,v):await this.sendSessionPinnedInput(t,S.primaryInput,v)?"sent":"send_failed",R=w==="sent";if(!this.isExpectedSessionStateCurrent(t))return;R&&u&&(this.approvalDetector.clear(),this.clearInteractivePromptsForAcceptedInput(t)),(w==="stale"||w==="unverified")&&await this.emitRejectedPromptResponseNotification("live_prompt_unverified",e,t),!R&&S.primaryInput!==oe&&!(0,m.requiresSyncInputDeliveryReceipt)(e)&&this.forgetMobilePrompt(i,S.primaryInput);let T=!0;if(R&&S.followUpInput){if(await new Promise(M=>setTimeout(M,200)),!this.isExpectedSessionStateCurrent(t))return;let b=S.followUpInput,E=()=>this.trackDurableMobileEcho(t,e,b,"follow_up");if(!this.isExpectedSessionStateCurrent(t)||(T=(c?await this.sendVerifiedFollowUpAfterDismissal(t,c,S.followUpInput,E):await this.sendSessionPinnedInput(t,S.followUpInput,E)?"sent":"send_failed")==="sent",!this.isExpectedSessionStateCurrent(t)))return;T||(await this.emitRejectedPromptResponseNotification("follow_up_delivery_failed",e,t),(0,m.requiresSyncInputDeliveryReceipt)(e)||this.forgetMobilePrompt(i,S.followUpInput))}if(R&&p&&c&&!c.terminalMenuIdentity&&this.pendingInteractivePrompt===c){let b=c;this.rememberResolvedApprovalDedupeKey(t.sessionId,b.dedupeKey),this.pendingInteractivePrompt=null;let E=this.beginE1PromptResolutions([b.promptId],t.sessionId);if(this.launchE1Resolutions(E),!this.isExpectedSessionStateCurrent(t)||(await this.emitNextQueuedInteractivePrompt(),!this.isExpectedSessionStateCurrent(t)))return}if(R&&T){if(!this.isExpectedSessionStateCurrent(t))return;try{await(0,m.acknowledgeMobileInputExecution)(this.appSyncClient.updateEventStatus.bind(this.appSyncClient),e)}catch(b){a.error("Failed to update executed status:",b)}}}}buildToolActivityIntegration(){return new ne({logger:a,selectTransport:async(e,t)=>{let i=this.sessionState;if(!i||i.sessionId!==e)throw new Error("SYNC_SOURCE_OWNER_CHANGED");let s=await this.selectNativeSourceTransport(i);return s.protocol==="LEGACY"?t:this.appSyncClient.toolActivitySyncTransport({sessionScope:s.sessionScope,getEncryptionContext:s.getEncryptionContext})},recoverPending:async(e,t,i)=>{await this.appSyncClient.recoverCompanionSyncSources({sessionId:e}),await this.appSyncClient.recoverToolActivityWindows({sessionId:e,outbox:t,ledger:i})},createEvent:e=>this.appSyncClient.createEvent(e),encryptContent:(e,t)=>m.cryptoService.encryptContent(e,t),encryptMetadata:(e,t)=>m.cryptoService.encryptMetadata(e,t),getSessionKey:()=>this.sessionKey,getSessionKeyGen:()=>this.sessionKeyGen,refreshSessionKey:e=>this.refreshToolActivitySessionKey(e)})}async refreshToolActivitySessionKey(e){try{let t=await this.appSyncClient.getSession(e);if(t&&t.status===m.SessionStatus.INACTIVE){let n=new Error(`SESSION_TERMINAL: session ${e} is ${t.status}; stop retrying`);throw n.errorType="SessionTerminal",n}if(!t||t.status!==m.SessionStatus.ACTIVE||!t.isEncrypted)return null;let i=t.sessionKeyGen??null,s=t.encryptedKeys??[];if(s.length===0)return null;let r=await m.keychainManager.getSessionKey(e,s,i);return r?(a.info("[tool-activity] refreshed session key for SessionKeyStale retry (live key untouched)",{sessionId:e,sessionKeyGen:i}),{sessionKey:r,sessionKeyGen:i}):null}catch(t){if((0,m.isTerminalSessionError)(t))throw t;return a.warn("[tool-activity] session key refresh failed after SessionKeyStale (staying retryable)",{sessionId:e,error:String(t)}),null}}getToolActivityLegacyRecorder(e){let t=this.toolActivityLegacyRecorders.get(e);return t||(t=new m.ToolActivityLedger({agent:"codex",sessionId:e,logger:a}),this.toolActivityLegacyRecorders.set(e,t)),t}async ensureToolActivityStarted(e){if(!this.sessionState||!e)return;let t=this.sessionWatcher.getActiveLogFile()||this.sessionState.codexLogFile||void 0,i=this.toolActivity;if(i){t&&i.bindTranscript(t);return}if(this.toolActivityStartPromise){await this.toolActivityStartPromise,t&&this.toolActivity?.bindTranscript(t);return}if(!this.sessionKey)return;let s=this.sessionState.sessionId;this.toolActivityStartPromise=(async()=>{let r=this.buildToolActivityIntegration();try{await r.start(s,e,t),this.toolActivity=r}catch(n){throw await r.stop().catch(()=>{}),this.toolActivityStartPromise=null,n}})().catch(r=>{a.warn("[tool-activity] failed to start codex consolidator (non-fatal)",{backendSessionId:s,rolloutId:e,error:String(r)})}),await this.toolActivityStartPromise,this.toolActivity?.isActive()&&this.sessionWatcher.retryActiveRead()}startMobileEndWatcher(e){!this.sessionState||this.sessionState.sessionId!==e||(this.sessionState.mobileEndWatcher=this.appSyncClient.watchForMobileEnd(e,async()=>{a.info("Mobile ended session \u2014 sending desktop quit",{sessionId:e}),this.appSyncClient.stopHeartbeat(e),this.appSyncClient.cleanupSubscription(e);try{await this.appSyncClient.updateSession({sessionId:e,status:m.SessionStatus.INACTIVE}),a.info("Marked session INACTIVE on mobile-end (before tmux terminate)",{sessionId:e})}catch(i){a.warn("Failed to mark session INACTIVE on mobile-end",{sessionId:e,error:i})}let t=process.env[Y];if(!t){a.warn("No tmux session set; skipping desktop self-terminate",{sessionId:e,expectedEnv:Y});return}await ls(t,ss)}))}async endActiveSession(e,t=!0){if(!this.sessionState)return;let i=e,s=t,r=this.sessionState;if(this.terminalInputBlockedStates.add(r),await this.terminalInputChain.catch(()=>{}),this.sessionState!==r){a.warn("Session changed while waiting for terminal-input teardown barrier",{endingSessionId:r.sessionId,currentSessionId:this.sessionState?.sessionId,reason:i});return}if(a.info("Ending active session",{sessionId:r.sessionId,codexSessionId:r.codexSessionId,reason:i}),this.sessionState.mobileEndWatcher&&(this.sessionState.mobileEndWatcher.stop(),this.sessionState.mobileEndWatcher=void 0),this.userDecisionUnsubscribe){try{this.userDecisionUnsubscribe()}catch(n){a.warn("Error invoking onApplyUserDecision unsubscribe (non-fatal)",{error:n})}this.userDecisionUnsubscribe=null}if(this.orchestrationClient){try{await this.orchestrationClient.destroy()}catch(n){a.warn("Error destroying OrchestrationClient (non-fatal)",{error:n})}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();for(let n of this.deferredTmuxPromptCandidates.keys())n.sessionId===r.sessionId&&this.deferredTmuxPromptCandidates.delete(n);this.queuedPermissionRequestRegistrations.delete(r.sessionId),this.terminalRetirementRequested&&(i="shutdown",s=!0),i==="shutdown"&&this.sessionWatcher.stop(),this.toolActivityStartPromise&&(await this.toolActivityStartPromise.catch(()=>{}),this.toolActivityStartPromise=null),await this.logEntryChain.catch(()=>{}),await this.stopNativeSources(r),this.toolActivity&&(await this.toolActivity.stop(),this.toolActivity=null);for(let n of this.toolActivityLegacyRecorders.values())n.disposeLegacyCoordination();this.toolActivityLegacyRecorders.clear(),this.terminalRetirementRequested&&(i="shutdown",s=!0),i==="daemon-handoff"&&this.persistDaemonHandoffState(r),(i==="new-codex-session-started"||i==="shutdown")&&(await this.exactClearOpenE1ForLifecycleEnd(r.sessionId),await this.drainPendingE1ResolutionsForLifecycleEnd(),this.stopE1TtlRefresh()),i!=="backend-generation-retired"&&i!=="daemon-handoff"&&(this.permissionRequestOccurrencesByCompletionKey.clear(),this.waitingPermissionRequests.clear()),this.pendingInteractivePrompt=null,this.queuedInteractivePrompts=[],this.queuedQuestionCallIds.clear(),this.isInitializingSession=!1,this.bufferedLogEntries=[],$e(),this.sessionKey&&(m.keychainManager.clearSessionKey(this.sessionState.sessionId),this.sessionKey=null,this.sessionKeyGen=null),this.terminalRetirementRequested&&(s=!0),s?await this.retireHostedSession(this.sessionState.sessionId,r):a.info("Preserving active backend session for daemon handoff",{sessionId:this.sessionState.sessionId}),this.sessionState=null}async boundedTeardownStep(e,t){await Ge(async()=>{try{await t()}catch(s){a.warn(`${e} failed`,{error:String(s)})}},3e3,()=>a.warn(`${e} timed out \u2014 continuing teardown without it`,{timeoutMs:3e3}))==="timeout"&&this.teardownStepsTimedOut.push(e)}isDurableObligationSettledForExit(){return!this.retirementOwed}getTeardownStepsTimedOut(){return[...this.teardownStepsTimedOut]}async retireHostedSession(e,t){ze("stall-retirement")&&(a.warn("[dev-fault] stall-retirement: this INACTIVE write will never settle",{sessionId:e}),await new Promise(()=>{}));let i;for(let s=1;s<=De;s+=1)try{let r=await this.appSyncClient.updateSession({sessionId:e,status:m.SessionStatus.INACTIVE});r?.sessionGenerationId&&await this.appSyncClient.completeDesktopSyncRetirement({sessionId:e,toolOutbox:new m.ToolActivityOutbox({agent:"codex",logger:a})},r,async()=>{await this.logEntryChain.catch(()=>{}),await this.stopNativeSources(t)});return}catch(r){i=r,a.warn("Failed to retire hosted Codex session",{sessionId:e,attempt:s,maxAttempts:De,error:r instanceof Error?r.message:String(r)}),s<De&&await new Promise(n=>setTimeout(n,os*s))}throw new Error(`Failed to retire hosted Codex session ${e} after ${De} attempts: ${String(i)}`)}async cleanupDetachedWrapperArtifacts(){let e=process.env.CODEVIBE_CODEX_WRAPPER_PID;if(!e||!/^\d+$/.test(e))return;let t=process.env.TMPDIR||Je.tmpdir(),i=[L.join(t,`codevibe-codex-server-${e}.pid`),L.join(t,`codevibe-codex-exit-${e}`),L.join(t,`codevibe-codex-tmux-session-${e}`)];for(let s of i)try{J.unlinkSync(s)}catch(r){r?.code!=="ENOENT"&&a.warn("Failed to remove detached-wrapper artifact",{ownedPath:s,error:String(r)})}}stop(e={}){return e.retireBackendSession!==!1&&(this.terminalRetirementRequested=!0),this.stopPromise?this.stopPromise:(this.stopPromise=this.doStop(),this.stopPromise)}async doStop(){a.info("Stopping CodeVibe Codex companion server"),this.stopTmuxLifecycleMonitor(),this.isStopping=!0,this.nativeSourceRetryTimer&&clearTimeout(this.nativeSourceRetryTimer),this.nativeSourceRetryTimer=null,this.lifecycleGeneration+=1,this.sessionWatcher.stop();let e=this.launchSessionInitPromise,t=this.sessionStartedInitPromise,i=this.retiredSessionRecoveryPromise,s=this.hookEventChain,r=typeof this.sessionWatcher.waitForTranscriptAdmissions=="function"?this.sessionWatcher.waitForTranscriptAdmissions():Promise.resolve();this.teardownStepsTimedOut=[],await this.boundedTeardownStep("inFlightChains.join",()=>Promise.all([e?.catch(()=>{}),t?.catch(()=>{}),i?.catch(()=>{}),r.catch(()=>{}),this.sessionWatcher.waitForReads().catch(()=>{}),s.catch(()=>{})]));try{let n=this.terminalRetirementRequested;this.retirementOwed=n&&this.sessionState!==null;let o,l=!1;if(await Ge(async()=>{try{await this.endActiveSession(n?"shutdown":"daemon-handoff",n),this.retirementOwed=!1}catch(c){l=!0,o=c}},1e4,()=>a.warn("endActiveSession timed out \u2014 continuing teardown without it",{timeoutMs:1e4,retirementOwed:this.retirementOwed}))==="timeout"&&this.teardownStepsTimedOut.push("endActiveSession"),l)throw o;this.sessionWatcher.stop(),this.approvalDetector.shutdown(),$e()}finally{await this.boundedTeardownStep("httpApi.stop",()=>this.httpApi.stop()),this.appSyncClient.cleanupSubscriptions(),this.terminalRetirementRequested&&await this.boundedTeardownStep("cleanupDetachedWrapperArtifacts",()=>this.cleanupDetachedWrapperArtifacts())}if(a.info("CodeVibe Codex companion server stopped"),this.retirementOwed)throw new Error("Session teardown timed out with the INACTIVE write still owed; the backend row may be stranded ACTIVE")}};if(require.main===module){let d=new Me;for(let e of Vt)process.on(e,()=>{a.info(`Received ${e}, evaluating terminal shutdown...`),(async()=>{let t;try{t=await d.shouldShutdownForTerminalSignal(e)}catch(s){a.error(`Failed to evaluate ${e} terminality; not shutting down`,{error:s instanceof Error?s.message:String(s)});return}if(!t)return;let i=he(s=>process.exit(s),()=>a.error("Shutdown watchdog fired \u2014 teardown did not complete in time; exiting anyway",{signal:e,watchdogMs:25e3,timedOutSteps:d.getTeardownStepsTimedOut(),durableObligationSettled:d.isDurableObligationSettledForExit()}),25e3,()=>d.isDurableObligationSettledForExit());try{await d.stop(),i(),process.exit(0)}catch(s){i(),a.error(`Failed to stop companion daemon after ${e}`,{error:s instanceof Error?s.message:String(s)}),process.exit(1)}})()});process.on("SIGUSR2",async()=>{a.info("Received SIGUSR2, handing off active session to replacement daemon...");let e=he(t=>process.exit(t),()=>a.error("Shutdown watchdog fired during SIGUSR2 handoff; exiting anyway",{watchdogMs:25e3,timedOutSteps:d.getTeardownStepsTimedOut()}),25e3,()=>d.isDurableObligationSettledForExit());try{await d.stop({retireBackendSession:!1})}catch(t){a.error("Handoff stop() failed; exiting anyway to free the session",{error:t instanceof Error?t.message:String(t)})}finally{e()}process.exit(0)}),(0,m.installDaemonProcessGuards)(a,{onFatal:()=>{let e=he(()=>process.exit(1),()=>a.error("Shutdown watchdog fired after a fatal guard; exiting anyway",{watchdogMs:25e3,timedOutSteps:d.getTeardownStepsTimedOut(),durableObligationSettled:d.isDurableObligationSettledForExit()}),25e3);d.stop().finally(()=>{e(),process.exit(1)})}}),d.start().catch(e=>{a.error("Failed to start server:",e),process.exit(1)})}0&&(module.exports={CodexCompanionServer,TERMINAL_SHUTDOWN_SIGNALS,classifyTmuxHasSessionError,extractShellCommandFromPromptText,extractShellCommandPartsFromPromptText,restoreCodexPersistOptionCommand,shellCommandPartsMatchExpected});
|