grix-connector 3.0.3 → 3.1.1

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,10 +1,11 @@
1
- import{execFileSync as A}from"node:child_process";import{createInterface as W}from"node:readline";import{EventEmitter as E}from"node:events";import{stat as M}from"node:fs/promises";import{join as C,resolve as B}from"node:path";import{fileURLToPath as J}from"node:url";import{homedir as G}from"node:os";import{syncDefaultSkillsToDir as X}from"../../default-skills/index.js";import{resolveCommandPath as V,spawnCommand as K,killProcessGroup as R,hasChildProcesses as Y}from"../../core/runtime/spawn.js";import{InternalApiServer as Z}from"../../core/mcp/internal-api-server.js";import{log as r}from"../../core/log/index.js";import{resolveClientVersion as Q}from"../../core/util/client-version.js";import{isUserVisibleAgentMessagePhase as ee}from"../../core/util/codex-output-policy.js";import{SessionBindingStore as te}from"../../core/persistence/session-binding-store.js";import{ensureCodexProjectTrusted as se,isCodexCommand as ie,readCodexProviderSettings as T}from"./codex-trust.js";import{checkCodexSessionActivity as ne}from"./session-activity.js";import{findRolloutFile as oe}from"./rollout-locator.js";import{checkCodexLock as P}from"./lock-monitor.js";import{resolveCliPath as re,getCliVersion as ae}from"../../core/util/cli-probe.js";import{scanSkills as de}from"../claude/skill-scanner.js";const ce=60*1e3,le=600*1e3,he=5*1e3,$=2,ue=20,pe=8e3,L=80,fe=120*1e3,me=[{id:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",defaultReasoningEffort:null,supportedReasoningEfforts:[],isDefault:!0}],O=[{id:"default",displayName:"Default"},{id:"plan",displayName:"Plan"}];function N(a,e){const t=String(a??"").trim()||"codex",i=V(t,e);if(i!==t)return i;const s=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")],o=[...s,...n];for(const d of o)try{return require("node:fs").accessSync(d,require("node:fs").constants.X_OK),d}catch{continue}return r.warn("codex-adapter",`resolveCodexCommandPath: failed to resolve "${t}". envPath=${e?"provided":"missing (using process.env.PATH)"}. fallbacks tried: [${o.join(", ")}]`),t}class q extends E{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;idleTimer=null;lastProgressAt=0;lastIdleCheckAt=0;idleNoProgressCount=0;inFlightToolOps=0;pendingApprovals=new Map;needsHistoryInjection=!1;lastInjectedSessionId=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 i=e.options??{};if(this.approvalPolicy=i.approvalPolicy??"never",this.sandboxMode=typeof i.sandboxMode=="string"&&i.sandboxMode.trim()&&i.sandboxMode.trim()!=="default"?i.sandboxMode.trim():void 0,this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.bindingStore=i.bindingStore instanceof te?i.bindingStore:null,this.model=i.model,this.collaborationMode=i.collaborationMode,this.reasoningEffort=i.reasoningEffort,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.sandboxMode=this.sandboxMode??this.bindingStore.getCodexSandboxMode(this.aibotSessionId)),this.autoTrustProject=typeof i.autoTrustProject=="boolean"?i.autoTrustProject:"auto",this.codexHome=typeof i.codexHome=="string"&&i.codexHome.trim()?i.codexHome.trim():void 0,this.cwd=this.resolveCwd(),this.bindingStore&&this.aibotSessionId){const s=this.bindingStore.getCodexThreadId(this.aibotSessionId);s&&(this.threadId=s,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(),r.info("codex-adapter",`Ready (pid=${this.process?.pid})`)}async ensureProjectTrusted(){if(this.shouldAutoTrustProject())try{const e=await se(this.cwd,{codexHome:this.codexHome});e.changed&&r.info("codex-adapter",`Trusted Codex project ${this.cwd} in ${e.configPath}`)}catch(e){const t=e instanceof Error?e.message:String(e);throw r.error("codex-adapter",`Failed to trust Codex project ${this.cwd}: ${t}`),e}}async startInternalApiAndRegisterMcp(){try{this.internalApi=new Z,this.internalApi.setInvokeHandler(async(d,h)=>this.callbacks.agentInvoke(d,h)),await this.internalApi.start(0),r.info("codex-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),t={...process.env,...this.config.env},i=typeof t.PATH=="string"?t.PATH:void 0,s=N(this.config.command||"codex",i);try{A(s,["mcp","remove",e.name],{env:t,timeout:1e4,stdio:"ignore"})}catch{}A(s,["mcp","add",e.name,"--",e.command,...e.args],{env:t,timeout:1e4,stdio:"ignore"}),r.info("codex-adapter",`Registered MCP server: ${e.name}`);const n=C(G(),".codex","skills"),o=X(n);o.length>0&&r.info("codex-adapter",`Synced connector skills to ${n}: [${o.join(", ")}]`)}catch(e){r.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:ie(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){r.warn("codex-adapter",`Failed to attach toolbar context to binding update: ${e instanceof Error?e.message:String(e)}`),this.notifyBindingReady()}}getEffortMeta(){const e=this.currentModelId(),t=this.getModelOption(e),i=t?.supportedReasoningEfforts??[];return i.length===0?{}:{available_efforts:i,reasoning_effort:this.reasoningEffort??t?.defaultReasoningEffort??null}}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")R(e,"SIGTERM"),await Promise.race([new Promise(i=>{e.once("exit",()=>i(!0))}),new Promise(i=>{setTimeout(()=>i(!1),5e3)})])||R(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 S(e.adapterSessionId);return this.runTurn(e,t).catch(i=>{t.emitError(i instanceof Error?i:new Error(String(i)))}),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),i=!!(this.process.stdout&&!this.process.stdout.destroyed);return t&&i}if(!this.process.stdin||this.process.stdin.destroyed)return!!(this.process.stdout&&!this.process.stdout.destroyed);try{const t=++this.requestId,i={jsonrpc:"2.0",id:t,method:"ping",params:{}};return await new Promise(s=>{const n=setTimeout(()=>{this.pendingRequests.delete(String(t)),s(!1)},e);this.pendingRequests.set(String(t),{resolve:()=>s(!0),reject:()=>s(!1),timer:n}),this.process.stdin.write(`${JSON.stringify(i)}
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(),r.info("codex-adapter",`Model set to: ${e}`)}setMode(e){const t=_(e);if(!t){r.info("codex-adapter",`Ignoring unsupported mode: ${e}`);return}this.collaborationMode=t,this.persistCodexContext(),r.info("codex-adapter",`Mode set to: ${t}`)}setReasoningEffort(e){this.reasoningEffort=e,this.persistCodexContext(),r.info("codex-adapter",`Reasoning effort set to: ${e}`)}setSandboxMode(e){this.sandboxMode=e,this.persistCodexContext(),r.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=B(J(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?Y(e,[e]):!1}async probe(e){const t=this.config.command||"codex",i=await re(t),s=i!==null;let n=null,o;if(s){const m=await ae(t);n=m.version,m.error&&(o=m.error)}else o={code:"cli_not_found",message:`command not found: ${t}`};const h=T().baseUrl??null,u=this.currentModelId()||null,f=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},x=await this.probeSessionRecord(),v=P({codexHome:this.codexHome});return{cli:{command:t,installed:s,path:i,version:n,...o?{error:o}:{}},conversation:p,config:{model:u,base_url:h,source:{model:u?"runtime":"unknown",base_url:h?"file":"unknown"}},process:{started:!!this.process,alive:f.alive,busy:f.busy},session:x,lock:{present:v.present,locked:v.locked,stale:v.stale,path:v.path}}}async probeSessionRecord(){const e=this.threadId?oe(this.threadId,this.codexHome):null;if(!e)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const t=await M(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,i){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 s=new Promise(n=>{this.compactionDoneResolver=n});try{return await this.threadCompact(),this.armCompactionFallback(),await s,{status:"ok",message:"Thread compacted"}}catch(n){this.finishCompaction("compact-error");const o=n instanceof Error?n.message:String(n);if(/thread.*(not found|not exist|unknown|invalid)/i.test(o)||/not found.*thread/i.test(o))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 s=t.trim();return s?this.getModelOptions().some(o=>o.id===s)?(this.setModel(s),{status:"ok",message:`Model set to ${s}`}):{status:"failed",message:`Unknown model: ${s}`}:{status:"ok",message:`Current: ${this.currentModelId()}`,data:{models:this.getModelOptions()}}}case"mode":{const s=t.trim();if(s){const n=_(s);return n?(this.setMode(n),{status:"ok",message:`Mode set to ${n}`}):{status:"failed",message:`Unknown mode: ${s}. Supported: default, plan`}}return{status:"ok",message:`Current: ${this.collaborationMode??"default"}`,data:{modes:O}}}case"rollback":{if(!this.threadId)return{status:"failed",message:"No active thread"};const s=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(s),{status:"ok",message:`Rolled back ${s} 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 s=de({mode:"codex",projectDir:this.cwd}),n=s.map(o=>`- ${o.name}${o.trigger?` (${o.trigger})`:""}: ${o.description}`);return{status:"ok",message:n.length>0?n.join(`
3
- `):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${e}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}async handleLocalAction(e){const t=e.action_type??"",i=e.params??{};switch(r.info("codex-adapter",`handleLocalAction action_type=${t} action_id=${e.action_id} session_id=${i.session_id??""}`),t){case"set_model":{const s=g(l(i.model_id),l(i.modelId),l(i.value));return s&&this.setModel(s),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("model_set")),{handled:!0,kind:"set_model"}}case"set_mode":{const s=i.mode_id;return s&&this.setMode(s),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("mode_set")),{handled:!0,kind:"set_mode"}}case"set_reasoning_effort":{const s=g(l(i.reasoning_effort),l(i.reasoning_eff),l(i.effort));return s&&this.setReasoningEffort(s),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("effort_set",!1)),{handled:!0,kind:"set_reasoning_effort"}}case"set_sandbox_mode":{const s=g(l(i.sandbox_mode),l(i.sandboxMode),l(i.value));return s&&this.setSandboxMode(s),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("sandbox_mode_set",!1)),{handled:!0,kind:"set_sandbox_mode"}}case"thread_compact":{r.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 r.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 s=new Promise(n=>{this.compactionDoneResolver=n});await this.threadCompact(),this.armCompactionFallback(),await s,r.info("codex-adapter",`thread_compact done action_id=${e.action_id}`),this.callbacks.sendLocalActionResult(e.action_id,"ok")}catch(s){this.finishCompaction("compact-error");const n=s instanceof Error?s.message:String(s);/thread.*(not found|not exist|unknown|invalid)/i.test(n)||/not found.*thread/i.test(n)?(r.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.")):(r.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 s=this.resolvePendingApproval(e);if(!s)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=i.decision||"allow-once",o=ge[n]??"accept";return this.sendApprovalDecision(s.requestId,o),this.pendingApprovals.delete(s.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:s.approvalId,approval_command_id:s.approvalCommandId,decision:n}),this.resumeAfterApproval(e,i,s),{handled:!0,kind:t}}case"exec_reject":case"file_reject":{const s=this.resolvePendingApproval(e);return s?(this.sendApprovalDecision(s.requestId,"deny"),this.pendingApprovals.delete(s.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:s.approvalId,approval_command_id:s.approvalCommandId,decision:"deny"}),this.resumeAfterApproval(e,i,s),{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 s=this.resolvePendingApproval(e);return!s||s.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(s.requestId,"accept"),this.pendingApprovals.delete(s.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:s.approvalId,decision:"approve"}),this.resumeAfterApproval(e,i,s),{handled:!0,kind:t})}case"permission_reject":{const s=this.resolvePendingApproval(e);return!s||s.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(s.requestId,"deny"),this.pendingApprovals.delete(s.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:s.approvalId,decision:"deny"}),this.resumeAfterApproval(e,i,s),{handled:!0,kind:t})}case"turn_interrupt":{try{await this.cancel(this.threadId??""),this.callbacks.sendLocalActionResult(e.action_id,"ok")}catch(s){this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,void 0,s instanceof Error?s.message:String(s))}return{handled:!0,kind:"turn_interrupt"}}case"thread_rollback":{const s=Number(i.numTurns??i.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(s),this.callbacks.sendLocalActionResult(e.action_id,"ok",{numTurns:s})}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 s=this.rateLimitSnapshot,n=this.buildContextWindowSnapshot(),o=Date.now(),d=this.currentThreadTokenUsage;return s?r.info("codex-adapter",`[rate-limits] responding: primary=${s.primary.usedPercent.toFixed(1)}% window=${s.primary.windowMinutes}min resetsAt=${s.primary.resetsAt} secondary=${s.secondary.usedPercent.toFixed(1)}% window=${s.secondary.windowMinutes}min resetsAt=${s.secondary.resetsAt}`):r.info("codex-adapter","[rate-limits] responding: no rateLimitSnapshot available"),r.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:s!==null,cached:!1,sampledAt:o,rateLimits:s,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 i=_(this.collaborationMode)??"default",s=this.currentModelId(),n=this.getModelOption(s),o=this.getModelOptions(),d=O,h=this.reasoningEffort??n?.defaultReasoningEffort??null,u=n?.supportedReasoningEfforts??[],f=T(this.codexHome),p=!!(f.baseUrl&&D(f.baseUrl)),x=p?[]:u,v=p?null:h,m={outcome:e,session_context:{modelId:s,modeId:i,reasoningEffort:v,approvalPolicy:this.approvalPolicy,sandboxMode:this.sandboxMode??null},model_id:s,mode_id:i,currentModelId:s,currentModeId:i,available_models:o,available_modes:d,available_efforts:x,availableModels:o,availableModes:d,reasoning_effort:v,sandbox_mode:this.sandboxMode??null,models:o.map(c=>({modelId:c.id,name:c.displayName})),modes:d.map(c=>({id:c.id,name:c.displayName}))};return this.rateLimitSnapshot&&(m.rate_limit_primary_percent=this.rateLimitSnapshot.primary.usedPercent,m.rate_limit_secondary_percent=this.rateLimitSnapshot.secondary.usedPercent,m.rate_limit_primary_window_min=this.rateLimitSnapshot.primary.windowMinutes,m.rate_limit_secondary_window_min=this.rateLimitSnapshot.secondary.windowMinutes),m}currentModelId(){const e=String(this.model??"").trim();if(e)return e;const t=this.getModelOptions();return t.find(i=>i.isDefault)?.id??t[0]?.id??""}getModelOption(e){const t=e.trim().toLowerCase();return this.getModelOptions().find(i=>i.id.trim().toLowerCase()===t)}getModelOptions(){const e=this.config.options??{},t=e.available_models??e.availableModels??e.models,i=we(t),s=this.codexModelOptions,n=[],o=String(this.model??"").trim(),d=o&&!s.some(p=>p.id.trim().toLowerCase()===o.toLowerCase()),h=s.length>0?s:d?[]:me;if(o){const p=[...s,...i].find(x=>x.id.trim().toLowerCase()===o.toLowerCase());n.push({id:o,displayName:p?.displayName??y(o),defaultReasoningEffort:p?.defaultReasoningEffort??null,supportedReasoningEfforts:p?.supportedReasoningEfforts??[],isDefault:p?.isDefault??!1})}n.push(...i),n.push(...h);const u=[],f=new Set;for(const p of n){const x=p.id.trim(),v=x.toLowerCase();!x||f.has(v)||(f.add(v),u.push({id:x,displayName:p.displayName.trim()||x,defaultReasoningEffort:p.defaultReasoningEffort,supportedReasoningEfforts:[...p.supportedReasoningEfforts],isDefault:p.isDefault}))}return u}async refreshCodexModelOptions(){if(!this.initialized||!this.alive||!this.process?.stdin||Date.now()-this.codexModelOptionsCachedAt<q.MODEL_CACHE_TTL_MS)return;const e=T(this.codexHome);if(e.baseUrl&&D(e.baseUrl)){try{const t=await _e(e.baseUrl,e.apiKey);if(t.length>0){this.codexModelOptions=j(t),this.codexModelOptionsCachedAt=Date.now(),r.info("codex-adapter",`Loaded ${t.length} models from external provider ${e.baseUrl}`);return}}catch(t){r.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 i;do{const s=await this.sendRequest("model/list",{cursor:i??null,includeHidden:!1,limit:100},15e3),n=Ce(s);t.push(...n.models),i=n.nextCursor}while(i);t.length>0&&(this.codexModelOptions=j(t),this.codexModelOptionsCachedAt=Date.now())}catch(t){r.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;deliverInboundEvent(e){if(this.compacting){r.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()){r.info("codex-adapter",`Event ${e.event_id}: steering active turn ${this.currentTurnId}`),this.steerTurn(t).catch(i=>{const s=i instanceof Error?i.message:String(i);if(r.info("codex-adapter",`Steer failed, falling through: ${s}`),!this.currentTurnId){this.startNewTurn(e,t);return}if(ke(s)){r.info("codex-adapter","Unsteerable turn detected, clearing active state and starting new turn"),this.clearActive(),this.startNewTurn(e,t);return}r.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){r.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 i=this.threadId??"",s=new S(i),n={adapterSessionId:i,text:t,contextMessages:e.context_messages_json?JSON.parse(e.context_messages_json).map(o=>({senderId:o.sender_id??"unknown",content:o.content})):void 0};this.runTurn(n,s,e.event_id,e.session_id).catch(o=>{r.error("codex-adapter",`Turn failed: ${o}`),this.callbacks.sendEventResult(e.event_id,"failed",o instanceof Error?o.message:String(o)),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||r.warn("codex-adapter",`spawnCodex: env.PATH is missing! process.env.PATH=${process.env.PATH?"set":"missing"}, config.env=${JSON.stringify(this.config.env)}`);const i=N(this.config.command||"codex",t),s=xe(this.config.args);this.sandboxMode&&s.push("-c",`sandbox_mode="${this.sandboxMode}"`),r.info("codex-adapter",`Spawning: ${i} ${s.join(" ")}`);try{if(!(await M(this.cwd)).isDirectory())throw new Error(`Bound path is not a directory: ${this.cwd}`)}catch(o){throw String(o?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${this.cwd}. Please rebind with /grix open <valid-directory>.`):o}const n=P({codexHome:this.codexHome});if(n.locked&&!n.stale)throw new Error(`Codex session appears locked by another process: ${n.path}`);n.stale&&r.warn("codex-adapter",`Ignoring stale Codex lock: ${n.path}`);try{this.process=K(i,s,{env:e,cwd:this.cwd}).process}catch(o){throw r.error("codex-adapter",`Codex spawn threw: ${o}`),this.process=null,this.alive=!1,this.bridgeStatus="closed",o}this.process.on("error",o=>{r.error("codex-adapter",`Codex process spawn error: ${o}`),this.process=null,this.alive=!1,this.bridgeStatus="closed",this.clearIdleTimer(),this.rejectAllPending("spawn failed: "+(o instanceof Error?o.message:String(o))),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",o=>{r.info("codex-adapter",`Codex process exited (code=${o})`),this.alive=!1,this.bridgeStatus="closed",this.clearIdleTimer(),this.rejectAllPending("process exited"),this.stopComposing(),this.emit("exit",o)}),this.process.stderr?.on("data",o=>{const d=o.toString().trim();d&&r.info("codex-adapter",`[codex stderr] ${d}`)}),this.bindStdout(),this.alive=!0}bindStdout(){if(!this.process?.stdout)return;this.process.stdout.setEncoding("utf8"),W({input:this.process.stdout}).on("line",t=>{if(!t.trim())return;let i;try{i=JSON.parse(t)}catch{r.error("codex-adapter",`Invalid JSON from Codex: ${t.slice(0,200)}`);return}if(this.bridgeStatus==="starting"&&(this.bridgeStatus="ready"),i.id!=null){const s=String(i.id),n=this.pendingRequests.get(s);if(n){clearTimeout(n.timer),this.pendingRequests.delete(s),n.resolve(i);return}}this.handleNotification(i)})}handleNotification(e){const t=e.method,i=e.params??{};switch(this.captureContextWindowFromPayload(t,i),this.activeEventId&&this.resetIdleTimer(this.activeEventId),this.activeEventId&&t&&t.startsWith("item/")&&!t.endsWith("/requestApproval")&&this.startComposing(),t){case"item/started":{const s=i.item,n=s?.id,o=s?.type,d=s?.phase;this.isLongRunningToolItemType(o)&&(this.inFlightToolOps+=1),o==="agentMessage"&&n&&(typeof d=="string"&&d.trim()?this.agentMessagePhases.set(n,d.trim().toLowerCase()):this.agentMessagePhases.delete(n),ee(d)?(this.visibleAgentMessageIds.add(n),this.hiddenAgentMessageIds.delete(n)):(this.hiddenAgentMessageIds.add(n),this.visibleAgentMessageIds.delete(n)));break}case"item/agentMessage/delta":{const s=i.delta,n=i.itemId;s&&this.activeEventId&&(!n||!this.hiddenAgentMessageIds.has(n))&&!this.shouldSuppressAgentMessageDeltaDuringToolRun(n)&&this.emitCodexEvent("item/agentMessage/delta",e);break}case"item/completed":{const s=i.item,n=s?.id,o=s?.type;this.isLongRunningToolItemType(o)&&(this.inFlightToolOps=Math.max(0,this.inFlightToolOps-1)),this.activeEventId&&o!=="agentMessage"&&this.emitCodexEvent("item/completed",e),o==="agentMessage"&&n&&(this.visibleAgentMessageIds.delete(n),this.hiddenAgentMessageIds.delete(n),this.agentMessagePhases.delete(n));break}case"turn/started":{const n=i.turn?.id;n&&(this.currentTurnId=n,this.turnError=null,r.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(i);break}case"error":{const s=i.message??JSON.stringify(i);r.error("codex-adapter",`Codex error: ${s}`),s&&(this.turnError=s),this.activeEventId&&this.callbacks.sendRunError(this.activeEventId,this.activeSessionId??"",s);break}case"account/rateLimits/updated":{this.rateLimitSnapshot=this.parseRateLimitSnapshot(i),this.rateLimitSnapshot&&(r.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 s=i.threadId,n=i.tokenUsage,o=n?.last;(!s||!n||!o)&&r.info("codex-adapter",`[cp-diagnose] token_usage payload_incomplete: method=thread/tokenUsage/updated hasThreadId=${String(!!s)} hasTokenUsage=${String(!!n)} hasLast=${String(!!o)} params=${JSON.stringify(i)}`),s&&n&&o&&(this.currentThreadTokenUsage={inputTokens:o.inputTokens??0,outputTokens:o.outputTokens??0,cacheReadInputTokens:o.cachedInputTokens??0,cacheCreationInputTokens:0},r.info("codex-adapter",`[cp-diagnose] token_usage raw thread=${s}: ${JSON.stringify(n)}`),r.info("codex-adapter",`[cp-diagnose] token_usage parsed thread=${s}: ${JSON.stringify(this.currentThreadTokenUsage)}`),this.callbacks.onTokenUsageUpdated?.(this.currentThreadTokenUsage),this.publishContextWindowSnapshot());break}default:break}}captureContextWindowFromPayload(e,t){const i=["model_context_window","modelContextWindow","context_window_size","contextWindowSize"],s=this.findNumericField(t,i);if(s==null||s<=0){const n=this.probeContextWindowFields(t,i);n.foundAnyCandidateField&&r.info("codex-adapter",`[cp-diagnose] context_window missing_or_invalid: method=${e??"-"} matchedFields=${n.matchedFields.join(",")||"-"} raw=${n.rawValues.join(",")||"-"} extracted=${String(s)}`);return}this.currentModelContextWindow!==s&&(this.currentModelContextWindow=s,r.info("codex-adapter",`[cp-diagnose] context_window updated: method=${e??"-"} size=${s}`),this.publishContextWindowSnapshot())}probeContextWindowFields(e,t){const i=[],s=[],n=o=>{if(!o||typeof o!="object")return;if(Array.isArray(o)){for(const h of o)n(h);return}const d=o;for(const h of t)Object.prototype.hasOwnProperty.call(d,h)&&(i.push(h),s.push(String(d[h])));for(const h of Object.values(d))n(h)};return n(e),{foundAnyCandidateField:i.length>0,matchedFields:i,rawValues:s}}findNumericField(e,t){if(!e||typeof e!="object")return null;const i=e;for(const s of t){const n=i[s];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){const o=Number(n);if(Number.isFinite(o))return o}}for(const s of Object.values(i)){if(Array.isArray(s)){for(const o of s){const d=this.findNumericField(o,t);if(d!=null)return d}continue}const n=this.findNumericField(s,t);if(n!=null)return n}return null}buildContextWindowSnapshot(){const e=this.currentModelContextWindow;if(!e||e<=0)return r.debug("codex-adapter",`[cp-diagnose] context_window snapshot skipped: invalid size=${String(e)}`),null;const t=this.currentThreadTokenUsage,i=t?t.inputTokens+t.outputTokens:null,s=i==null?null:Math.max(0,e-i),n=i==null?null:Math.min(100,i/e*100),o=i==null?null:Math.max(0,100-(n??0));return r.info("codex-adapter",`[cp-diagnose] context_window computed: threadId=${this.threadId??"-"} size=${e} usedTokens=${String(i)} usedPercentage=${String(n)}`),{sizeTokens:e,usedTokens:i,remainingTokens:s,usedPercentage:n,remainingPercentage:o,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<L||this.pendingAutoCompact||this.compacting||(this.pendingAutoCompact=!0,r.info("codex-adapter",`[auto-compact] context_window usedPercentage=${t.toFixed(1)}% >= ${L}%, 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=>{r.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=>{r.warn("codex-adapter",`[auto-compact] compact error: ${e instanceof Error?e.message:e}`)})))}parseRateLimitSnapshot(e){try{const i=e.rateLimitsByLimitId?.codex??e.rateLimits??e,s=i.primary,n=i.secondary,o=i.credits,d=c=>{if(typeof c=="number"&&Number.isFinite(c))return c;if(typeof c=="string"){const I=Number(c);if(Number.isFinite(I))return I}return 0},h=c=>typeof c=="boolean"?c:typeof c=="string"?c.toLowerCase()==="true":!1,u=c=>{if(c==null)return null;if(typeof c=="string"){const I=c.trim();if(!I)return null;const w=Number(I);return Number.isFinite(w)&&w>1e9?new Date(w*1e3).toISOString():I}if(typeof c=="number"&&Number.isFinite(c)&&c>0){const I=c>1e12?c/1e3:c;return new Date(I*1e3).toISOString()}return null},f=c=>({usedPercent:d(c.used_percent??c.usedPercent),windowMinutes:d(c.window_minutes??c.windowDurationMins??c.windowMinutes),resetsAt:u(c.resets_at??c.resetsAt)}),p=()=>({usedPercent:0,windowMinutes:0,resetsAt:null}),x=()=>{const c=i.windows;if(!Array.isArray(c))return null;const I=c.map(b=>b&&typeof b=="object"?f(b):p()).filter(b=>b.windowMinutes>0);if(I.length===0)return null;const w=[...I].sort((b,z)=>b.windowMinutes-z.windowMinutes),H=w.find(b=>Math.abs(b.windowMinutes-300)<=30)??w[0],U=w.find(b=>Math.abs(b.windowMinutes-10080)<=120)??w[w.length-1];return{primary:H,secondary:U}},m=(s||n?{primary:s?f(s):p(),secondary:n?f(n):p()}:null)??x();return m?{primary:m.primary,secondary:m.secondary,credits:o?{hasCredits:h(o.has_credits??o.hasCredits),unlimited:h(o.unlimited),balance:o.balance==null?null:d(o.balance)}:{hasCredits:!1,unlimited:!1,balance:null}}:null}catch{return null}}handleApprovalRequest(e,t){const i=e.id;if(i==null)return;const s=e.method,n=`${i}`.trim(),o=`codex_${F(this.activeSessionId??"")}_${F(n)}`;if(this.approvalPolicy==="never"){this.sendApprovalDecision(i,"accept");return}this.activeEventId&&this.emitCodexEvent(s,e),this.pendingApprovals.set(o,{approvalId:o,approvalCommandId:n,sourceEventId:this.activeEventId??"",requestId:i,kind:t}),r.info("codex-adapter",`Pending approval stored: ${o} (kind=${t})`),this.clearIdleTimer(),this.stopComposing()}resolvePendingApproval(e){const t=e.params??{},i=g(t.approval_id,t.approvalId);if(i)return this.pendingApprovals.get(i)??null;const s=g(t.approval_command_id,t.approvalCommandId);if(s){for(const[,n]of this.pendingApprovals)if(n.approvalCommandId===s)return n}return null}sendApprovalDecision(e,t){if(e==null||!this.process?.stdin)return;const i={jsonrpc:"2.0",id:e,result:{decision:t}};this.process.stdin.write(`${JSON.stringify(i)}
4
- `)}armCompactionFallback(){this.compacting&&(this.compactingTimer&&clearTimeout(this.compactingTimer),this.compactingTimer=setTimeout(()=>{r.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")},fe),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);r.info("codex-adapter",`Compaction finished (${e}); replaying ${t.length} deferred events`);for(const s of t)this.deliverInboundEvent(s);const i=this.compactionDoneResolver;this.compactionDoneResolver=null,i?.()}handleTurnCompleted(e){if(this.currentTurnId=null,this.stopComposing(),this.activeEventId){const t=this.activeEventId,i={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()},s=this.turnError;this.turnError=null;const n=!!s;this.callbacks.sendCodexEventReliable?(this.clearActive({runPendingAutoCompact:!1}),this.callbacks.sendCodexEventReliable(i).then(()=>{this.callbacks.sendEventResult(t,n?"failed":"responded",n?s??void 0:void 0),this.tryRunPendingAutoCompact()}).catch(o=>{r.error("codex-adapter",`sendCodexEventReliable failed event=${t}: ${o}`),this.callbacks.sendCodexEvent(i),this.callbacks.sendEventResult(t,n?"failed":"responded",n?s??void 0:void 0),this.tryRunPendingAutoCompact()})):(this.callbacks.sendCodexEvent(i),this.callbacks.sendEventResult(t,n?"failed":"responded",n?s??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,i=3e4){return new Promise((s,n)=>{if(!this.process?.stdin){n(new Error("Codex process not available"));return}const o=++this.requestId,d={jsonrpc:"2.0",id:o,method:e,params:t??{}},h=setTimeout(()=>{this.pendingRequests.delete(String(o)),n(new Error(`Request timeout: ${e}`))},i);this.pendingRequests.set(String(o),{resolve:f=>{f.error?n(new Error(`JSON-RPC error: ${f.error.message}`)):s(f.result)},reject:n,timer:h});const u=JSON.stringify(d);this.process.stdin.write(`${u}
1
+ import{execFileSync as A}from"node:child_process";import{createInterface as W}from"node:readline";import{EventEmitter as E}from"node:events";import{stat as M}from"node:fs/promises";import{join as T,resolve as B}from"node:path";import{fileURLToPath as J}from"node:url";import{homedir as G}from"node:os";import{syncDefaultSkillsToDir as X}from"../../default-skills/index.js";import{resolveCommandPath as V,spawnCommand as Y,killProcessGroup as R,hasChildProcesses as K}from"../../core/runtime/spawn.js";import{InternalApiServer as Z}from"../../core/mcp/internal-api-server.js";import{log as r}from"../../core/log/index.js";import{resolveClientVersion as Q}from"../../core/util/client-version.js";import{isUserVisibleAgentMessagePhase as ee}from"../../core/util/codex-output-policy.js";import{SessionBindingStore as te}from"../../core/persistence/session-binding-store.js";import{ensureCodexProjectTrusted as se,isCodexCommand as ie,readCodexProviderSettings as C}from"./codex-trust.js";import{checkCodexSessionActivity as ne}from"./session-activity.js";import{findRolloutFile as oe}from"./rollout-locator.js";import{checkCodexLock as P}from"./lock-monitor.js";import{resolveCliPath as re,getCliVersion as ae}from"../../core/util/cli-probe.js";import{scanSkills as de}from"../claude/skill-scanner.js";const ce=60*1e3,le=600*1e3,he=5*1e3,$=2,ue=20,pe=8e3,L=80,fe=120*1e3,me=[{id:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",defaultReasoningEffort:null,supportedReasoningEfforts:[],isDefault:!0}],N=[{id:"default",displayName:"Default"},{id:"plan",displayName:"Plan"}];function O(a,e){const t=String(a??"").trim()||"codex",i=V(t,e);if(i!==t)return i;const s=process.platform==="win32"?[]:["/opt/homebrew/bin/codex","/usr/local/bin/codex","/usr/bin/codex"],n=process.platform!=="win32"?[]:[T(process.env.LOCALAPPDATA??"","npm","codex.cmd"),T(process.env.APPDATA??"","npm","codex.cmd"),T(process.env.LOCALAPPDATA??"","Programs","codex","codex.exe")],o=[...s,...n];for(const d of o)try{return require("node:fs").accessSync(d,require("node:fs").constants.X_OK),d}catch{continue}return r.warn("codex-adapter",`resolveCodexCommandPath: failed to resolve "${t}". envPath=${e?"provided":"missing (using process.env.PATH)"}. fallbacks tried: [${o.join(", ")}]`),t}class q extends E{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;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 i=e.options??{};if(this.approvalPolicy=i.approvalPolicy??"never",this.sandboxMode=typeof i.sandboxMode=="string"&&i.sandboxMode.trim()&&i.sandboxMode.trim()!=="default"?i.sandboxMode.trim():void 0,this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.bindingStore=i.bindingStore instanceof te?i.bindingStore:null,this.model=i.model,this.collaborationMode=i.collaborationMode,this.reasoningEffort=i.reasoningEffort,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.sandboxMode=this.sandboxMode??this.bindingStore.getCodexSandboxMode(this.aibotSessionId)),this.autoTrustProject=typeof i.autoTrustProject=="boolean"?i.autoTrustProject:"auto",this.codexHome=typeof i.codexHome=="string"&&i.codexHome.trim()?i.codexHome.trim():void 0,this.cwd=this.resolveCwd(),this.bindingStore&&this.aibotSessionId){const s=this.bindingStore.getCodexThreadId(this.aibotSessionId);s&&(this.threadId=s,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(),r.info("codex-adapter",`Ready (pid=${this.process?.pid})`)}async ensureProjectTrusted(){if(this.shouldAutoTrustProject())try{const e=await se(this.cwd,{codexHome:this.codexHome});e.changed&&r.info("codex-adapter",`Trusted Codex project ${this.cwd} in ${e.configPath}`)}catch(e){const t=e instanceof Error?e.message:String(e);throw r.error("codex-adapter",`Failed to trust Codex project ${this.cwd}: ${t}`),e}}async startInternalApiAndRegisterMcp(){try{this.internalApi=new Z,this.internalApi.setInvokeHandler(async(d,u)=>this.callbacks.agentInvoke(d,u)),await this.internalApi.start(0),r.info("codex-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),t={...process.env,...this.config.env},i=typeof t.PATH=="string"?t.PATH:void 0,s=O(this.config.command||"codex",i);try{A(s,["mcp","remove",e.name],{env:t,timeout:1e4,stdio:"ignore"})}catch{}A(s,["mcp","add",e.name,"--",e.command,...e.args],{env:t,timeout:1e4,stdio:"ignore"}),r.info("codex-adapter",`Registered MCP server: ${e.name}`);const n=T(G(),".codex","skills"),o=X(n);o.length>0&&r.info("codex-adapter",`Synced connector skills to ${n}: [${o.join(", ")}]`)}catch(e){r.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:ie(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){r.warn("codex-adapter",`Failed to attach toolbar context to binding update: ${e instanceof Error?e.message:String(e)}`),this.notifyBindingReady()}}getEffortMeta(){const e=this.currentModelId(),t=this.getModelOption(e),i=t?.supportedReasoningEfforts??[];return i.length===0?{}:{available_efforts:i,reasoning_effort:this.reasoningEffort??t?.defaultReasoningEffort??null}}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")R(e,"SIGTERM"),await Promise.race([new Promise(i=>{e.once("exit",()=>i(!0))}),new Promise(i=>{setTimeout(()=>i(!1),5e3)})])||R(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 S(e.adapterSessionId);return this.runTurn(e,t).catch(i=>{t.emitError(i instanceof Error?i:new Error(String(i)))}),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),i=!!(this.process.stdout&&!this.process.stdout.destroyed);return t&&i}if(!this.process.stdin||this.process.stdin.destroyed)return!!(this.process.stdout&&!this.process.stdout.destroyed);try{const t=++this.requestId,i={jsonrpc:"2.0",id:t,method:"ping",params:{}};return await new Promise(s=>{const n=setTimeout(()=>{this.pendingRequests.delete(String(t)),s(!1)},e);this.pendingRequests.set(String(t),{resolve:()=>s(!0),reject:()=>s(!1),timer:n}),this.process.stdin.write(`${JSON.stringify(i)}
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(),r.info("codex-adapter",`Model set to: ${e}`)}setMode(e){const t=y(e);if(!t){r.info("codex-adapter",`Ignoring unsupported mode: ${e}`);return}this.collaborationMode=t,this.persistCodexContext(),r.info("codex-adapter",`Mode set to: ${t}`)}setReasoningEffort(e){this.reasoningEffort=e,this.persistCodexContext(),r.info("codex-adapter",`Reasoning effort set to: ${e}`)}setSandboxMode(e){this.sandboxMode=e,this.persistCodexContext(),r.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=B(J(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?K(e,[e]):!1}onAgentProfileChanged(){this.identityInjectedThreadId!==null&&(r.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",i=await re(t),s=i!==null;let n=null,o;if(s){const g=await ae(t);n=g.version,g.error&&(o=g.error)}else o={code:"cli_not_found",message:`command not found: ${t}`};const u=C().baseUrl??null,p=this.currentModelId()||null,f=this.getStatus(),h=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},m=await this.probeSessionRecord(),v=P({codexHome:this.codexHome});return{cli:{command:t,installed:s,path:i,version:n,...o?{error:o}:{}},conversation:h,config:{model:p,base_url:u,source:{model:p?"runtime":"unknown",base_url:u?"file":"unknown"}},process:{started:!!this.process,alive:f.alive,busy:f.busy},session:m,lock:{present:v.present,locked:v.locked,stale:v.stale,path:v.path}}}async probeSessionRecord(){const e=this.threadId?oe(this.threadId,this.codexHome):null;if(!e)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const t=await M(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,i){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 s=new Promise(n=>{this.compactionDoneResolver=n});try{return await this.threadCompact(),this.armCompactionFallback(),await s,{status:"ok",message:"Thread compacted"}}catch(n){this.finishCompaction("compact-error");const o=n instanceof Error?n.message:String(n);if(/thread.*(not found|not exist|unknown|invalid)/i.test(o)||/not found.*thread/i.test(o))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 s=t.trim();return s?this.getModelOptions().some(o=>o.id===s)?(this.setModel(s),{status:"ok",message:`Model set to ${s}`}):{status:"failed",message:`Unknown model: ${s}`}:{status:"ok",message:`Current: ${this.currentModelId()}`,data:{models:this.getModelOptions()}}}case"mode":{const s=t.trim();if(s){const n=y(s);return n?(this.setMode(n),{status:"ok",message:`Mode set to ${n}`}):{status:"failed",message:`Unknown mode: ${s}. Supported: default, plan`}}return{status:"ok",message:`Current: ${this.collaborationMode??"default"}`,data:{modes:N}}}case"rollback":{if(!this.threadId)return{status:"failed",message:"No active thread"};const s=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(s),{status:"ok",message:`Rolled back ${s} 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 s=de({mode:"codex",projectDir:this.cwd}),n=s.map(o=>`- ${o.name}${o.trigger?` (${o.trigger})`:""}: ${o.description}`);return{status:"ok",message:n.length>0?n.join(`
3
+ `):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${e}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}async handleLocalAction(e){const t=e.action_type??"",i=e.params??{};switch(r.info("codex-adapter",`handleLocalAction action_type=${t} action_id=${e.action_id} session_id=${i.session_id??""}`),t){case"set_model":{const s=x(l(i.model_id),l(i.modelId),l(i.value));return s&&this.setModel(s),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("model_set")),{handled:!0,kind:"set_model"}}case"set_mode":{const s=i.mode_id;return s&&this.setMode(s),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("mode_set")),{handled:!0,kind:"set_mode"}}case"set_reasoning_effort":{const s=x(l(i.reasoning_effort),l(i.reasoning_eff),l(i.effort));return s&&this.setReasoningEffort(s),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("effort_set",!1)),{handled:!0,kind:"set_reasoning_effort"}}case"set_sandbox_mode":{const s=x(l(i.sandbox_mode),l(i.sandboxMode),l(i.value));return s&&this.setSandboxMode(s),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("sandbox_mode_set",!1)),{handled:!0,kind:"set_sandbox_mode"}}case"thread_compact":{r.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 r.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 s=new Promise(n=>{this.compactionDoneResolver=n});await this.threadCompact(),this.armCompactionFallback(),await s,r.info("codex-adapter",`thread_compact done action_id=${e.action_id}`),this.callbacks.sendLocalActionResult(e.action_id,"ok")}catch(s){this.finishCompaction("compact-error");const n=s instanceof Error?s.message:String(s);/thread.*(not found|not exist|unknown|invalid)/i.test(n)||/not found.*thread/i.test(n)?(r.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.")):(r.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 s=this.resolvePendingApproval(e);if(!s)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=i.decision||"allow-once",o=ge[n]??"accept";return this.sendApprovalDecision(s.requestId,o),this.pendingApprovals.delete(s.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:s.approvalId,approval_command_id:s.approvalCommandId,decision:n}),this.resumeAfterApproval(e,i,s),{handled:!0,kind:t}}case"exec_reject":case"file_reject":{const s=this.resolvePendingApproval(e);return s?(this.sendApprovalDecision(s.requestId,"deny"),this.pendingApprovals.delete(s.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:s.approvalId,approval_command_id:s.approvalCommandId,decision:"deny"}),this.resumeAfterApproval(e,i,s),{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 s=this.resolvePendingApproval(e);return!s||s.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(s.requestId,"accept"),this.pendingApprovals.delete(s.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:s.approvalId,decision:"approve"}),this.resumeAfterApproval(e,i,s),{handled:!0,kind:t})}case"permission_reject":{const s=this.resolvePendingApproval(e);return!s||s.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(s.requestId,"deny"),this.pendingApprovals.delete(s.approvalId),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:s.approvalId,decision:"deny"}),this.resumeAfterApproval(e,i,s),{handled:!0,kind:t})}case"turn_interrupt":{try{await this.cancel(this.threadId??""),this.callbacks.sendLocalActionResult(e.action_id,"ok")}catch(s){this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,void 0,s instanceof Error?s.message:String(s))}return{handled:!0,kind:"turn_interrupt"}}case"thread_rollback":{const s=Number(i.numTurns??i.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(s),this.callbacks.sendLocalActionResult(e.action_id,"ok",{numTurns:s})}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 s=this.rateLimitSnapshot,n=this.buildContextWindowSnapshot(),o=Date.now(),d=this.currentThreadTokenUsage;return s?r.info("codex-adapter",`[rate-limits] responding: primary=${s.primary.usedPercent.toFixed(1)}% window=${s.primary.windowMinutes}min resetsAt=${s.primary.resetsAt} secondary=${s.secondary.usedPercent.toFixed(1)}% window=${s.secondary.windowMinutes}min resetsAt=${s.secondary.resetsAt}`):r.info("codex-adapter","[rate-limits] responding: no rateLimitSnapshot available"),r.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:s!==null,cached:!1,sampledAt:o,rateLimits:s,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 i=y(this.collaborationMode)??"default",s=this.currentModelId(),n=this.getModelOption(s),o=this.getModelOptions(),d=N,u=this.reasoningEffort??n?.defaultReasoningEffort??null,p=n?.supportedReasoningEfforts??[],f=C(this.codexHome),h=!!(f.baseUrl&&D(f.baseUrl)),m=h?[]:p,v=h?null:u,g={outcome:e,session_context:{modelId:s,modeId:i,reasoningEffort:v,approvalPolicy:this.approvalPolicy,sandboxMode:this.sandboxMode??null},model_id:s,mode_id:i,currentModelId:s,currentModeId:i,available_models:o,available_modes:d,available_efforts:m,availableModels:o,availableModes:d,reasoning_effort:v,sandbox_mode:this.sandboxMode??null,models:o.map(c=>({modelId:c.id,name:c.displayName})),modes:d.map(c=>({id:c.id,name:c.displayName}))};return this.rateLimitSnapshot&&(g.rate_limit_primary_percent=this.rateLimitSnapshot.primary.usedPercent,g.rate_limit_secondary_percent=this.rateLimitSnapshot.secondary.usedPercent,g.rate_limit_primary_window_min=this.rateLimitSnapshot.primary.windowMinutes,g.rate_limit_secondary_window_min=this.rateLimitSnapshot.secondary.windowMinutes),g}currentModelId(){const e=String(this.model??"").trim();if(e)return e;const t=this.getModelOptions();return t.find(i=>i.isDefault)?.id??t[0]?.id??""}getModelOption(e){const t=e.trim().toLowerCase();return this.getModelOptions().find(i=>i.id.trim().toLowerCase()===t)}getModelOptions(){const e=this.config.options??{},t=e.available_models??e.availableModels??e.models,i=we(t),s=this.codexModelOptions,n=[],o=String(this.model??"").trim(),d=o&&!s.some(h=>h.id.trim().toLowerCase()===o.toLowerCase()),u=s.length>0?s:d?[]:me;if(o){const h=[...s,...i].find(m=>m.id.trim().toLowerCase()===o.toLowerCase());n.push({id:o,displayName:h?.displayName??_(o),defaultReasoningEffort:h?.defaultReasoningEffort??null,supportedReasoningEfforts:h?.supportedReasoningEfforts??[],isDefault:h?.isDefault??!1})}n.push(...i),n.push(...u);const p=[],f=new Set;for(const h of n){const m=h.id.trim(),v=m.toLowerCase();!m||f.has(v)||(f.add(v),p.push({id:m,displayName:h.displayName.trim()||m,defaultReasoningEffort:h.defaultReasoningEffort,supportedReasoningEfforts:[...h.supportedReasoningEfforts],isDefault:h.isDefault}))}return p}async refreshCodexModelOptions(){if(!this.initialized||!this.alive||!this.process?.stdin||Date.now()-this.codexModelOptionsCachedAt<q.MODEL_CACHE_TTL_MS)return;const e=C(this.codexHome);if(e.baseUrl&&D(e.baseUrl)){try{const t=await ye(e.baseUrl,e.apiKey);if(t.length>0){this.codexModelOptions=j(t),this.codexModelOptionsCachedAt=Date.now(),r.info("codex-adapter",`Loaded ${t.length} models from external provider ${e.baseUrl}`);return}}catch(t){r.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 i;do{const s=await this.sendRequest("model/list",{cursor:i??null,includeHidden:!1,limit:100},15e3),n=Te(s);t.push(...n.models),i=n.nextCursor}while(i);t.length>0&&(this.codexModelOptions=j(t),this.codexModelOptionsCachedAt=Date.now())}catch(t){r.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;deliverInboundEvent(e){if(this.compacting){r.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()){r.info("codex-adapter",`Event ${e.event_id}: steering active turn ${this.currentTurnId}`),this.steerTurn(t).catch(i=>{const s=i instanceof Error?i.message:String(i);if(r.info("codex-adapter",`Steer failed, falling through: ${s}`),!this.currentTurnId){this.startNewTurn(e,t);return}if(ke(s)){r.info("codex-adapter","Unsteerable turn detected, clearing active state and starting new turn"),this.clearActive(),this.startNewTurn(e,t);return}r.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){r.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 i=this.threadId??"",s=new S(i),n={adapterSessionId:i,text:t,contextMessages:e.context_messages_json?JSON.parse(e.context_messages_json).map(o=>({senderId:o.sender_id??"unknown",content:o.content})):void 0};this.runTurn(n,s,e.event_id,e.session_id).catch(o=>{r.error("codex-adapter",`Turn failed: ${o}`),this.callbacks.sendEventResult(e.event_id,"failed",o instanceof Error?o.message:String(o)),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||r.warn("codex-adapter",`spawnCodex: env.PATH is missing! process.env.PATH=${process.env.PATH?"set":"missing"}, config.env=${JSON.stringify(this.config.env)}`);const i=O(this.config.command||"codex",t),s=xe(this.config.args);this.sandboxMode&&s.push("-c",`sandbox_mode="${this.sandboxMode}"`),r.info("codex-adapter",`Spawning: ${i} ${s.join(" ")}`);try{if(!(await M(this.cwd)).isDirectory())throw new Error(`Bound path is not a directory: ${this.cwd}`)}catch(o){throw String(o?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${this.cwd}. Please rebind with /grix open <valid-directory>.`):o}const n=P({codexHome:this.codexHome});if(n.locked&&!n.stale)throw new Error(`Codex session appears locked by another process: ${n.path}`);n.stale&&r.warn("codex-adapter",`Ignoring stale Codex lock: ${n.path}`);try{this.process=Y(i,s,{env:e,cwd:this.cwd}).process}catch(o){throw r.error("codex-adapter",`Codex spawn threw: ${o}`),this.process=null,this.alive=!1,this.bridgeStatus="closed",o}this.process.on("error",o=>{r.error("codex-adapter",`Codex process spawn error: ${o}`),this.process=null,this.alive=!1,this.bridgeStatus="closed",this.clearIdleTimer(),this.rejectAllPending("spawn failed: "+(o instanceof Error?o.message:String(o))),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",o=>{r.info("codex-adapter",`Codex process exited (code=${o})`),this.alive=!1,this.bridgeStatus="closed",this.clearIdleTimer(),this.rejectAllPending("process exited"),this.stopComposing(),this.emit("exit",o)}),this.process.stderr?.on("data",o=>{const d=o.toString().trim();d&&r.info("codex-adapter",`[codex stderr] ${d}`)}),this.bindStdout(),this.alive=!0}bindStdout(){if(!this.process?.stdout)return;this.process.stdout.setEncoding("utf8"),W({input:this.process.stdout}).on("line",t=>{if(!t.trim())return;let i;try{i=JSON.parse(t)}catch{r.error("codex-adapter",`Invalid JSON from Codex: ${t.slice(0,200)}`);return}if(this.bridgeStatus==="starting"&&(this.bridgeStatus="ready"),i.id!=null){const s=String(i.id),n=this.pendingRequests.get(s);if(n){clearTimeout(n.timer),this.pendingRequests.delete(s),n.resolve(i);return}}this.handleNotification(i)})}handleNotification(e){const t=e.method,i=e.params??{};switch(this.captureContextWindowFromPayload(t,i),this.activeEventId&&this.resetIdleTimer(this.activeEventId),this.activeEventId&&t&&t.startsWith("item/")&&!t.endsWith("/requestApproval")&&this.startComposing(),t){case"item/started":{const s=i.item,n=s?.id,o=s?.type,d=s?.phase;this.isLongRunningToolItemType(o)&&(this.inFlightToolOps+=1),o==="agentMessage"&&n&&(typeof d=="string"&&d.trim()?this.agentMessagePhases.set(n,d.trim().toLowerCase()):this.agentMessagePhases.delete(n),ee(d)?(this.visibleAgentMessageIds.add(n),this.hiddenAgentMessageIds.delete(n)):(this.hiddenAgentMessageIds.add(n),this.visibleAgentMessageIds.delete(n)));break}case"item/agentMessage/delta":{const s=i.delta,n=i.itemId;s&&this.activeEventId&&(!n||!this.hiddenAgentMessageIds.has(n))&&!this.shouldSuppressAgentMessageDeltaDuringToolRun(n)&&this.emitCodexEvent("item/agentMessage/delta",e);break}case"item/completed":{const s=i.item,n=s?.id,o=s?.type;this.isLongRunningToolItemType(o)&&(this.inFlightToolOps=Math.max(0,this.inFlightToolOps-1)),this.activeEventId&&o!=="agentMessage"&&this.emitCodexEvent("item/completed",e),o==="agentMessage"&&n&&(this.visibleAgentMessageIds.delete(n),this.hiddenAgentMessageIds.delete(n),this.agentMessagePhases.delete(n));break}case"turn/started":{const n=i.turn?.id;n&&(this.currentTurnId=n,this.turnError=null,r.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(i);break}case"error":{const s=i.message??JSON.stringify(i);r.error("codex-adapter",`Codex error: ${s}`),s&&(this.turnError=s),this.activeEventId&&this.callbacks.sendRunError(this.activeEventId,this.activeSessionId??"",s);break}case"account/rateLimits/updated":{this.rateLimitSnapshot=this.parseRateLimitSnapshot(i),this.rateLimitSnapshot&&(r.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 s=i.threadId,n=i.tokenUsage,o=n?.last;(!s||!n||!o)&&r.info("codex-adapter",`[cp-diagnose] token_usage payload_incomplete: method=thread/tokenUsage/updated hasThreadId=${String(!!s)} hasTokenUsage=${String(!!n)} hasLast=${String(!!o)} params=${JSON.stringify(i)}`),s&&n&&o&&(this.currentThreadTokenUsage={inputTokens:o.inputTokens??0,outputTokens:o.outputTokens??0,cacheReadInputTokens:o.cachedInputTokens??0,cacheCreationInputTokens:0},r.info("codex-adapter",`[cp-diagnose] token_usage raw thread=${s}: ${JSON.stringify(n)}`),r.info("codex-adapter",`[cp-diagnose] token_usage parsed thread=${s}: ${JSON.stringify(this.currentThreadTokenUsage)}`),this.callbacks.onTokenUsageUpdated?.(this.currentThreadTokenUsage),this.publishContextWindowSnapshot());break}default:break}}captureContextWindowFromPayload(e,t){const i=["model_context_window","modelContextWindow","context_window_size","contextWindowSize"],s=this.findNumericField(t,i);if(s==null||s<=0){const n=this.probeContextWindowFields(t,i);n.foundAnyCandidateField&&r.info("codex-adapter",`[cp-diagnose] context_window missing_or_invalid: method=${e??"-"} matchedFields=${n.matchedFields.join(",")||"-"} raw=${n.rawValues.join(",")||"-"} extracted=${String(s)}`);return}this.currentModelContextWindow!==s&&(this.currentModelContextWindow=s,r.info("codex-adapter",`[cp-diagnose] context_window updated: method=${e??"-"} size=${s}`),this.publishContextWindowSnapshot())}probeContextWindowFields(e,t){const i=[],s=[],n=o=>{if(!o||typeof o!="object")return;if(Array.isArray(o)){for(const u of o)n(u);return}const d=o;for(const u of t)Object.prototype.hasOwnProperty.call(d,u)&&(i.push(u),s.push(String(d[u])));for(const u of Object.values(d))n(u)};return n(e),{foundAnyCandidateField:i.length>0,matchedFields:i,rawValues:s}}findNumericField(e,t){if(!e||typeof e!="object")return null;const i=e;for(const s of t){const n=i[s];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){const o=Number(n);if(Number.isFinite(o))return o}}for(const s of Object.values(i)){if(Array.isArray(s)){for(const o of s){const d=this.findNumericField(o,t);if(d!=null)return d}continue}const n=this.findNumericField(s,t);if(n!=null)return n}return null}buildContextWindowSnapshot(){const e=this.currentModelContextWindow;if(!e||e<=0)return r.debug("codex-adapter",`[cp-diagnose] context_window snapshot skipped: invalid size=${String(e)}`),null;const t=this.currentThreadTokenUsage,i=t?t.inputTokens+t.outputTokens:null,s=i==null?null:Math.max(0,e-i),n=i==null?null:Math.min(100,i/e*100),o=i==null?null:Math.max(0,100-(n??0));return r.info("codex-adapter",`[cp-diagnose] context_window computed: threadId=${this.threadId??"-"} size=${e} usedTokens=${String(i)} usedPercentage=${String(n)}`),{sizeTokens:e,usedTokens:i,remainingTokens:s,usedPercentage:n,remainingPercentage:o,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<L||this.pendingAutoCompact||this.compacting||(this.pendingAutoCompact=!0,r.info("codex-adapter",`[auto-compact] context_window usedPercentage=${t.toFixed(1)}% >= ${L}%, 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=>{r.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=>{r.warn("codex-adapter",`[auto-compact] compact error: ${e instanceof Error?e.message:e}`)})))}parseRateLimitSnapshot(e){try{const i=e.rateLimitsByLimitId?.codex??e.rateLimits??e,s=i.primary,n=i.secondary,o=i.credits,d=c=>{if(typeof c=="number"&&Number.isFinite(c))return c;if(typeof c=="string"){const I=Number(c);if(Number.isFinite(I))return I}return 0},u=c=>typeof c=="boolean"?c:typeof c=="string"?c.toLowerCase()==="true":!1,p=c=>{if(c==null)return null;if(typeof c=="string"){const I=c.trim();if(!I)return null;const w=Number(I);return Number.isFinite(w)&&w>1e9?new Date(w*1e3).toISOString():I}if(typeof c=="number"&&Number.isFinite(c)&&c>0){const I=c>1e12?c/1e3:c;return new Date(I*1e3).toISOString()}return null},f=c=>({usedPercent:d(c.used_percent??c.usedPercent),windowMinutes:d(c.window_minutes??c.windowDurationMins??c.windowMinutes),resetsAt:p(c.resets_at??c.resetsAt)}),h=()=>({usedPercent:0,windowMinutes:0,resetsAt:null}),m=()=>{const c=i.windows;if(!Array.isArray(c))return null;const I=c.map(b=>b&&typeof b=="object"?f(b):h()).filter(b=>b.windowMinutes>0);if(I.length===0)return null;const w=[...I].sort((b,z)=>b.windowMinutes-z.windowMinutes),H=w.find(b=>Math.abs(b.windowMinutes-300)<=30)??w[0],U=w.find(b=>Math.abs(b.windowMinutes-10080)<=120)??w[w.length-1];return{primary:H,secondary:U}},g=(s||n?{primary:s?f(s):h(),secondary:n?f(n):h()}:null)??m();return g?{primary:g.primary,secondary:g.secondary,credits:o?{hasCredits:u(o.has_credits??o.hasCredits),unlimited:u(o.unlimited),balance:o.balance==null?null:d(o.balance)}:{hasCredits:!1,unlimited:!1,balance:null}}:null}catch{return null}}handleApprovalRequest(e,t){const i=e.id;if(i==null)return;const s=e.method,n=`${i}`.trim(),o=`codex_${F(this.activeSessionId??"")}_${F(n)}`;if(this.approvalPolicy==="never"){this.sendApprovalDecision(i,"accept");return}this.activeEventId&&this.emitCodexEvent(s,e),this.pendingApprovals.set(o,{approvalId:o,approvalCommandId:n,sourceEventId:this.activeEventId??"",requestId:i,kind:t}),r.info("codex-adapter",`Pending approval stored: ${o} (kind=${t})`),this.clearIdleTimer(),this.stopComposing()}resolvePendingApproval(e){const t=e.params??{},i=x(t.approval_id,t.approvalId);if(i)return this.pendingApprovals.get(i)??null;const s=x(t.approval_command_id,t.approvalCommandId);if(s){for(const[,n]of this.pendingApprovals)if(n.approvalCommandId===s)return n}return null}sendApprovalDecision(e,t){if(e==null||!this.process?.stdin)return;const i={jsonrpc:"2.0",id:e,result:{decision:t}};this.process.stdin.write(`${JSON.stringify(i)}
4
+ `)}armCompactionFallback(){this.compacting&&(this.compactingTimer&&clearTimeout(this.compactingTimer),this.compactingTimer=setTimeout(()=>{r.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")},fe),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);r.info("codex-adapter",`Compaction finished (${e}); replaying ${t.length} deferred events`);for(const s of t)this.deliverInboundEvent(s);const i=this.compactionDoneResolver;this.compactionDoneResolver=null,i?.()}handleTurnCompleted(e){if(this.currentTurnId=null,this.stopComposing(),this.activeEventId){const t=this.activeEventId,i={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()},s=this.turnError;this.turnError=null;const n=!!s;this.callbacks.sendCodexEventReliable?(this.clearActive({runPendingAutoCompact:!1}),this.callbacks.sendCodexEventReliable(i).then(()=>{this.callbacks.sendEventResult(t,n?"failed":"responded",n?s??void 0:void 0),this.tryRunPendingAutoCompact()}).catch(o=>{r.error("codex-adapter",`sendCodexEventReliable failed event=${t}: ${o}`),this.callbacks.sendCodexEvent(i),this.callbacks.sendEventResult(t,n?"failed":"responded",n?s??void 0:void 0),this.tryRunPendingAutoCompact()})):(this.callbacks.sendCodexEvent(i),this.callbacks.sendEventResult(t,n?"failed":"responded",n?s??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,i=3e4){return new Promise((s,n)=>{if(!this.process?.stdin){n(new Error("Codex process not available"));return}const o=++this.requestId,d={jsonrpc:"2.0",id:o,method:e,params:t??{}},u=setTimeout(()=>{this.pendingRequests.delete(String(o)),n(new Error(`Request timeout: ${e}`))},i);this.pendingRequests.set(String(o),{resolve:f=>{f.error?n(new Error(`JSON-RPC error: ${f.error.message}`)):s(f.result)},reject:n,timer:u});const p=JSON.stringify(d);this.process.stdin.write(`${p}
5
5
  `)})}sendNotification(e,t){if(!this.process?.stdin)return;const i={jsonrpc:"2.0",method:e,params:t??{}};this.process.stdin.write(`${JSON.stringify(i)}
6
- `)}async initializeHandshake(){if(this.initialized)return;const e=Q(),t=await this.sendRequest("initialize",{clientInfo:{name:"grix-connector",title:"Grix Connector",version:e},capabilities:{experimentalApi:!0}},15e3);r.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,r.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=>{r.warn("codex-adapter",`Failed to fetch rate limits: ${e instanceof Error?e.message:e}`)})}async runTurn(e,t,i,s){this.threadId||await this.createSession({cwd:this.cwd}),await this.ensureThreadResumed();const n=[];if(this.needsHistoryInjection&&s){this.needsHistoryInjection=!1;const h=await this.loadHistoryForInjection(s);for(const u of h)n.push(u);h.length>0&&r.info("codex-adapter",`Injected ${h.length} history items`)}if(e.contextMessages&&e.contextMessages.length>0){const h=e.contextMessages.map(u=>`[${u.senderId??"unknown"}]: ${u.content}`).join(`
6
+ `)}async initializeHandshake(){if(this.initialized)return;const e=Q(),t=await this.sendRequest("initialize",{clientInfo:{name:"grix-connector",title:"Grix Connector",version:e},capabilities:{experimentalApi:!0}},15e3);r.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,r.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=>{r.warn("codex-adapter",`Failed to fetch rate limits: ${e instanceof Error?e.message:e}`)})}async runTurn(e,t,i,s){this.threadId||await this.createSession({cwd:this.cwd}),await this.ensureThreadResumed();const n=[],o=this.callbacks.getAgentProfile?.(),d=o?.agentName?.trim()??"",u=o?.introduction?.trim()??"";if((d||u)&&this.identityInjectedThreadId!==this.threadId){const h=["[system-identity]"];d&&h.push(`Your name is "${d}".`),u&&h.push(`Your self-introduction: ${u}`),h.push("Treat this as an out-of-band instruction; do not echo or repeat it in your replies."),h.push("[/system-identity]"),n.push({type:"text",text:h.join(`
7
+ `),text_elements:[]}),this.identityInjectedThreadId=this.threadId,r.info("codex-adapter",`Injected agent identity for thread=${this.threadId} name="${d}"`)}if(this.needsHistoryInjection&&s){this.needsHistoryInjection=!1;const h=await this.loadHistoryForInjection(s);for(const m of h)n.push(m);h.length>0&&r.info("codex-adapter",`Injected ${h.length} history items`)}if(e.contextMessages&&e.contextMessages.length>0){const h=e.contextMessages.map(m=>`[${m.senderId??"unknown"}]: ${m.content}`).join(`
7
8
  `);n.push({type:"text",text:`Conversation context:
8
9
  ${h}
9
10
 
10
- Latest user message:`,text_elements:[]})}n.push({type:"text",text:e.text,text_elements:[]});const o={threadId:this.threadId,approvalPolicy:this.approvalPolicy,input:n,model:this.model},d=be(this.collaborationMode,this.model);d&&(o.collaborationMode=d),this.reasoningEffort&&(o.effort=this.reasoningEffort),await this.sendRequest("turn/start",o),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.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}:{}}),t=ve(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=Ie(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,sandboxMode:this.sandboxMode})}async loadHistoryForInjection(e){const t=this.callbacks.getConversationLog();if(!t)return[];try{const i=await t.readHistory(e,ue),s=[];for(const n of i){const o=(n.content??"").slice(0,pe);n.direction==="inbound"?s.push({type:"text",text:o,text_elements:[]}):n.direction==="outbound"&&s.push({type:"assistant",text:o,text_elements:[]})}return s}catch(i){return r.error("codex-adapter",`Failed to load history: ${i}`),[]}}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,i){if(!this.threadId)return;const s=e.event_id?.trim()||`local_action_${e.action_id.trim()}`,n=g(t.session_id,t.sessionId)??this.activeSessionId??"";if(!n)return;const o=this.threadId,d=new S(o),h={adapterSessionId:o,text:""};this.activeEventId=s,this.activeSessionId=n,this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.codexSequence=0,this.runTurn(h,d,s,n).catch(u=>{r.error("codex-adapter",`Post-approval turn failed: ${u}`),this.callbacks.sendEventResult(s,"failed",u instanceof Error?u.message:String(u)),this.clearActive()}),this.resetIdleTimer(s)}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);r.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?le:ce;this.idleTimer=setTimeout(()=>{this.onIdleTimeout(e,t)},t)}async onIdleTimeout(e,t){if(this.activeEventId!==e)return;let i=!1;try{i=await this.ping(he)}catch{i=!1}if(this.activeEventId!==e)return;if(!i){r.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 s=this.lastIdleCheckAt,n=this.lastProgressAt>s,o=n?!1:await this.checkSessionActivitySince(s);if(this.activeEventId===e){if(this.lastIdleCheckAt=Date.now(),n||o){o&&r.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>=$?(r.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`)):(r.warn("codex-adapter",`Idle timer fired, ping ok, no progress (${this.idleNoProgressCount}/${$}): ${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 ne(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:(r.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 ge={allow:"accept","allow-once":"accept","allow-always":"acceptForSession",deny:"deny"};function xe(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 ve(a){if(!a||typeof a!="object")return null;const e=a,t=e.thread&&typeof e.thread=="object"?e.thread:void 0;return g(l(e.threadId),l(e.threadID),l(t?.id))??null}function Ie(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 be(a,e){const t=_(a),i=l(e);if(!(!t||!i))return{mode:t,settings:{model:i}}}function we(a){if(!Array.isArray(a))return[];const e=[];for(const t of a){if(typeof t=="string"){const o=t.trim();o&&e.push(Te(o,y(o)));continue}if(!t||typeof t!="object")continue;const i=t,s=g(l(i.id),l(i.model_id),l(i.modelId),l(i.value));if(!s)continue;const n=g(l(i.displayName),l(i.display_name),l(i.name),l(i.label))??y(s);e.push({id:s,displayName:n,defaultReasoningEffort:l(i.defaultReasoningEffort)??null,supportedReasoningEfforts:k(i.supportedReasoningEfforts),isDefault:i.isDefault===!0})}return e}function D(a){const e=a.toLowerCase().replace(/\/+$/,"");return!(e==="https://api.openai.com"||e==="https://api.openai.com/v1"||e.endsWith(".openai.com"))}async function _e(a,e){const i=`${a.replace(/\/+$/,"")}/models`,s={Accept:"application/json"};e&&(s.Authorization=`Bearer ${e}`);const n=new AbortController,o=setTimeout(()=>n.abort(),1e4);try{const d=await fetch(i,{headers:s,signal:n.signal});if(!d.ok)return[];const h=await d.json();return ye(h)}finally{clearTimeout(o)}}function ye(a){if(!a||typeof a!="object")return[];const e=a,t=Array.isArray(e.data)?e.data:[],i=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s,o=g(l(n.id),l(n.model));if(!o)continue;const d=g(l(n.displayName),l(n.display_name),l(n.name))??y(o);i.push({id:o,displayName:d,defaultReasoningEffort:l(n.defaultReasoningEffort)??null,supportedReasoningEfforts:k(n.supportedReasoningEfforts),isDefault:n.isDefault===!0})}return i}function Ce(a){if(!a||typeof a!="object")return{models:[],nextCursor:null};const e=a,t=Array.isArray(e.data)?e.data:[],i=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;if(n.hidden===!0)continue;const o=g(l(n.id),l(n.model));if(!o)continue;const d=g(l(n.displayName),l(n.display_name),l(n.name))??y(o);i.push({id:o,displayName:d,defaultReasoningEffort:l(n.defaultReasoningEffort)??null,supportedReasoningEfforts:k(n.supportedReasoningEfforts),isDefault:n.isDefault===!0})}return{models:i,nextCursor:l(e.nextCursor)??null}}function j(a){const e=[],t=new Set;for(const i of a){const s=i.id.trim(),n=s.toLowerCase();!s||t.has(n)||(t.add(n),e.push({id:s,displayName:i.displayName.trim()||s,defaultReasoningEffort:i.defaultReasoningEffort,supportedReasoningEfforts:[...i.supportedReasoningEfforts],isDefault:i.isDefault}))}return e}function Te(a,e){return{id:a,displayName:e,defaultReasoningEffort:null,supportedReasoningEfforts:[],isDefault:!1}}function k(a){if(!Array.isArray(a))return[];const e=[];for(const t of a){if(typeof t=="string"){const s=t.trim();s&&e.push(s);continue}if(!t||typeof t!="object")continue;const i=l(t.reasoningEffort);i&&e.push(i)}return e}function y(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 g(...a){for(const e of a)if(e!=null){if(typeof e=="string"&&!e.trim())continue;return e}}function F(a){return a.trim().replace(/[^a-zA-Z0-9._:-]+/g,"_")}class S extends E{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){r.warn("codex-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}function ke(a){return["cannot steer a compact turn","turn not found","turn already completed","no active turn"].some(t=>a.includes(t))}export{q as CodexAdapter};
11
+ Latest user message:`,text_elements:[]})}n.push({type:"text",text:e.text,text_elements:[]});const p={threadId:this.threadId,approvalPolicy:this.approvalPolicy,input:n,model:this.model},f=be(this.collaborationMode,this.model);f&&(p.collaborationMode=f),this.reasoningEffort&&(p.effort=this.reasoningEffort),await this.sendRequest("turn/start",p),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.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}:{}}),t=ve(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=Ie(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,sandboxMode:this.sandboxMode})}async loadHistoryForInjection(e){const t=this.callbacks.getConversationLog();if(!t)return[];try{const i=await t.readHistory(e,ue),s=[];for(const n of i){const o=(n.content??"").slice(0,pe);n.direction==="inbound"?s.push({type:"text",text:o,text_elements:[]}):n.direction==="outbound"&&s.push({type:"assistant",text:o,text_elements:[]})}return s}catch(i){return r.error("codex-adapter",`Failed to load history: ${i}`),[]}}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,i){if(!this.threadId)return;const s=e.event_id?.trim()||`local_action_${e.action_id.trim()}`,n=x(t.session_id,t.sessionId)??this.activeSessionId??"";if(!n)return;const o=this.threadId,d=new S(o),u={adapterSessionId:o,text:""};this.activeEventId=s,this.activeSessionId=n,this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.codexSequence=0,this.runTurn(u,d,s,n).catch(p=>{r.error("codex-adapter",`Post-approval turn failed: ${p}`),this.callbacks.sendEventResult(s,"failed",p instanceof Error?p.message:String(p)),this.clearActive()}),this.resetIdleTimer(s)}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);r.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?le:ce;this.idleTimer=setTimeout(()=>{this.onIdleTimeout(e,t)},t)}async onIdleTimeout(e,t){if(this.activeEventId!==e)return;let i=!1;try{i=await this.ping(he)}catch{i=!1}if(this.activeEventId!==e)return;if(!i){r.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 s=this.lastIdleCheckAt,n=this.lastProgressAt>s,o=n?!1:await this.checkSessionActivitySince(s);if(this.activeEventId===e){if(this.lastIdleCheckAt=Date.now(),n||o){o&&r.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>=$?(r.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`)):(r.warn("codex-adapter",`Idle timer fired, ping ok, no progress (${this.idleNoProgressCount}/${$}): ${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 ne(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:(r.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 ge={allow:"accept","allow-once":"accept","allow-always":"acceptForSession",deny:"deny"};function xe(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 ve(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 Ie(a){return!a||typeof a!="object"?null:l(a.model)??null}function y(a){const e=a?.trim().toLowerCase();return e==="default"||e==="plan"?e:null}function be(a,e){const t=y(a),i=l(e);if(!(!t||!i))return{mode:t,settings:{model:i}}}function we(a){if(!Array.isArray(a))return[];const e=[];for(const t of a){if(typeof t=="string"){const o=t.trim();o&&e.push(Ce(o,_(o)));continue}if(!t||typeof t!="object")continue;const i=t,s=x(l(i.id),l(i.model_id),l(i.modelId),l(i.value));if(!s)continue;const n=x(l(i.displayName),l(i.display_name),l(i.name),l(i.label))??_(s);e.push({id:s,displayName:n,defaultReasoningEffort:l(i.defaultReasoningEffort)??null,supportedReasoningEfforts:k(i.supportedReasoningEfforts),isDefault:i.isDefault===!0})}return e}function D(a){const e=a.toLowerCase().replace(/\/+$/,"");return!(e==="https://api.openai.com"||e==="https://api.openai.com/v1"||e.endsWith(".openai.com"))}async function ye(a,e){const i=`${a.replace(/\/+$/,"")}/models`,s={Accept:"application/json"};e&&(s.Authorization=`Bearer ${e}`);const n=new AbortController,o=setTimeout(()=>n.abort(),1e4);try{const d=await fetch(i,{headers:s,signal:n.signal});if(!d.ok)return[];const u=await d.json();return _e(u)}finally{clearTimeout(o)}}function _e(a){if(!a||typeof a!="object")return[];const e=a,t=Array.isArray(e.data)?e.data:[],i=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s,o=x(l(n.id),l(n.model));if(!o)continue;const d=x(l(n.displayName),l(n.display_name),l(n.name))??_(o);i.push({id:o,displayName:d,defaultReasoningEffort:l(n.defaultReasoningEffort)??null,supportedReasoningEfforts:k(n.supportedReasoningEfforts),isDefault:n.isDefault===!0})}return i}function Te(a){if(!a||typeof a!="object")return{models:[],nextCursor:null};const e=a,t=Array.isArray(e.data)?e.data:[],i=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;if(n.hidden===!0)continue;const o=x(l(n.id),l(n.model));if(!o)continue;const d=x(l(n.displayName),l(n.display_name),l(n.name))??_(o);i.push({id:o,displayName:d,defaultReasoningEffort:l(n.defaultReasoningEffort)??null,supportedReasoningEfforts:k(n.supportedReasoningEfforts),isDefault:n.isDefault===!0})}return{models:i,nextCursor:l(e.nextCursor)??null}}function j(a){const e=[],t=new Set;for(const i of a){const s=i.id.trim(),n=s.toLowerCase();!s||t.has(n)||(t.add(n),e.push({id:s,displayName:i.displayName.trim()||s,defaultReasoningEffort:i.defaultReasoningEffort,supportedReasoningEfforts:[...i.supportedReasoningEfforts],isDefault:i.isDefault}))}return e}function Ce(a,e){return{id:a,displayName:e,defaultReasoningEffort:null,supportedReasoningEfforts:[],isDefault:!1}}function k(a){if(!Array.isArray(a))return[];const e=[];for(const t of a){if(typeof t=="string"){const s=t.trim();s&&e.push(s);continue}if(!t||typeof t!="object")continue;const i=l(t.reasoningEffort);i&&e.push(i)}return e}function _(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 F(a){return a.trim().replace(/[^a-zA-Z0-9._:-]+/g,"_")}class S extends E{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){r.warn("codex-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}function ke(a){return["cannot steer a compact turn","turn not found","turn already completed","no active turn"].some(t=>a.includes(t))}export{q as CodexAdapter};
@@ -1,8 +1,8 @@
1
- import{createInterface as q}from"node:readline";import{EventEmitter as M}from"node:events";import{mkdirSync as x,readFileSync as T,writeFileSync as $,readdirSync as j,statSync as F}from"node:fs";import{join as m}from"node:path";import{homedir as C}from"node:os";import{GRIX_PATHS as N,log as c}from"../../core/log/index.js";import{buildSimpleProbeReport as H}from"../shared/probe-util.js";import{InternalApiServer as U}from"../../core/mcp/internal-api-server.js";import{syncDefaultSkillsToDir as W}from"../../default-skills/index.js";import{resolveCommandPath as B,spawnCommand as E,killProcessGroup as S}from"../../core/runtime/spawn.js";import{SessionBindingStore as O}from"../../core/persistence/session-binding-store.js";const b=12e4;function J(h){try{return process.kill(h,0),!0}catch(e){return e.code==="EPERM"}}function D(h,e,t){if(t<0)return null;let i;try{i=j(h,{withFileTypes:!0})}catch{return null}for(const s of i){const o=m(h,s.name);if(s.isDirectory()){const n=D(o,e,t-1);if(n)return n}else if(s.isFile()&&s.name.endsWith(e))return o}return null}function G(h,e){if(!h)return null;const t=e||m(C(),".cursor","projects");return D(t,`${h}.jsonl`,6)}class L extends M{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){c.warn("cursor-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}class k extends M{type="cursor";static STDERR_MAX_CHARS=8192;config;callbacks;alive=!1;stopped=!1;permissionHandler=null;internalApi=null;bindingStore=null;inboundQueue=[];pendingBySession=new Map;sessions=new Set;sessionRuntime=new Map;sessionSeq=0;lastUsageBySession=new Map;_availableModels=[];activeBySession=new Map;constructor(e,t){super(),this.config=e,this.callbacks=t;const i=e.options??{};this.bindingStore=i.bindingStore instanceof O?i.bindingStore:null}async start(){this.alive=!0,this.stopped=!1,(this.config.options??{}).mcp_tools!==!1&&(this.internalApi=new U,this.internalApi.setInvokeHandler(async(t,i)=>this.callbacks.agentInvoke(t,i)),await this.internalApi.start()),this.refreshModels().catch(()=>{})}get availableModels(){return this._availableModels}async refreshModels(){try{const e={...process.env,...this.config.env??{}},t=B(this.config.command,typeof e.PATH=="string"?e.PATH:void 0),i=E(t,["agent","models"],{cwd:process.cwd(),env:e,stdio:["ignore","pipe","pipe"]}),s=await new Promise(n=>{let r="";i.process.stdout?.on("data",d=>{r+=String(d)}),i.process.once("close",()=>n(r))}),o=[];for(const n of s.split(`
2
- `)){const r=n.trim();if(!r||r.toLowerCase().includes("available model"))continue;const d=r.match(/^(\S+)\s+-\s+(.+)$/);d&&o.push({id:d[1],displayName:d[2].trim()})}o.length>0&&(this._availableModels=o,c.info("cursor-adapter",`Loaded ${o.length} available models`))}catch(e){c.warn("cursor-adapter",`Failed to refresh models: ${e instanceof Error?e.message:String(e)}`)}}async stop(){this.stopped=!0,this.alive=!1;for(const e of this.activeBySession.values())S(e.child,"SIGTERM");this.activeBySession.clear(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null)}isAlive(){return this.alive}async createSession(e){const t=`cursor-${Date.now()}-${++this.sessionSeq}`;return this.sessions.add(t),this.sessionRuntime.set(t,{cwd:typeof e.cwd=="string"?e.cwd:void 0,modelId:typeof e.modelId=="string"?e.modelId:void 0,modeId:typeof e.modeId=="string"?e.modeId:void 0}),t}async resumeSession(e,t){this.sessions.add(e);const i=this.sessionRuntime.get(e)??{};this.sessionRuntime.set(e,{...i,cwd:typeof t?.cwd=="string"?t.cwd:i.cwd,modelId:typeof t?.modelId=="string"?t.modelId:i.modelId,modeId:typeof t?.modeId=="string"?t.modeId:i.modeId})}async destroySession(e){this.sessions.delete(e),this.sessionRuntime.delete(e)}sendPrompt(e){const t=new L(e.adapterSessionId);if(!this.alive||this.stopped)return queueMicrotask(()=>t.emitError(new Error("adapter not running"))),t;const i=this.inboundQueue.shift()??{event_id:`cursor-evt-${Date.now()}`,session_id:e.adapterSessionId,content:e.text},s=e.adapterSessionId,o=this.pendingBySession.get(s)??[];return o.push({event:i,request:e,handle:t}),this.pendingBySession.set(s,o),this.tryStartNext(s),t}tryStartNext(e){if(this.activeBySession.has(e)||!this.alive||this.stopped)return;const t=this.pendingBySession.get(e);if(!t||t.length===0)return;const i=t.shift();t.length===0?this.pendingBySession.delete(e):this.pendingBySession.set(e,t),i&&this.startJob(i,!1,0)}startJob(e,t,i){const{event:s,request:o,handle:n}=e,r=o.adapterSessionId,d=this.sessionRuntime.get(o.adapterSessionId)??{},p=this.config.options??{},u=[...this.config.args??[]];u.push("-p","--output-format","stream-json","--stream-partial-output"),p.trust!==!1&&u.push("--trust");const v=d.cwd||p.workspace;this.internalApi&&v&&(this.ensureWorkspaceMcpAndSkills(v),u.push("--approve-mcps")),v&&u.push("--workspace",v);const I=d.modelId||p.model;I&&u.push("--model",I);const A=d.modeId||p.mode;A&&u.push("--mode",A);const w=d.cursorSessionId??this.bindingStore?.getAcpSessionId(o.adapterSessionId),R=!!(w&&p.use_continue!==!1&&!t);R&&u.push("--resume",w),u.push(this.buildPromptText(o));const _={...process.env,...this.config.env??{}},P=B(this.config.command,typeof _.PATH=="string"?_.PATH:void 0);c.info("cursor-adapter",`job start: event=${s.event_id} session=${s.session_id} retry=${i}`);let f;try{f=E(P,u,{cwd:v||process.cwd(),env:_,stdio:["ignore","pipe","pipe"]}).process}catch(a){this.finishActive(r,"failed",`spawn failed: ${a instanceof Error?a.message:String(a)}`);return}this.callbacks.sendEventAck(s.event_id,s.session_id);const l={event:s,request:o,handle:n,child:f,seq:0,done:!1,stderr:"",timer:null,idleTimer:null,retryCount:i,usedContinue:R,workspace:v||process.cwd(),args:u};this.activeBySession.set(r,l),this.armActiveIdleTimer(r);const y=o.timeoutMs&&o.timeoutMs>0?o.timeoutMs:0;y>0&&(l.timer=setTimeout(()=>{l.done||(S(f,"SIGTERM"),this.finishActive(r,"failed",`cursor agent timeout after ${y}ms`))},y)),q({input:f.stdout}).on("line",a=>this.handleStdoutLineForActive(l,a)),f.stderr?.on("data",a=>{const g=l.stderr+String(a??"");l.stderr=g.length>k.STDERR_MAX_CHARS?g.slice(-k.STDERR_MAX_CHARS):g}),f.once("error",a=>{this.finishActive(r,"failed",`spawn failed: ${String(a?.message??a)}`)}),f.once("close",a=>{if(!l.done)if((a??0)===0)this.finishActive(r,"responded");else{if(this.shouldRetryWithoutContinue(l)){l.timer&&clearTimeout(l.timer),l.idleTimer&&clearTimeout(l.idleTimer),this.activeBySession.delete(r),this.startJob(e,!0,l.retryCount+1);return}const g=l.stderr.trim()||`cursor agent exited with code ${a??-1}`;this.finishActive(r,"failed",g)}})}async cancel(e){const t=this.activeBySession.get(e);t&&(S(t.child,"SIGTERM"),this.finishActive(e,"canceled","canceled"))}deliverInboundEvent(e){const t=String(e.session_id??"").trim();if(!t){c.warn("cursor-adapter",`Dropping event ${e.event_id}: missing session_id`),this.callbacks.sendEventResult(e.event_id,"failed","missing session_id");return}if(!this.alive||this.stopped){c.warn("cursor-adapter",`Dropping event ${e.event_id}: adapter not running`),this.callbacks.sendEventAck(e.event_id,t),this.callbacks.sendEventResult(e.event_id,"failed","adapter not running");return}const i={adapterSessionId:t,text:String(e.content??"")},s=new L(t),o=this.pendingBySession.get(t)??[];o.push({event:e,request:i,handle:s}),this.pendingBySession.set(t,o),c.info("cursor-adapter",`inbound queued: event=${e.event_id} session=${t} depth=${o.length}`),this.tryStartNext(t)}killChildWithFallback(e){S(e,"SIGTERM"),setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{S(e,"SIGKILL")}catch{}},5e3).unref()}deliverStopEvent(e,t){if(t){const i=this.activeBySession.get(t);if(i?.event.event_id===e){this.killChildWithFallback(i.child),this.finishActive(t,"canceled","stopped");return}const s=this.pendingBySession.get(t)??[],o=s.findIndex(n=>n.event.event_id===e);if(o>=0){const[n]=s.splice(o,1);s.length===0?this.pendingBySession.delete(t):this.pendingBySession.set(t,s),this.callbacks.sendEventAck(n.event.event_id,n.event.session_id),this.callbacks.sendEventResult(n.event.event_id,"canceled","stopped"),n.handle.emitDone({status:"canceled",error:"stopped"})}return}for(const[i,s]of this.activeBySession.entries())if(s.event.event_id===e){this.killChildWithFallback(s.child),this.finishActive(i,"canceled","stopped");return}for(const[i,s]of this.pendingBySession.entries()){const o=s.findIndex(r=>r.event.event_id===e);if(o<0)continue;const[n]=s.splice(o,1);s.length===0?this.pendingBySession.delete(i):this.pendingBySession.set(i,s),this.callbacks.sendEventAck(n.event.event_id,n.event.session_id),this.callbacks.sendEventResult(n.event.event_id,"canceled","stopped"),n.handle.emitDone({status:"canceled",error:"stopped"});return}}async handleLocalAction(e){const t=String(e.action_type??"").trim().toLowerCase(),i=e.params??{},s=String(i.session_id??"").trim(),o=e.action_id;switch(t){case"set_model":{const n=String(i.model_id??"").trim();if(!n||!s)return this.callbacks.sendLocalActionResult(o,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};const r=this.sessionRuntime.get(s)??{};return this.sessionRuntime.set(s,{...r,modelId:n}),this.callbacks.sendLocalActionResult(o,"ok",{outcome:"model_set",session_context:{model_id:n,mode_id:r.modeId??null,modelId:n,modeId:r.modeId??null},model_id:n,mode_id:r.modeId??null,available_models:this.availableModels}),{handled:!0,kind:"set_model"}}case"set_mode":{const n=String(i.mode_id??"").trim();if(!n||!s)return this.callbacks.sendLocalActionResult(o,"failed",void 0,"invalid_params","mode_id and session_id are required"),{handled:!0,kind:"set_mode"};const r=this.sessionRuntime.get(s)??{};return this.sessionRuntime.set(s,{...r,modeId:n}),this.callbacks.sendLocalActionResult(o,"ok",{outcome:"mode_set",session_context:{model_id:r.modelId??null,mode_id:n,modelId:r.modelId??null,modeId:n},model_id:r.modelId??null,mode_id:n}),{handled:!0,kind:"set_mode"}}case"get_context":{const n=s?this.sessionRuntime.get(s):void 0;return this.callbacks.sendLocalActionResult(o,"ok",{session_context:{model_id:n?.modelId??null,mode_id:n?.modeId??null,cwd:n?.cwd??null},model_id:n?.modelId??null,mode_id:n?.modeId??null,modelId:n?.modelId??null,modeId:n?.modeId??null,cwd:n?.cwd??null,available_models:this.availableModels}),{handled:!0,kind:"get_context"}}case"get_rate_limits":{const n=this.getRateLimitsSnapshot();return this.callbacks.sendLocalActionResult(o,"ok",n),{handled:!0,kind:"get_rate_limits"}}case"get_session_usage":{const n=s?this.getUsageSnapshot(s):null;return n?this.callbacks.sendLocalActionResult(o,"ok",{adapterType:"cursor",available:!0,sampledAt:n.sampledAt,turns:n.turns,tokenUsage:n.total}):this.callbacks.sendLocalActionResult(o,"ok",{adapterType:"cursor",available:!1,sampledAt:null,turns:0,tokenUsage:null}),{handled:!0,kind:"get_session_usage"}}case"session_control":{const n=String(i.verb??"").trim().toLowerCase();if(n==="restart"&&s)this.deliverStopEvent("__all__",s),this.callbacks.sendLocalActionResult(o,"ok",{outcome:"restarted"});else if(n==="status"){const r=this.sessionRuntime.get(s),d=this.activeBySession.has(s);this.callbacks.sendLocalActionResult(o,"ok",{verb:"status",status:d?"running":"idle",session_context:{model_id:r?.modelId??null,mode_id:r?.modeId??null,cwd:r?.cwd??null},model_id:r?.modelId??null,mode_id:r?.modeId??null,modelId:r?.modelId??null,modeId:r?.modeId??null,cwd:r?.cwd??null})}else this.callbacks.sendLocalActionResult(o,"failed",void 0,"invalid_verb",`Unsupported verb: ${n}`);return{handled:!0,kind:"session_control"}}default:return{handled:!1,kind:"unsupported"}}}setPermissionHandler(e){this.permissionHandler=e}async ping(e){if(!this.alive||this.stopped||(this.config.options??{}).mcp_tools!==!1&&this.internalApi===null)return!1;for(const i of this.activeBySession.values()){const s=i.child?.pid;if(s&&!J(s))return!1}return!0}getStatus(){let e=0;for(const t of this.pendingBySession.values())e+=t.length;return{alive:this.alive,busy:this.activeBySession.size>0,sessions:this.sessions.size,details:{queueDepth:e+this.inboundQueue.length,activeSessions:this.activeBySession.size}}}getActiveEventIds(){const e=[];for(const t of this.activeBySession.values())t.event.event_id&&e.push(t.event.event_id);return e}clearActiveEventForShutdown(){this.activeBySession.clear()}getMcpConfig(){return null}async probe(e){const t=this.getStatus();return{...await H(this.config.command||"agent",{alive:t.alive,busy:t.busy,started:this.alive},e),session:this.probeSessionRecord()}}probeSessionRecord(){const e=this.firstKnownCursorSessionId(),t=e?G(e):null;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const i=F(t);return{recordPath:t,lastActivityMs:i.mtimeMs,freshMs:Date.now()-i.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}firstKnownCursorSessionId(){for(const e of this.activeBySession.keys()){const t=this.sessionRuntime.get(e);if(t?.cursorSessionId)return t.cursorSessionId}for(const e of this.sessionRuntime.values())if(e.cursorSessionId)return e.cursorSessionId;return null}getUsageSnapshot(e){return this.lastUsageBySession.get(e)??null}getRateLimitsSnapshot(){return{adapterType:"cursor",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null}}buildPromptText(e){return!e.contextMessages||e.contextMessages.length===0?e.text:`${e.contextMessages.map(i=>`[${i.senderId}] ${i.content}`).join(`
1
+ import{createInterface as q}from"node:readline";import{EventEmitter as x}from"node:events";import{mkdirSync as M,readFileSync as T,writeFileSync as C,readdirSync as j,statSync as F}from"node:fs";import{join as m}from"node:path";import{homedir as $}from"node:os";import{GRIX_PATHS as N,log as c}from"../../core/log/index.js";import{IdentityInjector as H}from"../shared/identity-injector.js";import{buildSimpleProbeReport as U}from"../shared/probe-util.js";import{InternalApiServer as W}from"../../core/mcp/internal-api-server.js";import{syncDefaultSkillsToDir as O}from"../../default-skills/index.js";import{resolveCommandPath as B,spawnCommand as E,killProcessGroup as S}from"../../core/runtime/spawn.js";import{SessionBindingStore as J}from"../../core/persistence/session-binding-store.js";const b=12e4;function G(h){try{return process.kill(h,0),!0}catch(e){return e.code==="EPERM"}}function P(h,e,t){if(t<0)return null;let i;try{i=j(h,{withFileTypes:!0})}catch{return null}for(const s of i){const o=m(h,s.name);if(s.isDirectory()){const n=P(o,e,t-1);if(n)return n}else if(s.isFile()&&s.name.endsWith(e))return o}return null}function X(h,e){if(!h)return null;const t=e||m($(),".cursor","projects");return P(t,`${h}.jsonl`,6)}class D extends x{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){c.warn("cursor-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}class k extends x{type="cursor";static STDERR_MAX_CHARS=8192;config;callbacks;alive=!1;stopped=!1;permissionHandler=null;internalApi=null;bindingStore=null;identity;inboundQueue=[];pendingBySession=new Map;sessions=new Set;sessionRuntime=new Map;sessionSeq=0;lastUsageBySession=new Map;_availableModels=[];activeBySession=new Map;constructor(e,t){super(),this.config=e,this.callbacks=t;const i=e.options??{};this.bindingStore=i.bindingStore instanceof J?i.bindingStore:null,this.identity=new H("cursor-adapter",t.getAgentProfile)}async start(){this.alive=!0,this.stopped=!1,(this.config.options??{}).mcp_tools!==!1&&(this.internalApi=new W,this.internalApi.setInvokeHandler(async(t,i)=>this.callbacks.agentInvoke(t,i)),await this.internalApi.start()),this.refreshModels().catch(()=>{})}get availableModels(){return this._availableModels}async refreshModels(){try{const e={...process.env,...this.config.env??{}},t=B(this.config.command,typeof e.PATH=="string"?e.PATH:void 0),i=E(t,["agent","models"],{cwd:process.cwd(),env:e,stdio:["ignore","pipe","pipe"]}),s=await new Promise(n=>{let r="";i.process.stdout?.on("data",d=>{r+=String(d)}),i.process.once("close",()=>n(r))}),o=[];for(const n of s.split(`
2
+ `)){const r=n.trim();if(!r||r.toLowerCase().includes("available model"))continue;const d=r.match(/^(\S+)\s+-\s+(.+)$/);d&&o.push({id:d[1],displayName:d[2].trim()})}o.length>0&&(this._availableModels=o,c.info("cursor-adapter",`Loaded ${o.length} available models`))}catch(e){c.warn("cursor-adapter",`Failed to refresh models: ${e instanceof Error?e.message:String(e)}`)}}async stop(){this.stopped=!0,this.alive=!1;for(const e of this.activeBySession.values())S(e.child,"SIGTERM");this.activeBySession.clear(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null)}isAlive(){return this.alive}async createSession(e){const t=`cursor-${Date.now()}-${++this.sessionSeq}`;return this.sessions.add(t),this.sessionRuntime.set(t,{cwd:typeof e.cwd=="string"?e.cwd:void 0,modelId:typeof e.modelId=="string"?e.modelId:void 0,modeId:typeof e.modeId=="string"?e.modeId:void 0}),t}async resumeSession(e,t){this.sessions.add(e);const i=this.sessionRuntime.get(e)??{};this.sessionRuntime.set(e,{...i,cwd:typeof t?.cwd=="string"?t.cwd:i.cwd,modelId:typeof t?.modelId=="string"?t.modelId:i.modelId,modeId:typeof t?.modeId=="string"?t.modeId:i.modeId})}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(e){this.sessions.delete(e),this.sessionRuntime.delete(e),this.identity.forgetSession(e)}sendPrompt(e){const t=new D(e.adapterSessionId);if(!this.alive||this.stopped)return queueMicrotask(()=>t.emitError(new Error("adapter not running"))),t;const i=this.inboundQueue.shift()??{event_id:`cursor-evt-${Date.now()}`,session_id:e.adapterSessionId,content:e.text},s=e.adapterSessionId,o=this.pendingBySession.get(s)??[];return o.push({event:i,request:e,handle:t}),this.pendingBySession.set(s,o),this.tryStartNext(s),t}tryStartNext(e){if(this.activeBySession.has(e)||!this.alive||this.stopped)return;const t=this.pendingBySession.get(e);if(!t||t.length===0)return;const i=t.shift();t.length===0?this.pendingBySession.delete(e):this.pendingBySession.set(e,t),i&&this.startJob(i,!1,0)}startJob(e,t,i){const{event:s,request:o,handle:n}=e,r=o.adapterSessionId,d=this.sessionRuntime.get(o.adapterSessionId)??{},p=this.config.options??{},u=[...this.config.args??[]];u.push("-p","--output-format","stream-json","--stream-partial-output"),p.trust!==!1&&u.push("--trust");const v=d.cwd||p.workspace;this.internalApi&&v&&(this.ensureWorkspaceMcpAndSkills(v),u.push("--approve-mcps")),v&&u.push("--workspace",v);const I=d.modelId||p.model;I&&u.push("--model",I);const A=d.modeId||p.mode;A&&u.push("--mode",A);const w=d.cursorSessionId??this.bindingStore?.getAcpSessionId(o.adapterSessionId),R=!!(w&&p.use_continue!==!1&&!t);R&&u.push("--resume",w),u.push(this.buildPromptText(o));const y={...process.env,...this.config.env??{}},L=B(this.config.command,typeof y.PATH=="string"?y.PATH:void 0);c.info("cursor-adapter",`job start: event=${s.event_id} session=${s.session_id} retry=${i}`);let f;try{f=E(L,u,{cwd:v||process.cwd(),env:y,stdio:["ignore","pipe","pipe"]}).process}catch(a){this.finishActive(r,"failed",`spawn failed: ${a instanceof Error?a.message:String(a)}`);return}this.callbacks.sendEventAck(s.event_id,s.session_id);const l={event:s,request:o,handle:n,child:f,seq:0,done:!1,stderr:"",timer:null,idleTimer:null,retryCount:i,usedContinue:R,workspace:v||process.cwd(),args:u};this.activeBySession.set(r,l),this.armActiveIdleTimer(r);const _=o.timeoutMs&&o.timeoutMs>0?o.timeoutMs:0;_>0&&(l.timer=setTimeout(()=>{l.done||(S(f,"SIGTERM"),this.finishActive(r,"failed",`cursor agent timeout after ${_}ms`))},_)),q({input:f.stdout}).on("line",a=>this.handleStdoutLineForActive(l,a)),f.stderr?.on("data",a=>{const g=l.stderr+String(a??"");l.stderr=g.length>k.STDERR_MAX_CHARS?g.slice(-k.STDERR_MAX_CHARS):g}),f.once("error",a=>{this.finishActive(r,"failed",`spawn failed: ${String(a?.message??a)}`)}),f.once("close",a=>{if(!l.done)if((a??0)===0)this.finishActive(r,"responded");else{if(this.shouldRetryWithoutContinue(l)){l.timer&&clearTimeout(l.timer),l.idleTimer&&clearTimeout(l.idleTimer),this.activeBySession.delete(r),this.startJob(e,!0,l.retryCount+1);return}const g=l.stderr.trim()||`cursor agent exited with code ${a??-1}`;this.finishActive(r,"failed",g)}})}async cancel(e){const t=this.activeBySession.get(e);t&&(S(t.child,"SIGTERM"),this.finishActive(e,"canceled","canceled"))}deliverInboundEvent(e){const t=String(e.session_id??"").trim();if(!t){c.warn("cursor-adapter",`Dropping event ${e.event_id}: missing session_id`),this.callbacks.sendEventResult(e.event_id,"failed","missing session_id");return}if(!this.alive||this.stopped){c.warn("cursor-adapter",`Dropping event ${e.event_id}: adapter not running`),this.callbacks.sendEventAck(e.event_id,t),this.callbacks.sendEventResult(e.event_id,"failed","adapter not running");return}const i={adapterSessionId:t,text:String(e.content??"")},s=new D(t),o=this.pendingBySession.get(t)??[];o.push({event:e,request:i,handle:s}),this.pendingBySession.set(t,o),c.info("cursor-adapter",`inbound queued: event=${e.event_id} session=${t} depth=${o.length}`),this.tryStartNext(t)}killChildWithFallback(e){S(e,"SIGTERM"),setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{S(e,"SIGKILL")}catch{}},5e3).unref()}deliverStopEvent(e,t){if(t){const i=this.activeBySession.get(t);if(i?.event.event_id===e){this.killChildWithFallback(i.child),this.finishActive(t,"canceled","stopped");return}const s=this.pendingBySession.get(t)??[],o=s.findIndex(n=>n.event.event_id===e);if(o>=0){const[n]=s.splice(o,1);s.length===0?this.pendingBySession.delete(t):this.pendingBySession.set(t,s),this.callbacks.sendEventAck(n.event.event_id,n.event.session_id),this.callbacks.sendEventResult(n.event.event_id,"canceled","stopped"),n.handle.emitDone({status:"canceled",error:"stopped"})}return}for(const[i,s]of this.activeBySession.entries())if(s.event.event_id===e){this.killChildWithFallback(s.child),this.finishActive(i,"canceled","stopped");return}for(const[i,s]of this.pendingBySession.entries()){const o=s.findIndex(r=>r.event.event_id===e);if(o<0)continue;const[n]=s.splice(o,1);s.length===0?this.pendingBySession.delete(i):this.pendingBySession.set(i,s),this.callbacks.sendEventAck(n.event.event_id,n.event.session_id),this.callbacks.sendEventResult(n.event.event_id,"canceled","stopped"),n.handle.emitDone({status:"canceled",error:"stopped"});return}}async handleLocalAction(e){const t=String(e.action_type??"").trim().toLowerCase(),i=e.params??{},s=String(i.session_id??"").trim(),o=e.action_id;switch(t){case"set_model":{const n=String(i.model_id??"").trim();if(!n||!s)return this.callbacks.sendLocalActionResult(o,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};const r=this.sessionRuntime.get(s)??{};return this.sessionRuntime.set(s,{...r,modelId:n}),this.callbacks.sendLocalActionResult(o,"ok",{outcome:"model_set",session_context:{model_id:n,mode_id:r.modeId??null,modelId:n,modeId:r.modeId??null},model_id:n,mode_id:r.modeId??null,available_models:this.availableModels}),{handled:!0,kind:"set_model"}}case"set_mode":{const n=String(i.mode_id??"").trim();if(!n||!s)return this.callbacks.sendLocalActionResult(o,"failed",void 0,"invalid_params","mode_id and session_id are required"),{handled:!0,kind:"set_mode"};const r=this.sessionRuntime.get(s)??{};return this.sessionRuntime.set(s,{...r,modeId:n}),this.callbacks.sendLocalActionResult(o,"ok",{outcome:"mode_set",session_context:{model_id:r.modelId??null,mode_id:n,modelId:r.modelId??null,modeId:n},model_id:r.modelId??null,mode_id:n}),{handled:!0,kind:"set_mode"}}case"get_context":{const n=s?this.sessionRuntime.get(s):void 0;return this.callbacks.sendLocalActionResult(o,"ok",{session_context:{model_id:n?.modelId??null,mode_id:n?.modeId??null,cwd:n?.cwd??null},model_id:n?.modelId??null,mode_id:n?.modeId??null,modelId:n?.modelId??null,modeId:n?.modeId??null,cwd:n?.cwd??null,available_models:this.availableModels}),{handled:!0,kind:"get_context"}}case"get_rate_limits":{const n=this.getRateLimitsSnapshot();return this.callbacks.sendLocalActionResult(o,"ok",n),{handled:!0,kind:"get_rate_limits"}}case"get_session_usage":{const n=s?this.getUsageSnapshot(s):null;return n?this.callbacks.sendLocalActionResult(o,"ok",{adapterType:"cursor",available:!0,sampledAt:n.sampledAt,turns:n.turns,tokenUsage:n.total}):this.callbacks.sendLocalActionResult(o,"ok",{adapterType:"cursor",available:!1,sampledAt:null,turns:0,tokenUsage:null}),{handled:!0,kind:"get_session_usage"}}case"session_control":{const n=String(i.verb??"").trim().toLowerCase();if(n==="restart"&&s)this.deliverStopEvent("__all__",s),this.callbacks.sendLocalActionResult(o,"ok",{outcome:"restarted"});else if(n==="status"){const r=this.sessionRuntime.get(s),d=this.activeBySession.has(s);this.callbacks.sendLocalActionResult(o,"ok",{verb:"status",status:d?"running":"idle",session_context:{model_id:r?.modelId??null,mode_id:r?.modeId??null,cwd:r?.cwd??null},model_id:r?.modelId??null,mode_id:r?.modeId??null,modelId:r?.modelId??null,modeId:r?.modeId??null,cwd:r?.cwd??null})}else this.callbacks.sendLocalActionResult(o,"failed",void 0,"invalid_verb",`Unsupported verb: ${n}`);return{handled:!0,kind:"session_control"}}default:return{handled:!1,kind:"unsupported"}}}setPermissionHandler(e){this.permissionHandler=e}async ping(e){if(!this.alive||this.stopped||(this.config.options??{}).mcp_tools!==!1&&this.internalApi===null)return!1;for(const i of this.activeBySession.values()){const s=i.child?.pid;if(s&&!G(s))return!1}return!0}getStatus(){let e=0;for(const t of this.pendingBySession.values())e+=t.length;return{alive:this.alive,busy:this.activeBySession.size>0,sessions:this.sessions.size,details:{queueDepth:e+this.inboundQueue.length,activeSessions:this.activeBySession.size}}}getActiveEventIds(){const e=[];for(const t of this.activeBySession.values())t.event.event_id&&e.push(t.event.event_id);return e}clearActiveEventForShutdown(){this.activeBySession.clear()}getMcpConfig(){return null}async probe(e){const t=this.getStatus();return{...await U(this.config.command||"agent",{alive:t.alive,busy:t.busy,started:this.alive},e),session:this.probeSessionRecord()}}probeSessionRecord(){const e=this.firstKnownCursorSessionId(),t=e?X(e):null;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const i=F(t);return{recordPath:t,lastActivityMs:i.mtimeMs,freshMs:Date.now()-i.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}firstKnownCursorSessionId(){for(const e of this.activeBySession.keys()){const t=this.sessionRuntime.get(e);if(t?.cursorSessionId)return t.cursorSessionId}for(const e of this.sessionRuntime.values())if(e.cursorSessionId)return e.cursorSessionId;return null}getUsageSnapshot(e){return this.lastUsageBySession.get(e)??null}getRateLimitsSnapshot(){return{adapterType:"cursor",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null}}buildPromptText(e){let t;return!e.contextMessages||e.contextMessages.length===0?t=e.text:t=`${e.contextMessages.map(s=>`[${s.senderId}] ${s.content}`).join(`
3
3
  `)}
4
4
 
5
5
  [Current user message]
6
- ${e.text}`}handleStdoutLineForActive(e,t){if(e.done)return;const i=t.trim();if(!i)return;this.armActiveIdleTimer(e.request.adapterSessionId);const{event:s}=e;let o;try{o=JSON.parse(i)}catch{this.callbacks.sendRawEventEnvelope?.(s.event_id,s.session_id,{type:"raw_text",text:i});return}this.callbacks.sendRawEventEnvelope?.(s.event_id,s.session_id,o);const n=this.extractAssistantText(o);if(n&&(e.seq+=1,this.callbacks.sendStreamChunk(s.event_id,s.session_id,n,e.seq,!1)),o?.type==="result"){const r=String(o?.session_id??"").trim();if(r){const p=this.sessionRuntime.get(e.request.adapterSessionId)??{};this.sessionRuntime.set(e.request.adapterSessionId,{...p,cursorSessionId:r}),this.bindingStore?.setAcpSessionId(e.request.adapterSessionId,r)}const d=o?.usage??{};this.lastUsageBySession.set(e.request.adapterSessionId,{sampledAt:new Date().toISOString(),turns:(this.lastUsageBySession.get(e.request.adapterSessionId)?.turns??0)+1,total:{input:Number(d.inputTokens??0),output:Number(d.outputTokens??0),cacheRead:Number(d.cacheReadTokens??0),cacheWrite:Number(d.cacheWriteTokens??0)}})}}extractAssistantText(e){if(e?.type!=="assistant")return"";const t=e?.message?.content;return Array.isArray(t)?t.map(s=>s?.type==="text"?String(s?.text??""):"").filter(Boolean).join(""):""}armActiveIdleTimer(e){const t=this.activeBySession.get(e);!t||t.done||(t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.done||(c.error("cursor-adapter",`Idle timeout (${b/1e3}s) \u2014 killing cursor child: event=${t.event.event_id} session=${e}`),this.killChildWithFallback(t.child),this.finishActive(e,"failed",`idle timeout after ${b/1e3}s`))},b),t.idleTimer.unref?.())}finishActive(e,t,i){const s=this.activeBySession.get(e);s&&(s.done=!0,s.timer&&clearTimeout(s.timer),s.idleTimer&&clearTimeout(s.idleTimer),s.seq>0&&(s.seq+=1,this.callbacks.sendStreamChunk(s.event.event_id,s.event.session_id,"",s.seq,!0)),c.info("cursor-adapter",`job finish: event=${s.event.event_id} session=${s.event.session_id} status=${t}${i?` msg=${i}`:""}`),this.callbacks.sendEventResult(s.event.event_id,t,i),t==="responded"?s.handle.emitDone({status:"completed"}):t==="canceled"?s.handle.emitDone({status:"canceled",error:i}):s.handle.emitDone({status:"failed",error:i}),this.emit("eventDone",s.event.event_id),this.activeBySession.delete(e),this.tryStartNext(e))}shouldRetryWithoutContinue(e){if(!e.usedContinue||e.retryCount>0)return!1;const t=e.stderr.toLowerCase(),i=t.includes("resume")||t.includes("continue")||t.includes("chat")||t.includes("session"),s=t.includes("not found")||t.includes("no previous session")||t.includes("does not exist")||t.includes("invalid");return i&&s}ensureWorkspaceMcpAndSkills(e){if(!this.internalApi)return;this.ensureCursorMcpConfig(e,this.internalApi.url);const t=m(C(),".cursor","skills"),i=W(t);i.length>0&&c.info("cursor-adapter",`Synced connector skills to ${t}: [${i.join(", ")}]`)}ensureCursorMcpConfig(e,t){try{const i=m(e,".cursor"),s=m(i,"mcp.json");x(i,{recursive:!0});let o={};try{o=JSON.parse(T(s,"utf8"))}catch{o={}}const n={command:process.execPath,args:[m(process.cwd(),"dist","mcp","stdio","server.js"),"--handle-url",t]};(!o.mcpServers||typeof o.mcpServers!="object")&&(o.mcpServers={}),o.mcpServers.grix=n,$(s,`${JSON.stringify(o,null,2)}
7
- `,"utf8"),this.recordCursorMcpRegistry(e,s,n),c.info("cursor-adapter",`MCP config synced: workspace=${e} file=${s}`)}catch(i){c.warn("cursor-adapter",`Failed to ensure .cursor/mcp.json: ${String(i)}`)}}recordCursorMcpRegistry(e,t,i){try{const s=m(N.data,"cursor"),o=m(s,"mcp-registry.json");x(s,{recursive:!0});let n={};try{n=JSON.parse(T(o,"utf8"))}catch{n={}}n[e]={mcp_path:t,server:i,updated_at:new Date().toISOString()},$(o,`${JSON.stringify(n,null,2)}
8
- `,"utf8")}catch(s){c.warn("cursor-adapter",`Failed to record MCP registry: ${String(s)}`)}}}export{k as CursorAdapter,G as findCursorTranscript};
6
+ ${e.text}`,this.identity.injectOnce(e.adapterSessionId,t)}handleStdoutLineForActive(e,t){if(e.done)return;const i=t.trim();if(!i)return;this.armActiveIdleTimer(e.request.adapterSessionId);const{event:s}=e;let o;try{o=JSON.parse(i)}catch{this.callbacks.sendRawEventEnvelope?.(s.event_id,s.session_id,{type:"raw_text",text:i});return}this.callbacks.sendRawEventEnvelope?.(s.event_id,s.session_id,o);const n=this.extractAssistantText(o);if(n&&(e.seq+=1,this.callbacks.sendStreamChunk(s.event_id,s.session_id,n,e.seq,!1)),o?.type==="result"){const r=String(o?.session_id??"").trim();if(r){const p=this.sessionRuntime.get(e.request.adapterSessionId)??{};this.sessionRuntime.set(e.request.adapterSessionId,{...p,cursorSessionId:r}),this.bindingStore?.setAcpSessionId(e.request.adapterSessionId,r)}const d=o?.usage??{};this.lastUsageBySession.set(e.request.adapterSessionId,{sampledAt:new Date().toISOString(),turns:(this.lastUsageBySession.get(e.request.adapterSessionId)?.turns??0)+1,total:{input:Number(d.inputTokens??0),output:Number(d.outputTokens??0),cacheRead:Number(d.cacheReadTokens??0),cacheWrite:Number(d.cacheWriteTokens??0)}})}}extractAssistantText(e){if(e?.type!=="assistant")return"";const t=e?.message?.content;return Array.isArray(t)?t.map(s=>s?.type==="text"?String(s?.text??""):"").filter(Boolean).join(""):""}armActiveIdleTimer(e){const t=this.activeBySession.get(e);!t||t.done||(t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.done||(c.error("cursor-adapter",`Idle timeout (${b/1e3}s) \u2014 killing cursor child: event=${t.event.event_id} session=${e}`),this.killChildWithFallback(t.child),this.finishActive(e,"failed",`idle timeout after ${b/1e3}s`))},b),t.idleTimer.unref?.())}finishActive(e,t,i){const s=this.activeBySession.get(e);s&&(s.done=!0,s.timer&&clearTimeout(s.timer),s.idleTimer&&clearTimeout(s.idleTimer),s.seq>0&&(s.seq+=1,this.callbacks.sendStreamChunk(s.event.event_id,s.event.session_id,"",s.seq,!0)),c.info("cursor-adapter",`job finish: event=${s.event.event_id} session=${s.event.session_id} status=${t}${i?` msg=${i}`:""}`),this.callbacks.sendEventResult(s.event.event_id,t,i),t==="responded"?s.handle.emitDone({status:"completed"}):t==="canceled"?s.handle.emitDone({status:"canceled",error:i}):s.handle.emitDone({status:"failed",error:i}),this.emit("eventDone",s.event.event_id),this.activeBySession.delete(e),this.tryStartNext(e))}shouldRetryWithoutContinue(e){if(!e.usedContinue||e.retryCount>0)return!1;const t=e.stderr.toLowerCase(),i=t.includes("resume")||t.includes("continue")||t.includes("chat")||t.includes("session"),s=t.includes("not found")||t.includes("no previous session")||t.includes("does not exist")||t.includes("invalid");return i&&s}ensureWorkspaceMcpAndSkills(e){if(!this.internalApi)return;this.ensureCursorMcpConfig(e,this.internalApi.url);const t=m($(),".cursor","skills"),i=O(t);i.length>0&&c.info("cursor-adapter",`Synced connector skills to ${t}: [${i.join(", ")}]`)}ensureCursorMcpConfig(e,t){try{const i=m(e,".cursor"),s=m(i,"mcp.json");M(i,{recursive:!0});let o={};try{o=JSON.parse(T(s,"utf8"))}catch{o={}}const n={command:process.execPath,args:[m(process.cwd(),"dist","mcp","stdio","server.js"),"--handle-url",t]};(!o.mcpServers||typeof o.mcpServers!="object")&&(o.mcpServers={}),o.mcpServers.grix=n,C(s,`${JSON.stringify(o,null,2)}
7
+ `,"utf8"),this.recordCursorMcpRegistry(e,s,n),c.info("cursor-adapter",`MCP config synced: workspace=${e} file=${s}`)}catch(i){c.warn("cursor-adapter",`Failed to ensure .cursor/mcp.json: ${String(i)}`)}}recordCursorMcpRegistry(e,t,i){try{const s=m(N.data,"cursor"),o=m(s,"mcp-registry.json");M(s,{recursive:!0});let n={};try{n=JSON.parse(T(o,"utf8"))}catch{n={}}n[e]={mcp_path:t,server:i,updated_at:new Date().toISOString()},C(o,`${JSON.stringify(n,null,2)}
8
+ `,"utf8")}catch(s){c.warn("cursor-adapter",`Failed to record MCP registry: ${String(s)}`)}}}export{k as CursorAdapter,X as findCursorTranscript};
@@ -1,9 +1,9 @@
1
- import{EventEmitter as I}from"node:events";import{stat as k}from"node:fs/promises";import{existsSync as y,mkdirSync as b,readFileSync as E,writeFileSync as $}from"node:fs";import{join as m,resolve as P,dirname as A}from"node:path";import{homedir as C}from"node:os";import{fileURLToPath as _}from"node:url";import{resolveCommandPath as O,spawnCommand as M,killProcessGroup as T,hasChildProcesses as F}from"../../core/runtime/spawn.js";import{InternalApiServer as B}from"../../core/mcp/internal-api-server.js";import{syncDefaultSkillsToDir as j}from"../../default-skills/index.js";import{buildSimpleProbeReport as D}from"../shared/probe-util.js";import{OpenCodeTransport as N}from"./opencode-transport.js";import{log as n}from"../../core/log/index.js";import{splitTextForAibotProtocol as S}from"../../core/protocol/index.js";class H extends I{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){n.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const L=200,U=2e3,J=12e4,G=6e5,w=3e4,q="127.0.0.1",X=0,W=1e3;class ae extends I{type="opencode";config;callbacks;options;process=null;transport=new N;alive=!1;stopped=!1;internalApi=null;sessions=new Map;activeRun=null;completedEvents=new Set;clientMsgSeq=0;idleTimer=null;pendingPermissions=new Map;permissionHandler=null;constructor(e,s,t){super(),this.config=e,this.callbacks=s,this.options=t??{}}async start(){await this.startInternalApiAndInjectMcp();const e=this.options.hostname??q,s=this.options.port??X,t=await this.spawnAndWait(e,s),i=this.resolveCwd();await this.transport.connect(t,i),this.transport.on("event",o=>this.handleSseEvent(o)),n.info("opencode-adapter",`Ready (pid=${this.process?.pid}, url=${t})`)}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.transport.disconnect(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.process){const e=this.process;try{T(e,"SIGTERM")}catch{}const s=setTimeout(()=>{try{T(e,"SIGKILL")}catch{}},5e3);e.on("exit",()=>clearTimeout(s)),this.process=null}}isAlive(){return this.alive}async createSession(e){const s=e.cwd??this.resolveCwd(),t=await this.transport.createSession({title:`grix-${Date.now()}`});return this.sessions.set(t.id,{ocSessionId:t.id,cwd:s}),n.info("opencode-adapter",`Created OC session ${t.id} for cwd=${s}`),t.id}async resumeSession(e,s){const t=this.sessions.get(e);if(t?.ocSessionId)try{await this.transport.getSession(t.ocSessionId)}catch{n.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, will create new on next prompt`),t.ocSessionId=""}}async destroySession(e){try{await this.transport.deleteSession(e)}catch{}this.sessions.delete(e)}sendPrompt(e){const s=new H(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(t=>{s.emitError(t instanceof Error?t:new Error(String(t)))}),s}async cancel(e){if(this.activeRun)try{await this.transport.abortSession(this.activeRun.ocSessionId)}catch{}}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){n.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){n.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}this.activeRun&&this.activeRun.eventId!==s&&(n.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),n.info("opencode-adapter",`prompt: event=${s} session=${t}`),this.callbacks.sendEventAck(s,t),this.startRun(s,t),this.startComposing(t),this.resetIdleTimer();const o=this.buildPromptTextFromEvent(e);this.sendOcPrompt(t,o).catch(r=>{n.error("opencode-adapter",`prompt_async failed: ${r}`),this.finishRun("failed",String(r))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(n.info("opencode-adapter",`stop: event=${e}`),this.transport.abortSession(this.activeRun.ocSessionId).catch(()=>{}),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.sessions.size}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=P(_(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?F(e,[e]):!1}async probe(e){const s=this.getStatus();return D(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){try{this.internalApi=new B,this.internalApi.setInvokeHandler(async(p,h)=>this.callbacks.agentInvoke(p,h)),await this.internalApi.start(0),n.info("opencode-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),s=process.env.XDG_CONFIG_HOME||m(C(),".config"),t=m(s,"opencode","opencode.json");b(A(t),{recursive:!0});let i={};try{y(t)&&(i=JSON.parse(E(t,"utf8")))}catch{}const o=i.mcp&&typeof i.mcp=="object"?i.mcp:{};o[e.name]={type:"local",command:[e.command,...e.args??[]],enabled:!0},i.mcp=o,$(t,`${JSON.stringify(i,null,2)}
2
- `,"utf8"),n.info("opencode-adapter",`MCP config injected into ${t}`);const r=m(s,"opencode","skills"),c=j(r);c.length>0&&n.info("opencode-adapter",`Synced connector skills to ${r}: [${c.join(", ")}]`)}catch(e){n.warn("opencode-adapter",`Failed to inject MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`)}}async handleLocalAction(e){const{action_type:s}=e;return s==="exec_approve"||s==="exec_reject"||s==="permission_approve"||s==="permission_reject"?this.handlePermissionAction(e):{handled:!1,kind:""}}bindSession(e,s){if(n.info("opencode-adapter",`bindSession: ${e} \u2192 ${s}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:s});else{const t=this.sessions.get(e);t.cwd=s}}async spawnAndWait(e,s){const t=this.resolveCwd();try{if(!(await k(t)).isDirectory())throw new Error(`Bound path is not a directory: ${t}`)}catch(i){throw String(i?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${t}. Please rebind with /grix open <valid-directory>.`):i}return new Promise((i,o)=>{const r=this.config.command||"opencode",p=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${s}`],h={...process.env,...this.config.env},u={};if(this.options.model){const[a,...l]=this.options.model.split("/");a&&l.length>0&&(u.agents={coder:{model:l.join("/"),maxTokens:16e3}})}this.options.permissionPolicy==="fullAuto"&&(u.permission={edit:"allow",bash:"allow",webfetch:"allow",doom_loop:"allow",external_directory:"allow"}),Object.keys(u).length>0&&(h.OPENCODE_CONFIG_CONTENT=JSON.stringify(u));const v=O(r,typeof h.PATH=="string"?h.PATH:void 0);n.info("opencode-adapter",`Spawning: ${v} ${p.join(" ")} (cwd=${t})`),this.process=M(v,p,{env:h,cwd:t}).process;let g="",d=!1;const f=setTimeout(()=>{d||(d=!0,o(new Error(`opencode serve did not start after ${w/1e3}s`)))},w);this.process.stdout?.on("data",a=>{if(g+=a.toString(),!d)for(const l of g.split(`
3
- `)){const R=l.match(/opencode server listening on (https?:\/\/[^\s]+)/);if(R){clearTimeout(f),d=!0,this.alive=!0,i(R[1]);return}}}),this.process.stderr?.on("data",a=>{const l=a.toString().trim();l&&n.info("opencode-adapter",`[stderr] ${l}`)}),this.process.on("error",a=>{n.error("opencode-adapter",`Spawn error: ${a.message}`),clearTimeout(f),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${a.message}`),this.clearRun()),d?this.stopped||this.emit("exit",1):(d=!0,o(a))}),this.process.on("exit",a=>{n.info("opencode-adapter",`Process exited (code=${a})`),clearTimeout(f),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${a})`),this.clearRun()),d?this.stopped||this.emit("exit",a??1):(d=!0,o(new Error(`opencode serve exited with code ${a}`)))})})}async ensureOcSession(e){const s=this.sessions.get(e);if(s?.ocSessionId)try{return await this.transport.getSession(s.ocSessionId),s.ocSessionId}catch{n.warn("opencode-adapter",`OC session ${s.ocSessionId} gone, creating new`),s.ocSessionId=""}const t=s?.cwd??this.resolveCwd(),i=this.options.bindingStore?.getAcpSessionId(e);if(i)try{return await this.transport.getSession(i),this.sessions.set(e,{ocSessionId:i,cwd:t}),n.info("opencode-adapter",`Resumed OC session ${i} for aibot=${e}`),i}catch{n.warn("opencode-adapter",`Persisted OC session ${i} gone, creating new`)}const o=await this.transport.createSession({title:`grix-${e.slice(-8)}`});return this.sessions.set(e,{ocSessionId:o.id,cwd:t}),this.options.bindingStore?.setAcpSessionId(e,o.id),n.info("opencode-adapter",`Created OC session ${o.id} for aibot=${e}`),o.id}async sendOcPrompt(e,s){const t=await this.ensureOcSession(e);this.activeRun&&(this.activeRun.ocSessionId=t),await this.transport.sendPromptAsync(t,{parts:[{type:"text",text:s}]})}handleSseEvent(e){if(!this.stopped)switch(this.resetIdleTimer(),e.type){case"message.part.updated":{if(!this.activeRun)break;const s=e.part,t=e.delta;s.type==="text"?t?this.appendText(t):s.text&&this.appendText(s.text):s.type==="reasoning"?t&&this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,t):s.type==="tool"&&this.handleToolPartUpdate(s,t);break}case"message.updated":{if(!this.activeRun)break;const s=e.info;if(s.role==="assistant"){const t=s;t.error&&n.warn("opencode-adapter",`Message error: ${JSON.stringify(t.error)}`)}break}case"session.idle":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.status":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&e.status.type==="idle"&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.error":{if(!this.activeRun)break;const s=e.error,t=s?typeof s=="object"&&"message"in s?s.message:JSON.stringify(s):"unknown session error";n.error("opencode-adapter",`Session error: ${t}`),this.flushTextBuffer(),this.finishRun("failed",t);break}case"permission.updated":{this.handlePermission(e.permission);break}case"session.created":case"session.updated":case"session.deleted":case"session.compacted":case"session.diff":case"file.edited":case"server.connected":break;case"server.instance.disposed":{n.warn("opencode-adapter",`Server instance disposed: ${e.directory}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"failed","server instance disposed"),this.clearRun()),this.stopped||this.emit("exit",-1);break}default:break}}handleToolPartUpdate(e,s){if(!this.activeRun)return;const t=e.state;switch(t.status){case"pending":case"running":{this.flushTextBuffer();const i=JSON.stringify(t.input??{});this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,i);break}case"completed":{const i=t.output??"";this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,i);break}case"error":{const i=t.error??"unknown tool error";this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,`Error: ${i}`);break}}}handlePermission(e){if(!this.activeRun)return;const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.options.permissionPolicy==="fullAuto"){this.transport.respondPermission(i,e.id,"always").catch(r=>{n.warn("opencode-adapter",`Auto-approve failed: ${r}`)});return}this.stopIdleTimer(),this.pendingPermissions.set(s,{permissionId:e.id,ocSessionId:i});const o=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(s,t,e.type,o)}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const s=this.pendingPermissions.get(this.activeRun.eventId);if(!s)return{handled:!1,kind:""};const{permissionId:t,ocSessionId:i}=s,r=e.action_type==="exec_approve"||e.action_type==="permission_approve"?"once":"reject";return this.pendingPermissions.delete(this.activeRun.eventId),this.transport.respondPermission(i,t,r).then(()=>{n.info("opencode-adapter",`Permission ${r}: ${t}`),this.resetIdleTimer()}).catch(c=>{n.warn("opencode-adapter",`Permission response failed: ${c}`)}),{handled:!0,kind:"permission"}}startRun(e,s){this.activeRun={eventId:e,sessionId:s,ocSessionId:"",chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null}}finishRun(e,s){const t=this.activeRun;if(!t)return;if(this.completedEvents.add(t.eventId),this.completedEvents.size>W){const c=[...this.completedEvents].slice(-500);this.completedEvents=new Set(c)}this.activeRun=null,this.stopComposing(),this.stopIdleTimer();const i=++t.chunkSeq,o=t.clientMsgId;e==="failed"&&s&&this.callbacks.sendRunError(t.eventId,t.sessionId,s);const r=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t.eventId,t.sessionId,i,o).then(()=>{this.callbacks.sendEventResult(t.eventId,e,s)}).catch(()=>{this.callbacks.sendStreamChunk(t.eventId,t.sessionId,"",i,!0,o),this.callbacks.sendEventResult(t.eventId,e,s)}):(this.callbacks.sendStreamChunk(t.eventId,t.sessionId,"",i,!0,o),this.callbacks.sendEventResult(t.eventId,e,s))};if(t.textBuffer){this.stopTextFlush();for(const c of S(t.textBuffer))t.chunkSeq++,this.callbacks.sendStreamChunk(t.eventId,t.sessionId,c,t.chunkSeq,!1,t.clientMsgId);t.textBuffer=""}r(),this.emit("eventDone",t.eventId)}clearRun(){this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const e=this.activeRun?.eventId;this.activeRun=null,e&&this.emit("eventDone",e)}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=U){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},L))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const e of S(this.activeRun.textBuffer))this.activeRun.chunkSeq++,this.callbacks.sendStreamChunk(this.activeRun.eventId,this.activeRun.sessionId,e,this.activeRun.chunkSeq,!1,this.activeRun.clientMsgId);this.activeRun.textBuffer=""}}stopTextFlush(){this.activeRun?.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null)}startComposing(e){}stopComposing(){}resetIdleTimer(){if(this.stopIdleTimer(),this.stopped||!this.activeRun)return;const e=this.pendingPermissions.has(this.activeRun.eventId)?G:J;this.idleTimer=setTimeout(()=>{n.error("opencode-adapter","Idle timeout \u2014 emitting exit for respawn"),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed","idle timeout"),this.clearRun()),this.emit("exit",-1)},e)}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveCwd(){const e=(this.config.options??{}).cwd;return typeof e=="string"&&e?e:process.cwd()}buildPromptText(e){let s=e.text;return e.contextMessages&&e.contextMessages.length>0&&(s=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
1
+ import{EventEmitter as I}from"node:events";import{stat as k}from"node:fs/promises";import{existsSync as y,mkdirSync as b,readFileSync as E,writeFileSync as $}from"node:fs";import{join as m,resolve as P,dirname as A}from"node:path";import{homedir as C}from"node:os";import{fileURLToPath as _}from"node:url";import{resolveCommandPath as O,spawnCommand as M,killProcessGroup as T,hasChildProcesses as F}from"../../core/runtime/spawn.js";import{InternalApiServer as B}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as j}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as D}from"../../default-skills/index.js";import{buildSimpleProbeReport as N}from"../shared/probe-util.js";import{OpenCodeTransport as H}from"./opencode-transport.js";import{log as n}from"../../core/log/index.js";import{splitTextForAibotProtocol as S}from"../../core/protocol/index.js";class L extends I{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){n.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const U=200,J=2e3,G=12e4,X=6e5,w=3e4,q="127.0.0.1",W=0,z=1e3;class de extends I{type="opencode";config;callbacks;options;identity;process=null;transport=new H;alive=!1;stopped=!1;internalApi=null;sessions=new Map;activeRun=null;completedEvents=new Set;clientMsgSeq=0;idleTimer=null;pendingPermissions=new Map;permissionHandler=null;constructor(e,s,t){super(),this.config=e,this.callbacks=s,this.options=t??{},this.identity=new j("opencode-adapter",s.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}async start(){await this.startInternalApiAndInjectMcp();const e=this.options.hostname??q,s=this.options.port??W,t=await this.spawnAndWait(e,s),i=this.resolveCwd();await this.transport.connect(t,i),this.transport.on("event",o=>this.handleSseEvent(o)),n.info("opencode-adapter",`Ready (pid=${this.process?.pid}, url=${t})`)}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.transport.disconnect(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.process){const e=this.process;try{T(e,"SIGTERM")}catch{}const s=setTimeout(()=>{try{T(e,"SIGKILL")}catch{}},5e3);e.on("exit",()=>clearTimeout(s)),this.process=null}}isAlive(){return this.alive}async createSession(e){const s=e.cwd??this.resolveCwd(),t=await this.transport.createSession({title:`grix-${Date.now()}`});return this.sessions.set(t.id,{ocSessionId:t.id,cwd:s}),n.info("opencode-adapter",`Created OC session ${t.id} for cwd=${s}`),t.id}async resumeSession(e,s){const t=this.sessions.get(e);if(t?.ocSessionId)try{await this.transport.getSession(t.ocSessionId)}catch{n.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, will create new on next prompt`),t.ocSessionId=""}}async destroySession(e){try{await this.transport.deleteSession(e)}catch{}this.sessions.delete(e),this.identity.forgetSession(e)}sendPrompt(e){const s=new L(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(t=>{s.emitError(t instanceof Error?t:new Error(String(t)))}),s}async cancel(e){if(this.activeRun)try{await this.transport.abortSession(this.activeRun.ocSessionId)}catch{}}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){n.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){n.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}this.activeRun&&this.activeRun.eventId!==s&&(n.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),n.info("opencode-adapter",`prompt: event=${s} session=${t}`),this.callbacks.sendEventAck(s,t),this.startRun(s,t),this.startComposing(t),this.resetIdleTimer();const o=this.buildPromptTextFromEvent(e);this.sendOcPrompt(t,o).catch(r=>{n.error("opencode-adapter",`prompt_async failed: ${r}`),this.finishRun("failed",String(r))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(n.info("opencode-adapter",`stop: event=${e}`),this.transport.abortSession(this.activeRun.ocSessionId).catch(()=>{}),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.sessions.size}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=P(_(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?F(e,[e]):!1}async probe(e){const s=this.getStatus();return N(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){try{this.internalApi=new B,this.internalApi.setInvokeHandler(async(p,h)=>this.callbacks.agentInvoke(p,h)),await this.internalApi.start(0),n.info("opencode-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),s=process.env.XDG_CONFIG_HOME||m(C(),".config"),t=m(s,"opencode","opencode.json");b(A(t),{recursive:!0});let i={};try{y(t)&&(i=JSON.parse(E(t,"utf8")))}catch{}const o=i.mcp&&typeof i.mcp=="object"?i.mcp:{};o[e.name]={type:"local",command:[e.command,...e.args??[]],enabled:!0},i.mcp=o,$(t,`${JSON.stringify(i,null,2)}
2
+ `,"utf8"),n.info("opencode-adapter",`MCP config injected into ${t}`);const r=m(s,"opencode","skills"),c=D(r);c.length>0&&n.info("opencode-adapter",`Synced connector skills to ${r}: [${c.join(", ")}]`)}catch(e){n.warn("opencode-adapter",`Failed to inject MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`)}}async handleLocalAction(e){const{action_type:s}=e;return s==="exec_approve"||s==="exec_reject"||s==="permission_approve"||s==="permission_reject"?this.handlePermissionAction(e):{handled:!1,kind:""}}bindSession(e,s){if(n.info("opencode-adapter",`bindSession: ${e} \u2192 ${s}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:s});else{const t=this.sessions.get(e);t.cwd=s}}async spawnAndWait(e,s){const t=this.resolveCwd();try{if(!(await k(t)).isDirectory())throw new Error(`Bound path is not a directory: ${t}`)}catch(i){throw String(i?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${t}. Please rebind with /grix open <valid-directory>.`):i}return new Promise((i,o)=>{const r=this.config.command||"opencode",p=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${s}`],h={...process.env,...this.config.env},u={};if(this.options.model){const[a,...l]=this.options.model.split("/");a&&l.length>0&&(u.agents={coder:{model:l.join("/"),maxTokens:16e3}})}this.options.permissionPolicy==="fullAuto"&&(u.permission={edit:"allow",bash:"allow",webfetch:"allow",doom_loop:"allow",external_directory:"allow"}),Object.keys(u).length>0&&(h.OPENCODE_CONFIG_CONTENT=JSON.stringify(u));const v=O(r,typeof h.PATH=="string"?h.PATH:void 0);n.info("opencode-adapter",`Spawning: ${v} ${p.join(" ")} (cwd=${t})`),this.process=M(v,p,{env:h,cwd:t}).process;let g="",d=!1;const f=setTimeout(()=>{d||(d=!0,o(new Error(`opencode serve did not start after ${w/1e3}s`)))},w);this.process.stdout?.on("data",a=>{if(g+=a.toString(),!d)for(const l of g.split(`
3
+ `)){const R=l.match(/opencode server listening on (https?:\/\/[^\s]+)/);if(R){clearTimeout(f),d=!0,this.alive=!0,i(R[1]);return}}}),this.process.stderr?.on("data",a=>{const l=a.toString().trim();l&&n.info("opencode-adapter",`[stderr] ${l}`)}),this.process.on("error",a=>{n.error("opencode-adapter",`Spawn error: ${a.message}`),clearTimeout(f),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${a.message}`),this.clearRun()),d?this.stopped||this.emit("exit",1):(d=!0,o(a))}),this.process.on("exit",a=>{n.info("opencode-adapter",`Process exited (code=${a})`),clearTimeout(f),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${a})`),this.clearRun()),d?this.stopped||this.emit("exit",a??1):(d=!0,o(new Error(`opencode serve exited with code ${a}`)))})})}async ensureOcSession(e){const s=this.sessions.get(e);if(s?.ocSessionId)try{return await this.transport.getSession(s.ocSessionId),s.ocSessionId}catch{n.warn("opencode-adapter",`OC session ${s.ocSessionId} gone, creating new`),s.ocSessionId=""}const t=s?.cwd??this.resolveCwd(),i=this.options.bindingStore?.getAcpSessionId(e);if(i)try{return await this.transport.getSession(i),this.sessions.set(e,{ocSessionId:i,cwd:t}),n.info("opencode-adapter",`Resumed OC session ${i} for aibot=${e}`),i}catch{n.warn("opencode-adapter",`Persisted OC session ${i} gone, creating new`)}const o=await this.transport.createSession({title:`grix-${e.slice(-8)}`});return this.sessions.set(e,{ocSessionId:o.id,cwd:t}),this.options.bindingStore?.setAcpSessionId(e,o.id),n.info("opencode-adapter",`Created OC session ${o.id} for aibot=${e}`),o.id}async sendOcPrompt(e,s){const t=await this.ensureOcSession(e);this.activeRun&&(this.activeRun.ocSessionId=t),await this.transport.sendPromptAsync(t,{parts:[{type:"text",text:s}]})}handleSseEvent(e){if(!this.stopped)switch(this.resetIdleTimer(),e.type){case"message.part.updated":{if(!this.activeRun)break;const s=e.part,t=e.delta;s.type==="text"?t?this.appendText(t):s.text&&this.appendText(s.text):s.type==="reasoning"?t&&this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,t):s.type==="tool"&&this.handleToolPartUpdate(s,t);break}case"message.updated":{if(!this.activeRun)break;const s=e.info;if(s.role==="assistant"){const t=s;t.error&&n.warn("opencode-adapter",`Message error: ${JSON.stringify(t.error)}`)}break}case"session.idle":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.status":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&e.status.type==="idle"&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.error":{if(!this.activeRun)break;const s=e.error,t=s?typeof s=="object"&&"message"in s?s.message:JSON.stringify(s):"unknown session error";n.error("opencode-adapter",`Session error: ${t}`),this.flushTextBuffer(),this.finishRun("failed",t);break}case"permission.updated":{this.handlePermission(e.permission);break}case"session.created":case"session.updated":case"session.deleted":case"session.compacted":case"session.diff":case"file.edited":case"server.connected":break;case"server.instance.disposed":{n.warn("opencode-adapter",`Server instance disposed: ${e.directory}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"failed","server instance disposed"),this.clearRun()),this.stopped||this.emit("exit",-1);break}default:break}}handleToolPartUpdate(e,s){if(!this.activeRun)return;const t=e.state;switch(t.status){case"pending":case"running":{this.flushTextBuffer();const i=JSON.stringify(t.input??{});this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,i);break}case"completed":{const i=t.output??"";this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,i);break}case"error":{const i=t.error??"unknown tool error";this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,`Error: ${i}`);break}}}handlePermission(e){if(!this.activeRun)return;const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.options.permissionPolicy==="fullAuto"){this.transport.respondPermission(i,e.id,"always").catch(r=>{n.warn("opencode-adapter",`Auto-approve failed: ${r}`)});return}this.stopIdleTimer(),this.pendingPermissions.set(s,{permissionId:e.id,ocSessionId:i});const o=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(s,t,e.type,o)}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const s=this.pendingPermissions.get(this.activeRun.eventId);if(!s)return{handled:!1,kind:""};const{permissionId:t,ocSessionId:i}=s,r=e.action_type==="exec_approve"||e.action_type==="permission_approve"?"once":"reject";return this.pendingPermissions.delete(this.activeRun.eventId),this.transport.respondPermission(i,t,r).then(()=>{n.info("opencode-adapter",`Permission ${r}: ${t}`),this.resetIdleTimer()}).catch(c=>{n.warn("opencode-adapter",`Permission response failed: ${c}`)}),{handled:!0,kind:"permission"}}startRun(e,s){this.activeRun={eventId:e,sessionId:s,ocSessionId:"",chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null}}finishRun(e,s){const t=this.activeRun;if(!t)return;if(this.completedEvents.add(t.eventId),this.completedEvents.size>z){const c=[...this.completedEvents].slice(-500);this.completedEvents=new Set(c)}this.activeRun=null,this.stopComposing(),this.stopIdleTimer();const i=++t.chunkSeq,o=t.clientMsgId;e==="failed"&&s&&this.callbacks.sendRunError(t.eventId,t.sessionId,s);const r=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t.eventId,t.sessionId,i,o).then(()=>{this.callbacks.sendEventResult(t.eventId,e,s)}).catch(()=>{this.callbacks.sendStreamChunk(t.eventId,t.sessionId,"",i,!0,o),this.callbacks.sendEventResult(t.eventId,e,s)}):(this.callbacks.sendStreamChunk(t.eventId,t.sessionId,"",i,!0,o),this.callbacks.sendEventResult(t.eventId,e,s))};if(t.textBuffer){this.stopTextFlush();for(const c of S(t.textBuffer))t.chunkSeq++,this.callbacks.sendStreamChunk(t.eventId,t.sessionId,c,t.chunkSeq,!1,t.clientMsgId);t.textBuffer=""}r(),this.emit("eventDone",t.eventId)}clearRun(){this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const e=this.activeRun?.eventId;this.activeRun=null,e&&this.emit("eventDone",e)}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=J){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},U))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const e of S(this.activeRun.textBuffer))this.activeRun.chunkSeq++,this.callbacks.sendStreamChunk(this.activeRun.eventId,this.activeRun.sessionId,e,this.activeRun.chunkSeq,!1,this.activeRun.clientMsgId);this.activeRun.textBuffer=""}}stopTextFlush(){this.activeRun?.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null)}startComposing(e){}stopComposing(){}resetIdleTimer(){if(this.stopIdleTimer(),this.stopped||!this.activeRun)return;const e=this.pendingPermissions.has(this.activeRun.eventId)?X:G;this.idleTimer=setTimeout(()=>{n.error("opencode-adapter","Idle timeout \u2014 emitting exit for respawn"),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed","idle timeout"),this.clearRun()),this.emit("exit",-1)},e)}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveCwd(){const e=(this.config.options??{}).cwd;return typeof e=="string"&&e?e:process.cwd()}buildPromptText(e){let s=e.text;return e.contextMessages&&e.contextMessages.length>0&&(s=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
4
4
  `)+`
5
5
 
6
- `+s),s}buildPromptTextFromEvent(e){let s=e.content||"";if(e.context_messages_json)try{const t=JSON.parse(e.context_messages_json);Array.isArray(t)&&t.length>0&&(s=t.map(o=>`[context] ${o.sender_id??"unknown"}: ${o.content}`).join(`
6
+ `+s),this.identity.injectOnce(e.adapterSessionId,s)}buildPromptTextFromEvent(e){let s=e.content||"";if(e.context_messages_json)try{const t=JSON.parse(e.context_messages_json);Array.isArray(t)&&t.length>0&&(s=t.map(o=>`[context] ${o.sender_id??"unknown"}: ${o.content}`).join(`
7
7
  `)+`
8
8
 
9
- `+s)}catch{}return s}}export{ae as OpenCodeAdapter};
9
+ `+s)}catch{}return this.identity.injectOnce(e.session_id,s)}}export{de as OpenCodeAdapter};
@@ -1,8 +1,8 @@
1
- import{EventEmitter as m}from"node:events";import{stat as R}from"node:fs/promises";import{mkdirSync as I}from"node:fs";import{homedir as u}from"node:os";import{join as p,resolve as _}from"node:path";import{fileURLToPath as g}from"node:url";import{randomUUID as k}from"node:crypto";import{resolveCommandPath as E,spawnCommand as x,killProcessGroup as f,hasChildProcesses as w}from"../../core/runtime/spawn.js";import{InternalApiServer as S}from"../../core/mcp/internal-api-server.js";import{syncDefaultSkillsToDir as b}from"../../default-skills/index.js";import{buildSimpleProbeReport as y}from"../shared/probe-util.js";import{OpenHumanTransport as $,readBearerToken as A}from"./openhuman-transport.js";import{log as n}from"../../core/log/index.js";import{splitTextForAibotProtocol as C}from"../../core/protocol/index.js";class L extends m{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitError(t){if(this.listenerCount("error")===0){n.warn("openhuman-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const P=200,F=2e3,D=12e4,M=500,v=3e4,N=7788,B="127.0.0.1";class Z extends m{type="openhuman";config;callbacks;options;process=null;transport=new $;alive=!1;stopped=!1;internalApi=null;clientId;activeRun=null;completedEvents=new Set;clientMsgSeq=0;idleTimer=null;constructor(t,e,s){super(),this.config=t,this.callbacks=e,this.options=s??{},this.clientId=`grix-connector-${Date.now()}`}async start(){await this.startInternalApiAndInjectMcp();const t=this.options.host??B,e=this.options.port??N;await this.spawnProcess(t,e),await this.waitForServerReady(t,e);const s=this.resolveWorkspaceDir(),i=await A(s),r=`http://${t}:${e}`;if(await this.transport.connect(r,i),this.transport.on("event",o=>this.handleSocketEvent(o)),this.options.sessionToken)try{await this.transport.storeSession({token:this.options.sessionToken}),n.info("openhuman-adapter","Session token stored")}catch(o){n.warn("openhuman-adapter",`Failed to store session token: ${o}`)}this.transport.socketId&&(this.clientId=this.transport.socketId),n.info("openhuman-adapter",`Ready (pid=${this.process?.pid}, clientId=${this.clientId})`)}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.transport.disconnect(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.process){const t=this.process;try{f(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{f(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){return this.clientId}async resumeSession(t,e){}async destroySession(t){}sendPrompt(t){const e=new L(t.adapterSessionId),s=this.buildPromptText(t);return this.doWebChat(t.adapterSessionId,s).then(i=>{this.activeRun&&(this.activeRun.requestId=i.request_id)}).catch(i=>{e.emitError(i instanceof Error?i:new Error(String(i)))}),e}async cancel(t){if(this.activeRun)try{await this.transport.webCancel({client_id:this.clientId,thread_id:this.activeRun.threadId})}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:s,content:i}=t,r=this.buildPromptTextFromEvent(t);if(this.completedEvents.has(e)){n.info("openhuman-adapter",`Dropping duplicate event ${e}`),this.callbacks.sendEventAck(e,s),this.callbacks.sendEventResult(e,"responded");return}if(!this.alive){n.warn("openhuman-adapter",`Dropping event ${e}: process not alive`),this.callbacks.sendEventAck(e,s),this.callbacks.sendEventResult(e,"failed","Agent process not running");return}this.activeRun&&this.activeRun.eventId!==e&&(n.info("openhuman-adapter",`steer: ${this.activeRun.eventId} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),n.info("openhuman-adapter",`prompt: event=${e} session=${s}`),this.callbacks.sendEventAck(e,s),this.startRun(e,s,s),this.startComposing(s,e),this.resetIdleTimer(),this.doWebChat(s,r).then(o=>{this.activeRun&&this.activeRun.eventId===e&&(this.activeRun.requestId=o.request_id,o.accepted||(n.warn("openhuman-adapter",`web_chat not accepted: ${o.request_id}`),this.finishRun("failed","Chat request not accepted")))}).catch(o=>{n.error("openhuman-adapter",`web_chat failed: ${o}`),this.finishRun("failed",String(o))})}deliverStopEvent(t,e){this.activeRun&&this.activeRun.eventId===t&&(n.info("openhuman-adapter",`stop: event=${t}`),this.transport.webCancel({client_id:this.clientId,thread_id:this.activeRun.threadId}).catch(()=>{}),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(t){}async ping(t){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.activeRun?1:0}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const t=_(g(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?w(t,[t]):!1}async probe(t){const e=this.getStatus();return y(this.config.command||"openhuman-core",{alive:e.alive,busy:e.busy,started:!!this.process},t)}async startInternalApiAndInjectMcp(){try{this.internalApi=new S,this.internalApi.setInvokeHandler(async(a,d)=>this.callbacks.agentInvoke(a,d)),await this.internalApi.start(0),n.info("openhuman-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=p(u(),".openhuman","users","local","workspace","mcp_clients"),s=p(e,"mcp_clients.db");I(e,{recursive:!0});const{execFileSync:i}=await import("node:child_process"),r=k(),o=JSON.stringify(t.args),l=["CREATE TABLE IF NOT EXISTS mcp_servers (server_id TEXT PRIMARY KEY, qualified_name TEXT NOT NULL, display_name TEXT NOT NULL, description TEXT, icon_url TEXT, command_kind TEXT NOT NULL DEFAULT 'node', command TEXT NOT NULL, args_json TEXT NOT NULL DEFAULT '[]', env_keys_json TEXT NOT NULL DEFAULT '[]', config_json TEXT, installed_at INTEGER NOT NULL, last_connected_at INTEGER);","DELETE FROM mcp_servers WHERE qualified_name = 'grix-connector-tools';",`INSERT INTO mcp_servers (server_id, qualified_name, display_name, description, command_kind, command, args_json, installed_at) VALUES ('${r}', 'grix-connector-tools', 'Grix Connector Tools', 'Grix platform query and management tools', 'node', '${t.command}', '${o.replace(/'/g,"''")}', ${Date.now()});`].join(`
2
- `);i("sqlite3",[s,l],{timeout:1e4,stdio:"ignore"}),n.info("openhuman-adapter",`MCP server registered in SQLite: ${s}`);const c=p(u(),".openhuman","skills"),h=b(c);h.length>0&&n.info("openhuman-adapter",`Synced connector skills to ${c}: [${h.join(", ")}]`)}catch(t){n.warn("openhuman-adapter",`Failed to inject MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async spawnProcess(t,e){const s=this.config.command||"openhuman-core",i=E(s,typeof process.env.PATH=="string"?process.env.PATH:void 0),r=this.config.args??[],l=r.includes("run")||r.includes("serve")?r:["run","--host",t,"--port",String(e),...r],c={...process.env,...this.config.env},h=this.resolveCwd();n.info("openhuman-adapter",`Spawning: ${i} ${l.join(" ")}`);try{if(!(await R(h)).isDirectory())throw new Error(`Bound path is not a directory: ${h}`)}catch(a){throw String(a?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${h}. Please rebind with /grix open <valid-directory>.`):a}try{this.process=x(i,l,{env:c,cwd:h}).process}catch(a){throw n.error("openhuman-adapter",`Spawn threw: ${a}`),this.alive=!1,a}this.process.on("error",a=>{n.error("openhuman-adapter",`Spawn error: ${a.message}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${a.message}`),this.clearRun()),this.stopped||this.emit("exit",1)}),this.process.on("exit",a=>{n.info("openhuman-adapter",`Process exited (code=${a})`),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${a})`),this.clearRun()),this.stopped||this.emit("exit",a??1)}),this.process.stderr?.on("data",a=>{const d=a.toString().trim();d&&n.info("openhuman-adapter",`[stderr] ${d}`)}),this.alive=!0}async waitForServerReady(t,e){const s=`http://${t}:${e}/health`,i=Date.now()+v;for(;Date.now()<i;){try{if((await fetch(s,{signal:AbortSignal.timeout(2e3)})).ok)return}catch{}await new Promise(r=>setTimeout(r,M))}throw new Error(`openhuman-core did not become ready at ${t}:${e} after ${v/1e3}s`)}async doWebChat(t,e){return this.transport.webChat({client_id:this.clientId,thread_id:t,message:e})}handleSocketEvent(t){if(this.stopped||!this.activeRun||t.request_id&&this.activeRun.requestId&&t.request_id!==this.activeRun.requestId)return;this.resetIdleTimer();const e=t.event;switch(e){case"text_delta":{t.delta&&t.delta_kind==="text"&&this.appendText(t.delta);break}case"thinking_delta":{t.delta&&t.delta_kind==="thinking"&&this.activeRun&&this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,t.delta);break}case"tool_call":{if(this.flushTextBuffer(),this.activeRun&&t.tool_name){const s=typeof t.args=="string"?t.args:JSON.stringify(t.args??{});this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,t.tool_name,s)}break}case"tool_result":{if(this.activeRun&&t.tool_name){const s=t.output??"";this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,t.tool_name,s)}break}case"chat_done":{n.info("openhuman-adapter",`chat_done request=${t.request_id}`),this.activeRun&&this.activeRun.textBuffer.length===0&&t.full_response&&(this.activeRun.textBuffer=t.full_response),this.flushTextBuffer(),this.finishRun("responded");break}case"chat_error":{if(n.error("openhuman-adapter",`chat_error: ${t.error_type} ${t.message}`),this.flushTextBuffer(),this.activeRun){const s=t.message??t.error_type??"unknown error";this.callbacks.sendRunError(this.activeRun.eventId,this.activeRun.sessionId,s)}this.finishRun("failed",t.message);break}case"chat_segment":case"inference_start":case"iteration_start":case"chat_accepted":break;default:{n.debug("openhuman-adapter",`Unhandled event: ${e}`);break}}}startRun(t,e,s){this.activeRun={eventId:t,sessionId:e,requestId:"",threadId:s,chunkSeq:0,clientMsgId:`oh_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null}}finishRun(t,e){const s=this.activeRun;if(!s)return;if(this.completedEvents.add(s.eventId),this.completedEvents.size>1e3){const o=this.completedEvents.values();for(let c=0;c<500;c++)o.next();const l=[...this.completedEvents].slice(-500);this.completedEvents=new Set(l)}this.activeRun=null,this.emit("eventDone",s.eventId),this.stopComposing(),this.stopIdleTimer();const i=++s.chunkSeq,r=s.clientMsgId;t==="failed"&&e&&this.callbacks.sendRunError(s.eventId,s.sessionId,e),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(s.eventId,s.sessionId,i,r).then(()=>{this.callbacks.sendEventResult(s.eventId,t,e)}).catch(()=>{this.callbacks.sendStreamChunk(s.eventId,s.sessionId,"",i,!0,r),this.callbacks.sendEventResult(s.eventId,t,e)}):(this.callbacks.sendStreamChunk(s.eventId,s.sessionId,"",i,!0,r),this.callbacks.sendEventResult(s.eventId,t,e))}clearRun(){this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const t=this.activeRun?.eventId;this.activeRun=null,t&&this.emit("eventDone",t)}appendText(t){if(this.activeRun){if(this.activeRun.textBuffer+=t,this.activeRun.textBuffer.length>=F){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},P))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const t of C(this.activeRun.textBuffer))this.activeRun.chunkSeq++,this.callbacks.sendStreamChunk(this.activeRun.eventId,this.activeRun.sessionId,t,this.activeRun.chunkSeq,!1,this.activeRun.clientMsgId);this.activeRun.textBuffer=""}}stopTextFlush(){this.activeRun?.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null)}startComposing(t,e){}stopComposing(){}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.activeRun)&&(this.idleTimer=setTimeout(()=>{n.error("openhuman-adapter","Idle timeout \u2014 emitting exit for respawn"),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed","idle timeout"),this.clearRun()),this.emit("exit",-1)},D))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveWorkspaceDir(){return this.options.workspaceDir?this.options.workspaceDir.replace(/^~/,u()):p(u(),".openhuman")}resolveCwd(){const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}buildPromptText(t){let e=t.text;return t.contextMessages&&t.contextMessages.length>0&&(e=t.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
1
+ import{EventEmitter as m}from"node:events";import{stat as R}from"node:fs/promises";import{mkdirSync as I}from"node:fs";import{homedir as u}from"node:os";import{join as p,resolve as g}from"node:path";import{fileURLToPath as _}from"node:url";import{randomUUID as k}from"node:crypto";import{resolveCommandPath as E,spawnCommand as x,killProcessGroup as f,hasChildProcesses as w}from"../../core/runtime/spawn.js";import{InternalApiServer as S}from"../../core/mcp/internal-api-server.js";import{syncDefaultSkillsToDir as b}from"../../default-skills/index.js";import{buildSimpleProbeReport as y}from"../shared/probe-util.js";import{OpenHumanTransport as $,readBearerToken as A}from"./openhuman-transport.js";import{IdentityInjector as C}from"../shared/identity-injector.js";import{log as n}from"../../core/log/index.js";import{splitTextForAibotProtocol as P}from"../../core/protocol/index.js";class L extends m{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitError(t){if(this.listenerCount("error")===0){n.warn("openhuman-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const F=200,D=2e3,M=12e4,N=500,v=3e4,B=7788,O="127.0.0.1";class et extends m{type="openhuman";config;callbacks;options;identity;process=null;transport=new $;alive=!1;stopped=!1;internalApi=null;clientId;activeRun=null;completedEvents=new Set;clientMsgSeq=0;idleTimer=null;constructor(t,e,s){super(),this.config=t,this.callbacks=e,this.options=s??{},this.clientId=`grix-connector-${Date.now()}`,this.identity=new C("openhuman-adapter",e.getAgentProfile)}async start(){await this.startInternalApiAndInjectMcp();const t=this.options.host??O,e=this.options.port??B;await this.spawnProcess(t,e),await this.waitForServerReady(t,e);const s=this.resolveWorkspaceDir(),i=await A(s),r=`http://${t}:${e}`;if(await this.transport.connect(r,i),this.transport.on("event",o=>this.handleSocketEvent(o)),this.options.sessionToken)try{await this.transport.storeSession({token:this.options.sessionToken}),n.info("openhuman-adapter","Session token stored")}catch(o){n.warn("openhuman-adapter",`Failed to store session token: ${o}`)}this.transport.socketId&&(this.clientId=this.transport.socketId),n.info("openhuman-adapter",`Ready (pid=${this.process?.pid}, clientId=${this.clientId})`)}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.transport.disconnect(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.process){const t=this.process;try{f(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{f(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){return this.clientId}async resumeSession(t,e){}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t)}sendPrompt(t){const e=new L(t.adapterSessionId),s=this.buildPromptText(t);return this.doWebChat(t.adapterSessionId,s).then(i=>{this.activeRun&&(this.activeRun.requestId=i.request_id)}).catch(i=>{e.emitError(i instanceof Error?i:new Error(String(i)))}),e}async cancel(t){if(this.activeRun)try{await this.transport.webCancel({client_id:this.clientId,thread_id:this.activeRun.threadId})}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:s,content:i}=t,r=this.buildPromptTextFromEvent(t);if(this.completedEvents.has(e)){n.info("openhuman-adapter",`Dropping duplicate event ${e}`),this.callbacks.sendEventAck(e,s),this.callbacks.sendEventResult(e,"responded");return}if(!this.alive){n.warn("openhuman-adapter",`Dropping event ${e}: process not alive`),this.callbacks.sendEventAck(e,s),this.callbacks.sendEventResult(e,"failed","Agent process not running");return}this.activeRun&&this.activeRun.eventId!==e&&(n.info("openhuman-adapter",`steer: ${this.activeRun.eventId} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),n.info("openhuman-adapter",`prompt: event=${e} session=${s}`),this.callbacks.sendEventAck(e,s),this.startRun(e,s,s),this.startComposing(s,e),this.resetIdleTimer(),this.doWebChat(s,r).then(o=>{this.activeRun&&this.activeRun.eventId===e&&(this.activeRun.requestId=o.request_id,o.accepted||(n.warn("openhuman-adapter",`web_chat not accepted: ${o.request_id}`),this.finishRun("failed","Chat request not accepted")))}).catch(o=>{n.error("openhuman-adapter",`web_chat failed: ${o}`),this.finishRun("failed",String(o))})}deliverStopEvent(t,e){this.activeRun&&this.activeRun.eventId===t&&(n.info("openhuman-adapter",`stop: event=${t}`),this.transport.webCancel({client_id:this.clientId,thread_id:this.activeRun.threadId}).catch(()=>{}),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(t){}async ping(t){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.activeRun?1:0}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const t=g(_(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?w(t,[t]):!1}async probe(t){const e=this.getStatus();return y(this.config.command||"openhuman-core",{alive:e.alive,busy:e.busy,started:!!this.process},t)}async startInternalApiAndInjectMcp(){try{this.internalApi=new S,this.internalApi.setInvokeHandler(async(a,d)=>this.callbacks.agentInvoke(a,d)),await this.internalApi.start(0),n.info("openhuman-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=p(u(),".openhuman","users","local","workspace","mcp_clients"),s=p(e,"mcp_clients.db");I(e,{recursive:!0});const{execFileSync:i}=await import("node:child_process"),r=k(),o=JSON.stringify(t.args),l=["CREATE TABLE IF NOT EXISTS mcp_servers (server_id TEXT PRIMARY KEY, qualified_name TEXT NOT NULL, display_name TEXT NOT NULL, description TEXT, icon_url TEXT, command_kind TEXT NOT NULL DEFAULT 'node', command TEXT NOT NULL, args_json TEXT NOT NULL DEFAULT '[]', env_keys_json TEXT NOT NULL DEFAULT '[]', config_json TEXT, installed_at INTEGER NOT NULL, last_connected_at INTEGER);","DELETE FROM mcp_servers WHERE qualified_name = 'grix-connector-tools';",`INSERT INTO mcp_servers (server_id, qualified_name, display_name, description, command_kind, command, args_json, installed_at) VALUES ('${r}', 'grix-connector-tools', 'Grix Connector Tools', 'Grix platform query and management tools', 'node', '${t.command}', '${o.replace(/'/g,"''")}', ${Date.now()});`].join(`
2
+ `);i("sqlite3",[s,l],{timeout:1e4,stdio:"ignore"}),n.info("openhuman-adapter",`MCP server registered in SQLite: ${s}`);const c=p(u(),".openhuman","skills"),h=b(c);h.length>0&&n.info("openhuman-adapter",`Synced connector skills to ${c}: [${h.join(", ")}]`)}catch(t){n.warn("openhuman-adapter",`Failed to inject MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async spawnProcess(t,e){const s=this.config.command||"openhuman-core",i=E(s,typeof process.env.PATH=="string"?process.env.PATH:void 0),r=this.config.args??[],l=r.includes("run")||r.includes("serve")?r:["run","--host",t,"--port",String(e),...r],c={...process.env,...this.config.env},h=this.resolveCwd();n.info("openhuman-adapter",`Spawning: ${i} ${l.join(" ")}`);try{if(!(await R(h)).isDirectory())throw new Error(`Bound path is not a directory: ${h}`)}catch(a){throw String(a?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${h}. Please rebind with /grix open <valid-directory>.`):a}try{this.process=x(i,l,{env:c,cwd:h}).process}catch(a){throw n.error("openhuman-adapter",`Spawn threw: ${a}`),this.alive=!1,a}this.process.on("error",a=>{n.error("openhuman-adapter",`Spawn error: ${a.message}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${a.message}`),this.clearRun()),this.stopped||this.emit("exit",1)}),this.process.on("exit",a=>{n.info("openhuman-adapter",`Process exited (code=${a})`),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${a})`),this.clearRun()),this.stopped||this.emit("exit",a??1)}),this.process.stderr?.on("data",a=>{const d=a.toString().trim();d&&n.info("openhuman-adapter",`[stderr] ${d}`)}),this.alive=!0}async waitForServerReady(t,e){const s=`http://${t}:${e}/health`,i=Date.now()+v;for(;Date.now()<i;){try{if((await fetch(s,{signal:AbortSignal.timeout(2e3)})).ok)return}catch{}await new Promise(r=>setTimeout(r,N))}throw new Error(`openhuman-core did not become ready at ${t}:${e} after ${v/1e3}s`)}async doWebChat(t,e){return this.transport.webChat({client_id:this.clientId,thread_id:t,message:e})}handleSocketEvent(t){if(this.stopped||!this.activeRun||t.request_id&&this.activeRun.requestId&&t.request_id!==this.activeRun.requestId)return;this.resetIdleTimer();const e=t.event;switch(e){case"text_delta":{t.delta&&t.delta_kind==="text"&&this.appendText(t.delta);break}case"thinking_delta":{t.delta&&t.delta_kind==="thinking"&&this.activeRun&&this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,t.delta);break}case"tool_call":{if(this.flushTextBuffer(),this.activeRun&&t.tool_name){const s=typeof t.args=="string"?t.args:JSON.stringify(t.args??{});this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,t.tool_name,s)}break}case"tool_result":{if(this.activeRun&&t.tool_name){const s=t.output??"";this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,t.tool_name,s)}break}case"chat_done":{n.info("openhuman-adapter",`chat_done request=${t.request_id}`),this.activeRun&&this.activeRun.textBuffer.length===0&&t.full_response&&(this.activeRun.textBuffer=t.full_response),this.flushTextBuffer(),this.finishRun("responded");break}case"chat_error":{if(n.error("openhuman-adapter",`chat_error: ${t.error_type} ${t.message}`),this.flushTextBuffer(),this.activeRun){const s=t.message??t.error_type??"unknown error";this.callbacks.sendRunError(this.activeRun.eventId,this.activeRun.sessionId,s)}this.finishRun("failed",t.message);break}case"chat_segment":case"inference_start":case"iteration_start":case"chat_accepted":break;default:{n.debug("openhuman-adapter",`Unhandled event: ${e}`);break}}}startRun(t,e,s){this.activeRun={eventId:t,sessionId:e,requestId:"",threadId:s,chunkSeq:0,clientMsgId:`oh_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null}}finishRun(t,e){const s=this.activeRun;if(!s)return;if(this.completedEvents.add(s.eventId),this.completedEvents.size>1e3){const o=this.completedEvents.values();for(let c=0;c<500;c++)o.next();const l=[...this.completedEvents].slice(-500);this.completedEvents=new Set(l)}this.activeRun=null,this.emit("eventDone",s.eventId),this.stopComposing(),this.stopIdleTimer();const i=++s.chunkSeq,r=s.clientMsgId;t==="failed"&&e&&this.callbacks.sendRunError(s.eventId,s.sessionId,e),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(s.eventId,s.sessionId,i,r).then(()=>{this.callbacks.sendEventResult(s.eventId,t,e)}).catch(()=>{this.callbacks.sendStreamChunk(s.eventId,s.sessionId,"",i,!0,r),this.callbacks.sendEventResult(s.eventId,t,e)}):(this.callbacks.sendStreamChunk(s.eventId,s.sessionId,"",i,!0,r),this.callbacks.sendEventResult(s.eventId,t,e))}clearRun(){this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const t=this.activeRun?.eventId;this.activeRun=null,t&&this.emit("eventDone",t)}appendText(t){if(this.activeRun){if(this.activeRun.textBuffer+=t,this.activeRun.textBuffer.length>=D){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},F))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const t of P(this.activeRun.textBuffer))this.activeRun.chunkSeq++,this.callbacks.sendStreamChunk(this.activeRun.eventId,this.activeRun.sessionId,t,this.activeRun.chunkSeq,!1,this.activeRun.clientMsgId);this.activeRun.textBuffer=""}}stopTextFlush(){this.activeRun?.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null)}startComposing(t,e){}stopComposing(){}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.activeRun)&&(this.idleTimer=setTimeout(()=>{n.error("openhuman-adapter","Idle timeout \u2014 emitting exit for respawn"),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed","idle timeout"),this.clearRun()),this.emit("exit",-1)},M))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveWorkspaceDir(){return this.options.workspaceDir?this.options.workspaceDir.replace(/^~/,u()):p(u(),".openhuman")}resolveCwd(){const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}buildPromptText(t){let e=t.text;return t.contextMessages&&t.contextMessages.length>0&&(e=t.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
3
3
  `)+`
4
4
 
5
- `+e),e}buildPromptTextFromEvent(t){let e=t.content||"";if(t.context_messages_json)try{const s=JSON.parse(t.context_messages_json);Array.isArray(s)&&s.length>0&&(e=s.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
5
+ `+e),this.identity.injectOnce(t.adapterSessionId,e)}buildPromptTextFromEvent(t){let e=t.content||"";if(t.context_messages_json)try{const s=JSON.parse(t.context_messages_json);Array.isArray(s)&&s.length>0&&(e=s.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
6
6
  `)+`
7
7
 
8
- `+e)}catch{}return e}}export{Z as OpenHumanAdapter};
8
+ `+e)}catch{}return this.identity.injectOnce(t.session_id,e)}}export{et as OpenHumanAdapter};