UNPKG

grix-connector

Version:

Connect local AI coding agents (Claude, Codex, Gemini, Qwen, DeepSeek, Cursor, OpenCode, Pi, OpenHuman, Reasonix) to the Grix scheduling platform. Also serves as an OpenClaw plugin for Grix channel transport.

10 lines (7 loc) 15.7 kB
import{EventEmitter as I}from"node:events";import{stat as w}from"node:fs/promises";import{existsSync as y,mkdirSync as b,readFileSync as E,writeFileSync as $}from"node:fs";import{join as m,resolve as P,dirname as A}from"node:path";import{homedir as _}from"node:os";import{fileURLToPath as C}from"node:url";import{resolveCommandPath as O,spawnCommand as M,killProcessGroup as T,hasChildProcesses as F}from"../../core/runtime/spawn.js";import{InternalApiServer as B}from"../../core/mcp/internal-api-server.js";import{syncDefaultSkillsToDir as j}from"../../default-skills/index.js";import{buildSimpleProbeReport as D}from"../shared/probe-util.js";import{OpenCodeTransport as N}from"./opencode-transport.js";import{log as n}from"../../core/log/index.js";import{splitTextForAibotProtocol as S}from"../../core/protocol/index.js";class H extends I{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){n.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const L=200,U=2e3,J=12e4,G=6e5,x=3e4,q="127.0.0.1",X=0,W=1e3;class ae extends I{type="opencode";config;callbacks;options;process=null;transport=new N;alive=!1;stopped=!1;internalApi=null;sessions=new Map;activeRun=null;completedEvents=new Set;clientMsgSeq=0;idleTimer=null;pendingPermissions=new Map;permissionHandler=null;constructor(e,s,t){super(),this.config=e,this.callbacks=s,this.options=t??{}}async start(){await this.startInternalApiAndInjectMcp();const e=this.options.hostname??q,s=this.options.port??X,t=await this.spawnAndWait(e,s),i=this.resolveCwd();await this.transport.connect(t,i),this.transport.on("event",o=>this.handleSseEvent(o)),n.info("opencode-adapter",`Ready (pid=${this.process?.pid}, url=${t})`)}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.transport.disconnect(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.process){const e=this.process;try{T(e,"SIGTERM")}catch{}const s=setTimeout(()=>{try{T(e,"SIGKILL")}catch{}},5e3);e.on("exit",()=>clearTimeout(s)),this.process=null}}isAlive(){return this.alive}async createSession(e){const s=e.cwd??this.resolveCwd(),t=await this.transport.createSession({title:`grix-${Date.now()}`});return this.sessions.set(t.id,{ocSessionId:t.id,cwd:s}),n.info("opencode-adapter",`Created OC session ${t.id} for cwd=${s}`),t.id}async resumeSession(e,s){const t=this.sessions.get(e);if(t?.ocSessionId)try{await this.transport.getSession(t.ocSessionId)}catch{n.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, will create new on next prompt`),t.ocSessionId=""}}async destroySession(e){try{await this.transport.deleteSession(e)}catch{}this.sessions.delete(e)}sendPrompt(e){const s=new H(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(t=>{s.emitError(t instanceof Error?t:new Error(String(t)))}),s}async cancel(e){if(this.activeRun)try{await this.transport.abortSession(this.activeRun.ocSessionId)}catch{}}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){n.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){n.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}this.activeRun&&this.activeRun.eventId!==s&&(n.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),n.info("opencode-adapter",`prompt: event=${s} session=${t}`),this.callbacks.sendEventAck(s,t),this.startRun(s,t),this.startComposing(t),this.resetIdleTimer();const o=this.buildPromptTextFromEvent(e);this.sendOcPrompt(t,o).catch(r=>{n.error("opencode-adapter",`prompt_async failed: ${r}`),this.finishRun("failed",String(r))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(n.info("opencode-adapter",`stop: event=${e}`),this.transport.abortSession(this.activeRun.ocSessionId).catch(()=>{}),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.sessions.size}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=P(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 hasBackgroundWork(){const e=this.process?.pid;return e?F(e,[e]):!1}async probe(e){const s=this.getStatus();return D(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){try{this.internalApi=new B,this.internalApi.setInvokeHandler(async(p,h)=>this.callbacks.agentInvoke(p,h)),await this.internalApi.start(0),n.info("opencode-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),s=process.env.XDG_CONFIG_HOME||m(_(),".config"),t=m(s,"opencode","opencode.json");b(A(t),{recursive:!0});let i={};try{y(t)&&(i=JSON.parse(E(t,"utf8")))}catch{}const o=i.mcp&&typeof i.mcp=="object"?i.mcp:{};o[e.name]={type:"local",command:[e.command,...e.args??[]],enabled:!0},i.mcp=o,$(t,`${JSON.stringify(i,null,2)} `,"utf8"),n.info("opencode-adapter",`MCP config injected into ${t}`);const r=m(s,"opencode","skills"),c=j(r);c.length>0&&n.info("opencode-adapter",`Synced connector skills to ${r}: [${c.join(", ")}]`)}catch(e){n.warn("opencode-adapter",`Failed to inject MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`)}}async handleLocalAction(e){const{action_type:s}=e;return s==="exec_approve"||s==="exec_reject"||s==="permission_approve"||s==="permission_reject"?this.handlePermissionAction(e):{handled:!1,kind:""}}bindSession(e,s){if(n.info("opencode-adapter",`bindSession: ${e} \u2192 ${s}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:s});else{const t=this.sessions.get(e);t.cwd=s}}async spawnAndWait(e,s){const t=this.resolveCwd();try{if(!(await 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 r=this.config.command||"opencode",p=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${s}`],h={...process.env,...this.config.env},u={};if(this.options.model){const[a,...l]=this.options.model.split("/");a&&l.length>0&&(u.agents={coder:{model:l.join("/"),maxTokens:16e3}})}this.options.permissionPolicy==="fullAuto"&&(u.permission={edit:"allow",bash:"allow",webfetch:"allow",doom_loop:"allow",external_directory:"allow"}),Object.keys(u).length>0&&(h.OPENCODE_CONFIG_CONTENT=JSON.stringify(u));const v=O(r,typeof h.PATH=="string"?h.PATH:void 0);n.info("opencode-adapter",`Spawning: ${v} ${p.join(" ")} (cwd=${t})`),this.process=M(v,p,{env:h,cwd:t}).process;let g="",d=!1;const f=setTimeout(()=>{d||(d=!0,o(new Error(`opencode serve did not start after ${x/1e3}s`)))},x);this.process.stdout?.on("data",a=>{if(g+=a.toString(),!d)for(const l of g.split(` `)){const R=l.match(/opencode server listening on (https?:\/\/[^\s]+)/);if(R){clearTimeout(f),d=!0,this.alive=!0,i(R[1]);return}}}),this.process.stderr?.on("data",a=>{const l=a.toString().trim();l&&n.info("opencode-adapter",`[stderr] ${l}`)}),this.process.on("error",a=>{n.error("opencode-adapter",`Spawn error: ${a.message}`),clearTimeout(f),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${a.message}`),this.clearRun()),d?this.stopped||this.emit("exit",1):(d=!0,o(a))}),this.process.on("exit",a=>{n.info("opencode-adapter",`Process exited (code=${a})`),clearTimeout(f),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${a})`),this.clearRun()),d?this.stopped||this.emit("exit",a??1):(d=!0,o(new Error(`opencode serve exited with code ${a}`)))})})}async ensureOcSession(e){const s=this.sessions.get(e);if(s?.ocSessionId)try{return await this.transport.getSession(s.ocSessionId),s.ocSessionId}catch{n.warn("opencode-adapter",`OC session ${s.ocSessionId} gone, creating new`),s.ocSessionId=""}const t=s?.cwd??this.resolveCwd(),i=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(r=>{n.warn("opencode-adapter",`Auto-approve failed: ${r}`)});return}this.stopIdleTimer(),this.pendingPermissions.set(s,{permissionId:e.id,ocSessionId:i});const o=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(s,t,e.type,o)}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const s=this.pendingPermissions.get(this.activeRun.eventId);if(!s)return{handled:!1,kind:""};const{permissionId:t,ocSessionId:i}=s,r=e.action_type==="exec_approve"||e.action_type==="permission_approve"?"once":"reject";return this.pendingPermissions.delete(this.activeRun.eventId),this.transport.respondPermission(i,t,r).then(()=>{n.info("opencode-adapter",`Permission ${r}: ${t}`),this.resetIdleTimer()}).catch(c=>{n.warn("opencode-adapter",`Permission response failed: ${c}`)}),{handled:!0,kind:"permission"}}startRun(e,s){this.activeRun={eventId:e,sessionId:s,ocSessionId:"",chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null}}finishRun(e,s){const t=this.activeRun;if(!t)return;if(this.completedEvents.add(t.eventId),this.completedEvents.size>W){const c=[...this.completedEvents].slice(-500);this.completedEvents=new Set(c)}this.activeRun=null,this.stopComposing(),this.stopIdleTimer();const i=++t.chunkSeq,o=t.clientMsgId;e==="failed"&&s&&this.callbacks.sendRunError(t.eventId,t.sessionId,s);const r=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t.eventId,t.sessionId,i,o).then(()=>{this.callbacks.sendEventResult(t.eventId,e,s)}).catch(()=>{this.callbacks.sendStreamChunk(t.eventId,t.sessionId,"",i,!0,o),this.callbacks.sendEventResult(t.eventId,e,s)}):(this.callbacks.sendStreamChunk(t.eventId,t.sessionId,"",i,!0,o),this.callbacks.sendEventResult(t.eventId,e,s))};if(t.textBuffer){this.stopTextFlush();for(const c of S(t.textBuffer))t.chunkSeq++,this.callbacks.sendStreamChunk(t.eventId,t.sessionId,c,t.chunkSeq,!1,t.clientMsgId);t.textBuffer=""}r(),this.emit("eventDone",t.eventId)}clearRun(){this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const e=this.activeRun?.eventId;this.activeRun=null,e&&this.emit("eventDone",e)}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=U){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},L))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const e of S(this.activeRun.textBuffer))this.activeRun.chunkSeq++,this.callbacks.sendStreamChunk(this.activeRun.eventId,this.activeRun.sessionId,e,this.activeRun.chunkSeq,!1,this.activeRun.clientMsgId);this.activeRun.textBuffer=""}}stopTextFlush(){this.activeRun?.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null)}startComposing(e){}stopComposing(){}resetIdleTimer(){if(this.stopIdleTimer(),this.stopped||!this.activeRun)return;const e=this.pendingPermissions.has(this.activeRun.eventId)?G:J;this.idleTimer=setTimeout(()=>{n.error("opencode-adapter","Idle timeout \u2014 emitting exit for respawn"),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed","idle timeout"),this.clearRun()),this.emit("exit",-1)},e)}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveCwd(){const e=(this.config.options??{}).cwd;return typeof e=="string"&&e?e:process.cwd()}buildPromptText(e){let s=e.text;return e.contextMessages&&e.contextMessages.length>0&&(s=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(` `)+` `+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(` `)+` `+s)}catch{}return s}}export{ae as OpenCodeAdapter};