grix-connector 3.8.2 → 3.8.3

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.
@@ -1,11 +1,12 @@
1
- import{execFileSync as L}from"node:child_process";import{createInterface as J}from"node:readline";import{EventEmitter as O}from"node:events";import{stat as N}from"node:fs/promises";import{join as C,resolve as V}from"node:path";import{fileURLToPath as X}from"node:url";import{homedir as G}from"node:os";import{syncDefaultSkillsToDir as Y}from"../../default-skills/index.js";import{resolveCommandPath as K,spawnCommand as Z,killProcessGroup as D,hasChildProcesses as Q}from"../../core/runtime/spawn.js";import{InternalApiServer as ee}from"../../core/mcp/internal-api-server.js";import{log as o}from"../../core/log/index.js";import{resolveClientVersion as te}from"../../core/util/client-version.js";import{isUserVisibleAgentMessagePhase as ie}from"../../core/util/codex-output-policy.js";import{SessionBindingStore as se}from"../../core/persistence/session-binding-store.js";import{ensureCodexProjectTrusted as ne,isCodexCommand as re,readCodexProviderSettings as k}from"./codex-trust.js";import{checkCodexSessionActivity as oe}from"./session-activity.js";import{findRolloutFile as ae}from"./rollout-locator.js";import{checkCodexLock as j}from"./lock-monitor.js";import{resolveCliPath as de,getCliVersion as ce}from"../../core/util/cli-probe.js";import{scanSkills as le}from"../claude/skill-scanner.js";const he=60*1e3,ue=600*1e3,pe=5*1e3,F=2,fe=20,me=8e3,H=80,ge=120*1e3,ve=[{id:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",defaultReasoningEffort:null,supportedReasoningEfforts:[],defaultServiceTier:null,serviceTiers:[],isDefault:!0}],q=[{id:"default",displayName:"Default"},{id:"plan",displayName:"Plan"}];function U(d,e){const t=String(d??"").trim()||"codex",s=K(t,e);if(s!==t)return s;const i=process.platform==="win32"?[]:["/opt/homebrew/bin/codex","/usr/local/bin/codex","/usr/bin/codex"],n=process.platform!=="win32"?[]:[C(process.env.LOCALAPPDATA??"","npm","codex.cmd"),C(process.env.APPDATA??"","npm","codex.cmd"),C(process.env.LOCALAPPDATA??"","Programs","codex","codex.exe")],r=[...i,...n];for(const a of r)try{return require("node:fs").accessSync(a,require("node:fs").constants.X_OK),a}catch{continue}return o.warn("codex-adapter",`resolveCodexCommandPath: failed to resolve "${t}". envPath=${e?"provided":"missing (using process.env.PATH)"}. fallbacks tried: [${r.join(", ")}]`),t}class M extends O{type="codex";config;callbacks;process=null;alive=!1;stopped=!1;internalApi=null;bridgeStatus="starting";pendingRequests=new Map;requestId=0;threadId=null;initialized=!1;cwd;approvalPolicy;sandboxMode;model;collaborationMode;reasoningEffort;serviceTier;idleTimer=null;lastProgressAt=0;lastIdleCheckAt=0;idleNoProgressCount=0;inFlightToolOps=0;pendingApprovals=new Map;needsHistoryInjection=!1;lastInjectedSessionId=null;identityInjectedThreadId=null;bindingStore=null;aibotSessionId="";threadResumePending=!1;autoTrustProject="auto";codexHome;codexModelOptions=[];codexModelOptionsCachedAt=0;static MODEL_CACHE_TTL_MS=3600*1e3;rateLimitSnapshot=null;currentThreadTokenUsage=null;currentModelContextWindow=null;constructor(e,t){super(),this.config=e,this.callbacks=t;const s=e.options??{};if(this.approvalPolicy=s.approvalPolicy??"never",this.sandboxMode=typeof s.sandboxMode=="string"&&s.sandboxMode.trim()&&s.sandboxMode.trim()!=="default"?s.sandboxMode.trim():void 0,this.aibotSessionId=String(s.aibotSessionId??"").trim(),this.bindingStore=s.bindingStore instanceof se?s.bindingStore:null,this.model=s.model,this.collaborationMode=s.collaborationMode,this.reasoningEffort=s.reasoningEffort,this.serviceTier=s.serviceTier,this.bindingStore&&this.aibotSessionId&&(this.model=this.model??this.bindingStore.getCodexModelId(this.aibotSessionId),this.collaborationMode=this.collaborationMode??this.bindingStore.getCodexModeId(this.aibotSessionId),this.reasoningEffort=this.reasoningEffort??this.bindingStore.getCodexReasoningEffort(this.aibotSessionId),this.serviceTier=this.serviceTier??this.bindingStore.getCodexServiceTier(this.aibotSessionId),this.sandboxMode=this.sandboxMode??this.bindingStore.getCodexSandboxMode(this.aibotSessionId)),this.autoTrustProject=typeof s.autoTrustProject=="boolean"?s.autoTrustProject:"auto",this.codexHome=typeof s.codexHome=="string"&&s.codexHome.trim()?s.codexHome.trim():void 0,this.cwd=this.resolveCwd(),this.bindingStore&&this.aibotSessionId){const i=this.bindingStore.getCodexThreadId(this.aibotSessionId);i&&(this.threadId=i,this.threadResumePending=!0)}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}return process.cwd()}async start(){await this.ensureProjectTrusted(),await this.startInternalApiAndRegisterMcp(),await this.spawnCodex(),await this.initializeHandshake(),await this.notifyBindingReadyWithContext(),o.info("codex-adapter",`Ready (pid=${this.process?.pid})`)}async ensureProjectTrusted(){if(this.shouldAutoTrustProject())try{const e=await ne(this.cwd,{codexHome:this.codexHome});e.changed&&o.info("codex-adapter",`Trusted Codex project ${this.cwd} in ${e.configPath}`)}catch(e){const t=e instanceof Error?e.message:String(e);throw o.error("codex-adapter",`Failed to trust Codex project ${this.cwd}: ${t}`),e}}async startInternalApiAndRegisterMcp(){try{this.internalApi=new ee,this.internalApi.setInvokeHandler(async(a,h,m,g)=>this.callbacks.agentInvoke(a,h,g)),await this.internalApi.start(0),o.info("codex-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),t={...process.env,...this.config.env},s=typeof t.PATH=="string"?t.PATH:void 0,i=U(this.config.command||"codex",s);try{L(i,["mcp","remove",e.name],{env:t,timeout:1e4,stdio:"ignore"})}catch{}L(i,["mcp","add",e.name,"--",e.command,...e.args],{env:t,timeout:1e4,stdio:"ignore"}),o.info("codex-adapter",`Registered MCP server: ${e.name}`);const n=C(G(),".codex","skills"),r=Y(n);r.length>0&&o.info("codex-adapter",`Synced connector skills to ${n}: [${r.join(", ")}]`)}catch(e){o.warn("codex-adapter",`Failed to register MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`)}}shouldAutoTrustProject(){return this.autoTrustProject===!1?!1:this.autoTrustProject===!0?!0:re(this.config.command)}notifyBindingReady(){!this.aibotSessionId||!this.cwd||this.callbacks.sendUpdateBindingCard(this.aibotSessionId,"ready",this.cwd)}async notifyBindingReadyWithContext(){if(!(!this.aibotSessionId||!this.cwd))try{this.callbacks.sendUpdateBindingCard(this.aibotSessionId,"ready",this.cwd,await this.buildToolbarContextResult("binding_ready"))}catch(e){o.warn("codex-adapter",`Failed to attach toolbar context to binding update: ${e instanceof Error?e.message:String(e)}`),this.notifyBindingReady()}}externalProviderCheckedAt=0;externalProviderCached=!1;static EXTERNAL_PROVIDER_CACHE_TTL_MS=60*1e3;isExternalProvider(){const e=Date.now();if(e-this.externalProviderCheckedAt<M.EXTERNAL_PROVIDER_CACHE_TTL_MS)return this.externalProviderCached;const t=k(this.codexHome);return this.externalProviderCached=!!(t.baseUrl&&z(t.baseUrl)),this.externalProviderCheckedAt=e,this.externalProviderCached}effectiveServiceTier(){if(!this.serviceTier||this.isExternalProvider())return;const e=this.getModelOption(this.currentModelId());if(!(e&&!e.serviceTiers.some(t=>t.id===this.serviceTier)))return this.serviceTier}getEffortMeta(){if(this.isExternalProvider())return{};const e=this.currentModelId(),t=this.getModelOption(e),s={},i=t?.supportedReasoningEfforts??[];i.length>0&&(s.available_efforts=i,s.reasoning_effort=this.reasoningEffort??t?.defaultReasoningEffort??null);const n=t?.serviceTiers??[];return n.length>0&&(s.available_service_tiers=n,s.service_tier=this.effectiveServiceTier()??t?.defaultServiceTier??null),s}async stop(){this.stopped=!0,this.alive=!1,this.stopComposing(),this.clearIdleTimer(),this.rejectAllPending("adapter stopped"),this.pendingAutoCompact=!1,this.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null);for(const t of this.compactionDeferred.splice(0))this.callbacks.sendEventResult(t.event_id,"failed","adapter stopped");for(const t of this.steerDeferred.splice(0))this.callbacks.sendEventResult(t.event_id,"failed","adapter stopped");this.internalApi&&(await this.internalApi.stop(),this.internalApi=null);const e=this.process;if(this.process=null,e?.pid&&typeof e.once=="function")D(e,"SIGTERM"),await Promise.race([new Promise(s=>{e.once("exit",()=>s(!0))}),new Promise(s=>{setTimeout(()=>s(!1),5e3)})])||D(e,"SIGKILL");else if(e)try{e.kill("SIGTERM")}catch{}}isAlive(){return this.alive}async createSession(e){if(this.initialized||await this.initializeHandshake(),this.threadId||await this.startNewThread(),!this.threadId)throw new Error("Failed to create session: thread ID is missing");return await this.notifyBindingReadyWithContext(),this.threadId}async resumeSession(e,t){await this.ensureThreadResumed()}async destroySession(e){this.threadId=null,this.threadResumePending=!1,this.persistThreadId(void 0)}sendPrompt(e){const t=new R(e.adapterSessionId);return this.runTurn(e,t).catch(s=>{t.emitError(s instanceof Error?s:new Error(String(s)))}),t}async cancel(e){if(this.threadId)try{await this.sendRequest("turn/interrupt",{threadId:this.threadId,turnId:this.currentTurnId??""},5e3)}catch{}}setPermissionHandler(e){this.permissionHandler=e}permissionHandler=null;async ping(e){if(!this.alive||!this.process)return!1;if(!this.process.pid){const t=!!(this.process.stdin&&!this.process.stdin.destroyed),s=!!(this.process.stdout&&!this.process.stdout.destroyed);return t&&s}if(!this.process.stdin||this.process.stdin.destroyed)return!!(this.process.stdout&&!this.process.stdout.destroyed);try{const t=++this.requestId,s={jsonrpc:"2.0",id:t,method:"ping",params:{}};return await new Promise(i=>{const n=setTimeout(()=>{this.pendingRequests.delete(String(t)),i(!1)},e);this.pendingRequests.set(String(t),{resolve:()=>i(!0),reject:()=>i(!1),timer:n}),this.process.stdin.write(`${JSON.stringify(s)}
2
- `)})}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.currentTurnId!==null||this.compacting,sessions:this.threadId?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}clearActiveEventForShutdown(){this.clearIdleTimer(),this.activeEventId=null}setModel(e){this.model=e,this.persistCodexContext(),o.info("codex-adapter",`Model set to: ${e}`)}setMode(e){const t=y(e);if(!t){o.info("codex-adapter",`Ignoring unsupported mode: ${e}`);return}this.collaborationMode=t,this.persistCodexContext(),o.info("codex-adapter",`Mode set to: ${t}`)}setReasoningEffort(e){this.reasoningEffort=e,this.persistCodexContext(),o.info("codex-adapter",`Reasoning effort set to: ${e}`)}setServiceTier(e){const t=e.trim();this.serviceTier=t.toLowerCase()==="default"?void 0:t,this.persistCodexContext(),o.info("codex-adapter",`Service tier set to: ${this.serviceTier??"default"}`)}setSandboxMode(e){this.sandboxMode=e,this.persistCodexContext(),o.info("codex-adapter",`Sandbox mode set to: ${e} (applied on next restart)`)}async threadCompact(){if(!this.threadId)throw new Error("No active thread");return this.sendRequest("thread/compact/start",{threadId:this.threadId},12e4)}async threadRollback(e){if(!this.threadId)throw new Error("No active thread");return this.sendRequest("thread/rollback",{threadId:this.threadId,numTurns:e},1e4)}getThreadId(){return this.threadId}getMcpConfig(){if(!this.internalApi)return null;const e=V(X(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?Q(e,[e]):!1}onAgentProfileChanged(){this.identityInjectedThreadId!==null&&(o.info("codex-adapter",`agent profile changed; clearing identity-injected thread record (was ${this.identityInjectedThreadId})`),this.identityInjectedThreadId=null)}async probe(e){const t=this.config.command||"codex",s=await de(t),i=s!==null;let n=null,r;if(i){const I=await ce(t);n=I.version,I.error&&(r=I.error)}else r={code:"cli_not_found",message:`command not found: ${t}`};const h=k().baseUrl??null,m=this.currentModelId()||null,g=this.getStatus(),p=e?.conversation?{attempted:!0,ok:!1,latency_ms:null,error:{code:"unsupported",message:"codex does not support minimal prompt probe"}}:{attempted:!1,ok:!1,latency_ms:null},u=await this.probeSessionRecord(),v=j({codexHome:this.codexHome});return{cli:{command:t,installed:i,path:s,version:n,...r?{error:r}:{}},conversation:p,config:{model:m,base_url:h,source:{model:m?"runtime":"unknown",base_url:h?"file":"unknown"}},process:{started:!!this.process,alive:g.alive,busy:g.busy},session:u,lock:{present:v.present,locked:v.locked,stale:v.stale,path:v.path}}}async probeSessionRecord(){const e=this.threadId?ae(this.threadId,this.codexHome):null;if(!e)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const t=await N(e);return{recordPath:e,lastActivityMs:t.mtimeMs,freshMs:Date.now()-t.mtimeMs}}catch{return{recordPath:e,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"compact",description:"Compact thread to reduce context size"},{name:"model",description:"List or set model",args:"[model_id]"},{name:"mode",description:"List or set collaboration mode",args:"[default|plan]"},{name:"rollback",description:"Roll back thread turns",args:"[num_turns]"},{name:"interrupt",description:"Interrupt current turn"},{name:"rate_limits",description:"Show current rate limits"},{name:"status",description:"Show thread and session status"},{name:"skills",description:"List available skills"}]}async execCommand(e,t,s){try{switch(e){case"compact":{if(!this.threadId)return{status:"failed",message:"No active thread"};if(this.compacting)return{status:"failed",message:"Compaction already in progress"};if(this.currentTurnId&&(await this.cancel(this.threadId).catch(()=>{}),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","compacting"),this.clearActive()),await this.ensureThreadResumed(),this.currentTurnId)return{status:"failed",message:"agent busy"};if(this.needsHistoryInjection)return{status:"failed",message:"The session has expired and there is no history to compact. Please send a new message and try again."};this.compacting=!0;const i=new Promise(n=>{this.compactionDoneResolver=n});try{return await this.threadCompact(),this.armCompactionFallback(),await i,{status:"ok",message:"Thread compacted"}}catch(n){this.finishCompaction("compact-error");const r=n instanceof Error?n.message:String(n);if(/thread.*(not found|not exist|unknown|invalid)/i.test(r)||/not found.*thread/i.test(r))return this.threadId=null,this.persistThreadId(void 0),{status:"failed",message:"The session has expired and there is no history to compact. Please send a new message and try again."};throw n}}case"model":{const i=t.trim();return i?this.getModelOptions().some(r=>r.id===i)?(this.setModel(i),{status:"ok",message:`Model set to ${i}`}):{status:"failed",message:`Unknown model: ${i}`}:{status:"ok",message:`Current: ${this.currentModelId()}`,data:{models:this.getModelOptions()}}}case"mode":{const i=t.trim();if(i){const n=y(i);return n?(this.setMode(n),{status:"ok",message:`Mode set to ${n}`}):{status:"failed",message:`Unknown mode: ${i}. Supported: default, plan`}}return{status:"ok",message:`Current: ${this.collaborationMode??"default"}`,data:{modes:q}}}case"rollback":{if(!this.threadId)return{status:"failed",message:"No active thread"};const i=Math.max(1,parseInt(t.trim(),10)||1);return this.currentTurnId&&(await this.cancel(this.threadId).catch(()=>{}),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","rolled back"),this.clearActive()),await this.threadRollback(i),{status:"ok",message:`Rolled back ${i} turn(s)`}}case"interrupt":return this.threadId?(await this.cancel(this.threadId),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Turn interrupted"}):{status:"failed",message:"No active thread"};case"rate_limits":return{status:"ok",message:this.rateLimitSnapshot?`Primary: ${this.rateLimitSnapshot.primary.usedPercent.toFixed(1)}%, Secondary: ${this.rateLimitSnapshot.secondary.usedPercent.toFixed(1)}%`:"Rate limits not available",data:{rateLimits:this.rateLimitSnapshot}};case"status":return{status:"ok",message:`Thread: ${this.threadId??"none"}, Model: ${this.currentModelId()}, Mode: ${this.collaborationMode??"default"}`,data:{threadId:this.threadId,model:this.currentModelId(),mode:this.collaborationMode??"default",cwd:this.cwd,alive:this.alive}};case"skills":{const i=le({mode:"codex",projectDir:this.cwd}),n=i.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""}: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
3
- `):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${e}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}async handleLocalAction(e){const t=e.action_type??"",s=e.params??{};switch(o.info("codex-adapter",`handleLocalAction action_type=${t} action_id=${e.action_id} session_id=${s.session_id??""}`),t){case"set_model":{const i=x(l(s.model_id),l(s.modelId),l(s.value));return i&&this.setModel(i),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("model_set")),{handled:!0,kind:"set_model"}}case"set_mode":{const i=s.mode_id;return i&&this.setMode(i),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("mode_set")),{handled:!0,kind:"set_mode"}}case"set_reasoning_effort":{const i=x(l(s.reasoning_effort),l(s.reasoning_eff),l(s.effort));return i&&this.setReasoningEffort(i),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("effort_set",!1)),{handled:!0,kind:"set_reasoning_effort"}}case"set_service_tier":{const i=x(l(s.service_tier),l(s.serviceTier),l(s.value));return i&&this.setServiceTier(i),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("service_tier_set",!1)),{handled:!0,kind:"set_service_tier"}}case"set_sandbox_mode":{const i=x(l(s.sandbox_mode),l(s.sandboxMode),l(s.value));return i&&this.setSandboxMode(i),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("sandbox_mode_set",!1)),{handled:!0,kind:"set_sandbox_mode"}}case"thread_compact":{o.info("codex-adapter",`thread_compact start action_id=${e.action_id} threadId=${this.threadId}`),this.currentTurnId&&(await this.cancel(this.threadId).catch(()=>{}),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","compacting"),this.clearActive());try{if(await this.ensureThreadResumed(),this.needsHistoryInjection)return o.info("codex-adapter",`thread_compact aborted: thread expired, new thread created action_id=${e.action_id}`),this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"thread_expired","The session has expired and there is no history to compact. Please send a new message and try again."),{handled:!0,kind:"thread_compact"};this.compacting=!0;const i=new Promise(n=>{this.compactionDoneResolver=n});await this.threadCompact(),this.armCompactionFallback(),await i,o.info("codex-adapter",`thread_compact done action_id=${e.action_id}`),this.callbacks.sendLocalActionResult(e.action_id,"ok")}catch(i){this.finishCompaction("compact-error");const n=i instanceof Error?i.message:String(i);/thread.*(not found|not exist|unknown|invalid)/i.test(n)||/not found.*thread/i.test(n)?(o.warn("codex-adapter",`thread_compact thread expired, resetting threadId action_id=${e.action_id} err=${n}`),this.threadId=null,this.persistThreadId(void 0),this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"thread_expired","The session has expired and there is no history to compact. Please send a new message and try again.")):(o.info("codex-adapter",`thread_compact failed action_id=${e.action_id} err=${n}`),this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,void 0,n))}return{handled:!0,kind:"thread_compact"}}case"get_context":return this.callbacks.sendLocalActionResult(e.action_id,"ok",{threadId:this.threadId,model:this.model,mode:this.collaborationMode,approvalPolicy:this.approvalPolicy,cwd:this.cwd,...await this.buildToolbarContextResult("context")}),{handled:!0,kind:"get_context"};case"exec_approve":case"file_approve":{const i=this.resolvePendingApproval(e);if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:t};const n=s.decision||"allow-once",r=xe[n]??"accept";return this.sendApprovalDecision(i.requestId,r),this.pendingApprovals.delete(i.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.approvalId,approval_command_id:i.approvalCommandId,decision:n}),this.resumeAfterApproval(e,s,i),{handled:!0,kind:t}}case"exec_reject":case"file_reject":{const i=this.resolvePendingApproval(e);return i?(this.sendApprovalDecision(i.requestId,"deny"),this.pendingApprovals.delete(i.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.approvalId,approval_command_id:i.approvalCommandId,decision:"deny"}),this.resumeAfterApproval(e,s,i),{handled:!0,kind:t}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:t})}case"permission_approve":{const i=this.resolvePendingApproval(e);return!i||i.kind!=="permission"?(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That permission approval request is no longer pending."),{handled:!0,kind:t}):(this.sendApprovalDecision(i.requestId,"accept"),this.pendingApprovals.delete(i.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.approvalId,decision:"approve"}),this.resumeAfterApproval(e,s,i),{handled:!0,kind:t})}case"permission_reject":{const i=this.resolvePendingApproval(e);return!i||i.kind!=="permission"?(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That permission approval request is no longer pending."),{handled:!0,kind:t}):(this.sendApprovalDecision(i.requestId,"deny"),this.pendingApprovals.delete(i.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.approvalId,decision:"deny"}),this.resumeAfterApproval(e,s,i),{handled:!0,kind:t})}case"turn_interrupt":{try{await this.cancel(this.threadId??""),this.callbacks.sendLocalActionResult(e.action_id,"ok")}catch(i){this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,void 0,i instanceof Error?i.message:String(i))}return{handled:!0,kind:"turn_interrupt"}}case"thread_rollback":{const i=Number(s.numTurns??s.num_turns??1);if(!this.threadId)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"no_thread","No active thread"),{handled:!0,kind:"thread_rollback"};this.currentTurnId&&(await this.cancel(this.threadId).catch(()=>{}),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","rolled back"),this.clearActive());try{await this.threadRollback(i),this.callbacks.sendLocalActionResult(e.action_id,"ok",{numTurns:i})}catch(n){this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,void 0,n instanceof Error?n.message:String(n))}return{handled:!0,kind:"thread_rollback"}}case"get_rate_limits":{const i=this.rateLimitSnapshot,n=this.buildContextWindowSnapshot(),r=Date.now(),a=this.currentThreadTokenUsage;return i?o.info("codex-adapter",`[rate-limits] responding: primary=${i.primary.usedPercent.toFixed(1)}% window=${i.primary.windowMinutes}min resetsAt=${i.primary.resetsAt} secondary=${i.secondary.usedPercent.toFixed(1)}% window=${i.secondary.windowMinutes}min resetsAt=${i.secondary.resetsAt}`):o.info("codex-adapter","[rate-limits] responding: no rateLimitSnapshot available"),o.debug("codex-adapter",`[cp-diagnose] get_rate_limits: threadId=${this.threadId??"-"} contextWindow=${JSON.stringify(n)} tokenUsage=${JSON.stringify(a)}`),this.callbacks.sendLocalActionResult(e.action_id,"ok",{adapterType:"codex",available:i!==null,cached:!1,sampledAt:r,rateLimits:i,contextWindow:n,tokenUsage:a}),{handled:!0,kind:"get_rate_limits"}}default:return{handled:!1,kind:""}}}async buildToolbarContextResult(e,t=!0){t&&await this.refreshCodexModelOptions();const s=y(this.collaborationMode)??"default",i=this.currentModelId(),n=this.getModelOption(i),r=this.getModelOptions(),a=q,h=this.reasoningEffort??n?.defaultReasoningEffort??null,m=n?.supportedReasoningEfforts??[],g=this.effectiveServiceTier()??n?.defaultServiceTier??null,p=n?.serviceTiers??[],u=this.isExternalProvider(),v=u?[]:m,I=u?null:h,_=u?[]:p,w=u?null:g,c={outcome:e,session_context:{modelId:i,modeId:s,reasoningEffort:I,serviceTier:w,approvalPolicy:this.approvalPolicy,sandboxMode:this.sandboxMode??null},model_id:i,mode_id:s,currentModelId:i,currentModeId:s,available_models:r,available_modes:a,available_efforts:v,availableModels:r,availableModes:a,reasoning_effort:I,available_service_tiers:_,service_tier:w,sandbox_mode:this.sandboxMode??null,models:r.map(f=>({modelId:f.id,name:f.displayName})),modes:a.map(f=>({id:f.id,name:f.displayName}))};return this.rateLimitSnapshot&&(c.rate_limit_primary_percent=this.rateLimitSnapshot.primary.usedPercent,c.rate_limit_secondary_percent=this.rateLimitSnapshot.secondary.usedPercent,c.rate_limit_primary_window_min=this.rateLimitSnapshot.primary.windowMinutes,c.rate_limit_secondary_window_min=this.rateLimitSnapshot.secondary.windowMinutes),c}currentModelId(){const e=String(this.model??"").trim();if(e)return e;const t=this.getModelOptions();return t.find(s=>s.isDefault)?.id??t[0]?.id??""}getModelOption(e){const t=e.trim().toLowerCase();return this.getModelOptions().find(s=>s.id.trim().toLowerCase()===t)}getModelOptions(){const e=this.config.options??{},t=e.available_models??e.availableModels??e.models,s=ye(t),i=this.codexModelOptions,n=[],r=String(this.model??"").trim(),a=r&&!i.some(p=>p.id.trim().toLowerCase()===r.toLowerCase()),h=i.length>0?i:a?[]:ve;if(r){const p=[...i,...s].find(u=>u.id.trim().toLowerCase()===r.toLowerCase());n.push({id:r,displayName:p?.displayName??T(r),defaultReasoningEffort:p?.defaultReasoningEffort??null,supportedReasoningEfforts:p?.supportedReasoningEfforts??[],defaultServiceTier:p?.defaultServiceTier??null,serviceTiers:p?.serviceTiers??[],isDefault:p?.isDefault??!1})}n.push(...s),n.push(...h);const m=[],g=new Set;for(const p of n){const u=p.id.trim(),v=u.toLowerCase();!u||g.has(v)||(g.add(v),m.push({id:u,displayName:p.displayName.trim()||u,defaultReasoningEffort:p.defaultReasoningEffort,supportedReasoningEfforts:[...p.supportedReasoningEfforts],defaultServiceTier:p.defaultServiceTier,serviceTiers:[...p.serviceTiers],isDefault:p.isDefault}))}return m}async refreshCodexModelOptions(){if(!this.initialized||!this.alive||!this.process?.stdin||Date.now()-this.codexModelOptionsCachedAt<M.MODEL_CACHE_TTL_MS)return;const e=k(this.codexHome);if(e.baseUrl&&z(e.baseUrl)){try{const t=await Te(e.baseUrl,e.apiKey);if(t.length>0){this.codexModelOptions=W(t),this.codexModelOptionsCachedAt=Date.now(),o.info("codex-adapter",`Loaded ${t.length} models from external provider ${e.baseUrl}`);return}}catch(t){o.warn("codex-adapter",`External provider /v1/models failed (${t instanceof Error?t.message:String(t)}), falling back`)}this.codexModelOptions=[],this.codexModelOptionsCachedAt=Date.now();return}try{const t=[];let s;do{const i=await this.sendRequest("model/list",{cursor:s??null,includeHidden:!1,limit:100},15e3),n=Ce(i);t.push(...n.models),s=n.nextCursor}while(s);t.length>0&&(this.codexModelOptions=W(t),this.codexModelOptionsCachedAt=Date.now())}catch(t){o.warn("codex-adapter",`Failed to load Codex model list: ${t instanceof Error?t.message:String(t)}`)}}currentTurnId=null;compacting=!1;pendingAutoCompact=!1;compactionDeferred=[];steerDeferred=[];compactingTimer=null;compactionDoneResolver=null;activeEventId=null;activeSessionId=null;visibleAgentMessageIds=new Set;hiddenAgentMessageIds=new Set;agentMessagePhases=new Map;codexSequence=0;turnError=null;turnErrorIsRetryableOnly=!0;turnHasVisibleOutput=!1;deliverInboundEvent(e){if(this.compacting){o.info("codex-adapter",`Event ${e.event_id} deferred: compaction in progress`),this.compactionDeferred.push(e);return}const t=e.content;if(this.currentTurnId&&t.trim()){o.info("codex-adapter",`Event ${e.event_id}: steering active turn ${this.currentTurnId}`),this.steerTurn(t).catch(s=>{const i=s instanceof Error?s.message:String(s);if(o.info("codex-adapter",`Steer failed, falling through: ${i}`),!this.currentTurnId){this.startNewTurn(e,t);return}if(Ee(i)){o.info("codex-adapter","Unsteerable turn detected, clearing active state and starting new turn"),this.clearActive(),this.startNewTurn(e,t);return}o.info("codex-adapter",`Steer failed but turn still active; deferring event ${e.event_id} for replay after turn ends`),this.steerDeferred.push(e)});return}if(this.currentTurnId){o.info("codex-adapter",`Event ${e.event_id} rejected: busy and empty content`),this.callbacks.sendEventResult(e.event_id,"failed","agent busy");return}this.startNewTurn(e,t)}startNewTurn(e,t){this.activeEventId=e.event_id,this.activeSessionId=e.session_id,this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.agentMessagePhases.clear(),this.codexSequence=0,this.startComposing();const s=this.threadId??"",i=new R(s),n={adapterSessionId:s,text:t,contextMessages:e.context_messages_json?JSON.parse(e.context_messages_json).map(r=>({senderId:r.sender_id??"unknown",content:r.content})):void 0};this.runTurn(n,i,e.event_id,e.session_id).catch(r=>{o.error("codex-adapter",`Turn failed: ${r}`),this.callbacks.sendEventResult(e.event_id,"failed",r instanceof Error?r.message:String(r)),this.clearActive()}),this.resetIdleTimer(e.event_id)}deliverStopEvent(e,t){this.activeEventId===e&&(this.cancel(this.threadId??"").catch(()=>{}),this.callbacks.sendEventResult(e,"canceled","stopped by user"),this.clearActive())}async spawnCodex(){const e={...process.env,...this.config.env},t=typeof e.PATH=="string"?e.PATH:void 0;t||o.warn("codex-adapter",`spawnCodex: env.PATH is missing! process.env.PATH=${process.env.PATH?"set":"missing"}, config.env=${JSON.stringify(this.config.env)}`);const s=U(this.config.command||"codex",t),i=Ie(this.config.args);this.sandboxMode&&i.push("-c",`sandbox_mode="${this.sandboxMode}"`),o.info("codex-adapter",`Spawning: ${s} ${i.join(" ")}`);try{if(!(await N(this.cwd)).isDirectory())throw new Error(`Bound path is not a directory: ${this.cwd}`)}catch(r){throw String(r?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${this.cwd}. Please rebind with /grix open <valid-directory>.`):r}const n=j({codexHome:this.codexHome});if(n.locked&&!n.stale)throw new Error(`Codex session appears locked by another process: ${n.path}`);n.stale&&o.warn("codex-adapter",`Ignoring stale Codex lock: ${n.path}`);try{this.process=Z(s,i,{env:e,cwd:this.cwd}).process}catch(r){throw o.error("codex-adapter",`Codex spawn threw: ${r}`),this.process=null,this.alive=!1,this.bridgeStatus="closed",r}this.process.on("error",r=>{o.error("codex-adapter",`Codex process spawn error: ${r}`),this.process=null,this.alive=!1,this.bridgeStatus="closed",this.clearIdleTimer(),this.rejectAllPending("spawn failed: "+(r instanceof Error?r.message:String(r))),this.stopComposing(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed","Codex process spawn failed"),this.activeEventId=null),this.emit("exit",1)}),this.process.on("exit",r=>{o.info("codex-adapter",`Codex process exited (code=${r})`),this.alive=!1,this.bridgeStatus="closed",this.clearIdleTimer(),this.rejectAllPending("process exited"),this.stopComposing(),this.emit("exit",r)}),this.process.stderr?.on("data",r=>{const a=r.toString().trim();a&&o.info("codex-adapter",`[codex stderr] ${a}`)}),this.bindStdout(),this.alive=!0}bindStdout(){if(!this.process?.stdout)return;this.process.stdout.setEncoding("utf8"),J({input:this.process.stdout}).on("line",t=>{if(!t.trim())return;let s;try{s=JSON.parse(t)}catch{o.error("codex-adapter",`Invalid JSON from Codex: ${t.slice(0,200)}`);return}if(this.bridgeStatus==="starting"&&(this.bridgeStatus="ready"),s.id!=null){const i=String(s.id),n=this.pendingRequests.get(i);if(n){clearTimeout(n.timer),this.pendingRequests.delete(i),n.resolve(s);return}}this.handleNotification(s)})}handleNotification(e){const t=e.method,s=e.params??{};switch(this.captureContextWindowFromPayload(t,s),this.activeEventId&&this.resetIdleTimer(this.activeEventId),this.activeEventId&&t&&t.startsWith("item/")&&!t.endsWith("/requestApproval")&&this.startComposing(),t){case"item/started":{const i=s.item,n=i?.id,r=i?.type,a=i?.phase;this.isLongRunningToolItemType(r)&&(this.inFlightToolOps+=1),r==="agentMessage"&&n&&(typeof a=="string"&&a.trim()?this.agentMessagePhases.set(n,a.trim().toLowerCase()):this.agentMessagePhases.delete(n),ie(a)?(this.visibleAgentMessageIds.add(n),this.hiddenAgentMessageIds.delete(n)):(this.hiddenAgentMessageIds.add(n),this.visibleAgentMessageIds.delete(n)));break}case"item/agentMessage/delta":{const i=s.delta,n=s.itemId;i&&this.activeEventId&&(!n||!this.hiddenAgentMessageIds.has(n))&&!this.shouldSuppressAgentMessageDeltaDuringToolRun(n)&&(this.turnHasVisibleOutput=!0,this.emitCodexEvent("item/agentMessage/delta",e));break}case"item/completed":{const i=s.item,n=i?.id,r=i?.type;this.isLongRunningToolItemType(r)&&(this.inFlightToolOps=Math.max(0,this.inFlightToolOps-1)),this.activeEventId&&r!=="agentMessage"&&(this.turnHasVisibleOutput=!0,this.emitCodexEvent("item/completed",e)),r==="agentMessage"&&n&&(this.visibleAgentMessageIds.delete(n),this.hiddenAgentMessageIds.delete(n),this.agentMessagePhases.delete(n));break}case"turn/started":{const n=s.turn?.id;n&&(this.currentTurnId=n,this.turnError=null,this.turnErrorIsRetryableOnly=!0,this.turnHasVisibleOutput=!1,o.info("codex-adapter",`Turn started: ${n}`),this.startComposing());break}case"item/fileChange/requestApproval":{this.handleApprovalRequest(e,"file");break}case"item/commandExecution/requestApproval":{this.handleApprovalRequest(e,"exec");break}case"item/permissions/requestApproval":{this.activeEventId&&this.emitCodexEvent("item/permissions/requestApproval",e),this.handleApprovalRequest(e,"permission");break}case"turn/completed":{this.handleTurnCompleted(s);break}case"error":{const i=s.message??JSON.stringify(s);o.error("codex-adapter",`Codex error: ${i}`);const n=s.willRetry===!0;i&&(this.turnError=i,n||(this.turnErrorIsRetryableOnly=!1)),this.activeEventId&&!n&&this.callbacks.sendRunError(this.activeEventId,this.activeSessionId??"",i);break}case"account/rateLimits/updated":{this.rateLimitSnapshot=this.parseRateLimitSnapshot(s),this.rateLimitSnapshot&&(o.info("codex-adapter",`Rate limits updated: primary=${this.rateLimitSnapshot.primary.usedPercent.toFixed(1)}% secondary=${this.rateLimitSnapshot.secondary.usedPercent.toFixed(1)}%`),this.callbacks.onRateLimitsUpdated?.(this.rateLimitSnapshot));break}case"thread/tokenUsage/updated":{const i=s.threadId,n=s.tokenUsage,r=n?.last;(!i||!n||!r)&&o.info("codex-adapter",`[cp-diagnose] token_usage payload_incomplete: method=thread/tokenUsage/updated hasThreadId=${String(!!i)} hasTokenUsage=${String(!!n)} hasLast=${String(!!r)} params=${JSON.stringify(s)}`),i&&n&&r&&(this.currentThreadTokenUsage={inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,cacheReadInputTokens:r.cachedInputTokens??0,cacheCreationInputTokens:0},o.info("codex-adapter",`[cp-diagnose] token_usage raw thread=${i}: ${JSON.stringify(n)}`),o.info("codex-adapter",`[cp-diagnose] token_usage parsed thread=${i}: ${JSON.stringify(this.currentThreadTokenUsage)}`),this.callbacks.onTokenUsageUpdated?.(this.currentThreadTokenUsage),this.publishContextWindowSnapshot());break}default:break}}captureContextWindowFromPayload(e,t){const s=["model_context_window","modelContextWindow","context_window_size","contextWindowSize"],i=this.findNumericField(t,s);if(i==null||i<=0){const n=this.probeContextWindowFields(t,s);n.foundAnyCandidateField&&o.info("codex-adapter",`[cp-diagnose] context_window missing_or_invalid: method=${e??"-"} matchedFields=${n.matchedFields.join(",")||"-"} raw=${n.rawValues.join(",")||"-"} extracted=${String(i)}`);return}this.currentModelContextWindow!==i&&(this.currentModelContextWindow=i,o.info("codex-adapter",`[cp-diagnose] context_window updated: method=${e??"-"} size=${i}`),this.publishContextWindowSnapshot())}probeContextWindowFields(e,t){const s=[],i=[],n=r=>{if(!r||typeof r!="object")return;if(Array.isArray(r)){for(const h of r)n(h);return}const a=r;for(const h of t)Object.prototype.hasOwnProperty.call(a,h)&&(s.push(h),i.push(String(a[h])));for(const h of Object.values(a))n(h)};return n(e),{foundAnyCandidateField:s.length>0,matchedFields:s,rawValues:i}}findNumericField(e,t){if(!e||typeof e!="object")return null;const s=e;for(const i of t){const n=s[i];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){const r=Number(n);if(Number.isFinite(r))return r}}for(const i of Object.values(s)){if(Array.isArray(i)){for(const r of i){const a=this.findNumericField(r,t);if(a!=null)return a}continue}const n=this.findNumericField(i,t);if(n!=null)return n}return null}buildContextWindowSnapshot(){const e=this.currentModelContextWindow;if(!e||e<=0)return o.debug("codex-adapter",`[cp-diagnose] context_window snapshot skipped: invalid size=${String(e)}`),null;const t=this.currentThreadTokenUsage,s=t?t.inputTokens+t.outputTokens:null,i=s==null?null:Math.max(0,e-s),n=s==null?null:Math.min(100,s/e*100),r=s==null?null:Math.max(0,100-(n??0));return o.info("codex-adapter",`[cp-diagnose] context_window computed: threadId=${this.threadId??"-"} size=${e} usedTokens=${String(s)} usedPercentage=${String(n)}`),{sizeTokens:e,usedTokens:s,remainingTokens:i,usedPercentage:n,remainingPercentage:r,source:"codex:model_context_window"}}publishContextWindowSnapshot(){const e=this.buildContextWindowSnapshot();this.callbacks.onContextWindowUpdated?.(e),this.maybeScheduleAutoCompact(e)}maybeScheduleAutoCompact(e){const t=e?.usedPercentage;typeof t!="number"||t<H||this.pendingAutoCompact||this.compacting||(this.pendingAutoCompact=!0,o.info("codex-adapter",`[auto-compact] context_window usedPercentage=${t.toFixed(1)}% >= ${H}%, scheduling compact`),this.tryRunPendingAutoCompact())}tryRunPendingAutoCompact(){this.pendingAutoCompact&&(this.stopped||!this.alive||this.currentTurnId||this.compacting||(this.pendingAutoCompact=!1,this.execCommand("compact","",this.activeSessionId??"").then(e=>{o.info("codex-adapter",`[auto-compact] compact done status=${e.status} msg=${e.message??""}`),e.status==="failed"&&/agent busy/i.test(e.message??"")&&(this.pendingAutoCompact=!0)}).catch(e=>{o.warn("codex-adapter",`[auto-compact] compact error: ${e instanceof Error?e.message:e}`)})))}parseRateLimitSnapshot(e){try{const s=e.rateLimitsByLimitId?.codex??e.rateLimits??e,i=s.primary,n=s.secondary,r=s.credits,a=c=>{if(typeof c=="number"&&Number.isFinite(c))return c;if(typeof c=="string"){const f=Number(c);if(Number.isFinite(f))return f}return 0},h=c=>typeof c=="boolean"?c:typeof c=="string"?c.toLowerCase()==="true":!1,m=c=>{if(c==null)return null;if(typeof c=="string"){const f=c.trim();if(!f)return null;const b=Number(f);return Number.isFinite(b)&&b>1e9?new Date(b*1e3).toISOString():f}if(typeof c=="number"&&Number.isFinite(c)&&c>0){const f=c>1e12?c/1e3:c;return new Date(f*1e3).toISOString()}return null},g=c=>{const f=c.resets_in_seconds??c.resetsInSeconds,b=typeof f=="number"||typeof f=="string"?Number(f):NaN;return!Number.isFinite(b)||b<=0?null:new Date(Date.now()+b*1e3).toISOString()},p=c=>({usedPercent:a(c.used_percent??c.usedPercent),windowMinutes:a(c.window_minutes??c.windowDurationMins??c.windowMinutes),resetsAt:m(c.resets_at??c.resetsAt)??g(c)}),u=()=>({usedPercent:0,windowMinutes:0,resetsAt:null}),v=()=>{const c=[];if(i&&c.push(i),n&&c.push(n),Array.isArray(s.windows))for(const f of s.windows)f&&typeof f=="object"&&c.push(f);return c.map(p).filter(f=>f.windowMinutes>0)},I=(c,f,b)=>{const P=c.filter(S=>b(S.windowMinutes));return P.length===0?null:P.reduce((S,$)=>Math.abs($.windowMinutes-f)<Math.abs(S.windowMinutes-f)?$:S)},_=v(),w=_.length>0?{primary:I(_,300,c=>c<1440)??u(),secondary:I(_,10080,c=>c>=1440)??u()}:i||n?{primary:i?p(i):u(),secondary:n?p(n):u()}:null;return w?{primary:w.primary,secondary:w.secondary,credits:r?{hasCredits:h(r.has_credits??r.hasCredits),unlimited:h(r.unlimited),balance:r.balance==null?null:a(r.balance)}:{hasCredits:!1,unlimited:!1,balance:null}}:null}catch{return null}}handleApprovalRequest(e,t){const s=e.id;if(s==null)return;const i=e.method,n=`${s}`.trim(),r=`codex_${B(this.activeSessionId??"")}_${B(n)}`;if(this.approvalPolicy==="never"){this.sendApprovalDecision(s,"accept");return}this.activeEventId&&this.emitCodexEvent(i,e),this.pendingApprovals.set(r,{approvalId:r,approvalCommandId:n,sourceEventId:this.activeEventId??"",requestId:s,kind:t}),o.info("codex-adapter",`Pending approval stored: ${r} (kind=${t})`),this.clearIdleTimer(),this.stopComposing()}resolvePendingApproval(e){const t=e.params??{},s=x(t.approval_id,t.approvalId);if(s)return this.pendingApprovals.get(s)??null;const i=x(t.approval_command_id,t.approvalCommandId);if(i){for(const[,n]of this.pendingApprovals)if(n.approvalCommandId===i)return n}return null}sendApprovalDecision(e,t){if(e==null||!this.process?.stdin)return;const s={jsonrpc:"2.0",id:e,result:{decision:t}};this.process.stdin.write(`${JSON.stringify(s)}
4
- `)}armCompactionFallback(){this.compacting&&(this.compactingTimer&&clearTimeout(this.compactingTimer),this.compactingTimer=setTimeout(()=>{o.warn("codex-adapter","Compaction fallback fired: turn/completed not received within timeout, treating as stuck and releasing deferred events"),this.currentTurnId=null,this.finishCompaction("fallback-timeout")},ge),this.compactingTimer.unref?.())}finishCompaction(e){if(!this.compacting)return;this.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null);const t=this.compactionDeferred.splice(0);o.info("codex-adapter",`Compaction finished (${e}); replaying ${t.length} deferred events`);for(const i of t)this.deliverInboundEvent(i);const s=this.compactionDoneResolver;this.compactionDoneResolver=null,s?.()}handleTurnCompleted(e){if(this.currentTurnId=null,this.stopComposing(),this.activeEventId){const t=this.activeEventId,s={event_id:t,session_id:this.activeSessionId??"",thread_id:this.threadId??void 0,codex_event_type:"codex",codex_method:"turn/completed",codex_sequence:++this.codexSequence,codex_payload:e,codex_at:new Date().toISOString()},i=this.turnError,n=this.turnErrorIsRetryableOnly,r=this.turnHasVisibleOutput;this.turnError=null,this.turnErrorIsRetryableOnly=!0,this.turnHasVisibleOutput=!1;const a=!!i&&!(n&&r);this.callbacks.sendCodexEventReliable?(this.clearActive({runPendingAutoCompact:!1}),this.callbacks.sendCodexEventReliable(s).then(()=>{this.callbacks.sendEventResult(t,a?"failed":"responded",a?i??void 0:void 0),this.tryRunPendingAutoCompact()}).catch(h=>{o.error("codex-adapter",`sendCodexEventReliable failed event=${t}: ${h}`),this.callbacks.sendCodexEvent(s),this.callbacks.sendEventResult(t,a?"failed":"responded",a?i??void 0:void 0),this.tryRunPendingAutoCompact()})):(this.callbacks.sendCodexEvent(s),this.callbacks.sendEventResult(t,a?"failed":"responded",a?i??void 0:void 0),this.clearActive())}this.compacting&&this.finishCompaction("turn-completed")}emitCodexEvent(e,t){this.activeEventId&&this.callbacks.sendCodexEvent({event_id:this.activeEventId,session_id:this.activeSessionId??"",thread_id:this.threadId??void 0,codex_event_type:"codex",codex_method:e,codex_sequence:++this.codexSequence,codex_payload:t,codex_at:new Date().toISOString()})}startComposing(){}stopComposing(){}async sendRequest(e,t,s=3e4){return new Promise((i,n)=>{if(!this.process?.stdin){n(new Error("Codex process not available"));return}const r=++this.requestId,a={jsonrpc:"2.0",id:r,method:e,params:t??{}},h=setTimeout(()=>{this.pendingRequests.delete(String(r)),n(new Error(`Request timeout: ${e}`))},s);this.pendingRequests.set(String(r),{resolve:g=>{g.error?n(new Error(`JSON-RPC error: ${g.error.message}`)):i(g.result)},reject:n,timer:h});const m=JSON.stringify(a);this.process.stdin.write(`${m}
1
+ import{execFileSync as O}from"node:child_process";import{createInterface as G}from"node:readline";import{EventEmitter as L}from"node:events";import{stat as N}from"node:fs/promises";import{join as C,resolve as X}from"node:path";import{fileURLToPath as Y}from"node:url";import{homedir as K}from"node:os";import{syncDefaultSkillsToDir as Z}from"../../default-skills/index.js";import{resolveCommandPath as Q,spawnCommand as ee,killProcessGroup as D,hasChildProcesses as te}from"../../core/runtime/spawn.js";import{InternalApiServer as ie}from"../../core/mcp/internal-api-server.js";import{log as o}from"../../core/log/index.js";import{resolveClientVersion as se}from"../../core/util/client-version.js";import{isUserVisibleAgentMessagePhase as ne}from"../../core/util/codex-output-policy.js";import{SessionBindingStore as re}from"../../core/persistence/session-binding-store.js";import{ensureCodexProjectTrusted as oe,isCodexCommand as ae,readCodexProviderSettings as k}from"./codex-trust.js";import{checkCodexSessionActivity as de}from"./session-activity.js";import{findRolloutFile as ce}from"./rollout-locator.js";import{checkCodexLock as j}from"./lock-monitor.js";import{resolveCliPath as le,getCliVersion as he}from"../../core/util/cli-probe.js";import{scanSkills as ue}from"../claude/skill-scanner.js";const pe=60*1e3,fe=600*1e3,me=5*1e3,F=2,ge=20,ve=8e3,H=32*1024,q=80,xe=120*1e3,Ie=[{id:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",defaultReasoningEffort:null,supportedReasoningEfforts:[],defaultServiceTier:null,serviceTiers:[],isDefault:!0}],U=[{id:"default",displayName:"Default"},{id:"plan",displayName:"Plan"}];function z(a,e){const t=String(a??"").trim()||"codex",s=Q(t,e);if(s!==t)return s;const i=process.platform==="win32"?[]:["/opt/homebrew/bin/codex","/usr/local/bin/codex","/usr/bin/codex"],n=process.platform!=="win32"?[]:[C(process.env.LOCALAPPDATA??"","npm","codex.cmd"),C(process.env.APPDATA??"","npm","codex.cmd"),C(process.env.LOCALAPPDATA??"","Programs","codex","codex.exe")],r=[...i,...n];for(const d of r)try{return require("node:fs").accessSync(d,require("node:fs").constants.X_OK),d}catch{continue}return o.warn("codex-adapter",`resolveCodexCommandPath: failed to resolve "${t}". envPath=${e?"provided":"missing (using process.env.PATH)"}. fallbacks tried: [${r.join(", ")}]`),t}class M extends L{type="codex";config;callbacks;process=null;alive=!1;stopped=!1;internalApi=null;bridgeStatus="starting";pendingRequests=new Map;requestId=0;threadId=null;initialized=!1;cwd;approvalPolicy;sandboxMode;model;collaborationMode;reasoningEffort;serviceTier;idleTimer=null;lastProgressAt=0;lastIdleCheckAt=0;idleNoProgressCount=0;inFlightToolOps=0;pendingApprovals=new Map;needsHistoryInjection=!1;lastInjectedSessionId=null;identityInjectedThreadId=null;bindingStore=null;aibotSessionId="";threadResumePending=!1;autoTrustProject="auto";codexHome;codexModelOptions=[];codexModelOptionsCachedAt=0;static MODEL_CACHE_TTL_MS=3600*1e3;rateLimitSnapshot=null;currentThreadTokenUsage=null;currentModelContextWindow=null;constructor(e,t){super(),this.config=e,this.callbacks=t;const s=e.options??{};if(this.approvalPolicy=s.approvalPolicy??"never",this.sandboxMode=typeof s.sandboxMode=="string"&&s.sandboxMode.trim()&&s.sandboxMode.trim()!=="default"?s.sandboxMode.trim():void 0,this.aibotSessionId=String(s.aibotSessionId??"").trim(),this.bindingStore=s.bindingStore instanceof re?s.bindingStore:null,this.model=s.model,this.collaborationMode=s.collaborationMode,this.reasoningEffort=s.reasoningEffort,this.serviceTier=s.serviceTier,this.bindingStore&&this.aibotSessionId&&(this.model=this.model??this.bindingStore.getCodexModelId(this.aibotSessionId),this.collaborationMode=this.collaborationMode??this.bindingStore.getCodexModeId(this.aibotSessionId),this.reasoningEffort=this.reasoningEffort??this.bindingStore.getCodexReasoningEffort(this.aibotSessionId),this.serviceTier=this.serviceTier??this.bindingStore.getCodexServiceTier(this.aibotSessionId),this.sandboxMode=this.sandboxMode??this.bindingStore.getCodexSandboxMode(this.aibotSessionId)),this.autoTrustProject=typeof s.autoTrustProject=="boolean"?s.autoTrustProject:"auto",this.codexHome=typeof s.codexHome=="string"&&s.codexHome.trim()?s.codexHome.trim():void 0,this.cwd=this.resolveCwd(),this.bindingStore&&this.aibotSessionId){const i=this.bindingStore.getCodexThreadId(this.aibotSessionId);i&&(this.threadId=i,this.threadResumePending=!0)}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}return process.cwd()}async start(){await this.ensureProjectTrusted(),await this.startInternalApiAndRegisterMcp(),await this.spawnCodex(),await this.initializeHandshake(),await this.notifyBindingReadyWithContext(),o.info("codex-adapter",`Ready (pid=${this.process?.pid})`)}async ensureProjectTrusted(){if(this.shouldAutoTrustProject())try{const e=await oe(this.cwd,{codexHome:this.codexHome});e.changed&&o.info("codex-adapter",`Trusted Codex project ${this.cwd} in ${e.configPath}`)}catch(e){const t=e instanceof Error?e.message:String(e);throw o.error("codex-adapter",`Failed to trust Codex project ${this.cwd}: ${t}`),e}}async startInternalApiAndRegisterMcp(){try{this.internalApi=new ie,this.internalApi.setInvokeHandler(async(d,h,m,g)=>this.callbacks.agentInvoke(d,h,g)),await this.internalApi.start(0),o.info("codex-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),t={...process.env,...this.config.env},s=typeof t.PATH=="string"?t.PATH:void 0,i=z(this.config.command||"codex",s);try{O(i,["mcp","remove",e.name],{env:t,timeout:1e4,stdio:"ignore"})}catch{}O(i,["mcp","add",e.name,"--",e.command,...e.args],{env:t,timeout:1e4,stdio:"ignore"}),o.info("codex-adapter",`Registered MCP server: ${e.name}`);const n=C(K(),".codex","skills"),r=Z(n);r.length>0&&o.info("codex-adapter",`Synced connector skills to ${n}: [${r.join(", ")}]`)}catch(e){o.warn("codex-adapter",`Failed to register MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`)}}shouldAutoTrustProject(){return this.autoTrustProject===!1?!1:this.autoTrustProject===!0?!0:ae(this.config.command)}notifyBindingReady(){!this.aibotSessionId||!this.cwd||this.callbacks.sendUpdateBindingCard(this.aibotSessionId,"ready",this.cwd)}async notifyBindingReadyWithContext(){if(!(!this.aibotSessionId||!this.cwd))try{this.callbacks.sendUpdateBindingCard(this.aibotSessionId,"ready",this.cwd,await this.buildToolbarContextResult("binding_ready"))}catch(e){o.warn("codex-adapter",`Failed to attach toolbar context to binding update: ${e instanceof Error?e.message:String(e)}`),this.notifyBindingReady()}}externalProviderCheckedAt=0;externalProviderCached=!1;static EXTERNAL_PROVIDER_CACHE_TTL_MS=60*1e3;isExternalProvider(){const e=Date.now();if(e-this.externalProviderCheckedAt<M.EXTERNAL_PROVIDER_CACHE_TTL_MS)return this.externalProviderCached;const t=k(this.codexHome);return this.externalProviderCached=!!(t.baseUrl&&W(t.baseUrl)),this.externalProviderCheckedAt=e,this.externalProviderCached}effectiveServiceTier(){if(!this.serviceTier||this.isExternalProvider())return;const e=this.getModelOption(this.currentModelId());if(!(e&&!e.serviceTiers.some(t=>t.id===this.serviceTier)))return this.serviceTier}getEffortMeta(){if(this.isExternalProvider())return{};const e=this.currentModelId(),t=this.getModelOption(e),s={},i=t?.supportedReasoningEfforts??[];i.length>0&&(s.available_efforts=i,s.reasoning_effort=this.reasoningEffort??t?.defaultReasoningEffort??null);const n=t?.serviceTiers??[];return n.length>0&&(s.available_service_tiers=n,s.service_tier=this.effectiveServiceTier()??t?.defaultServiceTier??null),s}async stop(){this.stopped=!0,this.alive=!1,this.stopComposing(),this.clearIdleTimer(),this.rejectAllPending("adapter stopped"),this.pendingAutoCompact=!1,this.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null);for(const t of this.compactionDeferred.splice(0))this.callbacks.sendEventResult(t.event_id,"failed","adapter stopped");for(const t of this.steerDeferred.splice(0))this.callbacks.sendEventResult(t.event_id,"failed","adapter stopped");this.internalApi&&(await this.internalApi.stop(),this.internalApi=null);const e=this.process;if(this.process=null,e?.pid&&typeof e.once=="function")D(e,"SIGTERM"),await Promise.race([new Promise(s=>{e.once("exit",()=>s(!0))}),new Promise(s=>{setTimeout(()=>s(!1),5e3)})])||D(e,"SIGKILL");else if(e)try{e.kill("SIGTERM")}catch{}}isAlive(){return this.alive}async createSession(e){if(this.initialized||await this.initializeHandshake(),this.threadId||await this.startNewThread(),!this.threadId)throw new Error("Failed to create session: thread ID is missing");return await this.notifyBindingReadyWithContext(),this.threadId}async resumeSession(e,t){await this.ensureThreadResumed()}async destroySession(e){this.threadId=null,this.threadResumePending=!1,this.persistThreadId(void 0)}sendPrompt(e){const t=new R(e.adapterSessionId);return this.runTurn(e,t).catch(s=>{t.emitError(s instanceof Error?s:new Error(String(s)))}),t}async cancel(e){if(this.threadId)try{await this.sendRequest("turn/interrupt",{threadId:this.threadId,turnId:this.currentTurnId??""},5e3)}catch{}}setPermissionHandler(e){this.permissionHandler=e}permissionHandler=null;async ping(e){if(!this.alive||!this.process)return!1;if(!this.process.pid){const t=!!(this.process.stdin&&!this.process.stdin.destroyed),s=!!(this.process.stdout&&!this.process.stdout.destroyed);return t&&s}if(!this.process.stdin||this.process.stdin.destroyed)return!!(this.process.stdout&&!this.process.stdout.destroyed);try{const t=++this.requestId,s={jsonrpc:"2.0",id:t,method:"ping",params:{}};return await new Promise(i=>{const n=setTimeout(()=>{this.pendingRequests.delete(String(t)),i(!1)},e);this.pendingRequests.set(String(t),{resolve:()=>i(!0),reject:()=>i(!1),timer:n}),this.process.stdin.write(`${JSON.stringify(s)}
2
+ `)})}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.currentTurnId!==null||this.compacting,sessions:this.threadId?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}clearActiveEventForShutdown(){this.clearIdleTimer(),this.activeEventId=null}setModel(e){this.model=e,this.persistCodexContext(),o.info("codex-adapter",`Model set to: ${e}`)}setMode(e){const t=_(e);if(!t){o.info("codex-adapter",`Ignoring unsupported mode: ${e}`);return}this.collaborationMode=t,this.persistCodexContext(),o.info("codex-adapter",`Mode set to: ${t}`)}setReasoningEffort(e){this.reasoningEffort=e,this.persistCodexContext(),o.info("codex-adapter",`Reasoning effort set to: ${e}`)}setServiceTier(e){const t=e.trim();this.serviceTier=t.toLowerCase()==="default"?void 0:t,this.persistCodexContext(),o.info("codex-adapter",`Service tier set to: ${this.serviceTier??"default"}`)}setSandboxMode(e){this.sandboxMode=e,this.persistCodexContext(),o.info("codex-adapter",`Sandbox mode set to: ${e} (applied on next restart)`)}async threadCompact(){if(!this.threadId)throw new Error("No active thread");return this.sendRequest("thread/compact/start",{threadId:this.threadId},12e4)}async threadRollback(e){if(!this.threadId)throw new Error("No active thread");return this.sendRequest("thread/rollback",{threadId:this.threadId,numTurns:e},1e4)}getThreadId(){return this.threadId}getMcpConfig(){if(!this.internalApi)return null;const e=X(Y(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?te(e,[e]):!1}onAgentProfileChanged(){this.identityInjectedThreadId!==null&&(o.info("codex-adapter",`agent profile changed; clearing identity-injected thread record (was ${this.identityInjectedThreadId})`),this.identityInjectedThreadId=null)}async probe(e){const t=this.config.command||"codex",s=await le(t),i=s!==null;let n=null,r;if(i){const I=await he(t);n=I.version,I.error&&(r=I.error)}else r={code:"cli_not_found",message:`command not found: ${t}`};const h=k().baseUrl??null,m=this.currentModelId()||null,g=this.getStatus(),p=e?.conversation?{attempted:!0,ok:!1,latency_ms:null,error:{code:"unsupported",message:"codex does not support minimal prompt probe"}}:{attempted:!1,ok:!1,latency_ms:null},u=await this.probeSessionRecord(),v=j({codexHome:this.codexHome});return{cli:{command:t,installed:i,path:s,version:n,...r?{error:r}:{}},conversation:p,config:{model:m,base_url:h,source:{model:m?"runtime":"unknown",base_url:h?"file":"unknown"}},process:{started:!!this.process,alive:g.alive,busy:g.busy},session:u,lock:{present:v.present,locked:v.locked,stale:v.stale,path:v.path}}}async probeSessionRecord(){const e=this.threadId?ce(this.threadId,this.codexHome):null;if(!e)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const t=await N(e);return{recordPath:e,lastActivityMs:t.mtimeMs,freshMs:Date.now()-t.mtimeMs}}catch{return{recordPath:e,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"compact",description:"Compact thread to reduce context size"},{name:"model",description:"List or set model",args:"[model_id]"},{name:"mode",description:"List or set collaboration mode",args:"[default|plan]"},{name:"rollback",description:"Roll back thread turns",args:"[num_turns]"},{name:"interrupt",description:"Interrupt current turn"},{name:"rate_limits",description:"Show current rate limits"},{name:"status",description:"Show thread and session status"},{name:"skills",description:"List available skills"}]}async execCommand(e,t,s){try{switch(e){case"compact":{if(!this.threadId)return{status:"failed",message:"No active thread"};if(this.compacting)return{status:"failed",message:"Compaction already in progress"};if(this.currentTurnId&&(await this.cancel(this.threadId).catch(()=>{}),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","compacting"),this.clearActive()),await this.ensureThreadResumed(),this.currentTurnId)return{status:"failed",message:"agent busy"};if(this.needsHistoryInjection)return{status:"failed",message:"The session has expired and there is no history to compact. Please send a new message and try again."};this.compacting=!0;const i=new Promise(n=>{this.compactionDoneResolver=n});try{return await this.threadCompact(),this.armCompactionFallback(),await i,{status:"ok",message:"Thread compacted"}}catch(n){this.finishCompaction("compact-error");const r=n instanceof Error?n.message:String(n);if(/thread.*(not found|not exist|unknown|invalid)/i.test(r)||/not found.*thread/i.test(r))return this.threadId=null,this.persistThreadId(void 0),{status:"failed",message:"The session has expired and there is no history to compact. Please send a new message and try again."};throw n}}case"model":{const i=t.trim();return i?this.getModelOptions().some(r=>r.id===i)?(this.setModel(i),{status:"ok",message:`Model set to ${i}`}):{status:"failed",message:`Unknown model: ${i}`}:{status:"ok",message:`Current: ${this.currentModelId()}`,data:{models:this.getModelOptions()}}}case"mode":{const i=t.trim();if(i){const n=_(i);return n?(this.setMode(n),{status:"ok",message:`Mode set to ${n}`}):{status:"failed",message:`Unknown mode: ${i}. Supported: default, plan`}}return{status:"ok",message:`Current: ${this.collaborationMode??"default"}`,data:{modes:U}}}case"rollback":{if(!this.threadId)return{status:"failed",message:"No active thread"};const i=Math.max(1,parseInt(t.trim(),10)||1);return this.currentTurnId&&(await this.cancel(this.threadId).catch(()=>{}),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","rolled back"),this.clearActive()),await this.threadRollback(i),{status:"ok",message:`Rolled back ${i} turn(s)`}}case"interrupt":return this.threadId?(await this.cancel(this.threadId),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Turn interrupted"}):{status:"failed",message:"No active thread"};case"rate_limits":return{status:"ok",message:this.rateLimitSnapshot?`Primary: ${this.rateLimitSnapshot.primary.usedPercent.toFixed(1)}%, Secondary: ${this.rateLimitSnapshot.secondary.usedPercent.toFixed(1)}%`:"Rate limits not available",data:{rateLimits:this.rateLimitSnapshot}};case"status":return{status:"ok",message:`Thread: ${this.threadId??"none"}, Model: ${this.currentModelId()}, Mode: ${this.collaborationMode??"default"}`,data:{threadId:this.threadId,model:this.currentModelId(),mode:this.collaborationMode??"default",cwd:this.cwd,alive:this.alive}};case"skills":{const i=ue({mode:"codex",projectDir:this.cwd}),n=i.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""}: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
3
+ `):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${e}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}async handleLocalAction(e){const t=e.action_type??"",s=e.params??{};switch(o.info("codex-adapter",`handleLocalAction action_type=${t} action_id=${e.action_id} session_id=${s.session_id??""}`),t){case"set_model":{const i=x(l(s.model_id),l(s.modelId),l(s.value));return i&&this.setModel(i),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("model_set")),{handled:!0,kind:"set_model"}}case"set_mode":{const i=s.mode_id;return i&&this.setMode(i),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("mode_set")),{handled:!0,kind:"set_mode"}}case"set_reasoning_effort":{const i=x(l(s.reasoning_effort),l(s.reasoning_eff),l(s.effort));return i&&this.setReasoningEffort(i),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("effort_set",!1)),{handled:!0,kind:"set_reasoning_effort"}}case"set_service_tier":{const i=x(l(s.service_tier),l(s.serviceTier),l(s.value));return i&&this.setServiceTier(i),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("service_tier_set",!1)),{handled:!0,kind:"set_service_tier"}}case"set_sandbox_mode":{const i=x(l(s.sandbox_mode),l(s.sandboxMode),l(s.value));return i&&this.setSandboxMode(i),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("sandbox_mode_set",!1)),{handled:!0,kind:"set_sandbox_mode"}}case"thread_compact":{o.info("codex-adapter",`thread_compact start action_id=${e.action_id} threadId=${this.threadId}`),this.currentTurnId&&(await this.cancel(this.threadId).catch(()=>{}),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","compacting"),this.clearActive());try{if(await this.ensureThreadResumed(),this.needsHistoryInjection)return o.info("codex-adapter",`thread_compact aborted: thread expired, new thread created action_id=${e.action_id}`),this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"thread_expired","The session has expired and there is no history to compact. Please send a new message and try again."),{handled:!0,kind:"thread_compact"};this.compacting=!0;const i=new Promise(n=>{this.compactionDoneResolver=n});await this.threadCompact(),this.armCompactionFallback(),await i,o.info("codex-adapter",`thread_compact done action_id=${e.action_id}`),this.callbacks.sendLocalActionResult(e.action_id,"ok")}catch(i){this.finishCompaction("compact-error");const n=i instanceof Error?i.message:String(i);/thread.*(not found|not exist|unknown|invalid)/i.test(n)||/not found.*thread/i.test(n)?(o.warn("codex-adapter",`thread_compact thread expired, resetting threadId action_id=${e.action_id} err=${n}`),this.threadId=null,this.persistThreadId(void 0),this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"thread_expired","The session has expired and there is no history to compact. Please send a new message and try again.")):(o.info("codex-adapter",`thread_compact failed action_id=${e.action_id} err=${n}`),this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,void 0,n))}return{handled:!0,kind:"thread_compact"}}case"get_context":return this.callbacks.sendLocalActionResult(e.action_id,"ok",{threadId:this.threadId,model:this.model,mode:this.collaborationMode,approvalPolicy:this.approvalPolicy,cwd:this.cwd,...await this.buildToolbarContextResult("context")}),{handled:!0,kind:"get_context"};case"exec_approve":case"file_approve":{const i=this.resolvePendingApproval(e);if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:t};const n=s.decision||"allow-once",r=be[n]??"accept";return this.sendApprovalDecision(i.requestId,r),this.pendingApprovals.delete(i.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.approvalId,approval_command_id:i.approvalCommandId,decision:n}),this.resumeAfterApproval(e,s,i),{handled:!0,kind:t}}case"exec_reject":case"file_reject":{const i=this.resolvePendingApproval(e);return i?(this.sendApprovalDecision(i.requestId,"deny"),this.pendingApprovals.delete(i.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.approvalId,approval_command_id:i.approvalCommandId,decision:"deny"}),this.resumeAfterApproval(e,s,i),{handled:!0,kind:t}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:t})}case"permission_approve":{const i=this.resolvePendingApproval(e);return!i||i.kind!=="permission"?(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That permission approval request is no longer pending."),{handled:!0,kind:t}):(this.sendApprovalDecision(i.requestId,"accept"),this.pendingApprovals.delete(i.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.approvalId,decision:"approve"}),this.resumeAfterApproval(e,s,i),{handled:!0,kind:t})}case"permission_reject":{const i=this.resolvePendingApproval(e);return!i||i.kind!=="permission"?(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That permission approval request is no longer pending."),{handled:!0,kind:t}):(this.sendApprovalDecision(i.requestId,"deny"),this.pendingApprovals.delete(i.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.approvalId,decision:"deny"}),this.resumeAfterApproval(e,s,i),{handled:!0,kind:t})}case"turn_interrupt":{try{await this.cancel(this.threadId??""),this.callbacks.sendLocalActionResult(e.action_id,"ok")}catch(i){this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,void 0,i instanceof Error?i.message:String(i))}return{handled:!0,kind:"turn_interrupt"}}case"thread_rollback":{const i=Number(s.numTurns??s.num_turns??1);if(!this.threadId)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"no_thread","No active thread"),{handled:!0,kind:"thread_rollback"};this.currentTurnId&&(await this.cancel(this.threadId).catch(()=>{}),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","rolled back"),this.clearActive());try{await this.threadRollback(i),this.callbacks.sendLocalActionResult(e.action_id,"ok",{numTurns:i})}catch(n){this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,void 0,n instanceof Error?n.message:String(n))}return{handled:!0,kind:"thread_rollback"}}case"get_rate_limits":{const i=this.rateLimitSnapshot,n=this.buildContextWindowSnapshot(),r=Date.now(),d=this.currentThreadTokenUsage;return i?o.info("codex-adapter",`[rate-limits] responding: primary=${i.primary.usedPercent.toFixed(1)}% window=${i.primary.windowMinutes}min resetsAt=${i.primary.resetsAt} secondary=${i.secondary.usedPercent.toFixed(1)}% window=${i.secondary.windowMinutes}min resetsAt=${i.secondary.resetsAt}`):o.info("codex-adapter","[rate-limits] responding: no rateLimitSnapshot available"),o.debug("codex-adapter",`[cp-diagnose] get_rate_limits: threadId=${this.threadId??"-"} contextWindow=${JSON.stringify(n)} tokenUsage=${JSON.stringify(d)}`),this.callbacks.sendLocalActionResult(e.action_id,"ok",{adapterType:"codex",available:i!==null,cached:!1,sampledAt:r,rateLimits:i,contextWindow:n,tokenUsage:d}),{handled:!0,kind:"get_rate_limits"}}default:return{handled:!1,kind:""}}}async buildToolbarContextResult(e,t=!0){t&&await this.refreshCodexModelOptions();const s=_(this.collaborationMode)??"default",i=this.currentModelId(),n=this.getModelOption(i),r=this.getModelOptions(),d=U,h=this.reasoningEffort??n?.defaultReasoningEffort??null,m=n?.supportedReasoningEfforts??[],g=this.effectiveServiceTier()??n?.defaultServiceTier??null,p=n?.serviceTiers??[],u=this.isExternalProvider(),v=u?[]:m,I=u?null:h,y=u?[]:p,w=u?null:g,c={outcome:e,session_context:{modelId:i,modeId:s,reasoningEffort:I,serviceTier:w,approvalPolicy:this.approvalPolicy,sandboxMode:this.sandboxMode??null},model_id:i,mode_id:s,currentModelId:i,currentModeId:s,available_models:r,available_modes:d,available_efforts:v,availableModels:r,availableModes:d,reasoning_effort:I,available_service_tiers:y,service_tier:w,sandbox_mode:this.sandboxMode??null,models:r.map(f=>({modelId:f.id,name:f.displayName})),modes:d.map(f=>({id:f.id,name:f.displayName}))};return this.rateLimitSnapshot&&(c.rate_limit_primary_percent=this.rateLimitSnapshot.primary.usedPercent,c.rate_limit_secondary_percent=this.rateLimitSnapshot.secondary.usedPercent,c.rate_limit_primary_window_min=this.rateLimitSnapshot.primary.windowMinutes,c.rate_limit_secondary_window_min=this.rateLimitSnapshot.secondary.windowMinutes),c}currentModelId(){const e=String(this.model??"").trim();if(e)return e;const t=this.getModelOptions();return t.find(s=>s.isDefault)?.id??t[0]?.id??""}getModelOption(e){const t=e.trim().toLowerCase();return this.getModelOptions().find(s=>s.id.trim().toLowerCase()===t)}getModelOptions(){const e=this.config.options??{},t=e.available_models??e.availableModels??e.models,s=Se(t),i=this.codexModelOptions,n=[],r=String(this.model??"").trim(),d=r&&!i.some(p=>p.id.trim().toLowerCase()===r.toLowerCase()),h=i.length>0?i:d?[]:Ie;if(r){const p=[...i,...s].find(u=>u.id.trim().toLowerCase()===r.toLowerCase());n.push({id:r,displayName:p?.displayName??T(r),defaultReasoningEffort:p?.defaultReasoningEffort??null,supportedReasoningEfforts:p?.supportedReasoningEfforts??[],defaultServiceTier:p?.defaultServiceTier??null,serviceTiers:p?.serviceTiers??[],isDefault:p?.isDefault??!1})}n.push(...s),n.push(...h);const m=[],g=new Set;for(const p of n){const u=p.id.trim(),v=u.toLowerCase();!u||g.has(v)||(g.add(v),m.push({id:u,displayName:p.displayName.trim()||u,defaultReasoningEffort:p.defaultReasoningEffort,supportedReasoningEfforts:[...p.supportedReasoningEfforts],defaultServiceTier:p.defaultServiceTier,serviceTiers:[...p.serviceTiers],isDefault:p.isDefault}))}return m}async refreshCodexModelOptions(){if(!this.initialized||!this.alive||!this.process?.stdin||Date.now()-this.codexModelOptionsCachedAt<M.MODEL_CACHE_TTL_MS)return;const e=k(this.codexHome);if(e.baseUrl&&W(e.baseUrl)){try{const t=await Ce(e.baseUrl,e.apiKey);if(t.length>0){this.codexModelOptions=B(t),this.codexModelOptionsCachedAt=Date.now(),o.info("codex-adapter",`Loaded ${t.length} models from external provider ${e.baseUrl}`);return}}catch(t){o.warn("codex-adapter",`External provider /v1/models failed (${t instanceof Error?t.message:String(t)}), falling back`)}this.codexModelOptions=[],this.codexModelOptionsCachedAt=Date.now();return}try{const t=[];let s;do{const i=await this.sendRequest("model/list",{cursor:s??null,includeHidden:!1,limit:100},15e3),n=Ee(i);t.push(...n.models),s=n.nextCursor}while(s);t.length>0&&(this.codexModelOptions=B(t),this.codexModelOptionsCachedAt=Date.now())}catch(t){o.warn("codex-adapter",`Failed to load Codex model list: ${t instanceof Error?t.message:String(t)}`)}}currentTurnId=null;compacting=!1;pendingAutoCompact=!1;compactionDeferred=[];steerDeferred=[];compactingTimer=null;compactionDoneResolver=null;activeEventId=null;activeSessionId=null;visibleAgentMessageIds=new Set;hiddenAgentMessageIds=new Set;agentMessagePhases=new Map;codexSequence=0;turnError=null;turnErrorIsRetryableOnly=!0;turnHasVisibleOutput=!1;deliverInboundEvent(e){if(this.compacting){o.info("codex-adapter",`Event ${e.event_id} deferred: compaction in progress`),this.compactionDeferred.push(e);return}const t=e.content;if(this.currentTurnId&&t.trim()){o.info("codex-adapter",`Event ${e.event_id}: steering active turn ${this.currentTurnId}`),this.steerTurn(t).catch(s=>{const i=s instanceof Error?s.message:String(s);if(o.info("codex-adapter",`Steer failed, falling through: ${i}`),!this.currentTurnId){this.startNewTurn(e,t);return}if(Re(i)){o.info("codex-adapter","Unsteerable turn detected, clearing active state and starting new turn"),this.clearActive(),this.startNewTurn(e,t);return}o.info("codex-adapter",`Steer failed but turn still active; deferring event ${e.event_id} for replay after turn ends`),this.steerDeferred.push(e)});return}if(this.currentTurnId){o.info("codex-adapter",`Event ${e.event_id} rejected: busy and empty content`),this.callbacks.sendEventResult(e.event_id,"failed","agent busy");return}this.startNewTurn(e,t)}startNewTurn(e,t){this.activeEventId=e.event_id,this.activeSessionId=e.session_id,this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.agentMessagePhases.clear(),this.codexSequence=0,this.startComposing();const s=this.threadId??"",i=new R(s),n={adapterSessionId:s,text:t,contextMessages:e.context_messages_json?JSON.parse(e.context_messages_json).map(r=>({senderId:r.sender_id??"unknown",content:r.content})):void 0};this.runTurn(n,i,e.event_id,e.session_id).catch(r=>{o.error("codex-adapter",`Turn failed: ${r}`),this.callbacks.sendEventResult(e.event_id,"failed",r instanceof Error?r.message:String(r)),this.clearActive()}),this.resetIdleTimer(e.event_id)}deliverStopEvent(e,t){this.activeEventId===e&&(this.cancel(this.threadId??"").catch(()=>{}),this.callbacks.sendEventResult(e,"canceled","stopped by user"),this.clearActive())}async spawnCodex(){const e={...process.env,...this.config.env},t=typeof e.PATH=="string"?e.PATH:void 0;t||o.warn("codex-adapter",`spawnCodex: env.PATH is missing! process.env.PATH=${process.env.PATH?"set":"missing"}, config.env=${JSON.stringify(this.config.env)}`);const s=z(this.config.command||"codex",t),i=we(this.config.args);this.sandboxMode&&i.push("-c",`sandbox_mode="${this.sandboxMode}"`),o.info("codex-adapter",`Spawning: ${s} ${i.join(" ")}`);try{if(!(await N(this.cwd)).isDirectory())throw new Error(`Bound path is not a directory: ${this.cwd}`)}catch(r){throw String(r?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${this.cwd}. Please rebind with /grix open <valid-directory>.`):r}const n=j({codexHome:this.codexHome});if(n.locked&&!n.stale)throw new Error(`Codex session appears locked by another process: ${n.path}`);n.stale&&o.warn("codex-adapter",`Ignoring stale Codex lock: ${n.path}`);try{this.process=ee(s,i,{env:e,cwd:this.cwd}).process}catch(r){throw o.error("codex-adapter",`Codex spawn threw: ${r}`),this.process=null,this.alive=!1,this.bridgeStatus="closed",r}this.process.on("error",r=>{o.error("codex-adapter",`Codex process spawn error: ${r}`),this.process=null,this.alive=!1,this.bridgeStatus="closed",this.clearIdleTimer(),this.rejectAllPending("spawn failed: "+(r instanceof Error?r.message:String(r))),this.stopComposing(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed","Codex process spawn failed"),this.activeEventId=null),this.emit("exit",1)}),this.process.on("exit",r=>{o.info("codex-adapter",`Codex process exited (code=${r})`),this.alive=!1,this.bridgeStatus="closed",this.clearIdleTimer(),this.rejectAllPending("process exited"),this.stopComposing(),this.emit("exit",r)}),this.process.stderr?.on("data",r=>{const d=r.toString().trim();d&&o.info("codex-adapter",`[codex stderr] ${d}`)}),this.bindStdout(),this.alive=!0}bindStdout(){if(!this.process?.stdout)return;this.process.stdout.setEncoding("utf8"),G({input:this.process.stdout}).on("line",t=>{if(!t.trim())return;let s;try{s=JSON.parse(t)}catch{o.error("codex-adapter",`Invalid JSON from Codex: ${t.slice(0,200)}`);return}if(this.bridgeStatus==="starting"&&(this.bridgeStatus="ready"),s.id!=null){const i=String(s.id),n=this.pendingRequests.get(i);if(n){clearTimeout(n.timer),this.pendingRequests.delete(i),n.resolve(s);return}}this.handleNotification(s)})}handleNotification(e){const t=e.method,s=e.params??{};switch(this.captureContextWindowFromPayload(t,s),this.activeEventId&&this.resetIdleTimer(this.activeEventId),this.activeEventId&&t&&t.startsWith("item/")&&!t.endsWith("/requestApproval")&&this.startComposing(),t){case"item/started":{const i=s.item,n=i?.id,r=i?.type,d=i?.phase;this.isLongRunningToolItemType(r)&&(this.inFlightToolOps+=1),r==="agentMessage"&&n&&(typeof d=="string"&&d.trim()?this.agentMessagePhases.set(n,d.trim().toLowerCase()):this.agentMessagePhases.delete(n),ne(d)?(this.visibleAgentMessageIds.add(n),this.hiddenAgentMessageIds.delete(n)):(this.hiddenAgentMessageIds.add(n),this.visibleAgentMessageIds.delete(n)));break}case"item/agentMessage/delta":{const i=s.delta,n=s.itemId;i&&this.activeEventId&&(!n||!this.hiddenAgentMessageIds.has(n))&&!this.shouldSuppressAgentMessageDeltaDuringToolRun(n)&&(this.turnHasVisibleOutput=!0,this.emitCodexEvent("item/agentMessage/delta",e));break}case"item/completed":{const i=s.item,n=i?.id,r=i?.type;this.isLongRunningToolItemType(r)&&(this.inFlightToolOps=Math.max(0,this.inFlightToolOps-1)),this.activeEventId&&r!=="agentMessage"&&(this.turnHasVisibleOutput=!0,this.emitCodexEvent("item/completed",e)),r==="agentMessage"&&n&&(this.visibleAgentMessageIds.delete(n),this.hiddenAgentMessageIds.delete(n),this.agentMessagePhases.delete(n));break}case"turn/started":{const n=s.turn?.id;n&&(this.currentTurnId=n,this.turnError=null,this.turnErrorIsRetryableOnly=!0,this.turnHasVisibleOutput=!1,o.info("codex-adapter",`Turn started: ${n}`),this.startComposing());break}case"item/fileChange/requestApproval":{this.handleApprovalRequest(e,"file");break}case"item/commandExecution/requestApproval":{this.handleApprovalRequest(e,"exec");break}case"item/permissions/requestApproval":{this.activeEventId&&this.emitCodexEvent("item/permissions/requestApproval",e),this.handleApprovalRequest(e,"permission");break}case"turn/completed":{this.handleTurnCompleted(s);break}case"error":{const i=s.message??JSON.stringify(s);o.error("codex-adapter",`Codex error: ${i}`);const n=s.willRetry===!0;i&&(this.turnError=i,n||(this.turnErrorIsRetryableOnly=!1)),this.activeEventId&&!n&&this.callbacks.sendRunError(this.activeEventId,this.activeSessionId??"",i);break}case"account/rateLimits/updated":{this.rateLimitSnapshot=this.parseRateLimitSnapshot(s),this.rateLimitSnapshot&&(o.info("codex-adapter",`Rate limits updated: primary=${this.rateLimitSnapshot.primary.usedPercent.toFixed(1)}% secondary=${this.rateLimitSnapshot.secondary.usedPercent.toFixed(1)}%`),this.callbacks.onRateLimitsUpdated?.(this.rateLimitSnapshot));break}case"thread/tokenUsage/updated":{const i=s.threadId,n=s.tokenUsage,r=n?.last;(!i||!n||!r)&&o.info("codex-adapter",`[cp-diagnose] token_usage payload_incomplete: method=thread/tokenUsage/updated hasThreadId=${String(!!i)} hasTokenUsage=${String(!!n)} hasLast=${String(!!r)} params=${JSON.stringify(s)}`),i&&n&&r&&(this.currentThreadTokenUsage={inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,cacheReadInputTokens:r.cachedInputTokens??0,cacheCreationInputTokens:0},o.info("codex-adapter",`[cp-diagnose] token_usage raw thread=${i}: ${JSON.stringify(n)}`),o.info("codex-adapter",`[cp-diagnose] token_usage parsed thread=${i}: ${JSON.stringify(this.currentThreadTokenUsage)}`),this.callbacks.onTokenUsageUpdated?.(this.currentThreadTokenUsage),this.publishContextWindowSnapshot());break}default:break}}captureContextWindowFromPayload(e,t){const s=["model_context_window","modelContextWindow","context_window_size","contextWindowSize"],i=this.findNumericField(t,s);if(i==null||i<=0){const n=this.probeContextWindowFields(t,s);n.foundAnyCandidateField&&o.info("codex-adapter",`[cp-diagnose] context_window missing_or_invalid: method=${e??"-"} matchedFields=${n.matchedFields.join(",")||"-"} raw=${n.rawValues.join(",")||"-"} extracted=${String(i)}`);return}this.currentModelContextWindow!==i&&(this.currentModelContextWindow=i,o.info("codex-adapter",`[cp-diagnose] context_window updated: method=${e??"-"} size=${i}`),this.publishContextWindowSnapshot())}probeContextWindowFields(e,t){const s=[],i=[],n=r=>{if(!r||typeof r!="object")return;if(Array.isArray(r)){for(const h of r)n(h);return}const d=r;for(const h of t)Object.prototype.hasOwnProperty.call(d,h)&&(s.push(h),i.push(String(d[h])));for(const h of Object.values(d))n(h)};return n(e),{foundAnyCandidateField:s.length>0,matchedFields:s,rawValues:i}}findNumericField(e,t){if(!e||typeof e!="object")return null;const s=e;for(const i of t){const n=s[i];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){const r=Number(n);if(Number.isFinite(r))return r}}for(const i of Object.values(s)){if(Array.isArray(i)){for(const r of i){const d=this.findNumericField(r,t);if(d!=null)return d}continue}const n=this.findNumericField(i,t);if(n!=null)return n}return null}buildContextWindowSnapshot(){const e=this.currentModelContextWindow;if(!e||e<=0)return o.debug("codex-adapter",`[cp-diagnose] context_window snapshot skipped: invalid size=${String(e)}`),null;const t=this.currentThreadTokenUsage,s=t?t.inputTokens+t.outputTokens:null,i=s==null?null:Math.max(0,e-s),n=s==null?null:Math.min(100,s/e*100),r=s==null?null:Math.max(0,100-(n??0));return o.info("codex-adapter",`[cp-diagnose] context_window computed: threadId=${this.threadId??"-"} size=${e} usedTokens=${String(s)} usedPercentage=${String(n)}`),{sizeTokens:e,usedTokens:s,remainingTokens:i,usedPercentage:n,remainingPercentage:r,source:"codex:model_context_window"}}publishContextWindowSnapshot(){const e=this.buildContextWindowSnapshot();this.callbacks.onContextWindowUpdated?.(e),this.maybeScheduleAutoCompact(e)}maybeScheduleAutoCompact(e){const t=e?.usedPercentage;typeof t!="number"||t<q||this.pendingAutoCompact||this.compacting||(this.pendingAutoCompact=!0,o.info("codex-adapter",`[auto-compact] context_window usedPercentage=${t.toFixed(1)}% >= ${q}%, scheduling compact`),this.tryRunPendingAutoCompact())}tryRunPendingAutoCompact(){this.pendingAutoCompact&&(this.stopped||!this.alive||this.currentTurnId||this.compacting||(this.pendingAutoCompact=!1,this.execCommand("compact","",this.activeSessionId??"").then(e=>{o.info("codex-adapter",`[auto-compact] compact done status=${e.status} msg=${e.message??""}`),e.status==="failed"&&/agent busy/i.test(e.message??"")&&(this.pendingAutoCompact=!0)}).catch(e=>{o.warn("codex-adapter",`[auto-compact] compact error: ${e instanceof Error?e.message:e}`)})))}parseRateLimitSnapshot(e){try{const s=e.rateLimitsByLimitId?.codex??e.rateLimits??e,i=s.primary,n=s.secondary,r=s.credits,d=c=>{if(typeof c=="number"&&Number.isFinite(c))return c;if(typeof c=="string"){const f=Number(c);if(Number.isFinite(f))return f}return 0},h=c=>typeof c=="boolean"?c:typeof c=="string"?c.toLowerCase()==="true":!1,m=c=>{if(c==null)return null;if(typeof c=="string"){const f=c.trim();if(!f)return null;const b=Number(f);return Number.isFinite(b)&&b>1e9?new Date(b*1e3).toISOString():f}if(typeof c=="number"&&Number.isFinite(c)&&c>0){const f=c>1e12?c/1e3:c;return new Date(f*1e3).toISOString()}return null},g=c=>{const f=c.resets_in_seconds??c.resetsInSeconds,b=typeof f=="number"||typeof f=="string"?Number(f):NaN;return!Number.isFinite(b)||b<=0?null:new Date(Date.now()+b*1e3).toISOString()},p=c=>({usedPercent:d(c.used_percent??c.usedPercent),windowMinutes:d(c.window_minutes??c.windowDurationMins??c.windowMinutes),resetsAt:m(c.resets_at??c.resetsAt)??g(c)}),u=()=>({usedPercent:0,windowMinutes:0,resetsAt:null}),v=()=>{const c=[];if(i&&c.push(i),n&&c.push(n),Array.isArray(s.windows))for(const f of s.windows)f&&typeof f=="object"&&c.push(f);return c.map(p).filter(f=>f.windowMinutes>0)},I=(c,f,b)=>{const P=c.filter(S=>b(S.windowMinutes));return P.length===0?null:P.reduce((S,$)=>Math.abs($.windowMinutes-f)<Math.abs(S.windowMinutes-f)?$:S)},y=v(),w=y.length>0?{primary:I(y,300,c=>c<1440)??u(),secondary:I(y,10080,c=>c>=1440)??u()}:i||n?{primary:i?p(i):u(),secondary:n?p(n):u()}:null;return w?{primary:w.primary,secondary:w.secondary,credits:r?{hasCredits:h(r.has_credits??r.hasCredits),unlimited:h(r.unlimited),balance:r.balance==null?null:d(r.balance)}:{hasCredits:!1,unlimited:!1,balance:null}}:null}catch{return null}}handleApprovalRequest(e,t){const s=e.id;if(s==null)return;const i=e.method,n=`${s}`.trim(),r=`codex_${J(this.activeSessionId??"")}_${J(n)}`;if(this.approvalPolicy==="never"){this.sendApprovalDecision(s,"accept");return}this.activeEventId&&this.emitCodexEvent(i,e),this.pendingApprovals.set(r,{approvalId:r,approvalCommandId:n,sourceEventId:this.activeEventId??"",requestId:s,kind:t}),o.info("codex-adapter",`Pending approval stored: ${r} (kind=${t})`),this.clearIdleTimer(),this.stopComposing()}resolvePendingApproval(e){const t=e.params??{},s=x(t.approval_id,t.approvalId);if(s)return this.pendingApprovals.get(s)??null;const i=x(t.approval_command_id,t.approvalCommandId);if(i){for(const[,n]of this.pendingApprovals)if(n.approvalCommandId===i)return n}return null}sendApprovalDecision(e,t){if(e==null||!this.process?.stdin)return;const s={jsonrpc:"2.0",id:e,result:{decision:t}};this.process.stdin.write(`${JSON.stringify(s)}
4
+ `)}armCompactionFallback(){this.compacting&&(this.compactingTimer&&clearTimeout(this.compactingTimer),this.compactingTimer=setTimeout(()=>{o.warn("codex-adapter","Compaction fallback fired: turn/completed not received within timeout, treating as stuck and releasing deferred events"),this.currentTurnId=null,this.finishCompaction("fallback-timeout")},xe),this.compactingTimer.unref?.())}finishCompaction(e){if(!this.compacting)return;this.compacting=!1,this.compactingTimer&&(clearTimeout(this.compactingTimer),this.compactingTimer=null);const t=this.compactionDeferred.splice(0);o.info("codex-adapter",`Compaction finished (${e}); replaying ${t.length} deferred events`);for(const i of t)this.deliverInboundEvent(i);const s=this.compactionDoneResolver;this.compactionDoneResolver=null,s?.()}handleTurnCompleted(e){if(this.currentTurnId=null,this.stopComposing(),this.activeEventId){const t=this.activeEventId,s={event_id:t,session_id:this.activeSessionId??"",thread_id:this.threadId??void 0,codex_event_type:"codex",codex_method:"turn/completed",codex_sequence:++this.codexSequence,codex_payload:V("turn/completed",e),codex_at:new Date().toISOString()},i=this.turnError,n=this.turnErrorIsRetryableOnly,r=this.turnHasVisibleOutput;this.turnError=null,this.turnErrorIsRetryableOnly=!0,this.turnHasVisibleOutput=!1;const d=!!i&&!(n&&r);this.callbacks.sendCodexEventReliable?(this.clearActive({runPendingAutoCompact:!1}),this.callbacks.sendCodexEventReliable(s).then(()=>{this.callbacks.sendEventResult(t,d?"failed":"responded",d?i??void 0:void 0),this.tryRunPendingAutoCompact()}).catch(h=>{o.error("codex-adapter",`sendCodexEventReliable failed event=${t}: ${h}`),this.callbacks.sendCodexEvent(s),this.callbacks.sendEventResult(t,d?"failed":"responded",d?i??void 0:void 0),this.tryRunPendingAutoCompact()})):(this.callbacks.sendCodexEvent(s),this.callbacks.sendEventResult(t,d?"failed":"responded",d?i??void 0:void 0),this.clearActive())}this.compacting&&this.finishCompaction("turn-completed")}emitCodexEvent(e,t){this.activeEventId&&this.callbacks.sendCodexEvent({event_id:this.activeEventId,session_id:this.activeSessionId??"",thread_id:this.threadId??void 0,codex_event_type:"codex",codex_method:e,codex_sequence:++this.codexSequence,codex_payload:V(e,t),codex_at:new Date().toISOString()})}startComposing(){}stopComposing(){}async sendRequest(e,t,s=3e4){return new Promise((i,n)=>{if(!this.process?.stdin){n(new Error("Codex process not available"));return}const r=++this.requestId,d={jsonrpc:"2.0",id:r,method:e,params:t??{}},h=setTimeout(()=>{this.pendingRequests.delete(String(r)),n(new Error(`Request timeout: ${e}`))},s);this.pendingRequests.set(String(r),{resolve:g=>{g.error?n(new Error(`JSON-RPC error: ${g.error.message}`)):i(g.result)},reject:n,timer:h});const m=JSON.stringify(d);this.process.stdin.write(`${m}
5
5
  `)})}sendNotification(e,t){if(!this.process?.stdin)return;const s={jsonrpc:"2.0",method:e,params:t??{}};this.process.stdin.write(`${JSON.stringify(s)}
6
- `)}async initializeHandshake(){if(this.initialized)return;const e=te(),t=await this.sendRequest("initialize",{clientInfo:{name:"grix-connector",title:"Grix Connector",version:e},capabilities:{experimentalApi:!0}},15e3);o.info("codex-adapter",`Initialized: ${JSON.stringify(t)}`),this.sendNotification("initialized"),this.initialized=!0,await this.refreshCodexModelOptions(),this.fetchRateLimits()}fetchRateLimits(){Promise.resolve(this.sendRequest("account/rateLimits/read",void 0,1e4)).then(e=>{const t=this.parseRateLimitSnapshot(e);t&&(this.rateLimitSnapshot=t,o.info("codex-adapter",`Initial rate limits: primary=${t.primary.usedPercent.toFixed(1)}% secondary=${t.secondary.usedPercent.toFixed(1)}% credits=${t.credits.balance??"N/A"}`),this.callbacks.onRateLimitsUpdated?.(t))}).catch(e=>{o.warn("codex-adapter",`Failed to fetch rate limits: ${e instanceof Error?e.message:e}`)})}async runTurn(e,t,s,i){this.threadId||await this.createSession({cwd:this.cwd}),await this.ensureThreadResumed();const n=[],r=this.callbacks.getAgentProfile?.(),a=r?.agentName?.trim()??"",h=r?.introduction?.trim()??"";if((a||h)&&this.identityInjectedThreadId!==this.threadId){const u=["[system-identity]"];a&&u.push(`Your name is "${a}".`),h&&u.push(`Your self-introduction: ${h}`),u.push("Treat this as an out-of-band instruction; do not echo or repeat it in your replies."),u.push("[/system-identity]"),n.push({type:"text",text:u.join(`
7
- `),text_elements:[]}),this.identityInjectedThreadId=this.threadId,o.info("codex-adapter",`Injected agent identity for thread=${this.threadId} name="${a}"`)}if(this.needsHistoryInjection&&i){this.needsHistoryInjection=!1;const u=await this.loadHistoryForInjection(i);for(const v of u)n.push(v);u.length>0&&o.info("codex-adapter",`Injected ${u.length} history items`)}if(e.contextMessages&&e.contextMessages.length>0){const u=e.contextMessages.map(v=>`[${v.senderId??"unknown"}]: ${v.content}`).join(`
6
+ `)}async initializeHandshake(){if(this.initialized)return;const e=se(),t=await this.sendRequest("initialize",{clientInfo:{name:"grix-connector",title:"Grix Connector",version:e},capabilities:{experimentalApi:!0}},15e3);o.info("codex-adapter",`Initialized: ${JSON.stringify(t)}`),this.sendNotification("initialized"),this.initialized=!0,await this.refreshCodexModelOptions(),this.fetchRateLimits()}fetchRateLimits(){Promise.resolve(this.sendRequest("account/rateLimits/read",void 0,1e4)).then(e=>{const t=this.parseRateLimitSnapshot(e);t&&(this.rateLimitSnapshot=t,o.info("codex-adapter",`Initial rate limits: primary=${t.primary.usedPercent.toFixed(1)}% secondary=${t.secondary.usedPercent.toFixed(1)}% credits=${t.credits.balance??"N/A"}`),this.callbacks.onRateLimitsUpdated?.(t))}).catch(e=>{o.warn("codex-adapter",`Failed to fetch rate limits: ${e instanceof Error?e.message:e}`)})}async runTurn(e,t,s,i){this.threadId||await this.createSession({cwd:this.cwd}),await this.ensureThreadResumed();const n=[],r=this.callbacks.getAgentProfile?.(),d=r?.agentName?.trim()??"",h=r?.introduction?.trim()??"";if((d||h)&&this.identityInjectedThreadId!==this.threadId){const u=["[system-identity]"];d&&u.push(`Your name is "${d}".`),h&&u.push(`Your self-introduction: ${h}`),u.push("Treat this as an out-of-band instruction; do not echo or repeat it in your replies."),u.push("[/system-identity]"),n.push({type:"text",text:u.join(`
7
+ `),text_elements:[]}),this.identityInjectedThreadId=this.threadId,o.info("codex-adapter",`Injected agent identity for thread=${this.threadId} name="${d}"`)}if(this.needsHistoryInjection&&i){this.needsHistoryInjection=!1;const u=await this.loadHistoryForInjection(i);for(const v of u)n.push(v);u.length>0&&o.info("codex-adapter",`Injected ${u.length} history items`)}if(e.contextMessages&&e.contextMessages.length>0){const u=e.contextMessages.map(v=>`[${v.senderId??"unknown"}]: ${v.content}`).join(`
8
8
  `);n.push({type:"text",text:`Conversation context:
9
9
  ${u}
10
10
 
11
- Latest user message:`,text_elements:[]})}n.push({type:"text",text:e.text,text_elements:[]});const m={threadId:this.threadId,approvalPolicy:this.approvalPolicy,input:n,model:this.model},g=_e(this.collaborationMode,this.model);g&&(m.collaborationMode=g),this.reasoningEffort&&(m.effort=this.reasoningEffort);const p=this.effectiveServiceTier();p&&(m.serviceTier=p),await this.sendRequest("turn/start",m),t.emitDone({status:"completed"})}async ensureThreadResumed(){if(!(!this.threadId||!this.threadResumePending))try{const e=await this.sendRequest("thread/resume",{threadId:this.threadId,approvalPolicy:this.approvalPolicy,model:this.model,excludeTurns:!0,persistExtendedHistory:!1,...this.reasoningEffort?{effort:this.reasoningEffort}:{},...this.effectiveServiceTier()?{serviceTier:this.effectiveServiceTier()}:{}});this.updateModelFromThreadResult(e),this.threadResumePending=!1}catch{this.threadId=null,this.needsHistoryInjection=!0,await this.startNewThread(),this.threadResumePending=!1}}async startNewThread(){try{const e=await this.sendRequest("thread/start",{approvalPolicy:this.approvalPolicy,model:this.model,cwd:this.cwd,experimentalRawEvents:!1,persistExtendedHistory:!1,...this.reasoningEffort?{effort:this.reasoningEffort}:{},...this.effectiveServiceTier()?{serviceTier:this.effectiveServiceTier()}:{}}),t=be(e);if(!t)throw new Error("Codex thread id is missing in thread/start result");this.threadId=t,this.updateModelFromThreadResult(e),this.threadResumePending=!1,this.persistThreadId(t)}catch{throw new Error("Failed to start Codex thread")}}updateModelFromThreadResult(e){if(this.model)return;const t=we(e);t&&(this.model=t,this.persistCodexContext())}persistThreadId(e){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setCodexThreadId(this.aibotSessionId,e)}persistCodexContext(){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setCodexContext(this.aibotSessionId,{modelId:this.model,modeId:y(this.collaborationMode)??void 0,reasoningEffort:this.reasoningEffort,serviceTier:this.serviceTier,sandboxMode:this.sandboxMode})}async loadHistoryForInjection(e){const t=this.callbacks.getConversationLog();if(!t)return[];try{const s=await t.readHistory(e,fe),i=[];for(const n of s){const r=(n.content??"").slice(0,me);n.direction==="inbound"?i.push({type:"text",text:r,text_elements:[]}):n.direction==="outbound"&&i.push({type:"assistant",text:r,text_elements:[]})}return i}catch(s){return o.error("codex-adapter",`Failed to load history: ${s}`),[]}}async steerTurn(e){if(!this.threadId||!this.currentTurnId)throw new Error("No active turn to steer");await this.sendRequest("turn/steer",{threadId:this.threadId,expectedTurnId:this.currentTurnId,input:[{type:"text",text:e,text_elements:[]}]})}resumeAfterApproval(e,t,s){if(!this.threadId)return;const i=e.event_id?.trim()||`local_action_${e.action_id.trim()}`,n=x(t.session_id,t.sessionId)??this.activeSessionId??"";if(!n)return;const r=this.threadId,a=new R(r),h={adapterSessionId:r,text:""};this.activeEventId=i,this.activeSessionId=n,this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.codexSequence=0,this.runTurn(h,a,i,n).catch(m=>{o.error("codex-adapter",`Post-approval turn failed: ${m}`),this.callbacks.sendEventResult(i,"failed",m instanceof Error?m.message:String(m)),this.clearActive()}),this.resetIdleTimer(i)}clearActive(e){const t=this.activeEventId;this.stopComposing(),this.activeEventId=null,this.activeSessionId=null,this.currentTurnId=null,this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.agentMessagePhases.clear(),this.inFlightToolOps=0,this.clearIdleTimer(),this.pendingApprovals.clear(),t&&this.emit("eventDone",t),this.replaySteerDeferred(),e?.runPendingAutoCompact!==!1&&this.tryRunPendingAutoCompact()}replaySteerDeferred(){if(this.steerDeferred.length===0)return;const e=this.steerDeferred.splice(0);o.info("codex-adapter",`Replaying ${e.length} steer-deferred event(s) after turn ended`);for(const t of e)this.deliverInboundEvent(t)}resetIdleTimer(e){const t=Date.now();this.lastProgressAt=t,this.lastIdleCheckAt=t,this.idleNoProgressCount=0,this.armIdleTimer(e)}armIdleTimer(e){this.clearIdleTimer();const t=this.inFlightToolOps>0?ue:he;this.idleTimer=setTimeout(()=>{this.onIdleTimeout(e,t)},t)}async onIdleTimeout(e,t){if(this.activeEventId!==e)return;let s=!1;try{s=await this.ping(pe)}catch{s=!1}if(this.activeEventId!==e)return;if(!s){o.error("codex-adapter",`Agent idle ${t/1e3}s and ping failed, declaring stuck: ${e}`),this.declareStuck(e,`agent idle ${t/1e3}s, ping failed`);return}const i=this.lastIdleCheckAt,n=this.lastProgressAt>i,r=n?!1:await this.checkSessionActivitySince(i);if(this.activeEventId===e){if(this.lastIdleCheckAt=Date.now(),n||r){r&&o.info("codex-adapter",`Idle timer: no stream output but rollout still being written, continuing: ${e}`),this.idleNoProgressCount=0,this.armIdleTimer(e);return}this.idleNoProgressCount++,this.idleNoProgressCount>=F?(o.error("codex-adapter",`Agent alive but no progress for ${this.idleNoProgressCount} idle cycles, declaring stuck: ${e}`),this.declareStuck(e,`agent alive but no progress for ${this.idleNoProgressCount} idle cycles`)):(o.warn("codex-adapter",`Idle timer fired, ping ok, no progress (${this.idleNoProgressCount}/${F}): ${e}`),this.armIdleTimer(e))}}declareStuck(e,t){this.callbacks.sendEventResult(e,"failed",t),this.clearActive(),this.emit("stuck")}async checkSessionActivitySince(e){if(!this.threadId)return!1;try{return await oe(this.threadId,e,this.codexHome)}catch{return!1}}isLongRunningToolItemType(e){if(!e)return!1;const t=e.toLowerCase();return t==="commandexecution"||t==="command_execution"||t==="item/commandexecution"||t==="filechange"||t==="file_change"||t==="item/filechange"}shouldSuppressAgentMessageDeltaDuringToolRun(e){return this.inFlightToolOps<=0?!1:(o.info("codex-adapter",`Suppressing agentMessage delta during tool run item_id=${e??"unknown"}`),!0)}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}rejectAllPending(e){for(const[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(new Error(`Request canceled: ${e}`));this.pendingRequests.clear(),this.pendingApprovals.clear()}}const xe={allow:"accept","allow-once":"accept","allow-always":"acceptForSession",deny:"deny"};function Ie(d){return d&&d.length>0?[...d]:["app-server"]}function l(d){if(typeof d!="string")return;const e=d.trim();return e||void 0}function be(d){if(!d||typeof d!="object")return null;const e=d,t=e.thread&&typeof e.thread=="object"?e.thread:void 0;return x(l(e.threadId),l(e.threadID),l(t?.id))??null}function we(d){return!d||typeof d!="object"?null:l(d.model)??null}function y(d){const e=d?.trim().toLowerCase();return e==="default"||e==="plan"?e:null}function _e(d,e){const t=y(d),s=l(e);if(!(!t||!s))return{mode:t,settings:{model:s}}}function ye(d){if(!Array.isArray(d))return[];const e=[];for(const t of d){if(typeof t=="string"){const r=t.trim();r&&e.push(ke(r,T(r)));continue}if(!t||typeof t!="object")continue;const s=t,i=x(l(s.id),l(s.model_id),l(s.modelId),l(s.value));if(!i)continue;const n=x(l(s.displayName),l(s.display_name),l(s.name),l(s.label))??T(i);e.push({id:i,displayName:n,defaultReasoningEffort:l(s.defaultReasoningEffort)??null,supportedReasoningEfforts:E(s.supportedReasoningEfforts),defaultServiceTier:l(s.defaultServiceTier)??null,serviceTiers:A(s.serviceTiers),isDefault:s.isDefault===!0})}return e}function z(d){const e=d.toLowerCase().replace(/\/+$/,"");return!(e==="https://api.openai.com"||e==="https://api.openai.com/v1"||e.endsWith(".openai.com"))}async function Te(d,e){const s=`${d.replace(/\/+$/,"")}/models`,i={Accept:"application/json"};e&&(i.Authorization=`Bearer ${e}`);const n=new AbortController,r=setTimeout(()=>n.abort(),1e4);try{const a=await fetch(s,{headers:i,signal:n.signal});if(!a.ok)return[];const h=await a.json();return Se(h)}finally{clearTimeout(r)}}function Se(d){if(!d||typeof d!="object")return[];const e=d,t=Array.isArray(e.data)?e.data:[],s=[];for(const i of t){if(!i||typeof i!="object")continue;const n=i,r=x(l(n.id),l(n.model));if(!r)continue;const a=x(l(n.displayName),l(n.display_name),l(n.name))??T(r);s.push({id:r,displayName:a,defaultReasoningEffort:l(n.defaultReasoningEffort)??null,supportedReasoningEfforts:E(n.supportedReasoningEfforts),defaultServiceTier:l(n.defaultServiceTier)??null,serviceTiers:A(n.serviceTiers),isDefault:n.isDefault===!0})}return s}function Ce(d){if(!d||typeof d!="object")return{models:[],nextCursor:null};const e=d,t=Array.isArray(e.data)?e.data:[],s=[];for(const i of t){if(!i||typeof i!="object")continue;const n=i;if(n.hidden===!0)continue;const r=x(l(n.id),l(n.model));if(!r)continue;const a=x(l(n.displayName),l(n.display_name),l(n.name))??T(r);s.push({id:r,displayName:a,defaultReasoningEffort:l(n.defaultReasoningEffort)??null,supportedReasoningEfforts:E(n.supportedReasoningEfforts),defaultServiceTier:l(n.defaultServiceTier)??null,serviceTiers:A(n.serviceTiers),isDefault:n.isDefault===!0})}return{models:s,nextCursor:l(e.nextCursor)??null}}function W(d){const e=[],t=new Set;for(const s of d){const i=s.id.trim(),n=i.toLowerCase();!i||t.has(n)||(t.add(n),e.push({id:i,displayName:s.displayName.trim()||i,defaultReasoningEffort:s.defaultReasoningEffort,supportedReasoningEfforts:[...s.supportedReasoningEfforts],defaultServiceTier:s.defaultServiceTier,serviceTiers:[...s.serviceTiers],isDefault:s.isDefault}))}return e}function ke(d,e){return{id:d,displayName:e,defaultReasoningEffort:null,supportedReasoningEfforts:[],defaultServiceTier:null,serviceTiers:[],isDefault:!1}}function E(d){if(!Array.isArray(d))return[];const e=[];for(const t of d){if(typeof t=="string"){const i=t.trim();i&&e.push(i);continue}if(!t||typeof t!="object")continue;const s=l(t.reasoningEffort);s&&e.push(s)}return e}function A(d){if(!Array.isArray(d))return[];const e=[];for(const t of d){if(typeof t=="string"){const n=t.trim();n&&e.push({id:n,displayName:n,description:null});continue}if(!t||typeof t!="object")continue;const s=t,i=l(s.id);i&&e.push({id:i,displayName:x(l(s.name),l(s.displayName),l(s.display_name))??i,description:l(s.description)??null})}return e}function T(d){return d.split(/[-_\s]+/).filter(Boolean).map(e=>/^(gpt|codex|o\d+)$/i.test(e)?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function x(...d){for(const e of d)if(e!=null){if(typeof e=="string"&&!e.trim())continue;return e}}function B(d){return d.trim().replace(/[^a-zA-Z0-9._:-]+/g,"_")}class R extends O{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){o.warn("codex-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}function Ee(d){return["cannot steer a compact turn","turn not found","turn already completed","no active turn"].some(t=>d.includes(t))}export{M as CodexAdapter};
11
+ Latest user message:`,text_elements:[]})}n.push({type:"text",text:e.text,text_elements:[]});const m={threadId:this.threadId,approvalPolicy:this.approvalPolicy,input:n,model:this.model},g=Te(this.collaborationMode,this.model);g&&(m.collaborationMode=g),this.reasoningEffort&&(m.effort=this.reasoningEffort);const p=this.effectiveServiceTier();p&&(m.serviceTier=p),await this.sendRequest("turn/start",m),t.emitDone({status:"completed"})}async ensureThreadResumed(){if(!(!this.threadId||!this.threadResumePending))try{const e=await this.sendRequest("thread/resume",{threadId:this.threadId,approvalPolicy:this.approvalPolicy,model:this.model,excludeTurns:!0,persistExtendedHistory:!1,...this.reasoningEffort?{effort:this.reasoningEffort}:{},...this.effectiveServiceTier()?{serviceTier:this.effectiveServiceTier()}:{}});this.updateModelFromThreadResult(e),this.threadResumePending=!1}catch{this.threadId=null,this.needsHistoryInjection=!0,await this.startNewThread(),this.threadResumePending=!1}}async startNewThread(){try{const e=await this.sendRequest("thread/start",{approvalPolicy:this.approvalPolicy,model:this.model,cwd:this.cwd,experimentalRawEvents:!1,persistExtendedHistory:!1,...this.reasoningEffort?{effort:this.reasoningEffort}:{},...this.effectiveServiceTier()?{serviceTier:this.effectiveServiceTier()}:{}}),t=ye(e);if(!t)throw new Error("Codex thread id is missing in thread/start result");this.threadId=t,this.updateModelFromThreadResult(e),this.threadResumePending=!1,this.persistThreadId(t)}catch{throw new Error("Failed to start Codex thread")}}updateModelFromThreadResult(e){if(this.model)return;const t=_e(e);t&&(this.model=t,this.persistCodexContext())}persistThreadId(e){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setCodexThreadId(this.aibotSessionId,e)}persistCodexContext(){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setCodexContext(this.aibotSessionId,{modelId:this.model,modeId:_(this.collaborationMode)??void 0,reasoningEffort:this.reasoningEffort,serviceTier:this.serviceTier,sandboxMode:this.sandboxMode})}async loadHistoryForInjection(e){const t=this.callbacks.getConversationLog();if(!t)return[];try{const s=await t.readHistory(e,ge),i=[];for(const n of s){const r=(n.content??"").slice(0,ve);n.direction==="inbound"?i.push({type:"text",text:r,text_elements:[]}):n.direction==="outbound"&&i.push({type:"assistant",text:r,text_elements:[]})}return i}catch(s){return o.error("codex-adapter",`Failed to load history: ${s}`),[]}}async steerTurn(e){if(!this.threadId||!this.currentTurnId)throw new Error("No active turn to steer");await this.sendRequest("turn/steer",{threadId:this.threadId,expectedTurnId:this.currentTurnId,input:[{type:"text",text:e,text_elements:[]}]})}resumeAfterApproval(e,t,s){if(!this.threadId)return;const i=e.event_id?.trim()||`local_action_${e.action_id.trim()}`,n=x(t.session_id,t.sessionId)??this.activeSessionId??"";if(!n)return;const r=this.threadId,d=new R(r),h={adapterSessionId:r,text:""};this.activeEventId=i,this.activeSessionId=n,this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.codexSequence=0,this.runTurn(h,d,i,n).catch(m=>{o.error("codex-adapter",`Post-approval turn failed: ${m}`),this.callbacks.sendEventResult(i,"failed",m instanceof Error?m.message:String(m)),this.clearActive()}),this.resetIdleTimer(i)}clearActive(e){const t=this.activeEventId;this.stopComposing(),this.activeEventId=null,this.activeSessionId=null,this.currentTurnId=null,this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.agentMessagePhases.clear(),this.inFlightToolOps=0,this.clearIdleTimer(),this.pendingApprovals.clear(),t&&this.emit("eventDone",t),this.replaySteerDeferred(),e?.runPendingAutoCompact!==!1&&this.tryRunPendingAutoCompact()}replaySteerDeferred(){if(this.steerDeferred.length===0)return;const e=this.steerDeferred.splice(0);o.info("codex-adapter",`Replaying ${e.length} steer-deferred event(s) after turn ended`);for(const t of e)this.deliverInboundEvent(t)}resetIdleTimer(e){const t=Date.now();this.lastProgressAt=t,this.lastIdleCheckAt=t,this.idleNoProgressCount=0,this.armIdleTimer(e)}armIdleTimer(e){this.clearIdleTimer();const t=this.inFlightToolOps>0?fe:pe;this.idleTimer=setTimeout(()=>{this.onIdleTimeout(e,t)},t)}async onIdleTimeout(e,t){if(this.activeEventId!==e)return;let s=!1;try{s=await this.ping(me)}catch{s=!1}if(this.activeEventId!==e)return;if(!s){o.error("codex-adapter",`Agent idle ${t/1e3}s and ping failed, declaring stuck: ${e}`),this.declareStuck(e,`agent idle ${t/1e3}s, ping failed`);return}const i=this.lastIdleCheckAt,n=this.lastProgressAt>i,r=n?!1:await this.checkSessionActivitySince(i);if(this.activeEventId===e){if(this.lastIdleCheckAt=Date.now(),n||r){r&&o.info("codex-adapter",`Idle timer: no stream output but rollout still being written, continuing: ${e}`),this.idleNoProgressCount=0,this.armIdleTimer(e);return}this.idleNoProgressCount++,this.idleNoProgressCount>=F?(o.error("codex-adapter",`Agent alive but no progress for ${this.idleNoProgressCount} idle cycles, declaring stuck: ${e}`),this.declareStuck(e,`agent alive but no progress for ${this.idleNoProgressCount} idle cycles`)):(o.warn("codex-adapter",`Idle timer fired, ping ok, no progress (${this.idleNoProgressCount}/${F}): ${e}`),this.armIdleTimer(e))}}declareStuck(e,t){this.callbacks.sendEventResult(e,"failed",t),this.clearActive(),this.emit("stuck")}async checkSessionActivitySince(e){if(!this.threadId)return!1;try{return await de(this.threadId,e,this.codexHome)}catch{return!1}}isLongRunningToolItemType(e){if(!e)return!1;const t=e.toLowerCase();return t==="commandexecution"||t==="command_execution"||t==="item/commandexecution"||t==="filechange"||t==="file_change"||t==="item/filechange"}shouldSuppressAgentMessageDeltaDuringToolRun(e){return this.inFlightToolOps<=0?!1:(o.info("codex-adapter",`Suppressing agentMessage delta during tool run item_id=${e??"unknown"}`),!0)}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}rejectAllPending(e){for(const[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(new Error(`Request canceled: ${e}`));this.pendingRequests.clear(),this.pendingApprovals.clear()}}const be={allow:"accept","allow-once":"accept","allow-always":"acceptForSession",deny:"deny"};function we(a){return a&&a.length>0?[...a]:["app-server"]}function l(a){if(typeof a!="string")return;const e=a.trim();return e||void 0}function ye(a){if(!a||typeof a!="object")return null;const e=a,t=e.thread&&typeof e.thread=="object"?e.thread:void 0;return x(l(e.threadId),l(e.threadID),l(t?.id))??null}function _e(a){return!a||typeof a!="object"?null:l(a.model)??null}function _(a){const e=a?.trim().toLowerCase();return e==="default"||e==="plan"?e:null}function Te(a,e){const t=_(a),s=l(e);if(!(!t||!s))return{mode:t,settings:{model:s}}}function Se(a){if(!Array.isArray(a))return[];const e=[];for(const t of a){if(typeof t=="string"){const r=t.trim();r&&e.push(Ae(r,T(r)));continue}if(!t||typeof t!="object")continue;const s=t,i=x(l(s.id),l(s.model_id),l(s.modelId),l(s.value));if(!i)continue;const n=x(l(s.displayName),l(s.display_name),l(s.name),l(s.label))??T(i);e.push({id:i,displayName:n,defaultReasoningEffort:l(s.defaultReasoningEffort)??null,supportedReasoningEfforts:E(s.supportedReasoningEfforts),defaultServiceTier:l(s.defaultServiceTier)??null,serviceTiers:A(s.serviceTiers),isDefault:s.isDefault===!0})}return e}function W(a){const e=a.toLowerCase().replace(/\/+$/,"");return!(e==="https://api.openai.com"||e==="https://api.openai.com/v1"||e.endsWith(".openai.com"))}async function Ce(a,e){const s=`${a.replace(/\/+$/,"")}/models`,i={Accept:"application/json"};e&&(i.Authorization=`Bearer ${e}`);const n=new AbortController,r=setTimeout(()=>n.abort(),1e4);try{const d=await fetch(s,{headers:i,signal:n.signal});if(!d.ok)return[];const h=await d.json();return ke(h)}finally{clearTimeout(r)}}function ke(a){if(!a||typeof a!="object")return[];const e=a,t=Array.isArray(e.data)?e.data:[],s=[];for(const i of t){if(!i||typeof i!="object")continue;const n=i,r=x(l(n.id),l(n.model));if(!r)continue;const d=x(l(n.displayName),l(n.display_name),l(n.name))??T(r);s.push({id:r,displayName:d,defaultReasoningEffort:l(n.defaultReasoningEffort)??null,supportedReasoningEfforts:E(n.supportedReasoningEfforts),defaultServiceTier:l(n.defaultServiceTier)??null,serviceTiers:A(n.serviceTiers),isDefault:n.isDefault===!0})}return s}function Ee(a){if(!a||typeof a!="object")return{models:[],nextCursor:null};const e=a,t=Array.isArray(e.data)?e.data:[],s=[];for(const i of t){if(!i||typeof i!="object")continue;const n=i;if(n.hidden===!0)continue;const r=x(l(n.id),l(n.model));if(!r)continue;const d=x(l(n.displayName),l(n.display_name),l(n.name))??T(r);s.push({id:r,displayName:d,defaultReasoningEffort:l(n.defaultReasoningEffort)??null,supportedReasoningEfforts:E(n.supportedReasoningEfforts),defaultServiceTier:l(n.defaultServiceTier)??null,serviceTiers:A(n.serviceTiers),isDefault:n.isDefault===!0})}return{models:s,nextCursor:l(e.nextCursor)??null}}function B(a){const e=[],t=new Set;for(const s of a){const i=s.id.trim(),n=i.toLowerCase();!i||t.has(n)||(t.add(n),e.push({id:i,displayName:s.displayName.trim()||i,defaultReasoningEffort:s.defaultReasoningEffort,supportedReasoningEfforts:[...s.supportedReasoningEfforts],defaultServiceTier:s.defaultServiceTier,serviceTiers:[...s.serviceTiers],isDefault:s.isDefault}))}return e}function Ae(a,e){return{id:a,displayName:e,defaultReasoningEffort:null,supportedReasoningEfforts:[],defaultServiceTier:null,serviceTiers:[],isDefault:!1}}function E(a){if(!Array.isArray(a))return[];const e=[];for(const t of a){if(typeof t=="string"){const i=t.trim();i&&e.push(i);continue}if(!t||typeof t!="object")continue;const s=l(t.reasoningEffort);s&&e.push(s)}return e}function A(a){if(!Array.isArray(a))return[];const e=[];for(const t of a){if(typeof t=="string"){const n=t.trim();n&&e.push({id:n,displayName:n,description:null});continue}if(!t||typeof t!="object")continue;const s=t,i=l(s.id);i&&e.push({id:i,displayName:x(l(s.name),l(s.displayName),l(s.display_name))??i,description:l(s.description)??null})}return e}function T(a){return a.split(/[-_\s]+/).filter(Boolean).map(e=>/^(gpt|codex|o\d+)$/i.test(e)?e.toUpperCase():e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}function x(...a){for(const e of a)if(e!=null){if(typeof e=="string"&&!e.trim())continue;return e}}function J(a){return a.trim().replace(/[^a-zA-Z0-9._:-]+/g,"_")}function V(a,e){switch(a){case"turn/completed":return;case"item/agentMessage/delta":return{params:{delta:(e?.params??{}).delta}};case"item/completed":{const s=(e?.params??{}).item;if(!s||typeof s!="object")return e;let i=s.aggregatedOutput;return typeof i=="string"&&i.length>H&&(i=i.slice(0,H)+`
12
+ \u2026(truncated)`),{params:{item:{type:s.type,command:s.command,aggregatedOutput:i,exitCode:s.exitCode,durationMs:s.durationMs}}}}default:return e}}class R extends L{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){o.warn("codex-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}function Re(a){return["cannot steer a compact turn","turn not found","turn already completed","no active turn"].some(t=>a.includes(t))}export{M as CodexAdapter,V as trimCodexPayloadForWire};
@@ -1 +1 @@
1
- import{log as o}from"../core/log/index.js";import{RespawnManager as d}from"./respawn-manager.js";import{EventQueue as p}from"./event-queue.js";class c extends Error{constructor(e){super(`adapter pool full (maxSize=${e})`),this.name="PoolFullError"}}const v=6e4;class g{slots=new Map;config;factory;sendAck;onEventState=null;onQueueComposing=null;onInternalError=null;onEventStarted=null;onEventDone=null;onSessionActivity=null;stopped=!1;sweepTimer=null;constructor(e,t,s){this.config=e,this.factory=t,this.sendAck=s}setEventStateHandler(e){this.onEventState=e}setQueueComposingHandler(e){this.onQueueComposing=e}setInternalErrorHandler(e){this.onInternalError=e}setEventStartedHandler(e){this.onEventStarted=e}setEventDoneHandler(e){this.onEventDone=e}setSessionActivityHandler(e){this.onSessionActivity=e}async deliverInboundEvent(e){const t=e.session_id,s=this.slots.get(t);if(s){s.startPromise&&await s.startPromise,s.lastActivityAt=Date.now(),this.sendAck(e.event_id,e.session_id),s.state==="stopped"&&o.info("adapter-pool",`Holding event ${e.event_id} in paused queue for restarting slot ${t}`),this.submitToSlotQueue(s,e);return}if(this.slots.size>=this.config.maxPoolSize&&!this.evictDeadSlot()&&!this.evictIdleSlot())throw new c(this.config.maxPoolSize);this.sendAck(e.event_id,e.session_id);const r=this.createSlot(t);try{await r.startPromise}catch(n){throw n}this.submitToSlotQueue(r,e)}submitToSlotQueue(e,t){e.eventQueue.submit(t)==="rejected"&&o.info("adapter-pool",`Event ${t.event_id} rejected by EventQueue (queue full)`)}eventComplete(e,t){const s=this.slots.get(t);s&&s.eventQueue.complete(e)}cancelEvent(e,t){const s=this.slots.get(t);return s?s.eventQueue.cancel(e):!1}removeQueuedEvent(e,t){const s=this.slots.get(e);return s?s.eventQueue.removeQueued(t):!1}clearQueue(e){const t=this.slots.get(e);return t?t.eventQueue.clear(e):[]}drainAllQueuedEvents(){const e=[];for(const t of this.slots.values())e.push(...t.eventQueue.drainQueuedForSession(t.sessionId));return e}drainQueuedForSession(e){if(!this.config.eventQueue)return[];const t=this.slots.get(e);return t?t.eventQueue.drainQueuedForSession(e):[]}getQueueSnapshot(e){if(!this.config.eventQueue)return null;const t=this.slots.get(e);return t?t.eventQueue.snapshot(e):null}deliverStopEvent(e,t){if(t){const s=this.slots.get(t);o.info("adapter-pool",`[stop-trace] pool.deliverStopEvent session=${t} event=${e} slotExists=${!!s} -> adapter.deliverStopEvent`),s?.adapter.deliverStopEvent(e,t);return}o.info("adapter-pool",`[stop-trace] pool.deliverStopEvent (broadcast, no session) event=${e} slots=${this.slots.size}`);for(const s of this.slots.values())s.adapter.deliverStopEvent(e)}collectActiveEventIds(){const e=[];for(const t of this.slots.values()){const s=t.adapter.getActiveEventIds;typeof s=="function"&&e.push(...s.call(t.adapter))}return e}clearActiveEventsForShutdown(){for(const e of this.slots.values()){const t=e.adapter.clearActiveEventForShutdown;typeof t=="function"&&t.call(e.adapter)}}async deliverLocalAction(e,t){const s=String((e.params??{}).session_id??"");let r=s?this.slots.get(s):void 0;if(!r&&s&&t?.autoCreateSlot&&!this.stopped&&(this.slots.size>=this.config.maxPoolSize&&(this.evictDeadSlot()||this.evictIdleSlotSync()),this.slots.size<this.config.maxPoolSize)){o.info("adapter-pool",`Auto-creating slot for session ${s} (local_action trigger)`);const i=this.createSlot(s);try{await i.startPromise,r=i}catch(u){o.error("adapter-pool",`Failed to auto-create slot for ${s}: ${u}`)}}return r?.adapter?.handleLocalAction?(r.lastActivityAt=Date.now(),r.adapter.handleLocalAction(e)):(await Promise.allSettled([...this.slots.values()].map(i=>i.adapter.handleLocalAction?.(e)??Promise.resolve({handled:!1,kind:""})))).find(i=>i.status==="fulfilled"&&i.value.handled)?.value??{handled:!1,kind:""}}getOrCreateSlot(e){const t=this.slots.get(e);if(t)return t;if(!this.stopped)return this.createSlot(e)}getSlot(e){return this.slots.get(e)}getAllSlots(){return[...this.slots.values()]}async removeSlot(e){const t=this.slots.get(e);t&&(this.onSessionActivity?.(e,!1),t.eventQueue.clear(e,"session slot removed"),t.eventQueue.destroy(),t.respawn.stopAll(),this.detachSlotEventListenersExceptDone(t),await t.adapter.stop().catch(()=>{}),t.adapter.removeAllListeners("eventDone"),this.slots.delete(e))}async stop(){this.stopped=!0,this.stopIdleSweep();const e=[...this.slots.values()];this.slots.clear(),await Promise.allSettled(e.map(async t=>{t.eventQueue.destroy(),t.respawn.stopAll(),this.detachAllSlotEventListeners(t),await t.adapter.stop().catch(()=>{})}))}startIdleSweep(){this.stopIdleSweep(),this.sweepTimer=setInterval(()=>this.sweepIdle(),v)}stopIdleSweep(){this.sweepTimer&&(clearInterval(this.sweepTimer),this.sweepTimer=null)}sweepIdle(){const e=Date.now();for(const[t,s]of this.slots){if(s.state==="stopped"&&s.respawn.exhausted){o.info("adapter-pool",`Removing dead slot for session ${t} (sweep)`),this.removeSlot(t).catch(()=>{});continue}if(s.state==="ready"){if(s.adapter.getStatus().busy){s.lastActivityAt=e;continue}e-s.lastActivityAt<=this.config.idleTimeoutMs||(s.adapter.hasBackgroundWork?s.adapter.hasBackgroundWork().then(r=>{r?(o.info("adapter-pool",`Deferred eviction for session ${t}: background grandchild processes detected`),s.lastActivityAt=Date.now()):(o.info("adapter-pool",`Evicting idle slot for session ${t}`),this.removeSlot(t).catch(n=>{o.error("adapter-pool",`Failed to evict slot ${t}: ${n}`)}))}).catch(()=>{o.info("adapter-pool",`Evicting idle slot for session ${t} (background probe failed)`),this.removeSlot(t).catch(r=>{o.error("adapter-pool",`Failed to evict slot ${t}: ${r}`)})}):(o.info("adapter-pool",`Evicting idle slot for session ${t}`),this.removeSlot(t).catch(r=>{o.error("adapter-pool",`Failed to evict slot ${t}: ${r}`)})))}}}evictDeadSlot(){for(const[e,t]of this.slots)if(t.state==="stopped"&&t.respawn.exhausted)return o.info("adapter-pool",`Removing dead slot for session ${e} (exhausted respawn)`),this.removeSlot(e).catch(()=>{}),!0;return!1}evictIdleSlot(){let e=null;for(const t of this.slots.values())t.state==="ready"&&(t.adapter.getStatus().busy||(!e||t.lastActivityAt<e.lastActivityAt)&&(e=t));return e?(o.info("adapter-pool",`Evicting idle slot for session ${e.sessionId} (pool full)`),this.removeSlot(e.sessionId).catch(()=>{}),!0):!1}evictIdleSlotSync(){let e=null,t="";for(const[s,r]of this.slots)r.state==="ready"&&(r.adapter.getStatus().busy||(!e||r.lastActivityAt<e.lastActivityAt)&&(e=r,t=s));return!e||!t?!1:(o.info("adapter-pool",`Evicting idle slot for session ${t} (pool full, sync)`),this.slots.delete(t),e.eventQueue.clear(t,"session slot removed"),e.eventQueue.destroy(),e.respawn.stopAll(),this.detachAllSlotEventListeners(e),e.adapter.stop().catch(()=>{}),!0)}getStatus(){let e=0,t=0;for(const s of this.slots.values())s.state==="ready"&&(e++,s.adapter.getStatus().busy&&t++);return{total:this.slots.size,ready:e,busy:t}}hasPendingWork(){for(const e of this.slots.values())if(e.eventQueue.runningCount>0||e.eventQueue.queuedCount>0||e.state==="ready"&&e.adapter.getStatus().busy)return!0;return!1}createSlot(e){const t=this.factory(e),s=new d,r=this.createEventQueue(e),n={sessionId:e,adapter:t,respawn:s,state:"starting",lastActivityAt:Date.now(),startPromise:null,eventQueue:r};this.slots.set(e,n);const a=(async()=>{try{this.wireSlotEvents(n),await t.start(),n.state="ready"}catch(i){throw this.detachAllSlotEventListeners(n),this.slots.delete(e),i}finally{n.startPromise=null}})();return n.startPromise=a,s.startHealthCheck(this.slotRespawnCtx(n)),n}wireSlotEvents(e){e.adapter.on("exit",t=>{this.stopped||(o.error("adapter-pool",`Slot ${e.sessionId} adapter exited (code=${t})`),e.state="stopped",e.eventQueue.pause("restart"),e.respawn.scheduleRespawn(this.slotRespawnCtx(e)))}),e.adapter.on("stuck",()=>{this.stopped||this.slots.get(e.sessionId)===e&&(o.error("adapter-pool",`Slot ${e.sessionId} adapter stuck, triggering respawn`),e.state="stopped",e.eventQueue.pause("restart"),e.respawn.scheduleRespawn(this.slotRespawnCtx(e)))}),e.adapter.on?.("error",t=>{if(this.stopped)return;const s=t instanceof Error?t.message:String(t);o.error("adapter-pool",`Slot ${e.sessionId} adapter error: ${s}`)}),e.adapter.on("internalError",t=>{if(!this.stopped){if(this.slots.get(e.sessionId)!==e){o.warn("adapter-pool",`Ignored internalError from detached slot session=${e.sessionId} event=${t.eventId}`);return}if(!this.onInternalError){o.warn("adapter-pool",`Slot ${e.sessionId} emitted internalError but no handler registered: event=${t.eventId} msg=${t.errorMsg}`);return}this.onInternalError(t)}}),e.adapter.on("eventStarted",(t,s)=>{this.stopped||this.slots.get(e.sessionId)===e&&this.onEventStarted?.(t,s)}),e.adapter.on("eventDone",t=>{this.stopped||this.slots.get(e.sessionId)===e&&this.onEventDone?.(t,e.sessionId)}),e.adapter.on("sessionActivity",(t,s,r)=>{this.stopped||this.slots.get(e.sessionId)===e&&this.onSessionActivity?.(t||e.sessionId,s,r)}),e.adapter.on("pauseIntake",t=>{this.stopped||this.slots.get(e.sessionId)===e&&e.eventQueue.pause(t)}),e.adapter.on("resumeIntake",t=>{this.stopped||this.slots.get(e.sessionId)===e&&e.eventQueue.resume(t)})}detachAllSlotEventListeners(e){e.adapter.removeAllListeners("exit"),e.adapter.removeAllListeners("error"),e.adapter.removeAllListeners("stuck"),e.adapter.removeAllListeners("internalError"),e.adapter.removeAllListeners("eventStarted"),e.adapter.removeAllListeners("eventDone"),e.adapter.removeAllListeners("sessionActivity"),e.adapter.removeAllListeners("pauseIntake"),e.adapter.removeAllListeners("resumeIntake")}detachSlotEventListenersExceptDone(e){e.adapter.removeAllListeners("exit"),e.adapter.removeAllListeners("error"),e.adapter.removeAllListeners("stuck"),e.adapter.removeAllListeners("internalError"),e.adapter.removeAllListeners("eventStarted"),e.adapter.removeAllListeners("sessionActivity"),e.adapter.removeAllListeners("pauseIntake"),e.adapter.removeAllListeners("resumeIntake")}slotRespawnCtx(e){const t=this,s=e.sessionId;return{name:`slot-${s}`,get stopped(){return t.stopped||!t.slots.has(s)},get agentAlive(){return e.adapter.isAlive()},pingAgent:r=>e.adapter.ping(r),onRespawnNeeded:async()=>{e.eventQueue.pause("restart"),this.detachAllSlotEventListeners(e),await e.adapter.stop().catch(()=>{}),e.adapter=t.factory(s),e.state="starting",t.wireSlotEvents(e),await e.adapter.start(),e.state="ready",e.respawn.resetAttempts(),e.respawn.resetHealthFailures(),e.respawn.stopSlowRetry(),e.respawn.startHealthCheck(t.slotRespawnCtx(e)),e.eventQueue.resume("compaction"),e.eventQueue.resume("barrier"),e.eventQueue.resume("restart")},onCleanupAgent:()=>{"cleanup"in e.adapter&&e.adapter.cleanup()},onAbortActiveRun:r=>{}}}createEventQueue(e){const t=this.config.eventQueue??{maxConcurrent:1,maxQueued:5,queueTimeoutMs:3e5,cancelableQueued:!0,cancelableRunning:!0},s={onDeliver:r=>{const n=this.slots.get(e);n&&n.adapter.deliverInboundEvent(r)},onStateChange:(r,n,a,i)=>{this.onEventState?.(r,n,a,i)},onCancelRunning:r=>{this.deliverStopEvent(r,e)},onRejected:(r,n)=>{this.onEventState?.(r.event_id,r.session_id,"failed",{reason:n})},onComposing:(r,n,a)=>{this.onQueueComposing?.(r,n,a)}};return new p(t,s)}}export{g as AdapterPool,c as PoolFullError};
1
+ import{log as o}from"../core/log/index.js";import{RespawnManager as d}from"./respawn-manager.js";import{EventQueue as p}from"./event-queue.js";class c extends Error{constructor(e){super(`adapter pool full (maxSize=${e})`),this.name="PoolFullError"}}const v=6e4;class g{slots=new Map;config;factory;sendAck;onEventState=null;onQueueComposing=null;onInternalError=null;onEventStarted=null;onEventDone=null;onSessionActivity=null;stopped=!1;sweepTimer=null;constructor(e,t,s){this.config=e,this.factory=t,this.sendAck=s}setEventStateHandler(e){this.onEventState=e}setQueueComposingHandler(e){this.onQueueComposing=e}setInternalErrorHandler(e){this.onInternalError=e}setEventStartedHandler(e){this.onEventStarted=e}setEventDoneHandler(e){this.onEventDone=e}setSessionActivityHandler(e){this.onSessionActivity=e}async deliverInboundEvent(e){const t=e.session_id,s=this.slots.get(t);if(s){s.startPromise&&await s.startPromise,s.lastActivityAt=Date.now(),this.sendAck(e.event_id,e.session_id),s.state==="stopped"&&o.info("adapter-pool",`Holding event ${e.event_id} in paused queue for restarting slot ${t}`),this.submitToSlotQueue(s,e);return}if(this.slots.size>=this.config.maxPoolSize&&!this.evictDeadSlot()&&!this.evictIdleSlot())throw new c(this.config.maxPoolSize);this.sendAck(e.event_id,e.session_id);const r=this.createSlot(t);try{await r.startPromise}catch(n){throw n}this.submitToSlotQueue(r,e)}submitToSlotQueue(e,t){e.eventQueue.submit(t)==="rejected"&&o.info("adapter-pool",`Event ${t.event_id} rejected by EventQueue (queue full)`)}eventComplete(e,t){const s=this.slots.get(t);s&&s.eventQueue.complete(e)}cancelEvent(e,t){const s=this.slots.get(t);return s?s.eventQueue.cancel(e):!1}removeQueuedEvent(e,t){const s=this.slots.get(e);return s?s.eventQueue.removeQueued(t):!1}clearQueue(e){const t=this.slots.get(e);return t?t.eventQueue.clear(e):[]}drainAllQueuedEvents(){const e=[];for(const t of this.slots.values())e.push(...t.eventQueue.drainQueuedForSession(t.sessionId));return e}drainQueuedForSession(e){if(!this.config.eventQueue)return[];const t=this.slots.get(e);return t?t.eventQueue.drainQueuedForSession(e):[]}getQueueSnapshot(e){if(!this.config.eventQueue)return null;const t=this.slots.get(e);return t?t.eventQueue.snapshot(e):null}deliverStopEvent(e,t){if(t){const s=this.slots.get(t);o.info("adapter-pool",`[stop-trace] pool.deliverStopEvent session=${t} event=${e} slotExists=${!!s} -> adapter.deliverStopEvent`),s?.adapter.deliverStopEvent(e,t);return}o.info("adapter-pool",`[stop-trace] pool.deliverStopEvent (broadcast, no session) event=${e} slots=${this.slots.size}`);for(const s of this.slots.values())s.adapter.deliverStopEvent(e)}collectActiveEventIds(){const e=[];for(const t of this.slots.values()){const s=t.adapter.getActiveEventIds;typeof s=="function"&&e.push(...s.call(t.adapter))}return e}clearActiveEventsForShutdown(){for(const e of this.slots.values()){const t=e.adapter.clearActiveEventForShutdown;typeof t=="function"&&t.call(e.adapter)}}async deliverLocalAction(e,t){const s=String((e.params??{}).session_id??"");let r=s?this.slots.get(s):void 0;if(!r&&s&&t?.autoCreateSlot&&!this.stopped&&(this.slots.size>=this.config.maxPoolSize&&(this.evictDeadSlot()||this.evictIdleSlotSync()),this.slots.size<this.config.maxPoolSize)){o.info("adapter-pool",`Auto-creating slot for session ${s} (local_action trigger)`);const i=this.createSlot(s);try{await i.startPromise,r=i}catch(u){o.error("adapter-pool",`Failed to auto-create slot for ${s}: ${u}`)}}return r?.adapter?.handleLocalAction?(r.lastActivityAt=Date.now(),r.adapter.handleLocalAction(e)):(await Promise.allSettled([...this.slots.values()].map(i=>i.adapter.handleLocalAction?.(e)??Promise.resolve({handled:!1,kind:""})))).find(i=>i.status==="fulfilled"&&i.value.handled)?.value??{handled:!1,kind:""}}getOrCreateSlot(e){const t=this.slots.get(e);if(t)return t;if(!this.stopped)return this.createSlot(e)}getSlot(e){return this.slots.get(e)}getAllSlots(){return[...this.slots.values()]}async removeSlot(e){const t=this.slots.get(e);t&&(this.onSessionActivity?.(e,!1),t.eventQueue.clear(e,"session slot removed"),t.eventQueue.destroy(),t.respawn.stopAll(),this.detachSlotEventListenersExceptDone(t),await t.adapter.stop().catch(()=>{}),t.adapter.removeAllListeners("eventDone"),this.slots.delete(e))}async stop(){this.stopped=!0,this.stopIdleSweep();const e=[...this.slots.values()];this.slots.clear(),await Promise.allSettled(e.map(async t=>{t.eventQueue.destroy(),t.respawn.stopAll(),this.detachAllSlotEventListeners(t),await t.adapter.stop().catch(()=>{})}))}startIdleSweep(){this.stopIdleSweep(),this.sweepTimer=setInterval(()=>this.sweepIdle(),v)}stopIdleSweep(){this.sweepTimer&&(clearInterval(this.sweepTimer),this.sweepTimer=null)}sweepIdle(){const e=Date.now();for(const[t,s]of this.slots){if(s.state==="stopped"&&s.respawn.exhausted){o.info("adapter-pool",`Removing dead slot for session ${t} (sweep)`),this.removeSlot(t).catch(()=>{});continue}if(s.state==="ready"){if(s.adapter.getStatus().busy){s.lastActivityAt=e;continue}e-s.lastActivityAt<=this.config.idleTimeoutMs||(s.adapter.hasBackgroundWork?s.adapter.hasBackgroundWork().then(r=>{r?(o.info("adapter-pool",`Deferred eviction for session ${t}: background grandchild processes detected`),s.lastActivityAt=Date.now()):(o.info("adapter-pool",`Evicting idle slot for session ${t}`),this.removeSlot(t).catch(n=>{o.error("adapter-pool",`Failed to evict slot ${t}: ${n}`)}))}).catch(()=>{o.info("adapter-pool",`Evicting idle slot for session ${t} (background probe failed)`),this.removeSlot(t).catch(r=>{o.error("adapter-pool",`Failed to evict slot ${t}: ${r}`)})}):(o.info("adapter-pool",`Evicting idle slot for session ${t}`),this.removeSlot(t).catch(r=>{o.error("adapter-pool",`Failed to evict slot ${t}: ${r}`)})))}}}evictDeadSlot(){for(const[e,t]of this.slots)if(t.state==="stopped"&&t.respawn.exhausted)return o.info("adapter-pool",`Removing dead slot for session ${e} (exhausted respawn)`),this.removeSlot(e).catch(()=>{}),!0;return!1}evictIdleSlot(){let e=null;for(const t of this.slots.values())t.state==="ready"&&(t.adapter.getStatus().busy||(!e||t.lastActivityAt<e.lastActivityAt)&&(e=t));return e?(o.info("adapter-pool",`Evicting idle slot for session ${e.sessionId} (pool full)`),this.removeSlot(e.sessionId).catch(()=>{}),!0):!1}evictIdleSlotSync(){let e=null,t="";for(const[s,r]of this.slots)r.state==="ready"&&(r.adapter.getStatus().busy||(!e||r.lastActivityAt<e.lastActivityAt)&&(e=r,t=s));return!e||!t?!1:(o.info("adapter-pool",`Evicting idle slot for session ${t} (pool full, sync)`),this.slots.delete(t),e.eventQueue.clear(t,"session slot removed"),e.eventQueue.destroy(),e.respawn.stopAll(),this.detachAllSlotEventListeners(e),e.adapter.stop().catch(()=>{}),!0)}getStatus(){let e=0,t=0;for(const s of this.slots.values())s.state==="ready"&&(e++,s.adapter.getStatus().busy&&t++);return{total:this.slots.size,ready:e,busy:t}}hasPendingWork(){for(const e of this.slots.values()){if(e.eventQueue.runningCount>0||e.eventQueue.queuedCount>0)return!0;if(e.state==="ready"){const t=e.adapter.getStatus();if(t.busy||t.backgroundBusy)return!0}}return!1}createSlot(e){const t=this.factory(e),s=new d,r=this.createEventQueue(e),n={sessionId:e,adapter:t,respawn:s,state:"starting",lastActivityAt:Date.now(),startPromise:null,eventQueue:r};this.slots.set(e,n);const a=(async()=>{try{this.wireSlotEvents(n),await t.start(),n.state="ready"}catch(i){throw this.detachAllSlotEventListeners(n),this.slots.delete(e),i}finally{n.startPromise=null}})();return n.startPromise=a,s.startHealthCheck(this.slotRespawnCtx(n)),n}wireSlotEvents(e){e.adapter.on("exit",t=>{this.stopped||(o.error("adapter-pool",`Slot ${e.sessionId} adapter exited (code=${t})`),e.state="stopped",e.eventQueue.pause("restart"),e.respawn.scheduleRespawn(this.slotRespawnCtx(e)))}),e.adapter.on("stuck",()=>{this.stopped||this.slots.get(e.sessionId)===e&&(o.error("adapter-pool",`Slot ${e.sessionId} adapter stuck, triggering respawn`),e.state="stopped",e.eventQueue.pause("restart"),e.respawn.scheduleRespawn(this.slotRespawnCtx(e)))}),e.adapter.on?.("error",t=>{if(this.stopped)return;const s=t instanceof Error?t.message:String(t);o.error("adapter-pool",`Slot ${e.sessionId} adapter error: ${s}`)}),e.adapter.on("internalError",t=>{if(!this.stopped){if(this.slots.get(e.sessionId)!==e){o.warn("adapter-pool",`Ignored internalError from detached slot session=${e.sessionId} event=${t.eventId}`);return}if(!this.onInternalError){o.warn("adapter-pool",`Slot ${e.sessionId} emitted internalError but no handler registered: event=${t.eventId} msg=${t.errorMsg}`);return}this.onInternalError(t)}}),e.adapter.on("eventStarted",(t,s)=>{this.stopped||this.slots.get(e.sessionId)===e&&this.onEventStarted?.(t,s)}),e.adapter.on("eventDone",t=>{this.stopped||this.slots.get(e.sessionId)===e&&this.onEventDone?.(t,e.sessionId)}),e.adapter.on("sessionActivity",(t,s,r)=>{this.stopped||this.slots.get(e.sessionId)===e&&this.onSessionActivity?.(t||e.sessionId,s,r)}),e.adapter.on("pauseIntake",t=>{this.stopped||this.slots.get(e.sessionId)===e&&e.eventQueue.pause(t)}),e.adapter.on("resumeIntake",t=>{this.stopped||this.slots.get(e.sessionId)===e&&e.eventQueue.resume(t)})}detachAllSlotEventListeners(e){e.adapter.removeAllListeners("exit"),e.adapter.removeAllListeners("error"),e.adapter.removeAllListeners("stuck"),e.adapter.removeAllListeners("internalError"),e.adapter.removeAllListeners("eventStarted"),e.adapter.removeAllListeners("eventDone"),e.adapter.removeAllListeners("sessionActivity"),e.adapter.removeAllListeners("pauseIntake"),e.adapter.removeAllListeners("resumeIntake")}detachSlotEventListenersExceptDone(e){e.adapter.removeAllListeners("exit"),e.adapter.removeAllListeners("error"),e.adapter.removeAllListeners("stuck"),e.adapter.removeAllListeners("internalError"),e.adapter.removeAllListeners("eventStarted"),e.adapter.removeAllListeners("sessionActivity"),e.adapter.removeAllListeners("pauseIntake"),e.adapter.removeAllListeners("resumeIntake")}slotRespawnCtx(e){const t=this,s=e.sessionId;return{name:`slot-${s}`,get stopped(){return t.stopped||!t.slots.has(s)},get agentAlive(){return e.adapter.isAlive()},pingAgent:r=>e.adapter.ping(r),onRespawnNeeded:async()=>{e.eventQueue.pause("restart"),this.detachAllSlotEventListeners(e),await e.adapter.stop().catch(()=>{}),e.adapter=t.factory(s),e.state="starting",t.wireSlotEvents(e),await e.adapter.start(),e.state="ready",e.respawn.resetAttempts(),e.respawn.resetHealthFailures(),e.respawn.stopSlowRetry(),e.respawn.startHealthCheck(t.slotRespawnCtx(e)),e.eventQueue.resume("compaction"),e.eventQueue.resume("barrier"),e.eventQueue.resume("restart")},onCleanupAgent:()=>{"cleanup"in e.adapter&&e.adapter.cleanup()},onAbortActiveRun:r=>{}}}createEventQueue(e){const t=this.config.eventQueue??{maxConcurrent:1,maxQueued:5,queueTimeoutMs:3e5,cancelableQueued:!0,cancelableRunning:!0},s={onDeliver:r=>{const n=this.slots.get(e);n&&n.adapter.deliverInboundEvent(r)},onStateChange:(r,n,a,i)=>{this.onEventState?.(r,n,a,i)},onCancelRunning:r=>{this.deliverStopEvent(r,e)},onRejected:(r,n)=>{this.onEventState?.(r.event_id,r.session_id,"failed",{reason:n})},onComposing:(r,n,a)=>{this.onQueueComposing?.(r,n,a)}};return new p(t,s)}}export{g as AdapterPool,c as PoolFullError};