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