grix-connector 3.15.2 → 3.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
- import{EventEmitter as I}from"node:events";import{stat as w}from"node:fs/promises";import{existsSync as y,mkdirSync as P,readFileSync as C,writeFileSync as b}from"node:fs";import{join as v,resolve as E,dirname as $}from"node:path";import{homedir as A}from"node:os";import{fileURLToPath as _}from"node:url";import{resolveCommandPath as O,spawnCommand as M,killProcessGroup as T,hasChildProcesses as F}from"../../core/runtime/spawn.js";import{InternalApiServer as D}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as B}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as j}from"../../default-skills/index.js";import{buildSimpleProbeReport as N}from"../shared/probe-util.js";import{buildOpencodeConfigContent as H}from"./opencode-config.js";import{OpenCodeTransport as U}from"./opencode-transport.js";import{log as n}from"../../core/log/index.js";import{splitTextForAibotProtocol as S}from"../../core/protocol/index.js";class L extends I{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){n.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const J=200,G=2e3,q=12e4,z=6e5,k=3e4,X="127.0.0.1",W=0,K=1e3;class he extends I{type="opencode";config;callbacks;options;identity;process=null;transport=new U;alive=!1;stopped=!1;internalApi=null;sessions=new Map;activeRun=null;completedEvents=new Set;clientMsgSeq=0;idleTimer=null;toolCallsInFlight=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;permissionHandler=null;constructor(e,t,s){super(),this.config=e,this.callbacks=t,this.options=s??{},this.identity=new B("opencode-adapter",t.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}async start(){await this.startInternalApiAndInjectMcp();const e=this.options.hostname??X,t=this.options.port??W,s=await this.spawnAndWait(e,t),i=this.resolveCwd();await this.transport.connect(s,i),this.transport.on("event",o=>this.handleSseEvent(o)),n.info("opencode-adapter",`Ready (pid=${this.process?.pid}, url=${s})`)}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 t=setTimeout(()=>{try{T(e,"SIGKILL")}catch{}},5e3);e.on("exit",()=>clearTimeout(t)),this.process=null}}isAlive(){return this.alive}async createSession(e){const t=e.cwd??this.resolveCwd(),s=await this.transport.createSession({title:`grix-${Date.now()}`});return this.sessions.set(s.id,{ocSessionId:s.id,cwd:t}),n.info("opencode-adapter",`Created OC session ${s.id} for cwd=${t}`),s.id}async resumeSession(e,t){const s=this.sessions.get(e);if(s?.ocSessionId)try{await this.transport.getSession(s.ocSessionId)}catch{n.warn("opencode-adapter",`OC session ${s.ocSessionId} gone, will create new on next prompt`),s.ocSessionId=""}}async destroySession(e){try{await this.transport.deleteSession(e)}catch{}this.sessions.delete(e),this.identity.forgetSession(e)}sendPrompt(e){const t=new L(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(s=>{t.emitError(s instanceof Error?s:new Error(String(s)))}),t}async cancel(e){if(this.activeRun)try{await this.transport.abortSession(this.activeRun.ocSessionId)}catch{}}deliverInboundEvent(e){const{event_id:t,session_id:s,content:i}=e;if(this.completedEvents.has(t)){n.info("opencode-adapter",`Dropping duplicate event ${t}`),this.callbacks.sendEventAck(t,s),this.callbacks.sendEventResult(t,"responded");return}if(!this.alive){n.warn("opencode-adapter",`Dropping event ${t}: process not alive`),this.callbacks.sendEventAck(t,s),this.callbacks.sendEventResult(t,"failed","Agent process not running");return}this.activeRun&&this.activeRun.eventId!==t&&(n.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${t}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),n.info("opencode-adapter",`prompt: event=${t} session=${s}`),this.callbacks.sendEventAck(t,s),this.startRun(t,s),this.startComposing(s),this.resetIdleTimer();const o=this.buildPromptTextFromEvent(e);this.sendOcPrompt(s,o).catch(r=>{n.error("opencode-adapter",`prompt_async failed: ${r}`),this.finishRun("failed",String(r))})}deliverStopEvent(e,t){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=E(_(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 t=this.getStatus();return N(this.config.command||"opencode",{alive:t.alive,busy:t.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){try{this.internalApi=new D,this.internalApi.setInvokeHandler(async(h,l,f,p)=>this.callbacks.agentInvoke(h,l,p)),await this.internalApi.start(0),n.info("opencode-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),t=process.env.XDG_CONFIG_HOME||v(A(),".config"),s=v(t,"opencode","opencode.json");P($(s),{recursive:!0});let i={};try{y(s)&&(i=JSON.parse(C(s,"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,b(s,`${JSON.stringify(i,null,2)}
2
- `,"utf8"),n.info("opencode-adapter",`MCP config injected into ${s}`);const r=v(t,"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:t}=e;return t==="exec_approve"||t==="exec_reject"||t==="permission_approve"||t==="permission_reject"?this.handlePermissionAction(e):{handled:!1,kind:""}}bindSession(e,t){if(n.info("opencode-adapter",`bindSession: ${e} \u2192 ${t}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:t});else{const s=this.sessions.get(e);s.cwd=t}}async spawnAndWait(e,t){const s=this.resolveCwd();try{if(!(await w(s)).isDirectory())throw new Error(`Bound path is not a directory: ${s}`)}catch(i){throw String(i?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${s}. Please rebind with /grix open <valid-directory>.`):i}return new Promise((i,o)=>{const r=this.config.command||"opencode",h=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${t}`],l={...process.env,...this.config.env},f=H({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider});f&&(l.OPENCODE_CONFIG_CONTENT=JSON.stringify(f));const p=O(r,typeof l.PATH=="string"?l.PATH:void 0);n.info("opencode-adapter",`Spawning: ${p} ${h.join(" ")} (cwd=${s})`),this.process=M(p,h,{env:l,cwd:s}).process;let g="",d=!1;const m=setTimeout(()=>{d||(d=!0,o(new Error(`opencode serve did not start after ${k/1e3}s`)))},k);this.process.stdout?.on("data",a=>{if(g+=a.toString(),!d)for(const u of g.split(`
3
- `)){const R=u.match(/opencode server listening on (https?:\/\/[^\s]+)/);if(R){clearTimeout(m),d=!0,this.alive=!0,i(R[1]);return}}}),this.process.stderr?.on("data",a=>{const u=a.toString().trim();u&&n.info("opencode-adapter",`[stderr] ${u}`)}),this.process.on("error",a=>{n.error("opencode-adapter",`Spawn error: ${a.message}`),clearTimeout(m),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(m),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 t=this.sessions.get(e);if(t?.ocSessionId)try{return await this.transport.getSession(t.ocSessionId),t.ocSessionId}catch{n.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, creating new`),t.ocSessionId=""}const s=t?.cwd??this.resolveCwd(),i=this.options.bindingStore?.getAcpSessionId(e);if(i)try{return await this.transport.getSession(i),this.sessions.set(e,{ocSessionId:i,cwd:s}),n.info("opencode-adapter",`Resumed OC session ${i} for aibot=${e}`),i}catch{n.warn("opencode-adapter",`Persisted OC session ${i} gone, creating new`)}const o=await this.transport.createSession({title:`grix-${e.slice(-8)}`});return this.sessions.set(e,{ocSessionId:o.id,cwd:s}),this.options.bindingStore?.setAcpSessionId(e,o.id),n.info("opencode-adapter",`Created OC session ${o.id} for aibot=${e}`),o.id}async sendOcPrompt(e,t){const s=await this.ensureOcSession(e);this.activeRun&&(this.activeRun.ocSessionId=s),await this.transport.sendPromptAsync(s,{parts:[{type:"text",text:t}]})}handleSseEvent(e){if(!this.stopped)switch(this.updateToolInFlight(e),this.resetIdleTimer(),e.type){case"message.part.updated":{if(!this.activeRun)break;const t=e.part,s=e.delta;if(t.type==="text"){const i=s||t.text;i&&this.acceptAssistantPartText(t.messageID,"text",i)}else t.type==="reasoning"?s&&this.acceptAssistantPartText(t.messageID,"reasoning",s):t.type==="tool"&&this.handleToolPartUpdate(t,s);break}case"message.updated":{if(!this.activeRun)break;const t=e.info;if(this.rememberMessageRole(t),t.role==="assistant"){const s=t;this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.resolveCwd(),{model_provider:s.providerID,model_id:s.modelID}),s.error&&n.warn("opencode-adapter",`Message error: ${JSON.stringify(s.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 t=e.error,s=t?typeof t=="object"&&"message"in t?t.message:JSON.stringify(t):"unknown session error";n.error("opencode-adapter",`Session error: ${s}`),this.flushTextBuffer(),this.finishRun("failed",s);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}}updateToolInFlight(e){if(e.type!=="message.part.updated")return;const t=e.part;if(t?.type!=="tool"||!t.callID)return;const s=t.state?.status;s==="pending"||s==="running"?this.toolCallsInFlight.add(t.callID):(s==="completed"||s==="error")&&this.toolCallsInFlight.delete(t.callID)}rememberMessageRole(e){const t=typeof e.id=="string"?e.id.trim():"";t&&(e.role!=="user"&&e.role!=="assistant"||(this.messageRoles.set(t,e.role),this.flushOrDropPendingParts(t,e.role)))}acceptAssistantPartText(e,t,s){if(!this.activeRun||!s)return;const i=typeof e=="string"?e.trim():"";if(!i)return;const o=this.messageRoles.get(i);if(o==="user")return;if(o==="assistant"){this.emitAssistantPartChunk(t,s);return}const r=this.pendingPartChunks.get(i)??[];r.push({kind:t,value:s}),this.pendingPartChunks.set(i,r)}flushOrDropPendingParts(e,t){const s=this.pendingPartChunks.get(e);if(this.pendingPartChunks.delete(e),!(!s||s.length===0)&&t==="assistant")for(const i of s)this.emitAssistantPartChunk(i.kind,i.value)}emitAssistantPartChunk(e,t){if(!(!this.activeRun||!t)){if(e==="reasoning"){this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,t);return}this.appendText(t)}}clearMessageRoleState(){this.messageRoles.clear(),this.pendingPartChunks.clear()}handleToolPartUpdate(e,t){if(!this.activeRun)return;const s=e.state;switch(s.status){case"pending":case"running":{this.flushTextBuffer();const i=JSON.stringify(s.input??{});this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,i);break}case"completed":{const i=s.output??"";this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,i);break}case"error":{const i=s.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:t,sessionId:s,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(t,{permissionId:e.id,ocSessionId:i});const o=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(t,s,e.type,o)}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const t=this.pendingPermissions.get(this.activeRun.eventId);if(!t)return{handled:!1,kind:""};const{permissionId:s,ocSessionId:i}=t,r=e.action_type==="exec_approve"||e.action_type==="permission_approve"?"once":"reject";return this.pendingPermissions.delete(this.activeRun.eventId),this.transport.respondPermission(i,s,r).then(()=>{n.info("opencode-adapter",`Permission ${r}: ${s}`),this.resetIdleTimer()}).catch(c=>{n.warn("opencode-adapter",`Permission response failed: ${c}`)}),{handled:!0,kind:"permission"}}startRun(e,t){this.activeRun={eventId:e,sessionId:t,ocSessionId:"",chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null}}finishRun(e,t){const s=this.activeRun;if(!s)return;if(this.completedEvents.add(s.eventId),this.completedEvents.size>K){const c=[...this.completedEvents].slice(-500);this.completedEvents=new Set(c)}this.activeRun=null,this.toolCallsInFlight.clear(),this.clearMessageRoleState(),this.stopComposing(),this.stopIdleTimer();const i=++s.chunkSeq,o=s.clientMsgId;e==="failed"&&t&&this.callbacks.sendRunError(s.eventId,s.sessionId,t);const r=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(s.eventId,s.sessionId,o).then(()=>{this.callbacks.sendEventResult(s.eventId,e,t)}).catch(()=>{this.callbacks.sendStreamChunk(s.eventId,s.sessionId,"",i,!0,o),this.callbacks.sendEventResult(s.eventId,e,t)}):(this.callbacks.sendStreamChunk(s.eventId,s.sessionId,"",i,!0,o),this.callbacks.sendEventResult(s.eventId,e,t))};if(s.textBuffer){this.stopTextFlush();for(const c of S(s.textBuffer))s.chunkSeq++,this.callbacks.sendStreamChunk(s.eventId,s.sessionId,c,s.chunkSeq,!1,s.clientMsgId);s.textBuffer=""}r(),this.emit("eventDone",s.eventId)}clearRun(){this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const e=this.activeRun?.eventId;this.activeRun=null,this.toolCallsInFlight.clear(),this.clearMessageRoleState(),e&&this.emit("eventDone",e)}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=G){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},J))}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)||this.toolCallsInFlight.size>0?z:q;this.idleTimer=setTimeout(()=>{n.error("opencode-adapter",`Idle timeout (${e/1e3}s, toolsInFlight=${this.toolCallsInFlight.size}) \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 t=e.text;return e.contextMessages&&e.contextMessages.length>0&&(t=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
1
+ import{EventEmitter as S}from"node:events";import{stat as E}from"node:fs/promises";import{existsSync as A,mkdirSync as P,readFileSync as b,writeFileSync as $}from"node:fs";import{join as g,resolve as C,dirname as _}from"node:path";import{homedir as F}from"node:os";import{fileURLToPath as M}from"node:url";import{resolveCommandPath as O,spawnCommand as D,killProcessGroup as T,hasChildProcesses as B}from"../../core/runtime/spawn.js";import{InternalApiServer as N}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as j}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as L}from"../../default-skills/index.js";import{buildSimpleProbeReport as H}from"../shared/probe-util.js";import{buildOpencodeConfigContent as U}from"./opencode-config.js";import{OpenCodeTransport as J}from"./opencode-transport.js";import{log as n}from"../../core/log/index.js";import{splitTextForAibotProtocol as x}from"../../core/protocol/index.js";class G extends S{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 X=200,z=2e3,q=12e4,V=90*1e3,k=1800*1e3,w=3e4,W="127.0.0.1",K=0,Y=1e3;function y(f){try{return process.kill(f,0),!0}catch(e){return e.code==="EPERM"}}class ue extends S{type="opencode";config;callbacks;options;identity;process=null;transport=new J;alive=!1;stopped=!1;internalApi=null;sessions=new Map;activeRun=null;completedEvents=new Set;clientMsgSeq=0;idleTimer=null;lastSseAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;permissionHandler=null;constructor(e,t,s){super(),this.config=e,this.callbacks=t,this.options=s??{},this.identity=new j("opencode-adapter",t.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}async start(){await this.startInternalApiAndInjectMcp();const e=this.options.hostname??W,t=this.options.port??K,s=await this.spawnAndWait(e,t),i=this.resolveCwd();await this.transport.connect(s,i),this.transport.on("event",o=>this.handleSseEvent(o)),n.info("opencode-adapter",`Ready (pid=${this.process?.pid}, url=${s})`)}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 t=setTimeout(()=>{try{T(e,"SIGKILL")}catch{}},5e3);e.on("exit",()=>clearTimeout(t)),this.process=null}}isAlive(){return this.alive}async createSession(e){const t=e.cwd??this.resolveCwd(),s=await this.transport.createSession({title:`grix-${Date.now()}`});return this.sessions.set(s.id,{ocSessionId:s.id,cwd:t}),n.info("opencode-adapter",`Created OC session ${s.id} for cwd=${t}`),s.id}async resumeSession(e,t){const s=this.sessions.get(e);if(s?.ocSessionId)try{await this.transport.getSession(s.ocSessionId)}catch{n.warn("opencode-adapter",`OC session ${s.ocSessionId} gone, will create new on next prompt`),s.ocSessionId=""}}async destroySession(e){try{await this.transport.deleteSession(e)}catch{}this.sessions.delete(e),this.identity.forgetSession(e)}sendPrompt(e){const t=new G(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(s=>{t.emitError(s instanceof Error?s:new Error(String(s)))}),t}async cancel(e){if(this.activeRun)try{await this.transport.abortSession(this.activeRun.ocSessionId)}catch{}}deliverInboundEvent(e){const{event_id:t,session_id:s,content:i}=e;if(this.completedEvents.has(t)){n.info("opencode-adapter",`Dropping duplicate event ${t}`),this.callbacks.sendEventAck(t,s),this.callbacks.sendEventResult(t,"responded");return}if(!this.alive){n.warn("opencode-adapter",`Dropping event ${t}: process not alive`),this.callbacks.sendEventAck(t,s),this.callbacks.sendEventResult(t,"failed","Agent process not running");return}this.activeRun&&this.activeRun.eventId!==t&&(n.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${t}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),n.info("opencode-adapter",`prompt: event=${t} session=${s}`),this.callbacks.sendEventAck(t,s),this.startRun(t,s),this.startComposing(s),this.resetIdleTimer();const o=this.buildPromptTextFromEvent(e);this.sendOcPrompt(s,o).catch(r=>{n.error("opencode-adapter",`prompt_async failed: ${r}`),this.finishRun("failed",String(r))})}deliverStopEvent(e,t){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=C(M(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?B(e,[e]):!1}async probe(e){const t=this.getStatus();return H(this.config.command||"opencode",{alive:t.alive,busy:t.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){try{this.internalApi=new N,this.internalApi.setInvokeHandler(async(h,l,m,p)=>this.callbacks.agentInvoke(h,l,p)),await this.internalApi.start(0),n.info("opencode-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),t=process.env.XDG_CONFIG_HOME||g(F(),".config"),s=g(t,"opencode","opencode.json");P(_(s),{recursive:!0});let i={};try{A(s)&&(i=JSON.parse(b(s,"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,$(s,`${JSON.stringify(i,null,2)}
2
+ `,"utf8"),n.info("opencode-adapter",`MCP config injected into ${s}`);const r=g(t,"opencode","skills"),c=L(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:t}=e;return t==="exec_approve"||t==="exec_reject"||t==="permission_approve"||t==="permission_reject"?this.handlePermissionAction(e):{handled:!1,kind:""}}bindSession(e,t){if(n.info("opencode-adapter",`bindSession: ${e} \u2192 ${t}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:t});else{const s=this.sessions.get(e);s.cwd=t}}async spawnAndWait(e,t){const s=this.resolveCwd();try{if(!(await E(s)).isDirectory())throw new Error(`Bound path is not a directory: ${s}`)}catch(i){throw String(i?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${s}. Please rebind with /grix open <valid-directory>.`):i}return new Promise((i,o)=>{const r=this.config.command||"opencode",h=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${t}`],l={...process.env,...this.config.env},m=U({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider});m&&(l.OPENCODE_CONFIG_CONTENT=JSON.stringify(m));const p=O(r,typeof l.PATH=="string"?l.PATH:void 0);n.info("opencode-adapter",`Spawning: ${p} ${h.join(" ")} (cwd=${s})`),this.process=D(p,h,{env:l,cwd:s}).process;let I="",d=!1;const v=setTimeout(()=>{d||(d=!0,o(new Error(`opencode serve did not start after ${w/1e3}s`)))},w);this.process.stdout?.on("data",a=>{if(I+=a.toString(),!d)for(const u of I.split(`
3
+ `)){const R=u.match(/opencode server listening on (https?:\/\/[^\s]+)/);if(R){clearTimeout(v),d=!0,this.alive=!0,i(R[1]);return}}}),this.process.stderr?.on("data",a=>{const u=a.toString().trim();u&&n.info("opencode-adapter",`[stderr] ${u}`)}),this.process.on("error",a=>{n.error("opencode-adapter",`Spawn error: ${a.message}`),clearTimeout(v),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(v),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 t=this.sessions.get(e);if(t?.ocSessionId)try{return await this.transport.getSession(t.ocSessionId),t.ocSessionId}catch{n.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, creating new`),t.ocSessionId=""}const s=t?.cwd??this.resolveCwd(),i=this.options.bindingStore?.getAcpSessionId(e);if(i)try{return await this.transport.getSession(i),this.sessions.set(e,{ocSessionId:i,cwd:s}),n.info("opencode-adapter",`Resumed OC session ${i} for aibot=${e}`),i}catch{n.warn("opencode-adapter",`Persisted OC session ${i} gone, creating new`)}const o=await this.transport.createSession({title:`grix-${e.slice(-8)}`});return this.sessions.set(e,{ocSessionId:o.id,cwd:s}),this.options.bindingStore?.setAcpSessionId(e,o.id),n.info("opencode-adapter",`Created OC session ${o.id} for aibot=${e}`),o.id}async sendOcPrompt(e,t){const s=await this.ensureOcSession(e);this.activeRun&&(this.activeRun.ocSessionId=s),await this.transport.sendPromptAsync(s,{parts:[{type:"text",text:t}]})}handleSseEvent(e){if(!this.stopped)switch(this.lastSseAt=Date.now(),this.updateToolInFlight(e),this.resetIdleTimer(),e.type){case"message.part.updated":{if(!this.activeRun)break;const t=e.part,s=e.delta;if(t.type==="text"){const i=s||t.text;i&&this.acceptAssistantPartText(t.messageID,"text",i)}else t.type==="reasoning"?s&&this.acceptAssistantPartText(t.messageID,"reasoning",s):t.type==="tool"&&this.handleToolPartUpdate(t,s);break}case"message.updated":{if(!this.activeRun)break;const t=e.info;if(this.rememberMessageRole(t),t.role==="assistant"){const s=t;this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.resolveCwd(),{model_provider:s.providerID,model_id:s.modelID}),s.error&&n.warn("opencode-adapter",`Message error: ${JSON.stringify(s.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 t=e.error,s=t?typeof t=="object"&&"message"in t?t.message:JSON.stringify(t):"unknown session error";n.error("opencode-adapter",`Session error: ${s}`),this.flushTextBuffer(),this.finishRun("failed",s);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}}updateToolInFlight(e){if(e.type!=="message.part.updated")return;const t=e.part;if(t?.type!=="tool"||!t.callID)return;const s=t.state?.status;s==="pending"||s==="running"?this.toolCallsInFlight.add(t.callID):(s==="completed"||s==="error")&&this.toolCallsInFlight.delete(t.callID)}rememberMessageRole(e){const t=typeof e.id=="string"?e.id.trim():"";t&&(e.role!=="user"&&e.role!=="assistant"||(this.messageRoles.set(t,e.role),this.flushOrDropPendingParts(t,e.role)))}acceptAssistantPartText(e,t,s){if(!this.activeRun||!s)return;const i=typeof e=="string"?e.trim():"";if(!i)return;const o=this.messageRoles.get(i);if(o==="user")return;if(o==="assistant"){this.emitAssistantPartChunk(t,s);return}const r=this.pendingPartChunks.get(i)??[];r.push({kind:t,value:s}),this.pendingPartChunks.set(i,r)}flushOrDropPendingParts(e,t){const s=this.pendingPartChunks.get(e);if(this.pendingPartChunks.delete(e),!(!s||s.length===0)&&t==="assistant")for(const i of s)this.emitAssistantPartChunk(i.kind,i.value)}emitAssistantPartChunk(e,t){if(!(!this.activeRun||!t)){if(e==="reasoning"){this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,t);return}this.appendText(t)}}clearMessageRoleState(){this.messageRoles.clear(),this.pendingPartChunks.clear()}handleToolPartUpdate(e,t){if(!this.activeRun)return;const s=e.state;switch(s.status){case"pending":case"running":{this.flushTextBuffer();const i=JSON.stringify(s.input??{});this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,i);break}case"completed":{const i=s.output??"";this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,i);break}case"error":{const i=s.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:t,sessionId:s,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(t,{permissionId:e.id,ocSessionId:i});const o=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(t,s,e.type,o)}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const t=this.pendingPermissions.get(this.activeRun.eventId);if(!t)return{handled:!1,kind:""};const{permissionId:s,ocSessionId:i}=t,r=e.action_type==="exec_approve"||e.action_type==="permission_approve"?"once":"reject";return this.pendingPermissions.delete(this.activeRun.eventId),this.transport.respondPermission(i,s,r).then(()=>{n.info("opencode-adapter",`Permission ${r}: ${s}`),this.resetIdleTimer()}).catch(c=>{n.warn("opencode-adapter",`Permission response failed: ${c}`)}),{handled:!0,kind:"permission"}}startRun(e,t){this.activeRun={eventId:e,sessionId:t,ocSessionId:"",chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null},this.lastSseAt=Date.now(),this.livenessExtendStartAt=void 0}finishRun(e,t){const s=this.activeRun;if(!s)return;if(this.completedEvents.add(s.eventId),this.completedEvents.size>Y){const c=[...this.completedEvents].slice(-500);this.completedEvents=new Set(c)}this.activeRun=null,this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopComposing(),this.stopIdleTimer();const i=++s.chunkSeq,o=s.clientMsgId;e==="failed"&&t&&this.callbacks.sendRunError(s.eventId,s.sessionId,t);const r=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(s.eventId,s.sessionId,o).then(()=>{this.callbacks.sendEventResult(s.eventId,e,t)}).catch(()=>{this.callbacks.sendStreamChunk(s.eventId,s.sessionId,"",i,!0,o),this.callbacks.sendEventResult(s.eventId,e,t)}):(this.callbacks.sendStreamChunk(s.eventId,s.sessionId,"",i,!0,o),this.callbacks.sendEventResult(s.eventId,e,t))};if(s.textBuffer){this.stopTextFlush();for(const c of x(s.textBuffer))s.chunkSeq++,this.callbacks.sendStreamChunk(s.eventId,s.sessionId,c,s.chunkSeq,!1,s.clientMsgId);s.textBuffer=""}r(),this.emit("eventDone",s.eventId)}clearRun(){this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const e=this.activeRun?.eventId;this.activeRun=null,this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopIdleTimer(),e&&this.emit("eventDone",e)}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=z){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 e of x(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(){}shouldExtendByLiveness(){if(!this.activeRun)return!1;const e=this.process?.pid;if(!this.alive||!e||!y(e))return!1;const t=Date.now(),s=this.lastSseAt>0?t-this.lastSseAt:Number.POSITIVE_INFINITY;if(s<V)return this.livenessExtendStartAt=t,n.info("opencode-adapter",`Liveness check: fresh SSE for ${this.activeRun.eventId} (sseAge=${s}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const o=this.livenessExtendStartAt??t;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=o),t-o>k?(n.warn("opencode-adapter",`Liveness extension budget exhausted for ${this.activeRun.eventId} (no progress for ${Math.round((t-o)/6e4)}min), allowing idle fail`),!1):(n.info("opencode-adapter",`Liveness check: turn in progress for ${this.activeRun.eventId} (toolsInFlight=${this.toolCallsInFlight.size}, sseAge=${Number.isFinite(s)?`${s}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.activeRun)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.activeRun)return;if(this.pendingPermissions.has(this.activeRun.eventId)&&this.shouldExtendByLiveness()){n.info("opencode-adapter",`Idle timeout skipped: pendingPermissions for ${this.activeRun.eventId}, resetting timer`),this.resetIdleTimer();return}if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const e=this.process?.pid,s=!!(this.alive&&e&&y(e))?`liveness budget exhausted after ${k/6e4}min`:"process not alive";n.error("opencode-adapter",`Idle timeout (${s}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`idle timeout: ${s}`),this.clearRun()),this.emit("exit",-1)},q))}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 t=e.text;return e.contextMessages&&e.contextMessages.length>0&&(t=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
4
4
  `)+`
5
5
 
6
6
  `+t),this.identity.injectOnce(e.adapterSessionId,t)}buildPromptTextFromEvent(e){let t=e.content||"";if(e.context_messages_json)try{const s=JSON.parse(e.context_messages_json);Array.isArray(s)&&s.length>0&&(t=s.map(o=>`[context] ${o.sender_id??"unknown"}: ${o.content}`).join(`
7
7
  `)+`
8
8
 
9
- `+t)}catch{}return this.identity.injectOnce(e.session_id,t)}}export{he as OpenCodeAdapter};
9
+ `+t)}catch{}return this.identity.injectOnce(e.session_id,t)}}export{ue as OpenCodeAdapter};
@@ -1,10 +1,10 @@
1
- import{execFile as x}from"node:child_process";import{promisify as y}from"node:util";import{EventEmitter as g}from"node:events";import{stat as _}from"node:fs/promises";import{mkdirSync as b,writeFileSync as T,unlinkSync as w,statSync as E,readFileSync as P,existsSync as k}from"node:fs";import{join as p,resolve as $}from"node:path";import{fileURLToPath as A}from"node:url";import{tmpdir as C,homedir as m}from"node:os";import{resolveCommandPath as M,spawnCommand as R,killProcessGroup as v,hasChildProcesses as F}from"../../core/runtime/spawn.js";import{InternalApiServer as B}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as D}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as G}from"../../default-skills/index.js";import{PiTransport as N}from"./pi-transport.js";import{log as r}from"../../core/log/index.js";import{scanSkills as j}from"../claude/skill-scanner.js";import{SessionBindingStore as L}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as O}from"../../core/protocol/index.js";import{buildSimpleProbeReport as q}from"../shared/probe-util.js";import{piGrixProviderId as U,removePiGrixProvider as H,writePiGrixProvider as W}from"./pi-provider-config.js";const S=new Map;function z(){const d=p(m(),".pi","agent","mcp.json");try{if(!k(d))return{};const e=JSON.parse(P(d,"utf8"))?.mcpServers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch(t){return r.warn("pi-adapter",`Failed to read Pi user MCP config ${d}: ${t instanceof Error?t.message:String(t)}`),{}}}async function J(d){const t=S.get(d);if(t!==void 0)return t;let e=!1;try{const s=y(x),i=process.platform==="win32",n=i&&/\s/.test(d)&&!d.startsWith('"')?`"${d}"`:d,{stdout:o,stderr:c}=await s(n,["--help"],{timeout:5e3,encoding:"utf-8",...i?{shell:!0}:{}});e=/--mcp-config\b/.test(`${o??""}${c??""}`)}catch{e=!1}return S.set(d,e),r.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class Y extends g{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){r.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const K=12e4,X=6e5,Q=500,V=2e3,u=3,Z=500;function tt(d){return new Promise(t=>setTimeout(t,d))}class I extends g{type="pi";config;callbacks;process=null;transport=new N;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;identity;piSessionPath=null;activeEventId=null;activeSessionId=null;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;idleTimer=null;toolCallsInFlight=new Set;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new D("pi-adapter",e.getAgentProfile);const s=t.options??{};this.aibotSessionId=String(s.aibotSessionId??"").trim(),this.agentName=String(s.agentName??"").trim(),this.provider=s.provider,this.bindingStore=s.bindingStore instanceof L?s.bindingStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}async start(){await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),r.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(this.aibotSessionId)for(let t=1;t<=u;t++)try{const[e,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),i=e.data?.models;if(!i||i.length===0){if(t<u){await tt(Z);continue}r.warn("pi-adapter",`syncModelBinding: empty model list after ${u} attempts, giving up`);return}const n=s.data?.model,o={available_models:i.map(c=>({id:c.id,display_name:c.name??c.id,...c.provider?{provider:c.provider}:{}}))};n?.id&&(o.model_id=n.id),n?.provider&&(o.model_provider=n.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),o),r.info("pi-adapter",`synced model binding: ${i.length} models, current=${n?.id??"unknown"} (attempt ${t})`);return}catch(e){r.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{w(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.process){const t=this.process;try{v(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{v(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return r.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new Y(t.adapterSessionId),s=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:s})).then(i=>{i.success||e.emitDone({status:"failed",error:i.error})}).catch(i=>{e.emitError(i instanceof Error?i:new Error(String(i)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:s,content:i}=t,n=this.buildPromptText(t);this.isStreaming?(this.activeEventId&&this.activeEventId!==e&&(r.info("pi-adapter",`steer: cancel ${this.activeEventId} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeEventId,"canceled","steered to new event")),this.activeEventId=e,this.activeSessionId=s,this.resetRunStreamState(),this.startComposing(s,e),this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(o=>{r.error("pi-adapter",`steer failed: ${o}`),this.callbacks.sendEventResult(e,"failed",String(o))})):(r.info("pi-adapter",`prompt: event=${e} session=${s}`),this.activeEventId=e,this.activeSessionId=s,this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(s,e),this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(o=>{o.success||(r.error("pi-adapter",`prompt rejected: ${o.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",o.error),this.clearActive())}).catch(o=>{r.error("pi-adapter",`prompt error: ${o}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(o)),this.clearActive()}))}deliverStopEvent(t,e){if(this.activeEventId===t){r.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const s=this.nextStreamSeq(),i=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",s,!0,i),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const s=t.params??{},i=(s.modelId??s.model_id??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{let n=s.provider?.trim();return n||(n=(await this.transport.send("get_available_models")).data?.models?.find(l=>l.id===i)?.provider?.trim()),n?(await this.transport.send("set_model",{provider:n,modelId:i}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:i}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${i}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"get_context":try{const s=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:s}),{handled:!0,kind:"get_context"}}catch(s){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",s instanceof Error?s.message:String(s)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=$(A(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?F(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await q(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=E(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,s){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const i=e.trim();if(i){const c=i.indexOf(":");if(c<1)return{status:"failed",message:"Format: provider:model_id"};const l=i.slice(0,c),h=i.slice(c+1);if(!h)return{status:"failed",message:"Format: provider:model_id"};const a=await this.transport.send("set_model",{provider:l,modelId:h});return a?.success?{status:"ok",message:`Model set to ${l}:${h}`}:{status:"failed",message:`Failed to set model: ${a?.error??"unknown error"}`}}const o=(await this.transport.send("get_available_models"))?.data?.models;return o&&o.length>0?{status:"ok",message:`Available models:
1
+ import{execFile as E}from"node:child_process";import{promisify as _}from"node:util";import{EventEmitter as g}from"node:events";import{stat as b}from"node:fs/promises";import{mkdirSync as w,writeFileSync as T,unlinkSync as P,statSync as k,readFileSync as A,existsSync as $}from"node:fs";import{join as p,resolve as C}from"node:path";import{fileURLToPath as R}from"node:url";import{tmpdir as M,homedir as u}from"node:os";import{resolveCommandPath as F,spawnCommand as B,killProcessGroup as v,hasChildProcesses as D}from"../../core/runtime/spawn.js";import{InternalApiServer as N}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as G}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as L}from"../../default-skills/index.js";import{PiTransport as j}from"./pi-transport.js";import{log as r}from"../../core/log/index.js";import{scanSkills as O}from"../claude/skill-scanner.js";import{SessionBindingStore as q}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as U}from"../../core/protocol/index.js";import{buildSimpleProbeReport as H}from"../shared/probe-util.js";import{piGrixProviderId as W,removePiGrixProvider as z,writePiGrixProvider as Y}from"./pi-provider-config.js";const S=new Map;function J(){const c=p(u(),".pi","agent","mcp.json");try{if(!$(c))return{};const e=JSON.parse(A(c,"utf8"))?.mcpServers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch(t){return r.warn("pi-adapter",`Failed to read Pi user MCP config ${c}: ${t instanceof Error?t.message:String(t)}`),{}}}async function X(c){const t=S.get(c);if(t!==void 0)return t;let e=!1;try{const s=_(E),i=process.platform==="win32",n=i&&/\s/.test(c)&&!c.startsWith('"')?`"${c}"`:c,{stdout:o,stderr:d}=await s(n,["--help"],{timeout:5e3,encoding:"utf-8",...i?{shell:!0}:{}});e=/--mcp-config\b/.test(`${o??""}${d??""}`)}catch{e=!1}return S.set(c,e),r.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${c})`),e}class V extends g{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){r.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const K=12e4,Q=90*1e3,I=1800*1e3;function x(c){try{return process.kill(c,0),!0}catch(t){return t.code==="EPERM"}}const Z=500,tt=2e3,m=3,et=500;function st(c){return new Promise(t=>setTimeout(t,c))}class y extends g{type="pi";config;callbacks;process=null;transport=new j;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;identity;piSessionPath=null;activeEventId=null;activeSessionId=null;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new G("pi-adapter",e.getAgentProfile);const s=t.options??{};this.aibotSessionId=String(s.aibotSessionId??"").trim(),this.agentName=String(s.agentName??"").trim(),this.provider=s.provider,this.bindingStore=s.bindingStore instanceof q?s.bindingStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}async start(){await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),r.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(this.aibotSessionId)for(let t=1;t<=m;t++)try{const[e,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),i=e.data?.models;if(!i||i.length===0){if(t<m){await st(et);continue}r.warn("pi-adapter",`syncModelBinding: empty model list after ${m} attempts, giving up`);return}const n=s.data?.model,o={available_models:i.map(d=>({id:d.id,display_name:d.name??d.id,...d.provider?{provider:d.provider}:{}}))};n?.id&&(o.model_id=n.id),n?.provider&&(o.model_provider=n.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),o),r.info("pi-adapter",`synced model binding: ${i.length} models, current=${n?.id??"unknown"} (attempt ${t})`);return}catch(e){r.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{P(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.process){const t=this.process;try{v(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{v(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return r.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new V(t.adapterSessionId),s=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:s})).then(i=>{i.success||e.emitDone({status:"failed",error:i.error})}).catch(i=>{e.emitError(i instanceof Error?i:new Error(String(i)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:s,content:i}=t,n=this.buildPromptText(t);this.isStreaming?(this.activeEventId&&this.activeEventId!==e&&(r.info("pi-adapter",`steer: cancel ${this.activeEventId} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeEventId,"canceled","steered to new event")),this.activeEventId=e,this.activeSessionId=s,this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(o=>{r.error("pi-adapter",`steer failed: ${o}`),this.callbacks.sendEventResult(e,"failed",String(o))})):(r.info("pi-adapter",`prompt: event=${e} session=${s}`),this.activeEventId=e,this.activeSessionId=s,this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(o=>{o.success||(r.error("pi-adapter",`prompt rejected: ${o.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",o.error),this.clearActive())}).catch(o=>{r.error("pi-adapter",`prompt error: ${o}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(o)),this.clearActive()}))}deliverStopEvent(t,e){if(this.activeEventId===t){r.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const s=this.nextStreamSeq(),i=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",s,!0,i),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const s=t.params??{},i=(s.modelId??s.model_id??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{let n=s.provider?.trim();return n||(n=(await this.transport.send("get_available_models")).data?.models?.find(l=>l.id===i)?.provider?.trim()),n?(await this.transport.send("set_model",{provider:n,modelId:i}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:i}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${i}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"get_context":try{const s=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:s}),{handled:!0,kind:"get_context"}}catch(s){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",s instanceof Error?s.message:String(s)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=C(R(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?D(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await H(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=k(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,s){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const i=e.trim();if(i){const d=i.indexOf(":");if(d<1)return{status:"failed",message:"Format: provider:model_id"};const l=i.slice(0,d),h=i.slice(d+1);if(!h)return{status:"failed",message:"Format: provider:model_id"};const a=await this.transport.send("set_model",{provider:l,modelId:h});return a?.success?{status:"ok",message:`Model set to ${l}:${h}`}:{status:"failed",message:`Failed to set model: ${a?.error??"unknown error"}`}}const o=(await this.transport.send("get_available_models"))?.data?.models;return o&&o.length>0?{status:"ok",message:`Available models:
2
2
  ${o.map(l=>` ${l.provider??"unknown"}:${l.id} (${l.name??l.id})`).join(`
3
- `)}`,data:o}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const i=this.getStatus();return{status:"ok",message:`Alive: ${i.alive}, Busy: ${i.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:i.alive,busy:i.busy,sessions:i.sessions,sessionPath:this.piSessionPath}}}case"skills":{const i=j({mode:"pi"}),n=i.map(o=>`- ${o.name}${o.trigger?` (${o.trigger})`:""} [${o.source}]: ${o.description}`);return{status:"ok",message:n.length>0?n.join(`
4
- `):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new B,this.internalApi.setInvokeHandler(async(o,c,l,h)=>this.callbacks.agentInvoke(o,c,h)),await this.internalApi.start(0),r.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=z(),s=p(C(),"grix-pi-mcp");b(s,{recursive:!0}),this.mcpConfigPath=p(s,`mcp-${process.pid}-${Date.now()}.json`),T(this.mcpConfigPath,JSON.stringify({mcpServers:{...e,[t.name]:{command:t.command,args:t.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),r.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const i=p(m(),".pi","agent","skills"),n=G(i);n.length>0&&r.info("pi-adapter",`Synced connector skills to ${i}: [${n.join(", ")}]`)}catch(t){r.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async spawnPi(){const t=this.config.command||"pi",e=M(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),s=this.config.args??[],n=s.some(a=>a.startsWith("--mode"))?[...s]:["--mode","rpc",...s],o=String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||p(m(),".pi","agent"),c=U(this.agentName);this.provider?await W(o,c,this.provider)?(n.includes("--provider")||n.push("--provider",c),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):r.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied"):await H(o,c).then(a=>{a&&r.info("pi-adapter",`Removed stale Grix provider "${c}" from models.json`)}).catch(a=>{r.warn("pi-adapter",`Failed to clean up Grix provider config: ${a instanceof Error?a.message:String(a)}`)}),this.mcpConfigPath&&!n.some(a=>a==="--mcp-config")&&(await J(e)?n.push("--mcp-config",this.mcpConfigPath):r.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));const l={...process.env,...this.config.env},h=this.resolveCwd();r.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await _(h)).isDirectory())throw new Error(`Bound path is not a directory: ${h}`)}catch(a){throw String(a?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${h}. Please rebind with /grix open <valid-directory>.`):a}try{this.process=R(e,n,{env:l,cwd:h}).process}catch(a){throw r.error("pi-adapter",`PI spawn threw: ${a}`),this.alive=!1,a}this.process.on("error",a=>{r.error("pi-adapter",`Spawn error: ${a.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${a.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",a=>{r.info("pi-adapter",`PI process exited (code=${a})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${a})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",a??1)}),this.process.stderr?.on("data",a=>{const f=a.toString().trim();f&&r.info("pi-adapter",`[pi stderr] ${f}`)}),this.transport.on("event",a=>this.handlePiEvent(a)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped)return;if(t.type==="tool_execution_start"){const s=t;s.toolCallId&&this.toolCallsInFlight.add(s.toolCallId)}else if(t.type==="tool_execution_end"){const s=t;s.toolCallId&&this.toolCallsInFlight.delete(s.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const s=t.assistantMessageEvent;if(!s)break;const i=s.type;if(i==="text_delta"){const n=s.delta;if(n){const o=typeof s.contentIndex=="number"?s.contentIndex:0;this.rememberEmittedText(o,n),this.appendText(n)}}else if(i==="text_end"){const n=s.content,o=typeof s.contentIndex=="number"?s.contentIndex:0;n&&this.appendMissingText(o,n)}else if(i==="thinking_delta"){const n=s.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(i==="done"||i==="error"){if(this.flushTextBuffer(),i==="error"&&this.activeEventId&&this.activeSessionId){const n=s.reason??"stream error";this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,String(n),this.nextStreamSeq(),this.activeClientMsgId??void 0)}this.scheduleDoneGuard()}break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const s=t;if(s.toolName){const i=typeof s.args=="object"&&s.args!==null?JSON.stringify(s.args):String(s.args??"");this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,s.toolName,i)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const s=t,i=et(s.result);i&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,s.toolName,i);break}case"agent_end":{r.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(r.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=V){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},Q))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of O(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(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(n=>`[context] ${n.sender_id??"unknown"}: ${n.content}`).join(`
3
+ `)}`,data:o}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const i=this.getStatus();return{status:"ok",message:`Alive: ${i.alive}, Busy: ${i.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:i.alive,busy:i.busy,sessions:i.sessions,sessionPath:this.piSessionPath}}}case"skills":{const i=O({mode:"pi"}),n=i.map(o=>`- ${o.name}${o.trigger?` (${o.trigger})`:""} [${o.source}]: ${o.description}`);return{status:"ok",message:n.length>0?n.join(`
4
+ `):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new N,this.internalApi.setInvokeHandler(async(o,d,l,h)=>this.callbacks.agentInvoke(o,d,h)),await this.internalApi.start(0),r.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=J(),s=p(M(),"grix-pi-mcp");w(s,{recursive:!0}),this.mcpConfigPath=p(s,`mcp-${process.pid}-${Date.now()}.json`),T(this.mcpConfigPath,JSON.stringify({mcpServers:{...e,[t.name]:{command:t.command,args:t.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),r.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const i=p(u(),".pi","agent","skills"),n=L(i);n.length>0&&r.info("pi-adapter",`Synced connector skills to ${i}: [${n.join(", ")}]`)}catch(t){r.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async spawnPi(){const t=this.config.command||"pi",e=F(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),s=this.config.args??[],n=s.some(a=>a.startsWith("--mode"))?[...s]:["--mode","rpc",...s],o=String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||p(u(),".pi","agent"),d=W(this.agentName);this.provider?await Y(o,d,this.provider)?(n.includes("--provider")||n.push("--provider",d),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):r.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied"):await z(o,d).then(a=>{a&&r.info("pi-adapter",`Removed stale Grix provider "${d}" from models.json`)}).catch(a=>{r.warn("pi-adapter",`Failed to clean up Grix provider config: ${a instanceof Error?a.message:String(a)}`)}),this.mcpConfigPath&&!n.some(a=>a==="--mcp-config")&&(await X(e)?n.push("--mcp-config",this.mcpConfigPath):r.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));const l={...process.env,...this.config.env},h=this.resolveCwd();r.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await b(h)).isDirectory())throw new Error(`Bound path is not a directory: ${h}`)}catch(a){throw String(a?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${h}. Please rebind with /grix open <valid-directory>.`):a}try{this.process=B(e,n,{env:l,cwd:h}).process}catch(a){throw r.error("pi-adapter",`PI spawn threw: ${a}`),this.alive=!1,a}this.process.on("error",a=>{r.error("pi-adapter",`Spawn error: ${a.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${a.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",a=>{r.info("pi-adapter",`PI process exited (code=${a})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${a})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",a??1)}),this.process.stderr?.on("data",a=>{const f=a.toString().trim();f&&r.info("pi-adapter",`[pi stderr] ${f}`)}),this.transport.on("event",a=>this.handlePiEvent(a)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const s=t;s.toolCallId&&this.toolCallsInFlight.add(s.toolCallId)}else if(t.type==="tool_execution_end"){const s=t;s.toolCallId&&this.toolCallsInFlight.delete(s.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const s=t.assistantMessageEvent;if(!s)break;const i=s.type;if(i==="text_delta"){const n=s.delta;if(n){const o=typeof s.contentIndex=="number"?s.contentIndex:0;this.rememberEmittedText(o,n),this.appendText(n)}}else if(i==="text_end"){const n=s.content,o=typeof s.contentIndex=="number"?s.contentIndex:0;n&&this.appendMissingText(o,n)}else if(i==="thinking_delta"){const n=s.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(i==="done"||i==="error"){if(this.flushTextBuffer(),i==="error"&&this.activeEventId&&this.activeSessionId){const n=s.reason??"stream error";this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,String(n),this.nextStreamSeq(),this.activeClientMsgId??void 0)}this.scheduleDoneGuard()}break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const s=t;if(s.toolName){const i=typeof s.args=="object"&&s.args!==null?JSON.stringify(s.args):String(s.args??"");this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,s.toolName,i)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const s=t,i=it(s.result);i&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,s.toolName,i);break}case"agent_end":{r.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(r.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=tt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},Z))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of U(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(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(n=>`[context] ${n.sender_id??"unknown"}: ${n.content}`).join(`
5
5
  `)+`
6
6
 
7
7
  `+e)}catch{}return this.identity.injectOnce(t.session_id,e)}buildPromptTextFromRequest(t){let e=t.text;return t.contextMessages&&t.contextMessages.length>0&&(e=t.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
8
8
  `)+`
9
9
 
10
- `+e),this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),t&&this.emit("eventDone",t)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",s=this.activeClientMsgId??void 0;this.clearActive(),this.finalizeEvent(t,e,s)}finalizeEvent(t,e,s){const i=this.nextStreamSeq();this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,s).then(()=>{this.callbacks.sendEventResult(t,"responded"),r.info("pi-adapter",`event completed (reliable) event=${t}`)}).catch(n=>{r.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${n}`),this.callbacks.sendStreamChunk(t,e,"",i,!0,s),this.callbacks.sendEventResult(t,"responded"),r.info("pi-adapter",`event completed (fallback) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",i,!0,s),this.callbacks.sendEventResult(t,"responded"),r.info("pi-adapter",`event completed event=${t}`))}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const s=this.emittedTextByIndex.get(t)??"";if(e!==s){if(e.startsWith(s)){const i=e.slice(s.length);i&&(this.rememberEmittedText(t,i),this.appendText(i));return}if(!s){this.rememberEmittedText(t,e),this.appendText(e);return}r.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(r.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},I.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}resetIdleTimer(){if(this.stopIdleTimer(),this.stopped||!this.isStreaming)return;const t=this.toolCallsInFlight.size>0?X:K;this.idleTimer=setTimeout(()=>{r.error("pi-adapter",`Idle timeout (${t/1e3}s, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed","idle timeout"),this.clearActive(),this.emit("exit",-1)},t)}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&r.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const i=await this.transport.send("get_state");i.success&&(e=i.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}function et(d){if(!d||typeof d!="object")return"";const t=d.content;if(!Array.isArray(t))return"";const e=[];for(const s of t)if(s&&typeof s=="object"){const i=s;i.type==="text"&&typeof i.text=="string"&&e.push(i.text)}return e.join("")}export{I as PiAdapter};
10
+ `+e),this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",s=this.activeClientMsgId??void 0;this.clearActive(),this.finalizeEvent(t,e,s)}finalizeEvent(t,e,s){const i=this.nextStreamSeq();this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,s).then(()=>{this.callbacks.sendEventResult(t,"responded"),r.info("pi-adapter",`event completed (reliable) event=${t}`)}).catch(n=>{r.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${n}`),this.callbacks.sendStreamChunk(t,e,"",i,!0,s),this.callbacks.sendEventResult(t,"responded"),r.info("pi-adapter",`event completed (fallback) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",i,!0,s),this.callbacks.sendEventResult(t,"responded"),r.info("pi-adapter",`event completed event=${t}`))}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const s=this.emittedTextByIndex.get(t)??"";if(e!==s){if(e.startsWith(s)){const i=e.slice(s.length);i&&(this.rememberEmittedText(t,i),this.appendText(i));return}if(!s){this.rememberEmittedText(t,e),this.appendText(e);return}r.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(r.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},y.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!x(t))return!1;const e=Date.now(),s=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY;if(s<Q)return this.livenessExtendStartAt=e,r.info("pi-adapter",`Liveness check: fresh RPC for ${this.activeEventId} (rpcAge=${s}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),e-n>I?(r.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-n)/6e4)}min), allowing idle fail`),!1):(r.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(s)?`${s}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,s=!!(this.alive&&t&&x(t))?`liveness budget exhausted after ${I/6e4}min`:"process not alive";r.error("pi-adapter",`Idle timeout (${s}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${s}`),this.clearActive(),this.emit("exit",-1)},K))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&r.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const i=await this.transport.send("get_state");i.success&&(e=i.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}function it(c){if(!c||typeof c!="object")return"";const t=c.content;if(!Array.isArray(t))return"";const e=[];for(const s of t)if(s&&typeof s=="object"){const i=s;i.type==="text"&&typeof i.text=="string"&&e.push(i.text)}return e.join("")}export{y as PiAdapter};
@@ -13,4 +13,4 @@ Error: ${c}`,1,!1)},sendPermissionCard:r=>{if(u.info("bridge","sendPermissionCar
13
13
  Error: ${t}`,1,!1)}sendEventResultWithCleanup(e,o,t,s){this.sendCtrl.sendEventResult(e,o,t,s);const i=this.eventSessionIndex.get(e);i&&(this.pool.eventComplete(e,i),this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,o,t),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),o==="responded"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:o,sessionId:t,errorMsg:s}=e;if(this.stopped)return;const i=this.inflightEvents.get(o);if(!i){u.warn(this.name,`[recovery] no inflight event for internalError event=${o} session=${t}; surface failure directly`),this.sendRunErrorAsChunk(o,t,s),this.sendEventResultWithCleanup(o,"failed",s,"agent_stop_failure");return}const n=(this.restartCount.get(o)??0)+1;this.restartCount.set(o,n);const a=this.config.adapterType??"acp";if(n>W){u.error(this.name,`[recovery] adapter=${a} session=${t} event=${o} restart=${n}/${W} outcome=give-up err=${s}`),this.sendRunErrorAsChunk(o,t,s),this.sendEventResultWithCleanup(o,"failed",s,"agent_stop_failure");return}u.info(this.name,`[recovery] adapter=${a} session=${t} event=${o} restart=${n}/${W} outcome=restarting err=${s}`);const r=this.pool.drainQueuedForSession(t);r.length>0&&u.info(this.name,`[recovery] session=${t} preserved ${r.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(t)}catch(l){u.warn(this.name,`[recovery] removeSlot failed session=${t}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const d=this.resolveRecoveryPrompt(a,i),c={...i,content:d};try{await this.pool.deliverInboundEvent(c)}catch(l){u.error(this.name,`[recovery] redeliver failed event=${o} session=${t}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(o,"failed",l instanceof Error?l.message:String(l));return}for(const l of r){if(this.stopped)break;try{await this.pool.deliverInboundEvent(l)}catch(h){u.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${t}: ${h instanceof Error?h.message:String(h)}`),this.sendEventResultWithCleanup(l.event_id,"failed",h instanceof Error?h.message:String(h))}}}resolveRecoveryPrompt(e,o){return e==="acp"?"continue":o.content}sendThinkingByRuntimeConfig(e,o,t){this.sendCtrl.sendThinking(e,o,t)}bufferStreamChunk(e,o,t,s,i){this.sendCtrl.bufferOnly(e,o,t,s,i)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),e.event_id&&!this.inflightEvents.has(e.event_id)&&this.inflightEvents.set(e.event_id,e)}indexEventSession(e,o){!e||!o||this.eventSessionIndex.set(e,o)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,o){return this.sendCtrl.shouldDropCodexDisplayEvent(e,o)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params?.delta;if(!t)return;const s=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(s,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:t.length,content:t})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,o){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,o)}sendAcpRawEventEnvelope(e,o,t){this.shouldDropAcpRawDisplayEvent(e,t.type)||this.deliverRawEventEnvelope(e,o,t,"acp",this.buildAcpRawEventFallbackText(t))}buildAcpRawEventFallbackText(e){const o=String(e.type??"").trim();if(!o)return"[acp] event";switch(o){case"permission_request":return`Permission required: ${String(e.payload?.tool_title??e.payload?.tool_name??"permission request")}`;case"tool_use":return`[tool] ${String(e.payload?.tool_name??"tool")}`;case"tool_result":return"[tool result]";case"thinking":return"[thinking]";case"error":return`[error] ${String(e.payload?.message??"agent error")}`;case"result":return"[result]";default:return`[acp] ${o}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,o,t,s,i){const n=pt({envelope:t,fallbackText:i,channelKey:s,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),a=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:o,msg_type:1,content:n.fallbackText,extra:{channel_data:{[s]:{raw_event:n.envelope}},agent_api_origin:!0}})};if(!n.sharded){a();return}u.info("bridge",`${s} raw_event oversized, sharded delivery: event=${e} fields=${n.oversizedFields.map(r=>r.field).join(",")}`),(async()=>{for(const r of n.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,o,ft({envelopeType:t.type,field:r.field,fullText:r.fullText}),r.refClientMsgId);a()})().catch(r=>{u.warn("bridge",`${s} raw_event sharded delivery failed event=${e}: ${r}`)})}buildCursorRawEventFallbackText(e){const o=String(e?.type??"").trim(),t=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(o){case"permission_request":return`Permission required: ${String(t.tool_title??t.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(t.tool_name??t.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(t.message??"agent error")}`;default:return o?`[cursor] ${o}`:"[cursor] event"}}sendToolExecutionCard(e,o,t,s){this.sendCtrl.sendToolExecutionCard(e,o,t,s)}async handleAibotEvent(e){if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const o=this.config.adapterType??"acp",t=ht(e.extra);if(t.error){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_config_invalid",msg:t.error,updated_at:Date.now()});return}const s=t.patch,i=Ze(e);if(i){if(i.verb===p.exec){await this.handleSessionControlCommand(i,e);return}if(i.verb===p.listSessions){await this.handleListSessionsTextCommand(e);return}if(o==="claude"){await this.handleSessionControlCommand(i,e);return}if(o==="codex"&&i.verb===p.open){await this.handleCodexSessionControlOpen(i,e);return}if(o==="pi"&&i.verb===p.open){await this.handlePiSessionControlOpen(i,e);return}if(o==="pi"&&i.verb===p.restart){await this.handlePiSessionControlRestart(e);return}if((o==="openhuman"||o==="opencode")&&i.verb===p.open){await this.handleOpenHumanSessionControlOpen(i,e);return}if(o==="codewhale"&&i.verb===p.open){await this.handleCodeWhaleSessionControlOpen(i,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),i.verb===p.open){const r=i.args.trim();if(!r){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const d=x.resolve(r);if(!(await D(d)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:`Path is not a directory: ${d}`,updated_at:Date.now()});return}}catch(d){const c=String(d?.code??""),l=c==="ENOENT"?`Directory does not exist: ${x.resolve(r)}`:c==="EACCES"||c==="EPERM"?"Directory is not accessible":`Invalid path: ${r}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:l,updated_at:Date.now()});return}}if(i.verb===p.open){const r=this.bindingStore.get(e.session_id);if(r?.cwd)try{await D(r.cwd)}catch{u.info("bridge",`Stale binding detected for session ${e.session_id}: ${r.cwd} no longer exists, clearing`),this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id);const d=this.pool.getSlot(e.session_id);d?.adapter instanceof A&&d.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(i,e),o==="acp"&&i.verb===p.stop){const d=this.bindingStore.get(e.session_id)?.cwd??"";await this.pool.removeSlot(e.session_id).catch(()=>{}),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${d}`,updated_at:Date.now()});return}if(V(i,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(),sendEventAck:()=>{}}),i.verb===p.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),o==="agy")){const r=this.bindingStore.get(e.session_id)?.cwd??"";r&&this.aibotHandle.sendUpdateBindingCard({session_id:e.session_id,worker_status:"ready",cwd:r,meta:this.buildAgyToolbarMeta(e.session_id)})}return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}if(kt.has(o)&&!this.bindingStore.get(e.session_id)?.cwd){const d=o;u.info(this.name,`[${d}] binding missing session_id=${e.session_id} event_id=${e.event_id}`),this.deferredMgr.defer(d,String(e.session_id??"").trim(),this.buildInboundEvent(e,s));const c=this.resolveBindingChannelKey(o);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[c]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:g.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const d=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(d){const[,c,l]=d,m=this.pool.getSlot(e.session_id)?.adapter;if(m?.execCommand&&(m.getSupportedCommands?.()??[]).some(f=>f.name===c||f.name===`/${c}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const f=await m.execCommand(c,l.trim(),e.session_id);f.status==="options"&&f.data&&this.handleExecCommandOptions(e.session_id,c,f.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:f.status==="failed"?"failed":"responded",msg:f.message,updated_at:Date.now()})}catch(f){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:f instanceof Error?f.message:String(f),updated_at:Date.now()})}return}}}const a=this.buildInboundEvent(e,s);try{this.captureEventRuntimeConfig(a),await this.pool.deliverInboundEvent(a)}catch(r){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.discardEventTrackingState(e.event_id),r instanceof Xe)this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:r.message,updated_at:Date.now()});else throw r}}async handleCodexSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(a,r)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:a,...r,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const a=await this.resolveCwdForBinding(s),r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(r.cwd)===a){i(),n("responded",{msg:`Session already bound to ${r.cwd}`});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){i(),n("failed",{msg:`Session already bound to ${r.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,a),this.sessionBindings.set(t,a),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),i(),n("responded",{msg:`Session bound to ${a}`})}catch(a){i(),n("failed",{code:g.invalidCwd,msg:a instanceof Error?a.message:String(a)})}}async handleSessionControlForPool(e,o){e.verb===p.open&&await this.bindSessionForPool(o.session_id,e.args.trim())}async replayDeferredEventsForSession(e){await this.deferredMgr.release(e,this.deferredCallbacks())}async handleSessionControlLocalActionForPool(e){if(String(e.action_type??"")!==b.sessionControl)return;const o=e.params??{};if(String(o.verb??"").trim().toLowerCase()!==p.open)return;const s=String(o.session_id??"").trim(),i=String(o.cwd??"").trim();!s||!i||await this.bindSessionForPool(s,i)}async handleCodexSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){n("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const a=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,a);const r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(r.cwd);if(c===a){this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){n("failed",void 0,g.rebindForbidden,`Session already bound to ${r.cwd}`);return}}this.bindingStore.set(t,a),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,a),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,a)})}catch(a){n("failed",void 0,a?.sessionControlErrorCode??g.invalidCwd,a instanceof Error?a.message:String(a))}}async handleCursorSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){n("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const a=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,a);const r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(r.cwd);if(c===a){this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,c),await this.bindSessionForPool(t,c),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:c,meta:this.buildCursorToolbarMeta(t)}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale cursor binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){n("failed",void 0,g.rebindForbidden,`Session already bound to ${r.cwd}`);return}}this.bindingStore.set(t,a),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,a),this.deferredMgr.sendCursorDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a,meta:this.buildCursorToolbarMeta(t)}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,a)})}catch(a){n("failed",void 0,a?.sessionControlErrorCode??g.invalidCwd,a instanceof Error?a.message:String(a))}}async handlePiSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(a,r)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:a,...r,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const a=await this.resolveCwdForBinding(s),r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(r.cwd)===a){i(),n("responded",{msg:`Session already bound to ${r.cwd}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Session already bound to \`${r.cwd}\``,quoted_message_id:o.msg_id});return}}catch{d=!0,u.info("bridge",`Stale pi binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){i(),n("failed",{msg:`Session already bound to ${r.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,a),this.sessionBindings.set(t,a),await this.ensureSlotStarted(t).catch(d=>{u.warn("bridge",`pi ensureSlotStarted on bind failed (non-fatal): ${d instanceof Error?d.message:String(d)}`)}),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),i(),n("responded",{msg:`Session bound to ${a}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Working directory bound: \`${a}\``,quoted_message_id:o.msg_id})}catch(a){i(),n("failed",{code:g.invalidCwd,msg:a instanceof Error?a.message:String(a)})}}async handlePiSessionControlRestart(e){const o=e.session_id,t=()=>this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:o,received_at:Date.now()}),s=(a,r)=>this.aibotHandle.sendEventResult({event_id:e.event_id,status:a,...r,updated_at:Date.now()}),n=this.bindingStore.get(o)?.cwd??"";if(!n){t(),s("failed",{msg:"session binding was not found",code:g.bindingMissing});return}t(),await this.pool.removeSlot(o).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:n}),s("responded",{msg:`Session worker restarted for ${n}`})}async handlePiSessionControlRestartLocalAction(e){const o=e.params??{},t=String(o.session_id??"").trim(),i=(t?this.bindingStore.get(t):void 0)?.cwd??"",n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t){n("failed",void 0,"session_id_required","session_id is required for restart");return}if(!i){n("failed",void 0,g.bindingMissing,"Session binding missing. Open a workspace first.");return}await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i}),n("ok",{outcome:"restarted",binding:{aibotSessionId:t,cwd:i,workerStatus:"ready"}})}async bindSessionForPool(e,o){const t=String(o??"").trim();if(!e||!t)return;const s=this.pool.getOrCreateSlot(e);if(!s||(s.startPromise&&await s.startPromise,!s.adapter))return;const i=s.adapter instanceof A?s.adapter:null;if(!i?.hasSessionBinding)return;const n=await this.resolveCwdForBinding(t);i.announceDeferredComposing(e),await i.bindSession(e,n),this.sessionBindings.set(e,n),this.sessionScanCache.invalidate(),i.replayDeferredEvents(e)}deferredCallbacks(){return{captureEventRuntimeConfig:e=>this.captureEventRuntimeConfig(e),deliverInboundEvent:e=>this.pool.deliverInboundEvent(e),sendEventResult:(e,o,t)=>this.sendEventResultWithCleanup(e,o,t),sendSessionComposing:(e,o,t)=>{const s={};o&&(s.ttl_ms=t?.ttlMs??3e4,t?.activity&&(s.activity=t.activity)),this.aibotHandle.sendSessionActivitySet({session_id:e,kind:"composing",active:o,...s})}}}async handleOpenHumanSessionControlOpen(e,o){const t=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:o.session_id,received_at:Date.now()});try{await this.resolveCwdForBinding(e.args.trim()),await this.handleSessionControlForPool(e,o),V(e,o,this.sessionControlCtx(o.session_id),this.sessionControlSenders()),await this.deferredMgr.release(o.session_id,this.deferredCallbacks())}catch(s){t(),this.aibotHandle.sendEventResult({event_id:o.event_id,status:"failed",code:s?.cwdErrorCode,msg:s instanceof Error?s.message:String(s),updated_at:Date.now()})}}async handleCodeWhaleSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(a,r)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:a,...r,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const a=await this.resolveCwdForBinding(s),r=this.bindingStore.get(t);if(r?.cwd){if(await this.resolveCwdForBinding(r.cwd)!==a){i(),n("failed",{msg:`Session already bound to ${r.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}i(),n("responded",{msg:`Session already bound to ${r.cwd}`});return}this.bindingStore.set(t,a),this.sessionBindings.set(t,a),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),i(),n("responded",{msg:`Session bound to ${a}`})}catch(a){i(),n("failed",{code:g.invalidCwd,msg:a instanceof Error?a.message:String(a)})}}async handleCodeWhaleSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){n("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const a=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,a);const r=this.bindingStore.get(t);if(r?.cwd){const d=await this.resolveCwdForBinding(r.cwd);if(d!==a){n("failed",void 0,g.rebindForbidden,`Session already bound to ${r.cwd}`);return}this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,d)});return}this.bindingStore.set(t,a),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,a),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,a)})}catch(a){n("failed",void 0,a?.sessionControlErrorCode??g.invalidCwd,a instanceof Error?a.message:String(a))}}normalizeClaudeModeId(e){return String(e??"").trim().toLowerCase()===C.approval?C.approval:C.fullAuto}handleExecCommandOptions(e,o,t){const s=Array.isArray(t?.options)?t.options:[];if(s.length===0)return;const n=this.bindingStore.get(e)?.cwd??"",a={};if(o==="model"){a.available_models=s.map(d=>({id:d.id,displayName:d.label}));const r=s.find(d=>d.current);r&&(a.model_id=r.id)}else if(o==="mode"){a.available_modes=s.map(d=>({id:d.id,displayName:d.label}));const r=s.find(d=>d.current);r&&(a.mode_id=r.id)}else a[`${o}_options`]=s;this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:n,meta:a})}resolveSessionModelId(e){const o=this.bindingStore.getModelId(e);if(o)return o;const t=String(this.globalConfigStore?.get(this.name)?.modelId??"").trim();if(t)return this.bindingStore.setModelId(e,t),t}resolveCodexSessionModelId(e){const o=this.bindingStore.getCodexModelId(e);if(o)return o;const t=String(this.globalConfigStore?.get(this.name)?.codexModelId??"").trim();if(t)return this.bindingStore.setCodexModelId(e,t),t}buildCursorToolbarMeta(e){const o=this.pool.getSlot(e);if(o?.adapter instanceof M)return o.adapter.getToolbarMeta(e);const t=this.bindingStore.getModelId(e)??"auto",s=this.bindingStore.getCursorModeId(e)??"full_auto";return{model_id:t,mode_id:s,currentModelId:t,currentModeId:s,available_models:[],available_modes:ce.map(i=>({...i}))}}buildAgyToolbarMeta(e){if(!this.bindingStore.get(e))return;const t=he(this.config.agent.command),s=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||s;t.length>0&&!t.some(a=>a.id===i)&&(i=s);const n=ge();return{model_id:i,currentModelId:i,available_models:t.map(a=>({id:a.id,displayName:a.displayName})),...n.plan!==void 0&&{plan:n.plan},...n.quota_exhausted!==void 0&&{quota_exhausted:n.quota_exhausted},...n.quota_reset_at!==void 0&&{quota_reset_at:n.quota_reset_at},...n.available_credits!==void 0&&{available_credits:n.available_credits}}}async handleAgySetModel(e,o){const t=e.params??{},s=String(t.model_id??t.modelId??"").trim();if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for set_model"});return}if(!s){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"set_model_invalid",error_msg:"model_id is required"});return}const i=this.bindingStore.get(o);if(!i?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"session binding was not found"});return}i.modelId!==s&&(this.bindingStore.setModelId(o,s),this.globalConfigStore?.set(this.name,{modelId:s})),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:i.cwd,meta:this.buildAgyToolbarMeta(o)}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"model_set",model_id:s,binding:{cwd:i.cwd,model_id:s}}})}buildClaudeToolbarMeta(e){const o=this.bindingStore.get(e);if(!o)return;const t=F(),s=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||s;t.length>0&&!t.some(l=>l.id===i)&&(i=s);const n=this.normalizeClaudeModeId(o.modeId),a={model_id:i,mode_id:n,currentModelId:i,currentModeId:n,available_models:t.map(l=>({id:l.id,displayName:l.displayName}))},r=this.pool.getSlot(e),d=r?.adapter instanceof P?r.adapter.getSessionState():null;(d?.rateLimits?.fiveHour||d?.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=d);const c=d??this.getFreshClaudeRateLimitState();if(c){const l=c.rateLimits;l&&(l.fiveHour||l.sevenDay)&&(a.rate_limits={...l.fiveHour?{fiveHour:l.fiveHour}:{},...l.sevenDay?{sevenDay:l.sevenDay}:{},sampledAt:c.sampledAt||Date.now()})}if(d){const l=d.contextWindow;l.usedPercentage!=null&&(a.context_window={usedPercentage:l.usedPercentage,remainingPercentage:l.remainingPercentage})}if(!a.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const l=this.providerQuotaToRateLimits(this.cachedProviderQuota);l&&(a.rate_limits=l),u.info(this.name,`[toolbar-meta] provider quota fallback: hasCached=${!!this.cachedProviderQuota} fromProvider=${JSON.stringify(l)}`)}return a.rate_limits&&u.info(this.name,`[toolbar-meta] rate_limits included: ${JSON.stringify(a.rate_limits)}`),a}providerQuotaToCodexRateLimits(e){return ee(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return Z(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){const o=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(o)||/^\\\\/.test(o))){const i=new Error(`Specified path is not valid on this host: ${o}`);throw i.cwdErrorCode=g.invalidCwd,i}const t=x.resolve(o);let s;try{s=await D(t)}catch(i){const n=String(i?.code??"");if(n==="ENOENT"){const a=new Error(`Specified path does not exist: ${t}`);throw a.cwdErrorCode=g.invalidCwd,a}if(n==="EACCES"||n==="EPERM"){const a=new Error("Specified path is not accessible.");throw a.cwdErrorCode=g.invalidCwd,a}throw i}if(!s.isDirectory()){const i=new Error("Specified path is not a directory.");throw i.cwdErrorCode=g.invalidCwd,i}try{return await ne(t)}catch{return t}}getClaudeWorkerStatus(e){const o=this.pool.getSlot(e);return o?o.state==="starting"?"starting":o.state==="stopped"?"stopped":o.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,o){const t=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,t),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:t,cwd:o,meta:this.buildClaudeToolbarMeta(e)}),t}async handleSkillUploadLocalAction(e){const o=e.params??{},t=String(o.name??"").trim(),s=String(o.session_id??"").trim();if(!t){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_SKILL_NAME",error_msg:"name is required"});return}const i=z(this.config.adapterType,this.config.aibot.clientType),n=this.bindingStore.get(s)?.cwd||this.sessionBindings.get(s)||void 0,a=i==="kiro"?n:n||process.cwd();try{await fe(t,{mode:i,projectDir:a},{apiKey:this.config.aibot.apiKey,wsUrl:this.config.aibot.url}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:t}})}catch(r){u.warn(this.name,`skill_upload failed name=${t}: ${r instanceof Error?r.message:String(r)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"SKILL_UPLOAD_FAILED",error_msg:r instanceof Error?r.message:String(r)})}}reportSessionSkills(e){const o=z(this.config.adapterType,this.config.aibot.clientType),t=this.bindingStore.get(e)?.cwd||this.sessionBindings.get(e)||void 0,s=o==="kiro"?t:t||process.cwd();let i;try{i=pe({mode:o,projectDir:s})}catch{return}if(i.length===0)return;const n=JSON.stringify(i.map(a=>`${a.source}:${a.name}`));if(n!==this.lastReportedSkillsHash){this.lastReportedSkillsHash=n;try{this.aibotHandle.sendSkillsUpdate({skills:G(i,j.skills)})}catch{}}}async ensureSlotStarted(e,o=6e4){const t=this.pool.getOrCreateSlot(e);if(!t)throw new Error("Failed to allocate session slot");t.startPromise&&(u.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([t.startPromise,new Promise((s,i)=>setTimeout(()=>i(new Error(`ensureSlotStarted timeout (${o}ms) session=${e}`)),o))]),u.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveOrphanTitle(e){if(e){if(this.reasonixTitleScan){const o=Te(e);if(!o)return;const t=this.reasonixTitleScan.get().filter(s=>s.stamp===o);return t.length===1?t[0].title:void 0}if((this.config.adapterType??"acp")==="cursor")return this.sessionScanCache.get().find(t=>t.sessionId===e)?.title}}resolveAgentSessionId(e){switch(this.config.adapterType??"acp"){case"claude":return e.claudeSessionId;case"codex":return e.codexThreadId;case"pi":return e.piSessionPath;case"codewhale":return e.codewhaleThreadId;case"agy":return e.agyConversationId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":return e;default:return"acp"}}setResolvedAgentSessionId(e,o){const t=String(e??"").trim(),s=String(o??"").trim();if(!t||!s)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(t,s);break;case"codex":this.bindingStore.setCodexThreadId(t,s);break;case"pi":this.bindingStore.setPiSessionPath(t,s);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(t,s);break;case"agy":this.bindingStore.setAgyConversationId(t,s);break;default:this.bindingStore.setAcpSessionId(t,s);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const o=String(e??"").trim();if(!o)return"";const t=x.resolve(o);return process.platform==="win32"?t.toLowerCase():t}ensureImportedAgentSession(e,o){const t=String(e??"").trim();if(!t)return;const s=this.normalizePathForCompare(o);let i="";const n=this.config.adapterType??"acp";if(n==="codex"?i=this.sessionScanCache.get().find(d=>d.threadId===t)?.cwd??"":n==="claude"?i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??"":n==="cursor"?i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??"":n==="acp"&&(i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??""),!i){for(const[,r]of this.bindingStore.entries())if(this.resolveAgentSessionId(r)===t){i=r.cwd??"";break}}if(!i){const r=new Error(`agent session not found: ${t}`);throw r.sessionControlErrorCode=g.invalidAgentSession,r}const a=this.normalizePathForCompare(i);if(a&&s&&a!==s){const r=new Error(`agent session cwd mismatch: expected ${o}, got ${i}`);throw r.sessionControlErrorCode=g.invalidAgentSession,r}}buildOpenedBindingResult(e,o,t="ready"){const s=this.bindingStore.get(e),i=s?String(this.resolveAgentSessionId(s)??"").trim():"",n={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:o,workerStatus:t};return i&&(n.bindingId=i,n.agentSessionId=i),n}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"}async handleListSessionsTextCommand(e){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const o=this.config.adapterType??"acp",t=new Map;for(const r of this.pool.getAllSlots())t.set(r.sessionId,r);const s=Array.from(this.bindingStore.entries()),i=new Map;for(const[r,d]of s){const c=this.resolveAgentSessionId(d);if(c){const l=t.get(r),h=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(c,{aibotSessionId:r,workerStatus:h})}}const n=[],a=new Set;if(o==="codex"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.threadId);const c=i.get(d.threadId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.threadId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??(d.archived?"archived":"inactive")}`),n.push(` Created: ${new Date(d.createdAt).toISOString()}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="claude"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="acp"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="pi"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionPath);const c=i.get(d.sessionPath);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionPath}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="codewhale"||o==="opencode"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}for(const[r,d]of s){const c=this.resolveAgentSessionId(d);if(c&&a.has(c))continue;const l=t.get(r),h=l?l.adapter.getStatus().busy?"busy":"ready":"closed",m=this.resolveOrphanTitle(c)??(c?c.slice(0,8)+"\u2026":r.slice(0,8)+"\u2026");n.push(` Title: ${m}`),n.push(` AIBot: ${r}`),c&&n.push(` Agent: ${c}`),n.push(` CWD: ${d.cwd??"-"}`),n.push(` State: ${h}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}if(n.length===0){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:"No sessions found.",updated_at:Date.now()});return}this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Sessions (${n.filter(r=>r==="---").length}):
14
14
  ${n.join(`
15
15
  `)}`,updated_at:Date.now()})}async handleListSessionsLocalAction(e){const o=this.config.adapterType??"acp",t=new Map;for(const r of this.pool.getAllSlots())t.set(r.sessionId,r);const s=Array.from(this.bindingStore.entries()),i=new Map;for(const[r,d]of s){const c=this.resolveAgentSessionId(d);if(c){const l=t.get(r),h=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(c,{aibotSessionId:r,workerStatus:h,bindingUpdatedAt:d.updatedAt??0})}}const n=[],a=new Set;if(o==="codex"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.threadId);const c=i.get(d.threadId),l={agentSessionId:d.threadId,cwd:d.cwd||null,workerStatus:c?.workerStatus??(d.archived?"archived":"inactive"),createdAt:d.createdAt,updatedAt:d.updatedAt,archived:d.archived};c&&(l.aibotSessionId=c.aibotSessionId),d.title&&(l.title=d.title),n.push(l)}}else if(o==="claude"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId),l={agentSessionId:d.sessionId,cwd:d.cwd||null,workerStatus:c?.workerStatus??"inactive",updatedAt:d.updatedAt};c&&(l.aibotSessionId=c.aibotSessionId),d.title&&(l.title=d.title),n.push(l)}}else if(o==="acp"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId),l=c&&c.bindingUpdatedAt>0?c.bindingUpdatedAt:d.updatedAt,h={agentSessionId:d.sessionId,cwd:d.cwd||null,agentType:d.agentType,workerStatus:c?.workerStatus??"inactive",updatedAt:l};c&&(h.aibotSessionId=c.aibotSessionId),d.title&&(h.title=d.title),d.createdAt&&(h.createdAt=d.createdAt),n.push(h)}}else if(o==="pi"||o==="codewhale"||o==="opencode"){const r=this.sessionScanCache.get();for(const d of r){const c="sessionPath"in d?d.sessionPath:d.sessionId;a.add(c);const l=i.get(c),h={agentSessionId:c,cwd:d.cwd||null,workerStatus:l?.workerStatus??("archived"in d&&d.archived?"archived":"inactive"),updatedAt:l&&l.bindingUpdatedAt>0?l.bindingUpdatedAt:d.updatedAt};l&&(h.aibotSessionId=l.aibotSessionId),d.title&&(h.title=d.title),d.createdAt&&(h.createdAt=d.createdAt),"archived"in d&&(h.archived=d.archived),n.push(h)}}for(const[r,d]of s){const c=this.resolveAgentSessionId(d);if(c&&a.has(c))continue;const l=t.get(r),h=l?l.adapter.getStatus().busy?"busy":"ready":"closed",m={aibotSessionId:r,cwd:d.cwd??null,workerStatus:h,updatedAt:d.updatedAt,title:this.resolveOrphanTitle(c)??(c?`${c.slice(0,8)}\u2026`:`${r.slice(0,8)}\u2026`)};c&&(m.agentSessionId=c),n.push(m)}n.sort((r,d)=>d.updatedAt-r.updatedAt),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"sessions_listed",sessions:n,total:n.length}})}async handleSessionControlCommand(e,o){const t=o.session_id,s=(i,n,a)=>{this.aibotHandle.sendEventResult({event_id:o.event_id,status:i,...n?{msg:n}:{},...a?{code:a}:{},updated_at:Date.now()})};this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()});try{switch(e.verb){case p.open:{await B().catch(()=>{});const i=e.args.trim();if(!i){s("failed","Usage: /grix open <working-directory>",g.cwdRequired);return}let n="";try{n=await this.resolveCwdForBinding(i)}catch(r){s("failed",r instanceof Error?r.message:String(r),g.invalidCwd);return}const a=this.bindingStore.get(t);if(a?.cwd){const r=await this.resolveCwdForBinding(a.cwd);if(r!==n){s("failed","session binding cannot be changed to another working directory",g.rebindForbidden);return}this.bindingStore.ensureModeId(t,C.fullAuto),this.sessionBindings.set(t,r),await this.ensureSlotStarted(t),await this.deferredMgr.release(t,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(t,r),s("responded",`Working directory already bound: ${r}`);return}this.bindingStore.set(t,n,{modeId:C.fullAuto}),this.sessionBindings.set(t,n),await this.ensureSlotStarted(t),await this.deferredMgr.release(t,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(t,n),s("responded",`Session bound to ${n}`);return}case p.where:{const i=this.bindingStore.get(t);if(!i?.cwd){s("failed","session binding was not found",g.bindingMissing);return}s("responded",`Working directory: ${i.cwd}`);return}case p.status:{const i=this.bindingStore.get(t);if(!i?.cwd){s("failed","session binding was not found",g.bindingMissing);return}const n=this.normalizeClaudeModeId(i.modeId),a=this.getClaudeWorkerStatus(t);s("responded",`Status: worker=${a} mode=${n} cwd=${i.cwd}`);return}case p.stop:{const i=this.bindingStore.get(t);if(!i?.cwd){s("failed","session binding was not found",g.bindingMissing);return}await this.pool.removeSlot(t),this.claudeWorkerStatus.set(t,"stopped"),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"stopped",cwd:i.cwd}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"stopped",cwd:i.cwd,meta:this.buildClaudeToolbarMeta(t)}),s("responded",`Session worker stopped for ${i.cwd}`);return}case p.restart:{const i=this.bindingStore.get(t);if(!i?.cwd){s("failed","session binding was not found",g.bindingMissing);return}await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,i.cwd),s("responded",`Session worker restarted for ${i.cwd}`);return}case p.setMode:{const i=e.args.trim();if(!i){s("failed","Usage: /grix set_mode <mode-id>",T.modeInvalid);return}const n=this.normalizeClaudeModeId(i);if(n!==i.toLowerCase()){s("failed","set mode_id is invalid",T.modeInvalid);return}const a=this.bindingStore.get(t);if(!a?.cwd){s("failed","session binding was not found",g.bindingMissing);return}if(this.normalizeClaudeModeId(a.modeId)===n){s("responded",`Mode unchanged: ${n}`);return}if(this.getClaudeWorkerStatus(t)==="busy"){s("failed","\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148 /grix stop \u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u5F0F",g.workerBusy);return}this.bindingStore.setModeId(t,n),await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,a.cwd),s("responded",`Mode set to ${n}`);return}case p.setModel:{const i=e.args.trim();if(!i){s("failed","Usage: /grix set_model <model-id>");return}const n=this.bindingStore.get(t);if(!n?.cwd){s("failed","session binding was not found",g.bindingMissing);return}if((n.modelId??"")===i){s("responded",`Model unchanged: ${i}`);return}if(this.getClaudeWorkerStatus(t)==="busy"){s("failed","\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148 /grix stop \u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u578B",g.workerBusy);return}this.bindingStore.setModelId(t,i),this.globalConfigStore?.set(this.name,{modelId:i}),await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,n.cwd),s("responded",`Model set to ${i}`);return}case p.listOptions:{const i=F(),n=this.bindingStore.get(t),a=i.map(d=>d.id).join(", "),r=`${C.fullAuto}, ${C.approval}`;s("responded",`Modes (current: ${this.normalizeClaudeModeId(n?.modeId)}): ${r}
16
- Models (current: ${n?.modelId??"default"}): ${a}`);return}case p.exec:{const[i,...n]=e.args.trim().split(/\s+/);if(!i){s("failed","Usage: /grix exec <command> [args]",g.verbInvalid);return}const r=this.pool.getSlot(t)?.adapter;if(!r?.execCommand){s("failed","Agent does not support command execution",g.verbInvalid);return}const d=r.getSupportedCommands?.()??[];if(!d.some(c=>c.name===i)){s("failed",`Unknown command: ${i}. Supported: ${d.map(c=>c.name).join(", ")}`,g.verbInvalid);return}try{const c=await r.execCommand(i,n.join(" "),t);s(c.status==="ok"?"responded":"failed",c.message??`${i} ${c.status}`,c.status==="ok"?void 0:g.runtimeError)}catch(c){s("failed",`exec error: ${c instanceof Error?c.message:c}`,g.runtimeError)}return}default:s("failed",`Unsupported command for Claude: /grix ${e.verb}`,g.verbInvalid)}}catch(i){s("failed",i instanceof Error?i.message:String(i),g.runtimeError)}}async handleSessionControlLocalAction(e){const o=String(e.action_type??"").trim();if(o!==b.sessionControl&&o!==b.setMode&&o!=="set_mode"&&o!==b.setModel&&o!=="set_model")return!1;const t=e.params??{},s=String(t.session_id??"").trim(),i=o===b.setMode?p.setMode:o===b.setModel?p.setModel:String(t.verb??"").trim().toLowerCase();if(u.info(this.name,`handleSessionControlLocalAction verb=${i} action_id=${e.action_id} session_id=${s}`),!s)return this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:T.localActionRouteMissing,error_msg:"local action session_id is required"}),!0;const n=r=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:r})},a=(r,d)=>{u.warn(this.name,`session_control local_action failed action_id=${e.action_id} session_id=${s} verb=${i} code=${r} msg=${d}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:r,error_msg:d})};try{switch(i){case p.open:{await B().catch(()=>{});const r=String(t.cwd??"").trim(),d=String(t.agent_session_id??"").trim();if(!r)return a(g.cwdRequired,"session control cwd is required"),!0;u.info(this.name,`handleSessionControlLocalAction open cwd=${r} session_id=${s}`);const c=await this.resolveCwdForBinding(r);this.ensureImportedAgentSession(d,c);const l=this.bindingStore.get(s);if(l?.cwd){const h=await this.resolveCwdForBinding(l.cwd);return h!==c?(a(g.rebindForbidden,"session binding cannot be changed to another working directory"),!0):(this.bindingStore.ensureModeId(s,C.fullAuto),this.setResolvedAgentSessionId(s,d),this.sessionBindings.set(s,h),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,h),n({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,h),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0)}return this.bindingStore.set(s,c,{modeId:C.fullAuto}),this.setResolvedAgentSessionId(s,d),this.sessionBindings.set(s,c),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,c),n({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,c),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0}case p.status:case p.where:{const r=this.bindingStore.get(s);return r?.cwd?(n({outcome:i,binding:{cwd:r.cwd,mode_id:this.normalizeClaudeModeId(r.modeId),worker_status:this.getClaudeWorkerStatus(s)}}),!0):(a(g.bindingMissing,"session binding was not found"),!0)}case p.stop:{const r=this.bindingStore.get(s);return r?.cwd?(await this.pool.removeSlot(s),n({outcome:"stopped",binding:{cwd:r.cwd,mode_id:this.normalizeClaudeModeId(r.modeId),worker_status:"stopped"}}),!0):(a(g.bindingMissing,"session binding was not found"),!0)}case p.restart:{const r=this.bindingStore.get(s);return r?.cwd?(await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,r.cwd),n({outcome:"restarted",binding:{cwd:r.cwd,mode_id:this.normalizeClaudeModeId(r.modeId)}}),!0):(a(g.bindingMissing,"session binding was not found"),!0)}case p.setMode:{const r=String(t.mode_id??t.modeId??"").trim();if(!r)return a(T.modeInvalid,"set mode_id is invalid"),!0;const d=this.normalizeClaudeModeId(r);if(d!==r.toLowerCase())return a(T.modeInvalid,"set mode_id is invalid"),!0;const c=this.bindingStore.get(s);if(!c?.cwd)return a(g.bindingMissing,"session binding was not found"),!0;if(this.normalizeClaudeModeId(c.modeId)!==d){if(this.getClaudeWorkerStatus(s)==="busy")return a(g.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u5F0F"),!0;this.bindingStore.setModeId(s,d),await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,c.cwd)}return n({outcome:"mode_set",mode_id:d,binding:{cwd:c.cwd,mode_id:d}}),!0}case p.setModel:{const r=String(t.model_id??t.modelId??"").trim();if(!r)return a("set_model_invalid","model_id is required"),!0;const d=this.bindingStore.get(s);if(!d?.cwd)return a(g.bindingMissing,"session binding was not found"),!0;if((d.modelId??"")!==r){if(this.getClaudeWorkerStatus(s)==="busy")return a(g.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u578B"),!0;this.bindingStore.setModelId(s,r),this.globalConfigStore?.set(this.name,{modelId:r}),await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,d.cwd)}return n({outcome:"model_set",model_id:r,binding:{cwd:d.cwd,model_id:r}}),!0}case p.listOptions:{const r=F(),d=this.pool.getSlot(s);return n({modes:[C.fullAuto,C.approval],currentModeId:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId),models:r.map(c=>({modelId:c.id,name:c.displayName})),currentModelId:this.bindingStore.get(s)?.modelId??"",available_models:r.map(c=>({id:c.id,displayName:c.displayName})),agent_commands:d?.adapter?.getSupportedCommands?.()??[]}),!0}case p.exec:{const[r,...d]=String(t.args??"").trim().split(/\s+/);if(!r)return a(g.verbInvalid,"Usage: exec <command> [args]"),!0;await this.ensureSlotStarted(s);const l=this.pool.getSlot(s)?.adapter;if(!l?.execCommand)return a(g.verbInvalid,"Agent does not support command execution"),!0;const h=l.getSupportedCommands?.()??[];if(!h.some(m=>m.name===r))return a(g.verbInvalid,`Unknown command: ${r}. Supported: ${h.map(m=>m.name).join(", ")}`),!0;try{const m=await l.execCommand(r,d.join(" "),s);m.status==="ok"?n({outcome:"exec",command:r,message:m.message,data:m.data}):a(g.runtimeError,m.message??`${r} failed`)}catch(m){a(g.runtimeError,`exec error: ${m instanceof Error?m.message:m}`)}return!0}default:return a(g.verbInvalid,`session control verb ${i} is not supported`),!0}}catch(r){const d=r instanceof Error&&r.cwdErrorCode?r.cwdErrorCode:r instanceof Error&&r.sessionControlErrorCode?r.sessionControlErrorCode:g.runtimeError;return u.error(this.name,`handleSessionControlLocalAction error verb=${i} session_id=${s}: ${r instanceof Error?r.message:r}`),a(d,r instanceof Error?r.message:String(r)),!0}}async handleEventCancel(e){const{event_id:o,session_id:t}=e;if(u.info(this.name,`handleEventCancel start event_id=${o} session_id=${t}`),this.pool.cancelEvent(o,t)){if(!(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(o)??!1)){this.sendEventResultWithCleanup(o,"canceled","canceled"),this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!0,final_state:"canceled"});return}await this.waitForEventDone(o,t,15e3),this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!0,final_state:"canceled"}),this.pushQueueSnapshotForSession(t);return}this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!1,reason:"event not found or not cancelable"})}waitForEventDone(e,o,t){return new Promise(s=>{const i=this.pool.getSlot(o);if(!i?.adapter){s();return}const n=setTimeout(()=>{i.adapter.removeListener("eventDone",a),s()},t),a=r=>{r===e&&(clearTimeout(n),i.adapter.removeListener("eventDone",a),s())};i.adapter.on("eventDone",a)})}handleAibotStop(e){if(u.info(this.name,`[stop-trace] handleAibotStop begin session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"} adapterType=${this.config.adapterType??"acp"}`),this.aibotHandle.sendEventStopAck({stop_id:e.stop_id,event_id:e.event_id,accepted:!0,updated_at:Date.now()}),this.pool.removeQueuedEvent(e.session_id,e.event_id)){u.info(this.name,`[stop-trace] handleAibotStop removed queued(not-running) event -> stopResult(stopped) session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"}`),this.discardEventTrackingState(e.event_id),this.pushQueueSnapshotForSession(e.session_id),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()});return}const o=this.pool.getSlot(e.session_id),t=o?.adapter?.getStatus().busy??!1,s=(this.config.adapterType??"acp")==="acp",i=o?.adapter?.getActiveEventIds,n=typeof i=="function"?i.call(o.adapter):[],a=n.length>0?n.includes(e.event_id):t,r=(s||(this.config.adapterType??"acp")==="codex"||(this.config.adapterType??"acp")==="claude")&&a;if(u.info(this.name,`[stop-trace] handleAibotStop decision session=${e.session_id} event=${e.event_id} slotExists=${!!o?.adapter} busy=${t} activeIds=[${n.join(",")}] stoppingActiveEvent=${a} killOnStop=${r}`),a&&this.sendCtrl.markEventStopped(e.event_id),o?.adapter&&t){const d=r?this.pool.drainQueuedForSession(e.session_id):[];let c=!1,l=null;const h=v=>{c||(c=!0,l&&(clearTimeout(l),l=null),o.adapter.removeListener("eventDone",m),u.info(this.name,`[stop-trace] handleAibotStop ${v} -> stopResult(stopped) session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"} killOnStop=${r}`),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()}),r&&this.killAndResumeStopSlot(e.session_id,d))},m=v=>{v===e.event_id&&h("eventDone")};o.adapter.on("eventDone",m),l=setTimeout(()=>h("timeout"),At),this.pool.deliverStopEvent(e.event_id,e.session_id)}else u.info(this.name,`[stop-trace] handleAibotStop slot-not-busy -> immediate stopResult(stopped) session=${e.session_id} event=${e.event_id} slotExists=${!!o?.adapter}`),this.pool.deliverStopEvent(e.event_id,e.session_id),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()});(this.config.adapterType??"acp")==="pi"&&this.aibotHandle.sendText({event_id:e.event_id,session_id:e.session_id,content:"/stop",msg_type:0})}async killAndResumeStopSlot(e,o){if(!this.stopped){u.info(this.name,`[stop-trace] killAndResumeStopSlot begin session=${e} siblings=${o.length} -> removeSlot (kill process group)`);try{await this.pool.removeSlot(e),u.info(this.name,`[stop-trace] killAndResumeStopSlot removeSlot done session=${e} (process killed) -> redeliver ${o.length} sibling(s)`)}catch(t){u.warn(this.name,`[acp-stop] removeSlot failed session=${e}: ${t instanceof Error?t.message:String(t)}`)}if(!this.stopped)for(const t of o){if(this.stopped)break;try{await this.pool.deliverInboundEvent(t)}catch(s){u.error(this.name,`[acp-stop] sibling redeliver failed event=${t.event_id} session=${e}: ${s instanceof Error?s.message:String(s)}`),this.sendEventResultWithCleanup(t.event_id,"failed",s instanceof Error?s.message:String(s))}}}}handleAibotRevoke(e){if(!e.event_id||!this.revokeHandler.checkAndTrack(e.event_id))return;const o=e.event_id,t=e.session_id;if(t&&this.pool.cancelEvent(o,t)){(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(o)??!1)||this.sendEventResultWithCleanup(o,"canceled","revoked");return}if(this.deferredMgr.removeEvent(o)){this.aibotHandle.sendEventResult({event_id:o,status:"canceled",msg:"revoked",updated_at:Date.now()});return}this.pool.deliverStopEvent(o,t||void 0)}async handleConfigureGatewayProvider(e){const o=e.params??{},t=String(o.api_key??"").trim(),s=String(o.anthropic_base_url??"").trim(),i=String(o.openai_base_url??"").trim(),n=typeof o.provider_id=="string"&&o.provider_id.trim().toLowerCase()||void 0,a=typeof o.quota_base_url=="string"&&o.quota_base_url.trim()||void 0,r=typeof o.model=="string"&&o.model.trim()||void 0;let d=!1;if(!t){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_API_KEY",error_msg:"api_key is required"});return}const c=this.config.adapterType??"acp",l=c==="claude"||c==="codex";try{if(l){const h=c==="claude"?s:i;if(!h){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_BASE_URL",error_msg:`${c==="claude"?"anthropic_base_url":"openai_base_url"} is required`});return}const m=be();if(!m){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"PROXY_UNAVAILABLE",error_msg:"MITM proxy manager not initialized"});return}const v=we(c),f=Ce(c,h,t,{model:r});m.setRoute(f);for(const R of v)m.setHostDefaultRoute(R,f.routeKey);await m.setAgentRelayEnabled(this.name,!0,{relayHosts:v}),d=!await this.recycleAdaptersForRelayChange()}else{if(!this.providerConfigHandler){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"unsupported",error_code:"UNSUPPORTED_CLIENT_TYPE",error_msg:`client type "${c}" does not support Grix relay provider config`});return}await this.providerConfigHandler({...n?{provider_id:n}:{},base_url:i||void 0,...a?{quota_base_url:a}:{},api_key:t,model:r})}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0,restart_deferred:d}})}catch(h){u.error(this.name,`handleConfigureGatewayProvider failed: ${h}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"CONFIGURE_FAILED",error_msg:h instanceof Error?h.message:String(h)})}}async handleAibotLocalAction(e){const o=e.action_type??"",t=String((e.params??{}).session_id??""),s=String((e.params??{}).verb??"").trim().toLowerCase();u.debug(this.name,`local_action received action_type=${o} verb=${s||"-"} action_id=${e.action_id} session_id=${t}`);const i=(this.config.adapterType??"acp")==="claude";if(o===b.sessionControl&&s===p.exec&&await this.handleSessionControlLocalAction(e))return;if(o===b.sessionControl&&s===p.listSessions){await this.handleListSessionsLocalAction(e);return}if(o==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(i&&(o===b.interactionReply||o==="exec_approve"||o==="exec_reject")&&(await this.pool.deliverLocalAction(e)).handled||i&&await this.handleSessionControlLocalAction(e))return;if(o===b.sessionControl){const c=this.config.adapterType??"acp",l=c==="codex",h=c==="pi",m=String((e.params??{}).verb??"").trim().toLowerCase();if(l&&m===p.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(c==="cursor"&&m===p.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(l&&m==="restart"){const S=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:t,cwd:S,workerStatus:"ready"}}});return}if(h&&m===p.open){try{const _=e.params??{},S=String(_.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(S),E=String(_.agent_session_id??"").trim();this.ensureImportedAgentSession(E,w),this.bindingStore.set(t,w),this.setResolvedAgentSessionId(t,E),this.sessionBindings.set(t,w),await this.ensureSlotStarted(t).catch(I=>{u.warn("bridge",`pi ensureSlotStarted on local-action bind failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:w}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,w)}})}catch(_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_?.sessionControlErrorCode??_?.cwdErrorCode??g.invalidCwd,error_msg:_ instanceof Error?_.message:String(_)})}return}if(h&&m===p.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((c==="openhuman"||c==="opencode")&&m===p.open){try{const _=e.params??{},S=String(_.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(S),E=String(_.agent_session_id??"").trim();this.ensureImportedAgentSession(E,w),this.bindingStore.set(t,w),this.setResolvedAgentSessionId(t,E),this.sessionBindings.set(t,w),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,w)}})}catch(_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_?.sessionControlErrorCode??_?.cwdErrorCode??g.invalidCwd,error_msg:_ instanceof Error?_.message:String(_)})}return}if(c==="codewhale"&&m===p.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(c==="acp"&&m===p.stop){const S=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:t,cwd:S,workerStatus:"stopped"}}});return}try{if(m===p.open){const _=e.params??{},S=String(_.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=String(_.agent_session_id??"").trim();if(w){const E=await this.resolveCwdForBinding(S);this.ensureImportedAgentSession(w,E)}}await this.handleSessionControlLocalActionForPool(e)}catch(_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_?.sessionControlErrorCode??_?.cwdErrorCode??g.runtimeError,error_msg:_ instanceof Error?_.message:String(_)});return}if(m===p.open){const _=e.params??{},S=await this.resolveCwdForBinding(String(_.cwd??"").trim());this.setResolvedAgentSessionId(t,String(_.agent_session_id??"").trim()),c==="agy"&&(this.bindingStore.set(t,S),this.sessionBindings.set(t,S)),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,S)}}),(this.config.adapterType??"acp")==="agy"&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:S,meta:this.buildAgyToolbarMeta(t)})}else et(e,this.sessionControlCtx(t),this.sessionControlSenders());return}if(o==="file_list"){const c=Date.now(),l=t?this.bindingStore.get(t)?.cwd:void 0,h=e.params??{},m=String(h.parent_id??"").trim(),v=Array.isArray(h.allowed_extensions)?h.allowed_extensions.filter(S=>typeof S=="string").map(S=>S.trim()).filter(S=>S.length>0):[];u.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${t} parent_id=${m||"<root>"} show_hidden=${!!h.show_hidden} ext_count=${v.length} bound_cwd=${l??"<none>"}`);const f=await st({parent_id:m||null,session_id:t,show_hidden:!!h.show_hidden,allowed_extensions:v},{resolveCwd:()=>l??this.config.agent.cwd??process.cwd(),fallbackDir:X()}),R=Date.now()-c,_=f.result?.files?.length??0;u.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${f.status} elapsed=${R}ms count=${_} current_path=${f.result?.current_path??""} error_code=${f.error_code??""} error_msg=${f.error_msg??""}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:f.status,...f.result?{result:{...f.result,machine_name:at()}}:{},...f.error_code?{error_code:f.error_code}:{},...f.error_msg?{error_msg:f.error_msg}:{}});return}if(o==="create_folder"){const c=t?this.bindingStore.get(t)?.cwd:void 0,l=String((e.params??{}).parent_id??"").trim(),h=String((e.params??{}).name??"").trim(),m=await ot({parent_id:l||null,name:h,session_id:t},{resolveCwd:()=>c??this.config.agent.cwd??process.cwd(),fallbackDir:X()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:m.status,...m.result?{result:m.result}:{},...m.error_code?{error_code:m.error_code}:{},...m.error_msg?{error_msg:m.error_msg}:{}});return}if(o===b.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,t);return}if(o===b.getSessionUsage){await this.handleGetSessionUsage(e,t);return}if(o===b.getRateLimits){await this.handleGetRateLimits(e,t);return}const n=(this.config.adapterType??"acp")==="acp";if((i||n)&&o===b.threadCompact){await this.handleThreadCompact(e,t);return}if(o==="connector_rollback"){await this.handleConnectorRollback(e);return}if(o==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(o===b.getAgentGlobalConfig){const c=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...c?{config:c}:{config:null}}});return}if(o==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}const a=this.config.adapterType??"acp",r=(a==="codex"||a==="cursor"||a==="pi"||a==="openhuman"||a==="opencode"||a==="acp")&&!!t&&!!this.bindingStore.get(t)?.cwd,d=await this.pool.deliverLocalAction(e,{autoCreateSlot:r});if(d.handled){if(d.kind==="set_mode"){const c=String((e.params??{}).mode_id??"");c&&(a==="cursor"?this.bindingStore.setCursorModeId(t,c):a==="claude"?this.bindingStore.setModeId(t,c):L.has(a)||this.globalConfigStore?.set(this.name,{acpInitialMode:c}))}else if(d.kind==="set_model"){const c=String((e.params??{}).model_id??"");c&&(a==="cursor"?(this.bindingStore.setModelId(t,c),this.globalConfigStore?.set(this.name,{modelId:c})):a==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:c}):L.has(a)||this.globalConfigStore?.set(this.name,{modelId:c}))}else if(d.kind==="set_reasoning_effort"){const c=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");c&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:c})}else if(d.kind==="set_sandbox_mode"){const c=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(c){const l=c==="default"?void 0:c;this.globalConfigStore?.set(this.name,{codexSandboxMode:l})}}return}if((a==="codex"||a==="cursor"||a==="pi"||a==="openhuman"||a==="opencode")&&t&&!this.bindingStore.get(t)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(a==="acp"&&(o==="set_mode"||o==="set_model")){const c=this.sessionControlSenders(),l=this.pool.getSlot(t)?.adapter,h={bindingStore:this.bindingStore,acpAdapter:l instanceof A?l:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:u};if(o==="set_mode"){const m=String((e.params??{}).mode_id??""),v=await Y(h,t,m);if(v.status==="failed")c.sendLocalActionResult(e.action_id,"failed",void 0,v.errorCode,v.errorMsg);else{const f=l instanceof A?l.buildToolbarContext(v.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,R=f?{...f,...v.result}:v.result;c.sendLocalActionResult(e.action_id,"ok",R)}}else{const m=String((e.params??{}).model_id??""),v=await J(h,t,m);if(v.status==="failed")c.sendLocalActionResult(e.action_id,"failed",void 0,v.errorCode,v.errorMsg);else{const f=l instanceof A?l.buildToolbarContext(v.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,R=f?{...f,...v.result}:v.result;c.sendLocalActionResult(e.action_id,"ok",R)}}return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:`action type ${o} is not supported`})}async handleGetSessionUsage(e,o){if(!o){u.warn(this.name,`[usage] get_session_usage rejected: no session_id in params, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for get_session_usage"});return}const t=this.config.adapterType??"acp",s=this.bindingStore.get(o),i=s?.cwd??this.config.agent.cwd??process.cwd();u.info(this.name,`[usage] get_session_usage action_id=${e.action_id} session_id=${o} adapterType=${t} hasBinding=${!!s} cwd=${i}`);let n=null,a,r;switch(t){case"claude":{if(a=s?.claudeSessionId,!a){u.warn(this.name,`[usage] no claude binding for session_id=${o}, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Claude session binding found"});return}u.info(this.name,`[usage] parsing claude usage: claudeSessionId=${a} cwd=${i}`),n=await me(a,i),r="claude";break}case"agy":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"agy",available:!1,reason:"agy print-mode adapter does not track token usage"}});return}case"opencode":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"opencode",available:!1,reason:"opencode session usage parsing is not implemented"}});return}case"openhuman":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"openhuman",available:!1,reason:"openhuman is deprecated; session usage is not tracked"}});return}case"acp":default:{if(a=s?.acpSessionId,!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No ACP session binding found"});return}n=await ve(a,i,this.config.aibot.clientType),r=t,(!r||r==="acp")&&(r="acp");break}case"codex":{if(a=s?.codexThreadId,!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Codex thread binding found"});return}n=await Re(a),r="codex";break}case"pi":{if(a=s?.piSessionPath,!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Pi session path binding found"});return}n=await Be(a),r="pi";break}case"cursor":{const c=this.pool.getSlot(o)?.adapter;if(!(c instanceof M)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Cursor session found"});return}const l=c.getUsageSnapshot(o);if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"cursor",models:[{modelId:this.bindingStore.get(o)?.modelId??"auto",turns:l.turns,input:l.total.input,output:l.total.output,cacheRead:l.total.cacheRead,cacheWrite:l.total.cacheWrite}],total:{input:l.total.input,output:l.total.output,cacheRead:l.total.cacheRead,cacheWrite:l.total.cacheWrite},turns:l.turns,sampledAt:l.sampledAt}});return}case"codewhale":{const c=this.pool.getSlot(o)?.adapter;if(!(c instanceof N)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No CodeWhale session found"});return}const l=c.getUsageSnapshot();if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"codewhale",models:[{modelId:this.bindingStore.get(o)?.modelId??"codewhale",turns:l.turns,input:l.total.input,output:l.total.output}],total:{input:l.total.input,output:l.total.output},turns:l.turns,sampledAt:l.sampledAt}});return}}if(!n){u.info(this.name,`[usage] no usage data found: session_id=${o} adapterSessionId=${a} adapterType=${r}`);const d=String(this.config.aibot.clientType??"").trim().toLowerCase();if(t==="acp"&&new Set(["hermes","reasonix","kimi","copilot"]).has(d)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:d||"acp",available:!1,reason:`${d} session usage parsing is not available`}});return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}u.info(this.name,`[usage] result ok: session_id=${o} adapterSessionId=${a} turns=${n.turns} models=${n.models.length}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:a,adapterType:r,models:n.models,total:n.total,turns:n.turns,sampledAt:new Date().toISOString()}})}async handleThreadCompact(e,o){if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for thread_compact"});return}if(!this.bindingStore.get(o)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"session binding was not found"});return}try{await this.ensureSlotStarted(o);const i=this.pool.getSlot(o)?.adapter;if(!i?.execCommand){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:"Agent does not support command execution"});return}u.info(this.name,`thread_compact session_id=${o} action_id=${e.action_id}`);const n=await i.execCommand("compact","",o);n.status==="ok"?this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"compacted",message:n.message,data:n.data}}):this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:n.message??"compact failed"})}catch(s){u.warn(this.name,`thread_compact error session_id=${o}: ${s instanceof Error?s.message:s}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:s instanceof Error?s.message:String(s)})}}async handleGetRateLimits(e,o){const t=this.config.adapterType??"acp";if(this.config.aibot.clientType==="kiro"){const s=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs),i=this.cachedAcpContextWindow;if(s&&this.cachedProviderQuota){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!0,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:i,tokenUsage:null,providerQuota:this.cachedProviderQuota}});return}try{const n=await O();this.cachedProviderQuota=n,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[rate-limits] kiro quota queried: success=${n.success}`+(n.balance?` balance=${n.balance.remaining} ${n.balance.unit}`:"")+(n.error?` error=${n.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!1,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:i,tokenUsage:null,providerQuota:n}})}catch(n){u.warn(this.name,`[rate-limits] kiro quota query failed: ${n instanceof Error?n.message:String(n)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:i,tokenUsage:null}})}return}switch(t){case"codex":{const s=this.maybeQueryProviderQuota(),i=this.getFreshCodexGlobalRateLimitCache();if(i.hasData&&!this.isRateLimitsCacheFresh(this.cachedRateLimitsSampledAtMs)&&!this.isRateLimitsCacheFresh(this.cachedCodexUsageSampledAtMs)){const l=this.pool.getAllSlots().find(h=>h.state==="ready"&&h.adapter);if(l&&(u.info(this.name,`[rate-limits] codex cache stale, refreshing from slot: session=${l.sessionId}`),(await l.adapter.handleLocalAction?.(e))?.handled))return}if(i.hasData){i.rateLimits?u.info(this.name,`[rate-limits] codex cached: primary=${i.rateLimits.primary.usedPercent.toFixed(1)}% resetsAt=${i.rateLimits.primary.resetsAt} secondary=${i.rateLimits.secondary.usedPercent.toFixed(1)}% resetsAt=${i.rateLimits.secondary.resetsAt}`):u.info(this.name,`[rate-limits] codex cached context/token only: hasContext=${!!i.contextWindow} hasToken=${!!i.tokenUsage}`);const l=await s;this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:i.hasData||!!l,cached:!0,sampledAt:i.sampledAt,rateLimits:i.rateLimits,contextWindow:i.contextWindow,tokenUsage:i.tokenUsage,providerQuota:l}});return}const a=this.pool.getAllSlots().find(l=>l.state==="ready"&&l.adapter);if(a&&(u.info(this.name,`[rate-limits] codex reuse existing slot: session=${a.sessionId}`),(await a.adapter.handleLocalAction?.(e))?.handled))return;const r=this.resolveRateLimitWakeSessionId(o,t);if(r){const l=await this.wakeRateLimitSlot(r,t);if(l?.adapter&&(await l.adapter.handleLocalAction?.(e))?.handled)return}const d=await s,c=!!d;u.info(this.name,`[rate-limits] codex no native data, providerQuota=${d?d.provider:"none"} available=${c}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:c,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:d}});return}case"claude":{const s=this.maybeQueryProviderQuota(),i=this.getFreshClaudeRateLimitState();if(i){const c=i.rateLimits,l=await s;u.info(this.name,`[rate-limits] claude global cached: sampledAt=${i.sampledAt} hasRateLimits=${!!c}`+(l?` providerQuota=${l.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!0,sampledAt:i.sampledAt,rateLimits:i.rateLimits??null,contextWindow:i.contextWindow,tokenUsage:null,providerQuota:l}});return}let n=this.pool.getAllSlots().find(c=>c.state==="ready"&&c.adapter instanceof P)??null;if(!n){const c=this.resolveRateLimitWakeSessionId(o,t);c&&(n=await this.wakeRateLimitSlot(c,t))}u.info(this.name,`[rate-limits] handleGetRateLimits: session_id=${o} adapterType=claude hasSlot=${!!n} hasAdapter=${!!n?.adapter}`);const a=n?.adapter,r=a instanceof P?a.getSessionState():null,d=await s;if(r){(r.rateLimits?.fiveHour||r.rateLimits?.sevenDay||r.contextWindow?.usedPercentage!=null)&&(this.cachedClaudeRateLimitState=r);const c=this.getFreshClaudeRateLimitState(),l=c?.rateLimits&&!r.rateLimits?{...r,rateLimits:c.rateLimits}:r,h=l.rateLimits;u.info(this.name,`[rate-limits] claude global state: sampledAt=${l.sampledAt} hasRateLimits=${!!h}`+(h?` fiveHour=${h.fiveHour?.usedPercentage??"n/a"}% resetsAt=${h.fiveHour?.resetsAt??"n/a"} sevenDay=${h.sevenDay?.usedPercentage??"n/a"}% resetsAt=${h.sevenDay?.resetsAt??"n/a"}`:"")+(c?.rateLimits&&!r.rateLimits?" source=live+cached-fallback":" source=live")+(d?` providerQuota=${d.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!1,sampledAt:l.sampledAt,rateLimits:l.rateLimits??null,contextWindow:l.contextWindow,tokenUsage:null,providerQuota:d}})}else u.info(this.name,`[rate-limits] claude no global state: hasAdapter=${!!a} adapterType=${a?.constructor?.name??"n/a"}`+(d?` providerQuota=${d.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!!d,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:d}});return}case"cursor":{const i=(o?this.pool.getSlot(o):null)?.adapter;if(i instanceof M){await i.refreshAccountRateLimits({force:!0});const a=i.getRateLimitsSnapshot(o);u.info(this.name,`[rate-limits] cursor: available=${a.available} monthly=${a.rateLimits?.fiveHour?.usedPercentage??"n/a"}% api=${a.rateLimits?.sevenDay?.usedPercentage??"n/a"}%`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:a});return}const n=await le();u.info(this.name,`[rate-limits] cursor(no-slot): available=${n.available} monthly=${n.rateLimits?.fiveHour?.usedPercentage??"n/a"}% api=${n.rateLimits?.sevenDay?.usedPercentage??"n/a"}%`+(n.error?` error=${n.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"cursor",available:n.available,cached:!1,sampledAt:Number.isFinite(Date.parse(n.sampledAt))?Date.parse(n.sampledAt):Date.now(),rateLimits:n.rateLimits,contextWindow:null,tokenUsage:null,...n.displayMessage?{displayMessage:n.displayMessage}:{},...n.error?{error:n.error}:{}}});return}default:{const s=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&!!this.cachedProviderQuota,i=await this.maybeQueryProviderQuota();if(!i){u.info(this.name,`[rate-limits] no provider quota available for adapterType=${t}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null}});return}u.info(this.name,`[rate-limits] provider quota ${s?"cached":"queried"}: provider=${i.provider} success=${i.success}`+(i.tiers.length>0?` tiers=${i.tiers.map(n=>`${n.name}=${n.usedPercent}%`).join(",")}`:"")+(i.balance?` balance=${i.balance.remaining} ${i.balance.unit}`:"")+(i.error?` error=${i.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:s,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null,providerQuota:i}});return}}}resolveRateLimitWakeSessionId(e,o){const t=String(e??"").trim(),s=this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0});return s?t&&t===s?t:o==="codex"||o==="claude"?(t&&t!==s&&u.info(this.name,`[rate-limits] ${o} remap wake session: requested=${t} use_recent=${s}`),s):t&&t!==s?(u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=not_recent_session recent=${s}`),null):t||null:(u.info(this.name,`[rate-limits] skip wake slot: adapterType=${o} reason=no_recent_binding`),null)}async wakeRateLimitSlot(e,o){const t=String(e??"").trim();if(!t)return null;if(!this.bindingStore.get(t)?.cwd)return u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=binding_cwd_missing`),null;try{const i=this.pool.getOrCreateSlot(t);if(!i)return u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=slot_unavailable`),null;if(i.startPromise){const n=o==="claude"?6e4:2e4;await Promise.race([i.startPromise,new Promise((a,r)=>setTimeout(()=>r(new Error(`wake rate-limits slot timeout (${n}ms)`)),n))])}return u.info(this.name,`[rate-limits] wake slot success: session=${t} adapterType=${o}`),this.pool.getSlot(t)??i}catch(i){return u.warn(this.name,`[rate-limits] wake slot failed: session=${t} adapterType=${o} err=${i instanceof Error?i.message:String(i)}`),null}}sessionControlCtx(e){const o=this.pool.getSlot(e),t=o?.adapter instanceof A?o.adapter:null,s=(this.config.adapterType??"acp")==="acp",i={bindingStore:this.bindingStore,acpAdapter:t,globalConfigStore:this.globalConfigStore,agentName:this.name,log:u};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(t)return t.getSessionBindings();const n=this.sessionBindings;if(e&&!n.has(e)){const a=this.bindingStore.get(e);a?.cwd&&n.set(e,a.cwd)}return n},getStatus:()=>this.getStatus(),isAcpAlive:!!t?.isAlive(),getAcpSessionOptions:()=>t?.acpSessionOptions??null,setMode:n=>t?t.setMode(n):Promise.resolve(!1),setModel:n=>t?t.setModel(n):Promise.resolve(!1),acpSetMode:s?(n,a)=>Y(i,n,a):void 0,acpSetModel:s?(n,a)=>J(i,n,a):void 0,getPendingApproval:n=>{const a=t?.pendingApprovalEntries.get(n);return a?{requestId:a}:void 0},deletePendingApproval:n=>t?.pendingApprovalEntries.delete(n)??!1,respondPermission:(n,a)=>(t&&t.respondToPermission(n,a),Promise.resolve()),onSessionBound:(n,a)=>{this.bindingStore.set(n,a)},onSessionUnbound:n=>{const r=this.bindingStore.get(n)?.cwd??"";this.bindingStore.delete(n),this.sessionBindings.delete(n),this.sessionProviderHints.delete(n),this.sessionProviderQuotas.delete(n),this.sessionProviderMeta.delete(n),this.claudeWorkerStatus.delete(n),this.deferredMgr.clearSession(n);for(const d of this.pool.drainQueuedForSession(n))this.discardEventTrackingState(d.event_id);r&&this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:"stopped",cwd:r})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&o?.adapter instanceof K?(o.adapter.cancelCurrentRun(),Promise.resolve()):o?.adapter?.cancel("")??Promise.resolve(),onModeSet:n=>{const a=this.config.adapterType??"acp";L.has(a)||this.globalConfigStore?.set(this.name,{acpInitialMode:n})},onModelSet:n=>{const a=this.config.adapterType??"acp";L.has(a)||this.globalConfigStore?.set(this.name,{modelId:n})}}}sessionControlSenders(){return{sendEventAck:(e,o)=>this.aibotHandle.sendEventAck({event_id:e,session_id:o,received_at:Date.now()}),sendEventResult:(e,o,t)=>this.aibotHandle.sendEventResult({event_id:e,status:o,...t?.msg?{msg:t.msg}:{},...t?.code?{code:t.code}:{},updated_at:Date.now()}),sendLocalActionResult:(e,o,t,s,i)=>this.aibotHandle.sendLocalActionResult({action_id:e,status:o,...t?{result:t}:{},...s?{error_code:s}:{},...i?{error_msg:i}:{}})}}resolveBindingChannelKey(e){switch(e){case"claude":return"grix-claude";case"codex":return"codex";case"cursor":return"cursor";case"pi":return"pi";case"openhuman":return"openhuman";case"codewhale":return"codewhale";case"opencode":return"opencode";case"agy":return"acp";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,o){this.sendCtrl.finalizeThinking(e,o)}logInboundConversation(e){const o=String(e.session_id??"").trim();o&&this.conversationLog?.logInbound(o,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}buildInboundEvent(e,o){const t=ut(this.sendCtrl.getGlobalRuntimeConfig(),o);return{event_id:e.event_id,session_id:e.session_id,thread_id:e.thread_id,sender_id:e.sender_id,msg_id:e.msg_id,msg_type:e.msg_type,content:e.content??"",quoted_message_id:e.quoted_message_id,context_messages_json:this.buildContextMessagesJson(e.context_messages),extra_json:e.extra?JSON.stringify(e.extra):void 0,connector_runtime_config:{response_delivery:t.responseDelivery,tool_events:t.toolEvents,thinking_events:t.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const o=e.filter(t=>!tt(String(t?.content??"")));if(o.length!==0)return JSON.stringify(o)}isStaleEvent(e){const o=Number(e.created_at);return!Number.isFinite(o)||o<=0?!1:Date.now()-o>wt}async handleConnectorRollback(e){const o=String((e.params??{}).target_version??"").trim(),t=String((e.params??{}).reason??"server_initiated");if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_VERSION",error_msg:"target_version is required for connector_rollback"});return}u.info(this.name,`connector_rollback: target=${o} reason=${t}`);try{const{npmInstall:s,writePending:i,removePending:n,upgradeLog:a}=await import("../core/upgrade/npm-upgrader.js"),{resolveClientVersion:r}=await import("../core/util/client-version.js"),d=r();a(`server rollback: ${d} -> ${o} reason=${t}`),i(d,o),await s("grix-connector",o),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{rolled_back_to:o}}),process.kill(process.pid,"SIGTERM")}catch(s){try{const{removePending:n}=await import("../core/upgrade/npm-upgrader.js");n()}catch{}const i=s instanceof Error?s.message:String(s);u.error(this.name,`connector_rollback failed: ${i}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"ROLLBACK_FAILED",error_msg:i})}}setUpgradeTrigger(e){this.upgradeTrigger=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setSkillSyncHandler(e){this.skillSyncHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}isSharedInstance(){return!!this.config.aibot.sharedOwnerId}}export{Ti as AgentInstance};
16
+ Models (current: ${n?.modelId??"default"}): ${a}`);return}case p.exec:{const[i,...n]=e.args.trim().split(/\s+/);if(!i){s("failed","Usage: /grix exec <command> [args]",g.verbInvalid);return}const r=this.pool.getSlot(t)?.adapter;if(!r?.execCommand){s("failed","Agent does not support command execution",g.verbInvalid);return}const d=r.getSupportedCommands?.()??[];if(!d.some(c=>c.name===i)){s("failed",`Unknown command: ${i}. Supported: ${d.map(c=>c.name).join(", ")}`,g.verbInvalid);return}try{const c=await r.execCommand(i,n.join(" "),t);s(c.status==="ok"?"responded":"failed",c.message??`${i} ${c.status}`,c.status==="ok"?void 0:g.runtimeError)}catch(c){s("failed",`exec error: ${c instanceof Error?c.message:c}`,g.runtimeError)}return}default:s("failed",`Unsupported command for Claude: /grix ${e.verb}`,g.verbInvalid)}}catch(i){s("failed",i instanceof Error?i.message:String(i),g.runtimeError)}}async handleSessionControlLocalAction(e){const o=String(e.action_type??"").trim();if(o!==b.sessionControl&&o!==b.setMode&&o!=="set_mode"&&o!==b.setModel&&o!=="set_model")return!1;const t=e.params??{},s=String(t.session_id??"").trim(),i=o===b.setMode?p.setMode:o===b.setModel?p.setModel:String(t.verb??"").trim().toLowerCase();if(u.info(this.name,`handleSessionControlLocalAction verb=${i} action_id=${e.action_id} session_id=${s}`),!s)return this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:T.localActionRouteMissing,error_msg:"local action session_id is required"}),!0;const n=r=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:r})},a=(r,d)=>{u.warn(this.name,`session_control local_action failed action_id=${e.action_id} session_id=${s} verb=${i} code=${r} msg=${d}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:r,error_msg:d})};try{switch(i){case p.open:{await B().catch(()=>{});const r=String(t.cwd??"").trim(),d=String(t.agent_session_id??"").trim();if(!r)return a(g.cwdRequired,"session control cwd is required"),!0;u.info(this.name,`handleSessionControlLocalAction open cwd=${r} session_id=${s}`);const c=await this.resolveCwdForBinding(r);this.ensureImportedAgentSession(d,c);const l=this.bindingStore.get(s);if(l?.cwd){const h=await this.resolveCwdForBinding(l.cwd);return h!==c?(a(g.rebindForbidden,"session binding cannot be changed to another working directory"),!0):(this.bindingStore.ensureModeId(s,C.fullAuto),this.setResolvedAgentSessionId(s,d),this.sessionBindings.set(s,h),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,h),n({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,h),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0)}return this.bindingStore.set(s,c,{modeId:C.fullAuto}),this.setResolvedAgentSessionId(s,d),this.sessionBindings.set(s,c),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,c),n({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,c),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0}case p.status:case p.where:{const r=this.bindingStore.get(s);return r?.cwd?(n({outcome:i,binding:{cwd:r.cwd,mode_id:this.normalizeClaudeModeId(r.modeId),worker_status:this.getClaudeWorkerStatus(s)}}),!0):(a(g.bindingMissing,"session binding was not found"),!0)}case p.stop:{const r=this.bindingStore.get(s);return r?.cwd?(await this.pool.removeSlot(s),n({outcome:"stopped",binding:{cwd:r.cwd,mode_id:this.normalizeClaudeModeId(r.modeId),worker_status:"stopped"}}),!0):(a(g.bindingMissing,"session binding was not found"),!0)}case p.restart:{const r=this.bindingStore.get(s);return r?.cwd?(await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,r.cwd),n({outcome:"restarted",binding:{cwd:r.cwd,mode_id:this.normalizeClaudeModeId(r.modeId)}}),!0):(a(g.bindingMissing,"session binding was not found"),!0)}case p.setMode:{const r=String(t.mode_id??t.modeId??"").trim();if(!r)return a(T.modeInvalid,"set mode_id is invalid"),!0;const d=this.normalizeClaudeModeId(r);if(d!==r.toLowerCase())return a(T.modeInvalid,"set mode_id is invalid"),!0;const c=this.bindingStore.get(s);if(!c?.cwd)return a(g.bindingMissing,"session binding was not found"),!0;if(this.normalizeClaudeModeId(c.modeId)!==d){if(this.getClaudeWorkerStatus(s)==="busy")return a(g.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u5F0F"),!0;this.bindingStore.setModeId(s,d),await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,c.cwd)}return n({outcome:"mode_set",mode_id:d,binding:{cwd:c.cwd,mode_id:d}}),!0}case p.setModel:{const r=String(t.model_id??t.modelId??"").trim();if(!r)return a("set_model_invalid","model_id is required"),!0;const d=this.bindingStore.get(s);if(!d?.cwd)return a(g.bindingMissing,"session binding was not found"),!0;if((d.modelId??"")!==r){if(this.getClaudeWorkerStatus(s)==="busy")return a(g.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u578B"),!0;this.bindingStore.setModelId(s,r),this.globalConfigStore?.set(this.name,{modelId:r}),await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,d.cwd)}return n({outcome:"model_set",model_id:r,binding:{cwd:d.cwd,model_id:r}}),!0}case p.listOptions:{const r=F(),d=this.pool.getSlot(s);return n({modes:[C.fullAuto,C.approval],currentModeId:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId),models:r.map(c=>({modelId:c.id,name:c.displayName})),currentModelId:this.bindingStore.get(s)?.modelId??"",available_models:r.map(c=>({id:c.id,displayName:c.displayName})),agent_commands:d?.adapter?.getSupportedCommands?.()??[]}),!0}case p.exec:{const[r,...d]=String(t.args??"").trim().split(/\s+/);if(!r)return a(g.verbInvalid,"Usage: exec <command> [args]"),!0;await this.ensureSlotStarted(s);const l=this.pool.getSlot(s)?.adapter;if(!l?.execCommand)return a(g.verbInvalid,"Agent does not support command execution"),!0;const h=l.getSupportedCommands?.()??[];if(!h.some(m=>m.name===r))return a(g.verbInvalid,`Unknown command: ${r}. Supported: ${h.map(m=>m.name).join(", ")}`),!0;try{const m=await l.execCommand(r,d.join(" "),s);m.status==="ok"?n({outcome:"exec",command:r,message:m.message,data:m.data}):a(g.runtimeError,m.message??`${r} failed`)}catch(m){a(g.runtimeError,`exec error: ${m instanceof Error?m.message:m}`)}return!0}default:return a(g.verbInvalid,`session control verb ${i} is not supported`),!0}}catch(r){const d=r instanceof Error&&r.cwdErrorCode?r.cwdErrorCode:r instanceof Error&&r.sessionControlErrorCode?r.sessionControlErrorCode:g.runtimeError;return u.error(this.name,`handleSessionControlLocalAction error verb=${i} session_id=${s}: ${r instanceof Error?r.message:r}`),a(d,r instanceof Error?r.message:String(r)),!0}}async handleEventCancel(e){const{event_id:o,session_id:t}=e;if(u.info(this.name,`handleEventCancel start event_id=${o} session_id=${t}`),this.pool.cancelEvent(o,t)){if(!(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(o)??!1)){this.sendEventResultWithCleanup(o,"canceled","canceled"),this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!0,final_state:"canceled"});return}await this.waitForEventDone(o,t,15e3),this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!0,final_state:"canceled"}),this.pushQueueSnapshotForSession(t);return}this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!1,reason:"event not found or not cancelable"})}waitForEventDone(e,o,t){return new Promise(s=>{const i=this.pool.getSlot(o);if(!i?.adapter){s();return}const n=setTimeout(()=>{i.adapter.removeListener("eventDone",a),s()},t),a=r=>{r===e&&(clearTimeout(n),i.adapter.removeListener("eventDone",a),s())};i.adapter.on("eventDone",a)})}handleAibotStop(e){if(u.info(this.name,`[stop-trace] handleAibotStop begin session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"} adapterType=${this.config.adapterType??"acp"}`),this.aibotHandle.sendEventStopAck({stop_id:e.stop_id,event_id:e.event_id,accepted:!0,updated_at:Date.now()}),this.pool.removeQueuedEvent(e.session_id,e.event_id)){u.info(this.name,`[stop-trace] handleAibotStop removed queued(not-running) event -> stopResult(stopped) session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"}`),this.discardEventTrackingState(e.event_id),this.pushQueueSnapshotForSession(e.session_id),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()});return}const o=this.pool.getSlot(e.session_id),t=o?.adapter?.getStatus().busy??!1,s=(this.config.adapterType??"acp")==="acp",i=o?.adapter?.getActiveEventIds,n=typeof i=="function"?i.call(o.adapter):[],a=n.length>0?n.includes(e.event_id):t,r=(s||(this.config.adapterType??"acp")==="codex"||(this.config.adapterType??"acp")==="claude")&&a;if(u.info(this.name,`[stop-trace] handleAibotStop decision session=${e.session_id} event=${e.event_id} slotExists=${!!o?.adapter} busy=${t} activeIds=[${n.join(",")}] stoppingActiveEvent=${a} killOnStop=${r}`),a&&this.sendCtrl.markEventStopped(e.event_id),o?.adapter&&t){const d=r?this.pool.drainQueuedForSession(e.session_id):[];let c=!1,l=null;const h=v=>{c||(c=!0,l&&(clearTimeout(l),l=null),o.adapter.removeListener("eventDone",m),u.info(this.name,`[stop-trace] handleAibotStop ${v} -> stopResult(stopped) session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"} killOnStop=${r}`),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()}),r&&this.killAndResumeStopSlot(e.session_id,d))},m=v=>{v===e.event_id&&h("eventDone")};o.adapter.on("eventDone",m),l=setTimeout(()=>h("timeout"),At),this.pool.deliverStopEvent(e.event_id,e.session_id)}else u.info(this.name,`[stop-trace] handleAibotStop slot-not-busy -> immediate stopResult(stopped) session=${e.session_id} event=${e.event_id} slotExists=${!!o?.adapter}`),this.pool.deliverStopEvent(e.event_id,e.session_id),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()});(this.config.adapterType??"acp")==="pi"&&this.aibotHandle.sendText({event_id:e.event_id,session_id:e.session_id,content:"/stop",msg_type:0})}async killAndResumeStopSlot(e,o){if(!this.stopped){u.info(this.name,`[stop-trace] killAndResumeStopSlot begin session=${e} siblings=${o.length} -> removeSlot (kill process group)`);try{await this.pool.removeSlot(e),u.info(this.name,`[stop-trace] killAndResumeStopSlot removeSlot done session=${e} (process killed) -> redeliver ${o.length} sibling(s)`)}catch(t){u.warn(this.name,`[acp-stop] removeSlot failed session=${e}: ${t instanceof Error?t.message:String(t)}`)}if(!this.stopped)for(const t of o){if(this.stopped)break;try{await this.pool.deliverInboundEvent(t)}catch(s){u.error(this.name,`[acp-stop] sibling redeliver failed event=${t.event_id} session=${e}: ${s instanceof Error?s.message:String(s)}`),this.sendEventResultWithCleanup(t.event_id,"failed",s instanceof Error?s.message:String(s))}}}}handleAibotRevoke(e){if(!e.event_id||!this.revokeHandler.checkAndTrack(e.event_id))return;const o=e.event_id,t=e.session_id;if(t&&this.pool.cancelEvent(o,t)){(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(o)??!1)||this.sendEventResultWithCleanup(o,"canceled","revoked");return}if(this.deferredMgr.removeEvent(o)){this.aibotHandle.sendEventResult({event_id:o,status:"canceled",msg:"revoked",updated_at:Date.now()});return}this.pool.deliverStopEvent(o,t||void 0)}async handleConfigureGatewayProvider(e){const o=e.params??{},t=String(o.api_key??"").trim(),s=String(o.anthropic_base_url??"").trim(),i=String(o.openai_base_url??"").trim(),n=typeof o.provider_id=="string"&&o.provider_id.trim().toLowerCase()||void 0,a=typeof o.quota_base_url=="string"&&o.quota_base_url.trim()||void 0,r=typeof o.model=="string"&&o.model.trim()||void 0;let d=!1;if(!t){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_API_KEY",error_msg:"api_key is required"});return}const c=this.config.adapterType??"acp",l=c==="claude"||c==="codex";try{if(l){const h=c==="claude"?s:i;if(!h){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_BASE_URL",error_msg:`${c==="claude"?"anthropic_base_url":"openai_base_url"} is required`});return}const m=be();if(!m){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"PROXY_UNAVAILABLE",error_msg:"MITM proxy manager not initialized"});return}const v=we(c),f=Ce(c,h,t,{model:r});m.setRoute(f);for(const R of v)m.setHostDefaultRoute(R,f.routeKey);await m.setAgentRelayEnabled(this.name,!0,{relayHosts:v}),d=!await this.recycleAdaptersForRelayChange()}else{if(!this.providerConfigHandler){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"unsupported",error_code:"UNSUPPORTED_CLIENT_TYPE",error_msg:`client type "${c}" does not support Grix relay provider config`});return}await this.providerConfigHandler({...n?{provider_id:n}:{},base_url:i||void 0,...a?{quota_base_url:a}:{},api_key:t,model:r})}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0,restart_deferred:d}})}catch(h){u.error(this.name,`handleConfigureGatewayProvider failed: ${h}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"CONFIGURE_FAILED",error_msg:h instanceof Error?h.message:String(h)})}}async handleAibotLocalAction(e){const o=e.action_type??"",t=String((e.params??{}).session_id??""),s=String((e.params??{}).verb??"").trim().toLowerCase();u.debug(this.name,`local_action received action_type=${o} verb=${s||"-"} action_id=${e.action_id} session_id=${t}`);const i=(this.config.adapterType??"acp")==="claude";if(o===b.sessionControl&&s===p.exec&&await this.handleSessionControlLocalAction(e))return;if(o===b.sessionControl&&s===p.listSessions){await this.handleListSessionsLocalAction(e);return}if(o==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(i&&(o===b.interactionReply||o==="exec_approve"||o==="exec_reject")&&(await this.pool.deliverLocalAction(e)).handled||i&&await this.handleSessionControlLocalAction(e))return;if(o===b.sessionControl){const c=this.config.adapterType??"acp",l=c==="codex",h=c==="pi",m=String((e.params??{}).verb??"").trim().toLowerCase();if(l&&m===p.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(c==="cursor"&&m===p.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(l&&m==="restart"){const S=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:t,cwd:S,workerStatus:"ready"}}});return}if(h&&m===p.open){try{const _=e.params??{},S=String(_.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(S),E=String(_.agent_session_id??"").trim();this.ensureImportedAgentSession(E,w),this.bindingStore.set(t,w),this.setResolvedAgentSessionId(t,E),this.sessionBindings.set(t,w),await this.ensureSlotStarted(t).catch(I=>{u.warn("bridge",`pi ensureSlotStarted on local-action bind failed (non-fatal): ${I instanceof Error?I.message:String(I)}`)}),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:w}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,w)}})}catch(_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_?.sessionControlErrorCode??_?.cwdErrorCode??g.invalidCwd,error_msg:_ instanceof Error?_.message:String(_)})}return}if(h&&m===p.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((c==="openhuman"||c==="opencode")&&m===p.open){try{const _=e.params??{},S=String(_.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(S),E=String(_.agent_session_id??"").trim();this.ensureImportedAgentSession(E,w),this.bindingStore.set(t,w),this.setResolvedAgentSessionId(t,E),this.sessionBindings.set(t,w),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,w)}})}catch(_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_?.sessionControlErrorCode??_?.cwdErrorCode??g.invalidCwd,error_msg:_ instanceof Error?_.message:String(_)})}return}if(c==="codewhale"&&m===p.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(c==="acp"&&m===p.stop){const S=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:t,cwd:S,workerStatus:"stopped"}}});return}try{if(m===p.open){const _=e.params??{},S=String(_.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=String(_.agent_session_id??"").trim();if(w){const E=await this.resolveCwdForBinding(S);this.ensureImportedAgentSession(w,E)}}await this.handleSessionControlLocalActionForPool(e)}catch(_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_?.sessionControlErrorCode??_?.cwdErrorCode??g.runtimeError,error_msg:_ instanceof Error?_.message:String(_)});return}if(m===p.open){const _=e.params??{},S=await this.resolveCwdForBinding(String(_.cwd??"").trim());this.setResolvedAgentSessionId(t,String(_.agent_session_id??"").trim()),c==="agy"&&(this.bindingStore.set(t,S),this.sessionBindings.set(t,S)),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,S)}}),(this.config.adapterType??"acp")==="agy"&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:S,meta:this.buildAgyToolbarMeta(t)})}else et(e,this.sessionControlCtx(t),this.sessionControlSenders());return}if(o==="file_list"){const c=Date.now(),l=t?this.bindingStore.get(t)?.cwd:void 0,h=e.params??{},m=String(h.parent_id??"").trim(),v=Array.isArray(h.allowed_extensions)?h.allowed_extensions.filter(S=>typeof S=="string").map(S=>S.trim()).filter(S=>S.length>0):[];u.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${t} parent_id=${m||"<root>"} show_hidden=${!!h.show_hidden} ext_count=${v.length} bound_cwd=${l??"<none>"}`);const f=await st({parent_id:m||null,session_id:t,show_hidden:!!h.show_hidden,allowed_extensions:v},{resolveCwd:()=>l??this.config.agent.cwd??process.cwd(),fallbackDir:X()}),R=Date.now()-c,_=f.result?.files?.length??0;u.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${f.status} elapsed=${R}ms count=${_} current_path=${f.result?.current_path??""} error_code=${f.error_code??""} error_msg=${f.error_msg??""}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:f.status,...f.result?{result:{...f.result,machine_name:at()}}:{},...f.error_code?{error_code:f.error_code}:{},...f.error_msg?{error_msg:f.error_msg}:{}});return}if(o==="create_folder"){const c=t?this.bindingStore.get(t)?.cwd:void 0,l=String((e.params??{}).parent_id??"").trim(),h=String((e.params??{}).name??"").trim(),m=await ot({parent_id:l||null,name:h,session_id:t},{resolveCwd:()=>c??this.config.agent.cwd??process.cwd(),fallbackDir:X()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:m.status,...m.result?{result:m.result}:{},...m.error_code?{error_code:m.error_code}:{},...m.error_msg?{error_msg:m.error_msg}:{}});return}if(o===b.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,t);return}if(o===b.getSessionUsage){await this.handleGetSessionUsage(e,t);return}if(o===b.getRateLimits){await this.handleGetRateLimits(e,t);return}const n=(this.config.adapterType??"acp")==="acp";if((i||n)&&o===b.threadCompact){await this.handleThreadCompact(e,t);return}if(o==="connector_rollback"){await this.handleConnectorRollback(e);return}if(o==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(o===b.getAgentGlobalConfig){const c=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...c?{config:c}:{config:null}}});return}if(o==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}const a=this.config.adapterType??"acp",r=(a==="codex"||a==="cursor"||a==="pi"||a==="openhuman"||a==="opencode"||a==="acp")&&!!t&&!!this.bindingStore.get(t)?.cwd,d=await this.pool.deliverLocalAction(e,{autoCreateSlot:r});if(d.handled){if(d.kind==="set_mode"){const c=String((e.params??{}).mode_id??"");c&&(a==="cursor"?this.bindingStore.setCursorModeId(t,c):a==="claude"?this.bindingStore.setModeId(t,c):L.has(a)||this.globalConfigStore?.set(this.name,{acpInitialMode:c}))}else if(d.kind==="set_model"){const c=String((e.params??{}).model_id??"");c&&(a==="cursor"?(this.bindingStore.setModelId(t,c),this.globalConfigStore?.set(this.name,{modelId:c})):a==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:c}):L.has(a)||this.globalConfigStore?.set(this.name,{modelId:c}))}else if(d.kind==="set_reasoning_effort"){const c=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");c&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:c})}else if(d.kind==="set_sandbox_mode"){const c=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(c){const l=c==="default"?void 0:c;this.globalConfigStore?.set(this.name,{codexSandboxMode:l})}}return}if((a==="codex"||a==="cursor"||a==="pi"||a==="openhuman"||a==="opencode")&&t&&!this.bindingStore.get(t)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(a==="acp"&&(o==="set_mode"||o==="set_model")){const c=this.sessionControlSenders(),l=this.pool.getSlot(t)?.adapter,h={bindingStore:this.bindingStore,acpAdapter:l instanceof A?l:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:u};if(o==="set_mode"){const m=String((e.params??{}).mode_id??""),v=await Y(h,t,m);if(v.status==="failed")c.sendLocalActionResult(e.action_id,"failed",void 0,v.errorCode,v.errorMsg);else{const f=l instanceof A?l.buildToolbarContext(v.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,R=f?{...f,...v.result}:v.result;c.sendLocalActionResult(e.action_id,"ok",R)}}else{const m=String((e.params??{}).model_id??""),v=await J(h,t,m);if(v.status==="failed")c.sendLocalActionResult(e.action_id,"failed",void 0,v.errorCode,v.errorMsg);else{const f=l instanceof A?l.buildToolbarContext(v.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,R=f?{...f,...v.result}:v.result;c.sendLocalActionResult(e.action_id,"ok",R)}}return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:`action type ${o} is not supported`})}async handleGetSessionUsage(e,o){if(!o){u.warn(this.name,`[usage] get_session_usage rejected: no session_id in params, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for get_session_usage"});return}const t=this.config.adapterType??"acp",s=this.bindingStore.get(o),i=s?.cwd??this.config.agent.cwd??process.cwd();u.info(this.name,`[usage] get_session_usage action_id=${e.action_id} session_id=${o} adapterType=${t} hasBinding=${!!s} cwd=${i}`);let n=null,a,r;switch(t){case"claude":{if(a=s?.claudeSessionId,!a){u.warn(this.name,`[usage] no claude binding for session_id=${o}, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Claude session binding found"});return}u.info(this.name,`[usage] parsing claude usage: claudeSessionId=${a} cwd=${i}`),n=await me(a,i),r="claude";break}case"agy":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"agy print-mode adapter does not track token usage"});return}case"opencode":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"opencode session usage parsing is not implemented"});return}case"openhuman":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"openhuman is deprecated; session usage is not tracked"});return}case"acp":default:{if(a=s?.acpSessionId,!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No ACP session binding found"});return}n=await ve(a,i,this.config.aibot.clientType),r=t,(!r||r==="acp")&&(r="acp");break}case"codex":{if(a=s?.codexThreadId,!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Codex thread binding found"});return}n=await Re(a),r="codex";break}case"pi":{if(a=s?.piSessionPath,!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Pi session path binding found"});return}n=await Be(a),r="pi";break}case"cursor":{const c=this.pool.getSlot(o)?.adapter;if(!(c instanceof M)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Cursor session found"});return}const l=c.getUsageSnapshot(o);if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}const h={inputTokens:l.total.input,outputTokens:l.total.output,cacheReadInputTokens:l.total.cacheRead,cacheCreationInputTokens:l.total.cacheWrite};this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"cursor",models:[{model:this.bindingStore.get(o)?.modelId??"auto",turns:l.turns,total:h}],total:h,turns:l.turns,sampledAt:l.sampledAt}});return}case"codewhale":{const c=this.pool.getSlot(o)?.adapter;if(!(c instanceof N)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No CodeWhale session found"});return}const l=c.getUsageSnapshot();if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}const h={inputTokens:l.total.input,outputTokens:l.total.output,cacheReadInputTokens:0,cacheCreationInputTokens:0};this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"codewhale",models:[{model:this.bindingStore.get(o)?.modelId??"codewhale",turns:l.turns,total:h}],total:h,turns:l.turns,sampledAt:l.sampledAt}});return}}if(!n){u.info(this.name,`[usage] no usage data found: session_id=${o} adapterSessionId=${a} adapterType=${r}`);const d=String(this.config.aibot.clientType??"").trim().toLowerCase(),l=t==="acp"&&new Set(["hermes","reasonix","kimi","copilot"]).has(d)?`${d} session usage parsing is not available`:"No usage data found for this session";this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:l});return}u.info(this.name,`[usage] result ok: session_id=${o} adapterSessionId=${a} turns=${n.turns} models=${n.models.length}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:a,adapterType:r,models:n.models,total:n.total,turns:n.turns,sampledAt:new Date().toISOString()}})}async handleThreadCompact(e,o){if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for thread_compact"});return}if(!this.bindingStore.get(o)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"session binding was not found"});return}try{await this.ensureSlotStarted(o);const i=this.pool.getSlot(o)?.adapter;if(!i?.execCommand){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:"Agent does not support command execution"});return}u.info(this.name,`thread_compact session_id=${o} action_id=${e.action_id}`);const n=await i.execCommand("compact","",o);n.status==="ok"?this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"compacted",message:n.message,data:n.data}}):this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:n.message??"compact failed"})}catch(s){u.warn(this.name,`thread_compact error session_id=${o}: ${s instanceof Error?s.message:s}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:s instanceof Error?s.message:String(s)})}}async handleGetRateLimits(e,o){const t=this.config.adapterType??"acp";if(this.config.aibot.clientType==="kiro"){const s=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs),i=this.cachedAcpContextWindow;if(s&&this.cachedProviderQuota){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!0,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:i,tokenUsage:null,providerQuota:this.cachedProviderQuota}});return}try{const n=await O();this.cachedProviderQuota=n,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[rate-limits] kiro quota queried: success=${n.success}`+(n.balance?` balance=${n.balance.remaining} ${n.balance.unit}`:"")+(n.error?` error=${n.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!1,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:i,tokenUsage:null,providerQuota:n}})}catch(n){u.warn(this.name,`[rate-limits] kiro quota query failed: ${n instanceof Error?n.message:String(n)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:i,tokenUsage:null}})}return}switch(t){case"codex":{const s=this.maybeQueryProviderQuota(),i=this.getFreshCodexGlobalRateLimitCache();if(i.hasData&&!this.isRateLimitsCacheFresh(this.cachedRateLimitsSampledAtMs)&&!this.isRateLimitsCacheFresh(this.cachedCodexUsageSampledAtMs)){const l=this.pool.getAllSlots().find(h=>h.state==="ready"&&h.adapter);if(l&&(u.info(this.name,`[rate-limits] codex cache stale, refreshing from slot: session=${l.sessionId}`),(await l.adapter.handleLocalAction?.(e))?.handled))return}if(i.hasData){i.rateLimits?u.info(this.name,`[rate-limits] codex cached: primary=${i.rateLimits.primary.usedPercent.toFixed(1)}% resetsAt=${i.rateLimits.primary.resetsAt} secondary=${i.rateLimits.secondary.usedPercent.toFixed(1)}% resetsAt=${i.rateLimits.secondary.resetsAt}`):u.info(this.name,`[rate-limits] codex cached context/token only: hasContext=${!!i.contextWindow} hasToken=${!!i.tokenUsage}`);const l=await s;this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:i.hasData||!!l,cached:!0,sampledAt:i.sampledAt,rateLimits:i.rateLimits,contextWindow:i.contextWindow,tokenUsage:i.tokenUsage,providerQuota:l}});return}const a=this.pool.getAllSlots().find(l=>l.state==="ready"&&l.adapter);if(a&&(u.info(this.name,`[rate-limits] codex reuse existing slot: session=${a.sessionId}`),(await a.adapter.handleLocalAction?.(e))?.handled))return;const r=this.resolveRateLimitWakeSessionId(o,t);if(r){const l=await this.wakeRateLimitSlot(r,t);if(l?.adapter&&(await l.adapter.handleLocalAction?.(e))?.handled)return}const d=await s,c=!!d;u.info(this.name,`[rate-limits] codex no native data, providerQuota=${d?d.provider:"none"} available=${c}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:c,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:d}});return}case"claude":{const s=this.maybeQueryProviderQuota(),i=this.getFreshClaudeRateLimitState();if(i){const c=i.rateLimits,l=await s;u.info(this.name,`[rate-limits] claude global cached: sampledAt=${i.sampledAt} hasRateLimits=${!!c}`+(l?` providerQuota=${l.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!0,sampledAt:i.sampledAt,rateLimits:i.rateLimits??null,contextWindow:i.contextWindow,tokenUsage:null,providerQuota:l}});return}let n=this.pool.getAllSlots().find(c=>c.state==="ready"&&c.adapter instanceof P)??null;if(!n){const c=this.resolveRateLimitWakeSessionId(o,t);c&&(n=await this.wakeRateLimitSlot(c,t))}u.info(this.name,`[rate-limits] handleGetRateLimits: session_id=${o} adapterType=claude hasSlot=${!!n} hasAdapter=${!!n?.adapter}`);const a=n?.adapter,r=a instanceof P?a.getSessionState():null,d=await s;if(r){(r.rateLimits?.fiveHour||r.rateLimits?.sevenDay||r.contextWindow?.usedPercentage!=null)&&(this.cachedClaudeRateLimitState=r);const c=this.getFreshClaudeRateLimitState(),l=c?.rateLimits&&!r.rateLimits?{...r,rateLimits:c.rateLimits}:r,h=l.rateLimits;u.info(this.name,`[rate-limits] claude global state: sampledAt=${l.sampledAt} hasRateLimits=${!!h}`+(h?` fiveHour=${h.fiveHour?.usedPercentage??"n/a"}% resetsAt=${h.fiveHour?.resetsAt??"n/a"} sevenDay=${h.sevenDay?.usedPercentage??"n/a"}% resetsAt=${h.sevenDay?.resetsAt??"n/a"}`:"")+(c?.rateLimits&&!r.rateLimits?" source=live+cached-fallback":" source=live")+(d?` providerQuota=${d.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!1,sampledAt:l.sampledAt,rateLimits:l.rateLimits??null,contextWindow:l.contextWindow,tokenUsage:null,providerQuota:d}})}else u.info(this.name,`[rate-limits] claude no global state: hasAdapter=${!!a} adapterType=${a?.constructor?.name??"n/a"}`+(d?` providerQuota=${d.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!!d,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:d}});return}case"cursor":{const i=(o?this.pool.getSlot(o):null)?.adapter;if(i instanceof M){await i.refreshAccountRateLimits({force:!0});const a=i.getRateLimitsSnapshot(o);u.info(this.name,`[rate-limits] cursor: available=${a.available} monthly=${a.rateLimits?.fiveHour?.usedPercentage??"n/a"}% api=${a.rateLimits?.sevenDay?.usedPercentage??"n/a"}%`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:a});return}const n=await le();u.info(this.name,`[rate-limits] cursor(no-slot): available=${n.available} monthly=${n.rateLimits?.fiveHour?.usedPercentage??"n/a"}% api=${n.rateLimits?.sevenDay?.usedPercentage??"n/a"}%`+(n.error?` error=${n.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"cursor",available:n.available,cached:!1,sampledAt:Number.isFinite(Date.parse(n.sampledAt))?Date.parse(n.sampledAt):Date.now(),rateLimits:n.rateLimits,contextWindow:null,tokenUsage:null,...n.displayMessage?{displayMessage:n.displayMessage}:{},...n.error?{error:n.error}:{}}});return}default:{const s=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&!!this.cachedProviderQuota,i=await this.maybeQueryProviderQuota();if(!i){u.info(this.name,`[rate-limits] no provider quota available for adapterType=${t}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null}});return}u.info(this.name,`[rate-limits] provider quota ${s?"cached":"queried"}: provider=${i.provider} success=${i.success}`+(i.tiers.length>0?` tiers=${i.tiers.map(n=>`${n.name}=${n.usedPercent}%`).join(",")}`:"")+(i.balance?` balance=${i.balance.remaining} ${i.balance.unit}`:"")+(i.error?` error=${i.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:s,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null,providerQuota:i}});return}}}resolveRateLimitWakeSessionId(e,o){const t=String(e??"").trim(),s=this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0});return s?t&&t===s?t:o==="codex"||o==="claude"?(t&&t!==s&&u.info(this.name,`[rate-limits] ${o} remap wake session: requested=${t} use_recent=${s}`),s):t&&t!==s?(u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=not_recent_session recent=${s}`),null):t||null:(u.info(this.name,`[rate-limits] skip wake slot: adapterType=${o} reason=no_recent_binding`),null)}async wakeRateLimitSlot(e,o){const t=String(e??"").trim();if(!t)return null;if(!this.bindingStore.get(t)?.cwd)return u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=binding_cwd_missing`),null;try{const i=this.pool.getOrCreateSlot(t);if(!i)return u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=slot_unavailable`),null;if(i.startPromise){const n=o==="claude"?6e4:2e4;await Promise.race([i.startPromise,new Promise((a,r)=>setTimeout(()=>r(new Error(`wake rate-limits slot timeout (${n}ms)`)),n))])}return u.info(this.name,`[rate-limits] wake slot success: session=${t} adapterType=${o}`),this.pool.getSlot(t)??i}catch(i){return u.warn(this.name,`[rate-limits] wake slot failed: session=${t} adapterType=${o} err=${i instanceof Error?i.message:String(i)}`),null}}sessionControlCtx(e){const o=this.pool.getSlot(e),t=o?.adapter instanceof A?o.adapter:null,s=(this.config.adapterType??"acp")==="acp",i={bindingStore:this.bindingStore,acpAdapter:t,globalConfigStore:this.globalConfigStore,agentName:this.name,log:u};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(t)return t.getSessionBindings();const n=this.sessionBindings;if(e&&!n.has(e)){const a=this.bindingStore.get(e);a?.cwd&&n.set(e,a.cwd)}return n},getStatus:()=>this.getStatus(),isAcpAlive:!!t?.isAlive(),getAcpSessionOptions:()=>t?.acpSessionOptions??null,setMode:n=>t?t.setMode(n):Promise.resolve(!1),setModel:n=>t?t.setModel(n):Promise.resolve(!1),acpSetMode:s?(n,a)=>Y(i,n,a):void 0,acpSetModel:s?(n,a)=>J(i,n,a):void 0,getPendingApproval:n=>{const a=t?.pendingApprovalEntries.get(n);return a?{requestId:a}:void 0},deletePendingApproval:n=>t?.pendingApprovalEntries.delete(n)??!1,respondPermission:(n,a)=>(t&&t.respondToPermission(n,a),Promise.resolve()),onSessionBound:(n,a)=>{this.bindingStore.set(n,a)},onSessionUnbound:n=>{const r=this.bindingStore.get(n)?.cwd??"";this.bindingStore.delete(n),this.sessionBindings.delete(n),this.sessionProviderHints.delete(n),this.sessionProviderQuotas.delete(n),this.sessionProviderMeta.delete(n),this.claudeWorkerStatus.delete(n),this.deferredMgr.clearSession(n);for(const d of this.pool.drainQueuedForSession(n))this.discardEventTrackingState(d.event_id);r&&this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:"stopped",cwd:r})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&o?.adapter instanceof K?(o.adapter.cancelCurrentRun(),Promise.resolve()):o?.adapter?.cancel("")??Promise.resolve(),onModeSet:n=>{const a=this.config.adapterType??"acp";L.has(a)||this.globalConfigStore?.set(this.name,{acpInitialMode:n})},onModelSet:n=>{const a=this.config.adapterType??"acp";L.has(a)||this.globalConfigStore?.set(this.name,{modelId:n})}}}sessionControlSenders(){return{sendEventAck:(e,o)=>this.aibotHandle.sendEventAck({event_id:e,session_id:o,received_at:Date.now()}),sendEventResult:(e,o,t)=>this.aibotHandle.sendEventResult({event_id:e,status:o,...t?.msg?{msg:t.msg}:{},...t?.code?{code:t.code}:{},updated_at:Date.now()}),sendLocalActionResult:(e,o,t,s,i)=>this.aibotHandle.sendLocalActionResult({action_id:e,status:o,...t?{result:t}:{},...s?{error_code:s}:{},...i?{error_msg:i}:{}})}}resolveBindingChannelKey(e){switch(e){case"claude":return"grix-claude";case"codex":return"codex";case"cursor":return"cursor";case"pi":return"pi";case"openhuman":return"openhuman";case"codewhale":return"codewhale";case"opencode":return"opencode";case"agy":return"acp";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,o){this.sendCtrl.finalizeThinking(e,o)}logInboundConversation(e){const o=String(e.session_id??"").trim();o&&this.conversationLog?.logInbound(o,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}buildInboundEvent(e,o){const t=ut(this.sendCtrl.getGlobalRuntimeConfig(),o);return{event_id:e.event_id,session_id:e.session_id,thread_id:e.thread_id,sender_id:e.sender_id,msg_id:e.msg_id,msg_type:e.msg_type,content:e.content??"",quoted_message_id:e.quoted_message_id,context_messages_json:this.buildContextMessagesJson(e.context_messages),extra_json:e.extra?JSON.stringify(e.extra):void 0,connector_runtime_config:{response_delivery:t.responseDelivery,tool_events:t.toolEvents,thinking_events:t.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const o=e.filter(t=>!tt(String(t?.content??"")));if(o.length!==0)return JSON.stringify(o)}isStaleEvent(e){const o=Number(e.created_at);return!Number.isFinite(o)||o<=0?!1:Date.now()-o>wt}async handleConnectorRollback(e){const o=String((e.params??{}).target_version??"").trim(),t=String((e.params??{}).reason??"server_initiated");if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_VERSION",error_msg:"target_version is required for connector_rollback"});return}u.info(this.name,`connector_rollback: target=${o} reason=${t}`);try{const{npmInstall:s,writePending:i,removePending:n,upgradeLog:a}=await import("../core/upgrade/npm-upgrader.js"),{resolveClientVersion:r}=await import("../core/util/client-version.js"),d=r();a(`server rollback: ${d} -> ${o} reason=${t}`),i(d,o),await s("grix-connector",o),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{rolled_back_to:o}}),process.kill(process.pid,"SIGTERM")}catch(s){try{const{removePending:n}=await import("../core/upgrade/npm-upgrader.js");n()}catch{}const i=s instanceof Error?s.message:String(s);u.error(this.name,`connector_rollback failed: ${i}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"ROLLBACK_FAILED",error_msg:i})}}setUpgradeTrigger(e){this.upgradeTrigger=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setSkillSyncHandler(e){this.skillSyncHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}isSharedInstance(){return!!this.config.aibot.sharedOwnerId}}export{Ti as AgentInstance};