grix-connector 3.26.3 → 3.26.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/agy/agy-adapter.js +5 -5
- package/dist/adapter/codewhale/codewhale-adapter.js +2 -2
- package/dist/adapter/codex/codex-bridge.js +8 -8
- package/dist/adapter/cursor/cursor-adapter.js +7 -7
- package/dist/adapter/opencode/opencode-adapter.js +5 -5
- package/dist/adapter/openhuman/openhuman-adapter.js +4 -4
- package/dist/bridge/bridge.js +7 -7
- package/dist/bridge/send-controller.js +3 -3
- package/dist/core/mcp/index.js +1 -1
- package/dist/core/mcp/server-name.js +1 -0
- package/dist/core/skill-sync/skill-syncer.js +1 -1
- package/dist/mcp/stream-http/security.js +1 -1
- package/package.json +1 -1
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import{spawn as $}from"node:child_process";import{randomUUID as k}from"node:crypto";import{EventEmitter as I}from"node:events";import{existsSync as E,readFileSync as _,readdirSync as b,statSync as w,mkdirSync as x,writeFileSync as C,realpathSync as L}from"node:fs";import{homedir as g}from"node:os";import{join as p,dirname as R,resolve as T}from"node:path";import{fileURLToPath as
|
|
2
|
-
`,"utf8"),o.info(a,`MCP config injected into ${e}`);const n=p(g(),".gemini","skills"),c=
|
|
1
|
+
import{spawn as $}from"node:child_process";import{randomUUID as k}from"node:crypto";import{EventEmitter as I}from"node:events";import{existsSync as E,readFileSync as _,readdirSync as b,statSync as w,mkdirSync as x,writeFileSync as C,realpathSync as L}from"node:fs";import{homedir as g}from"node:os";import{join as p,dirname as R,resolve as T}from"node:path";import{fileURLToPath as M}from"node:url";import{log as o}from"../../core/log/index.js";import{killProcessGroup as f}from"../../core/runtime/spawn.js";import{InternalApiServer as j}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as G,pruneLegacyMcpServerEntries as O}from"../../core/mcp/server-name.js";import{syncDefaultSkillsToDir as D}from"../../default-skills/index.js";import{buildSimpleProbeReport as N}from"../shared/probe-util.js";const a="agy-adapter";function B(y){try{return L(y)}catch{return y}}const m=p(g(),".gemini","antigravity-cli","log"),A=p(g(),".gemini","antigravity-cli","cache","last_conversations.json"),Q=["\u4F60\u63A5\u5165\u7684\u662F Grix \u804A\u5929\u3002\u7528\u6237\u6D88\u606F\u88AB\u5305\u5728 <channel ...> \u6807\u7B7E\u91CC\uFF0C\u6807\u7B7E\u5C5E\u6027\u643A\u5E26\u672C\u8F6E\u4E0A\u4E0B\u6587\uFF1A","chat_id\uFF08\u5F53\u524D\u4F1A\u8BDD\uFF09\u3001agent_id\uFF08\u5F53\u524D Agent\uFF09\u3001event_id\uFF08\u672C\u8F6E\u4E8B\u4EF6\uFF09\u3001message_id\uFF08\u7528\u6237\u8FD9\u6761\u6D88\u606F\u7684 ID\uFF09\u3001user_id\uFF08\u53D1\u9001\u8005\uFF09\u3002","\u91CD\u8981\uFF1A\u4F60\u7684\u56DE\u590D\u5FC5\u987B\u8C03\u7528 grix \u7684 `grix_message_send` \u5DE5\u5177\u53D1\u9001\uFF08sessionId \u53D6\u81EA channel \u7684 chat_id\uFF0Ccontent \u4E3A\u4F60\u7684\u56DE\u590D\u5185\u5BB9\uFF09\uFF0C","\u4E0D\u8981\u53EA\u628A\u7B54\u6848\u6253\u5370\u5230\u6807\u51C6\u8F93\u51FA\u2014\u2014\u53EA\u6709\u8C03\u7528\u5DE5\u5177\u624D\u4F1A\u628A\u6D88\u606F\u771F\u6B63\u53D1\u7ED9\u7528\u6237\u3002","grix_message_send \u4F1A\u8FD4\u56DE\u4F60\u521A\u53D1\u51FA\u6D88\u606F\u7684 msg_id\u3002\u9700\u8981\u65F6\u4F60\u53EF\u4EE5\u7528\u8FD9\u4E2A ID \u505A\u540E\u7EED\u64CD\u4F5C\uFF0C\u4F8B\u5982\u8C03\u7528 grix_message_unsend\uFF08\u4F20 msgId\uFF09\u64A4\u56DE\u67D0\u6761\u6D88\u606F\u3002"].join(""),F=new Set(["send_msg","grix_reply"]),V=new Set(["send_msg","grix_reply","delete_msg","session_send","grix_complete","grix_composing","grix_event_ack"]);class it extends I{type="agy";config;callbacks;runtimeResolver;alive=!1;stopped=!1;internalApi=null;activeEventId=null;activeEventSessionId=null;activeProcess=null;completedEventIds=new Set;activeEventSentViaTool=!1;sessionConversationMap=new Map;conversationOutputCache=new Map;eventQueue=[];constructor(t,e,s){super(),this.config=t,this.callbacks=e,this.runtimeResolver=s}async start(){this.alive||(this.alive=!0,this.stopped=!1,await this.startInternalApiAndInjectMcp(),o.info(a,"AgyAdapter started"))}async startInternalApiAndInjectMcp(){try{this.internalApi=new j,this.internalApi.setInvokeHandler(async(r,l,h,u)=>this.handleToolInvoke(r,l,u)),await this.internalApi.start(0),o.info(a,`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=p(g(),".gemini","config","mcp_config.json");x(R(e),{recursive:!0});let s={};try{E(e)&&(s=JSON.parse(_(e,"utf8")))}catch{}const i=s.mcpServers&&typeof s.mcpServers=="object"?s.mcpServers:{};O(i,this.internalApi.url),i[t.name]={command:t.command,args:t.args},s.mcpServers=i,C(e,`${JSON.stringify(s,null,2)}
|
|
2
|
+
`,"utf8"),o.info(a,`MCP config injected into ${e}`);const n=p(g(),".gemini","skills"),c=D(n);c.length>0&&o.info(a,`Synced connector skills to ${n}: [${c.join(", ")}]`)}catch(t){o.warn(a,`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async handleToolInvoke(t,e,s){let i=e;V.has(t)&&this.activeEventSessionId&&(i.session_id==null||i.session_id==="")&&(i={...i,session_id:this.activeEventSessionId});const n=await this.callbacks.agentInvoke(t,i,s);return F.has(t)&&this.activeEventId&&(this.activeEventSentViaTool=!0),n}async stop(){if(!this.stopped){if(this.stopped=!0,this.alive=!1,this.activeProcess){try{f(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null}if(this.activeEventId&&this.activeEventSessionId)try{this.callbacks.sendEventResult(this.activeEventId,"canceled","adapter stopped")}catch{}if(this.activeEventId=null,this.activeEventSessionId=null,this.internalApi){try{await this.internalApi.stop()}catch{}this.internalApi=null}this.emit("exit",0),o.info(a,"AgyAdapter stopped")}}isAlive(){return this.alive}async createSession(t){return t.cwd??k()}async resumeSession(t,e){}async destroySession(t){}sendPrompt(t){const e=new I;return e.adapterSessionId=t.adapterSessionId,e.cancel=async()=>{e.emit("done",{status:"canceled"})},e}async cancel(t){}cancelCurrentRun(){if(!this.activeEventId||!this.activeProcess)return;const t=this.activeEventId;o.info(a,`cancelCurrentRun: killing process group for event ${t}`);try{f(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null,this.callbacks.sendEventResult(t,"canceled","restarted by user"),this.clearActiveEvent(t),this.drainQueue()}deliverInboundEvent(t){if(!this.stopped){if(this.completedEventIds.has(t.event_id)){o.debug(a,`Skipping duplicate event: ${t.event_id}`);return}if(this.callbacks.sendEventAck(t.event_id,t.session_id),this.activeEventId){o.info(a,`Queuing event ${t.event_id} (active: ${this.activeEventId})`),this.eventQueue.push(t);return}this.processEvent(t)}}deliverStopEvent(t,e){if(this.activeEventId===t&&this.activeProcess){o.info(a,`Stopping event ${t}`);try{f(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null,this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActiveEvent(t),this.drainQueue()}}setPermissionHandler(){}async ping(t){return this.alive}getStatus(){return{alive:this.alive,busy:this.activeEventId!==null,sessions:this.sessionConversationMap.size}}async probe(t){const e=this.getStatus();return N(this.config.command||"agy",{alive:e.alive,busy:e.busy,started:e.alive},t)}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}clearActiveEventForShutdown(){if(this.activeProcess)try{f(this.activeProcess,"SIGKILL")}catch{}this.activeEventId=null,this.activeEventSessionId=null,this.activeProcess=null,this.activeEventSentViaTool=!1}getMcpConfig(){if(!this.internalApi)return null;const t=T(M(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:G(this.callbacks.getAgentId?.()),command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}processEvent(t){const{event_id:e,session_id:s}=t,i=this.runtimeResolver(s);if(!i.cwd){o.warn(a,`No working directory for session ${s}, event should have been intercepted by bridge`),this.callbacks.forceCompleteInternalEvent(e,s);return}this.activeEventId=e,this.activeEventSessionId=s,this.activeEventSentViaTool=!1,this.emit("eventStarted",e,s),o.info(a,`Processing event ${e} for session ${s}`);const n=this.buildAgyPrompt(t);this.spawnAgyPrint(e,s,n,i)}buildAgyPrompt(t){const s=[["chat_id",t.session_id],["agent_id",this.callbacks.getAgentId?.()],["event_id",t.event_id],["message_id",t.msg_id],["user_id",t.sender_id],["quoted_message_id",t.quoted_message_id]].filter(([,l])=>l!=null&&l!=="").map(([l,h])=>`${l}="${h}"`).join(" "),i=this.renderContextBlock(t),n=i?`${i}
|
|
3
3
|
|
|
4
4
|
${t.content}`:t.content,c=`<channel source="grix-agy" ${s}>
|
|
5
5
|
${n}
|
|
6
|
-
</channel>`;return`${this.buildIdentityBlock()}${
|
|
6
|
+
</channel>`;return`${this.buildIdentityBlock()}${Q}
|
|
7
7
|
|
|
8
8
|
${c}`}buildIdentityBlock(){const t=this.callbacks.getAgentProfile?.(),e=t?.agentName?.trim()??"",s=t?.introduction?.trim()??"";if(!e&&!s)return"";const i=["[system-identity]"];return e&&i.push(`\u4F60\u7684\u540D\u5B57\u662F"${e}"\u3002`),s&&i.push(`\u4F60\u7684\u81EA\u6211\u4ECB\u7ECD\uFF1A${s}`),i.push("\u8FD9\u662F\u5E26\u5916\u6307\u4EE4\uFF1B\u4E0D\u8981\u5728\u56DE\u590D\u4E2D\u590D\u8FF0\u6216\u5F15\u7528\u672C\u6BB5\u3002"),i.push("[/system-identity]"),`${i.join(`
|
|
9
9
|
`)}
|
|
10
10
|
|
|
11
11
|
`}renderContextBlock(t){const e=t.context_messages_json;if(!e)return"";let s;try{const r=JSON.parse(e);if(!Array.isArray(r))return"";s=r}catch{return""}const i=String(t.session_type??"")==="2",n=String(t.msg_id??""),c=[];for(const r of s){const l=String(r?.msg_id??"");if(l&&l===n)continue;const h=String(r?.content??"").trim();if(!h)continue;const u=String(r?.sender_id??"");if(h.startsWith("[\u5F15\u7528\u6D88\u606F]")){const d=h.slice(6).replace(/^\s*\n?/,"").trim();c.push(i&&u?`[\u5F15\u7528\u6D88\u606F] (\u6765\u81EA ${u})\uFF1A${d}`:`[\u5F15\u7528\u6D88\u606F]\uFF1A${d}`)}else c.push(i&&u?`[${u}]\uFF1A${h}`:h)}return c.join(`
|
|
12
|
-
`)}spawnAgyPrint(t,e,s,i){const n=this.buildPrintArgs(s,i),c={...process.env,...this.config.env??{}};o.info(a,`Spawning: agy ${n.map(d=>d.includes(" ")?`"${d}"`:d).join(" ")}`);const r=this.getLatestLogFilePath(),l=$(this.config.command,n,{cwd:i.cwd,env:c,stdio:["pipe","pipe","pipe"],detached:!0});this.activeProcess=l;const h=[],u=[];l.stdout?.on("data",d=>{h.push(d)}),l.stderr?.on("data",d=>{u.push(d)}),l.on("error",d=>{o.error(a,`Process spawn error for event ${t}: ${d.message}`),this.handleProcessResult(t,e,"",`spawn error: ${d.message}`,i)}),l.on("close",d=>{if(o.info(a,`Process exited for event ${t} with code ${d}`),this.activeEventId!==t)return;const v=Buffer.concat(h).toString("utf-8"),P=Buffer.concat(u).toString("utf-8");if(d!==0){const S=P.trim()||`process exited with code ${d}`;this.handleProcessResult(t,e,v,S,i)}else v.trim()?this.handleProcessResult(t,e,v,"",i):this.activeEventSentViaTool?this.handleProcessResult(t,e,v,"",i):setTimeout(()=>{const S=this.extractLogError(r);this.handleProcessResult(t,e,v,S,i)},300)}),l.stdin?.end()}buildPrintArgs(t,e){const s=[];return e.modelId&&s.push("--model",e.modelId),e.cwd&&s.push("--add-dir",e.cwd),s.push("--dangerously-skip-permissions"),e.conversationId&&s.push("--conversation",e.conversationId),s.push("-p",t),s}readAgyConversationId(t){try{if(E(A)){const e=JSON.parse(_(A,"utf-8"));return e[
|
|
13
|
-
`).filter(n=>n.startsWith("E")).map(n=>{const c=n.indexOf("] ");return c>=0?n.slice(c+2):n}).filter(n=>n.length>0);if(i.length>0){const n=i[i.length-1];return o.info(a,`Extracted error from agy log: ${n.slice(0,120)}`),n.length>500?n.slice(0,500)+"...":n}return"agy completed without output (possible auth or quota issue)"}catch(e){return o.info(a,`extractLogError: ${e}`),"agy completed without output"}}handleProcessResult(t,e,s,i,n){if(this.activeEventId===t){if(i&&!s.trim()){o.error(a,`Event ${t} failed: ${i}`);const r=i.includes("RESOURCE_EXHAUSTED")||i.includes("quota")?"The agy API quota has been exhausted. Please try again later.":`agy execution failed: ${i}`;this.callbacks.sendStreamChunk(t,e,r,1,!0,`agy-${t}`),this.callbacks.sendEventResult(t,"failed",i)}else{const c=s.trim();if(c){const r=n.cwd,l=r?this.extractDelta(c,r):c;r&&this.conversationOutputCache.set(r,c),l&&!this.activeEventSentViaTool&&this.callbacks.sendStreamChunk(t,e,l,1,!0,`agy-${t}`)}if(n.cwd){const r=this.readAgyConversationId(n.cwd);r&&r!==n.conversationId&&(this.sessionConversationMap.set(e,r),this.callbacks.persistConversationId(e,r))}this.callbacks.sendEventResult(t,"responded")}this.clearActiveEvent(t),this.drainQueue()}}extractDelta(t,e){const s=this.conversationOutputCache.get(e);return s&&t.startsWith(s)?t.slice(s.length).trim():t}clearActiveEvent(t){const e=t??this.activeEventId;if(e&&(this.completedEventIds.add(e),this.completedEventIds.size>1e3)){const s=Array.from(this.completedEventIds);this.completedEventIds.clear();for(let i=500;i<s.length;i++)this.completedEventIds.add(s[i])}this.activeEventId=null,this.activeEventSessionId=null,this.activeProcess=null,this.activeEventSentViaTool=!1,e&&this.emit("eventDone",e)}drainQueue(){if(this.stopped||this.activeEventId)return;const t=this.eventQueue.shift();t&&(o.info(a,`Draining queued event ${t.event_id}`),this.processEvent(t))}}export{
|
|
12
|
+
`)}spawnAgyPrint(t,e,s,i){const n=this.buildPrintArgs(s,i),c={...process.env,...this.config.env??{}};o.info(a,`Spawning: agy ${n.map(d=>d.includes(" ")?`"${d}"`:d).join(" ")}`);const r=this.getLatestLogFilePath(),l=$(this.config.command,n,{cwd:i.cwd,env:c,stdio:["pipe","pipe","pipe"],detached:!0});this.activeProcess=l;const h=[],u=[];l.stdout?.on("data",d=>{h.push(d)}),l.stderr?.on("data",d=>{u.push(d)}),l.on("error",d=>{o.error(a,`Process spawn error for event ${t}: ${d.message}`),this.handleProcessResult(t,e,"",`spawn error: ${d.message}`,i)}),l.on("close",d=>{if(o.info(a,`Process exited for event ${t} with code ${d}`),this.activeEventId!==t)return;const v=Buffer.concat(h).toString("utf-8"),P=Buffer.concat(u).toString("utf-8");if(d!==0){const S=P.trim()||`process exited with code ${d}`;this.handleProcessResult(t,e,v,S,i)}else v.trim()?this.handleProcessResult(t,e,v,"",i):this.activeEventSentViaTool?this.handleProcessResult(t,e,v,"",i):setTimeout(()=>{const S=this.extractLogError(r);this.handleProcessResult(t,e,v,S,i)},300)}),l.stdin?.end()}buildPrintArgs(t,e){const s=[];return e.modelId&&s.push("--model",e.modelId),e.cwd&&s.push("--add-dir",e.cwd),s.push("--dangerously-skip-permissions"),e.conversationId&&s.push("--conversation",e.conversationId),s.push("-p",t),s}readAgyConversationId(t){try{if(E(A)){const e=JSON.parse(_(A,"utf-8"));return e[B(t)]||e[t]||void 0}}catch(e){o.debug(a,`readAgyConversationId: ${e}`)}}getLatestLogFilePath(){try{if(!E(m))return null;const t=b(m).filter(e=>e.startsWith("cli-")&&e.endsWith(".log")).map(e=>({name:e,path:p(m,e),mtime:w(p(m,e)).mtimeMs})).sort((e,s)=>s.mtime-e.mtime);return t.length>0?t[0].path:null}catch{return null}}extractLogError(t){try{const e=this.getLatestLogFilePath();if(!e)return o.info(a,"extractLogError: no log files found"),"agy completed without output";const s=_(e,"utf-8");if(!s)return o.info(a,`extractLogError: log file is empty: ${e}`),"agy completed without output";const i=s.split(`
|
|
13
|
+
`).filter(n=>n.startsWith("E")).map(n=>{const c=n.indexOf("] ");return c>=0?n.slice(c+2):n}).filter(n=>n.length>0);if(i.length>0){const n=i[i.length-1];return o.info(a,`Extracted error from agy log: ${n.slice(0,120)}`),n.length>500?n.slice(0,500)+"...":n}return"agy completed without output (possible auth or quota issue)"}catch(e){return o.info(a,`extractLogError: ${e}`),"agy completed without output"}}handleProcessResult(t,e,s,i,n){if(this.activeEventId===t){if(i&&!s.trim()){o.error(a,`Event ${t} failed: ${i}`);const r=i.includes("RESOURCE_EXHAUSTED")||i.includes("quota")?"The agy API quota has been exhausted. Please try again later.":`agy execution failed: ${i}`;this.callbacks.sendStreamChunk(t,e,r,1,!0,`agy-${t}`),this.callbacks.sendEventResult(t,"failed",i)}else{const c=s.trim();if(c){const r=n.cwd,l=r?this.extractDelta(c,r):c;r&&this.conversationOutputCache.set(r,c),l&&!this.activeEventSentViaTool&&this.callbacks.sendStreamChunk(t,e,l,1,!0,`agy-${t}`)}if(n.cwd){const r=this.readAgyConversationId(n.cwd);r&&r!==n.conversationId&&(this.sessionConversationMap.set(e,r),this.callbacks.persistConversationId(e,r))}this.callbacks.sendEventResult(t,"responded")}this.clearActiveEvent(t),this.drainQueue()}}extractDelta(t,e){const s=this.conversationOutputCache.get(e);return s&&t.startsWith(s)?t.slice(s.length).trim():t}clearActiveEvent(t){const e=t??this.activeEventId;if(e&&(this.completedEventIds.add(e),this.completedEventIds.size>1e3)){const s=Array.from(this.completedEventIds);this.completedEventIds.clear();for(let i=500;i<s.length;i++)this.completedEventIds.add(s[i])}this.activeEventId=null,this.activeEventSessionId=null,this.activeProcess=null,this.activeEventSentViaTool=!1,e&&this.emit("eventDone",e)}drainQueue(){if(this.stopped||this.activeEventId)return;const t=this.eventQueue.shift();t&&(o.info(a,`Draining queued event ${t.event_id}`),this.processEvent(t))}}export{it as AgyAdapter};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{execFileSync as I}from"node:child_process";import{stat as A}from"node:fs/promises";import{resolveCommandPath as w,spawnCommand as C,killProcessGroup as b}from"../../core/runtime/spawn.js";import{createInterface as M}from"node:readline";import{EventEmitter as k}from"node:events";import{join as _,resolve as E}from"node:path";import{homedir as P}from"node:os";import{fileURLToPath as x}from"node:url";import{InternalApiServer as T}from"../../core/mcp/internal-api-server.js";import{InboundMessageIdInjector as
|
|
1
|
+
import{execFileSync as I}from"node:child_process";import{stat as A}from"node:fs/promises";import{resolveCommandPath as w,spawnCommand as C,killProcessGroup as b}from"../../core/runtime/spawn.js";import{createInterface as M}from"node:readline";import{EventEmitter as k}from"node:events";import{join as _,resolve as E}from"node:path";import{homedir as P}from"node:os";import{fileURLToPath as x}from"node:url";import{InternalApiServer as T}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as $,LEGACY_MCP_SERVER_NAMES as N}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as R}from"../shared/inbound-message-id-injector.js";import{IdentityInjector as B}from"../shared/identity-injector.js";import{compactToolInputForWire as D}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as L}from"../../default-skills/index.js";import{buildSimpleProbeReport as U}from"../shared/probe-util.js";import{getCachedCodeWhaleModels as j,primeCodeWhaleModels as O}from"./model-list.js";import{writeCodeWhaleGrixConfig as G}from"./codewhale-provider-config.js";import{log as o}from"../../core/log/index.js";import{SessionBindingStore as W}from"../../core/persistence/session-binding-store.js";const H=120*1e3,f=1800*1e3,q=5*1e3;function F(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class ue extends k{type="codewhale";config;callbacks;alive=!1;stopped=!1;internalApi=null;deepSeekSessionId=null;activeEventId=null;activeSessionId=null;chunkSeq=0;activeClientMsgId=null;idleTimer=null;lastProgressAt=0;activeProcess=null;identity;inboundMessageIds=new R;bindingStore=null;aibotSessionId="";cwd;provider;agentName="";grixConfigPath="";lastUsage=null;currentModel=null;toolNamesById=new Map;auditCaptures=new Map;completedAuditBoundaries=new Map;constructor(e,t){super(),this.config=e,this.callbacks=t,this.identity=new B("codewhale-adapter",t.getAgentProfile);const i=e.options??{};if(this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.bindingStore=i.bindingStore instanceof W?i.bindingStore:null,this.provider=i.provider,this.agentName=String(i.agentName??"").trim(),this.cwd=this.resolveCwd(),this.bindingStore&&this.aibotSessionId){const n=this.bindingStore.getCodeWhaleThreadId(this.aibotSessionId);n&&(this.deepSeekSessionId=n)}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}return process.cwd()}async start(){this.alive=!0,await this.applyGrixProviderConfig(),await this.startInternalApiAndRegisterMcp(),O(this.config.command||"codewhale"),this.notifyBindingReady(),o.info("codewhale-adapter","Ready (exec mode)")}async applyGrixProviderConfig(){if(!this.provider){this.grixConfigPath="";return}try{this.grixConfigPath=await G(this.agentName,this.provider)??"",this.grixConfigPath?o.info("codewhale-adapter",`Grix provider config written to ${this.grixConfigPath}`):o.warn("codewhale-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied")}catch(e){this.grixConfigPath="",o.warn("codewhale-adapter",`Failed to write Grix provider config: ${e instanceof Error?e.message:String(e)}`)}}async stop(){this.stopped=!0,this.alive=!1,this.stopComposing(),this.clearIdleTimer(),this.killActiveProcess(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null)}isAlive(){return this.alive}async createSession(e){const t=this.deepSeekSessionId??`ds-${Date.now()}`;return this.notifyBindingReady(),t}async resumeSession(e,t){}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(e){this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e),this.deepSeekSessionId=null,this.persistSessionId(void 0)}sendPrompt(e){const t=new y(e.adapterSessionId);return this.runMessage(e,t).catch(i=>{t.emitError(i instanceof Error?i:new Error(String(i)))}),t}async cancel(e){this.killActiveProcess()}setPermissionHandler(e){}async ping(e){if(this.stopped||!this.alive)return!1;const t=this.activeProcess;return!(t?.pid&&!F(t.pid))}getStatus(){return{alive:this.alive,busy:this.activeEventId!==null,sessions:this.deepSeekSessionId?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}clearActiveEventForShutdown(){this.clearIdleTimer(),this.killActiveProcess(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}getMcpConfig(){if(!this.internalApi)return null;const e=E(x(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:$(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async probe(e){const t=this.getStatus();return U(this.config.command||"codewhale",{alive:t.alive,busy:t.busy,started:this.alive},e)}getUsageSnapshot(){return this.lastUsage}async startInternalApiAndRegisterMcp(){try{this.internalApi=new T,this.internalApi.setInvokeHandler(async(a,p,h,c)=>this.callbacks.agentInvoke(a,p,c)),await this.internalApi.start(0),o.info("codewhale-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,n=w(this.config.command||"codewhale",i);for(const a of[...N,e.name])try{I(n,["mcp","remove",a],{env:t,timeout:1e4,stdio:"ignore"})}catch{}const s=["mcp","add",e.name,"--command",e.command];for(const a of e.args)s.push("--arg",a);I(n,s,{env:t,timeout:1e4,stdio:"ignore"}),o.info("codewhale-adapter",`Registered MCP server: ${e.name}`);const d=_(P(),".codewhale","skills"),r=L(d);r.length>0&&o.info("codewhale-adapter",`Synced connector skills to ${d}: [${r.join(", ")}]`)}catch(e){o.warn("codewhale-adapter",`Failed to register MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`)}}getSupportedCommands(){return[{name:"status",description:"Show session and working directory status"}]}async execCommand(e,t,i){return e==="status"?{status:"ok",message:`Session: ${this.deepSeekSessionId??"none"}, CWD: ${this.cwd}`,data:{sessionId:this.deepSeekSessionId,cwd:this.cwd,alive:this.alive}}:{status:"unsupported",message:`Unknown command: ${e}`}}async handleLocalAction(e){const t=e.action_type??"",i=e.params??{};switch(t){case"get_context":return this.callbacks.sendLocalActionResult(e.action_id,"ok",{sessionId:this.deepSeekSessionId,cwd:this.cwd,model:this.currentModel,model_id:this.currentModel,available_models:this.availableModelsMeta()}),{handled:!0,kind:"get_context"};case"set_model":{const n=String(i.model_id??"").trim();return n?(this.currentModel=n,this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"model_set",modelId:n,model_id:n,available_models:this.availableModelsMeta()}),o.info("codewhale-adapter",`Model set to: ${n}`),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","model_id is required"),{handled:!0,kind:"set_model"})}default:return{handled:!1,kind:""}}}availableModelsMeta(){return j(this.config.command||"codewhale").map(e=>({id:e.id,displayName:e.displayName}))}deliverInboundEvent(e){if(this.activeEventId){o.info("codewhale-adapter",`Event ${e.event_id}: rejected, busy with ${this.activeEventId}`),this.callbacks.sendEventResult(e.event_id,"failed","agent busy");return}const t=this.inboundMessageIds.inject(e.session_id,e.content,e.msg_id);this.startNewMessage(e,t)}deliverStopEvent(e,t){this.activeEventId===e&&(this.killActiveProcess(),this.callbacks.sendEventResult(e,"canceled","stopped by user"),this.clearActive())}startNewMessage(e,t){this.activeEventId=e.event_id,this.activeSessionId=e.session_id,this.chunkSeq=0,this.activeClientMsgId=`ds-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.beginAuditCapture(e),this.startComposing();const i={adapterSessionId:this.deepSeekSessionId??"",text:t,contextMessages:e.context_messages_json?JSON.parse(e.context_messages_json).map(s=>({senderId:s.sender_id??"unknown",content:s.content})):void 0},n=new y(this.deepSeekSessionId??"");this.runMessage(i,n,e.event_id,e.session_id).catch(s=>{o.error("codewhale-adapter",`Message failed: ${s}`),this.callbacks.sendEventResult(e.event_id,"failed",s instanceof Error?s.message:String(s)),this.clearActive()}),this.resetIdleTimer(e.event_id)}buildExecArgs(e){const t=[];if(this.grixConfigPath){t.push("--config",this.grixConfigPath);const n=this.provider?.baseUrl?.trim();n&&t.push("--base-url",n)}const i=[...this.config.args??[]];return t.push("exec"),i.includes("--output-format")||t.push("--output-format","stream-json"),t.push(...i),this.currentModel&&t.push("--model",this.currentModel),this.deepSeekSessionId&&t.push("--resume",this.deepSeekSessionId),t.push("--",e),t}async runMessage(e,t,i,n){let s=e.text;e.contextMessages&&e.contextMessages.length>0&&(s=`Conversation context:
|
|
2
2
|
${e.contextMessages.map(l=>`[${l.senderId??"unknown"}]: ${l.content}`).join(`
|
|
3
3
|
`)}
|
|
4
4
|
|
|
5
5
|
Latest user message:
|
|
6
|
-
${s}`),s=this.identity.injectOnce(n??e.adapterSessionId,s);const d=this.config.command||"codewhale",r=this.buildExecArgs(s),a={...process.env,...this.config.env},p=w(d,typeof a.PATH=="string"?a.PATH:void 0);o.info("codewhale-adapter",`Spawning: ${p} ${r.slice(0,5).join(" ")}...`);try{if(!(await A(this.cwd)).isDirectory())throw new Error(`Bound path is not a directory: ${this.cwd}`)}catch(c){throw String(c?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${this.cwd}. Please rebind with /grix open <valid-directory>.`):c}const h=C(p,r,{cwd:this.cwd,env:a}).process;return this.activeProcess=h,h.stderr?.on("data",c=>{const l=c.toString().trim();l&&o.info("codewhale-adapter",`[codewhale stderr] ${l}`)}),new Promise((c,l)=>{let m=!1,v="";const S=()=>{this.activeProcess=null};h.on("error",u=>{m||(m=!0,S(),l(u))}),h.on("exit",u=>{if(v.trim()&&this.handleOutputLine(v.trim(),i),v="",m){S();return}if(m=!0,S(),u!==0&&i&&this.activeEventId===i){l(new Error(`codewhale exec exited with code ${u}`));return}t.emitDone({status:"completed"}),c()}),M({input:h.stdout}).on("line",u=>{u.trim()&&this.handleOutputLine(u.trim(),i)}),h.stdin?.end()})}handleOutputLine(e,t){let i;try{i=JSON.parse(e)}catch{o.error("codewhale-adapter",`Invalid JSON: ${e.slice(0,200)}`);return}switch(t&&this.captureAuditEvent(t,e,i),i.type){case"content":{const s=i.content;s&&t&&this.activeEventId===t&&this.activeSessionId&&(this.chunkSeq++,this.callbacks.sendStreamChunk(t,this.activeSessionId,s,this.chunkSeq,!1,this.activeClientMsgId??void 0),this.startComposing(),this.resetIdleTimer(t));break}case"session_capture":{const s=i.content;s&&(this.deepSeekSessionId=s,this.persistSessionId(s),o.info("codewhale-adapter",`Session captured: ${s}`));break}case"metadata":{const s=i.meta;if(s){o.info("codewhale-adapter",`Metadata: model=${s.model}, tokens_in=${s.input_tokens}, tokens_out=${s.output_tokens}`);const d=Number(s.input_tokens??0),r=Number(s.output_tokens??0);if(d>0||r>0){const a=this.lastUsage;this.lastUsage={sampledAt:new Date().toISOString(),turns:(a?.turns??0)+1,total:{input:(a?.total.input??0)+d,output:(a?.total.output??0)+r}}}}break}case"tool_use":{const s=typeof i.name=="string"?i.name.trim():"",d=typeof i.id=="string"?i.id.trim():"",r=
|
|
6
|
+
${s}`),s=this.identity.injectOnce(n??e.adapterSessionId,s);const d=this.config.command||"codewhale",r=this.buildExecArgs(s),a={...process.env,...this.config.env},p=w(d,typeof a.PATH=="string"?a.PATH:void 0);o.info("codewhale-adapter",`Spawning: ${p} ${r.slice(0,5).join(" ")}...`);try{if(!(await A(this.cwd)).isDirectory())throw new Error(`Bound path is not a directory: ${this.cwd}`)}catch(c){throw String(c?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${this.cwd}. Please rebind with /grix open <valid-directory>.`):c}const h=C(p,r,{cwd:this.cwd,env:a}).process;return this.activeProcess=h,h.stderr?.on("data",c=>{const l=c.toString().trim();l&&o.info("codewhale-adapter",`[codewhale stderr] ${l}`)}),new Promise((c,l)=>{let m=!1,v="";const S=()=>{this.activeProcess=null};h.on("error",u=>{m||(m=!0,S(),l(u))}),h.on("exit",u=>{if(v.trim()&&this.handleOutputLine(v.trim(),i),v="",m){S();return}if(m=!0,S(),u!==0&&i&&this.activeEventId===i){l(new Error(`codewhale exec exited with code ${u}`));return}t.emitDone({status:"completed"}),c()}),M({input:h.stdout}).on("line",u=>{u.trim()&&this.handleOutputLine(u.trim(),i)}),h.stdin?.end()})}handleOutputLine(e,t){let i;try{i=JSON.parse(e)}catch{o.error("codewhale-adapter",`Invalid JSON: ${e.slice(0,200)}`);return}switch(t&&this.captureAuditEvent(t,e,i),i.type){case"content":{const s=i.content;s&&t&&this.activeEventId===t&&this.activeSessionId&&(this.chunkSeq++,this.callbacks.sendStreamChunk(t,this.activeSessionId,s,this.chunkSeq,!1,this.activeClientMsgId??void 0),this.startComposing(),this.resetIdleTimer(t));break}case"session_capture":{const s=i.content;s&&(this.deepSeekSessionId=s,this.persistSessionId(s),o.info("codewhale-adapter",`Session captured: ${s}`));break}case"metadata":{const s=i.meta;if(s){o.info("codewhale-adapter",`Metadata: model=${s.model}, tokens_in=${s.input_tokens}, tokens_out=${s.output_tokens}`);const d=Number(s.input_tokens??0),r=Number(s.output_tokens??0);if(d>0||r>0){const a=this.lastUsage;this.lastUsage={sampledAt:new Date().toISOString(),turns:(a?.turns??0)+1,total:{input:(a?.total.input??0)+d,output:(a?.total.output??0)+r}}}}break}case"tool_use":{const s=typeof i.name=="string"?i.name.trim():"",d=typeof i.id=="string"?i.id.trim():"",r=D(i.input);s&&t&&this.activeEventId===t&&this.activeSessionId&&(d&&this.toolNamesById.set(d,s),o.info("codewhale-adapter",`Tool use: ${s}`),this.callbacks.sendToolUse(t,this.activeSessionId,s,r),this.resetIdleTimer(t));break}case"tool_result":{const s=typeof i.id=="string"?i.id.trim():"",r=(typeof i.name=="string"?i.name.trim():"")||(s?this.toolNamesById.get(s):void 0)||"tool";s&&this.toolNamesById.delete(s);const a=typeof i.status=="string"?i.status.trim().toLowerCase():"",p=a==="failed"||a==="failure"||a==="error";t&&this.activeEventId===t&&this.activeSessionId&&(p&&this.callbacks.sendToolResult(t,this.activeSessionId,r,"(failed)"),this.resetIdleTimer(t));break}case"done":{this.handleMessageCompleted(t);break}default:break}}handleMessageCompleted(e){if(this.stopComposing(),e&&this.activeEventId===e){const t=this.activeSessionId??"",i=this.activeClientMsgId??void 0;t&&(this.chunkSeq++,this.callbacks.sendStreamChunk(e,t,"",this.chunkSeq,!0,i)),this.callbacks.sendEventResult(e,"responded"),this.clearActive()}}killActiveProcess(){const e=this.activeProcess;this.activeProcess=null,e?.pid&&(b(e,"SIGTERM"),setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{b(e,"SIGKILL")}catch{}},5e3).unref())}notifyBindingReady(){if(!this.aibotSessionId||!this.cwd)return;const e=this.availableModelsMeta(),t=this.currentModel??e[0]?.id??"";this.callbacks.sendUpdateBindingCard(this.aibotSessionId,"ready",this.cwd,{model_id:t,available_models:e})}persistSessionId(e){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setCodeWhaleThreadId(this.aibotSessionId,e)}startComposing(){}stopComposing(){}resetIdleTimer(e){this.lastProgressAt=Date.now(),this.armIdleTimer(e)}armIdleTimer(e){this.clearIdleTimer();const t=this.lastProgressAt+f-Date.now(),i=Math.max(0,Math.min(H,t));this.idleTimer=setTimeout(()=>{this.onIdleTimeout(e)},i)}async onIdleTimeout(e){if(this.activeEventId!==e)return;if(Date.now()-this.lastProgressAt>=f){this.failIdleRun(e,`liveness budget exhausted after ${f/6e4}min`);return}let i=!1;try{i=await this.ping(q)}catch{i=!1}if(this.activeEventId===e){if(i){o.info("codewhale-adapter",`Idle timer: process alive, extending until liveness cap (${f/6e4}min): ${e}`),this.armIdleTimer(e);return}this.failIdleRun(e,"process not alive")}}failIdleRun(e,t){this.activeEventId===e&&(o.error("codewhale-adapter",`Idle timeout (${t}): ${e}`),this.killActiveProcess(),this.callbacks.sendEventResult(e,"failed",`idle timeout: ${t}`),this.clearActive(),this.emit("stuck"))}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}clearActive(){const e=this.activeEventId;e&&this.snapshotAuditBoundary(e),this.stopComposing(),this.activeEventId=null,this.activeSessionId=null,this.chunkSeq=0,this.activeClientMsgId=null,this.toolNamesById.clear(),this.lastProgressAt=0,this.clearIdleTimer(),e&&this.emit("eventDone",e)}beginAuditCapture(e){!e.audit?.enabled||this.auditCaptures.has(e.event_id)||this.auditCaptures.set(e.event_id,{events:[]})}captureAuditEvent(e,t,i){const n=this.auditCaptures.get(e);n&&n.events.push({sequence:n.events.length,observedAt:new Date().toISOString(),rawLine:t,event:structuredClone(i)})}snapshotAuditBoundary(e){const t=this.auditCaptures.get(e);t&&(this.completedAuditBoundaries.set(e,{adapterType:"codewhale",providerSessionId:this.deepSeekSessionId??void 0,codeWhaleEvidence:{events:t.events}}),this.auditCaptures.delete(e))}}class y extends k{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){o.warn("codewhale-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}export{ue as CodeWhaleAdapter};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{execFileSync as J}from"node:child_process";import{createInterface as he}from"node:readline";import{EventEmitter as Y}from"node:events";import{stat as K}from"node:fs/promises";import{join as P,resolve as pe}from"node:path";import{fileURLToPath as fe}from"node:url";import{syncDefaultSkillsToDir as me}from"../../default-skills/index.js";import{resolveCommandPath as ge,spawnCommand as ve,killProcessGroup as Z,hasChildProcesses as Ie}from"../../core/runtime/spawn.js";import{InternalApiServer as xe}from"../../core/mcp/internal-api-server.js";import{
|
|
2
|
-
\u2026(truncated)`,ne=80,Je=120*1e3,Ye=F("GRIX_CODEX_DELTA_COALESCE_MS",1e3),Ke=F("GRIX_CODEX_DELTA_COALESCE_CHARS",4096),Ze=[{id:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",defaultReasoningEffort:null,supportedReasoningEfforts:[],defaultServiceTier:null,serviceTiers:[],isDefault:!0}],re=[{id:"default",displayName:"Default"},{id:"plan",displayName:"Plan"}],Qe=new Set(["rawResponse/completed","codex/rawResponse/completed","rawResponseItem/completed","codex/rawResponseItem/completed","thread/tokenUsage/updated","codex/thread/tokenUsage/updated","thread/compacted","codex/thread/compacted","turn/started","codex/turn/started","turn/completed","codex/turn/completed","item/started","codex/item/started","item/completed","codex/item/completed","error","codex/error"]);function oe(a,e){const t=String(a??"").trim()||"codex",i=ge(t,e);if(i!==t)return i;if(t!=="codex")return t;const s=process.platform==="win32"?[]:["/opt/homebrew/bin/codex","/usr/local/bin/codex","/usr/bin/codex"],n=process.platform!=="win32"?[]:[P(process.env.LOCALAPPDATA??"","npm","codex.cmd"),P(process.env.APPDATA??"","npm","codex.cmd"),P(process.env.LOCALAPPDATA??"","Programs","codex","codex.exe")],r=[...s,...n];for(const o of r)try{return require("node:fs").accessSync(o,require("node:fs").constants.X_OK),o}catch{continue}return d.warn("codex-adapter",`resolveCodexCommandPath: failed to resolve "${t}". envPath=${e?"provided":"missing (using process.env.PATH)"}. fallbacks tried: [${r.join(", ")}]`),t}class $ extends Y{type="codex";config;callbacks;process=null;alive=!1;stopped=!1;internalApi=null;bridgeStatus="starting";pendingRequests=new Map;requestId=0;threadId=null;initialized=!1;cwd;approvalPolicy;sandboxMode;model;collaborationMode;reasoningEffort;serviceTier;idleTimer=null;lastProgressAt=0;lastIdleCheckAt=0;activityGeneration=0;lastIdleCheckGeneration=0;idleNoProgressCount=0;inFlightToolOps=0;consecutivePingFailures=0;currentTurnStartedAt=0;preflightCheckComplete=!1;turnInactivityTimeoutMs=We("GRIX_CODEX_TURN_INACTIVITY_TIMEOUT_MS");pendingApprovals=new Map;needsHistoryInjection=!1;lastInjectedSessionId=null;identityInputInjectedThreadId=null;inboundMessageIds=new ye;legacyDeveloperInstructionsUnsupported=!1;profileIdentityRefreshPending=!1;bindingStore=null;aibotSessionId="";threadResumePending=!1;autoTrustProject="auto";codexHome;codexDirect=null;directEnv={};configOverrideArgs=[];rawCaptureOptions;rawCaptureRelay;rawCaptureConfigOverrides=[];rawCaptureUnavailableReason;codexModelOptions=[];codexModelOptionsCachedAt=0;static MODEL_CACHE_TTL_MS=3600*1e3;rateLimitSnapshot=null;lastNonDefaultLimitRefreshAt=0;static NON_DEFAULT_LIMIT_REFRESH_INTERVAL_MS=6e4;currentThreadTokenUsage=null;currentModelContextWindow=null;auditCaptureByEventId=new Map;constructor(e,t){super(),this.config=e,this.callbacks=t;const i=e.options??{};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 _e?i.bindingStore:null,this.model=i.model,this.collaborationMode=i.collaborationMode,this.reasoningEffort=i.reasoningEffort,this.serviceTier=i.serviceTier,this.bindingStore&&this.aibotSessionId&&(this.model=this.model??this.bindingStore.getCodexModelId(this.aibotSessionId),this.collaborationMode=this.collaborationMode??this.bindingStore.getCodexModeId(this.aibotSessionId),this.reasoningEffort=this.reasoningEffort??this.bindingStore.getCodexReasoningEffort(this.aibotSessionId),this.serviceTier=this.serviceTier??this.bindingStore.getCodexServiceTier(this.aibotSessionId),this.sandboxMode=this.sandboxMode??this.bindingStore.getCodexSandboxMode(this.aibotSessionId)),this.autoTrustProject=typeof i.autoTrustProject=="boolean"?i.autoTrustProject:"auto",this.codexHome=typeof i.codexHome=="string"&&i.codexHome.trim()?i.codexHome.trim():void 0;const s=i.codexDirect;if(this.codexDirect=s&&typeof s=="object"&&!Array.isArray(s)?s:null,this.configOverrideArgs=ee(i.codexConfigOverrides,"codexConfigOverrides"),this.rawCaptureOptions=Ve(i.rawApiCapture),this.cwd=this.resolveCwd(),this.bindingStore&&this.aibotSessionId){const n=this.bindingStore.getCodexThreadId(this.aibotSessionId);n&&(this.threadId=n,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.prepareDirectHome(),await this.ensureProjectTrusted(),await this.prepareRawApiCapture();try{await this.startInternalApiAndRegisterMcp(),await this.spawnCodex(),await this.initializeHandshake(),await this.notifyBindingReadyWithContext(),d.info("codex-adapter",`Ready (pid=${this.process?.pid})`)}catch(e){throw await this.stopRawApiCapture(),e}}async prepareRawApiCapture(){if(this.rawCaptureOptions)try{const e=await Oe(this.rawCaptureOptions,{adapterType:"codex",sessionId:this.rawCaptureOptions.sessionId,cwd:this.cwd,env:this.resolveChildEnv(),configOverrides:this.configOverrideArgs,codexHome:this.codexHome});this.rawCaptureRelay=e.relay,this.rawCaptureConfigOverrides=e.overlay.configOverrides??[],this.rawCaptureUnavailableReason=void 0,d.info("codex-adapter","Raw API audit capture relay is ready")}catch(e){this.rawCaptureRelay=void 0,this.rawCaptureConfigOverrides=[],this.rawCaptureUnavailableReason=e instanceof Error?e.message:String(e),d.warn("codex-adapter",`Raw API audit capture unavailable: ${this.rawCaptureUnavailableReason}`)}}async stopRawApiCapture(){const e=this.rawCaptureRelay;this.rawCaptureRelay=void 0,this.rawCaptureConfigOverrides=[],e&&await e.stop()}async prepareDirectHome(){if(!this.codexDirect)return;const e=await Ae(this.codexDirect);this.codexHome=e.codexHome,this.directEnv=e.env;const t=ee(e.configOverrides,"codexDirect.configOverrides");this.configOverrideArgs=[...this.configOverrideArgs,...t],d.info("codex-adapter",`Codex direct home ready: ${e.codexHome} (catalog=${e.catalogVersion??"none"}, token=${e.tokenDigest?`present sha256:${e.tokenDigest}`:"absent"})`)}resolveChildEnv(){const e={...process.env,...this.config.env};return this.codexHome&&(e.CODEX_HOME=this.codexHome),e}async ensureProjectTrusted(){if(this.shouldAutoTrustProject())try{const e=await Ce(this.cwd,{codexHome:this.codexHome});e.changed&&d.info("codex-adapter",`Trusted Codex project ${this.cwd} in ${e.configPath}`)}catch(e){const t=e instanceof Error?e.message:String(e);throw d.error("codex-adapter",`Failed to trust Codex project ${this.cwd}: ${t}`),e}}async startInternalApiAndRegisterMcp(){try{this.internalApi=new xe,this.internalApi.setInvokeHandler(async(o,c,p,h)=>this.callbacks.agentInvoke(o,c,h)),await this.internalApi.start(0),d.info("codex-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),t=this.resolveChildEnv(),i=typeof t.PATH=="string"?t.PATH:void 0,s=oe(this.config.command||"codex",i);try{J(s,["mcp","remove",e.name],{env:t,timeout:1e4,stdio:"ignore"})}catch{}J(s,["mcp","add",e.name,"--",e.command,...e.args],{env:t,timeout:1e4,stdio:"ignore"}),d.info("codex-adapter",`Registered MCP server: ${e.name}`);const n=P(Te(this.codexHome),"skills"),r=me(n);r.length>0&&d.info("codex-adapter",`Synced connector skills to ${n}: [${r.join(", ")}]`)}catch(e){d.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:be(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){d.warn("codex-adapter",`Failed to attach toolbar context to binding update: ${e instanceof Error?e.message:String(e)}`),this.notifyBindingReady()}}externalProviderCheckedAt=0;externalProviderCached=!1;static EXTERNAL_PROVIDER_CACHE_TTL_MS=60*1e3;isExternalProvider(){const e=Date.now();if(e-this.externalProviderCheckedAt<$.EXTERNAL_PROVIDER_CACHE_TTL_MS)return this.externalProviderCached;const t=N(this.codexHome);return this.externalProviderCached=!!(t.baseUrl&&de(t.baseUrl)),this.externalProviderCheckedAt=e,this.externalProviderCached}effectiveServiceTier(){if(!this.serviceTier||this.serviceTier.trim().toLowerCase()==="default"||this.isExternalProvider())return;const e=this.getModelOption(this.currentModelId());if(!(e&&!e.serviceTiers.some(t=>t.id===this.serviceTier)))return this.serviceTier}getEffortMeta(){if(this.isExternalProvider())return{};const e=this.currentModelId(),t=this.getModelOption(e),i={},s=t?.supportedReasoningEfforts??[];s.length>0&&(i.available_efforts=s,i.reasoning_effort=this.reasoningEffort??t?.defaultReasoningEffort??null);const n=t?.serviceTiers??[];return n.length>0&&(i.available_service_tiers=n,i.service_tier=this.effectiveServiceTier()??t?.defaultServiceTier??null),i}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.sendEventResultAfterFlushing(t.event_id,"failed","adapter stopped");for(const t of this.steerDeferred.splice(0))this.sendEventResultAfterFlushing(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")Z(e,"SIGTERM"),await Promise.race([new Promise(i=>{e.once("exit",()=>i(!0))}),new Promise(i=>{setTimeout(()=>i(!1),5e3)})])||Z(e,"SIGKILL");else if(e)try{e.kill("SIGTERM")}catch{}await this.stopRawApiCapture()}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),this.inboundMessageIds.reset()}sendPrompt(e){const t=new B(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)}
|
|
3
|
-
`)})}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.clearCodexDeltaBuffer(),this.activeEventId=null}setModel(e){this.model=e,this.persistCodexContext(),d.info("codex-adapter",`Model set to: ${e}`)}setMode(e){const t=M(e);if(!t){d.info("codex-adapter",`Ignoring unsupported mode: ${e}`);return}this.collaborationMode=t,this.persistCodexContext(),d.info("codex-adapter",`Mode set to: ${t}`)}setReasoningEffort(e){this.reasoningEffort=e,this.persistCodexContext(),d.info("codex-adapter",`Reasoning effort set to: ${e}`)}setServiceTier(e){const t=e.trim();this.serviceTier=t.toLowerCase()==="default"?"default":t,this.persistCodexContext(),d.info("codex-adapter",`Service tier set to: ${this.serviceTier}`)}setSandboxMode(e){this.sandboxMode=e,this.persistCodexContext(),d.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}hasRawApiCaptureRelay(){return!!this.rawCaptureRelay}enableAuditCapture(e,t={}){const i=e.trim();if(!i||this.auditCaptureByEventId.has(i))return;const s=t.rawProviderBody??!!this.rawCaptureOptions;this.auditCaptureByEventId.set(i,{threadId:this.threadId??void 0,modelId:this.currentModelId()??void 0,rawProviderBody:s,sequence:0,events:[]}),s&&this.rawCaptureRelay?.beginEvent(i,t.auditId)}takeAuditBoundary(e){const t=this.auditCaptureByEventId.get(e);if(t)return this.auditCaptureByEventId.delete(e),{adapterType:this.type,providerTurnId:t.providerTurnId,threadId:t.threadId??this.threadId??void 0,codexEvidence:{events:t.events,...t.modelId?{modelId:t.modelId}:{},...t.rawProviderBody?{rawApiCapture:this.rawCaptureRelay?this.rawCaptureRelay.takeEvent(e):
|
|
4
|
-
`):"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(d.info("codex-adapter",`handleLocalAction action_type=${t} action_id=${e.action_id} session_id=${i.session_id??""}`),t){case"set_model":{const s=I(u(i.model_id),u(i.modelId),u(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=I(u(i.reasoning_effort),u(i.reasoning_eff),u(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_service_tier":{const s=I(u(i.service_tier),u(i.serviceTier),u(i.value));return s&&this.setServiceTier(s),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("service_tier_set",!1)),{handled:!0,kind:"set_service_tier"}}case"set_sandbox_mode":{const s=I(u(i.sandbox_mode),u(i.sandboxMode),u(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":{d.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.sendEventResultAfterFlushing(this.activeEventId,"canceled","compacting"),this.clearActive());try{if(await this.ensureThreadResumed(),this.needsHistoryInjection)return d.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,d.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)?(d.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.")):(d.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",r=et[n]??"accept";return this.sendApprovalDecision(s.requestId,r),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.sendEventResultAfterFlushing(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(),r=Date.now(),o=this.currentThreadTokenUsage;return s?d.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}`):d.info("codex-adapter","[rate-limits] responding: no rateLimitSnapshot available"),d.debug("codex-adapter",`[cp-diagnose] get_rate_limits: threadId=${this.threadId??"-"} contextWindow=${JSON.stringify(n)} tokenUsage=${JSON.stringify(o)}`),this.callbacks.sendLocalActionResult(e.action_id,"ok",{adapterType:"codex",available:s!==null,cached:!1,sampledAt:r,rateLimits:s,contextWindow:n,tokenUsage:o}),{handled:!0,kind:"get_rate_limits"}}default:return{handled:!1,kind:""}}}async buildToolbarContextResult(e,t=!0){t&&await this.refreshCodexModelOptions();const i=M(this.collaborationMode)??"default",s=this.currentModelId(),n=this.getModelOption(s),r=this.getModelOptions(),o=re,c=this.reasoningEffort??n?.defaultReasoningEffort??null,p=n?.supportedReasoningEfforts??[],h=this.effectiveServiceTier()??n?.defaultServiceTier??null,m=n?.serviceTiers??[],v=this.isExternalProvider(),x=v?[]:p,y=v?null:c,E=v?[]:m,S=v?null:h,C={outcome:e,session_context:{modelId:s,modeId:i,reasoningEffort:y,serviceTier:S,approvalPolicy:this.approvalPolicy,sandboxMode:this.sandboxMode??null},model_id:s,mode_id:i,currentModelId:s,currentModeId:i,available_models:r,available_modes:o,available_efforts:x,availableModels:r,availableModes:o,reasoning_effort:y,available_service_tiers:E,service_tier:S,sandbox_mode:this.sandboxMode??null,models:r.map(w=>({modelId:w.id,name:w.displayName})),modes:o.map(w=>({id:w.id,name:w.displayName}))};return this.rateLimitSnapshot&&(C.rate_limit_primary_percent=this.rateLimitSnapshot.primary.usedPercent,C.rate_limit_secondary_percent=this.rateLimitSnapshot.secondary.usedPercent,C.rate_limit_primary_window_min=this.rateLimitSnapshot.primary.windowMinutes,C.rate_limit_secondary_window_min=this.rateLimitSnapshot.secondary.windowMinutes),C}currentModelId(){const e=String(this.model??"").trim();if(e)return e;const t=this.getModelOptions();return t.find(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=ot(t),s=this.codexModelOptions,n=[],r=String(this.model??"").trim(),o=r&&!s.some(m=>m.id.trim().toLowerCase()===r.toLowerCase()),c=s.length>0?s:o?[]:Ze;if(r){const m=[...s,...i].find(v=>v.id.trim().toLowerCase()===r.toLowerCase());n.push({id:r,displayName:m?.displayName??k(r),defaultReasoningEffort:m?.defaultReasoningEffort??null,supportedReasoningEfforts:m?.supportedReasoningEfforts??[],defaultServiceTier:m?.defaultServiceTier??null,serviceTiers:m?.serviceTiers??[],isDefault:m?.isDefault??!1})}n.push(...i),n.push(...c);const p=[],h=new Set;for(const m of n){const v=m.id.trim(),x=v.toLowerCase();!v||h.has(x)||(h.add(x),p.push({id:v,displayName:m.displayName.trim()||v,defaultReasoningEffort:m.defaultReasoningEffort,supportedReasoningEfforts:[...m.supportedReasoningEfforts],defaultServiceTier:m.defaultServiceTier,serviceTiers:[...m.serviceTiers],isDefault:m.isDefault}))}return p}async refreshCodexModelOptions(){if(!this.initialized||!this.alive||!this.process?.stdin||Date.now()-this.codexModelOptionsCachedAt<$.MODEL_CACHE_TTL_MS)return;const e=N(this.codexHome);if(e.baseUrl&&de(e.baseUrl)){try{const t=await at(e.baseUrl,e.apiKey);if(t.length>0){this.codexModelOptions=ce(t),this.codexModelOptionsCachedAt=Date.now(),d.info("codex-adapter",`Loaded ${t.length} models from external provider ${e.baseUrl}`);return}}catch(t){d.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=ct(s);t.push(...n.models),i=n.nextCursor}while(i);t.length>0&&(this.codexModelOptions=ce(t),this.codexModelOptionsCachedAt=Date.now())}catch(t){d.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;deliveredAgentMessageIds=new Set;codexSequence=0;pendingCodexDeltaFlush=null;turnError=null;turnErrorIsRetryableOnly=!0;turnHasVisibleOutput=!1;turnSawVisibleFinalAnswer=!1;turnHasDeliveredFinalAnswer=!1;deliverInboundEvent(e){if(this.compacting){d.info("codex-adapter",`Event ${e.event_id} deferred: compaction in progress`),this.compactionDeferred.push(e);return}const t=this.inboundMessageIds.prepare(e.session_id,e.content,e.msg_id),i=t.text,s=()=>{t.instructionPending&&this.inboundMessageIds.commitInstruction(e.session_id)},n=()=>{const r=this.inboundMessageIds.prepare(e.session_id,e.content,e.msg_id);r.instructionPending&&this.inboundMessageIds.commitInstruction(e.session_id),this.startNewTurn(e,r.text)};if(this.currentTurnId&&i.trim()){d.info("codex-adapter",`Event ${e.event_id}: steering active turn ${this.currentTurnId}`),this.steerTurn(i).then(()=>{s()}).catch(r=>{const o=r instanceof Error?r.message:String(r);if(d.info("codex-adapter",`Steer failed, falling through: ${o}`),!this.currentTurnId){n();return}if(ht(o)){d.info("codex-adapter","Unsteerable turn detected, clearing active state and starting new turn"),this.clearActive(),n();return}d.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){d.info("codex-adapter",`Event ${e.event_id} rejected: busy and empty content`),this.sendEventResultAfterFlushing(e.event_id,"failed","agent busy");return}s(),this.startNewTurn(e,i)}startNewTurn(e,t){this.activeEventId=e.event_id,this.activeSessionId=e.session_id,e.audit?.enabled===!0&&this.enableAuditCapture(e.event_id,{auditId:e.audit.auditId,rawProviderBody:e.audit.rawProviderBody}),this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.agentMessagePhases.clear(),this.deliveredAgentMessageIds.clear(),this.turnSawVisibleFinalAnswer=!1,this.turnHasDeliveredFinalAnswer=!1,this.codexSequence=0,this.startComposing();const i=this.threadId??"",s=new B(i),n={adapterSessionId:i,text:t,contextMessages:e.context_messages_json?JSON.parse(e.context_messages_json).map(r=>({senderId:r.sender_id??"unknown",content:r.content})):void 0};this.runTurn(n,s,e.event_id,e.session_id).catch(r=>{d.error("codex-adapter",`Turn failed: ${r}`),this.sendEventResultAfterFlushing(e.event_id,"failed",r instanceof Error?r.message:String(r)),this.clearActive()}),this.resetIdleTimer(e.event_id)}deliverStopEvent(e,t){this.activeEventId===e&&(this.cancel(this.threadId??"").catch(()=>{}),this.sendEventResultAfterFlushing(e,"canceled","stopped by user"),this.clearActive())}async spawnCodex(){const e={...this.resolveChildEnv(),...this.directEnv},t=typeof e.PATH=="string"?e.PATH:void 0;t||d.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=oe(this.config.command||"codex",t),s=it(this.config.args);for(const o of this.configOverrideArgs)s.push("-c",o);for(const o of this.resolveRelayTransportConfigOverrides())s.push("-c",o);for(const o of this.rawCaptureConfigOverrides)s.push("-c",o);this.sandboxMode&&s.push("-c",`sandbox_mode="${this.sandboxMode}"`);const n=s.map(o=>this.rawCaptureConfigOverrides.includes(o)?"<raw-api-capture-overlay>":o);d.info("codex-adapter",`Spawning: ${i} ${n.join(" ")}`);try{if(!(await K(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 r=Q({codexHome:this.codexHome});if(r.locked&&!r.stale)throw new Error(`Codex session appears locked by another process: ${r.path}`);r.stale&&d.warn("codex-adapter",`Ignoring stale Codex lock: ${r.path}`);try{this.process=ve(i,s,{env:e,cwd:this.cwd}).process}catch(o){throw d.error("codex-adapter",`Codex spawn threw: ${o}`),this.process=null,this.alive=!1,this.bridgeStatus="closed",o}this.process.on("error",o=>{d.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.flushCodexDeltaBuffer(),this.sendEventResultAfterFlushing(this.activeEventId,"failed","Codex process spawn failed"),this.activeEventId=null):this.clearCodexDeltaBuffer(),this.emit("exit",1)}),this.process.on("exit",o=>{d.info("codex-adapter",`Codex process exited (code=${o})`),this.alive=!1,this.bridgeStatus="closed",this.clearIdleTimer(),this.rejectAllPending("process exited"),this.stopComposing(),this.activeEventId?this.flushCodexDeltaBuffer():this.clearCodexDeltaBuffer(),this.emit("exit",o)}),this.process.stderr?.on("data",o=>{const c=o.toString().trim();c&&d.info("codex-adapter",`[codex stderr] ${c}`)}),this.bindStdout(),this.alive=!0}resolveRelayTransportConfigOverrides(){if(this.config.env?.[qe]!=="1")return[];const e=Le(this.codexHome,this.configOverrideArgs);if(e==="openai"){const i=Ne(this.codexHome,this.configOverrideArgs);return De($e,"Grix OpenAI Relay",i.targetBaseUrl)}const t=Fe(e);return t?[`${t}=false`]:[]}bindStdout(){if(!this.process?.stdout)return;this.process.stdout.setEncoding("utf8"),he({input:this.process.stdout}).on("line",t=>{if(!t.trim())return;let i;try{i=JSON.parse(t)}catch{d.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??{};if(this.shouldIgnoreOutOfScopeNotification(e,t,i)){this.activeEventId&&this.resetIdleTimer(this.activeEventId);return}switch(this.captureAuditNotification(t,i),this.captureContextWindowFromPayload(t,i),this.activeEventId&&t&&t.startsWith("item/")&&!t.endsWith("/requestApproval")&&this.startComposing(),t){case"item/started":{const n=i.item,r=n?.id,o=n?.type,c=this.normalizeAgentMessagePhase(n?.phase);this.isLongRunningToolItemType(o)&&(this.inFlightToolOps+=1),o==="agentMessage"&&r&&(c?this.agentMessagePhases.set(r,c):this.agentMessagePhases.delete(r),D(c)?(this.visibleAgentMessageIds.add(r),this.hiddenAgentMessageIds.delete(r)):(this.hiddenAgentMessageIds.add(r),this.visibleAgentMessageIds.delete(r)),c==="final_answer"&&D(c)&&(this.turnSawVisibleFinalAnswer=!0));break}case"item/agentMessage/delta":{const n=i.delta,r=i.itemId,o=this.resolveAgentMessagePhase(r,i.phase),c=(!r||!this.hiddenAgentMessageIds.has(r))&&D(o);o==="final_answer"&&c&&(this.turnSawVisibleFinalAnswer=!0),n&&this.activeEventId&&c&&!this.shouldSuppressAgentMessageDeltaDuringToolRun(r,o)&&(this.recordDeliveredAgentMessage(r,o),this.queueCodexDeltaEvent(e));break}case"item/completed":{const n=i.item,r=n?.id,o=n?.type;if(this.isLongRunningToolItemType(o)&&(this.inFlightToolOps=Math.max(0,this.inFlightToolOps-1)),this.activeEventId&&o==="commandExecution"&&(this.turnHasVisibleOutput=!0,this.emitCodexEvent("item/completed",e)),o==="agentMessage"){const c=this.resolveAgentMessagePhase(r,n?.phase),p=(!r||!this.hiddenAgentMessageIds.has(r))&&D(c);if(c==="final_answer"&&p){this.turnSawVisibleFinalAnswer=!0;const h=this.extractAgentMessageText(n),m=r?this.deliveredAgentMessageIds.has(r):!1;this.activeEventId&&h&&!m&&(d.warn("codex-adapter",`Recovering final_answer from item/completed item_id=${r??"unknown"}`),this.recordDeliveredAgentMessage(r,c),this.queueCodexDeltaEvent({method:"item/agentMessage/delta",params:{...r?{itemId:r}:{},delta:h,phase:c}}))}r&&(this.visibleAgentMessageIds.delete(r),this.hiddenAgentMessageIds.delete(r),this.agentMessagePhases.delete(r))}break}case"turn/started":{const r=i.turn?.id;r&&(this.currentTurnId=r,this.turnError=null,this.turnErrorIsRetryableOnly=!0,this.turnHasVisibleOutput=!1,this.turnSawVisibleFinalAnswer=!1,this.turnHasDeliveredFinalAnswer=!1,this.deliveredAgentMessageIds.clear(),this.currentTurnStartedAt=Date.now(),this.preflightCheckComplete=!1,d.info("codex-adapter",`Turn started: ${r}`),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.handleApprovalRequest(e,"permission");break}case"turn/completed":{this.handleTurnCompleted(i);break}case"error":{const n=i.message??JSON.stringify(i);d.error("codex-adapter",`Codex error: ${n}`);const r=i.willRetry===!0;n&&(this.turnError=n,r||(this.turnErrorIsRetryableOnly=!1)),this.activeEventId&&!r&&(this.flushCodexDeltaBuffer(),this.callbacks.sendRunError(this.activeEventId,this.activeSessionId??"",n));break}case"account/rateLimits/updated":{const n=this.extractRateLimitPushLimitId(i),r=this.parseRateLimitSnapshot(i,this.rateLimitSnapshot);r&&(this.rateLimitSnapshot=r,d.info("codex-adapter",`Rate limits updated: primary=${r.primary.usedPercent.toFixed(1)}% secondary=${r.secondary.usedPercent.toFixed(1)}% extras=${r.extras?.length??0}`),this.callbacks.onRateLimitsUpdated?.(r)),n&&n!=="codex"&&this.refreshMainRateLimitsThrottled();break}case"thread/tokenUsage/updated":{const n=i.threadId,r=i.tokenUsage,o=r?.last;(!n||!r||!o)&&d.info("codex-adapter",`[cp-diagnose] token_usage payload_incomplete: method=thread/tokenUsage/updated hasThreadId=${String(!!n)} hasTokenUsage=${String(!!r)} hasLast=${String(!!o)} params=${JSON.stringify(i)}`),n&&r&&o&&(this.currentThreadTokenUsage={inputTokens:o.inputTokens??0,outputTokens:o.outputTokens??0,cacheReadInputTokens:o.cachedInputTokens??0,cacheCreationInputTokens:0},d.info("codex-adapter",`[cp-diagnose] token_usage raw thread=${n}: ${JSON.stringify(r)}`),d.info("codex-adapter",`[cp-diagnose] token_usage parsed thread=${n}: ${JSON.stringify(this.currentThreadTokenUsage)}`),this.callbacks.onTokenUsageUpdated?.(this.currentThreadTokenUsage),this.publishContextWindowSnapshot());break}default:break}const s=t?.endsWith("/requestApproval")===!0;t&&t!=="turn/started"&&(t.startsWith("item/")||t==="error"||t==="turn/completed")&&(this.preflightCheckComplete=!0),this.activeEventId&&(!s||this.pendingApprovals.size===0)&&this.resetIdleTimer(this.activeEventId)}shouldIgnoreOutOfScopeNotification(e,t,i){if(!t||e.id!=null)return!1;const s=I(u(i.threadId),u(i.threadID));if(s&&this.threadId&&s!==this.threadId)return this.logIgnoredNotificationScope(t,s,this.readNotificationTurnId(i)),!0;const n=this.readNotificationTurnId(i);return n&&this.currentTurnId&&n!==this.currentTurnId?(this.logIgnoredNotificationScope(t,s,n),!0):!1}readNotificationTurnId(e){const t=e.turn&&typeof e.turn=="object"?e.turn:void 0;return I(u(e.turnId),u(e.turnID),u(t?.id))}logIgnoredNotificationScope(e,t,i){e!=="error"&&!e.startsWith("turn/")||d.info("codex-adapter",`[scope] ignored ${e} thread=${t??"<none>"} turn=${i??"<none>"} active_thread=${this.threadId??"<none>"} active_turn=${this.currentTurnId??"<none>"}`)}captureAuditNotification(e,t){const i=this.activeEventId;if(!e||!i)return;const s=this.auditCaptureByEventId.get(i);if(!s)return;const n=t.turn,r=typeof t.turnId=="string"&&t.turnId?t.turnId:typeof t.turn_id=="string"&&t.turn_id?t.turn_id:typeof n?.id=="string"&&n.id?n.id:this.currentTurnId;r&&(s.providerTurnId=r);const o=typeof t.threadId=="string"&&t.threadId?t.threadId:typeof t.thread_id=="string"&&t.thread_id?t.thread_id:this.threadId;if(o&&(s.threadId=o),!!Qe.has(e))try{const c=JSON.parse(JSON.stringify(t));s.events.push({sequence:++s.sequence,method:e,params:c,observedAt:new Date().toISOString()})}catch(c){const p=c instanceof Error?c.message:String(c);d.warn("codex-adapter",`Audit evidence capture skipped event=${i} method=${e}: ${p}`)}}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&&d.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,d.info("codex-adapter",`[cp-diagnose] context_window updated: method=${e??"-"} size=${s}`),this.publishContextWindowSnapshot())}probeContextWindowFields(e,t){const i=[],s=[],n=r=>{if(!r||typeof r!="object")return;if(Array.isArray(r)){for(const c of r)n(c);return}const o=r;for(const c of t)Object.prototype.hasOwnProperty.call(o,c)&&(i.push(c),s.push(String(o[c])));for(const c of Object.values(o))n(c)};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 r=Number(n);if(Number.isFinite(r))return r}}for(const s of Object.values(i)){if(Array.isArray(s)){for(const r of s){const o=this.findNumericField(r,t);if(o!=null)return o}continue}const n=this.findNumericField(s,t);if(n!=null)return n}return null}buildContextWindowSnapshot(){const e=this.currentModelContextWindow;if(!e||e<=0)return d.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),r=i==null?null:Math.max(0,100-(n??0));return d.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:r,source:"codex:model_context_window"}}publishContextWindowSnapshot(){const e=this.buildContextWindowSnapshot();this.callbacks.onContextWindowUpdated?.(e),this.maybeScheduleAutoCompact(e)}maybeScheduleAutoCompact(e){const t=e?.usedPercentage;typeof t!="number"||t<ne||this.pendingAutoCompact||this.compacting||(this.pendingAutoCompact=!0,d.info("codex-adapter",`[auto-compact] context_window usedPercentage=${t.toFixed(1)}% >= ${ne}%, 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=>{d.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=>{d.warn("codex-adapter",`[auto-compact] compact error: ${e instanceof Error?e.message:e}`)})))}parseRateLimitSnapshot(e,t=null){try{const i=e.rateLimitsByLimitId,s=this.extractRateLimitPushLimitId(e),n=!i?.codex&&!!s&&s!=="codex",r=i?.codex??(n?{}:e.rateLimits??e),o=r.primary,c=r.secondary,p=r.credits,h=l=>{if(typeof l=="number"&&Number.isFinite(l))return l;if(typeof l=="string"){const f=Number(l);if(Number.isFinite(f))return f}return 0},m=l=>typeof l=="boolean"?l:typeof l=="string"?l.toLowerCase()==="true":!1,v=l=>{if(l==null)return null;if(typeof l=="string"){const f=l.trim();if(!f)return null;const g=Number(f);return Number.isFinite(g)&&g>1e9?new Date(g*1e3).toISOString():f}if(typeof l=="number"&&Number.isFinite(l)&&l>0){const f=l>1e12?l/1e3:l;return new Date(f*1e3).toISOString()}return null},x=l=>{const f=l.resets_in_seconds??l.resetsInSeconds,g=typeof f=="number"||typeof f=="string"?Number(f):NaN;return!Number.isFinite(g)||g<=0?null:new Date(Date.now()+g*1e3).toISOString()},y=l=>({usedPercent:h(l.used_percent??l.usedPercent),windowMinutes:h(l.window_minutes??l.windowDurationMins??l.windowMinutes),resetsAt:v(l.resets_at??l.resetsAt)??x(l)}),E=()=>({usedPercent:0,windowMinutes:0,resetsAt:null}),S=(l,f)=>l??f??E(),C=()=>{const l=[];if(o&&l.push(o),c&&l.push(c),Array.isArray(r.windows))for(const f of r.windows)f&&typeof f=="object"&&l.push(f);return l.map(y).filter(f=>f.windowMinutes>0)},w=(l,f,g)=>{const b=l.filter(T=>g(T.windowMinutes));return b.length===0?null:b.reduce((T,A)=>Math.abs(A.windowMinutes-f)<Math.abs(T.windowMinutes-f)?A:T)},O=C(),L=n?t?{primary:t.primary,secondary:t.secondary}:null:O.length>0?{primary:S(w(O,300,l=>l<1440),t?.primary),secondary:S(w(O,10080,l=>l>=1440),t?.secondary)}:o||c?{primary:o?y(o):t?.primary??E(),secondary:c?y(c):t?.secondary??E()}:null;if(!L)return null;const z=(l,f)=>{if(!f||typeof f!="object"||Array.isArray(f))return null;const g=f,b=g.limitName??g.limit_name,T=typeof b=="string"&&b.trim()?b.trim():l,A=[],W=g.primary,V=g.secondary;W&&A.push(W),V&&A.push(V);const G=A.map(y).filter(R=>R.windowMinutes>0),X=w(G,10080,R=>R>=1440)??w(G,300,R=>R<1440);return X?{id:l,label:T,...X}:null};let _;if(i&&typeof i=="object"){_=[];for(const[l,f]of Object.entries(i)){if(l==="codex")continue;const g=z(l,f);g&&_.push(g)}}else if(_=t?.extras?[...t.extras]:[],n&&s){const l=z(s,e.rateLimits??e);if(l){const f=_.findIndex(g=>g.id===l.id);f>=0?_[f]=l:_.push(l)}}return{primary:L.primary,secondary:L.secondary,credits:p?{hasCredits:m(p.has_credits??p.hasCredits),unlimited:m(p.unlimited),balance:p.balance==null?null:h(p.balance)}:t?.credits??{hasCredits:!1,unlimited:!1,balance:null},..._.length>0?{extras:_}:{}}}catch{return null}}handleApprovalRequest(e,t){const i=e.id;if(i==null)return;const s=e.method,n=`${i}`.trim(),r=`codex_${le(this.activeSessionId??"")}_${le(n)}`;if(this.approvalPolicy==="never"){this.sendApprovalDecision(i,"accept");return}this.activeEventId&&this.emitCodexEvent(s,e),this.pendingApprovals.set(r,{approvalId:r,approvalCommandId:n,sourceEventId:this.activeEventId??"",requestId:i,kind:t}),d.info("codex-adapter",`Pending approval stored: ${r} (kind=${t})`),this.clearIdleTimer(),this.stopComposing()}resolvePendingApproval(e){const t=e.params??{},i=I(t.approval_id,t.approvalId);if(i)return this.pendingApprovals.get(i)??null;const s=I(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)}
|
|
5
|
-
`)}armCompactionFallback(){this.compacting&&(this.compactingTimer&&clearTimeout(this.compactingTimer),this.compactingTimer=setTimeout(()=>{d.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")},
|
|
1
|
+
import{execFileSync as J}from"node:child_process";import{createInterface as he}from"node:readline";import{EventEmitter as Y}from"node:events";import{stat as K}from"node:fs/promises";import{join as P,resolve as pe}from"node:path";import{fileURLToPath as fe}from"node:url";import{syncDefaultSkillsToDir as me}from"../../default-skills/index.js";import{resolveCommandPath as ge,spawnCommand as ve,killProcessGroup as Z,hasChildProcesses as Ie}from"../../core/runtime/spawn.js";import{InternalApiServer as xe}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as ye,LEGACY_MCP_SERVER_NAMES as we}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as _e}from"../shared/inbound-message-id-injector.js";import{log as d}from"../../core/log/index.js";import{resolveClientVersion as Ce}from"../../core/util/client-version.js";import{isUserVisibleAgentMessagePhase as D}from"../../core/util/codex-output-policy.js";import{SessionBindingStore as be}from"../../core/persistence/session-binding-store.js";import{ensureCodexProjectTrusted as Te,isCodexCommand as Ae,readCodexProviderSettings as N,resolveCodexHome as Ee}from"./codex-trust.js";import{prepareCodexDirectHome as Se}from"./direct-home.js";import{checkCodexSessionActivity as Re,inspectCodexTurnProgress as Me}from"./session-activity.js";import{findRolloutFile as ke}from"./rollout-locator.js";import{checkCodexLock as Q}from"./lock-monitor.js";import{resolveCliPath as Pe,getCliVersion as De}from"../../core/util/cli-probe.js";import{scanSkills as $e}from"../claude/skill-scanner.js";import{normalizeCodexConfigOverrides as ee}from"./config-overrides.js";import{buildCodexOpenAiCompatibleProviderOverrides as Oe,CODEX_RELAY_OPENAI_PROVIDER_ID as Le,prepareCodexRawCapture as Ne,resolveCodexProviderName as Fe,resolveCodexRawCaptureTarget as je,resolveCodexProviderSupportsWebsocketsConfigKey as He}from"./raw-capture-hook.js";import{unavailableRawApiCaptureBoundary as Ue}from"../../audit/raw-capture/capture-relay.js";const qe=60*1e3,Be=600*1e3,ze="GRIX_RELAY_PROXY",We=5*1e3,Ve=15*1e3,te=3;function F(a,e){const t=Number(process.env[a]);return Number.isFinite(t)&&t>0?t:e}function Ge(a){const e=Number(process.env[a]);return Number.isFinite(e)&&e>0?e:null}function Xe(a){if(!a||typeof a!="object"||Array.isArray(a))return;const e=a,t=typeof e.auditId=="string"?e.auditId.trim():"",i=typeof e.sessionId=="string"?e.sessionId.trim():"",s=typeof e.spoolRootDir=="string"?e.spoolRootDir.trim():"";return t&&i&&s?{auditId:t,sessionId:i,spoolRootDir:s}:void 0}const j=F("GRIX_CODEX_PREFLIGHT_STALL_TIMEOUT_MS",120*1e3),Je=20,Ye=8e3,ie=2*1024,se=`
|
|
2
|
+
\u2026(truncated)`,ne=80,Ke=120*1e3,Ze=F("GRIX_CODEX_DELTA_COALESCE_MS",1e3),Qe=F("GRIX_CODEX_DELTA_COALESCE_CHARS",4096),et=[{id:"gpt-5.3-codex",displayName:"GPT-5.3 Codex",defaultReasoningEffort:null,supportedReasoningEfforts:[],defaultServiceTier:null,serviceTiers:[],isDefault:!0}],re=[{id:"default",displayName:"Default"},{id:"plan",displayName:"Plan"}],tt=new Set(["rawResponse/completed","codex/rawResponse/completed","rawResponseItem/completed","codex/rawResponseItem/completed","thread/tokenUsage/updated","codex/thread/tokenUsage/updated","thread/compacted","codex/thread/compacted","turn/started","codex/turn/started","turn/completed","codex/turn/completed","item/started","codex/item/started","item/completed","codex/item/completed","error","codex/error"]);function oe(a,e){const t=String(a??"").trim()||"codex",i=ge(t,e);if(i!==t)return i;if(t!=="codex")return t;const s=process.platform==="win32"?[]:["/opt/homebrew/bin/codex","/usr/local/bin/codex","/usr/bin/codex"],n=process.platform!=="win32"?[]:[P(process.env.LOCALAPPDATA??"","npm","codex.cmd"),P(process.env.APPDATA??"","npm","codex.cmd"),P(process.env.LOCALAPPDATA??"","Programs","codex","codex.exe")],r=[...s,...n];for(const o of r)try{return require("node:fs").accessSync(o,require("node:fs").constants.X_OK),o}catch{continue}return d.warn("codex-adapter",`resolveCodexCommandPath: failed to resolve "${t}". envPath=${e?"provided":"missing (using process.env.PATH)"}. fallbacks tried: [${r.join(", ")}]`),t}class $ extends Y{type="codex";config;callbacks;process=null;alive=!1;stopped=!1;internalApi=null;bridgeStatus="starting";pendingRequests=new Map;requestId=0;threadId=null;initialized=!1;cwd;approvalPolicy;sandboxMode;model;collaborationMode;reasoningEffort;serviceTier;idleTimer=null;lastProgressAt=0;lastIdleCheckAt=0;activityGeneration=0;lastIdleCheckGeneration=0;idleNoProgressCount=0;inFlightToolOps=0;consecutivePingFailures=0;currentTurnStartedAt=0;preflightCheckComplete=!1;turnInactivityTimeoutMs=Ge("GRIX_CODEX_TURN_INACTIVITY_TIMEOUT_MS");pendingApprovals=new Map;needsHistoryInjection=!1;lastInjectedSessionId=null;identityInputInjectedThreadId=null;inboundMessageIds=new _e;legacyDeveloperInstructionsUnsupported=!1;profileIdentityRefreshPending=!1;bindingStore=null;aibotSessionId="";threadResumePending=!1;autoTrustProject="auto";codexHome;codexDirect=null;directEnv={};configOverrideArgs=[];rawCaptureOptions;rawCaptureRelay;rawCaptureConfigOverrides=[];rawCaptureUnavailableReason;codexModelOptions=[];codexModelOptionsCachedAt=0;static MODEL_CACHE_TTL_MS=3600*1e3;rateLimitSnapshot=null;lastNonDefaultLimitRefreshAt=0;static NON_DEFAULT_LIMIT_REFRESH_INTERVAL_MS=6e4;currentThreadTokenUsage=null;currentModelContextWindow=null;auditCaptureByEventId=new Map;constructor(e,t){super(),this.config=e,this.callbacks=t;const i=e.options??{};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 be?i.bindingStore:null,this.model=i.model,this.collaborationMode=i.collaborationMode,this.reasoningEffort=i.reasoningEffort,this.serviceTier=i.serviceTier,this.bindingStore&&this.aibotSessionId&&(this.model=this.model??this.bindingStore.getCodexModelId(this.aibotSessionId),this.collaborationMode=this.collaborationMode??this.bindingStore.getCodexModeId(this.aibotSessionId),this.reasoningEffort=this.reasoningEffort??this.bindingStore.getCodexReasoningEffort(this.aibotSessionId),this.serviceTier=this.serviceTier??this.bindingStore.getCodexServiceTier(this.aibotSessionId),this.sandboxMode=this.sandboxMode??this.bindingStore.getCodexSandboxMode(this.aibotSessionId)),this.autoTrustProject=typeof i.autoTrustProject=="boolean"?i.autoTrustProject:"auto",this.codexHome=typeof i.codexHome=="string"&&i.codexHome.trim()?i.codexHome.trim():void 0;const s=i.codexDirect;if(this.codexDirect=s&&typeof s=="object"&&!Array.isArray(s)?s:null,this.configOverrideArgs=ee(i.codexConfigOverrides,"codexConfigOverrides"),this.rawCaptureOptions=Xe(i.rawApiCapture),this.cwd=this.resolveCwd(),this.bindingStore&&this.aibotSessionId){const n=this.bindingStore.getCodexThreadId(this.aibotSessionId);n&&(this.threadId=n,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.prepareDirectHome(),await this.ensureProjectTrusted(),await this.prepareRawApiCapture();try{await this.startInternalApiAndRegisterMcp(),await this.spawnCodex(),await this.initializeHandshake(),await this.notifyBindingReadyWithContext(),d.info("codex-adapter",`Ready (pid=${this.process?.pid})`)}catch(e){throw await this.stopRawApiCapture(),e}}async prepareRawApiCapture(){if(this.rawCaptureOptions)try{const e=await Ne(this.rawCaptureOptions,{adapterType:"codex",sessionId:this.rawCaptureOptions.sessionId,cwd:this.cwd,env:this.resolveChildEnv(),configOverrides:this.configOverrideArgs,codexHome:this.codexHome});this.rawCaptureRelay=e.relay,this.rawCaptureConfigOverrides=e.overlay.configOverrides??[],this.rawCaptureUnavailableReason=void 0,d.info("codex-adapter","Raw API audit capture relay is ready")}catch(e){this.rawCaptureRelay=void 0,this.rawCaptureConfigOverrides=[],this.rawCaptureUnavailableReason=e instanceof Error?e.message:String(e),d.warn("codex-adapter",`Raw API audit capture unavailable: ${this.rawCaptureUnavailableReason}`)}}async stopRawApiCapture(){const e=this.rawCaptureRelay;this.rawCaptureRelay=void 0,this.rawCaptureConfigOverrides=[],e&&await e.stop()}async prepareDirectHome(){if(!this.codexDirect)return;const e=await Se(this.codexDirect);this.codexHome=e.codexHome,this.directEnv=e.env;const t=ee(e.configOverrides,"codexDirect.configOverrides");this.configOverrideArgs=[...this.configOverrideArgs,...t],d.info("codex-adapter",`Codex direct home ready: ${e.codexHome} (catalog=${e.catalogVersion??"none"}, token=${e.tokenDigest?`present sha256:${e.tokenDigest}`:"absent"})`)}resolveChildEnv(){const e={...process.env,...this.config.env};return this.codexHome&&(e.CODEX_HOME=this.codexHome),e}async ensureProjectTrusted(){if(this.shouldAutoTrustProject())try{const e=await Te(this.cwd,{codexHome:this.codexHome});e.changed&&d.info("codex-adapter",`Trusted Codex project ${this.cwd} in ${e.configPath}`)}catch(e){const t=e instanceof Error?e.message:String(e);throw d.error("codex-adapter",`Failed to trust Codex project ${this.cwd}: ${t}`),e}}async startInternalApiAndRegisterMcp(){try{this.internalApi=new xe,this.internalApi.setInvokeHandler(async(o,c,p,h)=>this.callbacks.agentInvoke(o,c,h)),await this.internalApi.start(0),d.info("codex-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),t=this.resolveChildEnv(),i=typeof t.PATH=="string"?t.PATH:void 0,s=oe(this.config.command||"codex",i);for(const o of[...we,e.name])try{J(s,["mcp","remove",o],{env:t,timeout:1e4,stdio:"ignore"})}catch{}J(s,["mcp","add",e.name,"--",e.command,...e.args],{env:t,timeout:1e4,stdio:"ignore"}),d.info("codex-adapter",`Registered MCP server: ${e.name}`);const n=P(Ee(this.codexHome),"skills"),r=me(n);r.length>0&&d.info("codex-adapter",`Synced connector skills to ${n}: [${r.join(", ")}]`)}catch(e){d.warn("codex-adapter",`Failed to register MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`)}}shouldAutoTrustProject(){return this.autoTrustProject===!1?!1:this.autoTrustProject===!0?!0:Ae(this.config.command)}notifyBindingReady(){!this.aibotSessionId||!this.cwd||this.callbacks.sendUpdateBindingCard(this.aibotSessionId,"ready",this.cwd)}async notifyBindingReadyWithContext(){if(!(!this.aibotSessionId||!this.cwd))try{this.callbacks.sendUpdateBindingCard(this.aibotSessionId,"ready",this.cwd,await this.buildToolbarContextResult("binding_ready"))}catch(e){d.warn("codex-adapter",`Failed to attach toolbar context to binding update: ${e instanceof Error?e.message:String(e)}`),this.notifyBindingReady()}}externalProviderCheckedAt=0;externalProviderCached=!1;static EXTERNAL_PROVIDER_CACHE_TTL_MS=60*1e3;isExternalProvider(){const e=Date.now();if(e-this.externalProviderCheckedAt<$.EXTERNAL_PROVIDER_CACHE_TTL_MS)return this.externalProviderCached;const t=N(this.codexHome);return this.externalProviderCached=!!(t.baseUrl&&de(t.baseUrl)),this.externalProviderCheckedAt=e,this.externalProviderCached}effectiveServiceTier(){if(!this.serviceTier||this.serviceTier.trim().toLowerCase()==="default"||this.isExternalProvider())return;const e=this.getModelOption(this.currentModelId());if(!(e&&!e.serviceTiers.some(t=>t.id===this.serviceTier)))return this.serviceTier}getEffortMeta(){if(this.isExternalProvider())return{};const e=this.currentModelId(),t=this.getModelOption(e),i={},s=t?.supportedReasoningEfforts??[];s.length>0&&(i.available_efforts=s,i.reasoning_effort=this.reasoningEffort??t?.defaultReasoningEffort??null);const n=t?.serviceTiers??[];return n.length>0&&(i.available_service_tiers=n,i.service_tier=this.effectiveServiceTier()??t?.defaultServiceTier??null),i}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.sendEventResultAfterFlushing(t.event_id,"failed","adapter stopped");for(const t of this.steerDeferred.splice(0))this.sendEventResultAfterFlushing(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")Z(e,"SIGTERM"),await Promise.race([new Promise(i=>{e.once("exit",()=>i(!0))}),new Promise(i=>{setTimeout(()=>i(!1),5e3)})])||Z(e,"SIGKILL");else if(e)try{e.kill("SIGTERM")}catch{}await this.stopRawApiCapture()}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),this.inboundMessageIds.reset()}sendPrompt(e){const t=new B(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)}
|
|
3
|
+
`)})}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.clearCodexDeltaBuffer(),this.activeEventId=null}setModel(e){this.model=e,this.persistCodexContext(),d.info("codex-adapter",`Model set to: ${e}`)}setMode(e){const t=M(e);if(!t){d.info("codex-adapter",`Ignoring unsupported mode: ${e}`);return}this.collaborationMode=t,this.persistCodexContext(),d.info("codex-adapter",`Mode set to: ${t}`)}setReasoningEffort(e){this.reasoningEffort=e,this.persistCodexContext(),d.info("codex-adapter",`Reasoning effort set to: ${e}`)}setServiceTier(e){const t=e.trim();this.serviceTier=t.toLowerCase()==="default"?"default":t,this.persistCodexContext(),d.info("codex-adapter",`Service tier set to: ${this.serviceTier}`)}setSandboxMode(e){this.sandboxMode=e,this.persistCodexContext(),d.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}hasRawApiCaptureRelay(){return!!this.rawCaptureRelay}enableAuditCapture(e,t={}){const i=e.trim();if(!i||this.auditCaptureByEventId.has(i))return;const s=t.rawProviderBody??!!this.rawCaptureOptions;this.auditCaptureByEventId.set(i,{threadId:this.threadId??void 0,modelId:this.currentModelId()??void 0,rawProviderBody:s,sequence:0,events:[]}),s&&this.rawCaptureRelay?.beginEvent(i,t.auditId)}takeAuditBoundary(e){const t=this.auditCaptureByEventId.get(e);if(t)return this.auditCaptureByEventId.delete(e),{adapterType:this.type,providerTurnId:t.providerTurnId,threadId:t.threadId??this.threadId??void 0,codexEvidence:{events:t.events,...t.modelId?{modelId:t.modelId}:{},...t.rawProviderBody?{rawApiCapture:this.rawCaptureRelay?this.rawCaptureRelay.takeEvent(e):Ue(this.rawCaptureUnavailableReason??"raw_capture_relay_not_prepared_before_adapter_start")}:{}}}}getMcpConfig(){if(!this.internalApi)return null;const e=pe(fe(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:ye(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?Ie(e,[e]):!1}onAgentProfileChanged(){this.threadId&&(this.profileIdentityRefreshPending=!0,this.identityInputInjectedThreadId=null,d.info("codex-adapter",`agent profile changed; scheduling identity refresh for thread=${this.threadId}`))}async probe(e){const t=this.config.command||"codex",i=await Pe(t),s=i!==null;let n=null,r;if(s){const y=await De(t);n=y.version,y.error&&(r=y.error)}else r={code:"cli_not_found",message:`command not found: ${t}`};const c=N(this.codexHome).baseUrl??null,p=this.currentModelId()||null,h=this.getStatus(),m=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},v=await this.probeSessionRecord(),x=Q({codexHome:this.codexHome});return{cli:{command:t,installed:s,path:i,version:n,...r?{error:r}:{}},conversation:m,config:{model:p,base_url:c,source:{model:p?"runtime":"unknown",base_url:c?"file":"unknown"}},process:{started:!!this.process,alive:h.alive,busy:h.busy},session:v,lock:{present:x.present,locked:x.locked,stale:x.stale,path:x.path}}}async probeSessionRecord(){const e=this.threadId?ke(this.threadId,this.codexHome):null;if(!e)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const t=await K(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.sendEventResultAfterFlushing(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 r=n instanceof Error?n.message:String(n);if(/thread.*(not found|not exist|unknown|invalid)/i.test(r)||/not found.*thread/i.test(r))return this.threadId=null,this.persistThreadId(void 0),{status:"failed",message:"The session has expired and there is no history to compact. Please send a new message and try again."};throw n}}case"model":{const s=t.trim();return s?this.getModelOptions().some(r=>r.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=M(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:re}}}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.sendEventResultAfterFlushing(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.sendEventResultAfterFlushing(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=$e({mode:"codex",projectDir:this.cwd}),n=s.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""}: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
|
|
4
|
+
`):"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(d.info("codex-adapter",`handleLocalAction action_type=${t} action_id=${e.action_id} session_id=${i.session_id??""}`),t){case"set_model":{const s=I(u(i.model_id),u(i.modelId),u(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=I(u(i.reasoning_effort),u(i.reasoning_eff),u(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_service_tier":{const s=I(u(i.service_tier),u(i.serviceTier),u(i.value));return s&&this.setServiceTier(s),this.callbacks.sendLocalActionResult(e.action_id,"ok",await this.buildToolbarContextResult("service_tier_set",!1)),{handled:!0,kind:"set_service_tier"}}case"set_sandbox_mode":{const s=I(u(i.sandbox_mode),u(i.sandboxMode),u(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":{d.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.sendEventResultAfterFlushing(this.activeEventId,"canceled","compacting"),this.clearActive());try{if(await this.ensureThreadResumed(),this.needsHistoryInjection)return d.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,d.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)?(d.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.")):(d.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",r=it[n]??"accept";return this.sendApprovalDecision(s.requestId,r),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.sendEventResultAfterFlushing(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(),r=Date.now(),o=this.currentThreadTokenUsage;return s?d.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}`):d.info("codex-adapter","[rate-limits] responding: no rateLimitSnapshot available"),d.debug("codex-adapter",`[cp-diagnose] get_rate_limits: threadId=${this.threadId??"-"} contextWindow=${JSON.stringify(n)} tokenUsage=${JSON.stringify(o)}`),this.callbacks.sendLocalActionResult(e.action_id,"ok",{adapterType:"codex",available:s!==null,cached:!1,sampledAt:r,rateLimits:s,contextWindow:n,tokenUsage:o}),{handled:!0,kind:"get_rate_limits"}}default:return{handled:!1,kind:""}}}async buildToolbarContextResult(e,t=!0){t&&await this.refreshCodexModelOptions();const i=M(this.collaborationMode)??"default",s=this.currentModelId(),n=this.getModelOption(s),r=this.getModelOptions(),o=re,c=this.reasoningEffort??n?.defaultReasoningEffort??null,p=n?.supportedReasoningEfforts??[],h=this.effectiveServiceTier()??n?.defaultServiceTier??null,m=n?.serviceTiers??[],v=this.isExternalProvider(),x=v?[]:p,y=v?null:c,E=v?[]:m,S=v?null:h,C={outcome:e,session_context:{modelId:s,modeId:i,reasoningEffort:y,serviceTier:S,approvalPolicy:this.approvalPolicy,sandboxMode:this.sandboxMode??null},model_id:s,mode_id:i,currentModelId:s,currentModeId:i,available_models:r,available_modes:o,available_efforts:x,availableModels:r,availableModes:o,reasoning_effort:y,available_service_tiers:E,service_tier:S,sandbox_mode:this.sandboxMode??null,models:r.map(w=>({modelId:w.id,name:w.displayName})),modes:o.map(w=>({id:w.id,name:w.displayName}))};return this.rateLimitSnapshot&&(C.rate_limit_primary_percent=this.rateLimitSnapshot.primary.usedPercent,C.rate_limit_secondary_percent=this.rateLimitSnapshot.secondary.usedPercent,C.rate_limit_primary_window_min=this.rateLimitSnapshot.primary.windowMinutes,C.rate_limit_secondary_window_min=this.rateLimitSnapshot.secondary.windowMinutes),C}currentModelId(){const e=String(this.model??"").trim();if(e)return e;const t=this.getModelOptions();return t.find(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=dt(t),s=this.codexModelOptions,n=[],r=String(this.model??"").trim(),o=r&&!s.some(m=>m.id.trim().toLowerCase()===r.toLowerCase()),c=s.length>0?s:o?[]:et;if(r){const m=[...s,...i].find(v=>v.id.trim().toLowerCase()===r.toLowerCase());n.push({id:r,displayName:m?.displayName??k(r),defaultReasoningEffort:m?.defaultReasoningEffort??null,supportedReasoningEfforts:m?.supportedReasoningEfforts??[],defaultServiceTier:m?.defaultServiceTier??null,serviceTiers:m?.serviceTiers??[],isDefault:m?.isDefault??!1})}n.push(...i),n.push(...c);const p=[],h=new Set;for(const m of n){const v=m.id.trim(),x=v.toLowerCase();!v||h.has(x)||(h.add(x),p.push({id:v,displayName:m.displayName.trim()||v,defaultReasoningEffort:m.defaultReasoningEffort,supportedReasoningEfforts:[...m.supportedReasoningEfforts],defaultServiceTier:m.defaultServiceTier,serviceTiers:[...m.serviceTiers],isDefault:m.isDefault}))}return p}async refreshCodexModelOptions(){if(!this.initialized||!this.alive||!this.process?.stdin||Date.now()-this.codexModelOptionsCachedAt<$.MODEL_CACHE_TTL_MS)return;const e=N(this.codexHome);if(e.baseUrl&&de(e.baseUrl)){try{const t=await ct(e.baseUrl,e.apiKey);if(t.length>0){this.codexModelOptions=ce(t),this.codexModelOptionsCachedAt=Date.now(),d.info("codex-adapter",`Loaded ${t.length} models from external provider ${e.baseUrl}`);return}}catch(t){d.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=ut(s);t.push(...n.models),i=n.nextCursor}while(i);t.length>0&&(this.codexModelOptions=ce(t),this.codexModelOptionsCachedAt=Date.now())}catch(t){d.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;deliveredAgentMessageIds=new Set;codexSequence=0;pendingCodexDeltaFlush=null;turnError=null;turnErrorIsRetryableOnly=!0;turnHasVisibleOutput=!1;turnSawVisibleFinalAnswer=!1;turnHasDeliveredFinalAnswer=!1;deliverInboundEvent(e){if(this.compacting){d.info("codex-adapter",`Event ${e.event_id} deferred: compaction in progress`),this.compactionDeferred.push(e);return}const t=this.inboundMessageIds.prepare(e.session_id,e.content,e.msg_id),i=t.text,s=()=>{t.instructionPending&&this.inboundMessageIds.commitInstruction(e.session_id)},n=()=>{const r=this.inboundMessageIds.prepare(e.session_id,e.content,e.msg_id);r.instructionPending&&this.inboundMessageIds.commitInstruction(e.session_id),this.startNewTurn(e,r.text)};if(this.currentTurnId&&i.trim()){d.info("codex-adapter",`Event ${e.event_id}: steering active turn ${this.currentTurnId}`),this.steerTurn(i).then(()=>{s()}).catch(r=>{const o=r instanceof Error?r.message:String(r);if(d.info("codex-adapter",`Steer failed, falling through: ${o}`),!this.currentTurnId){n();return}if(ft(o)){d.info("codex-adapter","Unsteerable turn detected, clearing active state and starting new turn"),this.clearActive(),n();return}d.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){d.info("codex-adapter",`Event ${e.event_id} rejected: busy and empty content`),this.sendEventResultAfterFlushing(e.event_id,"failed","agent busy");return}s(),this.startNewTurn(e,i)}startNewTurn(e,t){this.activeEventId=e.event_id,this.activeSessionId=e.session_id,e.audit?.enabled===!0&&this.enableAuditCapture(e.event_id,{auditId:e.audit.auditId,rawProviderBody:e.audit.rawProviderBody}),this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.agentMessagePhases.clear(),this.deliveredAgentMessageIds.clear(),this.turnSawVisibleFinalAnswer=!1,this.turnHasDeliveredFinalAnswer=!1,this.codexSequence=0,this.startComposing();const i=this.threadId??"",s=new B(i),n={adapterSessionId:i,text:t,contextMessages:e.context_messages_json?JSON.parse(e.context_messages_json).map(r=>({senderId:r.sender_id??"unknown",content:r.content})):void 0};this.runTurn(n,s,e.event_id,e.session_id).catch(r=>{d.error("codex-adapter",`Turn failed: ${r}`),this.sendEventResultAfterFlushing(e.event_id,"failed",r instanceof Error?r.message:String(r)),this.clearActive()}),this.resetIdleTimer(e.event_id)}deliverStopEvent(e,t){this.activeEventId===e&&(this.cancel(this.threadId??"").catch(()=>{}),this.sendEventResultAfterFlushing(e,"canceled","stopped by user"),this.clearActive())}async spawnCodex(){const e={...this.resolveChildEnv(),...this.directEnv},t=typeof e.PATH=="string"?e.PATH:void 0;t||d.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=oe(this.config.command||"codex",t),s=nt(this.config.args);for(const o of this.configOverrideArgs)s.push("-c",o);for(const o of this.resolveRelayTransportConfigOverrides())s.push("-c",o);for(const o of this.rawCaptureConfigOverrides)s.push("-c",o);this.sandboxMode&&s.push("-c",`sandbox_mode="${this.sandboxMode}"`);const n=s.map(o=>this.rawCaptureConfigOverrides.includes(o)?"<raw-api-capture-overlay>":o);d.info("codex-adapter",`Spawning: ${i} ${n.join(" ")}`);try{if(!(await K(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 r=Q({codexHome:this.codexHome});if(r.locked&&!r.stale)throw new Error(`Codex session appears locked by another process: ${r.path}`);r.stale&&d.warn("codex-adapter",`Ignoring stale Codex lock: ${r.path}`);try{this.process=ve(i,s,{env:e,cwd:this.cwd}).process}catch(o){throw d.error("codex-adapter",`Codex spawn threw: ${o}`),this.process=null,this.alive=!1,this.bridgeStatus="closed",o}this.process.on("error",o=>{d.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.flushCodexDeltaBuffer(),this.sendEventResultAfterFlushing(this.activeEventId,"failed","Codex process spawn failed"),this.activeEventId=null):this.clearCodexDeltaBuffer(),this.emit("exit",1)}),this.process.on("exit",o=>{d.info("codex-adapter",`Codex process exited (code=${o})`),this.alive=!1,this.bridgeStatus="closed",this.clearIdleTimer(),this.rejectAllPending("process exited"),this.stopComposing(),this.activeEventId?this.flushCodexDeltaBuffer():this.clearCodexDeltaBuffer(),this.emit("exit",o)}),this.process.stderr?.on("data",o=>{const c=o.toString().trim();c&&d.info("codex-adapter",`[codex stderr] ${c}`)}),this.bindStdout(),this.alive=!0}resolveRelayTransportConfigOverrides(){if(this.config.env?.[ze]!=="1")return[];const e=Fe(this.codexHome,this.configOverrideArgs);if(e==="openai"){const i=je(this.codexHome,this.configOverrideArgs);return Oe(Le,"Grix OpenAI Relay",i.targetBaseUrl)}const t=He(e);return t?[`${t}=false`]:[]}bindStdout(){if(!this.process?.stdout)return;this.process.stdout.setEncoding("utf8"),he({input:this.process.stdout}).on("line",t=>{if(!t.trim())return;let i;try{i=JSON.parse(t)}catch{d.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??{};if(this.shouldIgnoreOutOfScopeNotification(e,t,i)){this.activeEventId&&this.resetIdleTimer(this.activeEventId);return}switch(this.captureAuditNotification(t,i),this.captureContextWindowFromPayload(t,i),this.activeEventId&&t&&t.startsWith("item/")&&!t.endsWith("/requestApproval")&&this.startComposing(),t){case"item/started":{const n=i.item,r=n?.id,o=n?.type,c=this.normalizeAgentMessagePhase(n?.phase);this.isLongRunningToolItemType(o)&&(this.inFlightToolOps+=1),o==="agentMessage"&&r&&(c?this.agentMessagePhases.set(r,c):this.agentMessagePhases.delete(r),D(c)?(this.visibleAgentMessageIds.add(r),this.hiddenAgentMessageIds.delete(r)):(this.hiddenAgentMessageIds.add(r),this.visibleAgentMessageIds.delete(r)),c==="final_answer"&&D(c)&&(this.turnSawVisibleFinalAnswer=!0));break}case"item/agentMessage/delta":{const n=i.delta,r=i.itemId,o=this.resolveAgentMessagePhase(r,i.phase),c=(!r||!this.hiddenAgentMessageIds.has(r))&&D(o);o==="final_answer"&&c&&(this.turnSawVisibleFinalAnswer=!0),n&&this.activeEventId&&c&&!this.shouldSuppressAgentMessageDeltaDuringToolRun(r,o)&&(this.recordDeliveredAgentMessage(r,o),this.queueCodexDeltaEvent(e));break}case"item/completed":{const n=i.item,r=n?.id,o=n?.type;if(this.isLongRunningToolItemType(o)&&(this.inFlightToolOps=Math.max(0,this.inFlightToolOps-1)),this.activeEventId&&o==="commandExecution"&&(this.turnHasVisibleOutput=!0,this.emitCodexEvent("item/completed",e)),o==="agentMessage"){const c=this.resolveAgentMessagePhase(r,n?.phase),p=(!r||!this.hiddenAgentMessageIds.has(r))&&D(c);if(c==="final_answer"&&p){this.turnSawVisibleFinalAnswer=!0;const h=this.extractAgentMessageText(n),m=r?this.deliveredAgentMessageIds.has(r):!1;this.activeEventId&&h&&!m&&(d.warn("codex-adapter",`Recovering final_answer from item/completed item_id=${r??"unknown"}`),this.recordDeliveredAgentMessage(r,c),this.queueCodexDeltaEvent({method:"item/agentMessage/delta",params:{...r?{itemId:r}:{},delta:h,phase:c}}))}r&&(this.visibleAgentMessageIds.delete(r),this.hiddenAgentMessageIds.delete(r),this.agentMessagePhases.delete(r))}break}case"turn/started":{const r=i.turn?.id;r&&(this.currentTurnId=r,this.turnError=null,this.turnErrorIsRetryableOnly=!0,this.turnHasVisibleOutput=!1,this.turnSawVisibleFinalAnswer=!1,this.turnHasDeliveredFinalAnswer=!1,this.deliveredAgentMessageIds.clear(),this.currentTurnStartedAt=Date.now(),this.preflightCheckComplete=!1,d.info("codex-adapter",`Turn started: ${r}`),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.handleApprovalRequest(e,"permission");break}case"turn/completed":{this.handleTurnCompleted(i);break}case"error":{const n=i.message??JSON.stringify(i);d.error("codex-adapter",`Codex error: ${n}`);const r=i.willRetry===!0;n&&(this.turnError=n,r||(this.turnErrorIsRetryableOnly=!1)),this.activeEventId&&!r&&(this.flushCodexDeltaBuffer(),this.callbacks.sendRunError(this.activeEventId,this.activeSessionId??"",n));break}case"account/rateLimits/updated":{const n=this.extractRateLimitPushLimitId(i),r=this.parseRateLimitSnapshot(i,this.rateLimitSnapshot);r&&(this.rateLimitSnapshot=r,d.info("codex-adapter",`Rate limits updated: primary=${r.primary.usedPercent.toFixed(1)}% secondary=${r.secondary.usedPercent.toFixed(1)}% extras=${r.extras?.length??0}`),this.callbacks.onRateLimitsUpdated?.(r)),n&&n!=="codex"&&this.refreshMainRateLimitsThrottled();break}case"thread/tokenUsage/updated":{const n=i.threadId,r=i.tokenUsage,o=r?.last;(!n||!r||!o)&&d.info("codex-adapter",`[cp-diagnose] token_usage payload_incomplete: method=thread/tokenUsage/updated hasThreadId=${String(!!n)} hasTokenUsage=${String(!!r)} hasLast=${String(!!o)} params=${JSON.stringify(i)}`),n&&r&&o&&(this.currentThreadTokenUsage={inputTokens:o.inputTokens??0,outputTokens:o.outputTokens??0,cacheReadInputTokens:o.cachedInputTokens??0,cacheCreationInputTokens:0},d.info("codex-adapter",`[cp-diagnose] token_usage raw thread=${n}: ${JSON.stringify(r)}`),d.info("codex-adapter",`[cp-diagnose] token_usage parsed thread=${n}: ${JSON.stringify(this.currentThreadTokenUsage)}`),this.callbacks.onTokenUsageUpdated?.(this.currentThreadTokenUsage),this.publishContextWindowSnapshot());break}default:break}const s=t?.endsWith("/requestApproval")===!0;t&&t!=="turn/started"&&(t.startsWith("item/")||t==="error"||t==="turn/completed")&&(this.preflightCheckComplete=!0),this.activeEventId&&(!s||this.pendingApprovals.size===0)&&this.resetIdleTimer(this.activeEventId)}shouldIgnoreOutOfScopeNotification(e,t,i){if(!t||e.id!=null)return!1;const s=I(u(i.threadId),u(i.threadID));if(s&&this.threadId&&s!==this.threadId)return this.logIgnoredNotificationScope(t,s,this.readNotificationTurnId(i)),!0;const n=this.readNotificationTurnId(i);return n&&this.currentTurnId&&n!==this.currentTurnId?(this.logIgnoredNotificationScope(t,s,n),!0):!1}readNotificationTurnId(e){const t=e.turn&&typeof e.turn=="object"?e.turn:void 0;return I(u(e.turnId),u(e.turnID),u(t?.id))}logIgnoredNotificationScope(e,t,i){e!=="error"&&!e.startsWith("turn/")||d.info("codex-adapter",`[scope] ignored ${e} thread=${t??"<none>"} turn=${i??"<none>"} active_thread=${this.threadId??"<none>"} active_turn=${this.currentTurnId??"<none>"}`)}captureAuditNotification(e,t){const i=this.activeEventId;if(!e||!i)return;const s=this.auditCaptureByEventId.get(i);if(!s)return;const n=t.turn,r=typeof t.turnId=="string"&&t.turnId?t.turnId:typeof t.turn_id=="string"&&t.turn_id?t.turn_id:typeof n?.id=="string"&&n.id?n.id:this.currentTurnId;r&&(s.providerTurnId=r);const o=typeof t.threadId=="string"&&t.threadId?t.threadId:typeof t.thread_id=="string"&&t.thread_id?t.thread_id:this.threadId;if(o&&(s.threadId=o),!!tt.has(e))try{const c=JSON.parse(JSON.stringify(t));s.events.push({sequence:++s.sequence,method:e,params:c,observedAt:new Date().toISOString()})}catch(c){const p=c instanceof Error?c.message:String(c);d.warn("codex-adapter",`Audit evidence capture skipped event=${i} method=${e}: ${p}`)}}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&&d.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,d.info("codex-adapter",`[cp-diagnose] context_window updated: method=${e??"-"} size=${s}`),this.publishContextWindowSnapshot())}probeContextWindowFields(e,t){const i=[],s=[],n=r=>{if(!r||typeof r!="object")return;if(Array.isArray(r)){for(const c of r)n(c);return}const o=r;for(const c of t)Object.prototype.hasOwnProperty.call(o,c)&&(i.push(c),s.push(String(o[c])));for(const c of Object.values(o))n(c)};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 r=Number(n);if(Number.isFinite(r))return r}}for(const s of Object.values(i)){if(Array.isArray(s)){for(const r of s){const o=this.findNumericField(r,t);if(o!=null)return o}continue}const n=this.findNumericField(s,t);if(n!=null)return n}return null}buildContextWindowSnapshot(){const e=this.currentModelContextWindow;if(!e||e<=0)return d.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),r=i==null?null:Math.max(0,100-(n??0));return d.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:r,source:"codex:model_context_window"}}publishContextWindowSnapshot(){const e=this.buildContextWindowSnapshot();this.callbacks.onContextWindowUpdated?.(e),this.maybeScheduleAutoCompact(e)}maybeScheduleAutoCompact(e){const t=e?.usedPercentage;typeof t!="number"||t<ne||this.pendingAutoCompact||this.compacting||(this.pendingAutoCompact=!0,d.info("codex-adapter",`[auto-compact] context_window usedPercentage=${t.toFixed(1)}% >= ${ne}%, 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=>{d.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=>{d.warn("codex-adapter",`[auto-compact] compact error: ${e instanceof Error?e.message:e}`)})))}parseRateLimitSnapshot(e,t=null){try{const i=e.rateLimitsByLimitId,s=this.extractRateLimitPushLimitId(e),n=!i?.codex&&!!s&&s!=="codex",r=i?.codex??(n?{}:e.rateLimits??e),o=r.primary,c=r.secondary,p=r.credits,h=l=>{if(typeof l=="number"&&Number.isFinite(l))return l;if(typeof l=="string"){const f=Number(l);if(Number.isFinite(f))return f}return 0},m=l=>typeof l=="boolean"?l:typeof l=="string"?l.toLowerCase()==="true":!1,v=l=>{if(l==null)return null;if(typeof l=="string"){const f=l.trim();if(!f)return null;const g=Number(f);return Number.isFinite(g)&&g>1e9?new Date(g*1e3).toISOString():f}if(typeof l=="number"&&Number.isFinite(l)&&l>0){const f=l>1e12?l/1e3:l;return new Date(f*1e3).toISOString()}return null},x=l=>{const f=l.resets_in_seconds??l.resetsInSeconds,g=typeof f=="number"||typeof f=="string"?Number(f):NaN;return!Number.isFinite(g)||g<=0?null:new Date(Date.now()+g*1e3).toISOString()},y=l=>({usedPercent:h(l.used_percent??l.usedPercent),windowMinutes:h(l.window_minutes??l.windowDurationMins??l.windowMinutes),resetsAt:v(l.resets_at??l.resetsAt)??x(l)}),E=()=>({usedPercent:0,windowMinutes:0,resetsAt:null}),S=(l,f)=>l??f??E(),C=()=>{const l=[];if(o&&l.push(o),c&&l.push(c),Array.isArray(r.windows))for(const f of r.windows)f&&typeof f=="object"&&l.push(f);return l.map(y).filter(f=>f.windowMinutes>0)},w=(l,f,g)=>{const b=l.filter(T=>g(T.windowMinutes));return b.length===0?null:b.reduce((T,A)=>Math.abs(A.windowMinutes-f)<Math.abs(T.windowMinutes-f)?A:T)},O=C(),L=n?t?{primary:t.primary,secondary:t.secondary}:null:O.length>0?{primary:S(w(O,300,l=>l<1440),t?.primary),secondary:S(w(O,10080,l=>l>=1440),t?.secondary)}:o||c?{primary:o?y(o):t?.primary??E(),secondary:c?y(c):t?.secondary??E()}:null;if(!L)return null;const z=(l,f)=>{if(!f||typeof f!="object"||Array.isArray(f))return null;const g=f,b=g.limitName??g.limit_name,T=typeof b=="string"&&b.trim()?b.trim():l,A=[],W=g.primary,V=g.secondary;W&&A.push(W),V&&A.push(V);const G=A.map(y).filter(R=>R.windowMinutes>0),X=w(G,10080,R=>R>=1440)??w(G,300,R=>R<1440);return X?{id:l,label:T,...X}:null};let _;if(i&&typeof i=="object"){_=[];for(const[l,f]of Object.entries(i)){if(l==="codex")continue;const g=z(l,f);g&&_.push(g)}}else if(_=t?.extras?[...t.extras]:[],n&&s){const l=z(s,e.rateLimits??e);if(l){const f=_.findIndex(g=>g.id===l.id);f>=0?_[f]=l:_.push(l)}}return{primary:L.primary,secondary:L.secondary,credits:p?{hasCredits:m(p.has_credits??p.hasCredits),unlimited:m(p.unlimited),balance:p.balance==null?null:h(p.balance)}:t?.credits??{hasCredits:!1,unlimited:!1,balance:null},..._.length>0?{extras:_}:{}}}catch{return null}}handleApprovalRequest(e,t){const i=e.id;if(i==null)return;const s=e.method,n=`${i}`.trim(),r=`codex_${le(this.activeSessionId??"")}_${le(n)}`;if(this.approvalPolicy==="never"){this.sendApprovalDecision(i,"accept");return}this.activeEventId&&this.emitCodexEvent(s,e),this.pendingApprovals.set(r,{approvalId:r,approvalCommandId:n,sourceEventId:this.activeEventId??"",requestId:i,kind:t}),d.info("codex-adapter",`Pending approval stored: ${r} (kind=${t})`),this.clearIdleTimer(),this.stopComposing()}resolvePendingApproval(e){const t=e.params??{},i=I(t.approval_id,t.approvalId);if(i)return this.pendingApprovals.get(i)??null;const s=I(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)}
|
|
5
|
+
`)}armCompactionFallback(){this.compacting&&(this.compactingTimer&&clearTimeout(this.compactingTimer),this.compactingTimer=setTimeout(()=>{d.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")},Ke),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);d.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){this.flushCodexDeltaBuffer();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},s=this.turnError,n=this.turnErrorIsRetryableOnly,r=this.turnHasVisibleOutput,o=this.turnSawVisibleFinalAnswer&&!this.turnHasDeliveredFinalAnswer;this.turnError=null,this.turnErrorIsRetryableOnly=!0,this.turnHasVisibleOutput=!1,this.turnSawVisibleFinalAnswer=!1,this.turnHasDeliveredFinalAnswer=!1;const p=(s&&!(n&&r)?s:null)??(o?"Codex final answer was observed but not delivered":null)??(r?null:"Codex completed without producing any visible output"),h=p!==null;this.callbacks.sendCodexEvent(i),this.sendEventResultAfterFlushing(t,h?"failed":"responded",p??void 0),this.clearActive()}this.compacting&&this.finishCompaction("turn-completed")}emitCodexEvent(e,t){if(!this.activeEventId)return;this.flushCodexDeltaBuffer();const i=ue(e,t);if(i===void 0&&e==="item/completed")return;const s={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};i!==void 0&&(s.codex_payload=i),this.callbacks.sendCodexEvent(s)}queueCodexDeltaEvent(e){if(!this.activeEventId)return;const i=ue("item/agentMessage/delta",e)?.params?.delta;if(typeof i!="string"||i.length===0)return;const s=this.activeEventId,n=this.activeSessionId??"",r=this.threadId??void 0,o=this.pendingCodexDeltaFlush;if(o&&(o.eventId!==s||o.sessionId!==n||o.threadId!==r)&&this.flushCodexDeltaBuffer(),this.pendingCodexDeltaFlush||(this.pendingCodexDeltaFlush={eventId:s,sessionId:n,threadId:r,delta:"",timer:null}),this.pendingCodexDeltaFlush.delta+=i,this.pendingCodexDeltaFlush.delta.length>=Qe){this.flushCodexDeltaBuffer();return}this.pendingCodexDeltaFlush.timer||(this.pendingCodexDeltaFlush.timer=setTimeout(()=>{if(this.activeEventId!==s){this.clearCodexDeltaBuffer();return}this.flushCodexDeltaBuffer()},Ze))}flushCodexDeltaBuffer(){const e=this.pendingCodexDeltaFlush;if(!e||(this.pendingCodexDeltaFlush=null,e.timer&&clearTimeout(e.timer),!e.delta))return;const t={event_id:e.eventId,session_id:e.sessionId,thread_id:e.threadId,codex_event_type:"codex",codex_method:"item/agentMessage/delta",codex_sequence:++this.codexSequence,codex_payload:{params:{delta:e.delta}}};this.callbacks.sendCodexEvent(t)}clearCodexDeltaBuffer(){const e=this.pendingCodexDeltaFlush;this.pendingCodexDeltaFlush=null,e?.timer&&clearTimeout(e.timer)}sendEventResultAfterFlushing(e,t,i){this.pendingCodexDeltaFlush?.eventId===e&&this.flushCodexDeltaBuffer(),this.callbacks.sendEventResult(e,t,i)}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 r=++this.requestId,o={jsonrpc:"2.0",id:r,method:e,params:t??{}},c=setTimeout(()=>{this.pendingRequests.delete(String(r)),n(new Error(`Request timeout: ${e}`))},i);this.pendingRequests.set(String(r),{resolve:h=>{h.error?n(new Error(`JSON-RPC error: ${h.error.message}`)):s(h.result)},reject:n,timer:c});const p=JSON.stringify(o);this.process.stdin.write(`${p}
|
|
6
6
|
`)})}sendNotification(e,t){if(!this.process?.stdin)return;const i={jsonrpc:"2.0",method:e,params:t??{}};this.process.stdin.write(`${JSON.stringify(i)}
|
|
7
|
-
`)}async initializeHandshake(){if(this.initialized)return;const e=
|
|
7
|
+
`)}async initializeHandshake(){if(this.initialized)return;const e=Ce(),t=await this.sendRequest("initialize",{clientInfo:{name:"grix-connector",title:"Grix Connector",version:e},capabilities:{experimentalApi:!0}},15e3);d.info("codex-adapter",`Initialized: ${JSON.stringify(t)}`),this.sendNotification("initialized"),this.initialized=!0,await this.refreshCodexModelOptions(),this.fetchRateLimits()}extractRateLimitPushLimitId(e){const t=s=>{if(!s||typeof s!="object"||Array.isArray(s))return null;const n=s.limitId??s.limit_id;return typeof n=="string"&&n.trim()?n.trim():null},i=e.rateLimitsByLimitId;if(i&&typeof i=="object"&&!Array.isArray(i)){const s=i;return s.codex?"codex":t(Object.values(s)[0])}return t(e.rateLimits??e)}refreshMainRateLimitsThrottled(){const e=Date.now();e-this.lastNonDefaultLimitRefreshAt<$.NON_DEFAULT_LIMIT_REFRESH_INTERVAL_MS||(this.lastNonDefaultLimitRefreshAt=e,this.fetchRateLimits())}fetchRateLimits(){Promise.resolve(this.sendRequest("account/rateLimits/read",void 0,1e4)).then(e=>{const t=this.parseRateLimitSnapshot(e);t&&(this.rateLimitSnapshot=t,d.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=>{d.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.legacyDeveloperInstructionsUnsupported||this.profileIdentityRefreshPending)&&this.identityInputInjectedThreadId!==this.threadId){const h=ae(this.callbacks.getAgentProfile?.());h&&(n.push({type:"text",text:h.instructions,text_elements:[]}),d.info("codex-adapter",`Injected agent identity through compatibility input for thread=${this.threadId} name="${h.agentName}"`)),this.identityInputInjectedThreadId=this.threadId,this.profileIdentityRefreshPending=!1}if(this.needsHistoryInjection&&s){this.needsHistoryInjection=!1;const h=await this.loadHistoryForInjection(s);for(const m of h)n.push(m);h.length>0&&d.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(`
|
|
8
8
|
`);n.push({type:"text",text:`Conversation context:
|
|
9
9
|
${h}
|
|
10
10
|
|
|
11
|
-
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},c=rt(this.collaborationMode,this.model);c&&(o.collaborationMode=c),this.reasoningEffort&&(o.effort=this.reasoningEffort);const p=this.effectiveServiceTier();p&&(o.serviceTier=p),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.effectiveServiceTier()?{serviceTier:this.effectiveServiceTier()}:{}});this.updateModelFromThreadResult(e),this.threadResumePending=!1}catch{this.threadId=null,this.needsHistoryInjection=!0,await this.startNewThread(),this.threadResumePending=!1}}async startNewThread(){const e=ae(this.callbacks.getAgentProfile?.()),t={approvalPolicy:this.approvalPolicy,model:this.model,cwd:this.cwd,experimentalRawEvents:!1,persistExtendedHistory:!1,...this.reasoningEffort?{effort:this.reasoningEffort}:{},...this.effectiveServiceTier()?{serviceTier:this.effectiveServiceTier()}:{}};try{let i;if(e&&!this.legacyDeveloperInstructionsUnsupported)try{i=await this.sendRequest("thread/start",{...t,developerInstructions:e.instructions})}catch(n){if(!tt(n))throw n;this.legacyDeveloperInstructionsUnsupported=!0,d.warn("codex-adapter","Codex app-server does not support thread/start.developerInstructions; falling back to first-turn identity input"),i=await this.sendRequest("thread/start",t)}else i=await this.sendRequest("thread/start",t);const s=st(i);if(!s)throw new Error("Codex thread id is missing in thread/start result");this.threadId=s,this.identityInputInjectedThreadId=null,this.profileIdentityRefreshPending=!1,this.updateModelFromThreadResult(i),this.threadResumePending=!1,this.persistThreadId(s)}catch(i){const s=i instanceof Error?i.message:String(i);throw new Error(`Failed to start Codex thread: ${s}`)}}updateModelFromThreadResult(e){if(this.model)return;const t=nt(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:M(this.collaborationMode)??void 0,reasoningEffort:this.reasoningEffort,serviceTier:this.serviceTier,sandboxMode:this.sandboxMode})}async loadHistoryForInjection(e){const t=this.callbacks.getConversationLog();if(!t)return[];try{const i=await t.readHistory(e,Ge),s=[];for(const n of i){const r=(n.content??"").slice(0,Xe);n.direction==="inbound"?s.push({type:"text",text:r,text_elements:[]}):n.direction==="outbound"&&s.push({type:"assistant",text:r,text_elements:[]})}return s}catch(i){return d.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=I(t.session_id,t.sessionId)??this.activeSessionId??"";if(!n)return;const r=this.threadId,o=new B(r),c={adapterSessionId:r,text:""};this.activeEventId=s,this.activeSessionId=n,this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.agentMessagePhases.clear(),this.deliveredAgentMessageIds.clear(),this.turnSawVisibleFinalAnswer=!1,this.turnHasDeliveredFinalAnswer=!1,this.codexSequence=0,this.runTurn(c,o,s,n).catch(p=>{d.error("codex-adapter",`Post-approval turn failed: ${p}`),this.sendEventResultAfterFlushing(s,"failed",p instanceof Error?p.message:String(p)),this.clearActive()}),this.resetIdleTimer(s)}clearActive(e){const t=this.activeEventId;if(this.flushCodexDeltaBuffer(),this.stopComposing(),this.activeEventId=null,this.activeSessionId=null,this.currentTurnId=null,this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.agentMessagePhases.clear(),this.deliveredAgentMessageIds.clear(),this.turnSawVisibleFinalAnswer=!1,this.turnHasDeliveredFinalAnswer=!1,this.inFlightToolOps=0,this.consecutivePingFailures=0,this.currentTurnStartedAt=0,this.preflightCheckComplete=!1,this.clearIdleTimer(),this.pendingApprovals.clear(),t&&e?.emitEventDone!==!1){const i=this.rawCaptureRelay;i?i.completeEvent(t).catch(s=>{d.warn("codex-adapter",`Raw API audit capture did not settle cleanly: ${s instanceof Error?s.message:String(s)}`)}).finally(()=>this.emit("eventDone",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);d.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.activityGeneration+=1,this.lastIdleCheckGeneration=this.activityGeneration,this.idleNoProgressCount=0,this.consecutivePingFailures=0,this.armIdleTimer(e)}armIdleTimer(e,t=Number.POSITIVE_INFINITY){this.clearIdleTimer();const i=Date.now(),s=this.inFlightToolOps>0?Ue:He,n=this.turnInactivityTimeoutMs===null?Number.POSITIVE_INFINITY:this.lastProgressAt+this.turnInactivityTimeoutMs-i,r=this.currentTurnStartedAt>0&&!this.preflightCheckComplete?this.currentTurnStartedAt+j-i:Number.POSITIVE_INFINITY,o=Math.max(0,Math.min(s,n,r,t));this.idleTimer=setTimeout(()=>{this.onIdleTimeout(e,o)},o)}async onIdleTimeout(e,t){if(this.activeEventId!==e)return;const i=this.lastIdleCheckAt,s=this.lastIdleCheckGeneration,n=this.ping(Be).catch(()=>!1),r=this.checkSessionActivitySince(i),[o,c]=await Promise.all([n,r]);if(this.activeEventId!==e)return;const p=this.activityGeneration>s;if(this.lastIdleCheckAt=Date.now(),this.lastIdleCheckGeneration=this.activityGeneration,!this.preflightCheckComplete&&this.currentTurnStartedAt>0&&Date.now()-this.currentTurnStartedAt>=j){const m=this.activityGeneration,v=await this.inspectCurrentTurnProgress();if(this.activeEventId!==e)return;if(this.activityGeneration>m)this.preflightCheckComplete=!0;else if(v==="task_started_only"){this.declareRecoverablePreflightStuck(e,`Codex preflight stalled for ${Math.round(j/1e3)}s before model execution`);return}else v==="unknown"?this.currentTurnStartedAt=Date.now():this.preflightCheckComplete=!0}if(p||c){c&&(d.info("codex-adapter",`Idle timer: no stream output but rollout still being written, continuing: ${e}`),this.lastProgressAt=Date.now()),this.idleNoProgressCount=0,this.consecutivePingFailures=0,this.armIdleTimer(e);return}const h=Date.now()-this.lastProgressAt;if(this.turnInactivityTimeoutMs!==null&&h>=this.turnInactivityTimeoutMs){d.error("codex-adapter",`Turn inactive ${Math.round(h/1e3)}s \u2265 cap ${Math.round(this.turnInactivityTimeoutMs/1e3)}s, declaring stuck: ${e}`),this.declareStuck(e,`turn inactivity timeout after ${Math.round(h/1e3)}s with no Codex activity`);return}if(!o){if(this.consecutivePingFailures+=1,this.consecutivePingFailures<te){d.warn("codex-adapter",`Agent idle ${t/1e3}s and ping failed (${this.consecutivePingFailures}/${te}); retrying liveness probe: ${e}`),this.armIdleTimer(e,ze);return}d.error("codex-adapter",`Agent idle ${t/1e3}s and ping failed ${this.consecutivePingFailures}x, declaring stuck: ${e}`),this.declareStuck(e,`agent idle ${t/1e3}s, ping failed ${this.consecutivePingFailures}x`);return}this.consecutivePingFailures=0,this.idleNoProgressCount++,d.info("codex-adapter",`Idle timer: ping ok, no stream progress (cycle=${this.idleNoProgressCount}), keeping active turn alive${this.turnInactivityTimeoutMs===null?"":` until inactivity cap (${Math.round(this.turnInactivityTimeoutMs/6e4)}min)`}: ${e}`),this.armIdleTimer(e)}declareStuck(e,t){this.sendEventResultAfterFlushing(e,"failed",t),this.clearActive(),this.emit("stuck")}declareRecoverablePreflightStuck(e,t){const i=this.activeSessionId??"";d.error("codex-adapter",`${t}; restarting adapter and replaying event: ${e}`),this.clearActive({runPendingAutoCompact:!1,emitEventDone:!1}),this.emit("internalError",{eventId:e,sessionId:i,errorMsg:t})}async inspectCurrentTurnProgress(){if(!this.threadId||!this.currentTurnId)return"unknown";try{return await Se(this.threadId,this.currentTurnId,this.codexHome)}catch{return"unknown"}}async checkSessionActivitySince(e){if(!this.threadId)return!1;try{return await Ee(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"}normalizeAgentMessagePhase(e){return typeof e!="string"?void 0:e.trim().toLowerCase()||void 0}resolveAgentMessagePhase(e,t){return this.normalizeAgentMessagePhase(t)??(e?this.agentMessagePhases.get(e):void 0)}extractAgentMessageText(e){return e?typeof e.text=="string"&&e.text.length>0?e.text:typeof e.message=="string"&&e.message.length>0?e.message:Array.isArray(e.content)&&e.content.map(i=>{if(typeof i=="string")return i;if(!i||typeof i!="object"||Array.isArray(i))return"";const s=i;return typeof s.text=="string"?s.text:""}).join("")||void 0:void 0}recordDeliveredAgentMessage(e,t){this.turnHasVisibleOutput=!0,e&&this.deliveredAgentMessageIds.add(e),t==="final_answer"&&(this.turnSawVisibleFinalAnswer=!0,this.turnHasDeliveredFinalAnswer=!0)}shouldSuppressAgentMessageDeltaDuringToolRun(e,t){return t==="final_answer"||this.inFlightToolOps<=0?!1:(d.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 et={allow:"accept","allow-once":"accept","allow-always":"acceptForSession",deny:"deny"};function ae(a){const e=a?.agentName?.trim()??"",t=a?.introduction?.trim()??"";if(!e&&!t)return;const i=["[system-identity]"];return e&&i.push(`Your name is "${e}".`),t&&i.push(`Your self-introduction: ${t}`),i.push("Treat this as an out-of-band instruction; do not echo or repeat it in your replies."),i.push("[/system-identity]"),{agentName:e,instructions:i.join(`
|
|
12
|
-
`)}}function
|
|
11
|
+
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},c=at(this.collaborationMode,this.model);c&&(o.collaborationMode=c),this.reasoningEffort&&(o.effort=this.reasoningEffort);const p=this.effectiveServiceTier();p&&(o.serviceTier=p),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.effectiveServiceTier()?{serviceTier:this.effectiveServiceTier()}:{}});this.updateModelFromThreadResult(e),this.threadResumePending=!1}catch{this.threadId=null,this.needsHistoryInjection=!0,await this.startNewThread(),this.threadResumePending=!1}}async startNewThread(){const e=ae(this.callbacks.getAgentProfile?.()),t={approvalPolicy:this.approvalPolicy,model:this.model,cwd:this.cwd,experimentalRawEvents:!1,persistExtendedHistory:!1,...this.reasoningEffort?{effort:this.reasoningEffort}:{},...this.effectiveServiceTier()?{serviceTier:this.effectiveServiceTier()}:{}};try{let i;if(e&&!this.legacyDeveloperInstructionsUnsupported)try{i=await this.sendRequest("thread/start",{...t,developerInstructions:e.instructions})}catch(n){if(!st(n))throw n;this.legacyDeveloperInstructionsUnsupported=!0,d.warn("codex-adapter","Codex app-server does not support thread/start.developerInstructions; falling back to first-turn identity input"),i=await this.sendRequest("thread/start",t)}else i=await this.sendRequest("thread/start",t);const s=rt(i);if(!s)throw new Error("Codex thread id is missing in thread/start result");this.threadId=s,this.identityInputInjectedThreadId=null,this.profileIdentityRefreshPending=!1,this.updateModelFromThreadResult(i),this.threadResumePending=!1,this.persistThreadId(s)}catch(i){const s=i instanceof Error?i.message:String(i);throw new Error(`Failed to start Codex thread: ${s}`)}}updateModelFromThreadResult(e){if(this.model)return;const t=ot(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:M(this.collaborationMode)??void 0,reasoningEffort:this.reasoningEffort,serviceTier:this.serviceTier,sandboxMode:this.sandboxMode})}async loadHistoryForInjection(e){const t=this.callbacks.getConversationLog();if(!t)return[];try{const i=await t.readHistory(e,Je),s=[];for(const n of i){const r=(n.content??"").slice(0,Ye);n.direction==="inbound"?s.push({type:"text",text:r,text_elements:[]}):n.direction==="outbound"&&s.push({type:"assistant",text:r,text_elements:[]})}return s}catch(i){return d.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=I(t.session_id,t.sessionId)??this.activeSessionId??"";if(!n)return;const r=this.threadId,o=new B(r),c={adapterSessionId:r,text:""};this.activeEventId=s,this.activeSessionId=n,this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.agentMessagePhases.clear(),this.deliveredAgentMessageIds.clear(),this.turnSawVisibleFinalAnswer=!1,this.turnHasDeliveredFinalAnswer=!1,this.codexSequence=0,this.runTurn(c,o,s,n).catch(p=>{d.error("codex-adapter",`Post-approval turn failed: ${p}`),this.sendEventResultAfterFlushing(s,"failed",p instanceof Error?p.message:String(p)),this.clearActive()}),this.resetIdleTimer(s)}clearActive(e){const t=this.activeEventId;if(this.flushCodexDeltaBuffer(),this.stopComposing(),this.activeEventId=null,this.activeSessionId=null,this.currentTurnId=null,this.visibleAgentMessageIds.clear(),this.hiddenAgentMessageIds.clear(),this.agentMessagePhases.clear(),this.deliveredAgentMessageIds.clear(),this.turnSawVisibleFinalAnswer=!1,this.turnHasDeliveredFinalAnswer=!1,this.inFlightToolOps=0,this.consecutivePingFailures=0,this.currentTurnStartedAt=0,this.preflightCheckComplete=!1,this.clearIdleTimer(),this.pendingApprovals.clear(),t&&e?.emitEventDone!==!1){const i=this.rawCaptureRelay;i?i.completeEvent(t).catch(s=>{d.warn("codex-adapter",`Raw API audit capture did not settle cleanly: ${s instanceof Error?s.message:String(s)}`)}).finally(()=>this.emit("eventDone",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);d.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.activityGeneration+=1,this.lastIdleCheckGeneration=this.activityGeneration,this.idleNoProgressCount=0,this.consecutivePingFailures=0,this.armIdleTimer(e)}armIdleTimer(e,t=Number.POSITIVE_INFINITY){this.clearIdleTimer();const i=Date.now(),s=this.inFlightToolOps>0?Be:qe,n=this.turnInactivityTimeoutMs===null?Number.POSITIVE_INFINITY:this.lastProgressAt+this.turnInactivityTimeoutMs-i,r=this.currentTurnStartedAt>0&&!this.preflightCheckComplete?this.currentTurnStartedAt+j-i:Number.POSITIVE_INFINITY,o=Math.max(0,Math.min(s,n,r,t));this.idleTimer=setTimeout(()=>{this.onIdleTimeout(e,o)},o)}async onIdleTimeout(e,t){if(this.activeEventId!==e)return;const i=this.lastIdleCheckAt,s=this.lastIdleCheckGeneration,n=this.ping(We).catch(()=>!1),r=this.checkSessionActivitySince(i),[o,c]=await Promise.all([n,r]);if(this.activeEventId!==e)return;const p=this.activityGeneration>s;if(this.lastIdleCheckAt=Date.now(),this.lastIdleCheckGeneration=this.activityGeneration,!this.preflightCheckComplete&&this.currentTurnStartedAt>0&&Date.now()-this.currentTurnStartedAt>=j){const m=this.activityGeneration,v=await this.inspectCurrentTurnProgress();if(this.activeEventId!==e)return;if(this.activityGeneration>m)this.preflightCheckComplete=!0;else if(v==="task_started_only"){this.declareRecoverablePreflightStuck(e,`Codex preflight stalled for ${Math.round(j/1e3)}s before model execution`);return}else v==="unknown"?this.currentTurnStartedAt=Date.now():this.preflightCheckComplete=!0}if(p||c){c&&(d.info("codex-adapter",`Idle timer: no stream output but rollout still being written, continuing: ${e}`),this.lastProgressAt=Date.now()),this.idleNoProgressCount=0,this.consecutivePingFailures=0,this.armIdleTimer(e);return}const h=Date.now()-this.lastProgressAt;if(this.turnInactivityTimeoutMs!==null&&h>=this.turnInactivityTimeoutMs){d.error("codex-adapter",`Turn inactive ${Math.round(h/1e3)}s \u2265 cap ${Math.round(this.turnInactivityTimeoutMs/1e3)}s, declaring stuck: ${e}`),this.declareStuck(e,`turn inactivity timeout after ${Math.round(h/1e3)}s with no Codex activity`);return}if(!o){if(this.consecutivePingFailures+=1,this.consecutivePingFailures<te){d.warn("codex-adapter",`Agent idle ${t/1e3}s and ping failed (${this.consecutivePingFailures}/${te}); retrying liveness probe: ${e}`),this.armIdleTimer(e,Ve);return}d.error("codex-adapter",`Agent idle ${t/1e3}s and ping failed ${this.consecutivePingFailures}x, declaring stuck: ${e}`),this.declareStuck(e,`agent idle ${t/1e3}s, ping failed ${this.consecutivePingFailures}x`);return}this.consecutivePingFailures=0,this.idleNoProgressCount++,d.info("codex-adapter",`Idle timer: ping ok, no stream progress (cycle=${this.idleNoProgressCount}), keeping active turn alive${this.turnInactivityTimeoutMs===null?"":` until inactivity cap (${Math.round(this.turnInactivityTimeoutMs/6e4)}min)`}: ${e}`),this.armIdleTimer(e)}declareStuck(e,t){this.sendEventResultAfterFlushing(e,"failed",t),this.clearActive(),this.emit("stuck")}declareRecoverablePreflightStuck(e,t){const i=this.activeSessionId??"";d.error("codex-adapter",`${t}; restarting adapter and replaying event: ${e}`),this.clearActive({runPendingAutoCompact:!1,emitEventDone:!1}),this.emit("internalError",{eventId:e,sessionId:i,errorMsg:t})}async inspectCurrentTurnProgress(){if(!this.threadId||!this.currentTurnId)return"unknown";try{return await Me(this.threadId,this.currentTurnId,this.codexHome)}catch{return"unknown"}}async checkSessionActivitySince(e){if(!this.threadId)return!1;try{return await Re(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"}normalizeAgentMessagePhase(e){return typeof e!="string"?void 0:e.trim().toLowerCase()||void 0}resolveAgentMessagePhase(e,t){return this.normalizeAgentMessagePhase(t)??(e?this.agentMessagePhases.get(e):void 0)}extractAgentMessageText(e){return e?typeof e.text=="string"&&e.text.length>0?e.text:typeof e.message=="string"&&e.message.length>0?e.message:Array.isArray(e.content)&&e.content.map(i=>{if(typeof i=="string")return i;if(!i||typeof i!="object"||Array.isArray(i))return"";const s=i;return typeof s.text=="string"?s.text:""}).join("")||void 0:void 0}recordDeliveredAgentMessage(e,t){this.turnHasVisibleOutput=!0,e&&this.deliveredAgentMessageIds.add(e),t==="final_answer"&&(this.turnSawVisibleFinalAnswer=!0,this.turnHasDeliveredFinalAnswer=!0)}shouldSuppressAgentMessageDeltaDuringToolRun(e,t){return t==="final_answer"||this.inFlightToolOps<=0?!1:(d.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 it={allow:"accept","allow-once":"accept","allow-always":"acceptForSession",deny:"deny"};function ae(a){const e=a?.agentName?.trim()??"",t=a?.introduction?.trim()??"";if(!e&&!t)return;const i=["[system-identity]"];return e&&i.push(`Your name is "${e}".`),t&&i.push(`Your self-introduction: ${t}`),i.push("Treat this as an out-of-band instruction; do not echo or repeat it in your replies."),i.push("[/system-identity]"),{agentName:e,instructions:i.join(`
|
|
12
|
+
`)}}function st(a){return a instanceof Error?/unknown\s+(?:field|parameter|property)[^\n]*(?:developerInstructions|developer_instructions)/i.test(a.message):!1}function nt(a){return a&&a.length>0?[...a]:["app-server"]}function u(a){if(typeof a!="string")return;const e=a.trim();return e||void 0}function rt(a){if(!a||typeof a!="object")return null;const e=a,t=e.thread&&typeof e.thread=="object"?e.thread:void 0;return I(u(e.threadId),u(e.threadID),u(t?.id))??null}function ot(a){return!a||typeof a!="object"?null:u(a.model)??null}function M(a){const e=a?.trim().toLowerCase();return e==="default"||e==="plan"?e:null}function at(a,e){const t=M(a),i=u(e);if(!(!t||!i))return{mode:t,settings:{model:i}}}function dt(a){if(!Array.isArray(a))return[];const e=[];for(const t of a){if(typeof t=="string"){const r=t.trim();r&&e.push(ht(r,k(r)));continue}if(!t||typeof t!="object")continue;const i=t,s=I(u(i.id),u(i.model_id),u(i.modelId),u(i.value));if(!s)continue;const n=I(u(i.displayName),u(i.display_name),u(i.name),u(i.label))??k(s);e.push({id:s,displayName:n,defaultReasoningEffort:u(i.defaultReasoningEffort)??null,supportedReasoningEfforts:H(i.supportedReasoningEfforts),defaultServiceTier:u(i.defaultServiceTier)??null,serviceTiers:U(i.serviceTiers),isDefault:i.isDefault===!0})}return e}function de(a){const e=a.toLowerCase().replace(/\/+$/,"");return!(e==="https://api.openai.com"||e==="https://api.openai.com/v1"||e.endsWith(".openai.com"))}async function ct(a,e){const i=`${a.replace(/\/+$/,"")}/models`,s={Accept:"application/json"};e&&(s.Authorization=`Bearer ${e}`);const n=new AbortController,r=setTimeout(()=>n.abort(),1e4);try{const o=await fetch(i,{headers:s,signal:n.signal});if(!o.ok)return[];const c=await o.json();return lt(c)}finally{clearTimeout(r)}}function lt(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,r=I(u(n.id),u(n.model));if(!r)continue;const o=I(u(n.displayName),u(n.display_name),u(n.name))??k(r);i.push({id:r,displayName:o,defaultReasoningEffort:u(n.defaultReasoningEffort)??null,supportedReasoningEfforts:H(n.supportedReasoningEfforts),defaultServiceTier:u(n.defaultServiceTier)??null,serviceTiers:U(n.serviceTiers),isDefault:n.isDefault===!0})}return i}function ut(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 r=I(u(n.id),u(n.model));if(!r)continue;const o=I(u(n.displayName),u(n.display_name),u(n.name))??k(r);i.push({id:r,displayName:o,defaultReasoningEffort:u(n.defaultReasoningEffort)??null,supportedReasoningEfforts:H(n.supportedReasoningEfforts),defaultServiceTier:u(n.defaultServiceTier)??null,serviceTiers:U(n.serviceTiers),isDefault:n.isDefault===!0})}return{models:i,nextCursor:u(e.nextCursor)??null}}function ce(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],defaultServiceTier:i.defaultServiceTier,serviceTiers:[...i.serviceTiers],isDefault:i.isDefault}))}return e}function ht(a,e){return{id:a,displayName:e,defaultReasoningEffort:null,supportedReasoningEfforts:[],defaultServiceTier:null,serviceTiers:[],isDefault:!1}}function H(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=u(t.reasoningEffort);i&&e.push(i)}return e}function U(a){if(!Array.isArray(a))return[];const e=[];for(const t of a){if(typeof t=="string"){const n=t.trim();n&&e.push({id:n,displayName:n,description:null});continue}if(!t||typeof t!="object")continue;const i=t,s=u(i.id);s&&e.push({id:s,displayName:I(u(i.name),u(i.displayName),u(i.display_name))??s,description:u(i.description)??null})}return e}function k(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 I(...a){for(const e of a)if(e!=null){if(typeof e=="string"&&!e.trim())continue;return e}}function le(a){return a.trim().replace(/[^a-zA-Z0-9._:-]+/g,"_")}function ue(a,e){switch(a){case"turn/completed":return;case"item/agentMessage/delta":{const t=e?.params??{};return typeof t.delta!="string"||t.delta.length===0?void 0:{params:{delta:t.delta}}}case"item/completed":{const i=(e?.params??{}).item;if(!i||typeof i!="object"||i.type!=="commandExecution")return;const s=pt(i.command);return{params:{item:{type:"commandExecution",...s!==void 0?{command:s}:{},...i.exitCode!==void 0?{exitCode:i.exitCode}:{},...i.durationMs!==void 0?{durationMs:i.durationMs}:{}}}}}case"item/permissions/requestApproval":return q(e,"permission");case"item/commandExecution/requestApproval":return q(e,"exec");case"item/fileChange/requestApproval":return q(e,"file");default:return}}function q(a,e){if(a==null||typeof a!="object")return;const t=a.params??{};if(t==null||typeof t!="object"||Array.isArray(t))return;const i={},s=(...r)=>{for(const o of r)t[o]!==void 0&&(i[o]=t[o])};e==="permission"?s("threadId","turnId","itemId","reason","permissions"):e==="exec"?s("command","commandLine","command_line","argv","args","availableDecisions","cwd","workingDirectory","working_directory"):s("path","filePath","file_path","targetPath","target_path","paths","files","availableDecisions","cwd","workingDirectory","working_directory");const n={params:i};return a.id!==void 0&&(n.id=a.id),typeof a.method=="string"&&a.method&&(n.method=a.method),n}function pt(a){if(typeof a!="string")return;const e=a.trim();if(e)return e.length<=ie?e:e.slice(0,ie-se.length)+se}class B extends Y{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){d.warn("codex-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}function ft(a){return["cannot steer a compact turn","turn not found","turn already completed","no active turn"].some(t=>a.includes(t))}export{$ as CodexAdapter,ue as trimCodexPayloadForWire};
|