grix-connector 3.22.0 → 3.23.0

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 +1 @@
1
- import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const n of t)e.push(n);const r=Buffer.concat(e).toString("utf8").trim();return r?JSON.parse(r):{}}function k(t){const e=(t.headers.authorization??"").trim();return e.toLowerCase().startsWith("bearer ")?e.slice(7).trim():""}class w{host="127.0.0.1";port=0;token;callbacks;server=null;address=null;constructor(e){this.token=d(),this.callbacks=e}getToken(){return this.token}getURL(){return this.address?`http://${this.address.address}:${this.address.port}`:""}async start(){this.server||(this.server=c.createServer(async(e,r)=>{try{await this.handleRequest(e,r)}catch(n){h(r,n instanceof Error?n.message:String(n))}}),await new Promise((e,r)=>{this.server.once("error",r),this.server.listen(this.port,this.host,()=>{this.server.off("error",r),e()})}),this.address=this.server.address(),o.info("claude-bridge",`Bridge server listening on ${this.getURL()}`))}async stop(){if(!this.server)return;const e=this.server;this.server=null,this.address=null,e.closeIdleConnections?.(),e.closeAllConnections?.(),await new Promise((r,n)=>{e.close(s=>s?n(s):r())})}async handleRequest(e,r){if(k(e)!==this.token){l(r);return}if(e.method!=="POST"){r.writeHead(405,{"content-type":"application/json"}),r.end(JSON.stringify({error:"method_not_allowed"}));return}const n=new URL(e.url,"http://localhost").pathname,s=await v(e),i=f.get(n);if(!i){u(r);return}const a=await i(this.callbacks,s);p(r,a??{ok:!0})}}const f=new Map([["/v1/worker/register",async(t,e)=>(o.info("claude-bridge",`Worker registered: ${e.worker_id} (pid=${e.pid})`),t.onRegisterWorker(e))],["/v1/worker/status",async(t,e)=>(o.info("claude-bridge",`Worker status: ${e.status}`),t.onStatusUpdate(e))],["/v1/worker/send-text",async(t,e)=>t.onSendText(e)],["/v1/worker/send-stream-chunk",async(t,e)=>t.onSendStreamChunk(e)],["/v1/worker/send-media",async(t,e)=>t.onSendMedia(e)],["/v1/worker/delete-message",async(t,e)=>t.onDeleteMessage(e)],["/v1/worker/ack-event",async(t,e)=>t.onAckEvent(e)],["/v1/worker/event-result",async(t,e)=>t.onSendEventResult(e)],["/v1/worker/event-stop-ack",async(t,e)=>t.onSendEventStopAck(e)],["/v1/worker/event-stop-result",async(t,e)=>t.onSendEventStopResult(e)],["/v1/worker/session-composing",async(t,e)=>t.onSetSessionComposing(e)],["/v1/worker/agent-invoke",async(t,e)=>t.onAgentInvoke(e)],["/v1/worker/local-action-result",async(t,e)=>t.onLocalActionResult(e)]]);export{w as ClaudeBridgeServer};
1
+ import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const r of t)e.push(r);const n=Buffer.concat(e).toString("utf8").trim();return n?JSON.parse(n):{}}function k(t){const e=(t.headers.authorization??"").trim();return e.toLowerCase().startsWith("bearer ")?e.slice(7).trim():""}class w{host="127.0.0.1";port=0;token;callbacks;server=null;address=null;constructor(e){this.token=d(),this.callbacks=e}getToken(){return this.token}getURL(){return this.address?`http://${this.address.address}:${this.address.port}`:""}async start(){this.server||(this.server=c.createServer(async(e,n)=>{try{await this.handleRequest(e,n)}catch(r){h(n,r instanceof Error?r.message:String(r))}}),await new Promise((e,n)=>{this.server.once("error",n),this.server.listen(this.port,this.host,()=>{this.server.off("error",n),e()})}),this.address=this.server.address(),o.info("claude-bridge",`Bridge server listening on ${this.getURL()}`))}async stop(){if(!this.server)return;const e=this.server;this.server=null,this.address=null,e.closeIdleConnections?.(),e.closeAllConnections?.(),await new Promise((n,r)=>{e.close(s=>s?r(s):n())})}async handleRequest(e,n){if(k(e)!==this.token){l(n);return}if(e.method!=="POST"){n.writeHead(405,{"content-type":"application/json"}),n.end(JSON.stringify({error:"method_not_allowed"}));return}const r=new URL(e.url,"http://localhost").pathname,s=await v(e),i=f.get(r);if(!i){u(n);return}const a=await i(this.callbacks,s);p(n,a??{ok:!0})}}const f=new Map([["/v1/worker/register",async(t,e)=>(o.info("claude-bridge",`Worker registered: ${e.worker_id} (pid=${e.pid})`),t.onRegisterWorker(e))],["/v1/worker/status",async(t,e)=>(o.info("claude-bridge",`Worker status: ${e.status}`),t.onStatusUpdate(e))],["/v1/worker/send-text",async(t,e)=>t.onSendText(e)],["/v1/worker/send-stream-chunk",async(t,e)=>t.onSendStreamChunk(e)],["/v1/worker/send-media",async(t,e)=>t.onSendMedia(e)],["/v1/worker/delete-message",async(t,e)=>t.onDeleteMessage(e)],["/v1/worker/ack-event",async(t,e)=>t.onAckEvent(e)],["/v1/worker/event-result",async(t,e)=>t.onSendEventResult(e)],["/v1/worker/event-stop-ack",async(t,e)=>t.onSendEventStopAck(e)],["/v1/worker/event-stop-result",async(t,e)=>t.onSendEventStopResult(e)],["/v1/worker/session-composing",async(t,e)=>t.onSetSessionComposing(e)],["/v1/worker/agent-invoke",async(t,e)=>t.onAgentInvoke(e)],["/v1/worker/local-action-result",async(t,e)=>t.onLocalActionResult(e)]]);export{w as ClaudeBridgeServer};
@@ -1 +1 @@
1
- import{randomUUID as x}from"node:crypto";import{CallToolRequestSchema as S,ListToolsRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{log as f}from"../../core/log/index.js";import{toolCallToInvoke as k}from"../../core/mcp/tools.js";const E=new Set(["contact_search","session_search","message_history","message_search","group_create","group_detail_read","group_leave_self","group_member_add","group_member_remove","group_member_role_update","group_all_members_muted_update","group_member_speaking_update","group_dissolve","send_msg","delete_msg","agent_api_create","agent_category_list","agent_category_create","agent_category_update","agent_category_assign","agent_api_key_rotate"]),y=3e4,I=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},files:{type:"array",items:{type:"string"},description:"Optional absolute local file paths. Each file is uploaded through Agent API OSS presign before sending."},final:{type:"boolean",description:"Whether this is the final reply for the event. Defaults to false \u2014 the event stays open while Claude continues working, and auto-completes after inactivity. Set true only when this is definitively the last message for the event."}},required:["chat_id","event_id"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},code:{type:"string"},msg:{type:"string"}},required:["event_id","status"]}},{name:"delete_message",description:"Delete a previously sent message in the same grix-claude chat.",inputSchema:{type:"object",properties:{chat_id:{type:"string"},message_id:{type:"string"}},required:["chat_id","message_id"]}},{name:"status",description:"Show grix-claude runtime status, upstream access state, bridge health, and startup hints.",inputSchema:{type:"object",properties:{}}},{name:"send",description:"Send a message to a chat session proactively, without requiring an inbound event. Use for notifications or scheduled reports.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The target chat/session id."},text:{type:"string",description:"The message text to send."}},required:["chat_id","text"]}},{name:"access_pair",description:"Forward a sender pairing approval code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"access_deny",description:"Forward a sender pairing denial code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"allow_sender",description:"Ask upstream access control to allow a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"remove_sender",description:"Ask upstream access control to remove a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"access_policy",description:"Ask upstream access control to update the sender access policy.",inputSchema:{type:"object",properties:{policy:{type:"string",enum:["allowlist","open","disabled"]}},required:["policy"]}},{name:"grix_query",description:"Search contacts, sessions, message history, or messages by keyword in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},keyword:{type:"string"},id:{type:"string"},sessionId:{type:"string"},limit:{type:"number"},offset:{type:"number"},beforeId:{type:"string"}},required:["action"]}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string"},memberIds:{type:"array",items:{type:"string"}},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer",description:"Member type (for update_member_role / update_member_speaking)."},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted (for update_member_speaking)."}},required:["action"]}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},content:{type:"string"},msgType:{type:"number"},quotedMessageId:{type:"string"},threadId:{type:"string"}},required:["sessionId","content"]}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},msgId:{type:"string"}},required:["sessionId","msgId"]}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentId:{type:"string"},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"number"}},required:["action"]}}];function q(n,e){n.setRequestHandler(w,async()=>({tools:I})),n.setRequestHandler(S,async i=>{const{name:r,arguments:t}=i.params,s=t??{};try{switch(r){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(r,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(r,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${r}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${r} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(n,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const r=String(n.text??""),t=String(n.chat_id??""),s=String(n.event_id??i.eventId),a=n.reply_to,d=n.files,_=n.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!r.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,r),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(n,e){const i=e.getActiveEvent(),r=String(n.event_id??""),t=n.status??"",s=n.code,a=n.msg;if(!r||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(r)?(e.bridge.sendEventResult(r,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(n,e){const i=String(n.chat_id??""),r=String(n.message_id??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:r},y),c(`deleted (${r})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(n){const e=n.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(n,e){const i=String(n.chat_id??""),r=String(n.text??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(r),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(n,e,i){try{const r=C[n];if(!r)throw new Error(`Unknown access control tool: ${n}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:r.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}async function O(n,e,i){try{const r=k(n,e);if(!E.has(r.action))throw new Error(`Action not allowed: ${r.action}`);const t=await i.bridge.agentInvoke(r.action,r.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}function c(n){return{content:[{type:"text",text:n}]}}export{q as registerClaudeTools};
1
+ import{randomUUID as x}from"node:crypto";import{CallToolRequestSchema as S,ListToolsRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{log as f}from"../../core/log/index.js";import{toolCallToInvoke as k}from"../../core/mcp/tools.js";const E=new Set(["contact_search","session_search","message_history","message_search","group_create","group_detail_read","group_leave_self","group_member_add","group_member_remove","group_member_role_update","group_all_members_muted_update","group_member_speaking_update","group_dissolve","send_msg","delete_msg","agent_api_create","agent_category_list","agent_category_create","agent_category_update","agent_category_assign","agent_api_key_rotate"]),y=3e4,I=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},files:{type:"array",items:{type:"string"},description:"Optional absolute local file paths. Each file is uploaded through Agent API OSS presign before sending."},final:{type:"boolean",description:"Whether this is the final reply for the event. Defaults to false \u2014 the event stays open while Claude continues working, and auto-completes after inactivity. Set true only when this is definitively the last message for the event."}},required:["chat_id","event_id"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},code:{type:"string"},msg:{type:"string"}},required:["event_id","status"]}},{name:"delete_message",description:"Delete a previously sent message in the same grix-claude chat.",inputSchema:{type:"object",properties:{chat_id:{type:"string"},message_id:{type:"string"}},required:["chat_id","message_id"]}},{name:"status",description:"Show grix-claude runtime status, upstream access state, bridge health, and startup hints.",inputSchema:{type:"object",properties:{}}},{name:"send",description:"Send a message to a chat session proactively, without requiring an inbound event. Use for notifications or scheduled reports.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The target chat/session id."},text:{type:"string",description:"The message text to send."}},required:["chat_id","text"]}},{name:"access_pair",description:"Forward a sender pairing approval code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"access_deny",description:"Forward a sender pairing denial code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"allow_sender",description:"Ask upstream access control to allow a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"remove_sender",description:"Ask upstream access control to remove a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"access_policy",description:"Ask upstream access control to update the sender access policy.",inputSchema:{type:"object",properties:{policy:{type:"string",enum:["allowlist","open","disabled"]}},required:["policy"]}},{name:"grix_query",description:"Search contacts, sessions, message history, or messages by keyword in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},keyword:{type:"string"},id:{type:"string"},sessionId:{type:"string"},limit:{type:"number"},offset:{type:"number"},beforeId:{type:"string"}},required:["action"]}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string"},memberIds:{type:"array",items:{type:"string"}},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer",description:"Member type (for update_member_role / update_member_speaking)."},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted (for update_member_speaking)."}},required:["action"]}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},content:{type:"string"},msgType:{type:"number"},quotedMessageId:{type:"string"},threadId:{type:"string"}},required:["sessionId","content"]}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},msgId:{type:"string"}},required:["sessionId","msgId"]}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentId:{type:"string"},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"number"}},required:["action"]}}];function q(r,e){r.setRequestHandler(w,async()=>({tools:I})),r.setRequestHandler(S,async i=>{const{name:n,arguments:t}=i.params,s=t??{};try{switch(n){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(n,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(n,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${n}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${n} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(r,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const n=String(r.text??""),t=String(r.chat_id??""),s=String(r.event_id??i.eventId),a=r.reply_to,d=r.files,_=r.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!n.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,n),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(r,e){const i=e.getActiveEvent(),n=String(r.event_id??""),t=r.status??"",s=r.code,a=r.msg;if(!n||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(n)?(e.bridge.sendEventResult(n,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(r,e){const i=String(r.chat_id??""),n=String(r.message_id??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:n},y),c(`deleted (${n})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(r){const e=r.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(r,e){const i=String(r.chat_id??""),n=String(r.text??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(n),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(r,e,i){try{const n=C[r];if(!n)throw new Error(`Unknown access control tool: ${r}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:n.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}async function O(r,e,i){try{const n=k(r,e);if(!E.has(n.action))throw new Error(`Action not allowed: ${n.action}`);const t=await i.bridge.agentInvoke(n.action,n.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}function c(r){return{content:[{type:"text",text:r}]}}export{q as registerClaudeTools};
@@ -1 +1 @@
1
- import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(t,e){this.controlURL=t.replace(/\/+$/,""),this.token=e.trim(),l.info("claude-worker-client",`Configured with control URL: ${this.controlURL}`)}async post(t,e,s){if(!this.isConfigured())throw new Error("worker control not configured");const i=new AbortController,o=setTimeout(()=>i.abort(),s);try{const r=await fetch(`${this.controlURL}${t}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.token}`},body:JSON.stringify(e),signal:i.signal}),n=await r.text(),a=n.trim()?JSON.parse(n):{};if(!r.ok)throw new Error(a.error||`worker control failed ${r.status}`);return a}finally{clearTimeout(o)}}isRetryableError(t){const e=t instanceof Error?t.message:String(t);return/fetch failed|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|aborted/i.test(e)}async postWithRetry(t,e,s,i=1){let o;for(let r=0;r<=i;r++)try{return r>0&&l.info("claude-worker-client",`Retrying ${t} attempt=${r+1}`),await this.post(t,e,s)}catch(n){if(o=n,r>=i||!this.isRetryableError(n))break;await new Promise(a=>setTimeout(a,150))}throw o instanceof Error?o:new Error(String(o))}async deliverEvent(t){return this.postWithRetry("/v1/worker/deliver-event",{payload:t},1e4,1)}async deliverStop(t){return this.postWithRetry("/v1/worker/deliver-stop",{payload:t},1e4,1)}async deliverLocalAction(t){return this.postWithRetry("/v1/worker/deliver-local-action",{payload:t},1e4,1)}async ping(){try{return await this.postWithRetry("/v1/worker/ping",{},5e3,1),!0}catch{return!1}}}export{c as ClaudeWorkerClient};
1
+ import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(r,e){this.controlURL=r.replace(/\/+$/,""),this.token=e.trim(),l.info("claude-worker-client",`Configured with control URL: ${this.controlURL}`)}async post(r,e,s){if(!this.isConfigured())throw new Error("worker control not configured");const i=new AbortController,o=setTimeout(()=>i.abort(),s);try{const t=await fetch(`${this.controlURL}${r}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.token}`},body:JSON.stringify(e),signal:i.signal}),n=await t.text(),a=n.trim()?JSON.parse(n):{};if(!t.ok)throw new Error(a.error||`worker control failed ${t.status}`);return a}finally{clearTimeout(o)}}isRetryableError(r){const e=r instanceof Error?r.message:String(r);return/fetch failed|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|aborted/i.test(e)}async postWithRetry(r,e,s,i=1){let o;for(let t=0;t<=i;t++)try{return t>0&&l.info("claude-worker-client",`Retrying ${r} attempt=${t+1}`),await this.post(r,e,s)}catch(n){if(o=n,t>=i||!this.isRetryableError(n))break;await new Promise(a=>setTimeout(a,150))}throw o instanceof Error?o:new Error(String(o))}async deliverEvent(r){return this.postWithRetry("/v1/worker/deliver-event",{payload:r},1e4,1)}async deliverStop(r){return this.postWithRetry("/v1/worker/deliver-stop",{payload:r},1e4,1)}async deliverLocalAction(r){return this.postWithRetry("/v1/worker/deliver-local-action",{payload:r},1e4,1)}async ping(){try{return await this.postWithRetry("/v1/worker/ping",{},5e3,1),!0}catch{return!1}}}export{c as ClaudeWorkerClient};
@@ -1,2 +1,2 @@
1
- import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as l}from"./protocol-contract.js";function P(e){let t=null,r=0,n=!1,i=!1;const a=v(),s=e.gatewayUrl??"http://127.0.0.1:19580/mcp";return{async start(){await F(e.command,s,e.env);const c=E(e.grix),u=[...e.args??[],"--name",`grix-mcp-${e.name}`,"--session-id",a];e.fullAuto&&u.push("--dangerously-skip-permissions"),u.push("--dangerously-load-development-channels",`server:${l}`,"--append-system-prompt",c);const f=d(I(),`grix-mcp-claude-${e.name}`);await S(f,{recursive:!0});const{expectPath:$,pidPath:g}=await M(f,e.command,u),_={...process.env,...e.env??{}};t=x("/usr/bin/expect",[$],{cwd:e.cwd,env:_,stdio:["ignore","pipe","pipe"],detached:!0}),o.info("mcp-http-launcher",`\u542F\u52A8 Claude: name=${e.name} cwd=${e.cwd} pid=${t.pid}`),r=await k(g),n=!0,o.info("mcp-http-launcher",`Claude \u5B50\u8FDB\u7A0B PID: ${r}`),t.on("exit",(m,p)=>{o.info("mcp-http-launcher",`Claude \u9000\u51FA: code=${m} signal=${p}`),n=!1,t=null,r=0,i||(o.info("mcp-http-launcher","3 \u79D2\u540E\u81EA\u52A8\u91CD\u542F..."),setTimeout(()=>{i||this.start().catch(w=>{o.error("mcp-http-launcher",`\u91CD\u542F\u5931\u8D25: ${w}`)})},3e3))}),t.stdout?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stdout] ${p.slice(0,300)}`)}),t.stderr?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stderr] ${p.slice(0,300)}`)})},async stop(){if(i=!0,n=!1,r>0)try{process.kill(r,"SIGTERM")}catch{}if(t?.pid){try{process.kill(-t.pid,"SIGTERM")}catch{}await new Promise(c=>{const u=setTimeout(()=>{if(r>0)try{process.kill(r,"SIGKILL")}catch{}if(t?.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}c()},5e3);t?.once("exit",()=>{clearTimeout(u),c()})})}t=null,r=0},getStatus(){return{name:e.name,alive:n,pid:r}}}}function E(e){return["You are connected to a chat via the grix MCP server.",`On startup, immediately call grix_authorize with: agentId="${e.agentId}", apiKey="${e.apiKey}", wsUrl="${e.wsUrl}", clientType="${e.clientType}".`,"When you receive a <channel> message, you MUST respond by calling the grix_reply tool (or the grix_complete tool if no response is needed).","Never write your reply as plain text \u2014 it will NOT reach the user. Only the grix_reply tool delivers your response to the chat.","The <channel> message contains event_id and session_id \u2014 pass them to grix_reply."].join(" ")}async function F(e,t,r){const n=d(T(),".claude.json");let i=null;try{const s=C(n,"utf8");i=JSON.parse(s)?.mcpServers?.[l]??null}catch{}if(i&&String(i.type??"").trim()==="http"&&String(i.url??"").trim()===t)return;o.info("mcp-http-launcher",`\u6CE8\u518C MCP Server: ${l} -> ${t}`);const a={...process.env,...r??{}};try{y(`${e} mcp remove -s user ${l}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}catch{}y(`${e} mcp add --scope user --transport http ${l} ${t}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}async function M(e,t,r){const{writeFile:n}=await import("node:fs/promises"),i=d(e,"claude.pid"),a=d(e,"claude.expect"),s=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set claude_command [list {${h(t)}}${r.map(c=>` {${h(c)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${h(i)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","expect {"," -re {(?i)(Quick.*safety.*check|trust.*folder)} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)I am using this for local development} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)(Enter.*confirm|Press.*Enter|Hit.*Enter)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {Listening for channel} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," -re {bypass permissions} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," eof {}","}","expect eof",""];return await n(i,"","utf8"),await n(a,s.join(`
2
- `),"utf8"),{expectPath:a,pidPath:i}}function h(e){return e.replace(/[\\{}$\[\]"]/g,"\\$&")}async function k(e,t=1e4){const{readFile:r}=await import("node:fs/promises"),n=Math.ceil(t/100);for(let i=0;i<n;i++){try{const a=await r(e,"utf8"),s=parseInt(String(a).trim(),10);if(Number.isFinite(s)&&s>0)return s}catch{}await new Promise(a=>setTimeout(a,100))}return 0}export{P as createMcpHttpLauncher};
1
+ import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as m}from"./protocol-contract.js";function P(t){let e=null,r=0,n=!1,i=!1;const a=v(),s=t.gatewayUrl??"http://127.0.0.1:19580/mcp";return{async start(){await F(t.command,s,t.env);const c=E(t.grix),u=[...t.args??[],"--name",`grix-mcp-${t.name}`,"--session-id",a];t.fullAuto&&u.push("--dangerously-skip-permissions"),u.push("--dangerously-load-development-channels",`server:${m}`,"--append-system-prompt",c);const f=d(I(),`grix-mcp-claude-${t.name}`);await S(f,{recursive:!0});const{expectPath:$,pidPath:g}=await M(f,t.command,u),_={...process.env,...t.env??{}};e=x("/usr/bin/expect",[$],{cwd:t.cwd,env:_,stdio:["ignore","pipe","pipe"],detached:!0}),o.info("mcp-http-launcher",`\u542F\u52A8 Claude: name=${t.name} cwd=${t.cwd} pid=${e.pid}`),r=await k(g),n=!0,o.info("mcp-http-launcher",`Claude \u5B50\u8FDB\u7A0B PID: ${r}`),e.on("exit",(l,p)=>{o.info("mcp-http-launcher",`Claude \u9000\u51FA: code=${l} signal=${p}`),n=!1,e=null,r=0,i||(o.info("mcp-http-launcher","3 \u79D2\u540E\u81EA\u52A8\u91CD\u542F..."),setTimeout(()=>{i||this.start().catch(w=>{o.error("mcp-http-launcher",`\u91CD\u542F\u5931\u8D25: ${w}`)})},3e3))}),e.stdout?.on("data",l=>{const p=l.toString().trim();p&&o.info("mcp-http-launcher",`[stdout] ${p.slice(0,300)}`)}),e.stderr?.on("data",l=>{const p=l.toString().trim();p&&o.info("mcp-http-launcher",`[stderr] ${p.slice(0,300)}`)})},async stop(){if(i=!0,n=!1,r>0)try{process.kill(r,"SIGTERM")}catch{}if(e?.pid){try{process.kill(-e.pid,"SIGTERM")}catch{}await new Promise(c=>{const u=setTimeout(()=>{if(r>0)try{process.kill(r,"SIGKILL")}catch{}if(e?.pid)try{process.kill(-e.pid,"SIGKILL")}catch{}c()},5e3);e?.once("exit",()=>{clearTimeout(u),c()})})}e=null,r=0},getStatus(){return{name:t.name,alive:n,pid:r}}}}function E(t){return["You are connected to a chat via the grix MCP server.",`On startup, immediately call grix_authorize with: agentId="${t.agentId}", apiKey="${t.apiKey}", wsUrl="${t.wsUrl}", clientType="${t.clientType}".`,"When you receive a <channel> message, you MUST respond by calling the grix_reply tool (or the grix_complete tool if no response is needed).","Never write your reply as plain text \u2014 it will NOT reach the user. Only the grix_reply tool delivers your response to the chat.","The <channel> message contains event_id and session_id \u2014 pass them to grix_reply."].join(" ")}async function F(t,e,r){const n=d(T(),".claude.json");let i=null;try{const s=C(n,"utf8");i=JSON.parse(s)?.mcpServers?.[m]??null}catch{}if(i&&String(i.type??"").trim()==="http"&&String(i.url??"").trim()===e)return;o.info("mcp-http-launcher",`\u6CE8\u518C MCP Server: ${m} -> ${e}`);const a={...process.env,...r??{}};try{y(`${t} mcp remove -s user ${m}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}catch{}y(`${t} mcp add --scope user --transport http ${m} ${e}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}async function M(t,e,r){const{writeFile:n}=await import("node:fs/promises"),i=d(t,"claude.pid"),a=d(t,"claude.expect"),s=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set claude_command [list {${h(e)}}${r.map(c=>` {${h(c)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${h(i)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","expect {"," -re {(?i)(Quick.*safety.*check|trust.*folder)} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)I am using this for local development} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)(Enter.*confirm|Press.*Enter|Hit.*Enter)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {Listening for channel} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," -re {bypass permissions} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," eof {}","}","expect eof",""];return await n(i,"","utf8"),await n(a,s.join(`
2
+ `),"utf8"),{expectPath:a,pidPath:i}}function h(t){return t.replace(/[\\{}$\[\]"]/g,"\\$&")}async function k(t,e=1e4){const{readFile:r}=await import("node:fs/promises"),n=Math.ceil(e/100);for(let i=0;i<n;i++){try{const a=await r(t,"utf8"),s=parseInt(String(a).trim(),10);if(Number.isFinite(s)&&s>0)return s}catch{}await new Promise(a=>setTimeout(a,100))}return 0}export{P as createMcpHttpLauncher};
@@ -1 +1 @@
1
- class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(t){this.defaultTimeoutMs=t.defaultTimeoutMs??9e4,this.onTimeout=t.onTimeout}arm(t,e){this.cancel(t);const s=e?.timeoutMs??this.defaultTimeoutMs,i=Date.now()+s,o=setTimeout(()=>{this.timers.delete(t),this.onTimeout(t).catch(()=>{})},s);return this.timers.set(t,o),i}cancel(t){const e=this.timers.get(t);e&&(clearTimeout(e),this.timers.delete(t))}has(t){return this.timers.has(t)}close(){for(const t of this.timers.values())clearTimeout(t);this.timers.clear()}}export{m as ResultTimeoutManager};
1
+ class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(e){this.defaultTimeoutMs=e.defaultTimeoutMs??9e4,this.onTimeout=e.onTimeout}arm(e,t){this.cancel(e);const s=t?.timeoutMs??this.defaultTimeoutMs,i=Date.now()+s,o=setTimeout(()=>{this.timers.delete(e),this.onTimeout(e).catch(()=>{})},s);return this.timers.set(e,o),i}cancel(e){const t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}has(e){return this.timers.has(e)}close(){for(const e of this.timers.values())clearTimeout(e);this.timers.clear()}}export{m as ResultTimeoutManager};
@@ -1,10 +1,10 @@
1
- import{EventEmitter as T}from"node:events";import{stat as P}from"node:fs/promises";import{existsSync as _,mkdirSync as b,readFileSync as C,writeFileSync as E}from"node:fs";import{join as I,resolve as $,dirname as O}from"node:path";import{homedir as M}from"node:os";import{fileURLToPath as F}from"node:url";import{resolveCommandPath as B,spawnCommand as j,killProcessGroup as w,hasChildProcesses as D}from"../../core/runtime/spawn.js";import{InternalApiServer as N}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as Q}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as L}from"../../default-skills/index.js";import{buildSimpleProbeReport as U}from"../shared/probe-util.js";import{compactToolInputForWire as H}from"../shared/tool-wire-payload.js";import{buildOpencodeConfigContent as q}from"./opencode-config.js";import{OpenCodeTransport as J}from"./opencode-transport.js";import{log as o}from"../../core/log/index.js";import{splitTextForAibotProtocol as k}from"../../core/protocol/index.js";class G extends T{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){o.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const X=200,z=2e3,W=12e4,V=90*1e3,y=1800*1e3,A=3e4,R=600*1e3,Y="claude_interaction_reply",K="127.0.0.1",Z=0,ee=1e3;function x(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class ge extends T{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;auditCaptures=new Map;completedAuditBoundaries=new Map;idleTimer=null;lastSseAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;toolCardsSent=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;pendingQuestions=new Map;permissionHandler=null;constructor(e,t,s){super(),this.config=e,this.callbacks=t,this.options=s??{},this.identity=new Q("opencode-adapter",t.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}async start(){await this.startInternalApiAndInjectMcp();const e=this.options.hostname??K,t=this.options.port??Z,s=await this.spawnAndWait(e,t),i=this.resolveCwd();await this.transport.connect(s,i),this.transport.on("event",n=>this.handleSseEvent(n)),o.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{w(e,"SIGTERM")}catch{}const t=setTimeout(()=>{try{w(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();await this.transport.useDirectory(t);const s=await this.transport.createSession({title:`grix-${Date.now()}`},t);return this.sessions.set(s.id,{ocSessionId:s.id,cwd:t}),o.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.useDirectory(s.cwd),await this.transport.getSession(s.ocSessionId,s.cwd)}catch{o.warn("opencode-adapter",`OC session ${s.ocSessionId} gone, will create new on next prompt`),s.ocSessionId=""}}async destroySession(e){const t=this.sessions.get(e),s=t?t.ocSessionId:e;if(s)try{await this.transport.deleteSession(s,t?.cwd)}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,this.activeRun.cwd)}catch{}}deliverInboundEvent(e){const{event_id:t,session_id:s,content:i}=e;if(this.completedEvents.has(t)){o.info("opencode-adapter",`Dropping duplicate event ${t}`),this.callbacks.sendEventAck(t,s),this.callbacks.sendEventResult(t,"responded");return}if(!this.alive){o.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&&(o.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${t}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),o.info("opencode-adapter",`prompt: event=${t} session=${s}`),this.callbacks.sendEventAck(t,s),this.startRun(t,s,e.audit?.enabled===!0),this.startComposing(s),this.resetIdleTimer();const n=this.buildPromptTextFromEvent(e);this.sendOcPrompt(s,n).catch(r=>{o.error("opencode-adapter",`prompt_async failed: ${r}`),this.finishRun("failed",String(r))})}deliverStopEvent(e,t){this.activeRun&&this.activeRun.eventId===e&&(o.info("opencode-adapter",`stop: event=${e}`),this.rejectAllPendingInteractions(),this.transport.abortSession(this.activeRun.ocSessionId,this.activeRun.cwd).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]:[]}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.rejectAllPendingInteractions(),this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=$(F(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?D(e,[e]):!1}async probe(e){const t=this.getStatus();return U(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(d,p,c,u)=>this.callbacks.agentInvoke(d,p,u)),await this.internalApi.start(0),o.info("opencode-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),t=process.env.XDG_CONFIG_HOME||I(M(),".config"),s=I(t,"opencode","opencode.json");b(O(s),{recursive:!0});let i={};try{_(s)&&(i=JSON.parse(C(s,"utf8")))}catch{}const n=i.mcp&&typeof i.mcp=="object"?i.mcp:{};n[e.name]={type:"local",command:[e.command,...e.args??[]],enabled:!0},i.mcp=n,E(s,`${JSON.stringify(i,null,2)}
2
- `,"utf8"),o.info("opencode-adapter",`MCP config injected into ${s}`);const r=I(t,"opencode","skills"),a=L(r);a.length>0&&o.info("opencode-adapter",`Synced connector skills to ${r}: [${a.join(", ")}]`)}catch(e){o.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;if(t==="exec_approve"||t==="exec_reject"||t==="permission_approve"||t==="permission_reject")return this.handlePermissionAction(e);if(t===Y){const s=e.params??{};if(String(s.kind??"")==="permission"){const i=s.resolution??{},n=String(i.value??"");return this.handlePermissionAction({...e,action_type:n==="allow"?"exec_approve":"exec_reject",params:{...s,approval_command_id:s.request_id}})}return this.handleQuestionReplyAction(e)}return{handled:!1,kind:""}}bindSession(e,t){if(o.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 P(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,n)=>{const r=this.config.command||"opencode",d=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${t}`],p={...process.env,...this.config.env},c=q({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider});c&&(p.OPENCODE_CONFIG_CONTENT=JSON.stringify(c));const u=B(r,typeof p.PATH=="string"?p.PATH:void 0);o.info("opencode-adapter",`Spawning: ${u} ${d.join(" ")} (cwd=${s})`),this.process=j(u,d,{env:p,cwd:s}).process;let f="",l=!1;const m=setTimeout(()=>{l||(l=!0,n(new Error(`opencode serve did not start after ${A/1e3}s`)))},A);this.process.stdout?.on("data",h=>{if(f+=h.toString(),!l)for(const v of f.split(`
3
- `)){const S=v.match(/opencode server listening on (https?:\/\/[^\s]+)/);if(S){clearTimeout(m),l=!0,this.alive=!0,i(S[1]);return}}}),this.process.stderr?.on("data",h=>{const v=h.toString().trim();v&&o.info("opencode-adapter",`[stderr] ${v}`)}),this.process.on("error",h=>{o.error("opencode-adapter",`Spawn error: ${h.message}`),clearTimeout(m),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${h.message}`),this.clearRun()),l?this.stopped||this.emit("exit",1):(l=!0,n(h))}),this.process.on("exit",h=>{o.info("opencode-adapter",`Process exited (code=${h})`),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=${h})`),this.clearRun()),l?this.stopped||this.emit("exit",h??1):(l=!0,n(new Error(`opencode serve exited with code ${h}`)))})})}async ensureOcSession(e){const t=this.sessions.get(e),s=this.getSessionCwd(e);if(await this.transport.useDirectory(s),t?.ocSessionId)try{return await this.transport.getSession(t.ocSessionId,s),t.ocSessionId}catch{o.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, creating new`),t.ocSessionId=""}const i=this.options.bindingStore?.getAcpSessionId(e);if(i)try{return await this.transport.getSession(i,s),this.sessions.set(e,{ocSessionId:i,cwd:s}),o.info("opencode-adapter",`Resumed OC session ${i} for aibot=${e}`),i}catch{o.warn("opencode-adapter",`Persisted OC session ${i} gone, creating new`)}const n=await this.transport.createSession({title:`grix-${e.slice(-8)}`},s);return this.sessions.set(e,{ocSessionId:n.id,cwd:s}),this.options.bindingStore?.setAcpSessionId(e,n.id),o.info("opencode-adapter",`Created OC session ${n.id} for aibot=${e}`),n.id}async sendOcPrompt(e,t){const s=this.getSessionCwd(e),i=await this.ensureOcSession(e);this.activeRun&&(this.activeRun.ocSessionId=i,this.activeRun.cwd=s),await this.transport.sendPromptAsync(i,{parts:[{type:"text",text:t}]},s)}handleSseEvent(e){if(!this.stopped){if(this.lastSseAt=Date.now(),this.updateToolInFlight(e),this.resetIdleTimer(),this.activeRun){const t=this.auditCaptures.get(this.activeRun.eventId);t&&t.push({sequence:t.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(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.activeRun.cwd,{model_provider:s.providerID,model_id:s.modelID}),s.error&&o.warn("opencode-adapter",`Message error: ${JSON.stringify(s.error)}`);const i=this.activeRun.ocSessionId;i&&s.sessionID===i&&(s.error?(this.flushTextBuffer(),this.finishRun("failed",s.error.message||s.error.type)):s.time?.completed&&s.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}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";o.error("opencode-adapter",`Session error: ${s}`),this.flushTextBuffer(),this.finishRun("failed",s);break}case"permission.updated":{this.handlePermission(e.permission);break}case"permission.asked":{this.handlePermissionAsked(e);break}case"question.asked":{this.handleQuestionAsked(e);break}case"permission.replied":case"question.replied":case"question.rejected":o.debug("opencode-adapter",`Interaction settled: ${e.type}`);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":{o.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:o.debug("opencode-adapter",`Unhandled SSE event type: ${e.type}`);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 n=this.messageRoles.get(i);if(n==="user")return;if(n==="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.sendToolUseOnce(e,s.input);break}case"completed":{this.sendToolUseOnce(e,s.input);break}case"error":{this.sendToolUseOnce(e,s.input),this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,"(failed)");break}}}sendToolUseOnce(e,t){!this.activeRun||this.toolCardsSent.has(e.callID)||(this.flushTextBuffer(),this.toolCardsSent.add(e.callID),this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,H(t??{})))}onPermissionTimeout(e){const t=this.pendingPermissions.get(e);t&&(this.pendingPermissions.delete(e),o.error("opencode-adapter",`Permission approval timeout: ${e}`),this.transport.respondPermission(t.ocSessionId,e,"reject",t.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===t.eventId&&(this.flushTextBuffer(),this.finishRun("failed","permission approval timeout")))}trackPendingPermission(e){if(!this.activeRun)return;this.stopIdleTimer();const t=setTimeout(()=>this.onPermissionTimeout(e),R);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:t})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(r=>{o.warn("opencode-adapter",`Orphan permission reject failed: ${r}`)});return}const{eventId:t,sessionId:s,ocSessionId:i}=this.activeRun;if(this.options.permissionPolicy==="fullAuto"){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(r=>{o.warn("opencode-adapter",`Auto-approve failed: ${r}`)});return}this.trackPendingPermission(e.id);const n=e.patterns.length>0?`${e.permission}: ${e.patterns.join(", ")}`:e.permission;this.callbacks.sendPermissionCard?this.callbacks.sendPermissionCard({eventId:t,sessionId:s,approvalId:e.id,toolName:e.permission,toolTitle:n,toolInput:JSON.stringify(e.metadata??{})}):this.callbacks.sendToolUse(t,s,e.permission,JSON.stringify(e.metadata??{}))}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",this.activeRun.cwd).catch(n=>{o.warn("opencode-adapter",`Auto-approve failed: ${n}`)});return}if(this.trackPendingPermission(e.id),this.callbacks.sendPermissionCard)this.callbacks.sendPermissionCard({eventId:t,sessionId:s,approvalId:e.id,toolName:e.type,toolTitle:e.title||e.type,toolInput:JSON.stringify(e.metadata??{})});else{const n=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(t,s,e.type,n)}}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const t=e.params??{},s=String(t.approval_id??t.approval_command_id??t.approvalId??t.tool_call_id??"");let i=s?this.pendingPermissions.get(s):void 0;if(!i){for(const a of this.pendingPermissions.values())if(a.eventId===this.activeRun.eventId){i=a;break}}if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:"permission"};const n=e.action_type==="exec_approve"||e.action_type==="permission_approve",r=n?"once":"reject";return clearTimeout(i.timer),this.pendingPermissions.delete(i.permissionId),this.transport.respondPermission(i.ocSessionId,i.permissionId,r,i.cwd).then(()=>{o.info("opencode-adapter",`Permission ${r}: ${i.permissionId}`),this.resetIdleTimer()}).catch(a=>{o.warn("opencode-adapter",`Permission response failed: ${a}`),this.resetIdleTimer()}),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.permissionId,decision:n?"approve":"reject"}),{handled:!0,kind:"permission"}}onQuestionTimeout(e){const t=this.pendingQuestions.get(e);t&&(this.pendingQuestions.delete(e),o.error("opencode-adapter",`Question answer timeout: ${e}`),this.transport.rejectQuestion(e,t.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===t.eventId&&(this.flushTextBuffer(),this.finishRun("failed","question answer timeout")))}handleQuestionAsked(e){if(!this.activeRun){this.transport.rejectQuestion(e.id).catch(n=>{o.warn("opencode-adapter",`Orphan question reject failed: ${n}`)});return}const{eventId:t,sessionId:s}=this.activeRun;this.stopIdleTimer();const i=setTimeout(()=>this.onQuestionTimeout(e.id),R);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:t,cwd:this.activeRun.cwd,questions:e.questions,timer:i}),this.callbacks.sendAgentQuestionCard)this.callbacks.sendAgentQuestionCard(t,s,{request_id:e.id,mode:"form",questions:e.questions.map(n=>({header:n.header,prompt:n.question,...n.options.length>0?{options:n.options.map(r=>r.label)}:{},...n.multiple!==void 0?{multi_select:n.multiple}:{}})),expires_at:Date.now()+R});else{const n=e.questions.map(r=>r.question).join(`
4
- `);this.callbacks.sendRunError(t,s,`Agent asks: ${n}`)}}handleQuestionReplyAction(e){const t=e.params??{},s=String(t.request_id??""),i=s?this.pendingQuestions.get(s):void 0;if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"interaction_request_not_pending","The question is no longer pending; the reply was not delivered."),{handled:!0,kind:"question_reply"};const n=t.resolution??{},r=String(n.type??""),a=(c,u)=>{clearTimeout(i.timer),this.pendingQuestions.delete(i.requestId),c().then(()=>this.resetIdleTimer()).catch(f=>{o.warn("opencode-adapter",`Question response failed: ${f}`),this.resetIdleTimer()}),this.callbacks.sendLocalActionResult(e.action_id,"ok",u)};if(r==="action"){const c=String(n.value??"");if(c==="cancel"||c==="decline")return a(()=>this.transport.rejectQuestion(i.requestId,i.cwd),{request_id:s,resolution:"cancel"}),{handled:!0,kind:"question_reply"}}let d=null;if(Array.isArray(t.answers))d=t.answers.map(c=>Array.isArray(c)?c.map(String):[String(c)]);else if(r==="text"){const c=String(n.value??"");c&&(d=i.questions.map((u,f)=>f===0?[c]:[]))}else if(r==="map"){const c=Array.isArray(n.entries)?n.entries:[];d=i.questions.map((u,f)=>{const l=c.find(m=>m.key===u.header||m.key===String(f));return l&&l.value?[l.value]:[]})}if(!d||d.every(c=>c.length===0))return a(()=>this.transport.rejectQuestion(i.requestId,i.cwd),{request_id:s,resolution:"cancel"}),{handled:!0,kind:"question_reply"};const p=d;return a(()=>this.transport.replyQuestion(i.requestId,p,i.cwd),{request_id:s,resolution:"answer"}),{handled:!0,kind:"question_reply"}}rejectAllPendingInteractions(){for(const e of this.pendingPermissions.values())clearTimeout(e.timer),this.transport.respondPermission(e.ocSessionId,e.permissionId,"reject",e.cwd).catch(()=>{});this.pendingPermissions.clear();for(const e of this.pendingQuestions.values())clearTimeout(e.timer),this.transport.rejectQuestion(e.requestId,e.cwd).catch(()=>{});this.pendingQuestions.clear()}hasPendingInteractionForRun(e){for(const t of this.pendingPermissions.values())if(t.eventId===e)return!0;for(const t of this.pendingQuestions.values())if(t.eventId===e)return!0;return!1}startRun(e,t,s=!1){this.activeRun={eventId:e,sessionId:t,ocSessionId:"",cwd:this.getSessionCwd(t),chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null},this.toolCardsSent.clear(),s&&this.auditCaptures.set(e,[]),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>ee){const a=[...this.completedEvents].slice(-500);this.completedEvents=new Set(a)}this.snapshotAuditBoundary(s),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopComposing(),this.stopIdleTimer();const i=++s.chunkSeq,n=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,n).then(()=>{this.callbacks.sendEventResult(s.eventId,e,t)}).catch(a=>{const d=e==="responded"?"failed":e,p=e==="responded"?`final output delivery failed: ${a instanceof Error?a.message:String(a)}`:t;this.callbacks.sendEventResult(s.eventId,d,p)}):(this.callbacks.sendStreamChunk(s.eventId,s.sessionId,"",i,!0,n),this.callbacks.sendEventResult(s.eventId,e,t))};if(s.textBuffer){this.stopTextFlush();for(const a of k(s.textBuffer))s.chunkSeq++,this.callbacks.sendStreamChunk(s.eventId,s.sessionId,a,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&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopIdleTimer(),e&&this.emit("eventDone",e)}snapshotAuditBoundary(e){const t=this.auditCaptures.get(e.eventId);t&&(this.completedAuditBoundaries.set(e.eventId,{adapterType:"opencode",providerSessionId:e.ocSessionId||void 0,openCodeEvidence:{events:t}}),this.auditCaptures.delete(e.eventId))}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 k(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||!x(e))return!1;const t=Date.now(),s=this.lastSseAt>0?t-this.lastSseAt:Number.POSITIVE_INFINITY;if(s<V)return this.livenessExtendStartAt=t,o.info("opencode-adapter",`Liveness check: fresh SSE for ${this.activeRun.eventId} (sseAge=${s}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??t;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),t-n>y?(o.warn("opencode-adapter",`Liveness extension budget exhausted for ${this.activeRun.eventId} (no progress for ${Math.round((t-n)/6e4)}min), allowing idle fail`),!1):(o.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.hasPendingInteractionForRun(this.activeRun.eventId)&&this.shouldExtendByLiveness()){o.info("opencode-adapter",`Idle timeout skipped: pending interaction for ${this.activeRun.eventId}, resetting timer`),this.resetIdleTimer();return}if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const e=this.process?.pid,s=!!(this.alive&&e&&x(e))?`liveness budget exhausted after ${y/6e4}min`:"process not alive";o.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)},W))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveCwd(){const e=this.options.aibotSessionId?this.options.bindingStore?.get(this.options.aibotSessionId)?.cwd:void 0;if(e)return e;const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}getSessionCwd(e){return this.sessions.get(e)?.cwd??this.options.bindingStore?.get(e)?.cwd??this.resolveCwd()}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 _}from"node:events";import{stat as E}from"node:fs/promises";import{existsSync as C,mkdirSync as M,readFileSync as $,writeFileSync as O}from"node:fs";import{join as S,resolve as F,dirname as D}from"node:path";import{homedir as B}from"node:os";import{fileURLToPath as j}from"node:url";import{resolveCommandPath as N,spawnCommand as L,killProcessGroup as k,hasChildProcesses as U}from"../../core/runtime/spawn.js";import{InternalApiServer as Q}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as q}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as H}from"../../default-skills/index.js";import{buildSimpleProbeReport as J}from"../shared/probe-util.js";import{compactToolInputForWire as z}from"../shared/tool-wire-payload.js";import{buildOpencodeConfigContent as G}from"./opencode-config.js";import{OpenCodeTransport as V}from"./opencode-transport.js";import{log as o}from"../../core/log/index.js";import{splitTextForAibotProtocol as A}from"../../core/protocol/index.js";class X extends _{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){o.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const W=200,Y=2e3,K=12e4,Z=90*1e3,y=1800*1e3,P=3e4,R=600*1e3,ee="claude_interaction_reply",te="set_mode",se="set_model",ie="127.0.0.1",ne=0,oe=1e3,m={fullAuto:"full_auto",approval:"approval"},b=[{id:m.fullAuto,displayName:"Full Auto"},{id:m.approval,displayName:"Approval"}],re=[{permission:"*",pattern:"*",action:"allow"}],ae=[{permission:"doom_loop",pattern:"*",action:"ask"},{permission:"external_directory",pattern:"*",action:"ask"},{permission:"question",pattern:"*",action:"deny"},{permission:"plan_enter",pattern:"*",action:"deny"},{permission:"plan_exit",pattern:"*",action:"deny"},{permission:"repo_clone",pattern:"*",action:"deny"},{permission:"repo_overview",pattern:"*",action:"deny"},{permission:"read",pattern:"*.env",action:"ask"},{permission:"read",pattern:"*.env.*",action:"ask"},{permission:"read",pattern:"*.env.example",action:"allow"}];function w(g){const e=String(g??"").trim().toLowerCase();if(e==="full_auto"||e==="fullauto")return m.fullAuto;if(e==="approval"||e==="ask"||e==="autoedit"||e==="auto_edit")return m.approval}function x(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class ke extends _{type="opencode";config;callbacks;options;identity;process=null;transport=new V;alive=!1;stopped=!1;internalApi=null;sessions=new Map;sessionModes=new Map;sessionModels=new Map;availableModels=[];activeRun=null;completedEvents=new Set;clientMsgSeq=0;auditCaptures=new Map;completedAuditBoundaries=new Map;idleTimer=null;lastSseAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;toolCardsSent=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;pendingQuestions=new Map;permissionHandler=null;constructor(e,t,s){super(),this.config=e,this.callbacks=t,this.options=s??{},this.identity=new q("opencode-adapter",t.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}async start(){await this.startInternalApiAndInjectMcp();const e=this.options.hostname??ie,t=this.options.port??ne,s=await this.spawnAndWait(e,t),i=this.resolveCwd();await this.transport.connect(s,i),this.transport.on("event",n=>this.handleSseEvent(n));try{await this.refreshModels()}catch(n){o.warn("opencode-adapter",`Failed to fetch providers for toolbar models: ${n instanceof Error?n.message:String(n)}`)}o.info("opencode-adapter",`Ready (pid=${this.process?.pid}, url=${s})`)}async refreshModels(){const e=await this.transport.listProviders(),t=[];for(const s of e)for(const i of s.models??[])t.push({id:`${s.id}/${i.id}`,displayName:i.name||i.id});this.availableModels=t,o.info("opencode-adapter",`Fetched ${t.length} models from ${e.length} providers`)}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{k(e,"SIGTERM")}catch{}const t=setTimeout(()=>{try{k(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();await this.transport.useDirectory(t);const s=await this.transport.createSession({title:`grix-${Date.now()}`},t);return this.sessions.set(s.id,{ocSessionId:s.id,cwd:t}),o.info("opencode-adapter",`Created OC session ${s.id} for cwd=${t}`),await this.applySessionPermission(s.id,s.id,t),s.id}async resumeSession(e,t){const s=this.sessions.get(e);if(s?.ocSessionId)try{await this.transport.useDirectory(s.cwd),await this.transport.getSession(s.ocSessionId,s.cwd),await this.applySessionPermission(e,s.ocSessionId,s.cwd)}catch{o.warn("opencode-adapter",`OC session ${s.ocSessionId} gone, will create new on next prompt`),s.ocSessionId=""}}async destroySession(e){const t=this.sessions.get(e),s=t?t.ocSessionId:e;if(s)try{await this.transport.deleteSession(s,t?.cwd)}catch{}this.sessions.delete(e),this.identity.forgetSession(e)}sendPrompt(e){const t=new X(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,this.activeRun.cwd)}catch{}}deliverInboundEvent(e){const{event_id:t,session_id:s,content:i}=e;if(this.completedEvents.has(t)){o.info("opencode-adapter",`Dropping duplicate event ${t}`),this.callbacks.sendEventAck(t,s),this.callbacks.sendEventResult(t,"responded");return}if(!this.alive){o.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&&(o.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${t}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),o.info("opencode-adapter",`prompt: event=${t} session=${s}`),this.callbacks.sendEventAck(t,s),this.startRun(t,s,e.audit?.enabled===!0),this.startComposing(s),this.resetIdleTimer();const n=this.buildPromptTextFromEvent(e);this.sendOcPrompt(s,n).catch(r=>{o.error("opencode-adapter",`prompt_async failed: ${r}`),this.finishRun("failed",String(r))})}deliverStopEvent(e,t){this.activeRun&&this.activeRun.eventId===e&&(o.info("opencode-adapter",`stop: event=${e}`),this.rejectAllPendingInteractions(),this.transport.abortSession(this.activeRun.ocSessionId,this.activeRun.cwd).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]:[]}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.rejectAllPendingInteractions(),this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=F(j(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?U(e,[e]):!1}async probe(e){const t=this.getStatus();return J(this.config.command||"opencode",{alive:t.alive,busy:t.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){try{this.internalApi=new Q,this.internalApi.setInvokeHandler(async(c,p,d,u)=>this.callbacks.agentInvoke(c,p,u)),await this.internalApi.start(0),o.info("opencode-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),t=process.env.XDG_CONFIG_HOME||S(B(),".config"),s=S(t,"opencode","opencode.json");M(D(s),{recursive:!0});let i={};try{C(s)&&(i=JSON.parse($(s,"utf8")))}catch{}const n=i.mcp&&typeof i.mcp=="object"?i.mcp:{};n[e.name]={type:"local",command:[e.command,...e.args??[]],enabled:!0},i.mcp=n,O(s,`${JSON.stringify(i,null,2)}
2
+ `,"utf8"),o.info("opencode-adapter",`MCP config injected into ${s}`);const r=S(t,"opencode","skills"),a=H(r);a.length>0&&o.info("opencode-adapter",`Synced connector skills to ${r}: [${a.join(", ")}]`)}catch(e){o.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;if(t==="exec_approve"||t==="exec_reject"||t==="permission_approve"||t==="permission_reject")return this.handlePermissionAction(e);if(t===te)return this.handleSetModeAction(e);if(t===se)return this.handleSetModelAction(e);if(t===ee){const s=e.params??{};if(String(s.kind??"")==="permission"){const i=s.resolution??{},n=String(i.value??"");return this.handlePermissionAction({...e,action_type:n==="allow"?"exec_approve":"exec_reject",params:{...s,approval_command_id:s.request_id}})}return this.handleQuestionReplyAction(e)}return{handled:!1,kind:""}}bindSession(e,t){if(o.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}this.callbacks.sendUpdateBindingCard(e,"ready",t,this.buildToolbarMeta(e))}resolveModeId(e){if(e){const s=this.sessionModes.get(e);if(s)return s}const t=w(this.options.permissionPolicy);if(t)return t;if(e){const s=w(this.options.bindingStore?.get(e)?.modeId);if(s)return s}return m.fullAuto}buildModeToolbarMeta(e){const t=this.resolveModeId(e);return{mode_id:t,currentModeId:t,available_modes:b.map(s=>({...s}))}}async applySessionPermission(e,t,s){const i=this.resolveModeId(e),n=i===m.fullAuto?re:ae;try{await this.transport.updateSessionPermission(t,n,s),o.info("opencode-adapter",`Applied session permission ruleset (${i}) to ${t}`)}catch(r){o.warn("opencode-adapter",`Failed to apply session permission ruleset: ${r instanceof Error?r.message:String(r)}`)}}async handleSetModeAction(e){const t=e.params??{},s=String(t.session_id??this.options.aibotSessionId??"").trim(),i=w(t.mode_id);if(!i||!s)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","mode_id must be full_auto or approval and session_id is required"),{handled:!0,kind:"set_mode"};this.sessionModes.set(s,i);const n=this.sessions.get(s);n?.ocSessionId&&await this.applySessionPermission(s,n.ocSessionId,n.cwd);const r=n?.cwd??this.getSessionCwd(s);return this.callbacks.sendUpdateBindingCard(s,"ready",r,this.buildToolbarMeta(s)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"mode_set",session_context:{mode_id:i,modeId:i},mode_id:i,available_modes:b.map(a=>({...a}))}),{handled:!0,kind:"set_mode"}}resolveModelId(e){if(e){const s=this.sessionModels.get(e);if(s)return s}const t=String(this.options.model??"").trim();if(t)return t;if(e){const s=String(this.options.bindingStore?.get(e)?.modelId??"").trim();if(s)return s}return""}buildModelToolbarMeta(e){const t=this.resolveModelId(e);return{model_id:t,currentModelId:t,available_models:this.availableModels.map(s=>({...s}))}}buildToolbarMeta(e){return{...this.buildModelToolbarMeta(e),...this.buildModeToolbarMeta(e)}}handleSetModelAction(e){const t=e.params??{},s=String(t.session_id??this.options.aibotSessionId??"").trim(),i=String(t.model_id??"").trim();if(!i||!s)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};this.sessionModels.set(s,i);const n=this.sessions.get(s)?.cwd??this.getSessionCwd(s);return this.callbacks.sendUpdateBindingCard(s,"ready",n,this.buildToolbarMeta(s)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"model_set",session_context:{model_id:i,modelId:i},model_id:i,available_models:this.availableModels.map(r=>({...r}))}),{handled:!0,kind:"set_model"}}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,n)=>{const r=this.config.command||"opencode",c=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${t}`],p={...process.env,...this.config.env},d=G({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider});d&&(p.OPENCODE_CONFIG_CONTENT=JSON.stringify(d));const u=N(r,typeof p.PATH=="string"?p.PATH:void 0);o.info("opencode-adapter",`Spawning: ${u} ${c.join(" ")} (cwd=${s})`),this.process=L(u,c,{env:p,cwd:s}).process;let f="",l=!1;const v=setTimeout(()=>{l||(l=!0,n(new Error(`opencode serve did not start after ${P/1e3}s`)))},P);this.process.stdout?.on("data",h=>{if(f+=h.toString(),!l)for(const I of f.split(`
3
+ `)){const T=I.match(/opencode server listening on (https?:\/\/[^\s]+)/);if(T){clearTimeout(v),l=!0,this.alive=!0,i(T[1]);return}}}),this.process.stderr?.on("data",h=>{const I=h.toString().trim();I&&o.info("opencode-adapter",`[stderr] ${I}`)}),this.process.on("error",h=>{o.error("opencode-adapter",`Spawn error: ${h.message}`),clearTimeout(v),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${h.message}`),this.clearRun()),l?this.stopped||this.emit("exit",1):(l=!0,n(h))}),this.process.on("exit",h=>{o.info("opencode-adapter",`Process exited (code=${h})`),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=${h})`),this.clearRun()),l?this.stopped||this.emit("exit",h??1):(l=!0,n(new Error(`opencode serve exited with code ${h}`)))})})}async ensureOcSession(e){const t=this.sessions.get(e),s=this.getSessionCwd(e);if(await this.transport.useDirectory(s),t?.ocSessionId)try{return await this.transport.getSession(t.ocSessionId,s),t.ocSessionId}catch{o.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, creating new`),t.ocSessionId=""}const i=this.options.bindingStore?.getAcpSessionId(e);if(i)try{return await this.transport.getSession(i,s),this.sessions.set(e,{ocSessionId:i,cwd:s}),o.info("opencode-adapter",`Resumed OC session ${i} for aibot=${e}`),await this.applySessionPermission(e,i,s),i}catch{o.warn("opencode-adapter",`Persisted OC session ${i} gone, creating new`)}const n=await this.transport.createSession({title:`grix-${e.slice(-8)}`},s);return this.sessions.set(e,{ocSessionId:n.id,cwd:s}),this.options.bindingStore?.setAcpSessionId(e,n.id),o.info("opencode-adapter",`Created OC session ${n.id} for aibot=${e}`),await this.applySessionPermission(e,n.id,s),n.id}async sendOcPrompt(e,t){const s=this.getSessionCwd(e),i=await this.ensureOcSession(e);this.activeRun&&(this.activeRun.ocSessionId=i,this.activeRun.cwd=s);const n=this.resolveModelId(e),r=n.indexOf("/"),a=r>0&&r<n.length-1?{providerID:n.slice(0,r),modelID:n.slice(r+1)}:void 0;await this.transport.sendPromptAsync(i,{parts:[{type:"text",text:t}],...a?{model:a}:{}},s)}handleSseEvent(e){if(!this.stopped){if(this.lastSseAt=Date.now(),this.updateToolInFlight(e),this.resetIdleTimer(),this.activeRun){const t=this.auditCaptures.get(this.activeRun.eventId);t&&t.push({sequence:t.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(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.activeRun.cwd,{...this.buildToolbarMeta(this.activeRun.sessionId),model_provider:s.providerID,model_id:s.modelID}),s.error&&o.warn("opencode-adapter",`Message error: ${JSON.stringify(s.error)}`);const i=this.activeRun.ocSessionId;i&&s.sessionID===i&&(s.error?(this.flushTextBuffer(),this.finishRun("failed",s.error.message||s.error.type)):s.time?.completed&&s.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}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";o.error("opencode-adapter",`Session error: ${s}`),this.flushTextBuffer(),this.finishRun("failed",s);break}case"permission.updated":{this.handlePermission(e.permission);break}case"permission.asked":{this.handlePermissionAsked(e);break}case"question.asked":{this.handleQuestionAsked(e);break}case"permission.replied":case"question.replied":case"question.rejected":o.debug("opencode-adapter",`Interaction settled: ${e.type}`);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":{o.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:o.debug("opencode-adapter",`Unhandled SSE event type: ${e.type}`);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 n=this.messageRoles.get(i);if(n==="user")return;if(n==="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.sendToolUseOnce(e,s.input);break}case"completed":{this.sendToolUseOnce(e,s.input);break}case"error":{this.sendToolUseOnce(e,s.input),this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,"(failed)");break}}}sendToolUseOnce(e,t){!this.activeRun||this.toolCardsSent.has(e.callID)||(this.flushTextBuffer(),this.toolCardsSent.add(e.callID),this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,z(t??{})))}onPermissionTimeout(e){const t=this.pendingPermissions.get(e);t&&(this.pendingPermissions.delete(e),o.error("opencode-adapter",`Permission approval timeout: ${e}`),this.transport.respondPermission(t.ocSessionId,e,"reject",t.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===t.eventId&&(this.flushTextBuffer(),this.finishRun("failed","permission approval timeout")))}trackPendingPermission(e){if(!this.activeRun)return;this.stopIdleTimer();const t=setTimeout(()=>this.onPermissionTimeout(e),R);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:t})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(r=>{o.warn("opencode-adapter",`Orphan permission reject failed: ${r}`)});return}const{eventId:t,sessionId:s,ocSessionId:i}=this.activeRun;if(this.resolveModeId(s)===m.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(r=>{o.warn("opencode-adapter",`Auto-approve failed: ${r}`)});return}this.trackPendingPermission(e.id);const n=e.patterns.length>0?`${e.permission}: ${e.patterns.join(", ")}`:e.permission;this.callbacks.sendPermissionCard?this.callbacks.sendPermissionCard({eventId:t,sessionId:s,approvalId:e.id,toolName:e.permission,toolTitle:n,toolInput:JSON.stringify(e.metadata??{})}):this.callbacks.sendToolUse(t,s,e.permission,JSON.stringify(e.metadata??{}))}handlePermission(e){if(!this.activeRun)return;const{eventId:t,sessionId:s,ocSessionId:i}=this.activeRun;if(this.resolveModeId(s)===m.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(n=>{o.warn("opencode-adapter",`Auto-approve failed: ${n}`)});return}if(this.trackPendingPermission(e.id),this.callbacks.sendPermissionCard)this.callbacks.sendPermissionCard({eventId:t,sessionId:s,approvalId:e.id,toolName:e.type,toolTitle:e.title||e.type,toolInput:JSON.stringify(e.metadata??{})});else{const n=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(t,s,e.type,n)}}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const t=e.params??{},s=String(t.approval_id??t.approval_command_id??t.approvalId??t.tool_call_id??"");let i=s?this.pendingPermissions.get(s):void 0;if(!i){for(const a of this.pendingPermissions.values())if(a.eventId===this.activeRun.eventId){i=a;break}}if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:"permission"};const n=e.action_type==="exec_approve"||e.action_type==="permission_approve",r=n?"once":"reject";return clearTimeout(i.timer),this.pendingPermissions.delete(i.permissionId),this.transport.respondPermission(i.ocSessionId,i.permissionId,r,i.cwd).then(()=>{o.info("opencode-adapter",`Permission ${r}: ${i.permissionId}`),this.resetIdleTimer()}).catch(a=>{o.warn("opencode-adapter",`Permission response failed: ${a}`),this.resetIdleTimer()}),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.permissionId,decision:n?"approve":"reject"}),{handled:!0,kind:"permission"}}onQuestionTimeout(e){const t=this.pendingQuestions.get(e);t&&(this.pendingQuestions.delete(e),o.error("opencode-adapter",`Question answer timeout: ${e}`),this.transport.rejectQuestion(e,t.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===t.eventId&&(this.flushTextBuffer(),this.finishRun("failed","question answer timeout")))}handleQuestionAsked(e){if(!this.activeRun){this.transport.rejectQuestion(e.id).catch(n=>{o.warn("opencode-adapter",`Orphan question reject failed: ${n}`)});return}const{eventId:t,sessionId:s}=this.activeRun;this.stopIdleTimer();const i=setTimeout(()=>this.onQuestionTimeout(e.id),R);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:t,cwd:this.activeRun.cwd,questions:e.questions,timer:i}),this.callbacks.sendAgentQuestionCard)this.callbacks.sendAgentQuestionCard(t,s,{request_id:e.id,mode:"form",questions:e.questions.map(n=>({header:n.header,prompt:n.question,...n.options.length>0?{options:n.options.map(r=>r.label)}:{},...n.multiple!==void 0?{multi_select:n.multiple}:{}})),expires_at:Date.now()+R});else{const n=e.questions.map(r=>r.question).join(`
4
+ `);this.callbacks.sendRunError(t,s,`Agent asks: ${n}`)}}handleQuestionReplyAction(e){const t=e.params??{},s=String(t.request_id??""),i=s?this.pendingQuestions.get(s):void 0;if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"interaction_request_not_pending","The question is no longer pending; the reply was not delivered."),{handled:!0,kind:"question_reply"};const n=t.resolution??{},r=String(n.type??""),a=(d,u)=>{clearTimeout(i.timer),this.pendingQuestions.delete(i.requestId),d().then(()=>this.resetIdleTimer()).catch(f=>{o.warn("opencode-adapter",`Question response failed: ${f}`),this.resetIdleTimer()}),this.callbacks.sendLocalActionResult(e.action_id,"ok",u)};if(r==="action"){const d=String(n.value??"");if(d==="cancel"||d==="decline")return a(()=>this.transport.rejectQuestion(i.requestId,i.cwd),{request_id:s,resolution:"cancel"}),{handled:!0,kind:"question_reply"}}let c=null;if(Array.isArray(t.answers))c=t.answers.map(d=>Array.isArray(d)?d.map(String):[String(d)]);else if(r==="text"){const d=String(n.value??"");d&&(c=i.questions.map((u,f)=>f===0?[d]:[]))}else if(r==="map"){const d=Array.isArray(n.entries)?n.entries:[];c=i.questions.map((u,f)=>{const l=d.find(v=>v.key===u.header||v.key===String(f));return l&&l.value?[l.value]:[]})}if(!c||c.every(d=>d.length===0))return a(()=>this.transport.rejectQuestion(i.requestId,i.cwd),{request_id:s,resolution:"cancel"}),{handled:!0,kind:"question_reply"};const p=c;return a(()=>this.transport.replyQuestion(i.requestId,p,i.cwd),{request_id:s,resolution:"answer"}),{handled:!0,kind:"question_reply"}}rejectAllPendingInteractions(){for(const e of this.pendingPermissions.values())clearTimeout(e.timer),this.transport.respondPermission(e.ocSessionId,e.permissionId,"reject",e.cwd).catch(()=>{});this.pendingPermissions.clear();for(const e of this.pendingQuestions.values())clearTimeout(e.timer),this.transport.rejectQuestion(e.requestId,e.cwd).catch(()=>{});this.pendingQuestions.clear()}hasPendingInteractionForRun(e){for(const t of this.pendingPermissions.values())if(t.eventId===e)return!0;for(const t of this.pendingQuestions.values())if(t.eventId===e)return!0;return!1}startRun(e,t,s=!1){this.activeRun={eventId:e,sessionId:t,ocSessionId:"",cwd:this.getSessionCwd(t),chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null},this.toolCardsSent.clear(),s&&this.auditCaptures.set(e,[]),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>oe){const a=[...this.completedEvents].slice(-500);this.completedEvents=new Set(a)}this.snapshotAuditBoundary(s),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopComposing(),this.stopIdleTimer();const i=++s.chunkSeq,n=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,n).then(()=>{this.callbacks.sendEventResult(s.eventId,e,t)}).catch(a=>{const c=e==="responded"?"failed":e,p=e==="responded"?`final output delivery failed: ${a instanceof Error?a.message:String(a)}`:t;this.callbacks.sendEventResult(s.eventId,c,p)}):(this.callbacks.sendStreamChunk(s.eventId,s.sessionId,"",i,!0,n),this.callbacks.sendEventResult(s.eventId,e,t))};if(s.textBuffer){this.stopTextFlush();for(const a of A(s.textBuffer))s.chunkSeq++,this.callbacks.sendStreamChunk(s.eventId,s.sessionId,a,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&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopIdleTimer(),e&&this.emit("eventDone",e)}snapshotAuditBoundary(e){const t=this.auditCaptures.get(e.eventId);t&&(this.completedAuditBoundaries.set(e.eventId,{adapterType:"opencode",providerSessionId:e.ocSessionId||void 0,openCodeEvidence:{events:t}}),this.auditCaptures.delete(e.eventId))}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=Y){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},W))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const e of A(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||!x(e))return!1;const t=Date.now(),s=this.lastSseAt>0?t-this.lastSseAt:Number.POSITIVE_INFINITY;if(s<Z)return this.livenessExtendStartAt=t,o.info("opencode-adapter",`Liveness check: fresh SSE for ${this.activeRun.eventId} (sseAge=${s}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??t;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),t-n>y?(o.warn("opencode-adapter",`Liveness extension budget exhausted for ${this.activeRun.eventId} (no progress for ${Math.round((t-n)/6e4)}min), allowing idle fail`),!1):(o.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.hasPendingInteractionForRun(this.activeRun.eventId)&&this.shouldExtendByLiveness()){o.info("opencode-adapter",`Idle timeout skipped: pending interaction for ${this.activeRun.eventId}, resetting timer`),this.resetIdleTimer();return}if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const e=this.process?.pid,s=!!(this.alive&&e&&x(e))?`liveness budget exhausted after ${y/6e4}min`:"process not alive";o.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)},K))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveCwd(){const e=this.options.aibotSessionId?this.options.bindingStore?.get(this.options.aibotSessionId)?.cwd:void 0;if(e)return e;const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}getSessionCwd(e){return this.sessions.get(e)?.cwd??this.options.bindingStore?.get(e)?.cwd??this.resolveCwd()}buildPromptText(e){let t=e.text;return e.contextMessages&&e.contextMessages.length>0&&(t=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
5
5
  `)+`
6
6
 
7
7
  `+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(n=>`[context] ${n.sender_id??"unknown"}: ${n.content}`).join(`
8
8
  `)+`
9
9
 
10
- `+t)}catch{}return this.identity.injectOnce(e.session_id,t)}}export{ge as OpenCodeAdapter};
10
+ `+t)}catch{}return this.identity.injectOnce(e.session_id,t)}}export{ke as OpenCodeAdapter};
@@ -1,5 +1,5 @@
1
- import{EventEmitter as f}from"node:events";import{log as l}from"../../core/log/index.js";const p=3e4,u=3e3,y=3e4;class b extends f{baseUrl="";directory="";abortController=null;closed=!1;sseConnected=!1;sseGeneration=0;async connect(t,e){this.baseUrl=t,this.directory=e??"",this.closed=!1,await this.subscribeEvents(),l.info("opencode-transport",`connected to ${t}`)}async useDirectory(t){const e=t??"";this.directory===e&&this.sseConnected&&!this.closed||(this.directory=e,!(!this.baseUrl||this.closed)&&(this.abortController&&(this.abortController.abort(),this.abortController=null),this.sseConnected=!1,await this.subscribeEvents(),l.info("opencode-transport",`switched directory to ${e||"<default>"}`)))}async subscribeEvents(){if(this.closed)return;const t=++this.sseGeneration,e=new AbortController;this.abortController=e;const s=new URL("/event",this.baseUrl);this.directory&&s.searchParams.set("directory",this.directory);const r=await fetch(s.toString(),{method:"GET",headers:{Accept:"text/event-stream"},signal:e.signal});if(!r.ok||!r.body)throw new Error(`SSE connect failed: ${r.status}`);this.sseConnected=!0,this.readSseStream(r.body.getReader(),t)}async readSseStream(t,e){const s=new TextDecoder;let r="";try{for(;!this.closed;){const{done:n,value:o}=await t.read();if(n)break;r+=s.decode(o,{stream:!0});const a=r.split(`
1
+ import{EventEmitter as f}from"node:events";import{log as l}from"../../core/log/index.js";const p=3e4,u=3e3,y=3e4;class b extends f{baseUrl="";directory="";abortController=null;closed=!1;sseConnected=!1;sseGeneration=0;async connect(t,e){this.baseUrl=t,this.directory=e??"",this.closed=!1,await this.subscribeEvents(),l.info("opencode-transport",`connected to ${t}`)}async useDirectory(t){const e=t??"";this.directory===e&&this.sseConnected&&!this.closed||(this.directory=e,!(!this.baseUrl||this.closed)&&(this.abortController&&(this.abortController.abort(),this.abortController=null),this.sseConnected=!1,await this.subscribeEvents(),l.info("opencode-transport",`switched directory to ${e||"<default>"}`)))}async subscribeEvents(){if(this.closed)return;const t=++this.sseGeneration,e=new AbortController;this.abortController=e;const s=new URL("/event",this.baseUrl);this.directory&&s.searchParams.set("directory",this.directory);const r=await fetch(s.toString(),{method:"GET",headers:{Accept:"text/event-stream"},signal:e.signal});if(!r.ok||!r.body)throw new Error(`SSE connect failed: ${r.status}`);this.sseConnected=!0,this.readSseStream(r.body.getReader(),t)}async readSseStream(t,e){const s=new TextDecoder;let r="";try{for(;!this.closed;){const{done:n,value:i}=await t.read();if(n)break;r+=s.decode(i,{stream:!0});const a=r.split(`
2
2
 
3
- `);r=a.pop()??"";for(const h of a){const c=this.parseSseFrame(h);if(c)try{this.emit("event",c)}catch(i){const d=i instanceof Error?i.message:String(i);l.warn("opencode-transport",`event handler failed (${c.type}): ${d}`)}}}}catch(n){if(this.closed)return;const o=n instanceof Error?n.message:String(n);if(o.includes("abort"))return;l.warn("opencode-transport",`SSE error: ${o}, reconnecting...`),await this.reconnectSse(e)}finally{e===this.sseGeneration&&(this.sseConnected=!1)}}parseSseFrame(t){let e="",s=[];for(const r of t.split(`
3
+ `);r=a.pop()??"";for(const h of a){const c=this.parseSseFrame(h);if(c)try{this.emit("event",c)}catch(o){const d=o instanceof Error?o.message:String(o);l.warn("opencode-transport",`event handler failed (${c.type}): ${d}`)}}}}catch(n){if(this.closed)return;const i=n instanceof Error?n.message:String(n);if(i.includes("abort"))return;l.warn("opencode-transport",`SSE error: ${i}, reconnecting...`),await this.reconnectSse(e)}finally{e===this.sseGeneration&&(this.sseConnected=!1)}}parseSseFrame(t){let e="",s=[];for(const r of t.split(`
4
4
  `))r.startsWith("event:")?e=r.slice(6).trim():r.startsWith("data:")&&s.push(r.slice(5).trimStart());if(s.length===0)return null;try{const r=s.join(`
5
- `),n=JSON.parse(r);if(e&&n.type!==e&&(n.type=e),n&&typeof n.properties=="object"&&n.properties!==null){const{properties:o,...a}=n;return{...a,...o}}return n}catch{return null}}async reconnectSse(t){if(this.closed||t!==this.sseGeneration)return;const e=u+Math.random()*u;if(await new Promise(s=>setTimeout(s,Math.min(e,y))),!this.closed&&t===this.sseGeneration)try{await this.subscribeEvents()}catch(s){if(this.closed)return;l.warn("opencode-transport",`SSE reconnect failed: ${s instanceof Error?s.message:String(s)}`),this.reconnectSse(this.sseGeneration)}}async request(t,e,s,r){if(this.closed)throw new Error("transport closed");const n=new URL(e,this.baseUrl),o=r?.directory??this.directory;o&&n.searchParams.set("directory",o);const a=new AbortController,h=setTimeout(()=>a.abort(),p);try{const c={method:t,headers:{"Content-Type":"application/json"},signal:a.signal};s!==void 0&&(c.body=JSON.stringify(s));const i=await fetch(n.toString(),c);if(i.status===204)return;const d=await i.json();if(!i.ok)throw new Error(`REST ${t} ${e}: ${i.status} ${JSON.stringify(d)}`);return d}finally{clearTimeout(h)}}async createSession(t,e){return this.request("POST","/session",t??{},{directory:e})}async getSession(t,e){return this.request("GET",`/session/${t}`,void 0,{directory:e})}async deleteSession(t,e){await this.request("DELETE",`/session/${t}`,void 0,{directory:e})}async sendPromptAsync(t,e,s){await this.request("POST",`/session/${t}/prompt_async`,e,{directory:s})}async abortSession(t,e){await this.request("POST",`/session/${t}/abort`,void 0,{directory:e})}async respondPermission(t,e,s,r){await this.request("POST",`/session/${t}/permissions/${e}`,{response:s},{directory:r})}async replyQuestion(t,e,s){await this.request("POST",`/question/${t}/reply`,{answers:e},{directory:s})}async rejectQuestion(t,e){await this.request("POST",`/question/${t}/reject`,void 0,{directory:e})}async listProviders(){return(await this.request("GET","/config/providers"))?.providers??[]}async healthCheck(){try{return(await fetch(new URL("/session",this.baseUrl).toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:AbortSignal.timeout(3e3)})).ok}catch{return!1}}disconnect(){this.closed=!0,this.sseGeneration++,this.abortController&&(this.abortController.abort(),this.abortController=null),this.sseConnected=!1,this.removeAllListeners()}get isConnected(){return this.sseConnected&&!this.closed}}export{b as OpenCodeTransport};
5
+ `),n=JSON.parse(r);if(e&&n.type!==e&&(n.type=e),n&&typeof n.properties=="object"&&n.properties!==null){const{properties:i,...a}=n;return{...a,...i}}return n}catch{return null}}async reconnectSse(t){if(this.closed||t!==this.sseGeneration)return;const e=u+Math.random()*u;if(await new Promise(s=>setTimeout(s,Math.min(e,y))),!this.closed&&t===this.sseGeneration)try{await this.subscribeEvents()}catch(s){if(this.closed)return;l.warn("opencode-transport",`SSE reconnect failed: ${s instanceof Error?s.message:String(s)}`),this.reconnectSse(this.sseGeneration)}}async request(t,e,s,r){if(this.closed)throw new Error("transport closed");const n=new URL(e,this.baseUrl),i=r?.directory??this.directory;i&&n.searchParams.set("directory",i);const a=new AbortController,h=setTimeout(()=>a.abort(),p);try{const c={method:t,headers:{"Content-Type":"application/json"},signal:a.signal};s!==void 0&&(c.body=JSON.stringify(s));const o=await fetch(n.toString(),c);if(o.status===204)return;const d=await o.json();if(!o.ok)throw new Error(`REST ${t} ${e}: ${o.status} ${JSON.stringify(d)}`);return d}finally{clearTimeout(h)}}async createSession(t,e){return this.request("POST","/session",t??{},{directory:e})}async getSession(t,e){return this.request("GET",`/session/${t}`,void 0,{directory:e})}async deleteSession(t,e){await this.request("DELETE",`/session/${t}`,void 0,{directory:e})}async updateSessionPermission(t,e,s){await this.request("PATCH",`/session/${t}`,{permission:e},{directory:s})}async sendPromptAsync(t,e,s){await this.request("POST",`/session/${t}/prompt_async`,e,{directory:s})}async abortSession(t,e){await this.request("POST",`/session/${t}/abort`,void 0,{directory:e})}async respondPermission(t,e,s,r){await this.request("POST",`/session/${t}/permissions/${e}`,{response:s},{directory:r})}async replyQuestion(t,e,s){await this.request("POST",`/question/${t}/reply`,{answers:e},{directory:s})}async rejectQuestion(t,e){await this.request("POST",`/question/${t}/reject`,void 0,{directory:e})}async listProviders(){return(await this.request("GET","/config/providers"))?.providers??[]}async healthCheck(){try{return(await fetch(new URL("/session",this.baseUrl).toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:AbortSignal.timeout(3e3)})).ok}catch{return!1}}disconnect(){this.closed=!0,this.sseGeneration++,this.abortController&&(this.abortController.abort(),this.abortController=null),this.sseConnected=!1,this.removeAllListeners()}get isConnected(){return this.sseConnected&&!this.closed}}export{b as OpenCodeTransport};
@@ -13,4 +13,4 @@ Error: ${u}`,1,!1)},sendPermissionCard:c=>{h.info("bridge","sendPermissionCard c
13
13
  Error: ${t}`,1,!1),this.surfacedRunErrorEvents.add(e))}sendEventResultWithCleanup(e,n,t,s){const i=this.eventSessionIndex.get(e);n==="failed"&&i&&t?.trim()&&this.sendRunErrorAsChunk(e,i,t),this.auditController.markResponded(e,n,t),this.sendCtrl.sendEventResult(e,n,t,s),i&&(this.pool.eventComplete(e,i)===!1&&h.error(this.name,`Event terminal result could not release queue slot event=${e} session=${i} status=${n}`),this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,n,t),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorEvents.delete(e),n==="responded"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:n,sessionId:t,errorMsg:s}=e;if(this.stopped)return;const i=this.inflightEvents.get(n);if(!i){h.warn(this.name,`[recovery] no inflight event for internalError event=${n} session=${t}; surface failure directly`),this.sendRunErrorAsChunk(n,t,s),this.sendEventResultWithCleanup(n,"failed",s,"agent_stop_failure");return}const o=(this.restartCount.get(n)??0)+1;this.restartCount.set(n,o);const r=this.config.adapterType??"acp";if(o>V){h.error(this.name,`[recovery] adapter=${r} session=${t} event=${n} restart=${o}/${V} outcome=give-up err=${s}`),this.sendRunErrorAsChunk(n,t,s),this.sendEventResultWithCleanup(n,"failed",s,"agent_stop_failure");return}h.info(this.name,`[recovery] adapter=${r} session=${t} event=${n} restart=${o}/${V} outcome=restarting err=${s}`);const a=this.pool.drainQueuedForSession(t);a.length>0&&h.info(this.name,`[recovery] session=${t} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(t)}catch(l){h.warn(this.name,`[recovery] removeSlot failed session=${t}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const d=this.resolveRecoveryPrompt(r,i),c={...i,content:d};try{await this.pool.deliverInboundEvent(c)}catch(l){h.error(this.name,`[recovery] redeliver failed event=${n} session=${t}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(n,"failed",l instanceof Error?l.message:String(l));return}for(const l of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(l)}catch(u){h.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${t}: ${u instanceof Error?u.message:String(u)}`),this.sendEventResultWithCleanup(l.event_id,"failed",u instanceof Error?u.message:String(u))}}}resolveRecoveryPrompt(e,n){return e==="acp"?"continue":n.content}sendThinkingByRuntimeConfig(e,n,t){this.sendCtrl.sendThinking(e,n,t)}bufferStreamChunk(e,n,t,s,i){this.auditController.captureUnsequencedStreamChunk(e,t),this.sendCtrl.bufferOnly(e,n,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),this.auditController.markRecording(e.event_id),e.event_id&&!this.inflightEvents.has(e.event_id)&&this.inflightEvents.set(e.event_id,e)}indexEventSession(e,n){if(!e||!n)return;const t=this.eventSessionIndex.get(e);return t?(t!==n&&h.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${t} supplied=${n}`),t):(this.eventSessionIndex.set(e,n),n)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,n){return this.sendCtrl.shouldDropCodexDisplayEvent(e,n)}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,n){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,n)}sendAcpRawEventEnvelope(e,n,t){this.shouldDropAcpRawDisplayEvent(e,t.type)||this.deliverRawEventEnvelope(e,n,t,"acp",this.buildAcpRawEventFallbackText(t))}buildAcpRawEventFallbackText(e){const n=String(e.type??"").trim();if(!n)return"[acp] event";switch(n){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] ${n}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,n,t,s,i){const o=jt({envelope:t,fallbackText:i,channelKey:s,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),r=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:n,msg_type:1,content:o.fallbackText,extra:{channel_data:{[s]:{raw_event:o.envelope}},agent_api_origin:!0}})};if(!o.sharded){r();return}h.info("bridge",`${s} raw_event oversized, sharded delivery: event=${e} fields=${o.oversizedFields.map(a=>a.field).join(",")}`),(async()=>{for(const a of o.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,n,Vt({envelopeType:t.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);r()})().catch(a=>{h.warn("bridge",`${s} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const n=String(e?.type??"").trim(),t=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(n){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 n?`[cursor] ${n}`:"[cursor] event"}}sendToolExecutionCard(e,n,t,s){this.sendCtrl.sendToolExecutionCard(e,n,t,s)}sendGrixApprovalCard(e,n){this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${F()}`,msg_type:1,content:e.toolTitle?`Permission required: ${e.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:e.approvalId,approvalSlug:e.toolName},grix:{execApproval:{approval_command_id:e.approvalId,command:e.toolTitle||e.toolName,host:n}}},agent_api_origin:!0}})}sendGrixAgentQuestionCard(e,n,t){const s=t.questions.map(o=>o.header).join(", "),i=pe(`[Agent Question] ${t.request_id}`,"agent_question",t);this.aibotHandle.sendText({event_id:e,session_id:n,content:i,msg_type:1,extra:{card_type:"agent_question",summary_text: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 n=this.config.adapterType??"acp",t=Ft(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=oi(e.extra);if((i.state!=="absent"||i.error)&&h.info(this.name,`[audit-marker] event=${e.event_id} session=${e.session_id} msg=${e.msg_id??""} state=${i.state??"error"} scope=${i.options?.enabled?i.options.scope:""} error=${i.error??""}`),i.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:"audit_config_invalid",msg:i.error,updated_at:Date.now()});return}if(i.state==="enabled"&&n!=="claude"&&n!=="codex"&&n!=="cursor"&&n!=="opencode"&&n!=="pi"&&n!=="codewhale"&&n!=="acp"){if(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:"audit_provider_unsupported",msg:`Audit replay is not supported for adapter: ${n}`,updated_at:Date.now()}),i.options?.enabled&&i.options.scope==="turn")try{this.aibotHandle.sendAuditState(j({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_provider_unsupported",errorMessage:`Audit replay is not supported for adapter: ${n}`},Date.now()))}catch{}return}const o=Pt(e);if(o){if(i.state!=="absent"||o.verb===_.open)try{this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra})}catch(c){this.sendAuditConfigurationError(e,c);return}if(o.verb===_.exec){await this.handleSessionControlCommand(o,e);return}if(o.verb===_.listSessions){await this.handleListSessionsTextCommand(e);return}if(n==="claude"){await this.handleSessionControlCommand(o,e);return}if(n==="codex"&&o.verb===_.open){await this.handleCodexSessionControlOpen(o,e);return}if(n==="pi"&&o.verb===_.open){await this.handlePiSessionControlOpen(o,e);return}if(n==="pi"&&o.verb===_.restart){await this.handlePiSessionControlRestart(e);return}if((n==="openhuman"||n==="opencode")&&o.verb===_.open){await this.handleOpenHumanSessionControlOpen(o,e);return}if(n==="codewhale"&&o.verb===_.open){await this.handleCodeWhaleSessionControlOpen(o,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),o.verb===_.open){const c=o.args.trim();if(!c){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const l=P.resolve(c);if(!(await O(l)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:`Path is not a directory: ${l}`,updated_at:Date.now()});return}}catch(l){const u=String(l?.code??""),p=u==="ENOENT"?`Directory does not exist: ${P.resolve(c)}`:u==="EACCES"||u==="EPERM"?"Directory is not accessible":`Invalid path: ${c}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:p,updated_at:Date.now()});return}}if(o.verb===_.open){const c=this.bindingStore.get(e.session_id);if(c?.cwd)try{await O(c.cwd)}catch{h.info("bridge",`Stale binding detected for session ${e.session_id}: ${c.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 l=this.pool.getSlot(e.session_id);l?.adapter instanceof R&&l.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(o,e),n==="acp"&&o.verb===_.stop){const l=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 ${l}`,updated_at:Date.now()});return}if(ae(o,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(),sendEventAck:()=>{}}),o.verb===_.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),n==="agy")){const c=this.bindingStore.get(e.session_id)?.cwd??"";c&&this.aibotHandle.sendUpdateBindingCard({session_id:e.session_id,worker_status:"ready",cwd:c,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}let r;try{r=this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra,eventId:e.event_id}).session}catch(c){this.sendAuditConfigurationError(e,c);return}if(hi.has(n)&&!this.bindingStore.get(e.session_id)?.cwd){const l=n;h.info(this.name,`[${l}] binding missing session_id=${e.session_id} event_id=${e.event_id}`),this.deferredMgr.defer(l,String(e.session_id??"").trim(),this.prepareAuditedInboundEvent(e,s,r));const u=this.resolveBindingChannelKey(n);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:{[u]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:g.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const l=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(l){const[,u,p]=l,m=this.pool.getSlot(e.session_id)?.adapter;if(m?.execCommand&&(m.getSupportedCommands?.()??[]).some(b=>b.name===u||b.name===`/${u}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const b=await m.execCommand(u,p.trim(),e.session_id);b.status==="options"&&b.data&&this.handleExecCommandOptions(e.session_id,u,b.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:b.status==="failed"?"failed":"responded",msg:b.message,updated_at:Date.now()})}catch(b){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:b instanceof Error?b.message:String(b),updated_at:Date.now()})}return}}}if(n==="codex"&&te(r?.options)){const c=this.pool.getSlot(e.session_id);if(c?.adapter instanceof J&&!c.adapter.hasRawApiCaptureRelay()){const l=c.eventQueue.snapshot(e.session_id);l.running.length===0&&l.queued.length===0?(h.info(this.name,`[audit-raw-capture] recreating idle Codex adapter before event=${e.event_id} session=${e.session_id}`),await this.pool.removeSlot(e.session_id)):h.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${l.running.length} queued=${l.queued.length}`)}}const d=this.prepareAuditedInboundEvent(e,s,r);try{this.captureEventRuntimeConfig(d),await this.pool.deliverInboundEvent(d)}catch(c){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",c instanceof Error?c.message:String(c),{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),c instanceof $t)this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:c.message,updated_at:Date.now()});else throw c}}async handleCodexSessionControlOpen(e,n){const t=n.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:t,received_at:Date.now()}),o=(r,a)=>this.aibotHandle.sendEventResult({event_id:n.event_id,status:r,...a,updated_at:Date.now()});if(!s){i(),o("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const r=await this.resolveCwdForBinding(s),a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(a.cwd)===r){i(),o("responded",{msg:`Session already bound to ${a.cwd}`});return}}catch{d=!0,h.info("bridge",`Stale codex binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){i(),o("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),o("responded",{msg:`Session bound to ${r}`})}catch(r){i(),o("failed",{code:g.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handleSessionControlForPool(e,n){e.verb===_.open&&await this.bindSessionForPool(n.session_id,e.args.trim())}async replayDeferredEventsForSession(e){await this.deferredMgr.release(e,this.deferredCallbacks())}async handleSessionControlLocalActionForPool(e){if(String(e.action_type??"")!==A.sessionControl)return;const n=e.params??{};if(String(n.verb??"").trim().toLowerCase()!==_.open)return;const s=String(n.session_id??"").trim(),i=String(n.cwd??"").trim();!s||!i||await this.bindSessionForPool(s,i)}async handleCodexSessionControlLocalActionOpen(e){const n=e.params??{},t=String(n.session_id??"").trim(),s=String(n.cwd??"").trim(),i=String(n.agent_session_id??"").trim(),o=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){o("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(a.cwd);if(c===r){this.setResolvedAgentSessionId(t,i),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,h.info("bridge",`Stale codex binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){o("failed",void 0,g.rebindForbidden,`Session already bound to ${a.cwd}`);return}}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){o("failed",void 0,r?.sessionControlErrorCode??g.invalidCwd,r instanceof Error?r.message:String(r))}}async handleCursorSessionControlLocalActionOpen(e){const n=e.params??{},t=String(n.session_id??"").trim(),s=String(n.cwd??"").trim(),i=String(n.agent_session_id??"").trim(),o=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){o("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(a.cwd);if(c===r){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)}),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,h.info("bridge",`Stale cursor binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){o("failed",void 0,g.rebindForbidden,`Session already bound to ${a.cwd}`);return}}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),this.deferredMgr.sendCursorDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r,meta:this.buildCursorToolbarMeta(t)}),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){o("failed",void 0,r?.sessionControlErrorCode??g.invalidCwd,r instanceof Error?r.message:String(r))}}async handlePiSessionControlOpen(e,n){const t=n.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:t,received_at:Date.now()}),o=(r,a)=>this.aibotHandle.sendEventResult({event_id:n.event_id,status:r,...a,updated_at:Date.now()});if(!s){i(),o("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const r=await this.resolveCwdForBinding(s),a=this.bindingStore.get(t);if(a?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(a.cwd)===r){i(),o("responded",{msg:`Session already bound to ${a.cwd}`}),this.aibotHandle.sendMsg({event_id:n.event_id,session_id:t,msg_type:1,content:`\u2705 Session already bound to \`${a.cwd}\``,quoted_message_id:n.msg_id});return}}catch{d=!0,h.info("bridge",`Stale pi binding for session ${t}: ${a.cwd} no longer exists, allowing rebind`)}if(!d){i(),o("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),await this.ensureSlotStarted(t).catch(d=>{h.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:r}),i(),o("responded",{msg:`Session bound to ${r}`}),this.aibotHandle.sendMsg({event_id:n.event_id,session_id:t,msg_type:1,content:`\u2705 Working directory bound: \`${r}\``,quoted_message_id:n.msg_id})}catch(r){i(),o("failed",{code:g.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handlePiSessionControlRestart(e){const n=e.session_id,t=()=>this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:n,received_at:Date.now()}),s=(r,a)=>this.aibotHandle.sendEventResult({event_id:e.event_id,status:r,...a,updated_at:Date.now()}),o=this.bindingStore.get(n)?.cwd??"";if(!o){t(),s("failed",{msg:"session binding was not found",code:g.bindingMissing});return}t(),await this.pool.removeSlot(n).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:"ready",cwd:o}),s("responded",{msg:`Session worker restarted for ${o}`})}async handlePiSessionControlRestartLocalAction(e){const n=e.params??{},t=String(n.session_id??"").trim(),i=(t?this.bindingStore.get(t):void 0)?.cwd??"",o=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t){o("failed",void 0,"session_id_required","session_id is required for restart");return}if(!i){o("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}),o("ok",{outcome:"restarted",binding:{aibotSessionId:t,cwd:i,workerStatus:"ready"}})}syncOpenCodeBinding(e,n){if(!e||!n)return;const t=this.pool.getSlot(e);t?.adapter instanceof Z&&t.adapter.bindSession(e,n)}async bindSessionForPool(e,n){const t=String(n??"").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 R?s.adapter:null;if(!i?.hasSessionBinding)return;const o=await this.resolveCwdForBinding(t);i.announceDeferredComposing(e),await i.bindSession(e,o),this.sessionBindings.set(e,o),this.sessionScanCache.invalidate(),i.replayDeferredEvents(e)}deferredCallbacks(){return{captureEventRuntimeConfig:e=>this.captureEventRuntimeConfig(e),deliverInboundEvent:e=>this.pool.deliverInboundEvent(e),sendEventResult:(e,n,t)=>this.sendEventResultWithCleanup(e,n,t),sendSessionComposing:(e,n,t)=>{const s={};n&&(s.ttl_ms=t?.ttlMs??3e4,t?.activity&&(s.activity=t.activity)),this.aibotHandle.sendSessionActivitySet({session_id:e,kind:"composing",active:n,...s})}}}async handleOpenHumanSessionControlOpen(e,n){const t=()=>this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:n.session_id,received_at:Date.now()});try{const s=await this.resolveCwdForBinding(e.args.trim());await this.handleSessionControlForPool(e,n),this.syncOpenCodeBinding(n.session_id,s),ae(e,n,this.sessionControlCtx(n.session_id),this.sessionControlSenders()),await this.deferredMgr.release(n.session_id,this.deferredCallbacks())}catch(s){t(),this.aibotHandle.sendEventResult({event_id:n.event_id,status:"failed",code:s?.cwdErrorCode,msg:s instanceof Error?s.message:String(s),updated_at:Date.now()})}}async handleCodeWhaleSessionControlOpen(e,n){const t=n.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:t,received_at:Date.now()}),o=(r,a)=>this.aibotHandle.sendEventResult({event_id:n.event_id,status:r,...a,updated_at:Date.now()});if(!s){i(),o("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const r=await this.resolveCwdForBinding(s),a=this.bindingStore.get(t);if(a?.cwd){if(await this.resolveCwdForBinding(a.cwd)!==r){i(),o("failed",{msg:`Session already bound to ${a.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}i(),o("responded",{msg:`Session already bound to ${a.cwd}`});return}this.bindingStore.set(t,r),this.sessionBindings.set(t,r),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),i(),o("responded",{msg:`Session bound to ${r}`})}catch(r){i(),o("failed",{code:g.invalidCwd,msg:r instanceof Error?r.message:String(r)})}}async handleCodeWhaleSessionControlLocalActionOpen(e){const n=e.params??{},t=String(n.session_id??"").trim(),s=String(n.cwd??"").trim(),i=String(n.agent_session_id??"").trim(),o=(r,a,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:r,...a!==void 0?{result:a}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){o("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const r=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,r);const a=this.bindingStore.get(t);if(a?.cwd){const d=await this.resolveCwdForBinding(a.cwd);if(d!==r){o("failed",void 0,g.rebindForbidden,`Session already bound to ${a.cwd}`);return}this.setResolvedAgentSessionId(t,i),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,d)});return}this.bindingStore.set(t,r),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,r),await this.bindSessionForPool(t,r),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:r}),o("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,r)})}catch(r){o("failed",void 0,r?.sessionControlErrorCode??g.invalidCwd,r instanceof Error?r.message:String(r))}}normalizeClaudeModeId(e){return String(e??"").trim().toLowerCase()===k.approval?k.approval:k.fullAuto}handleExecCommandOptions(e,n,t){const s=Array.isArray(t?.options)?t.options:[];if(s.length===0)return;const o=this.bindingStore.get(e)?.cwd??"",r={};if(n==="model"){r.available_models=s.map(d=>({id:d.id,displayName:d.label}));const a=s.find(d=>d.current);a&&(r.model_id=a.id)}else if(n==="mode"){r.available_modes=s.map(d=>({id:d.id,displayName:d.label}));const a=s.find(d=>d.current);a&&(r.mode_id=a.id)}else r[`${n}_options`]=s;this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:o,meta:r})}resolveSessionModelId(e){const n=this.bindingStore.getModelId(e);if(n)return n;const t=String(this.globalConfigStore?.get(this.name)?.modelId??"").trim();if(t)return this.bindingStore.setModelId(e,t),t}resolveCodexSessionModelId(e){const n=this.bindingStore.getCodexModelId(e);if(n)return n;if(this.bindingStore.getCodexThreadId(e))return;const t=String(this.globalConfigStore?.get(this.name)?.codexModelId??"").trim();if(t)return this.bindingStore.setCodexModelId(e,t),t}resolveCodexNewSessionGlobalDefault(e,n,t){const s=String(n??"").trim();if(s&&!this.bindingStore.getCodexThreadId(e))return t(s),s}buildCursorToolbarMeta(e){const n=this.pool.getSlot(e);if(n?.adapter instanceof D)return n.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:Ae.map(i=>({...i}))}}buildAgyToolbarMeta(e){if(!this.bindingStore.get(e))return;const t=Re(this.config.agent.command),s=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||s;t.length>0&&!t.some(r=>r.id===i)&&(i=s);const o=ye();return{model_id:i,currentModelId:i,available_models:t.map(r=>({id:r.id,displayName:r.displayName})),...o.plan!==void 0&&{plan:o.plan},...o.quota_exhausted!==void 0&&{quota_exhausted:o.quota_exhausted},...o.quota_reset_at!==void 0&&{quota_reset_at:o.quota_reset_at},...o.available_credits!==void 0&&{available_credits:o.available_credits}}}async handleAgySetModel(e,n){const t=e.params??{},s=String(t.model_id??t.modelId??"").trim();if(!n){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(n);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(n,s),this.globalConfigStore?.set(this.name,{modelId:s})),await Ee().catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:"ready",cwd:i.cwd,meta:this.buildAgyToolbarMeta(n)}),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 n=this.bindingStore.get(e);if(!n)return;const t=W(),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 o=this.normalizeClaudeModeId(n.modeId),r={model_id:i,mode_id:o,currentModelId:i,currentModeId:o,available_models:t.map(l=>({id:l.id,displayName:l.displayName}))},a=this.pool.getSlot(e),d=a?.adapter instanceof L?a.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)&&(r.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&&(r.context_window={usedPercentage:l.usedPercentage,remainingPercentage:l.remainingPercentage})}if(!r.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const l=this.providerQuotaToRateLimits(this.cachedProviderQuota);l&&(r.rate_limits=l),h.info(this.name,`[toolbar-meta] provider quota fallback: hasCached=${!!this.cachedProviderQuota} fromProvider=${JSON.stringify(l)}`)}return r.rate_limits&&h.info(this.name,`[toolbar-meta] rate_limits included: ${JSON.stringify(r.rate_limits)}`),r}providerQuotaToCodexRateLimits(e){return he(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return ue(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){const n=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(n)||/^\\\\/.test(n))){const i=new Error(`Specified path is not valid on this host: ${n}`);throw i.cwdErrorCode=g.invalidCwd,i}const t=P.resolve(n);let s;try{s=await O(t)}catch(i){const o=String(i?.code??"");if(o==="ENOENT"){const r=new Error(`Specified path does not exist: ${t}`);throw r.cwdErrorCode=g.invalidCwd,r}if(o==="EACCES"||o==="EPERM"){const r=new Error("Specified path is not accessible.");throw r.cwdErrorCode=g.invalidCwd,r}throw i}if(!s.isDirectory()){const i=new Error("Specified path is not a directory.");throw i.cwdErrorCode=g.invalidCwd,i}try{return await fe(t)}catch{return t}}getClaudeWorkerStatus(e){const n=this.pool.getSlot(e);return n?n.state==="starting"?"starting":n.state==="stopped"?"stopped":n.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,n){const t=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,t),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:t,cwd:n,meta:this.buildClaudeToolbarMeta(e)}),t}async handleSkillUploadLocalAction(e){const n=e.params??{},t=String(n.name??"").trim(),s=String(n.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=M(this.config.adapterType,this.config.aibot.clientType),o=this.bindingStore.get(s)?.cwd||this.sessionBindings.get(s)||void 0,r=i==="kiro"?o:o||process.cwd();try{await Qe(t,{mode:i,projectDir:r},{apiKey:this.config.aibot.apiKey,wsUrl:this.config.aibot.url}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:t}})}catch(a){h.warn(this.name,`skill_upload failed name=${t}: ${a instanceof Error?a.message:String(a)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"SKILL_UPLOAD_FAILED",error_msg:a instanceof Error?a.message:String(a)})}}async handleSkillEnableLocalAction(e){const n=e.params??{},t=String(n.name??"").trim(),s=String(n.session_id??"").trim(),i=String(n.scope??"").trim(),o=String(n.actor_id??"").trim(),r=n.force==="replace_link"||n.force==="replace_with_link"?n.force:void 0,a=M(this.config.adapterType,this.config.aibot.clientType),d=this.bindingStore.get(s)?.cwd||this.sessionBindings.get(s)||void 0;try{const c=await qe({skillsDir:$.skills,mode:a,home:U(),cwd:d},{name:t,scope:i,actorId:o,force:r});h.info(this.name,`skill_enable name=${t} scope=${i} actor=${o||"-"} changed=${c.changed}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:c.name,scope:c.scope,path:c.path,changed:c.changed,enable_state:c.status,uninstallable:!0}})}catch(c){const l=c instanceof se?c.code:"SKILL_ENABLE_FAILED";h.warn(this.name,`skill_enable failed name=${t} scope=${i}: ${c instanceof Error?c.message:String(c)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:l,error_msg:c instanceof Error?c.message:String(c),result:{conflict_kind:l==="CONFLICT"||l==="NEEDS_FORCE"||l==="BLOCKED"?l.toLowerCase():void 0}})}this.forceRefreshSkills()}handleSkillRefreshLocalAction(e){const n=e.params??{},t=String(n.session_id??"").trim();if(this.forceRefreshSkills(t||void 0)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{session_id:t||void 0}});return}h.warn(this.name,`skill_refresh produced no report session=${t||"-"}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"SKILL_REFRESH_FAILED",error_msg:"skill rescan produced no report (scan error or empty skill set)"})}async handleSkillDisableLocalAction(e){const n=e.params??{},t=String(n.name??"").trim(),s=String(n.session_id??"").trim(),i=String(n.scope??"").trim(),o=String(n.actor_id??"").trim(),r=M(this.config.adapterType,this.config.aibot.clientType),a=this.bindingStore.get(s)?.cwd||this.sessionBindings.get(s)||void 0;try{const d=await Oe({skillsDir:$.skills,mode:r,home:U(),cwd:a},{name:t,scope:i,actorId:o});h.info(this.name,`skill_disable name=${t} scope=${i} actor=${o||"-"} removed=${d.removed}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:d.name,scope:d.scope,path:d.path,removed:d.removed,enable_state:"none",uninstallable:!1}})}catch(d){const c=d instanceof se?d.code:"SKILL_DISABLE_FAILED";h.warn(this.name,`skill_disable failed name=${t} scope=${i}: ${d instanceof Error?d.message:String(d)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:c,error_msg:d instanceof Error?d.message:String(d),result:{conflict_kind:c==="CONFLICT"||c==="BLOCKED"?c.toLowerCase():void 0}})}this.forceRefreshSkills()}computeSkillReport(e){const n=M(this.config.adapterType,this.config.aibot.clientType),t=n==="kiro"?e:e||process.cwd();let s;try{s=De({mode:n,projectDir:t})}catch{return null}if(s.length===0)return null;const i=JSON.stringify(s.map(o=>`${o.source}:${o.name}`));return{skills:ie(s,$.skills),hash:i}}reportSessionSkills(e){const n=this.bindingStore.get(e)?.cwd||this.sessionBindings.get(e)||void 0,t=this.computeSkillReport(n);if(t&&t.hash!==this.lastReportedSkillsHash){this.lastReportedSkillsHash=t.hash;try{this.aibotHandle.sendSkillsUpdate({skills:t.skills,library_skills:this.buildLibrarySkillsReport(n)})}catch{}}}forceRefreshSkills(e){const n=e?.trim(),t=n||this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0}),s=n?this.bindingStore.get(n)?.cwd||this.sessionBindings.get(n)||void 0:t?this.bindingStore.get(t)?.cwd:void 0,i=this.computeSkillReport(s);if(!i)return!1;this.lastReportedSkillsHash=i.hash;try{return this.aibotHandle.sendSkillsUpdate({skills:i.skills,library_skills:this.buildLibrarySkillsReport(s)}),!0}catch{return!1}}buildLibrarySkillsReport(e){const n=M(this.config.adapterType,this.config.aibot.clientType);return Be({skillsDir:$.skills,mode:n,home:U(),cwd:e})}async ensureSlotStarted(e,n=6e4){const t=this.pool.getOrCreateSlot(e);if(!t)throw new Error("Failed to allocate session slot");t.startPromise&&(h.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([t.startPromise,new Promise((s,i)=>setTimeout(()=>i(new Error(`ensureSlotStarted timeout (${n}ms) session=${e}`)),n))]),h.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveOrphanTitle(e){if(e){if(this.reasonixTitleScan){const n=rt(e);if(!n)return;const t=this.reasonixTitleScan.get().filter(s=>s.stamp===n);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,n){const t=String(e??"").trim(),s=String(n??"").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 n=String(e??"").trim();if(!n)return"";const t=P.resolve(n);return process.platform==="win32"?t.toLowerCase():t}ensureImportedAgentSession(e,n){const t=String(e??"").trim();if(!t)return;const s=this.normalizePathForCompare(n);let i="";const o=this.config.adapterType??"acp";if(o==="codex"?i=this.sessionScanCache.get().find(d=>d.threadId===t)?.cwd??"":o==="claude"?i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??"":o==="cursor"?i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??"":o==="acp"&&(i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??""),!i){for(const[,a]of this.bindingStore.entries())if(this.resolveAgentSessionId(a)===t){i=a.cwd??"";break}}if(!i){const a=new Error(`agent session not found: ${t}`);throw a.sessionControlErrorCode=g.invalidAgentSession,a}const r=this.normalizePathForCompare(i);if(r&&s&&r!==s){const a=new Error(`agent session cwd mismatch: expected ${n}, got ${i}`);throw a.sessionControlErrorCode=g.invalidAgentSession,a}}buildOpenedBindingResult(e,n,t="ready"){const s=this.bindingStore.get(e),i=s?String(this.resolveAgentSessionId(s)??"").trim():"",o={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:n,workerStatus:t};return i&&(o.bindingId=i,o.agentSessionId=i),o}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 n=this.config.adapterType??"acp",t=new Map;for(const a of this.pool.getAllSlots())t.set(a.sessionId,a);const s=Array.from(this.bindingStore.entries()),i=new Map;for(const[a,d]of s){const c=this.resolveAgentSessionId(d);if(c){const l=t.get(a),u=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(c,{aibotSessionId:a,workerStatus:u})}}const o=[],r=new Set;if(n==="codex"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.threadId);const c=i.get(d.threadId);d.title&&o.push(` Title: ${d.title}`),o.push(` Agent: ${d.threadId}`),c&&o.push(` AIBot: ${c.aibotSessionId}`),o.push(` CWD: ${d.cwd||"-"}`),o.push(` State: ${c?.workerStatus??(d.archived?"archived":"inactive")}`),o.push(` Created: ${new Date(d.createdAt).toISOString()}`),o.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),o.push("---")}}else if(n==="claude"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=i.get(d.sessionId);d.title&&o.push(` Title: ${d.title}`),o.push(` Agent: ${d.sessionId}`),c&&o.push(` AIBot: ${c.aibotSessionId}`),o.push(` CWD: ${d.cwd||"-"}`),o.push(` State: ${c?.workerStatus??"inactive"}`),o.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),o.push("---")}}else if(n==="acp"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=i.get(d.sessionId);d.title&&o.push(` Title: ${d.title}`),o.push(` Agent: ${d.sessionId}`),c&&o.push(` AIBot: ${c.aibotSessionId}`),o.push(` CWD: ${d.cwd||"-"}`),o.push(` State: ${c?.workerStatus??"inactive"}`),o.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),o.push("---")}}else if(n==="pi"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionPath);const c=i.get(d.sessionPath);d.title&&o.push(` Title: ${d.title}`),o.push(` Agent: ${d.sessionPath}`),c&&o.push(` AIBot: ${c.aibotSessionId}`),o.push(` CWD: ${d.cwd||"-"}`),o.push(` State: ${c?.workerStatus??"inactive"}`),o.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),o.push("---")}}else if(n==="codewhale"||n==="opencode"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=i.get(d.sessionId);d.title&&o.push(` Title: ${d.title}`),o.push(` Agent: ${d.sessionId}`),c&&o.push(` AIBot: ${c.aibotSessionId}`),o.push(` CWD: ${d.cwd||"-"}`),o.push(` State: ${c?.workerStatus??"inactive"}`),o.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),o.push("---")}}for(const[a,d]of s){const c=this.resolveAgentSessionId(d);if(c&&r.has(c))continue;const l=t.get(a),u=l?l.adapter.getStatus().busy?"busy":"ready":"closed",p=this.resolveOrphanTitle(c)??(c?c.slice(0,8)+"\u2026":a.slice(0,8)+"\u2026");o.push(` Title: ${p}`),o.push(` AIBot: ${a}`),c&&o.push(` Agent: ${c}`),o.push(` CWD: ${d.cwd??"-"}`),o.push(` State: ${u}`),o.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),o.push("---")}if(o.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 (${o.filter(a=>a==="---").length}):
14
14
  ${o.join(`
15
15
  `)}`,updated_at:Date.now()})}async handleListSessionsLocalAction(e){const n=this.config.adapterType??"acp",t=new Map;for(const a of this.pool.getAllSlots())t.set(a.sessionId,a);const s=Array.from(this.bindingStore.entries()),i=new Map;for(const[a,d]of s){const c=this.resolveAgentSessionId(d);if(c){const l=t.get(a),u=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(c,{aibotSessionId:a,workerStatus:u,bindingUpdatedAt:d.updatedAt??0})}}const o=[],r=new Set;if(n==="codex"){const a=this.sessionScanCache.get();for(const d of a){r.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),o.push(l)}}else if(n==="claude"){const a=this.sessionScanCache.get();for(const d of a){r.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),o.push(l)}}else if(n==="acp"){const a=this.sessionScanCache.get();for(const d of a){r.add(d.sessionId);const c=i.get(d.sessionId),l=c&&c.bindingUpdatedAt>0?c.bindingUpdatedAt:d.updatedAt,u={agentSessionId:d.sessionId,cwd:d.cwd||null,agentType:d.agentType,workerStatus:c?.workerStatus??"inactive",updatedAt:l};c&&(u.aibotSessionId=c.aibotSessionId),d.title&&(u.title=d.title),d.createdAt&&(u.createdAt=d.createdAt),o.push(u)}}else if(n==="pi"||n==="codewhale"||n==="opencode"){const a=this.sessionScanCache.get();for(const d of a){const c="sessionPath"in d?d.sessionPath:d.sessionId;r.add(c);const l=i.get(c),u={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&&(u.aibotSessionId=l.aibotSessionId),d.title&&(u.title=d.title),d.createdAt&&(u.createdAt=d.createdAt),"archived"in d&&(u.archived=d.archived),o.push(u)}}for(const[a,d]of s){const c=this.resolveAgentSessionId(d);if(c&&r.has(c))continue;const l=t.get(a),u=l?l.adapter.getStatus().busy?"busy":"ready":"closed",p={aibotSessionId:a,cwd:d.cwd??null,workerStatus:u,updatedAt:d.updatedAt,title:this.resolveOrphanTitle(c)??(c?`${c.slice(0,8)}\u2026`:`${a.slice(0,8)}\u2026`)};c&&(p.agentSessionId=c),o.push(p)}o.sort((a,d)=>d.updatedAt-a.updatedAt),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"sessions_listed",sessions:o,total:o.length}})}async handleSyncHistoryLocalAction(e){const n=e.params??{},t=String(n.provider_key??this.config.adapterType??"acp").trim().toLowerCase(),s=String(n.agent_session_id??"").trim(),i=String(n.cwd??"").trim(),o=typeof n.sync_run_id=="string"&&n.sync_run_id?n.sync_run_id:void 0,r=(d,c)=>{h.warn(this.name,`sync_history failed action_id=${e.action_id} provider=${t} code=${d} msg=${c}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:d,error_msg:c})};if(!s){r(Q.agentSessionRequired,"agent_session_id is required for sync_history");return}if(!i){r(Q.cwdRequired,"cwd is required for sync_history");return}const a=Ie(t);if(!a){r(Q.providerUnsupported,`provider ${t} does not support sync_history`);return}try{const d=await a({session_id:String(n.session_id??""),provider_key:t,agent_session_id:s,cwd:i,cursor:typeof n.cursor=="string"&&n.cursor?n.cursor:void 0,limit:typeof n.limit=="number"?n.limit:void 0,sync_run_id:o});h.debug(this.name,`sync_history ok action_id=${e.action_id} provider=${t} agent_session_id=${s} messages=${d.messages.length} has_more=${d.has_more}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"history_synced",messages:d.messages,has_more:d.has_more,next_cursor:d.next_cursor,...o?{sync_run_id:o}:{}}})}catch(d){d instanceof Me?r(d.code,d.message):r(Q.runtimeError,String(d))}}async handleSessionControlCommand(e,n){const t=n.session_id,s=(i,o,r)=>{this.aibotHandle.sendEventResult({event_id:n.event_id,status:i,...o?{msg:o}:{},...r?{code:r}:{},updated_at:Date.now()})};this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:t,received_at:Date.now()});try{switch(e.verb){case _.open:{await N().catch(()=>{});const i=e.args.trim();if(!i){s("failed","Usage: /grix open <working-directory>",g.cwdRequired);return}let o="";try{o=await this.resolveCwdForBinding(i)}catch(a){s("failed",a instanceof Error?a.message:String(a),g.invalidCwd);return}const r=this.bindingStore.get(t);if(r?.cwd){const a=await this.resolveCwdForBinding(r.cwd);if(a!==o){s("failed","session binding cannot be changed to another working directory",g.rebindForbidden);return}this.bindingStore.ensureModeId(t,k.fullAuto),this.sessionBindings.set(t,a),await this.ensureSlotStarted(t),await this.deferredMgr.release(t,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(t,a),s("responded",`Working directory already bound: ${a}`);return}this.bindingStore.set(t,o,{modeId:k.fullAuto}),this.sessionBindings.set(t,o),await this.ensureSlotStarted(t),await this.deferredMgr.release(t,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(t,o),s("responded",`Session bound to ${o}`);return}case _.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 _.status:{const i=this.bindingStore.get(t);if(!i?.cwd){s("failed","session binding was not found",g.bindingMissing);return}const o=this.normalizeClaudeModeId(i.modeId),r=this.getClaudeWorkerStatus(t);s("responded",`Status: worker=${r} mode=${o} cwd=${i.cwd}`);return}case _.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 _.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 _.setMode:{const i=e.args.trim();if(!i){s("failed","Usage: /grix set_mode <mode-id>",H.modeInvalid);return}const o=this.normalizeClaudeModeId(i);if(o!==i.toLowerCase()){s("failed","set mode_id is invalid",H.modeInvalid);return}const r=this.bindingStore.get(t);if(!r?.cwd){s("failed","session binding was not found",g.bindingMissing);return}if(this.normalizeClaudeModeId(r.modeId)===o){s("responded",`Mode unchanged: ${o}`);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,o),await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,r.cwd),s("responded",`Mode set to ${o}`);return}case _.setModel:{const i=e.args.trim();if(!i){s("failed","Usage: /grix set_model <model-id>");return}const o=this.bindingStore.get(t);if(!o?.cwd){s("failed","session binding was not found",g.bindingMissing);return}if((o.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,o.cwd),this.refreshQuotaAfterModelSwitch(t,i),s("responded",`Model set to ${i}`);return}case _.listOptions:{const i=W(),o=this.bindingStore.get(t),r=i.map(d=>d.id).join(", "),a=`${k.fullAuto}, ${k.approval}`;s("responded",`Modes (current: ${this.normalizeClaudeModeId(o?.modeId)}): ${a}
16
- Models (current: ${o?.modelId??"default"}): ${r}`);return}case _.exec:{const[i,...o]=e.args.trim().split(/\s+/);if(!i){s("failed","Usage: /grix exec <command> [args]",g.verbInvalid);return}const a=this.pool.getSlot(t)?.adapter;if(!a?.execCommand){s("failed","Agent does not support command execution",g.verbInvalid);return}const d=a.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 a.execCommand(i,o.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 n=String(e.action_type??"").trim();if(n!==A.sessionControl&&n!==A.setMode&&n!=="set_mode"&&n!==A.setModel&&n!=="set_model")return!1;const t=e.params??{},s=String(t.session_id??"").trim(),i=n===A.setMode?_.setMode:n===A.setModel?_.setModel:String(t.verb??"").trim().toLowerCase();if(h.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:H.localActionRouteMissing,error_msg:"local action session_id is required"}),!0;const o=a=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:a})},r=(a,d)=>{h.warn(this.name,`session_control local_action failed action_id=${e.action_id} session_id=${s} verb=${i} code=${a} msg=${d}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:a,error_msg:d})};try{switch(i){case _.open:{await N().catch(()=>{});const a=String(t.cwd??"").trim(),d=String(t.agent_session_id??"").trim();if(!a)return r(g.cwdRequired,"session control cwd is required"),!0;h.info(this.name,`handleSessionControlLocalAction open cwd=${a} session_id=${s}`);const c=await this.resolveCwdForBinding(a);this.ensureImportedAgentSession(d,c);const l=this.bindingStore.get(s);if(l?.cwd){const u=await this.resolveCwdForBinding(l.cwd);return u!==c?(r(g.rebindForbidden,"session binding cannot be changed to another working directory"),!0):(this.bindingStore.ensureModeId(s,k.fullAuto),this.setResolvedAgentSessionId(s,d),this.sessionBindings.set(s,u),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,u),o({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,u),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0)}return this.bindingStore.set(s,c,{modeId:k.fullAuto}),this.setResolvedAgentSessionId(s,d),this.sessionBindings.set(s,c),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,c),o({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,c),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0}case _.status:case _.where:{const a=this.bindingStore.get(s);return a?.cwd?(o({outcome:i,binding:{cwd:a.cwd,mode_id:this.normalizeClaudeModeId(a.modeId),worker_status:this.getClaudeWorkerStatus(s)}}),!0):(r(g.bindingMissing,"session binding was not found"),!0)}case _.stop:{const a=this.bindingStore.get(s);return a?.cwd?(await this.pool.removeSlot(s),o({outcome:"stopped",binding:{cwd:a.cwd,mode_id:this.normalizeClaudeModeId(a.modeId),worker_status:"stopped"}}),!0):(r(g.bindingMissing,"session binding was not found"),!0)}case _.restart:{const a=this.bindingStore.get(s);return a?.cwd?(await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,a.cwd),o({outcome:"restarted",binding:{cwd:a.cwd,mode_id:this.normalizeClaudeModeId(a.modeId)}}),!0):(r(g.bindingMissing,"session binding was not found"),!0)}case _.setMode:{const a=String(t.mode_id??t.modeId??"").trim();if(!a)return r(H.modeInvalid,"set mode_id is invalid"),!0;const d=this.normalizeClaudeModeId(a);if(d!==a.toLowerCase())return r(H.modeInvalid,"set mode_id is invalid"),!0;const c=this.bindingStore.get(s);if(!c?.cwd)return r(g.bindingMissing,"session binding was not found"),!0;if(this.normalizeClaudeModeId(c.modeId)!==d){if(this.getClaudeWorkerStatus(s)==="busy")return r(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 o({outcome:"mode_set",mode_id:d,binding:{cwd:c.cwd,mode_id:d}}),!0}case _.setModel:{const a=String(t.model_id??t.modelId??"").trim();if(!a)return r("set_model_invalid","model_id is required"),!0;const d=this.bindingStore.get(s);if(!d?.cwd)return r(g.bindingMissing,"session binding was not found"),!0;if((d.modelId??"")!==a){if(this.getClaudeWorkerStatus(s)==="busy")return r(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,a),this.globalConfigStore?.set(this.name,{modelId:a}),await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,d.cwd),this.refreshQuotaAfterModelSwitch(s,a)}return o({outcome:"model_set",model_id:a,binding:{cwd:d.cwd,model_id:a}}),!0}case _.listOptions:{const a=W(),d=this.pool.getSlot(s);return o({modes:[k.fullAuto,k.approval],currentModeId:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId),models:a.map(c=>({modelId:c.id,name:c.displayName})),currentModelId:this.bindingStore.get(s)?.modelId??"",available_models:a.map(c=>({id:c.id,displayName:c.displayName})),agent_commands:d?.adapter?.getSupportedCommands?.()??[]}),!0}case _.exec:{const[a,...d]=String(t.args??"").trim().split(/\s+/);if(!a)return r(g.verbInvalid,"Usage: exec <command> [args]"),!0;await this.ensureSlotStarted(s);const l=this.pool.getSlot(s)?.adapter;if(!l?.execCommand)return r(g.verbInvalid,"Agent does not support command execution"),!0;const u=l.getSupportedCommands?.()??[];if(!u.some(p=>p.name===a))return r(g.verbInvalid,`Unknown command: ${a}. Supported: ${u.map(p=>p.name).join(", ")}`),!0;try{const p=await l.execCommand(a,d.join(" "),s);p.status==="ok"?o({outcome:"exec",command:a,message:p.message,data:p.data}):r(g.runtimeError,p.message??`${a} failed`)}catch(p){r(g.runtimeError,`exec error: ${p instanceof Error?p.message:p}`)}return!0}default:return r(g.verbInvalid,`session control verb ${i} is not supported`),!0}}catch(a){const d=a instanceof Error&&a.cwdErrorCode?a.cwdErrorCode:a instanceof Error&&a.sessionControlErrorCode?a.sessionControlErrorCode:g.runtimeError;return h.error(this.name,`handleSessionControlLocalAction error verb=${i} session_id=${s}: ${a instanceof Error?a.message:a}`),r(d,a instanceof Error?a.message:String(a)),!0}}async handleEventCancel(e){const{event_id:n,session_id:t}=e;if(h.info(this.name,`handleEventCancel start event_id=${n} session_id=${t}`),this.pool.cancelEvent(n,t)){if(!(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(n)??!1)){this.sendEventResultWithCleanup(n,"canceled","canceled"),this.aibotHandle.sendEventCancelResult({event_id:n,accepted:!0,final_state:"canceled"});return}await this.waitForEventDone(n,t,15e3),this.aibotHandle.sendEventCancelResult({event_id:n,accepted:!0,final_state:"canceled"}),this.pushQueueSnapshotForSession(t);return}this.aibotHandle.sendEventCancelResult({event_id:n,accepted:!1,reason:"event not found or not cancelable"})}waitForEventDone(e,n,t){return new Promise(s=>{const i=this.pool.getSlot(n);if(!i?.adapter){s();return}const o=setTimeout(()=>{i.adapter.removeListener("eventDone",r),s()},t),r=a=>{a===e&&(clearTimeout(o),i.adapter.removeListener("eventDone",r),s())};i.adapter.on("eventDone",r)})}handleAibotStop(e){const n=e.event_id?.trim()??"",t=e.scope?.trim()??"";h.info(this.name,`[stop-trace] handleAibotStop begin session=${e.session_id} event=${n||"-"} scope=${t||"event"} stop_id=${e.stop_id||"-"} adapterType=${this.config.adapterType??"acp"}`);const s=this.pool.getSlot(e.session_id),i=s?.adapter?.getStatus().busy??!1;let o=!1,r=[];if(s?.adapter)try{r=[...new Set(s.adapter.getActiveEventIds().map(m=>m.trim()).filter(Boolean))]}catch(m){o=!0,h.warn(this.name,`[stop-trace] handleAibotStop active event probe failed session=${e.session_id}: ${m}`)}const a=t==="session";let d=a?"":n;const c=m=>({stop_id:e.stop_id,...m?{event_id:m}:{},...e.terminal_commit_token?{terminal_commit_token:e.terminal_commit_token}:{},session_id:e.session_id,...t?{scope:t}:{}}),l=m=>{!m||!e.terminal_commit_token?.trim()||this.sendEventResultWithCleanup(m,"canceled","stopped by owner","event_stopped")};if(a)if(!o&&r.length===1)[d]=r;else if(!o&&r.length===0&&!i){this.aibotHandle.sendEventStopAck({...c(""),accepted:!0,updated_at:Date.now()}),this.aibotHandle.sendEventStopResult({...c(""),status:"already_finished",updated_at:Date.now()}),h.info(this.name,`[stop-trace] handleAibotStop session idle -> stopResult(already_finished) session=${e.session_id} stop_id=${e.stop_id||"-"}`);return}else{const m=o?"session_stop_target_unavailable":r.length>1?"session_stop_target_ambiguous":"session_stop_target_unresolved",v=o?"failed to inspect active events for session stop":r.length>1?"multiple active events prevent a safe session stop":"adapter is busy but no active event can be identified";this.aibotHandle.sendEventStopAck({...c(""),accepted:!1,updated_at:Date.now()}),this.aibotHandle.sendEventStopResult({...c(""),status:"failed",code:m,msg:v,updated_at:Date.now()}),h.warn(this.name,`[stop-trace] handleAibotStop session target unsafe -> stopResult(failed) session=${e.session_id} activeIds=[${r.join(",")}] busy=${i} code=${m}`);return}if(this.aibotHandle.sendEventStopAck({...c(d),accepted:!0,updated_at:Date.now()}),this.pool.removeQueuedEvent(e.session_id,d)){h.info(this.name,`[stop-trace] handleAibotStop removed queued(not-running) event -> stopResult(stopped) session=${e.session_id} event=${d} stop_id=${e.stop_id||"-"}`),e.terminal_commit_token?.trim()?l(d):this.discardEventTrackingState(d),this.pushQueueSnapshotForSession(e.session_id),this.aibotHandle.sendEventStopResult({...c(d),status:"stopped",updated_at:Date.now()});return}const u=(this.config.adapterType??"acp")==="acp",p=r.length>0?r.includes(d):i,f=(u||(this.config.adapterType??"acp")==="codex"||(this.config.adapterType??"acp")==="claude")&&p;if(h.info(this.name,`[stop-trace] handleAibotStop decision session=${e.session_id} event=${d} scope=${t||"event"} slotExists=${!!s?.adapter} busy=${i} activeIds=[${r.join(",")}] stoppingActiveEvent=${p} killOnStop=${f}`),p&&this.sendCtrl.markEventStopped(d),s?.adapter&&i){const m=f?this.pool.drainQueuedForSession(e.session_id):[];let v=!1,b=null;const S=C=>{v||(v=!0,b&&(clearTimeout(b),b=null),s.adapter.removeListener("eventDone",w),h.info(this.name,`[stop-trace] handleAibotStop ${C} -> stopResult(stopped) session=${e.session_id} event=${d} stop_id=${e.stop_id||"-"} killOnStop=${f}`),l(d),this.aibotHandle.sendEventStopResult({...c(d),status:"stopped",updated_at:Date.now()}),f&&this.killAndResumeStopSlot(e.session_id,m))},w=C=>{C===d&&S("eventDone")};s.adapter.on("eventDone",w),b=setTimeout(()=>S("timeout"),li),this.pool.deliverStopEvent(d,e.session_id)}else h.info(this.name,`[stop-trace] handleAibotStop slot-not-busy -> immediate stopResult(stopped) session=${e.session_id} event=${d} slotExists=${!!s?.adapter}`),this.pool.deliverStopEvent(d,e.session_id),l(d),this.aibotHandle.sendEventStopResult({...c(d),status:"stopped",updated_at:Date.now()});(this.config.adapterType??"acp")==="pi"&&this.aibotHandle.sendText({event_id:d,session_id:e.session_id,content:"/stop",msg_type:0})}async killAndResumeStopSlot(e,n){if(!this.stopped){h.info(this.name,`[stop-trace] killAndResumeStopSlot begin session=${e} siblings=${n.length} -> removeSlot (kill process group)`);try{await this.pool.removeSlot(e),h.info(this.name,`[stop-trace] killAndResumeStopSlot removeSlot done session=${e} (process killed) -> redeliver ${n.length} sibling(s)`)}catch(t){h.warn(this.name,`[acp-stop] removeSlot failed session=${e}: ${t instanceof Error?t.message:String(t)}`)}if(!this.stopped)for(const t of n){if(this.stopped)break;try{await this.pool.deliverInboundEvent(t)}catch(s){h.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 n=e.event_id,t=e.session_id;if(t&&this.pool.cancelEvent(n,t)){(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(n)??!1)||this.sendEventResultWithCleanup(n,"canceled","revoked");return}if(this.deferredMgr.removeEvent(n)){this.aibotHandle.sendEventResult({event_id:n,status:"canceled",msg:"revoked",updated_at:Date.now()});return}this.pool.deliverStopEvent(n,t||void 0)}async handleConfigureGatewayProvider(e){const n=e.params??{},t=String(n.api_key??"").trim(),s=String(n.anthropic_base_url??"").trim(),i=String(n.openai_base_url??"").trim(),o=typeof n.provider_id=="string"&&n.provider_id.trim().toLowerCase()||void 0,r=typeof n.quota_base_url=="string"&&n.quota_base_url.trim()||void 0,a=typeof n.model=="string"&&n.model.trim()||void 0;let d=!1,c;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 l=this.config.adapterType??"acp",u=l==="claude"||l==="codex",p=u&&Ye(n.direct_relay,l),f=u&&n.direct_relay!==void 0&&!p;try{if(f){if(!this.relayStateApplyPorts){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"unsupported",error_code:"UNSUPPORTED_CLIENT_TYPE",error_msg:"relay state applier is not configured"});return}const m=await this.relayStateApplyPorts.applyEnable({apiKey:t,...s?{anthropicBaseUrl:s}:{},...i?{openaiBaseUrl:i}:{},...a?{model:a}:{},directRelay:n.direct_relay},a);m&&(c=m,d=m.busy||m.pending!==void 0)}else if(u){const m=l==="claude"?s:i;if(!m){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_BASE_URL",error_msg:`${l==="claude"?"anthropic_base_url":"openai_base_url"} is required`});return}const v=ne();if(!v){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"PROXY_UNAVAILABLE",error_msg:"MITM proxy manager not initialized"});return}const b=We(l),S=Ke(l,m,t,{model:a});v.setRoute(S);for(const w of b)v.setHostDefaultRoute(w,S.routeKey);await v.setAgentRelayEnabled(this.name,!0,{relayHosts:b}),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 "${l}" does not support Grix relay provider config`});return}const m=this.config.aibot.clientType,v=oe(m),b=v?s:i;if(!b){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_BASE_URL",error_msg:`${v?"anthropic_base_url":"openai_base_url"} is required`});return}if(v&&!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_MODEL",error_msg:'model is required for client type "kiro"'});return}await this.providerConfigHandler({...o?{provider_id:o}:{},base_url:b||void 0,...r?{quota_base_url:r}:{},api_key:t,model:a})}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0,restart_deferred:d,...c?{restarted:c.restarted,busy:c.busy,...c.pending?{pending:c.pending}:{}}:{}}})}catch(m){h.error(this.name,`handleConfigureGatewayProvider failed: ${m}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"CONFIGURE_FAILED",error_msg:m instanceof Error?m.message:String(m)})}}getAuditLocalActionHandler(){if(!this.auditLocalActionHandler){const e=new Le({rootDir:xe()});this.auditLocalActionHandler=new $e(new Te(e))}return this.auditLocalActionHandler}async handleAuditLocalAction(e){const n=await this.getAuditLocalActionHandler().handle(e.action_type,e.params);if(n.status==="ok"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:n.result});return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:n.errorCode,error_msg:n.errorMsg})}async handleAibotLocalAction(e){const n=e.action_type??"",t=String((e.params??{}).session_id??""),s=String((e.params??{}).verb??"").trim().toLowerCase();if(h.debug(this.name,`local_action received action_type=${n} verb=${s||"-"} action_id=${e.action_id} session_id=${t}`),Pe(n)){await this.handleAuditLocalAction(e);return}const i=(this.config.adapterType??"acp")==="claude";if(n===A.sessionControl&&s===_.exec&&await this.handleSessionControlLocalAction(e))return;if(n===A.sessionControl&&s===_.listSessions){await this.handleListSessionsLocalAction(e);return}if(n===A.sessionControl&&s===_.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(n==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(n==="skill_enable"){await this.handleSkillEnableLocalAction(e);return}if(n==="skill_disable"){await this.handleSkillDisableLocalAction(e);return}if(n==="skill_refresh"){this.handleSkillRefreshLocalAction(e);return}const o=(this.config.adapterType??"acp")==="opencode";if((i&&(n===A.interactionReply||n==="exec_approve"||n==="exec_reject")||o&&n===A.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||i&&await this.handleSessionControlLocalAction(e))return;if(n===A.sessionControl){const l=this.config.adapterType??"acp",u=l==="codex",p=l==="pi",f=String((e.params??{}).verb??"").trim().toLowerCase();if(u&&f===_.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(l==="cursor"&&f===_.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(u&&f==="restart"){const w=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:w,workerStatus:"ready"}}});return}if(p&&f===_.open){try{const S=e.params??{},w=String(S.cwd??"").trim();if(!w){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const C=await this.resolveCwdForBinding(w),E=String(S.agent_session_id??"").trim();this.ensureImportedAgentSession(E,C),this.bindingStore.set(t,C),this.setResolvedAgentSessionId(t,E),this.sessionBindings.set(t,C),await this.ensureSlotStarted(t).catch(q=>{h.warn("bridge",`pi ensureSlotStarted on local-action bind failed (non-fatal): ${q instanceof Error?q.message:String(q)}`)}),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:C}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,C)}})}catch(S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:S?.sessionControlErrorCode??S?.cwdErrorCode??g.invalidCwd,error_msg:S instanceof Error?S.message:String(S)})}return}if(p&&f===_.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((l==="openhuman"||l==="opencode")&&f===_.open){try{const S=e.params??{},w=String(S.cwd??"").trim();if(!w){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const C=await this.resolveCwdForBinding(w),E=String(S.agent_session_id??"").trim();this.ensureImportedAgentSession(E,C),this.bindingStore.set(t,C),this.setResolvedAgentSessionId(t,E),this.sessionBindings.set(t,C),this.syncOpenCodeBinding(t,C),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,C)}})}catch(S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:S?.sessionControlErrorCode??S?.cwdErrorCode??g.invalidCwd,error_msg:S instanceof Error?S.message:String(S)})}return}if(l==="codewhale"&&f===_.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(l==="acp"&&f===_.stop){const w=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:w,workerStatus:"stopped"}}});return}try{if(f===_.open){const S=e.params??{},w=String(S.cwd??"").trim();if(!w){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const C=String(S.agent_session_id??"").trim();if(C){const E=await this.resolveCwdForBinding(w);this.ensureImportedAgentSession(C,E)}}await this.handleSessionControlLocalActionForPool(e)}catch(S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:S?.sessionControlErrorCode??S?.cwdErrorCode??g.runtimeError,error_msg:S instanceof Error?S.message:String(S)});return}if(f===_.open){const S=e.params??{},w=await this.resolveCwdForBinding(String(S.cwd??"").trim());this.setResolvedAgentSessionId(t,String(S.agent_session_id??"").trim()),l==="agy"&&(this.bindingStore.set(t,w),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)}}),(this.config.adapterType??"acp")==="agy"&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:w,meta:this.buildAgyToolbarMeta(t)})}else Tt(e,this.sessionControlCtx(t),this.sessionControlSenders());return}if(n==="file_list"){const l=Date.now(),u=t?this.bindingStore.get(t)?.cwd:void 0,p=e.params??{},f=String(p.parent_id??"").trim(),m=Array.isArray(p.allowed_extensions)?p.allowed_extensions.filter(w=>typeof w=="string").map(w=>w.trim()).filter(w=>w.length>0):[];h.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${t} parent_id=${f||"<root>"} show_hidden=${!!p.show_hidden} ext_count=${m.length} bound_cwd=${u??"<none>"}`);const v=await Mt({parent_id:f||null,session_id:t,show_hidden:!!p.show_hidden,allowed_extensions:m},{resolveCwd:()=>u??this.config.agent.cwd??process.cwd(),fallbackDir:le()}),b=Date.now()-l,S=v.result?.files?.length??0;h.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${v.status} elapsed=${b}ms count=${S} current_path=${v.result?.current_path??""} error_code=${v.error_code??""} error_msg=${v.error_msg??""}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:v.status,...v.result?{result:{...v.result,machine_name:Qt()}}:{},...v.error_code?{error_code:v.error_code}:{},...v.error_msg?{error_msg:v.error_msg}:{}});return}if(n==="create_folder"){const l=t?this.bindingStore.get(t)?.cwd:void 0,u=String((e.params??{}).parent_id??"").trim(),p=String((e.params??{}).name??"").trim(),f=await It({parent_id:u||null,name:p,session_id:t},{resolveCwd:()=>l??this.config.agent.cwd??process.cwd(),fallbackDir:le()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:f.status,...f.result?{result:f.result}:{},...f.error_code?{error_code:f.error_code}:{},...f.error_msg?{error_msg:f.error_msg}:{}});return}if(n===A.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,t);return}if(n===A.getSessionUsage){await this.handleGetSessionUsage(e,t);return}if(n===A.getRateLimits){await this.handleGetRateLimits(e,t);return}const r=(this.config.adapterType??"acp")==="acp";if((i||r)&&n===A.threadCompact){await this.handleThreadCompact(e,t);return}if(n==="connector_rollback"){await this.handleConnectorRollback(e);return}if(n==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(n===A.getAgentGlobalConfig){const l=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...l?{config:l}:{config:null}}});return}if(n==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}if(n==="apply_relay_state"){await this.handleApplyRelayState(e);return}const a=this.config.adapterType??"acp",d=(a==="codex"||a==="cursor"||a==="pi"||a==="openhuman"||a==="opencode"||a==="acp")&&!!t&&!!this.bindingStore.get(t)?.cwd,c=await this.pool.deliverLocalAction(e,{autoCreateSlot:d});if(c.handled){if(c.kind==="set_mode"){const l=String((e.params??{}).mode_id??"");l&&(a==="cursor"?this.bindingStore.setCursorModeId(t,l):a==="claude"?this.bindingStore.setModeId(t,l):B.has(a)?a==="codex"&&this.globalConfigStore?.set(this.name,{codexModeId:l}):this.globalConfigStore?.set(this.name,{acpInitialMode:l}))}else if(c.kind==="set_model"){const l=String((e.params??{}).model_id??"");if(l){a==="cursor"?(this.bindingStore.setModelId(t,l),this.globalConfigStore?.set(this.name,{modelId:l})):a==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:l}):B.has(a)||this.globalConfigStore?.set(this.name,{modelId:l});const u=String((e.params??{}).provider??(e.params??{}).model_provider??"").trim()||void 0;this.refreshQuotaAfterModelSwitch(t,l,u)}}else if(c.kind==="set_reasoning_effort"){const l=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");l&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:l})}else if(c.kind==="set_sandbox_mode"){const l=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(l){const u=l==="default"?void 0:l;this.globalConfigStore?.set(this.name,{codexSandboxMode:u})}}else if(c.kind==="set_service_tier"){const l=String((e.params??{}).service_tier??(e.params??{}).serviceTier??(e.params??{}).value??"").trim();if(l){const u=l.toLowerCase()==="default"?void 0:l;this.globalConfigStore?.set(this.name,{codexServiceTier:u})}}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"&&(n==="set_mode"||n==="set_model")){const l=this.sessionControlSenders(),u=this.pool.getSlot(t)?.adapter,p={bindingStore:this.bindingStore,acpAdapter:u instanceof R?u:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:h};if(n==="set_mode"){const f=String((e.params??{}).mode_id??""),m=await ce(p,t,f);if(m.status==="failed")l.sendLocalActionResult(e.action_id,"failed",void 0,m.errorCode,m.errorMsg);else{const v=u instanceof R?u.buildToolbarContext(m.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,b=v?{...v,...m.result}:m.result;l.sendLocalActionResult(e.action_id,"ok",b)}}else{const f=String((e.params??{}).model_id??""),m=await de(p,t,f);if(m.status==="failed")l.sendLocalActionResult(e.action_id,"failed",void 0,m.errorCode,m.errorMsg);else{const v=u instanceof R?u.buildToolbarContext(m.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,b=v?{...v,...m.result}:m.result;l.sendLocalActionResult(e.action_id,"ok",b),m.result?.outcome==="model_set"&&this.refreshQuotaAfterModelSwitch(t,f)}}return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:`action type ${n} is not supported`})}async handleGetSessionUsage(e,n){if(!n){h.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(n),i=s?.cwd??this.config.agent.cwd??process.cwd();h.info(this.name,`[usage] get_session_usage action_id=${e.action_id} session_id=${n} adapterType=${t} hasBinding=${!!s} cwd=${i}`);let o=null,r,a;switch(t){case"claude":{if(r=s?.claudeSessionId,!r){h.warn(this.name,`[usage] no claude binding for session_id=${n}, 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}h.info(this.name,`[usage] parsing claude usage: claudeSessionId=${r} cwd=${i}`),o=await He(r,i),a="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(r=s?.acpSessionId,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No ACP session binding found"});return}o=await Fe(r,i,this.config.aibot.clientType),a=t,(!a||a==="acp")&&(a="acp");break}case"codex":{if(r=s?.codexThreadId,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Codex thread binding found"});return}o=await tt(r),a="codex";break}case"pi":{if(r=s?.piSessionPath,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Pi session path binding found"});return}o=await pt(r),a="pi";break}case"cursor":{const c=this.pool.getSlot(n)?.adapter;if(!(c instanceof D)){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(n);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 u={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:n,adapterType:"cursor",models:[{model:this.bindingStore.get(n)?.modelId??"auto",turns:l.turns,total:u}],total:u,turns:l.turns,sampledAt:l.sampledAt}});return}case"codewhale":{const c=this.pool.getSlot(n)?.adapter;if(!(c instanceof X)){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 u={inputTokens:l.total.input,outputTokens:l.total.output,cacheReadInputTokens:0,cacheCreationInputTokens:0};this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:n,adapterType:"codewhale",models:[{model:this.bindingStore.get(n)?.modelId??"codewhale",turns:l.turns,total:u}],total:u,turns:l.turns,sampledAt:l.sampledAt}});return}}if(!o){h.info(this.name,`[usage] no usage data found: session_id=${n} adapterSessionId=${r} adapterType=${a}`);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}h.info(this.name,`[usage] result ok: session_id=${n} adapterSessionId=${r} turns=${o.turns} models=${o.models.length}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:r,adapterType:a,models:o.models,total:o.total,turns:o.turns,sampledAt:new Date().toISOString()}})}async handleThreadCompact(e,n){if(!n){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(n)?.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(n);const i=this.pool.getSlot(n)?.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}h.info(this.name,`thread_compact session_id=${n} action_id=${e.action_id}`);const o=await i.execCommand("compact","",n);o.status==="ok"?this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"compacted",message:o.message,data:o.data}}):this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:o.message??"compact failed"})}catch(s){h.warn(this.name,`thread_compact error session_id=${n}: ${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,n){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 o=await z();this.cachedProviderQuota=o,this.cachedProviderQuotaSampledAtMs=Date.now(),h.info(this.name,`[rate-limits] kiro quota queried: success=${o.success}`+(o.balance?` balance=${o.balance.remaining} ${o.balance.unit}`:"")+(o.error?` error=${o.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:o}})}catch(o){h.warn(this.name,`[rate-limits] kiro quota query failed: ${o instanceof Error?o.message:String(o)}`),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(u=>u.state==="ready"&&u.adapter);if(l&&(h.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?h.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}`):h.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 r=this.pool.getAllSlots().find(l=>l.state==="ready"&&l.adapter);if(r&&(h.info(this.name,`[rate-limits] codex reuse existing slot: session=${r.sessionId}`),(await r.adapter.handleLocalAction?.(e))?.handled))return;const a=this.resolveRateLimitWakeSessionId(n,t);if(a){const l=await this.wakeRateLimitSlot(a,t);if(l?.adapter&&(await l.adapter.handleLocalAction?.(e))?.handled)return}const d=await s,c=!!d;h.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;h.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 o=this.pool.getAllSlots().find(c=>c.state==="ready"&&c.adapter instanceof L)??null;if(!o){const c=this.resolveRateLimitWakeSessionId(n,t);c&&(o=await this.wakeRateLimitSlot(c,t))}h.info(this.name,`[rate-limits] handleGetRateLimits: session_id=${n} adapterType=claude hasSlot=${!!o} hasAdapter=${!!o?.adapter}`);const r=o?.adapter,a=r instanceof L?r.getSessionState():null,d=await s;if(a){(a.rateLimits?.fiveHour||a.rateLimits?.sevenDay||a.contextWindow?.usedPercentage!=null)&&(this.cachedClaudeRateLimitState=a);const c=this.getFreshClaudeRateLimitState(),l=c?.rateLimits&&!a.rateLimits?{...a,rateLimits:c.rateLimits}:a,u=l.rateLimits;h.info(this.name,`[rate-limits] claude global state: sampledAt=${l.sampledAt} hasRateLimits=${!!u}`+(u?` fiveHour=${u.fiveHour?.usedPercentage??"n/a"}% resetsAt=${u.fiveHour?.resetsAt??"n/a"} sevenDay=${u.sevenDay?.usedPercentage??"n/a"}% resetsAt=${u.sevenDay?.resetsAt??"n/a"}`:"")+(c?.rateLimits&&!a.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 h.info(this.name,`[rate-limits] claude no global state: hasAdapter=${!!r} adapterType=${r?.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=(n?this.pool.getSlot(n):null)?.adapter;if(i instanceof D){await i.refreshAccountRateLimits({force:!0});const r=i.getRateLimitsSnapshot(n);h.info(this.name,`[rate-limits] cursor: available=${r.available} monthly=${r.rateLimits?.fiveHour?.usedPercentage??"n/a"}% api=${r.rateLimits?.sevenDay?.usedPercentage??"n/a"}%`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:r});return}const o=await ke();h.info(this.name,`[rate-limits] cursor(no-slot): available=${o.available} monthly=${o.rateLimits?.fiveHour?.usedPercentage??"n/a"}% api=${o.rateLimits?.sevenDay?.usedPercentage??"n/a"}%`+(o.error?` error=${o.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"cursor",available:o.available,cached:!1,sampledAt:Number.isFinite(Date.parse(o.sampledAt))?Date.parse(o.sampledAt):Date.now(),rateLimits:o.rateLimits,contextWindow:null,tokenUsage:null,...o.displayMessage?{displayMessage:o.displayMessage}:{},...o.error?{error:o.error}:{}}});return}default:{const s=this.sessionProviderHints.get(n),i=this.sessionBindings.get(n)||this.bindingStore.get(n)?.cwd;if(s&&i&&!s.disabled){await this.refreshProviderQuotaForSession(n,i,!0);const a=this.sessionProviderQuotas.get(n),d=a?.quota??null;if(!d){h.info(this.name,`[rate-limits] no session provider quota available for adapterType=${t} session=${n}`),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}h.info(this.name,`[rate-limits] session provider quota queried: provider=${d.provider} success=${d.success}`+(d.tiers.length>0?` tiers=${d.tiers.map(c=>`${c.name}=${c.usedPercent}%`).join(",")}`:"")+(d.error?` error=${d.error}`:"")+` session=${n}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:!1,sampledAt:a?.sampledAt??null,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null,providerQuota:d}});return}const o=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&!!this.cachedProviderQuota,r=await this.maybeQueryProviderQuota();if(!r){h.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}h.info(this.name,`[rate-limits] provider quota ${o?"cached":"queried"}: provider=${r.provider} success=${r.success}`+(r.tiers.length>0?` tiers=${r.tiers.map(a=>`${a.name}=${a.usedPercent}%`).join(",")}`:"")+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.error?` error=${r.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:o,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null,providerQuota:r}});return}}}resolveRateLimitWakeSessionId(e,n){const t=String(e??"").trim(),s=this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0});return s?t&&t===s?t:n==="codex"||n==="claude"?(t&&t!==s&&h.info(this.name,`[rate-limits] ${n} remap wake session: requested=${t} use_recent=${s}`),s):t&&t!==s?(h.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${n} reason=not_recent_session recent=${s}`),null):t||null:(h.info(this.name,`[rate-limits] skip wake slot: adapterType=${n} reason=no_recent_binding`),null)}async wakeRateLimitSlot(e,n){const t=String(e??"").trim();if(!t)return null;if(!this.bindingStore.get(t)?.cwd)return h.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${n} reason=binding_cwd_missing`),null;try{const i=this.pool.getOrCreateSlot(t);if(!i)return h.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${n} reason=slot_unavailable`),null;if(i.startPromise){const o=n==="claude"?6e4:2e4;await Promise.race([i.startPromise,new Promise((r,a)=>setTimeout(()=>a(new Error(`wake rate-limits slot timeout (${o}ms)`)),o))])}return h.info(this.name,`[rate-limits] wake slot success: session=${t} adapterType=${n}`),this.pool.getSlot(t)??i}catch(i){return h.warn(this.name,`[rate-limits] wake slot failed: session=${t} adapterType=${n} err=${i instanceof Error?i.message:String(i)}`),null}}sessionControlCtx(e){const n=this.pool.getSlot(e),t=n?.adapter instanceof R?n.adapter:null,s=(this.config.adapterType??"acp")==="acp",i={bindingStore:this.bindingStore,acpAdapter:t,globalConfigStore:this.globalConfigStore,agentName:this.name,log:h};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(t)return t.getSessionBindings();const o=this.sessionBindings;if(e&&!o.has(e)){const r=this.bindingStore.get(e);r?.cwd&&o.set(e,r.cwd)}return o},getStatus:()=>this.getStatus(),isAcpAlive:!!t?.isAlive(),getAcpSessionOptions:()=>t?.acpSessionOptions??null,setMode:o=>t?t.setMode(o):Promise.resolve(!1),setModel:o=>t?t.setModel(o):Promise.resolve(!1),acpSetMode:s?(o,r)=>ce(i,o,r):void 0,acpSetModel:s?(o,r)=>de(i,o,r):void 0,getPendingApproval:o=>{const r=t?.pendingApprovalEntries.get(o);return r?{requestId:r}:void 0},deletePendingApproval:o=>t?.pendingApprovalEntries.delete(o)??!1,respondPermission:(o,r)=>(t&&t.respondToPermission(o,r),Promise.resolve()),onSessionBound:(o,r)=>{this.bindingStore.set(o,r)},onSessionUnbound:o=>{const a=this.bindingStore.get(o)?.cwd??"";this.bindingStore.delete(o),this.sessionBindings.delete(o),this.sessionProviderHints.delete(o),this.sessionProviderQuotas.delete(o),this.sessionProviderMeta.delete(o),this.claudeWorkerStatus.delete(o),this.deferredMgr.clearSession(o),this.aibotHandle.clearBindingCardMetaCache?.(o);for(const d of this.pool.drainQueuedForSession(o))this.discardEventTrackingState(d.event_id);a&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"stopped",cwd:a})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&n?.adapter instanceof ee?(n.adapter.cancelCurrentRun(),Promise.resolve()):n?.adapter?.cancel("")??Promise.resolve(),onModeSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModeId:o}):B.has(r)||this.globalConfigStore?.set(this.name,{acpInitialMode:o})},onModelSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:o}):B.has(r)||this.globalConfigStore?.set(this.name,{modelId:o}),this.refreshQuotaAfterModelSwitch(e,o)}}}sessionControlSenders(){return{sendEventAck:(e,n)=>this.aibotHandle.sendEventAck({event_id:e,session_id:n,received_at:Date.now()}),sendEventResult:(e,n,t)=>this.aibotHandle.sendEventResult({event_id:e,status:n,...t?.msg?{msg:t.msg}:{},...t?.code?{code:t.code}:{},updated_at:Date.now()}),sendLocalActionResult:(e,n,t,s,i)=>this.aibotHandle.sendLocalActionResult({action_id:e,status:n,...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,n){this.sendCtrl.finalizeThinking(e,n)}logInboundConversation(e){const n=String(e.session_id??"").trim();n&&this.conversationLog?.logInbound(n,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}resolveAuditProvider(){const e=this.config.adapterType??"acp";return e==="claude"||e==="codex"||e==="cursor"||e==="opencode"||e==="pi"||e==="codewhale"?e:"acp"}sendAuditConfigurationError(e,n){const t=n instanceof Error?n.message:String(n),s=n instanceof ni||n instanceof si,i=s?n.code:"audit_config_conflict";if(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:i,msg:t,updated_at:Date.now()}),s)try{this.aibotHandle.sendAuditState(j({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:i,errorMessage:t},Date.now()))}catch{}}markAuditAdapterClosed(e,n){const s=this.pool.getSlot(n)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,s)}prepareAuditedInboundEvent(e,n,t){const s=this.buildInboundEvent(e,n),i=this.bindingStore.get(e.session_id),o=i?this.resolveAgentSessionId(i):void 0,r=Number(e.created_at),a=Number.isFinite(r)&&r>0?new Date(r).toISOString():void 0,d=this.auditController.startTurn({session:t,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...a===void 0?{}:{startedAt:a},boundary:{adapterType:this.config.adapterType??"acp",...o?{providerSessionId:o}:{}}});return d&&(s.audit={enabled:!0,auditId:d.auditId,turnId:d.turnId,...t?{profile:t.options.profile,capture:{...t.options.capture}}:{},rawProviderBody:t?.options.capture.rawProviderBody===!0}),s}buildInboundEvent(e,n){const t=Ut(this.sendCtrl.getGlobalRuntimeConfig(),n),s=ri(e.extra);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:s===void 0?void 0:JSON.stringify(s),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 n=e.filter(t=>!xt(String(t?.content??"")));if(n.length!==0)return JSON.stringify(n)}isStaleEvent(e){const n=Number(e.created_at);return!Number.isFinite(n)||n<=0?!1:Date.now()-n>ai}async handleConnectorRollback(e){const n=String((e.params??{}).target_version??"").trim(),t=String((e.params??{}).reason??"server_initiated");if(!n){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}h.info(this.name,`connector_rollback: target=${n} reason=${t}`);try{const{npmInstall:s,writePending:i,removePending:o,upgradeLog:r}=await import("../core/upgrade/npm-upgrader.js"),{resolveClientVersion:a}=await import("../core/util/client-version.js"),d=a();r(`server rollback: ${d} -> ${n} reason=${t}`),i(d,n),await s("grix-connector",n),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{rolled_back_to:n}}),process.kill(process.pid,"SIGTERM")}catch(s){try{const{removePending:o}=await import("../core/upgrade/npm-upgrader.js");o()}catch{}const i=s instanceof Error?s.message:String(s);h.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}setRelayStateApplyPorts(e){this.relayStateApplyPorts=e}getRelayStateSyncer(){const e=this.relayStateApplyPorts;return!e||!this.aibotHandle||this.isSharedInstance()?null:(this.relayStateSyncer||(this.relayStateSyncer=new Ve({...e,sendSyncRequest:(n,t)=>this.aibotHandle.relayStateSyncRequest(n,t),sendCredentialRequest:(n,t)=>{const{anthropicBaseUrl:s,openaiBaseUrl:i}=re(this.aibotConfig.url);return this.aibotHandle.relayCredentialRequest({anthropic_base_url:s,openai_base_url:i,...n},t)},sendReport:n=>this.aibotHandle.sendRelayStateReport(n),log:{info:n=>h.info(this.name,n),warn:n=>h.warn(this.name,n)}})),this.relayStateSyncer)}relayStateSyncOnConnect(){const e=this.getRelayStateSyncer();e&&e.syncOnConnect().catch(n=>{h.warn(this.name,`relay state sync failed: ${n instanceof Error?n.message:String(n)}`)})}reportRelayStateLocalChange(){try{this.getRelayStateSyncer()?.reportLocalChange()}catch{}}async handleApplyRelayState(e){const n=e.params??{},t=n.enabled,s=Number(n.revision);if(typeof t!="boolean"||!Number.isFinite(s)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"INVALID_PARAMS",error_msg:"enabled (boolean) and revision (number) are required"});return}const i=this.getRelayStateSyncer();if(!i){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"RELAY_UNAVAILABLE",error_msg:"relay state sync is not available on this agent",result:{revision:s}});return}const o=await i.applyFromLocalAction({enabled:t,model:typeof n.model=="string"?n.model:void 0,revision:s});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:o.ok?"ok":"failed",result:{revision:o.revision},...o.error_code?{error_code:o.error_code}:{},...o.error_msg?{error_msg:o.error_msg}:{}})}async fetchRelayCredential(e){const n=this.aibotHandle;if(!n||n.status!=="ready")throw new ze("agent websocket is not connected","OFFLINE");const{anthropicBaseUrl:t,openaiBaseUrl:s}=re(this.aibotConfig.url);return je((i,o)=>n.relayCredentialRequest(i,o),{anthropic_base_url:t,openai_base_url:s,...e.model?{model:e.model}:{}})}isSharedInstance(){return!!this.config.aibot.sharedOwnerId}}export{Us as AgentInstance};
16
+ Models (current: ${o?.modelId??"default"}): ${r}`);return}case _.exec:{const[i,...o]=e.args.trim().split(/\s+/);if(!i){s("failed","Usage: /grix exec <command> [args]",g.verbInvalid);return}const a=this.pool.getSlot(t)?.adapter;if(!a?.execCommand){s("failed","Agent does not support command execution",g.verbInvalid);return}const d=a.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 a.execCommand(i,o.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 n=String(e.action_type??"").trim();if(n!==A.sessionControl&&n!==A.setMode&&n!=="set_mode"&&n!==A.setModel&&n!=="set_model")return!1;const t=e.params??{},s=String(t.session_id??"").trim(),i=n===A.setMode?_.setMode:n===A.setModel?_.setModel:String(t.verb??"").trim().toLowerCase();if(h.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:H.localActionRouteMissing,error_msg:"local action session_id is required"}),!0;const o=a=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:a})},r=(a,d)=>{h.warn(this.name,`session_control local_action failed action_id=${e.action_id} session_id=${s} verb=${i} code=${a} msg=${d}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:a,error_msg:d})};try{switch(i){case _.open:{await N().catch(()=>{});const a=String(t.cwd??"").trim(),d=String(t.agent_session_id??"").trim();if(!a)return r(g.cwdRequired,"session control cwd is required"),!0;h.info(this.name,`handleSessionControlLocalAction open cwd=${a} session_id=${s}`);const c=await this.resolveCwdForBinding(a);this.ensureImportedAgentSession(d,c);const l=this.bindingStore.get(s);if(l?.cwd){const u=await this.resolveCwdForBinding(l.cwd);return u!==c?(r(g.rebindForbidden,"session binding cannot be changed to another working directory"),!0):(this.bindingStore.ensureModeId(s,k.fullAuto),this.setResolvedAgentSessionId(s,d),this.sessionBindings.set(s,u),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,u),o({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,u),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0)}return this.bindingStore.set(s,c,{modeId:k.fullAuto}),this.setResolvedAgentSessionId(s,d),this.sessionBindings.set(s,c),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,c),o({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,c),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0}case _.status:case _.where:{const a=this.bindingStore.get(s);return a?.cwd?(o({outcome:i,binding:{cwd:a.cwd,mode_id:this.normalizeClaudeModeId(a.modeId),worker_status:this.getClaudeWorkerStatus(s)}}),!0):(r(g.bindingMissing,"session binding was not found"),!0)}case _.stop:{const a=this.bindingStore.get(s);return a?.cwd?(await this.pool.removeSlot(s),o({outcome:"stopped",binding:{cwd:a.cwd,mode_id:this.normalizeClaudeModeId(a.modeId),worker_status:"stopped"}}),!0):(r(g.bindingMissing,"session binding was not found"),!0)}case _.restart:{const a=this.bindingStore.get(s);return a?.cwd?(await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,a.cwd),o({outcome:"restarted",binding:{cwd:a.cwd,mode_id:this.normalizeClaudeModeId(a.modeId)}}),!0):(r(g.bindingMissing,"session binding was not found"),!0)}case _.setMode:{const a=String(t.mode_id??t.modeId??"").trim();if(!a)return r(H.modeInvalid,"set mode_id is invalid"),!0;const d=this.normalizeClaudeModeId(a);if(d!==a.toLowerCase())return r(H.modeInvalid,"set mode_id is invalid"),!0;const c=this.bindingStore.get(s);if(!c?.cwd)return r(g.bindingMissing,"session binding was not found"),!0;if(this.normalizeClaudeModeId(c.modeId)!==d){if(this.getClaudeWorkerStatus(s)==="busy")return r(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 o({outcome:"mode_set",mode_id:d,binding:{cwd:c.cwd,mode_id:d}}),!0}case _.setModel:{const a=String(t.model_id??t.modelId??"").trim();if(!a)return r("set_model_invalid","model_id is required"),!0;const d=this.bindingStore.get(s);if(!d?.cwd)return r(g.bindingMissing,"session binding was not found"),!0;if((d.modelId??"")!==a){if(this.getClaudeWorkerStatus(s)==="busy")return r(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,a),this.globalConfigStore?.set(this.name,{modelId:a}),await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,d.cwd),this.refreshQuotaAfterModelSwitch(s,a)}return o({outcome:"model_set",model_id:a,binding:{cwd:d.cwd,model_id:a}}),!0}case _.listOptions:{const a=W(),d=this.pool.getSlot(s);return o({modes:[k.fullAuto,k.approval],currentModeId:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId),models:a.map(c=>({modelId:c.id,name:c.displayName})),currentModelId:this.bindingStore.get(s)?.modelId??"",available_models:a.map(c=>({id:c.id,displayName:c.displayName})),agent_commands:d?.adapter?.getSupportedCommands?.()??[]}),!0}case _.exec:{const[a,...d]=String(t.args??"").trim().split(/\s+/);if(!a)return r(g.verbInvalid,"Usage: exec <command> [args]"),!0;await this.ensureSlotStarted(s);const l=this.pool.getSlot(s)?.adapter;if(!l?.execCommand)return r(g.verbInvalid,"Agent does not support command execution"),!0;const u=l.getSupportedCommands?.()??[];if(!u.some(p=>p.name===a))return r(g.verbInvalid,`Unknown command: ${a}. Supported: ${u.map(p=>p.name).join(", ")}`),!0;try{const p=await l.execCommand(a,d.join(" "),s);p.status==="ok"?o({outcome:"exec",command:a,message:p.message,data:p.data}):r(g.runtimeError,p.message??`${a} failed`)}catch(p){r(g.runtimeError,`exec error: ${p instanceof Error?p.message:p}`)}return!0}default:return r(g.verbInvalid,`session control verb ${i} is not supported`),!0}}catch(a){const d=a instanceof Error&&a.cwdErrorCode?a.cwdErrorCode:a instanceof Error&&a.sessionControlErrorCode?a.sessionControlErrorCode:g.runtimeError;return h.error(this.name,`handleSessionControlLocalAction error verb=${i} session_id=${s}: ${a instanceof Error?a.message:a}`),r(d,a instanceof Error?a.message:String(a)),!0}}async handleEventCancel(e){const{event_id:n,session_id:t}=e;if(h.info(this.name,`handleEventCancel start event_id=${n} session_id=${t}`),this.pool.cancelEvent(n,t)){if(!(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(n)??!1)){this.sendEventResultWithCleanup(n,"canceled","canceled"),this.aibotHandle.sendEventCancelResult({event_id:n,accepted:!0,final_state:"canceled"});return}await this.waitForEventDone(n,t,15e3),this.aibotHandle.sendEventCancelResult({event_id:n,accepted:!0,final_state:"canceled"}),this.pushQueueSnapshotForSession(t);return}this.aibotHandle.sendEventCancelResult({event_id:n,accepted:!1,reason:"event not found or not cancelable"})}waitForEventDone(e,n,t){return new Promise(s=>{const i=this.pool.getSlot(n);if(!i?.adapter){s();return}const o=setTimeout(()=>{i.adapter.removeListener("eventDone",r),s()},t),r=a=>{a===e&&(clearTimeout(o),i.adapter.removeListener("eventDone",r),s())};i.adapter.on("eventDone",r)})}handleAibotStop(e){const n=e.event_id?.trim()??"",t=e.scope?.trim()??"";h.info(this.name,`[stop-trace] handleAibotStop begin session=${e.session_id} event=${n||"-"} scope=${t||"event"} stop_id=${e.stop_id||"-"} adapterType=${this.config.adapterType??"acp"}`);const s=this.pool.getSlot(e.session_id),i=s?.adapter?.getStatus().busy??!1;let o=!1,r=[];if(s?.adapter)try{r=[...new Set(s.adapter.getActiveEventIds().map(m=>m.trim()).filter(Boolean))]}catch(m){o=!0,h.warn(this.name,`[stop-trace] handleAibotStop active event probe failed session=${e.session_id}: ${m}`)}const a=t==="session";let d=a?"":n;const c=m=>({stop_id:e.stop_id,...m?{event_id:m}:{},...e.terminal_commit_token?{terminal_commit_token:e.terminal_commit_token}:{},session_id:e.session_id,...t?{scope:t}:{}}),l=m=>{!m||!e.terminal_commit_token?.trim()||this.sendEventResultWithCleanup(m,"canceled","stopped by owner","event_stopped")};if(a)if(!o&&r.length===1)[d]=r;else if(!o&&r.length===0&&!i){this.aibotHandle.sendEventStopAck({...c(""),accepted:!0,updated_at:Date.now()}),this.aibotHandle.sendEventStopResult({...c(""),status:"already_finished",updated_at:Date.now()}),h.info(this.name,`[stop-trace] handleAibotStop session idle -> stopResult(already_finished) session=${e.session_id} stop_id=${e.stop_id||"-"}`);return}else{const m=o?"session_stop_target_unavailable":r.length>1?"session_stop_target_ambiguous":"session_stop_target_unresolved",v=o?"failed to inspect active events for session stop":r.length>1?"multiple active events prevent a safe session stop":"adapter is busy but no active event can be identified";this.aibotHandle.sendEventStopAck({...c(""),accepted:!1,updated_at:Date.now()}),this.aibotHandle.sendEventStopResult({...c(""),status:"failed",code:m,msg:v,updated_at:Date.now()}),h.warn(this.name,`[stop-trace] handleAibotStop session target unsafe -> stopResult(failed) session=${e.session_id} activeIds=[${r.join(",")}] busy=${i} code=${m}`);return}if(this.aibotHandle.sendEventStopAck({...c(d),accepted:!0,updated_at:Date.now()}),this.pool.removeQueuedEvent(e.session_id,d)){h.info(this.name,`[stop-trace] handleAibotStop removed queued(not-running) event -> stopResult(stopped) session=${e.session_id} event=${d} stop_id=${e.stop_id||"-"}`),e.terminal_commit_token?.trim()?l(d):this.discardEventTrackingState(d),this.pushQueueSnapshotForSession(e.session_id),this.aibotHandle.sendEventStopResult({...c(d),status:"stopped",updated_at:Date.now()});return}const u=(this.config.adapterType??"acp")==="acp",p=r.length>0?r.includes(d):i,f=(u||(this.config.adapterType??"acp")==="codex"||(this.config.adapterType??"acp")==="claude")&&p;if(h.info(this.name,`[stop-trace] handleAibotStop decision session=${e.session_id} event=${d} scope=${t||"event"} slotExists=${!!s?.adapter} busy=${i} activeIds=[${r.join(",")}] stoppingActiveEvent=${p} killOnStop=${f}`),p&&this.sendCtrl.markEventStopped(d),s?.adapter&&i){const m=f?this.pool.drainQueuedForSession(e.session_id):[];let v=!1,b=null;const S=C=>{v||(v=!0,b&&(clearTimeout(b),b=null),s.adapter.removeListener("eventDone",w),h.info(this.name,`[stop-trace] handleAibotStop ${C} -> stopResult(stopped) session=${e.session_id} event=${d} stop_id=${e.stop_id||"-"} killOnStop=${f}`),l(d),this.aibotHandle.sendEventStopResult({...c(d),status:"stopped",updated_at:Date.now()}),f&&this.killAndResumeStopSlot(e.session_id,m))},w=C=>{C===d&&S("eventDone")};s.adapter.on("eventDone",w),b=setTimeout(()=>S("timeout"),li),this.pool.deliverStopEvent(d,e.session_id)}else h.info(this.name,`[stop-trace] handleAibotStop slot-not-busy -> immediate stopResult(stopped) session=${e.session_id} event=${d} slotExists=${!!s?.adapter}`),this.pool.deliverStopEvent(d,e.session_id),l(d),this.aibotHandle.sendEventStopResult({...c(d),status:"stopped",updated_at:Date.now()});(this.config.adapterType??"acp")==="pi"&&this.aibotHandle.sendText({event_id:d,session_id:e.session_id,content:"/stop",msg_type:0})}async killAndResumeStopSlot(e,n){if(!this.stopped){h.info(this.name,`[stop-trace] killAndResumeStopSlot begin session=${e} siblings=${n.length} -> removeSlot (kill process group)`);try{await this.pool.removeSlot(e),h.info(this.name,`[stop-trace] killAndResumeStopSlot removeSlot done session=${e} (process killed) -> redeliver ${n.length} sibling(s)`)}catch(t){h.warn(this.name,`[acp-stop] removeSlot failed session=${e}: ${t instanceof Error?t.message:String(t)}`)}if(!this.stopped)for(const t of n){if(this.stopped)break;try{await this.pool.deliverInboundEvent(t)}catch(s){h.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 n=e.event_id,t=e.session_id;if(t&&this.pool.cancelEvent(n,t)){(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(n)??!1)||this.sendEventResultWithCleanup(n,"canceled","revoked");return}if(this.deferredMgr.removeEvent(n)){this.aibotHandle.sendEventResult({event_id:n,status:"canceled",msg:"revoked",updated_at:Date.now()});return}this.pool.deliverStopEvent(n,t||void 0)}async handleConfigureGatewayProvider(e){const n=e.params??{},t=String(n.api_key??"").trim(),s=String(n.anthropic_base_url??"").trim(),i=String(n.openai_base_url??"").trim(),o=typeof n.provider_id=="string"&&n.provider_id.trim().toLowerCase()||void 0,r=typeof n.quota_base_url=="string"&&n.quota_base_url.trim()||void 0,a=typeof n.model=="string"&&n.model.trim()||void 0;let d=!1,c;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 l=this.config.adapterType??"acp",u=l==="claude"||l==="codex",p=u&&Ye(n.direct_relay,l),f=u&&n.direct_relay!==void 0&&!p;try{if(f){if(!this.relayStateApplyPorts){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"unsupported",error_code:"UNSUPPORTED_CLIENT_TYPE",error_msg:"relay state applier is not configured"});return}const m=await this.relayStateApplyPorts.applyEnable({apiKey:t,...s?{anthropicBaseUrl:s}:{},...i?{openaiBaseUrl:i}:{},...a?{model:a}:{},directRelay:n.direct_relay},a);m&&(c=m,d=m.busy||m.pending!==void 0)}else if(u){const m=l==="claude"?s:i;if(!m){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_BASE_URL",error_msg:`${l==="claude"?"anthropic_base_url":"openai_base_url"} is required`});return}const v=ne();if(!v){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"PROXY_UNAVAILABLE",error_msg:"MITM proxy manager not initialized"});return}const b=We(l),S=Ke(l,m,t,{model:a});v.setRoute(S);for(const w of b)v.setHostDefaultRoute(w,S.routeKey);await v.setAgentRelayEnabled(this.name,!0,{relayHosts:b}),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 "${l}" does not support Grix relay provider config`});return}const m=this.config.aibot.clientType,v=oe(m),b=v?s:i;if(!b){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_BASE_URL",error_msg:`${v?"anthropic_base_url":"openai_base_url"} is required`});return}if(v&&!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_MODEL",error_msg:'model is required for client type "kiro"'});return}await this.providerConfigHandler({...o?{provider_id:o}:{},base_url:b||void 0,...r?{quota_base_url:r}:{},api_key:t,model:a})}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0,restart_deferred:d,...c?{restarted:c.restarted,busy:c.busy,...c.pending?{pending:c.pending}:{}}:{}}})}catch(m){h.error(this.name,`handleConfigureGatewayProvider failed: ${m}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"CONFIGURE_FAILED",error_msg:m instanceof Error?m.message:String(m)})}}getAuditLocalActionHandler(){if(!this.auditLocalActionHandler){const e=new Le({rootDir:xe()});this.auditLocalActionHandler=new $e(new Te(e))}return this.auditLocalActionHandler}async handleAuditLocalAction(e){const n=await this.getAuditLocalActionHandler().handle(e.action_type,e.params);if(n.status==="ok"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:n.result});return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:n.errorCode,error_msg:n.errorMsg})}async handleAibotLocalAction(e){const n=e.action_type??"",t=String((e.params??{}).session_id??""),s=String((e.params??{}).verb??"").trim().toLowerCase();if(h.debug(this.name,`local_action received action_type=${n} verb=${s||"-"} action_id=${e.action_id} session_id=${t}`),Pe(n)){await this.handleAuditLocalAction(e);return}const i=(this.config.adapterType??"acp")==="claude";if(n===A.sessionControl&&s===_.exec&&await this.handleSessionControlLocalAction(e))return;if(n===A.sessionControl&&s===_.listSessions){await this.handleListSessionsLocalAction(e);return}if(n===A.sessionControl&&s===_.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(n==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(n==="skill_enable"){await this.handleSkillEnableLocalAction(e);return}if(n==="skill_disable"){await this.handleSkillDisableLocalAction(e);return}if(n==="skill_refresh"){this.handleSkillRefreshLocalAction(e);return}const o=(this.config.adapterType??"acp")==="opencode";if((i&&(n===A.interactionReply||n==="exec_approve"||n==="exec_reject")||o&&n===A.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||i&&await this.handleSessionControlLocalAction(e))return;if(n===A.sessionControl){const l=this.config.adapterType??"acp",u=l==="codex",p=l==="pi",f=String((e.params??{}).verb??"").trim().toLowerCase();if(u&&f===_.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(l==="cursor"&&f===_.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(u&&f==="restart"){const w=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:w,workerStatus:"ready"}}});return}if(p&&f===_.open){try{const S=e.params??{},w=String(S.cwd??"").trim();if(!w){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const C=await this.resolveCwdForBinding(w),E=String(S.agent_session_id??"").trim();this.ensureImportedAgentSession(E,C),this.bindingStore.set(t,C),this.setResolvedAgentSessionId(t,E),this.sessionBindings.set(t,C),await this.ensureSlotStarted(t).catch(q=>{h.warn("bridge",`pi ensureSlotStarted on local-action bind failed (non-fatal): ${q instanceof Error?q.message:String(q)}`)}),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:C}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,C)}})}catch(S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:S?.sessionControlErrorCode??S?.cwdErrorCode??g.invalidCwd,error_msg:S instanceof Error?S.message:String(S)})}return}if(p&&f===_.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((l==="openhuman"||l==="opencode")&&f===_.open){try{const S=e.params??{},w=String(S.cwd??"").trim();if(!w){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const C=await this.resolveCwdForBinding(w),E=String(S.agent_session_id??"").trim();this.ensureImportedAgentSession(E,C),this.bindingStore.set(t,C),this.setResolvedAgentSessionId(t,E),this.sessionBindings.set(t,C),this.syncOpenCodeBinding(t,C),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,C)}})}catch(S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:S?.sessionControlErrorCode??S?.cwdErrorCode??g.invalidCwd,error_msg:S instanceof Error?S.message:String(S)})}return}if(l==="codewhale"&&f===_.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(l==="acp"&&f===_.stop){const w=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:w,workerStatus:"stopped"}}});return}try{if(f===_.open){const S=e.params??{},w=String(S.cwd??"").trim();if(!w){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const C=String(S.agent_session_id??"").trim();if(C){const E=await this.resolveCwdForBinding(w);this.ensureImportedAgentSession(C,E)}}await this.handleSessionControlLocalActionForPool(e)}catch(S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:S?.sessionControlErrorCode??S?.cwdErrorCode??g.runtimeError,error_msg:S instanceof Error?S.message:String(S)});return}if(f===_.open){const S=e.params??{},w=await this.resolveCwdForBinding(String(S.cwd??"").trim());this.setResolvedAgentSessionId(t,String(S.agent_session_id??"").trim()),l==="agy"&&(this.bindingStore.set(t,w),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)}}),(this.config.adapterType??"acp")==="agy"&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:w,meta:this.buildAgyToolbarMeta(t)})}else Tt(e,this.sessionControlCtx(t),this.sessionControlSenders());return}if(n==="file_list"){const l=Date.now(),u=t?this.bindingStore.get(t)?.cwd:void 0,p=e.params??{},f=String(p.parent_id??"").trim(),m=Array.isArray(p.allowed_extensions)?p.allowed_extensions.filter(w=>typeof w=="string").map(w=>w.trim()).filter(w=>w.length>0):[];h.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${t} parent_id=${f||"<root>"} show_hidden=${!!p.show_hidden} ext_count=${m.length} bound_cwd=${u??"<none>"}`);const v=await Mt({parent_id:f||null,session_id:t,show_hidden:!!p.show_hidden,allowed_extensions:m},{resolveCwd:()=>u??this.config.agent.cwd??process.cwd(),fallbackDir:le()}),b=Date.now()-l,S=v.result?.files?.length??0;h.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${v.status} elapsed=${b}ms count=${S} current_path=${v.result?.current_path??""} error_code=${v.error_code??""} error_msg=${v.error_msg??""}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:v.status,...v.result?{result:{...v.result,machine_name:Qt()}}:{},...v.error_code?{error_code:v.error_code}:{},...v.error_msg?{error_msg:v.error_msg}:{}});return}if(n==="create_folder"){const l=t?this.bindingStore.get(t)?.cwd:void 0,u=String((e.params??{}).parent_id??"").trim(),p=String((e.params??{}).name??"").trim(),f=await It({parent_id:u||null,name:p,session_id:t},{resolveCwd:()=>l??this.config.agent.cwd??process.cwd(),fallbackDir:le()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:f.status,...f.result?{result:f.result}:{},...f.error_code?{error_code:f.error_code}:{},...f.error_msg?{error_msg:f.error_msg}:{}});return}if(n===A.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,t);return}if(n===A.getSessionUsage){await this.handleGetSessionUsage(e,t);return}if(n===A.getRateLimits){await this.handleGetRateLimits(e,t);return}const r=(this.config.adapterType??"acp")==="acp";if((i||r)&&n===A.threadCompact){await this.handleThreadCompact(e,t);return}if(n==="connector_rollback"){await this.handleConnectorRollback(e);return}if(n==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(n===A.getAgentGlobalConfig){const l=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...l?{config:l}:{config:null}}});return}if(n==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}if(n==="apply_relay_state"){await this.handleApplyRelayState(e);return}const a=this.config.adapterType??"acp",d=(a==="codex"||a==="cursor"||a==="pi"||a==="openhuman"||a==="opencode"||a==="acp")&&!!t&&!!this.bindingStore.get(t)?.cwd,c=await this.pool.deliverLocalAction(e,{autoCreateSlot:d});if(c.handled){if(c.kind==="set_mode"){const l=String((e.params??{}).mode_id??"");l&&(a==="cursor"?this.bindingStore.setCursorModeId(t,l):a==="claude"?this.bindingStore.setModeId(t,l):a==="opencode"?this.bindingStore.setModeId(t,l):B.has(a)?a==="codex"&&this.globalConfigStore?.set(this.name,{codexModeId:l}):this.globalConfigStore?.set(this.name,{acpInitialMode:l}))}else if(c.kind==="set_model"){const l=String((e.params??{}).model_id??"").trim();if(l){a==="cursor"?(this.bindingStore.setModelId(t,l),this.globalConfigStore?.set(this.name,{modelId:l})):a==="opencode"?this.bindingStore.setModelId(t,l):a==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:l}):B.has(a)||this.globalConfigStore?.set(this.name,{modelId:l});const u=String((e.params??{}).provider??(e.params??{}).model_provider??"").trim()||void 0;this.refreshQuotaAfterModelSwitch(t,l,u)}}else if(c.kind==="set_reasoning_effort"){const l=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");l&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:l})}else if(c.kind==="set_sandbox_mode"){const l=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(l){const u=l==="default"?void 0:l;this.globalConfigStore?.set(this.name,{codexSandboxMode:u})}}else if(c.kind==="set_service_tier"){const l=String((e.params??{}).service_tier??(e.params??{}).serviceTier??(e.params??{}).value??"").trim();if(l){const u=l.toLowerCase()==="default"?void 0:l;this.globalConfigStore?.set(this.name,{codexServiceTier:u})}}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"&&(n==="set_mode"||n==="set_model")){const l=this.sessionControlSenders(),u=this.pool.getSlot(t)?.adapter,p={bindingStore:this.bindingStore,acpAdapter:u instanceof R?u:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:h};if(n==="set_mode"){const f=String((e.params??{}).mode_id??""),m=await ce(p,t,f);if(m.status==="failed")l.sendLocalActionResult(e.action_id,"failed",void 0,m.errorCode,m.errorMsg);else{const v=u instanceof R?u.buildToolbarContext(m.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,b=v?{...v,...m.result}:m.result;l.sendLocalActionResult(e.action_id,"ok",b)}}else{const f=String((e.params??{}).model_id??""),m=await de(p,t,f);if(m.status==="failed")l.sendLocalActionResult(e.action_id,"failed",void 0,m.errorCode,m.errorMsg);else{const v=u instanceof R?u.buildToolbarContext(m.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,b=v?{...v,...m.result}:m.result;l.sendLocalActionResult(e.action_id,"ok",b),m.result?.outcome==="model_set"&&this.refreshQuotaAfterModelSwitch(t,f)}}return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:`action type ${n} is not supported`})}async handleGetSessionUsage(e,n){if(!n){h.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(n),i=s?.cwd??this.config.agent.cwd??process.cwd();h.info(this.name,`[usage] get_session_usage action_id=${e.action_id} session_id=${n} adapterType=${t} hasBinding=${!!s} cwd=${i}`);let o=null,r,a;switch(t){case"claude":{if(r=s?.claudeSessionId,!r){h.warn(this.name,`[usage] no claude binding for session_id=${n}, 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}h.info(this.name,`[usage] parsing claude usage: claudeSessionId=${r} cwd=${i}`),o=await He(r,i),a="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(r=s?.acpSessionId,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No ACP session binding found"});return}o=await Fe(r,i,this.config.aibot.clientType),a=t,(!a||a==="acp")&&(a="acp");break}case"codex":{if(r=s?.codexThreadId,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Codex thread binding found"});return}o=await tt(r),a="codex";break}case"pi":{if(r=s?.piSessionPath,!r){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Pi session path binding found"});return}o=await pt(r),a="pi";break}case"cursor":{const c=this.pool.getSlot(n)?.adapter;if(!(c instanceof D)){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(n);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 u={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:n,adapterType:"cursor",models:[{model:this.bindingStore.get(n)?.modelId??"auto",turns:l.turns,total:u}],total:u,turns:l.turns,sampledAt:l.sampledAt}});return}case"codewhale":{const c=this.pool.getSlot(n)?.adapter;if(!(c instanceof X)){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 u={inputTokens:l.total.input,outputTokens:l.total.output,cacheReadInputTokens:0,cacheCreationInputTokens:0};this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:n,adapterType:"codewhale",models:[{model:this.bindingStore.get(n)?.modelId??"codewhale",turns:l.turns,total:u}],total:u,turns:l.turns,sampledAt:l.sampledAt}});return}}if(!o){h.info(this.name,`[usage] no usage data found: session_id=${n} adapterSessionId=${r} adapterType=${a}`);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}h.info(this.name,`[usage] result ok: session_id=${n} adapterSessionId=${r} turns=${o.turns} models=${o.models.length}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:r,adapterType:a,models:o.models,total:o.total,turns:o.turns,sampledAt:new Date().toISOString()}})}async handleThreadCompact(e,n){if(!n){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(n)?.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(n);const i=this.pool.getSlot(n)?.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}h.info(this.name,`thread_compact session_id=${n} action_id=${e.action_id}`);const o=await i.execCommand("compact","",n);o.status==="ok"?this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"compacted",message:o.message,data:o.data}}):this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:o.message??"compact failed"})}catch(s){h.warn(this.name,`thread_compact error session_id=${n}: ${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,n){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 o=await z();this.cachedProviderQuota=o,this.cachedProviderQuotaSampledAtMs=Date.now(),h.info(this.name,`[rate-limits] kiro quota queried: success=${o.success}`+(o.balance?` balance=${o.balance.remaining} ${o.balance.unit}`:"")+(o.error?` error=${o.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:o}})}catch(o){h.warn(this.name,`[rate-limits] kiro quota query failed: ${o instanceof Error?o.message:String(o)}`),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(u=>u.state==="ready"&&u.adapter);if(l&&(h.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?h.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}`):h.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 r=this.pool.getAllSlots().find(l=>l.state==="ready"&&l.adapter);if(r&&(h.info(this.name,`[rate-limits] codex reuse existing slot: session=${r.sessionId}`),(await r.adapter.handleLocalAction?.(e))?.handled))return;const a=this.resolveRateLimitWakeSessionId(n,t);if(a){const l=await this.wakeRateLimitSlot(a,t);if(l?.adapter&&(await l.adapter.handleLocalAction?.(e))?.handled)return}const d=await s,c=!!d;h.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;h.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 o=this.pool.getAllSlots().find(c=>c.state==="ready"&&c.adapter instanceof L)??null;if(!o){const c=this.resolveRateLimitWakeSessionId(n,t);c&&(o=await this.wakeRateLimitSlot(c,t))}h.info(this.name,`[rate-limits] handleGetRateLimits: session_id=${n} adapterType=claude hasSlot=${!!o} hasAdapter=${!!o?.adapter}`);const r=o?.adapter,a=r instanceof L?r.getSessionState():null,d=await s;if(a){(a.rateLimits?.fiveHour||a.rateLimits?.sevenDay||a.contextWindow?.usedPercentage!=null)&&(this.cachedClaudeRateLimitState=a);const c=this.getFreshClaudeRateLimitState(),l=c?.rateLimits&&!a.rateLimits?{...a,rateLimits:c.rateLimits}:a,u=l.rateLimits;h.info(this.name,`[rate-limits] claude global state: sampledAt=${l.sampledAt} hasRateLimits=${!!u}`+(u?` fiveHour=${u.fiveHour?.usedPercentage??"n/a"}% resetsAt=${u.fiveHour?.resetsAt??"n/a"} sevenDay=${u.sevenDay?.usedPercentage??"n/a"}% resetsAt=${u.sevenDay?.resetsAt??"n/a"}`:"")+(c?.rateLimits&&!a.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 h.info(this.name,`[rate-limits] claude no global state: hasAdapter=${!!r} adapterType=${r?.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=(n?this.pool.getSlot(n):null)?.adapter;if(i instanceof D){await i.refreshAccountRateLimits({force:!0});const r=i.getRateLimitsSnapshot(n);h.info(this.name,`[rate-limits] cursor: available=${r.available} monthly=${r.rateLimits?.fiveHour?.usedPercentage??"n/a"}% api=${r.rateLimits?.sevenDay?.usedPercentage??"n/a"}%`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:r});return}const o=await ke();h.info(this.name,`[rate-limits] cursor(no-slot): available=${o.available} monthly=${o.rateLimits?.fiveHour?.usedPercentage??"n/a"}% api=${o.rateLimits?.sevenDay?.usedPercentage??"n/a"}%`+(o.error?` error=${o.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"cursor",available:o.available,cached:!1,sampledAt:Number.isFinite(Date.parse(o.sampledAt))?Date.parse(o.sampledAt):Date.now(),rateLimits:o.rateLimits,contextWindow:null,tokenUsage:null,...o.displayMessage?{displayMessage:o.displayMessage}:{},...o.error?{error:o.error}:{}}});return}default:{const s=this.sessionProviderHints.get(n),i=this.sessionBindings.get(n)||this.bindingStore.get(n)?.cwd;if(s&&i&&!s.disabled){await this.refreshProviderQuotaForSession(n,i,!0);const a=this.sessionProviderQuotas.get(n),d=a?.quota??null;if(!d){h.info(this.name,`[rate-limits] no session provider quota available for adapterType=${t} session=${n}`),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}h.info(this.name,`[rate-limits] session provider quota queried: provider=${d.provider} success=${d.success}`+(d.tiers.length>0?` tiers=${d.tiers.map(c=>`${c.name}=${c.usedPercent}%`).join(",")}`:"")+(d.error?` error=${d.error}`:"")+` session=${n}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:!1,sampledAt:a?.sampledAt??null,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null,providerQuota:d}});return}const o=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&!!this.cachedProviderQuota,r=await this.maybeQueryProviderQuota();if(!r){h.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}h.info(this.name,`[rate-limits] provider quota ${o?"cached":"queried"}: provider=${r.provider} success=${r.success}`+(r.tiers.length>0?` tiers=${r.tiers.map(a=>`${a.name}=${a.usedPercent}%`).join(",")}`:"")+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.error?` error=${r.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:o,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null,providerQuota:r}});return}}}resolveRateLimitWakeSessionId(e,n){const t=String(e??"").trim(),s=this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0});return s?t&&t===s?t:n==="codex"||n==="claude"?(t&&t!==s&&h.info(this.name,`[rate-limits] ${n} remap wake session: requested=${t} use_recent=${s}`),s):t&&t!==s?(h.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${n} reason=not_recent_session recent=${s}`),null):t||null:(h.info(this.name,`[rate-limits] skip wake slot: adapterType=${n} reason=no_recent_binding`),null)}async wakeRateLimitSlot(e,n){const t=String(e??"").trim();if(!t)return null;if(!this.bindingStore.get(t)?.cwd)return h.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${n} reason=binding_cwd_missing`),null;try{const i=this.pool.getOrCreateSlot(t);if(!i)return h.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${n} reason=slot_unavailable`),null;if(i.startPromise){const o=n==="claude"?6e4:2e4;await Promise.race([i.startPromise,new Promise((r,a)=>setTimeout(()=>a(new Error(`wake rate-limits slot timeout (${o}ms)`)),o))])}return h.info(this.name,`[rate-limits] wake slot success: session=${t} adapterType=${n}`),this.pool.getSlot(t)??i}catch(i){return h.warn(this.name,`[rate-limits] wake slot failed: session=${t} adapterType=${n} err=${i instanceof Error?i.message:String(i)}`),null}}sessionControlCtx(e){const n=this.pool.getSlot(e),t=n?.adapter instanceof R?n.adapter:null,s=(this.config.adapterType??"acp")==="acp",i={bindingStore:this.bindingStore,acpAdapter:t,globalConfigStore:this.globalConfigStore,agentName:this.name,log:h};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(t)return t.getSessionBindings();const o=this.sessionBindings;if(e&&!o.has(e)){const r=this.bindingStore.get(e);r?.cwd&&o.set(e,r.cwd)}return o},getStatus:()=>this.getStatus(),isAcpAlive:!!t?.isAlive(),getAcpSessionOptions:()=>t?.acpSessionOptions??null,setMode:o=>t?t.setMode(o):Promise.resolve(!1),setModel:o=>t?t.setModel(o):Promise.resolve(!1),acpSetMode:s?(o,r)=>ce(i,o,r):void 0,acpSetModel:s?(o,r)=>de(i,o,r):void 0,getPendingApproval:o=>{const r=t?.pendingApprovalEntries.get(o);return r?{requestId:r}:void 0},deletePendingApproval:o=>t?.pendingApprovalEntries.delete(o)??!1,respondPermission:(o,r)=>(t&&t.respondToPermission(o,r),Promise.resolve()),onSessionBound:(o,r)=>{this.bindingStore.set(o,r)},onSessionUnbound:o=>{const a=this.bindingStore.get(o)?.cwd??"";this.bindingStore.delete(o),this.sessionBindings.delete(o),this.sessionProviderHints.delete(o),this.sessionProviderQuotas.delete(o),this.sessionProviderMeta.delete(o),this.claudeWorkerStatus.delete(o),this.deferredMgr.clearSession(o),this.aibotHandle.clearBindingCardMetaCache?.(o);for(const d of this.pool.drainQueuedForSession(o))this.discardEventTrackingState(d.event_id);a&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"stopped",cwd:a})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&n?.adapter instanceof ee?(n.adapter.cancelCurrentRun(),Promise.resolve()):n?.adapter?.cancel("")??Promise.resolve(),onModeSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModeId:o}):r==="opencode"?this.bindingStore.setModeId(e,o):B.has(r)||this.globalConfigStore?.set(this.name,{acpInitialMode:o})},onModelSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:o}):r==="opencode"?this.bindingStore.setModelId(e,o):B.has(r)||this.globalConfigStore?.set(this.name,{modelId:o}),this.refreshQuotaAfterModelSwitch(e,o)}}}sessionControlSenders(){return{sendEventAck:(e,n)=>this.aibotHandle.sendEventAck({event_id:e,session_id:n,received_at:Date.now()}),sendEventResult:(e,n,t)=>this.aibotHandle.sendEventResult({event_id:e,status:n,...t?.msg?{msg:t.msg}:{},...t?.code?{code:t.code}:{},updated_at:Date.now()}),sendLocalActionResult:(e,n,t,s,i)=>this.aibotHandle.sendLocalActionResult({action_id:e,status:n,...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,n){this.sendCtrl.finalizeThinking(e,n)}logInboundConversation(e){const n=String(e.session_id??"").trim();n&&this.conversationLog?.logInbound(n,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}resolveAuditProvider(){const e=this.config.adapterType??"acp";return e==="claude"||e==="codex"||e==="cursor"||e==="opencode"||e==="pi"||e==="codewhale"?e:"acp"}sendAuditConfigurationError(e,n){const t=n instanceof Error?n.message:String(n),s=n instanceof ni||n instanceof si,i=s?n.code:"audit_config_conflict";if(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:i,msg:t,updated_at:Date.now()}),s)try{this.aibotHandle.sendAuditState(j({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:i,errorMessage:t},Date.now()))}catch{}}markAuditAdapterClosed(e,n){const s=this.pool.getSlot(n)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,s)}prepareAuditedInboundEvent(e,n,t){const s=this.buildInboundEvent(e,n),i=this.bindingStore.get(e.session_id),o=i?this.resolveAgentSessionId(i):void 0,r=Number(e.created_at),a=Number.isFinite(r)&&r>0?new Date(r).toISOString():void 0,d=this.auditController.startTurn({session:t,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...a===void 0?{}:{startedAt:a},boundary:{adapterType:this.config.adapterType??"acp",...o?{providerSessionId:o}:{}}});return d&&(s.audit={enabled:!0,auditId:d.auditId,turnId:d.turnId,...t?{profile:t.options.profile,capture:{...t.options.capture}}:{},rawProviderBody:t?.options.capture.rawProviderBody===!0}),s}buildInboundEvent(e,n){const t=Ut(this.sendCtrl.getGlobalRuntimeConfig(),n),s=ri(e.extra);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:s===void 0?void 0:JSON.stringify(s),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 n=e.filter(t=>!xt(String(t?.content??"")));if(n.length!==0)return JSON.stringify(n)}isStaleEvent(e){const n=Number(e.created_at);return!Number.isFinite(n)||n<=0?!1:Date.now()-n>ai}async handleConnectorRollback(e){const n=String((e.params??{}).target_version??"").trim(),t=String((e.params??{}).reason??"server_initiated");if(!n){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}h.info(this.name,`connector_rollback: target=${n} reason=${t}`);try{const{npmInstall:s,writePending:i,removePending:o,upgradeLog:r}=await import("../core/upgrade/npm-upgrader.js"),{resolveClientVersion:a}=await import("../core/util/client-version.js"),d=a();r(`server rollback: ${d} -> ${n} reason=${t}`),i(d,n),await s("grix-connector",n),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{rolled_back_to:n}}),process.kill(process.pid,"SIGTERM")}catch(s){try{const{removePending:o}=await import("../core/upgrade/npm-upgrader.js");o()}catch{}const i=s instanceof Error?s.message:String(s);h.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}setRelayStateApplyPorts(e){this.relayStateApplyPorts=e}getRelayStateSyncer(){const e=this.relayStateApplyPorts;return!e||!this.aibotHandle||this.isSharedInstance()?null:(this.relayStateSyncer||(this.relayStateSyncer=new Ve({...e,sendSyncRequest:(n,t)=>this.aibotHandle.relayStateSyncRequest(n,t),sendCredentialRequest:(n,t)=>{const{anthropicBaseUrl:s,openaiBaseUrl:i}=re(this.aibotConfig.url);return this.aibotHandle.relayCredentialRequest({anthropic_base_url:s,openai_base_url:i,...n},t)},sendReport:n=>this.aibotHandle.sendRelayStateReport(n),log:{info:n=>h.info(this.name,n),warn:n=>h.warn(this.name,n)}})),this.relayStateSyncer)}relayStateSyncOnConnect(){const e=this.getRelayStateSyncer();e&&e.syncOnConnect().catch(n=>{h.warn(this.name,`relay state sync failed: ${n instanceof Error?n.message:String(n)}`)})}reportRelayStateLocalChange(){try{this.getRelayStateSyncer()?.reportLocalChange()}catch{}}async handleApplyRelayState(e){const n=e.params??{},t=n.enabled,s=Number(n.revision);if(typeof t!="boolean"||!Number.isFinite(s)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"INVALID_PARAMS",error_msg:"enabled (boolean) and revision (number) are required"});return}const i=this.getRelayStateSyncer();if(!i){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"RELAY_UNAVAILABLE",error_msg:"relay state sync is not available on this agent",result:{revision:s}});return}const o=await i.applyFromLocalAction({enabled:t,model:typeof n.model=="string"?n.model:void 0,revision:s});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:o.ok?"ok":"failed",result:{revision:o.revision},...o.error_code?{error_code:o.error_code}:{},...o.error_msg?{error_msg:o.error_msg}:{}})}async fetchRelayCredential(e){const n=this.aibotHandle;if(!n||n.status!=="ready")throw new ze("agent websocket is not connected","OFFLINE");const{anthropicBaseUrl:t,openaiBaseUrl:s}=re(this.aibotConfig.url);return je((i,o)=>n.relayCredentialRequest(i,o),{anthropic_base_url:t,openai_base_url:s,...e.model?{model:e.model}:{}})}isSharedInstance(){return!!this.config.aibot.sharedOwnerId}}export{Us as AgentInstance};
@@ -1 +1 @@
1
- import{readJSONFile as o,writeJSONFileAtomic as e}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(i=>typeof i=="string"&&i.trim().length>0):[]}async function s(t,r){await e(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
1
+ import{readJSONFile as o,writeJSONFileAtomic as i}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(e=>typeof e=="string"&&e.trim().length>0):[]}async function s(t,r){await i(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
@@ -1 +1 @@
1
- import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const t of c){if(!p&&t.name.startsWith("."))continue;const i=l(a,t.name),e={id:i,name:t.name,is_directory:t.isDirectory()};try{if(t.isDirectory()){const o=await m(i);e.modified_at=o.mtime.toISOString()}else{const o=await m(i);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(t.name)}}catch{}s.push(e)}return s.sort((t,i)=>t.is_directory!==i.is_directory?t.is_directory?-1:1:t.name.localeCompare(i.name)),s}export{f as listFiles,n as resolveMimeType};
1
+ import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const i of c){if(!p&&i.name.startsWith("."))continue;const t=l(a,i.name),e={id:t,name:i.name,is_directory:i.isDirectory()};try{if(i.isDirectory()){const o=await m(t);e.modified_at=o.mtime.toISOString()}else{const o=await m(t);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(i.name)}}catch{}s.push(e)}return s.sort((i,t)=>i.is_directory!==t.is_directory?i.is_directory?-1:1:i.name.localeCompare(t.name)),s}export{f as listFiles,n as resolveMimeType};
package/dist/log.js CHANGED
@@ -1,3 +1,3 @@
1
- import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as t}from"node:path";import{homedir as m}from"node:os";const i=t(m(),".grix"),s={base:i,config:t(i,"config"),log:t(i,"log"),data:t(i,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=t(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...n){const e=`${c()} [${o}] ${r}${n.length?" "+n.map(String).join(" "):""}`;console.log(e),a?.write(e+`
2
- `)},error(o,r,...n){const e=`${c()} [${o}] ERROR ${r}${n.length?" "+n.map(String).join(" "):""}`;console.error(e),a?.write(e+`
1
+ import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as i}from"node:path";import{homedir as m}from"node:os";const n=i(m(),".grix"),s={base:n,config:i(n,"config"),log:i(n,"log"),data:i(n,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=i(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...t){const e=`${c()} [${o}] ${r}${t.length?" "+t.map(String).join(" "):""}`;console.log(e),a?.write(e+`
2
+ `)},error(o,r,...t){const e=`${c()} [${o}] ERROR ${r}${t.length?" "+t.map(String).join(" "):""}`;console.error(e),a?.write(e+`
3
3
  `)}};export{s as GRIX_PATHS,S as ensureGrixDirs,$ as initLogger,u as log};
@@ -1 +1 @@
1
- import*as i from"node:net";const e={bind:"127.0.0.1",port:0,endpoint:"/mcp",sessionTimeoutMs:18e5,invokeTimeoutMs:3e4};function n(o){const u={bind:o?.bind??e.bind,port:o?.port??e.port,endpoint:o?.endpoint??e.endpoint,sessionTimeoutMs:o?.sessionTimeoutMs??e.sessionTimeoutMs,invokeTimeoutMs:o?.invokeTimeoutMs??e.invokeTimeoutMs,allowedOrigins:o?.allowedOrigins,allowedHosts:o?.allowedHosts};return s(u.bind),u.port!==0&&t(u.port),r(u.sessionTimeoutMs),u}function s(o){if(!o||!i.isIPv4(o)&&!i.isIPv6(o))throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: bind \u5730\u5740 "${o}" \u4E0D\u662F\u5408\u6CD5\u7684 IPv4 \u6216 IPv6 \u5730\u5740`)}function t(o){if(!Number.isInteger(o)||o<1||o>65535)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: port \u503C ${o} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1-65535 \u5185\u6216\u4E0D\u662F\u6574\u6570`)}function r(o){if(!Number.isInteger(o)||o<1e3||o>864e5)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: session_timeout_ms \u503C ${o} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1000-86400000 \u5185`)}export{n as createDefaultGatewayConfig};
1
+ import*as n from"node:net";const i={bind:"127.0.0.1",port:0,endpoint:"/mcp",sessionTimeoutMs:18e5,invokeTimeoutMs:3e4};function s(u){const e={bind:u?.bind??i.bind,port:u?.port??i.port,endpoint:u?.endpoint??i.endpoint,sessionTimeoutMs:u?.sessionTimeoutMs??i.sessionTimeoutMs,invokeTimeoutMs:u?.invokeTimeoutMs??i.invokeTimeoutMs,allowedOrigins:u?.allowedOrigins,allowedHosts:u?.allowedHosts};return t(e.bind),e.port!==0&&o(e.port),r(e.sessionTimeoutMs),e}function t(u){if(!u||!n.isIPv4(u)&&!n.isIPv6(u))throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: bind \u5730\u5740 "${u}" \u4E0D\u662F\u5408\u6CD5\u7684 IPv4 \u6216 IPv6 \u5730\u5740`)}function o(u){if(!Number.isInteger(u)||u<1||u>65535)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: port \u503C ${u} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1-65535 \u5185\u6216\u4E0D\u662F\u6574\u6570`)}function r(u){if(!Number.isInteger(u)||u<1e3||u>864e5)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: session_timeout_ms \u503C ${u} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1000-86400000 \u5185`)}export{s as createDefaultGatewayConfig};
@@ -1 +1 @@
1
- const r=3e4;class c{connectionManager;onDisconnected;bindings=new Map;constructor(n,i){this.connectionManager=n,this.onDisconnected=i}async bind(n,i){if(this.bindings.has(n))throw new Error(`Session ${n} is already bound to a connection`);const e=await this.connectWithTimeout(i),t=[],s=e.onDisconnected(()=>{this.removeBinding(n),this.onDisconnected(n)});return t.push(s),this.bindings.set(n,{sessionId:n,handle:e,subscriptions:t}),e}getHandle(n){return this.bindings.get(n)?.handle}unbind(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e();i.handle.disconnect()}}unbindAll(){const n=[...this.bindings.keys()];for(const i of n)this.unbind(i)}connectWithTimeout(n){return new Promise((i,e)=>{let t=!1;const s=setTimeout(()=>{t||(t=!0,e(new Error("Connection bind timeout after 30000ms")))},3e4);this.connectionManager.connect({agentId:n.agentId,apiKey:n.apiKey,url:n.wsUrl,clientType:n.clientType,capabilities:["agent_invoke"],adapterHint:`${n.clientType}/base`},{maxRetries:0}).then(o=>{t?o.disconnect():(t=!0,clearTimeout(s),i(o))}).catch(o=>{t||(t=!0,clearTimeout(s),e(o))})})}removeBinding(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e()}}}export{c as ConnectionBindingImpl};
1
+ const a=3e4;class c{connectionManager;onDisconnected;bindings=new Map;constructor(n,i){this.connectionManager=n,this.onDisconnected=i}async bind(n,i){if(this.bindings.has(n))throw new Error(`Session ${n} is already bound to a connection`);const e=await this.connectWithTimeout(i),t=[],s=e.onDisconnected(()=>{this.removeBinding(n),this.onDisconnected(n)});return t.push(s),this.bindings.set(n,{sessionId:n,handle:e,subscriptions:t}),e}getHandle(n){return this.bindings.get(n)?.handle}unbind(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e();i.handle.disconnect()}}unbindAll(){const n=[...this.bindings.keys()];for(const i of n)this.unbind(i)}connectWithTimeout(n){return new Promise((i,e)=>{let t=!1;const s=setTimeout(()=>{t||(t=!0,e(new Error("Connection bind timeout after 30000ms")))},3e4);this.connectionManager.connect({agentId:n.agentId,apiKey:n.apiKey,url:n.wsUrl,clientType:n.clientType,capabilities:["agent_invoke"],adapterHint:`${n.clientType}/base`},{maxRetries:0}).then(o=>{t?o.disconnect():(t=!0,clearTimeout(s),i(o))}).catch(o=>{t||(t=!0,clearTimeout(s),e(o))})})}removeBinding(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e()}}}export{c as ConnectionBindingImpl};
@@ -1 +1 @@
1
- function a(t){const o=new Set([`http://127.0.0.1:${t.serverPort}`,`http://localhost:${t.serverPort}`,...t.allowedOrigins]),e=new Set([`127.0.0.1:${t.serverPort}`,`localhost:${t.serverPort}`,...t.allowedHosts]);return{validateRequest(s){const r=i(s,o);if(!r.ok)return r;const n=l(s,e);return n.ok?{ok:!0}:n}}}function i(t,o){const e=t.headers.origin;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${e}`}:{ok:!0}}function l(t,o){const e=t.headers.host;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${e}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
1
+ function a(e){const t=new Set([`http://127.0.0.1:${e.serverPort}`,`http://localhost:${e.serverPort}`,...e.allowedOrigins]),o=new Set([`127.0.0.1:${e.serverPort}`,`localhost:${e.serverPort}`,...e.allowedHosts]);return{validateRequest(s){const r=i(s,t);if(!r.ok)return r;const n=l(s,o);return n.ok?{ok:!0}:n}}}function i(e,t){const o=e.headers.origin;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${o}`}:{ok:!0}}function l(e,t){const o=e.headers.host;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${o}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
@@ -1 +1 @@
1
- import{toolCallToInvoke as i}from"../../core/mcp/tools.js";import{ToolRegistryImpl as l}from"./tool-registry.js";import{validateToolArgs as a}from"./tool-schemas.js";import{isEventTool as p,executeEventTool as d}from"./event-tool-executor.js";class y{registry;constructor(){this.registry=new l}async execute(t,e,r,n){if(!this.registry.hasTool(e))return this.errorResult(`\u672A\u77E5\u5DE5\u5177: ${e}`);const s=a(e,r);if(!s.valid)return this.errorResult(`\u53C2\u6570\u6821\u9A8C\u5931\u8D25: ${s.error}`);if(t.status!=="ready")return this.errorResult(`\u8FDE\u63A5\u4E0D\u53EF\u7528: \u5F53\u524D\u72B6\u6001\u4E3A ${t.status}`);if(p(e))return this.executeEventTool(t,e,r);const o=i(e,r);try{const u=await t.agentInvoke(o.action,o.params,n);return this.normalizeResult(u)}catch(u){const c=u instanceof Error?u.message:String(u);return c.toLowerCase().includes("timeout")?this.errorResult(`\u8C03\u7528\u8D85\u65F6: ${c}`):this.errorResult(`\u8C03\u7528\u5931\u8D25: ${c}`)}}normalizeResult(t){if(t==null||typeof t!="object")return this.successResult(t??null);const e=t,r=typeof e.code=="number"?e.code:0;if(r===0){const s="data"in e?e.data:null;return this.successResult(s??null)}const n=typeof e.msg=="string"?e.msg:"\u672A\u77E5\u9519\u8BEF";return this.errorResult(`\u4E0A\u6E38\u9519\u8BEF [code=${r}]: ${n}`)}successResult(t){return{content:[{type:"text",text:JSON.stringify(t)}],isError:!1}}errorResult(t){return{content:[{type:"text",text:t}],isError:!0}}async executeEventTool(t,e,r){return e==="grix_access_control"?this.executeAccessControl(t,r):d(t,e,r)}async executeAccessControl(t,e){const r=String(e.action??""),n={pair_approve:"pair_approve",pair_deny:"pair_deny",allow_sender:"sender_allow",remove_sender:"sender_remove",set_policy:"policy_set"}[r];if(!n)return this.errorResult(`\u672A\u77E5 access_control action: ${r}`);const s={};e.code!=null&&(s.code=e.code),e.sender_id!=null&&(s.sender_id=e.sender_id),e.policy!=null&&(s.policy=e.policy);try{const o=await t.agentInvoke("claude_access_control",{verb:n,payload:s},3e4);return this.successResult(o)}catch(o){const u=o instanceof Error?o.message:String(o);return this.errorResult(`access_control \u8C03\u7528\u5931\u8D25: ${u}`)}}}export{y as ToolExecutorImpl};
1
+ import{toolCallToInvoke as i}from"../../core/mcp/tools.js";import{ToolRegistryImpl as l}from"./tool-registry.js";import{validateToolArgs as a}from"./tool-schemas.js";import{isEventTool as p,executeEventTool as d}from"./event-tool-executor.js";class y{registry;constructor(){this.registry=new l}async execute(r,e,t,n){if(!this.registry.hasTool(e))return this.errorResult(`\u672A\u77E5\u5DE5\u5177: ${e}`);const s=a(e,t);if(!s.valid)return this.errorResult(`\u53C2\u6570\u6821\u9A8C\u5931\u8D25: ${s.error}`);if(r.status!=="ready")return this.errorResult(`\u8FDE\u63A5\u4E0D\u53EF\u7528: \u5F53\u524D\u72B6\u6001\u4E3A ${r.status}`);if(p(e))return this.executeEventTool(r,e,t);const o=i(e,t);try{const u=await r.agentInvoke(o.action,o.params,n);return this.normalizeResult(u)}catch(u){const c=u instanceof Error?u.message:String(u);return c.toLowerCase().includes("timeout")?this.errorResult(`\u8C03\u7528\u8D85\u65F6: ${c}`):this.errorResult(`\u8C03\u7528\u5931\u8D25: ${c}`)}}normalizeResult(r){if(r==null||typeof r!="object")return this.successResult(r??null);const e=r,t=typeof e.code=="number"?e.code:0;if(t===0){const s="data"in e?e.data:null;return this.successResult(s??null)}const n=typeof e.msg=="string"?e.msg:"\u672A\u77E5\u9519\u8BEF";return this.errorResult(`\u4E0A\u6E38\u9519\u8BEF [code=${t}]: ${n}`)}successResult(r){return{content:[{type:"text",text:JSON.stringify(r)}],isError:!1}}errorResult(r){return{content:[{type:"text",text:r}],isError:!0}}async executeEventTool(r,e,t){return e==="grix_access_control"?this.executeAccessControl(r,t):d(r,e,t)}async executeAccessControl(r,e){const t=String(e.action??""),n={pair_approve:"pair_approve",pair_deny:"pair_deny",allow_sender:"sender_allow",remove_sender:"sender_remove",set_policy:"policy_set"}[t];if(!n)return this.errorResult(`\u672A\u77E5 access_control action: ${t}`);const s={};e.code!=null&&(s.code=e.code),e.sender_id!=null&&(s.sender_id=e.sender_id),e.policy!=null&&(s.policy=e.policy);try{const o=await r.agentInvoke("claude_access_control",{verb:n,payload:s},3e4);return this.successResult(o)}catch(o){const u=o instanceof Error?o.message:String(o);return this.errorResult(`access_control \u8C03\u7528\u5931\u8D25: ${u}`)}}}export{y as ToolExecutorImpl};
@@ -1 +1 @@
1
- import{TOOLS as s,EVENT_TOOLS as t}from"../../core/mcp/tools.js";const e=new Set(["grix_query","grix_group","grix_message_send","grix_message_unsend","grix_admin"]),r=new Set(["grix_reply","grix_complete","grix_event_ack","grix_composing","grix_access_control","grix_status"]);class a{tools;toolMap;constructor(){this.tools=[...s.filter(o=>e.has(o.name)),...t.filter(o=>r.has(o.name))],this.toolMap=new Map(this.tools.map(o=>[o.name,o]))}getTools(){return this.tools}getTool(o){return this.toolMap.get(o)}hasTool(o){return this.toolMap.has(o)}}export{a as ToolRegistryImpl};
1
+ import{TOOLS as o,EVENT_TOOLS as s}from"../../core/mcp/tools.js";const e=new Set(["grix_query","grix_group","grix_message_send","grix_message_unsend","grix_admin"]),r=new Set(["grix_reply","grix_complete","grix_event_ack","grix_composing","grix_access_control","grix_status"]);class a{tools;toolMap;constructor(){this.tools=[...o.filter(t=>e.has(t.name)),...s.filter(t=>r.has(t.name))],this.toolMap=new Map(this.tools.map(t=>[t.name,t]))}getTools(){return this.tools}getTool(t){return this.toolMap.get(t)}hasTool(t){return this.toolMap.has(t)}}export{a as ToolRegistryImpl};
@@ -1 +1 @@
1
- const o={required:["action"],properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},id:{type:"string"},keyword:{type:"string",maxLength:200},limit:{type:"integer",minimum:1,maximum:100},offset:{type:"integer",minimum:0},sessionId:{type:"string"},beforeId:{type:"string"}}},a={required:["action"],properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string",maxLength:128},memberIds:{type:"array",items:{type:"string"},maxItems:100},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer"},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean"}}},p={required:["sessionId","content"],properties:{sessionId:{type:"string"},content:{type:"string",maxLength:1e4},msgType:{type:"integer"},quotedMessageId:{type:"string"},threadId:{type:"string"}}},m={required:["sessionId","msgId"],properties:{sessionId:{type:"string"},msgId:{type:"string"}}},g={required:["action"],properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},agentId:{type:"string"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"integer"}}},y={required:["session_id","text"],properties:{event_id:{type:"string"},session_id:{type:"string"},text:{type:"string",maxLength:5e4},quoted_message_id:{type:"string"},is_final:{type:"boolean"}}},d={required:["event_id","status"],properties:{event_id:{type:"string"},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string",maxLength:500}}},c={required:["event_id"],properties:{event_id:{type:"string"},session_id:{type:"string"}}},l={required:["session_id","active"],properties:{session_id:{type:"string"},active:{type:"boolean"},event_id:{type:"string"}}},_={required:["action"],properties:{action:{type:"string",enum:["pair_approve","pair_deny","allow_sender","remove_sender","set_policy"]},code:{type:"string"},sender_id:{type:"string"},policy:{type:"string",enum:["allowlist","open","disabled"]}}},f={required:[],properties:{}},C={grix_query:o,grix_group:a,grix_message_send:p,grix_message_unsend:m,grix_admin:g,grix_reply:y,grix_complete:d,grix_event_ack:c,grix_composing:l,grix_access_control:_,grix_status:f};function B(u,t){const e=C[u];if(!e)return{valid:!1,error:`\u672A\u77E5\u5DE5\u5177: ${u}`};for(const i of e.required)if(t[i]===void 0||t[i]===null)return{valid:!1,error:`\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570: ${i}`};for(const[i,r]of Object.entries(t)){if(r==null)continue;const n=e.properties[i];if(!n)continue;const s=$(i,r,n);if(s)return{valid:!1,error:s}}return{valid:!0}}function $(u,t,e){switch(e.type){case"string":if(typeof t!="string")return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxLength!==void 0&&t.length>e.maxLength)return`\u53C2\u6570 ${u} \u8D85\u8FC7\u6700\u5927\u957F\u5EA6 ${e.maxLength}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${u} \u503C "${t}" \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"integer":if(typeof t!="number"||!Number.isInteger(t))return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof t=="number"?"\u6D6E\u70B9\u6570":typeof t}`;if(e.minimum!==void 0&&t<e.minimum)return`\u53C2\u6570 ${u} \u503C ${t} \u5C0F\u4E8E\u6700\u5C0F\u503C ${e.minimum}`;if(e.maximum!==void 0&&t>e.maximum)return`\u53C2\u6570 ${u} \u503C ${t} \u5927\u4E8E\u6700\u5927\u503C ${e.maximum}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${u} \u503C ${t} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"boolean":if(typeof t!="boolean")return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B boolean\uFF0C\u5B9E\u9645 ${typeof t}`;break;case"array":if(!Array.isArray(t))return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B array\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxItems!==void 0&&t.length>e.maxItems)return`\u53C2\u6570 ${u} \u8D85\u8FC7\u6700\u5927\u5143\u7D20\u6570 ${e.maxItems}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.items)for(let i=0;i<t.length;i++){const r=t[i];if(e.items.type==="string"&&typeof r!="string")return`\u53C2\u6570 ${u}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof r}`;if(e.items.type==="integer"){if(typeof r!="number"||!Number.isInteger(r))return`\u53C2\u6570 ${u}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof r}`;if(e.items.enum&&!e.items.enum.includes(r))return`\u53C2\u6570 ${u}[${i}] \u503C ${r} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.items.enum.join(", ")}]`}}break}}export{B as validateToolArgs};
1
+ const o={required:["action"],properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},id:{type:"string"},keyword:{type:"string",maxLength:200},limit:{type:"integer",minimum:1,maximum:100},offset:{type:"integer",minimum:0},sessionId:{type:"string"},beforeId:{type:"string"}}},a={required:["action"],properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string",maxLength:128},memberIds:{type:"array",items:{type:"string"},maxItems:100},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer"},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean"}}},p={required:["sessionId","content"],properties:{sessionId:{type:"string"},content:{type:"string",maxLength:1e4},msgType:{type:"integer"},quotedMessageId:{type:"string"},threadId:{type:"string"}}},m={required:["sessionId","msgId"],properties:{sessionId:{type:"string"},msgId:{type:"string"}}},g={required:["action"],properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},agentId:{type:"string"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"integer"}}},y={required:["session_id","text"],properties:{event_id:{type:"string"},session_id:{type:"string"},text:{type:"string",maxLength:5e4},quoted_message_id:{type:"string"},is_final:{type:"boolean"}}},d={required:["event_id","status"],properties:{event_id:{type:"string"},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string",maxLength:500}}},c={required:["event_id"],properties:{event_id:{type:"string"},session_id:{type:"string"}}},l={required:["session_id","active"],properties:{session_id:{type:"string"},active:{type:"boolean"},event_id:{type:"string"}}},_={required:["action"],properties:{action:{type:"string",enum:["pair_approve","pair_deny","allow_sender","remove_sender","set_policy"]},code:{type:"string"},sender_id:{type:"string"},policy:{type:"string",enum:["allowlist","open","disabled"]}}},f={required:[],properties:{}},C={grix_query:o,grix_group:a,grix_message_send:p,grix_message_unsend:m,grix_admin:g,grix_reply:y,grix_complete:d,grix_event_ack:c,grix_composing:l,grix_access_control:_,grix_status:f};function B(r,t){const e=C[r];if(!e)return{valid:!1,error:`\u672A\u77E5\u5DE5\u5177: ${r}`};for(const i of e.required)if(t[i]===void 0||t[i]===null)return{valid:!1,error:`\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570: ${i}`};for(const[i,u]of Object.entries(t)){if(u==null)continue;const n=e.properties[i];if(!n)continue;const s=$(i,u,n);if(s)return{valid:!1,error:s}}return{valid:!0}}function $(r,t,e){switch(e.type){case"string":if(typeof t!="string")return`\u53C2\u6570 ${r} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxLength!==void 0&&t.length>e.maxLength)return`\u53C2\u6570 ${r} \u8D85\u8FC7\u6700\u5927\u957F\u5EA6 ${e.maxLength}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${r} \u503C "${t}" \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"integer":if(typeof t!="number"||!Number.isInteger(t))return`\u53C2\u6570 ${r} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof t=="number"?"\u6D6E\u70B9\u6570":typeof t}`;if(e.minimum!==void 0&&t<e.minimum)return`\u53C2\u6570 ${r} \u503C ${t} \u5C0F\u4E8E\u6700\u5C0F\u503C ${e.minimum}`;if(e.maximum!==void 0&&t>e.maximum)return`\u53C2\u6570 ${r} \u503C ${t} \u5927\u4E8E\u6700\u5927\u503C ${e.maximum}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${r} \u503C ${t} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"boolean":if(typeof t!="boolean")return`\u53C2\u6570 ${r} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B boolean\uFF0C\u5B9E\u9645 ${typeof t}`;break;case"array":if(!Array.isArray(t))return`\u53C2\u6570 ${r} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B array\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxItems!==void 0&&t.length>e.maxItems)return`\u53C2\u6570 ${r} \u8D85\u8FC7\u6700\u5927\u5143\u7D20\u6570 ${e.maxItems}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.items)for(let i=0;i<t.length;i++){const u=t[i];if(e.items.type==="string"&&typeof u!="string")return`\u53C2\u6570 ${r}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof u}`;if(e.items.type==="integer"){if(typeof u!="number"||!Number.isInteger(u))return`\u53C2\u6570 ${r}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof u}`;if(e.items.enum&&!e.items.enum.includes(u))return`\u53C2\u6570 ${r}[${i}] \u503C ${u} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.items.enum.join(", ")}]`}}break}}export{B as validateToolArgs};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grix-connector",
3
- "version": "3.22.0",
3
+ "version": "3.23.0",
4
4
  "description": "Connect local AI coding agents (Claude, Codex, Gemini, Qwen, DeepSeek, Cursor, OpenCode, Pi, OpenHuman, Reasonix) to the Grix scheduling platform. Also serves as an OpenClaw plugin for Grix channel transport.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",