grix-connector 3.10.0 → 3.10.1

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,2 +1,2 @@
1
- import{readdirSync as y,readFileSync as g,existsSync as d,statSync as S}from"node:fs";import{dirname as w,join as r,resolve as b}from"node:path";import{homedir as F}from"node:os";import{log as O}from"../../core/log/index.js";function D(t){const e=t.trim();if(!e.startsWith("---"))return{name:"",description:""};const i=e.indexOf("---",3);if(i===-1)return{name:"",description:""};const n=e.slice(3,i).trim();let s="",c="",f;for(const a of n.split(`
2
- `)){const u=a.indexOf(":");if(u===-1)continue;const p=a.slice(0,u).trim();let o=a.slice(u+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),p==="name"?s=o:p==="description"?c=o:p==="trigger"&&(f=o)}return{name:s,description:c,trigger:f}}function W(t,e,i){if(!d(t))return[];const n=[];try{for(const s of y(t,{withFileTypes:!0})){const c=r(t,s.name);if(!j(s,c)||s.name.startsWith("."))continue;const f=r(c,"SKILL.md");if(d(f))try{const a=g(f,"utf-8"),u=D(a);u.name&&n.push({name:u.name,description:u.description,trigger:u.trigger,source:e,pluginName:i})}catch{}}}catch{}return n}function l(t,e,i){if(!d(t))return[];const n=i?.maxDepth??6,s=i?.includeHiddenDirs??!1,c=[],f=(a,u)=>{if(u>n)return;let p;try{p=y(a,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(const o of p){const m=r(a,o.name);if(!j(o,m)||!s&&o.name.startsWith("."))continue;const h=r(m,"SKILL.md");if(d(h))try{const x=g(h,"utf-8"),k=D(x);k.name&&c.push({name:k.name,description:k.description,trigger:k.trigger,source:e,pluginName:i?.pluginName})}catch{}f(m,u+1)}};return f(t,0),c}function j(t,e){if(t.isDirectory())return!0;if(!t.isSymbolicLink())return!1;try{return S(e).isDirectory()}catch{return!1}}function L(t){const e=[],i=new Set;for(const n of t){const s=n.name.trim().toLowerCase();i.has(s)||(i.add(s),e.push(n))}return e}function v(t){const e=[],i=new Set;let n=b(t);for(;;){i.has(n)||(e.push(n),i.add(n));const s=w(n);if(s===n)break;n=s}return e}function H(t){const e=r(t,".claude","plugins","installed_plugins.json");if(!d(e))return[];const i=[];try{const n=g(e,"utf-8"),c=JSON.parse(n)?.plugins;if(!c||typeof c!="object")return i;for(const[f,a]of Object.entries(c))if(Array.isArray(a))for(const u of a){const p=u?.installPath;if(!p||!d(p))continue;const o=r(p,"skills"),m=f.split("@")[0],h=W(o,"plugin",m);i.push(...h)}}catch{}return i}function P(t,e){return t==="claude"?"claude":t==="codex"?"codex":t==="pi"?"pi":e==="kiro"?"kiro":"gemini"}function C(t){const e=[],i=t.homeDir??F();switch(t.mode){case"claude":{const s=r(i,".claude","skills");e.push(...l(s,"global")),t.projectDir&&e.push(...l(r(t.projectDir,".claude","skills"),"project")),e.push(...H(i));break}case"codex":{const s=process.env.CODEX_HOME?.trim()||r(i,".codex");if(t.projectDir)for(const c of v(t.projectDir))e.push(...l(r(c,".agents","skills"),"project")),e.push(...l(r(c,".codex","skills"),"project"));e.push(...l(r(i,".agents","skills"),"codex")),e.push(...l(r(s,"skills"),"codex")),e.push(...l(r(s,"skills",".system"),"codex"));break}case"gemini":{e.push(...l(r(i,".gemini","skills"),"gemini")),e.push(...l(r(i,".agents","skills"),"gemini")),t.projectDir&&(e.push(...l(r(t.projectDir,".gemini","skills"),"project")),e.push(...l(r(t.projectDir,".agents","skills"),"project")));break}case"pi":{e.push(...l(r(i,".pi","agent","skills"),"pi")),t.projectDir&&e.push(...l(r(t.projectDir,".pi","skills"),"project"));break}case"kiro":{e.push(...l(r(i,".kiro","skills"),"kiro")),t.projectDir&&e.push(...l(r(t.projectDir,".kiro","skills"),"project"));break}}const n=L(e);return O.info("skill-scanner",`Scanned skills: mode=${t.mode} count=${n.length}`),n}export{L as dedupeSkills,D as parseSkillFrontmatter,P as resolveSkillScanMode,l as scanSkillTree,C as scanSkills};
1
+ import{readdirSync as y,readFileSync as g,existsSync as d,statSync as w}from"node:fs";import{dirname as b,join as r,resolve as F}from"node:path";import{homedir as O}from"node:os";import{log as W}from"../../core/log/index.js";function D(t){const e=t.trim();if(!e.startsWith("---"))return{name:"",description:""};const i=e.indexOf("---",3);if(i===-1)return{name:"",description:""};const n=e.slice(3,i).trim();let s="",c="",a;for(const f of n.split(`
2
+ `)){const u=f.indexOf(":");if(u===-1)continue;const p=f.slice(0,u).trim();let o=f.slice(u+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),p==="name"?s=o:p==="description"?c=o:p==="trigger"&&(a=o)}return{name:s,description:c,trigger:a}}function L(t,e,i){if(!d(t))return[];const n=[];try{for(const s of y(t,{withFileTypes:!0})){const c=r(t,s.name);if(!x(s,c)||s.name.startsWith("."))continue;const a=r(c,"SKILL.md");if(d(a))try{const f=g(a,"utf-8"),u=D(f);u.name&&n.push({name:u.name,description:u.description,trigger:u.trigger,source:e,pluginName:i,filePath:a})}catch{}}}catch{}return n}function l(t,e,i){if(!d(t))return[];const n=i?.maxDepth??6,s=i?.includeHiddenDirs??!1,c=[],a=(f,u)=>{if(u>n)return;let p;try{p=y(f,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(const o of p){const m=r(f,o.name);if(!x(o,m)||!s&&o.name.startsWith("."))continue;const h=r(m,"SKILL.md");if(d(h))try{const S=g(h,"utf-8"),k=D(S);k.name&&c.push({name:k.name,description:k.description,trigger:k.trigger,source:e,pluginName:i?.pluginName,filePath:h})}catch{}a(m,u+1)}};return a(t,0),c}function j(t){return t.map(e=>({...e,managed:!0}))}function x(t,e){if(t.isDirectory())return!0;if(!t.isSymbolicLink())return!1;try{return w(e).isDirectory()}catch{return!1}}function P(t){const e=[],i=new Set;for(const n of t){const s=n.name.trim().toLowerCase();i.has(s)||(i.add(s),e.push(n))}return e}function v(t){const e=[],i=new Set;let n=F(t);for(;;){i.has(n)||(e.push(n),i.add(n));const s=b(n);if(s===n)break;n=s}return e}function H(t){const e=r(t,".claude","plugins","installed_plugins.json");if(!d(e))return[];const i=[];try{const n=g(e,"utf-8"),c=JSON.parse(n)?.plugins;if(!c||typeof c!="object")return i;for(const[a,f]of Object.entries(c))if(Array.isArray(f))for(const u of f){const p=u?.installPath;if(!p||!d(p))continue;const o=r(p,"skills"),m=a.split("@")[0],h=j(L(o,"plugin",m));i.push(...h)}}catch{}return i}function M(t,e){return t==="claude"?"claude":t==="codex"?"codex":t==="pi"?"pi":e==="kiro"?"kiro":"gemini"}function C(t){const e=[],i=t.homeDir??O();switch(t.mode){case"claude":{const s=r(i,".claude","skills");e.push(...l(s,"global")),t.projectDir&&e.push(...l(r(t.projectDir,".claude","skills"),"project")),e.push(...H(i));break}case"codex":{const s=process.env.CODEX_HOME?.trim()||r(i,".codex");if(t.projectDir)for(const c of v(t.projectDir))e.push(...l(r(c,".agents","skills"),"project")),e.push(...l(r(c,".codex","skills"),"project"));e.push(...l(r(i,".agents","skills"),"codex")),e.push(...l(r(s,"skills"),"codex")),e.push(...j(l(r(s,"skills",".system"),"codex")));break}case"gemini":{e.push(...l(r(i,".gemini","skills"),"gemini")),e.push(...l(r(i,".agents","skills"),"gemini")),t.projectDir&&(e.push(...l(r(t.projectDir,".gemini","skills"),"project")),e.push(...l(r(t.projectDir,".agents","skills"),"project")));break}case"pi":{e.push(...l(r(i,".pi","agent","skills"),"pi")),t.projectDir&&e.push(...l(r(t.projectDir,".pi","skills"),"project"));break}case"kiro":{e.push(...l(r(i,".kiro","skills"),"kiro")),t.projectDir&&e.push(...l(r(t.projectDir,".kiro","skills"),"project"));break}}const n=P(e);return W.info("skill-scanner",`Scanned skills: mode=${t.mode} count=${n.length}`),n}export{P as dedupeSkills,j as markManaged,D as parseSkillFrontmatter,M as resolveSkillScanMode,l as scanSkillTree,C as scanSkills};
@@ -1,16 +1,16 @@
1
- import P from"node:path";import{realpath as K,stat as L}from"node:fs/promises";import{tmpdir as j}from"node:os";import{randomUUID as M}from"node:crypto";import{ConnectionManager as V}from"../core/aibot/index.js";import{ClaudeAdapter as T}from"../adapter/claude/index.js";import{CodexAdapter as J}from"../adapter/codex/index.js";import{PiAdapter as Y}from"../adapter/pi/index.js";import{AcpAdapter as A}from"../adapter/acp/index.js";import{OpenHumanAdapter as X}from"../adapter/openhuman/index.js";import{CursorAdapter as H}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as O}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as Z}from"../adapter/opencode/index.js";import{AgyAdapter as U}from"../adapter/agy/index.js";import{getCachedAgyModels as ee}from"../adapter/agy/model-list.js";import{getCachedAgyQuotaInfo as te}from"../adapter/agy/quota.js";import{LOCAL_ACTION_ERROR_CODES as x,LOCAL_ACTION_TYPES as b,SESSION_CONTROL_ERROR_CODES as g,SESSION_CONTROL_VERBS as p,SESSION_MODE_IDS as C}from"../adapter/claude/protocol-contract.js";import{parseClaudeSessionUsage as ie}from"../adapter/claude/usage-parser.js";import{resolveSkillScanMode as ne}from"../adapter/claude/skill-scanner.js";import{buildReportedSkills as se}from"../default-skills/index.js";import{fetchAvailableModels as D,getCachedModels as Q,readSettingsEnv as oe}from"../adapter/claude/model-list.js";import{parseAcpSessionUsage as re}from"../adapter/acp/usage-parser.js";import{applyProxyEnv as ae,getProxyManager as de,relayHostsForClientType as ce,buildGatewayRoute as le}from"../core/proxy/index.js";import{buildProviderEnv as ue}from"../core/config/provider-env.js";import{sweepNativeProviderResidue as he}from"./native-provider-sweep.js";import{parseCodexSessionUsage as ge}from"../adapter/codex/usage-parser.js";import{readCodexProviderSettings as me}from"../adapter/codex/codex-trust.js";import{resolveKimiProviderSettings as pe}from"../core/provider-quota/index.js";import{scanCodexSessions as fe}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as _e}from"../adapter/claude/session-scanner.js";import{reasonixStampFromSessionId as ve,resolveAcpAgentTypes as Se,scanAcpSessions as be,scanReasonixSessionTitles as we}from"../adapter/acp/session-scanner.js";import{scanPiSessions as Ce}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as Ae}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as ke}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as Re}from"../adapter/opencode/session-scanner.js";import{parsePiSessionUsage as Ee}from"../adapter/pi/usage-parser.js";import{SessionScanCache as k,resolveCodexLeafDirs as $e,resolveClaudeLeafDirs as ye,resolveAcpLeafDirs as Te,resolvePiLeafDirs as xe,resolveCodeWhaleLeafDirs as Pe,resolveCursorLeafDirs as Ie,resolveOpenCodeLeafDirs as Le,resolveReasonixLeafDirs as Me}from"./session-scan-cache.js";import{log as u,ConversationLog as He,AgentApiPacketLog as De,BridgeEventLog as Qe}from"../core/log/index.js";import{RevokeHandler as Be}from"./revoke-handler.js";import{AdapterPool as Fe,PoolFullError as Oe}from"./adapter-pool.js";import{parseSessionControlCommand as Ue,handleSessionControlCommand as q,handleSessionControlLocalAction as qe}from"./session-controller.js";import{isOpenSessionDirectiveMessage as We}from"../core/protocol/interaction-parser.js";import{handleAcpSetModel as W,handleAcpSetMode as N,resolveAcpInitialDefaults as Ne}from"./acp-toolbar-persist.js";import{SessionBindingStore as ze}from"../core/persistence/session-binding-store.js";import{handleFileListAction as Ge,handleCreateFolderAction as Ke,serveLocalFile as je,realHomeDir as z}from"../core/files/index.js";import{getMachineName as Ve}from"../core/util/index.js";import{uploadReplyFileToAgentMedia as Je}from"../core/protocol/agent-api-media.js";import{ActiveEventStore as Ye}from"../core/persistence/active-event-store.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as Xe,applyConnectorRuntimeConfigPatch as Ze,extractConnectorRuntimeConfigPatch as et}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as tt,SendController as it}from"./send-controller.js";import{queryProviderQuota as nt}from"../core/provider-quota/index.js";import{queryKiroQuota as B}from"../core/provider-quota/kiro.js";import{buildToolUseCard as $,buildToolResultCard as y,buildLocalGrixCardLink as st}from"./tool-card-utils.js";import{DeferredEventManager as ot}from"./deferred-events.js";import{buildAgentProbeResult as rt,PROBE_CACHE_TTL_STATIC_MS as at,PROBE_CACHE_TTL_FULL_MS as dt}from"./probe-helper.js";const ct=600*1e3,lt=60*1e3,G=30*1e3,ut=10*1e3,I=new Set(["claude","acp","agy","cursor","codex"]),ht=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp"]),F=3;class pi{config;name;aibotHandle;aibotConfig;pool;stopped=!1;revokeHandler=new Be;sessionBindings=new Map;deferredMgr;sendCtrl=new it(Xe);bindingStore;globalConfigStore;upgradeTrigger=null;agentDeletedHandler=null;shareSetHandler=null;skillSyncHandler=null;providerConfigHandler=null;agentProfile={agentName:"",introduction:""};activeEventStore;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";conversationLog=null;packetLog=null;providerQuotaTimer=null;eventSessionIndex=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;sessionScanCache;reasonixTitleScan=null;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const o=Number(e);return o>0&&Date.now()-o<=lt}async maybeQueryProviderQuota(){if(this.config.aibot.clientType==="kiro"){if(this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&this.cachedProviderQuota)return this.cachedProviderQuota;try{const t=await B();return this.cachedProviderQuota=t,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[provider-quota] kiro queried: success=${t.success}`+(t.balance?` balance=${t.balance.remaining} ${t.balance.unit}`:"")+(t.planName?` plan=${t.planName}`:"")+(t.error?` error=${t.error}`:"")),t}catch(t){return u.warn(this.name,`[provider-quota] kiro query failed: ${t instanceof Error?t.message:String(t)}`),null}}let e=this.config.providerBaseUrl,o=this.config.providerApiKey;if((!e||!o)&&(this.config.adapterType??"acp")==="claude"){const t=oe();e||(e=(t.ANTHROPIC_BASE_URL??"").trim()||void 0),o||(o=(t.ANTHROPIC_API_KEY??"").trim()||(t.ANTHROPIC_AUTH_TOKEN??"").trim()||void 0)}if((!e||!o)&&(this.config.adapterType??"acp")==="codex"){const t=me();!e&&t.baseUrl&&(e=t.baseUrl),!o&&t.apiKey&&(o=t.apiKey)}if((!e||!o)&&(this.config.adapterType??"acp")==="acp"&&this.config.aibot.clientType==="kimi"){const t=await pe();!e&&t.baseUrl&&(e=t.baseUrl),!o&&t.apiKey&&(o=t.apiKey)}if(!e||!o)return null;if(this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&this.cachedProviderQuota)return this.cachedProviderQuota;try{const t=await nt(e,o);return this.cachedProviderQuota=t,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[provider-quota] queried: provider=${t.provider} success=${t.success}`+(t.tiers.length>0?` tiers=${t.tiers.map(s=>`${s.name}=${s.usedPercent}%`).join(",")}`:"")+(t.balance?` balance=${t.balance.remaining} ${t.balance.unit}`:"")+(t.error?` error=${t.error}`:"")),t}catch(t){return u.warn(this.name,`[provider-quota] query failed: ${t instanceof Error?t.message:String(t)}`),null}}startProviderQuotaTimer(){this.providerQuotaTimer||(this.providerQuotaTimer=setInterval(()=>{if(this.stopped){this.stopProviderQuotaTimer();return}this.refreshAndPushProviderQuota().catch(()=>{})},G),u.info(this.name,`[provider-quota-timer] started (interval=${G}ms)`))}stopProviderQuotaTimer(){this.providerQuotaTimer&&(clearInterval(this.providerQuotaTimer),this.providerQuotaTimer=null,u.info(this.name,"[provider-quota-timer] stopped"))}async refreshAndPushProviderQuota(){try{let e;this.config.aibot.clientType==="kiro"?(e=await B(),this.cachedProviderQuota=e,this.cachedProviderQuotaSampledAtMs=Date.now()):e=await this.maybeQueryProviderQuota(),e?.success&&this.pushProviderQuotaToBindings(e)}catch{}}pushProviderQuotaToBindings(e){const o=this.providerQuotaToRateLimits(e);for(const[t,s]of this.sessionBindings.entries()){if(!s)continue;const i={provider_quota:e};o&&(i.rate_limits=o);const n=this.cachedAcpContextWindow;n&&("usedPercentage"in n?i.context_window={usedPercentage:n.usedPercentage,remainingPercentage:100-n.usedPercentage}:i.context_window=n),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:s,meta:i})}}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,o=this.cachedCodexContextWindow,t=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:o,tokenUsage:t,hasData:!!(e||o||t)}}getStatus(){const e=this.pool?.getStatus()??{total:0,ready:0,busy:0};return{name:this.name,agentId:this.config.aibot.agentId,alive:!this.stopped,busy:e.busy>0,exhausted:this.pool?[...this.pool.getAllSlots()].some(o=>o.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}hasPendingOrBackgroundWork(){return this.pool?.hasPendingOrBackgroundWork()??!1}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,u.info(this.name,"relay changed but agent is busy; adapters keep the old env until the next message (marked stale)"),!1;const e=[...this.pool.getAllSlots()];let o=0,t=!1;for(const s of e){if(this.hasPendingWork())return this.relayEnvStale=!0,u.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let i=!1;await this.pool.removeSlot(s.sessionId).catch(n=>{t=!0,i=!0,u.warn(this.name,`failed to recycle adapter slot ${s.sessionId} after relay change: ${n}`)}),i||(o+=1)}return o>0&&u.info(this.name,`recycled ${o} adapter slot(s) so the new Grix relay env takes effect`),t?(this.relayEnvStale=!0,!1):(this.relayEnvStale=!1,this.relayEnvSettledHandler?.(),!0)}setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}hasStaleRelayEnv(){return this.relayEnvStale}markRelayEnvStale(){this.relayEnvStale=!0}async probe(e={}){const o=e.conversation?"full":"static",t=e.conversation?dt:at;if(!e.fresh){const r=this.probeCache.get(o);if(r&&Date.now()-r.sampledAt<t)return{...r.result,cached:!0}}const s=this.config.adapterType??"acp",i=this.createAdapter(s,"__probe__"),n=e.conversation&&s==="acp"?()=>this.runAcpConversationProbe(i,e.timeoutMs??1e4):void 0;let a;try{a=await rt({adapter:i,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:s,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:n})}finally{i.stop().catch(()=>{})}return this.probeCache.set(o,{result:a,sampledAt:a.probed_at}),a}async runAcpConversationProbe(e,o){const t=Date.now(),s="__probe__",i=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,n=this.config.agent.cwd||j(),a=()=>Date.now()-t;try{await e.start()}catch(h){return{attempted:!0,ok:!1,latency_ms:a(),error:{code:"conversation_failed",message:`start failed: ${h instanceof Error?h.message:String(h)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:a(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof A)try{await e.bindSession(s,n)}catch{}let r=null;const d=new Promise(h=>{r=m=>{m===i&&h()},e.on("eventDone",r)});e.deliverInboundEvent({event_id:i,session_id:s,content:"ping",msg_id:i}),e.deliverStopEvent(i,s);let c=null;const l=await Promise.race([d.then(()=>!1),new Promise(h=>{c=setTimeout(()=>h(!0),o)})]);return c&&clearTimeout(c),r&&e.removeListener("eventDone",r),l?{attempted:!0,ok:!1,latency_ms:a(),error:{code:"conversation_timeout",message:`no eventDone within ${o}ms`}}:{attempted:!0,ok:!0,latency_ms:a()}}constructor(e,o){this.config=e,this.name=e.name;const t=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(tt[t]),this.aibotConfig={...e.aibot,...t==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","thread_compact","get_agent_global_config"]}:{}},e.eventQueue&&(this.aibotConfig.concurrency={max_concurrent:e.eventQueue.maxConcurrent,max_queued:e.eventQueue.maxQueued,queue_timeout_ms:e.eventQueue.queueTimeoutMs,cancelable_queued:e.eventQueue.cancelableQueued,cancelable_running:e.eventQueue.cancelableRunning}),this.conversationLog=e.logDir?new He(e.logDir):null,this.packetLog=e.logDir?new De(e.logDir):null,this.bindingStore=new ze(e.bindingsPath),this.bindingStore.load(),this.globalConfigStore=o??null,this.deferredMgr=new ot(this.name),this.activeEventStore=e.activeEventStorePath?new Ye(e.activeEventStorePath):null,t==="codex")this.sessionScanCache=new k(fe,$e);else if(t==="claude")this.sessionScanCache=new k(_e,ye);else if(t==="pi"){const s=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new k(()=>Ce(void 0,s),()=>xe(void 0,s))}else if(t==="codewhale")this.sessionScanCache=new k(Ae,Pe);else if(t==="cursor")this.sessionScanCache=new k(ke,Ie);else if(t==="opencode")this.sessionScanCache=new k(Re,Le);else if(t==="agy")this.sessionScanCache=new k(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new k(we,Me));const s=Se(e.aibot.clientType);this.sessionScanCache=s?new k(()=>be(void 0,s),()=>Te(void 0,s)):new k(()=>[],()=>[])}}async start(){await he({agentName:this.name,adapterType:this.config.adapterType??"acp",command:this.config.agent.command,piConfigDir:this.config.agent.env?.PI_CODING_AGENT_DIR,hasProvider:!!this.config.agent.provider,boundCwds:[...this.bindingStore.entries()].map(([,o])=>String(o.cwd??""))}).then(o=>{o.length>0&&u.info(this.name,`restored native provider config after relay disable: ${o.join(", ")}`)}).catch(o=>{u.warn(this.name,`native provider residue sweep failed: ${o instanceof Error?o.message:String(o)}`)}),(this.config.adapterType??"acp")==="claude"&&(await D().catch(()=>{}),this.maybeQueryProviderQuota().catch(()=>{})),(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),await this.connectAibot(),this.sendCtrl.bind(this.aibotHandle);const e=this.config.adapterType??"acp";this.pool=new Fe({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},o=>{const t=this.createAdapter(e,o);return t instanceof A&&t.on("acpSessionReady",s=>{this.bindingStore.setAcpSessionId(o,s),this.sessionScanCache.invalidate()}),t},(o,t)=>{this.aibotHandle.sendEventAck({event_id:o,session_id:t,received_at:Date.now()})}),this.pool.setEventStateHandler((o,t,s,i)=>{u.info(this.name,`[queue-debug] send event_state session=${t} event=${o} state=${s} queue_pos=${i?.queue_position??""} queue_total=${i?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:o,session_id:t,state:s,content_preview:i?.content_preview,queue_position:i?.queue_position,queue_total:i?.queue_total,actions:i?.actions,reason:i?.reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(t),(s==="canceled"||s==="failed")&&(this.aibotHandle.sendEventResult({event_id:o,status:s==="canceled"?"canceled":"failed",msg:i?.reason,updated_at:Date.now()}),this.discardEventTrackingState(o))}),this.pool.setQueueComposingHandler((o,t,s)=>{this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:t,...t?{ttl_ms:3e4,ref_event_id:s}:{}})}),this.pool.setInternalErrorHandler(o=>{this.handleSessionInternalError(o).catch(t=>{u.error(this.name,`[recovery] handleSessionInternalError failed event=${o.eventId} session=${o.sessionId}: ${t instanceof Error?t.message:String(t)}`)})}),this.pool.setEventStartedHandler((o,t)=>{if(this.reportSessionSkills(t),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(t,"busy");const s=this.bindingStore.get(t);s?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"busy",cwd:s.cwd,meta:this.buildClaudeToolbarMeta(t)})}),this.pool.setEventDoneHandler((o,t)=>{const s=this.config.adapterType??"acp";if(s==="claude"){this.claudeWorkerStatus.set(t,"ready");const i=this.bindingStore.get(t);i?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i.cwd,meta:this.buildClaudeToolbarMeta(t)})}else if(s==="agy"){const i=this.bindingStore.get(t);if(i?.cwd){const n=this.buildAgyToolbarMeta(t),a=n?.available_models??[];u.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${t} model_id=${String(n?.model_id??"")} available_models=${a.length} meta_keys=${n?Object.keys(n).join(","):"<none>"}`),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i.cwd,meta:n})}else u.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${t}`)}}),this.pool.setSessionActivityHandler((o,t,s)=>{const i=this.selfDrivenSessions.has(o),n=this.selfDrivenLabels.get(o);t?(this.selfDrivenSessions.add(o),s&&this.selfDrivenLabels.set(o,s),this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(o),this.selfDrivenLabels.delete(o),i&&this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:!1})),(i!==t||t&&s!==void 0&&s!==n)&&this.pushQueueSnapshotForSession(o)}),this.pool.startIdleSweep(),u.info(this.name,`Ready (adapter: ${e}, poolMax: ${this.config.poolMaxSize??20})`)}async stop(){this.stopped=!0,this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer();const e=this.pool?.collectActiveEventIds()??[];e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const s of e)u.info(this.name,`Canceling active event on shutdown: ${s}`),this.sendEventResultWithCleanup(s,"canceled","process shutting down");e.length>0&&await new Promise(s=>setTimeout(s,100)),this.pool?.clearActiveEventsForShutdown();const o=this.deferredMgr.getAllDeferredEvents();for(const s of o)u.info(this.name,`Failing deferred event on shutdown: ${s.event_id}`),this.sendEventResultWithCleanup(s.event_id,"failed","process shutting down");const t=this.pool?.drainAllQueuedEvents()??[];for(const s of t)u.info(this.name,`Failing queued event on shutdown: ${s.event_id}`),this.sendEventResultWithCleanup(s.event_id,"failed","process shutting down");this.deferredMgr.clearAll(),await this.pool?.stop(),this.aibotHandle?.disconnect(),e.length>0&&this.activeEventStore&&await this.activeEventStore.save([]),this.eventSessionIndex.clear(),this.inflightEvents.clear(),this.restartCount.clear()}resolveSpawnEnv(){const e=ue(this.config.agent.clientType,this.config.agent.provider),o=this.config.agent.env,t=Object.keys(e).length>0?{...e,...o}:o;return ae(t,this.name,this.config.agent.clientType)}createAdapter(e,o){switch(e){case"claude":return this.createClaudeAdapter(o);case"codex":return this.createCodexAdapter(o);case"pi":return this.createPiAdapter(o);case"openhuman":return this.createOpenHumanAdapter(o);case"codewhale":return this.createCodeWhaleAdapter(o);case"cursor":return this.createCursorAdapter(o);case"opencode":return this.createOpenCodeAdapter(o);case"agy":return this.createAgyAdapter(o);default:return this.createAcpAdapter(o)}}createCursorAdapter(e){const o={...this.config.adapterOptions??{}};o.bindingStore=this.bindingStore,o.aibotSessionId=e;const t=this.bindingStore.get(e),s=this.resolveSessionModelId(e);s&&(o.model=s),t?.modeId&&(o.mode=t.modeId);const i={sendStreamChunk:(n,a,r,d,c)=>{this.sendStreamChunkByRuntimeConfig(n,a,r,d,c)},sendEventResult:(n,a,r)=>{this.sendEventResultWithCleanup(n,a,r)},sendEventAck:(n,a)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:a,received_at:Date.now()})},sendRawEventEnvelope:(n,a,r)=>{this.aibotHandle.sendMsg({event_id:n,session_id:a,msg_type:1,content:"[cursor] raw_event",extra:{channel_data:{cursor:{raw_event:r}},agent_api_origin:!0}})},agentInvoke:async(n,a,r)=>this.platformInvoke(n,a,r),sendLocalActionResult:(n,a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})}};return new H({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:o},i)}createClaudeAdapter(e){const o={sendReply:(i,n,a,r,d)=>{this.sendReplyByRuntimeConfig(i,n,a,r,d)},sendStreamChunk:(i,n,a,r,d,c,l)=>{this.sendStreamChunkByRuntimeConfig(i,n,a,r,d,c,l)},sendMedia:(i,n,a,r,d,c,l)=>{this.aibotHandle.sendMedia({event_id:i,session_id:n,content:a,msg_type:2,quoted_message_id:d||void 0,client_msg_id:c||void 0,extra:l?{media_caption:r,...l}:{media_caption:r}})},sendEventResult:(i,n,a,r)=>{this.sendEventResultWithCleanup(i,n,a,r)},sendEventAck:(i,n)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()})},agentInvoke:async(i,n,a)=>this.platformInvoke(i,n,a),sendLocalActionResult:(i,n,a,r,d)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...a!==void 0?{result:a}:{},...r?{error_code:r}:{},...d?{error_msg:d}:{}})},sendToolUse:(i,n,a,r)=>{this.sendToolExecutionCard(i,n,$(a,r))},sendToolResult:(i,n,a,r)=>{this.sendToolExecutionCard(i,n,y(a,r))},getWsUrl:()=>this.config.aibot.url,getAgentId:()=>this.config.aibot.agentId,getAgentProfile:()=>this.agentProfile,getApiKey:()=>this.config.aibot.apiKey,getActiveEventCount:()=>0,getPendingPermissionCount:()=>0,getPendingElicitationCount:()=>0,sendAgentQuestionCard:(i,n,a)=>{const r=a.questions.map(c=>c.header).join(", "),d=st(`[Agent Question] ${a.request_id}`,"agent_question",a);this.aibotHandle.sendText({event_id:i,session_id:n,content:d,msg_type:1,extra:{card_type:"agent_question",summary_text:r}})},sendPermissionCard:i=>{this.aibotHandle.sendMsg({event_id:i.eventId,session_id:i.sessionId,client_msg_id:`perm_${M()}`,msg_type:1,content:i.toolTitle?`Permission required: ${i.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:i.approvalId,approvalSlug:i.toolName},grix:{execApproval:{approval_command_id:i.approvalId,command:i.toolTitle||i.toolName,host:"claude"}}},agent_api_origin:!0}})},sendDirectMessage:i=>{this.aibotHandle.sendMsg({session_id:i.sessionId,msg_type:1,content:i.content,...i.clientMsgId?{client_msg_id:i.clientMsgId}:{},...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}})},onStatusLineUpdated:i=>{(i.rateLimits?.fiveHour||i.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=i);const n=this.bindingStore.get(e);n?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:n.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:i=>{this.aibotHandle.sendMcpFrame(e,i)}},t=this.config.adapterOptions??{},s={...t,sessionRuntimeResolver:()=>{const i=this.bindingStore.get(e);return{cwd:i?.cwd,modeId:i?.modeId??C.fullAuto,modelId:this.resolveSessionModelId(e),pluginDir:t.pluginDir,claudeSessionId:i?.claudeSessionId,onSessionIdAssigned:n=>{this.bindingStore.setClaudeSessionId(e,n),this.sessionScanCache.invalidate()}}}};return new T({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},o)}createCodexAdapter(e){let o=null;const t={sendEventResult:(n,a,r)=>{this.sendEventResultWithCleanup(n,a,r)},sendEventAck:(n,a)=>this.aibotHandle.sendEventAck({event_id:n,session_id:a,received_at:Date.now()}),sendCodexEvent:n=>{this.shouldDropCodexDisplayEvent(n.event_id,n.codex_method)||(this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(n)),this.logCodexEventToConversation(n))},sendCodexEventReliable:async n=>{if(!this.shouldDropCodexDisplayEvent(n.event_id,n.codex_method)){try{await this.aibotHandle.sendCodexEventReliable(this.stampCodexEventQuote(n))}catch(a){u.warn("bridge",`[codex] sendCodexEventReliable ACK failed event=${n.event_id}: ${a}`)}u.info("bridge",`[codex] sendCodexEventReliable done event=${n.event_id} method=${n.codex_method}`),this.logCodexEventToConversation(n)}},sendRunError:(n,a,r)=>{this.sendStreamChunkByRuntimeConfig(n,a,`
1
+ import P from"node:path";import{realpath as J,stat as L}from"node:fs/promises";import{tmpdir as Y}from"node:os";import{randomUUID as M}from"node:crypto";import{ConnectionManager as X}from"../core/aibot/index.js";import{ClaudeAdapter as T}from"../adapter/claude/index.js";import{CodexAdapter as Z}from"../adapter/codex/index.js";import{PiAdapter as ee}from"../adapter/pi/index.js";import{AcpAdapter as A}from"../adapter/acp/index.js";import{OpenHumanAdapter as te}from"../adapter/openhuman/index.js";import{CursorAdapter as H}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as O}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as ie}from"../adapter/opencode/index.js";import{AgyAdapter as U}from"../adapter/agy/index.js";import{getCachedAgyModels as ne}from"../adapter/agy/model-list.js";import{getCachedAgyQuotaInfo as se}from"../adapter/agy/quota.js";import{LOCAL_ACTION_ERROR_CODES as x,LOCAL_ACTION_TYPES as b,SESSION_CONTROL_ERROR_CODES as g,SESSION_CONTROL_VERBS as p,SESSION_MODE_IDS as C}from"../adapter/claude/protocol-contract.js";import{parseClaudeSessionUsage as oe}from"../adapter/claude/usage-parser.js";import{resolveSkillScanMode as q}from"../adapter/claude/skill-scanner.js";import{buildReportedSkills as re}from"../default-skills/index.js";import{buildWireSkills as W}from"../core/skill-sync/sync-state.js";import{uploadSkill as ae}from"../core/skill-sync/skill-upload.js";import{fetchAvailableModels as D,getCachedModels as Q,readSettingsEnv as de}from"../adapter/claude/model-list.js";import{parseAcpSessionUsage as ce}from"../adapter/acp/usage-parser.js";import{applyProxyEnv as le,getProxyManager as ue,relayHostsForClientType as he,buildGatewayRoute as ge}from"../core/proxy/index.js";import{buildProviderEnv as me}from"../core/config/provider-env.js";import{sweepNativeProviderResidue as pe}from"./native-provider-sweep.js";import{parseCodexSessionUsage as fe}from"../adapter/codex/usage-parser.js";import{readCodexProviderSettings as _e}from"../adapter/codex/codex-trust.js";import{resolveKimiProviderSettings as ve}from"../core/provider-quota/index.js";import{scanCodexSessions as Se}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as be}from"../adapter/claude/session-scanner.js";import{reasonixStampFromSessionId as we,resolveAcpAgentTypes as Ce,scanAcpSessions as Ae,scanReasonixSessionTitles as ke}from"../adapter/acp/session-scanner.js";import{scanPiSessions as Re}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as Ee}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as $e}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as ye}from"../adapter/opencode/session-scanner.js";import{parsePiSessionUsage as Te}from"../adapter/pi/usage-parser.js";import{SessionScanCache as k,resolveCodexLeafDirs as xe,resolveClaudeLeafDirs as Pe,resolveAcpLeafDirs as Ie,resolvePiLeafDirs as Le,resolveCodeWhaleLeafDirs as Me,resolveCursorLeafDirs as He,resolveOpenCodeLeafDirs as De,resolveReasonixLeafDirs as Qe}from"./session-scan-cache.js";import{log as u,ConversationLog as Be,AgentApiPacketLog as Fe,BridgeEventLog as Oe,GRIX_PATHS as N}from"../core/log/index.js";import{RevokeHandler as Ue}from"./revoke-handler.js";import{AdapterPool as qe,PoolFullError as We}from"./adapter-pool.js";import{parseSessionControlCommand as Ne,handleSessionControlCommand as z,handleSessionControlLocalAction as ze}from"./session-controller.js";import{isOpenSessionDirectiveMessage as Ge}from"../core/protocol/interaction-parser.js";import{handleAcpSetModel as G,handleAcpSetMode as K,resolveAcpInitialDefaults as Ke}from"./acp-toolbar-persist.js";import{SessionBindingStore as je}from"../core/persistence/session-binding-store.js";import{handleFileListAction as Ve,handleCreateFolderAction as Je,serveLocalFile as Ye,realHomeDir as j}from"../core/files/index.js";import{getMachineName as Xe}from"../core/util/index.js";import{uploadReplyFileToAgentMedia as Ze}from"../core/protocol/agent-api-media.js";import{ActiveEventStore as et}from"../core/persistence/active-event-store.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as tt,applyConnectorRuntimeConfigPatch as it,extractConnectorRuntimeConfigPatch as nt}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as st,SendController as ot}from"./send-controller.js";import{queryProviderQuota as rt}from"../core/provider-quota/index.js";import{queryKiroQuota as B}from"../core/provider-quota/kiro.js";import{buildToolUseCard as $,buildToolResultCard as y,buildLocalGrixCardLink as at}from"./tool-card-utils.js";import{DeferredEventManager as dt}from"./deferred-events.js";import{buildAgentProbeResult as ct,PROBE_CACHE_TTL_STATIC_MS as lt,PROBE_CACHE_TTL_FULL_MS as ut}from"./probe-helper.js";const ht=600*1e3,gt=60*1e3,V=30*1e3,mt=10*1e3,I=new Set(["claude","acp","agy","cursor","codex"]),pt=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp"]),F=3;class bi{config;name;aibotHandle;aibotConfig;pool;stopped=!1;revokeHandler=new Ue;sessionBindings=new Map;deferredMgr;sendCtrl=new ot(tt);bindingStore;globalConfigStore;upgradeTrigger=null;agentDeletedHandler=null;shareSetHandler=null;skillSyncHandler=null;providerConfigHandler=null;agentProfile={agentName:"",introduction:""};activeEventStore;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";conversationLog=null;packetLog=null;providerQuotaTimer=null;eventSessionIndex=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;sessionScanCache;reasonixTitleScan=null;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const o=Number(e);return o>0&&Date.now()-o<=gt}async maybeQueryProviderQuota(){if(this.config.aibot.clientType==="kiro"){if(this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&this.cachedProviderQuota)return this.cachedProviderQuota;try{const t=await B();return this.cachedProviderQuota=t,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[provider-quota] kiro queried: success=${t.success}`+(t.balance?` balance=${t.balance.remaining} ${t.balance.unit}`:"")+(t.planName?` plan=${t.planName}`:"")+(t.error?` error=${t.error}`:"")),t}catch(t){return u.warn(this.name,`[provider-quota] kiro query failed: ${t instanceof Error?t.message:String(t)}`),null}}let e=this.config.providerBaseUrl,o=this.config.providerApiKey;if((!e||!o)&&(this.config.adapterType??"acp")==="claude"){const t=de();e||(e=(t.ANTHROPIC_BASE_URL??"").trim()||void 0),o||(o=(t.ANTHROPIC_API_KEY??"").trim()||(t.ANTHROPIC_AUTH_TOKEN??"").trim()||void 0)}if((!e||!o)&&(this.config.adapterType??"acp")==="codex"){const t=_e();!e&&t.baseUrl&&(e=t.baseUrl),!o&&t.apiKey&&(o=t.apiKey)}if((!e||!o)&&(this.config.adapterType??"acp")==="acp"&&this.config.aibot.clientType==="kimi"){const t=await ve();!e&&t.baseUrl&&(e=t.baseUrl),!o&&t.apiKey&&(o=t.apiKey)}if(!e||!o)return null;if(this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&this.cachedProviderQuota)return this.cachedProviderQuota;try{const t=await rt(e,o);return this.cachedProviderQuota=t,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[provider-quota] queried: provider=${t.provider} success=${t.success}`+(t.tiers.length>0?` tiers=${t.tiers.map(s=>`${s.name}=${s.usedPercent}%`).join(",")}`:"")+(t.balance?` balance=${t.balance.remaining} ${t.balance.unit}`:"")+(t.error?` error=${t.error}`:"")),t}catch(t){return u.warn(this.name,`[provider-quota] query failed: ${t instanceof Error?t.message:String(t)}`),null}}startProviderQuotaTimer(){this.providerQuotaTimer||(this.providerQuotaTimer=setInterval(()=>{if(this.stopped){this.stopProviderQuotaTimer();return}this.refreshAndPushProviderQuota().catch(()=>{})},V),u.info(this.name,`[provider-quota-timer] started (interval=${V}ms)`))}stopProviderQuotaTimer(){this.providerQuotaTimer&&(clearInterval(this.providerQuotaTimer),this.providerQuotaTimer=null,u.info(this.name,"[provider-quota-timer] stopped"))}async refreshAndPushProviderQuota(){try{let e;this.config.aibot.clientType==="kiro"?(e=await B(),this.cachedProviderQuota=e,this.cachedProviderQuotaSampledAtMs=Date.now()):e=await this.maybeQueryProviderQuota(),e?.success&&this.pushProviderQuotaToBindings(e)}catch{}}pushProviderQuotaToBindings(e){const o=this.providerQuotaToRateLimits(e);for(const[t,s]of this.sessionBindings.entries()){if(!s)continue;const i={provider_quota:e};o&&(i.rate_limits=o);const n=this.cachedAcpContextWindow;n&&("usedPercentage"in n?i.context_window={usedPercentage:n.usedPercentage,remainingPercentage:100-n.usedPercentage}:i.context_window=n),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:s,meta:i})}}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,o=this.cachedCodexContextWindow,t=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:o,tokenUsage:t,hasData:!!(e||o||t)}}getStatus(){const e=this.pool?.getStatus()??{total:0,ready:0,busy:0};return{name:this.name,agentId:this.config.aibot.agentId,alive:!this.stopped,busy:e.busy>0,exhausted:this.pool?[...this.pool.getAllSlots()].some(o=>o.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}hasPendingOrBackgroundWork(){return this.pool?.hasPendingOrBackgroundWork()??!1}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,u.info(this.name,"relay changed but agent is busy; adapters keep the old env until the next message (marked stale)"),!1;const e=[...this.pool.getAllSlots()];let o=0,t=!1;for(const s of e){if(this.hasPendingWork())return this.relayEnvStale=!0,u.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let i=!1;await this.pool.removeSlot(s.sessionId).catch(n=>{t=!0,i=!0,u.warn(this.name,`failed to recycle adapter slot ${s.sessionId} after relay change: ${n}`)}),i||(o+=1)}return o>0&&u.info(this.name,`recycled ${o} adapter slot(s) so the new Grix relay env takes effect`),t?(this.relayEnvStale=!0,!1):(this.relayEnvStale=!1,this.relayEnvSettledHandler?.(),!0)}setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}hasStaleRelayEnv(){return this.relayEnvStale}markRelayEnvStale(){this.relayEnvStale=!0}async probe(e={}){const o=e.conversation?"full":"static",t=e.conversation?ut:lt;if(!e.fresh){const r=this.probeCache.get(o);if(r&&Date.now()-r.sampledAt<t)return{...r.result,cached:!0}}const s=this.config.adapterType??"acp",i=this.createAdapter(s,"__probe__"),n=e.conversation&&s==="acp"?()=>this.runAcpConversationProbe(i,e.timeoutMs??1e4):void 0;let a;try{a=await ct({adapter:i,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:s,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:n})}finally{i.stop().catch(()=>{})}return this.probeCache.set(o,{result:a,sampledAt:a.probed_at}),a}async runAcpConversationProbe(e,o){const t=Date.now(),s="__probe__",i=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,n=this.config.agent.cwd||Y(),a=()=>Date.now()-t;try{await e.start()}catch(h){return{attempted:!0,ok:!1,latency_ms:a(),error:{code:"conversation_failed",message:`start failed: ${h instanceof Error?h.message:String(h)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:a(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof A)try{await e.bindSession(s,n)}catch{}let r=null;const d=new Promise(h=>{r=m=>{m===i&&h()},e.on("eventDone",r)});e.deliverInboundEvent({event_id:i,session_id:s,content:"ping",msg_id:i}),e.deliverStopEvent(i,s);let c=null;const l=await Promise.race([d.then(()=>!1),new Promise(h=>{c=setTimeout(()=>h(!0),o)})]);return c&&clearTimeout(c),r&&e.removeListener("eventDone",r),l?{attempted:!0,ok:!1,latency_ms:a(),error:{code:"conversation_timeout",message:`no eventDone within ${o}ms`}}:{attempted:!0,ok:!0,latency_ms:a()}}constructor(e,o){this.config=e,this.name=e.name;const t=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(st[t]),this.aibotConfig={...e.aibot,...t==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","thread_compact","get_agent_global_config"]}:{}},e.eventQueue&&(this.aibotConfig.concurrency={max_concurrent:e.eventQueue.maxConcurrent,max_queued:e.eventQueue.maxQueued,queue_timeout_ms:e.eventQueue.queueTimeoutMs,cancelable_queued:e.eventQueue.cancelableQueued,cancelable_running:e.eventQueue.cancelableRunning}),this.conversationLog=e.logDir?new Be(e.logDir):null,this.packetLog=e.logDir?new Fe(e.logDir):null,this.bindingStore=new je(e.bindingsPath),this.bindingStore.load(),this.globalConfigStore=o??null,this.deferredMgr=new dt(this.name),this.activeEventStore=e.activeEventStorePath?new et(e.activeEventStorePath):null,t==="codex")this.sessionScanCache=new k(Se,xe);else if(t==="claude")this.sessionScanCache=new k(be,Pe);else if(t==="pi"){const s=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new k(()=>Re(void 0,s),()=>Le(void 0,s))}else if(t==="codewhale")this.sessionScanCache=new k(Ee,Me);else if(t==="cursor")this.sessionScanCache=new k($e,He);else if(t==="opencode")this.sessionScanCache=new k(ye,De);else if(t==="agy")this.sessionScanCache=new k(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new k(ke,Qe));const s=Ce(e.aibot.clientType);this.sessionScanCache=s?new k(()=>Ae(void 0,s),()=>Ie(void 0,s)):new k(()=>[],()=>[])}}async start(){await pe({agentName:this.name,adapterType:this.config.adapterType??"acp",command:this.config.agent.command,piConfigDir:this.config.agent.env?.PI_CODING_AGENT_DIR,hasProvider:!!this.config.agent.provider,boundCwds:[...this.bindingStore.entries()].map(([,o])=>String(o.cwd??""))}).then(o=>{o.length>0&&u.info(this.name,`restored native provider config after relay disable: ${o.join(", ")}`)}).catch(o=>{u.warn(this.name,`native provider residue sweep failed: ${o instanceof Error?o.message:String(o)}`)}),(this.config.adapterType??"acp")==="claude"&&(await D().catch(()=>{}),this.maybeQueryProviderQuota().catch(()=>{})),(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),await this.connectAibot(),this.sendCtrl.bind(this.aibotHandle);const e=this.config.adapterType??"acp";this.pool=new qe({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},o=>{const t=this.createAdapter(e,o);return t instanceof A&&t.on("acpSessionReady",s=>{this.bindingStore.setAcpSessionId(o,s),this.sessionScanCache.invalidate()}),t},(o,t)=>{this.aibotHandle.sendEventAck({event_id:o,session_id:t,received_at:Date.now()})}),this.pool.setEventStateHandler((o,t,s,i)=>{u.info(this.name,`[queue-debug] send event_state session=${t} event=${o} state=${s} queue_pos=${i?.queue_position??""} queue_total=${i?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:o,session_id:t,state:s,content_preview:i?.content_preview,queue_position:i?.queue_position,queue_total:i?.queue_total,actions:i?.actions,reason:i?.reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(t),(s==="canceled"||s==="failed")&&(this.aibotHandle.sendEventResult({event_id:o,status:s==="canceled"?"canceled":"failed",msg:i?.reason,updated_at:Date.now()}),this.discardEventTrackingState(o))}),this.pool.setQueueComposingHandler((o,t,s)=>{this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:t,...t?{ttl_ms:3e4,ref_event_id:s}:{}})}),this.pool.setInternalErrorHandler(o=>{this.handleSessionInternalError(o).catch(t=>{u.error(this.name,`[recovery] handleSessionInternalError failed event=${o.eventId} session=${o.sessionId}: ${t instanceof Error?t.message:String(t)}`)})}),this.pool.setEventStartedHandler((o,t)=>{if(this.reportSessionSkills(t),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(t,"busy");const s=this.bindingStore.get(t);s?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"busy",cwd:s.cwd,meta:this.buildClaudeToolbarMeta(t)})}),this.pool.setEventDoneHandler((o,t)=>{const s=this.config.adapterType??"acp";if(s==="claude"){this.claudeWorkerStatus.set(t,"ready");const i=this.bindingStore.get(t);i?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i.cwd,meta:this.buildClaudeToolbarMeta(t)})}else if(s==="agy"){const i=this.bindingStore.get(t);if(i?.cwd){const n=this.buildAgyToolbarMeta(t),a=n?.available_models??[];u.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${t} model_id=${String(n?.model_id??"")} available_models=${a.length} meta_keys=${n?Object.keys(n).join(","):"<none>"}`),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i.cwd,meta:n})}else u.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${t}`)}}),this.pool.setSessionActivityHandler((o,t,s)=>{const i=this.selfDrivenSessions.has(o),n=this.selfDrivenLabels.get(o);t?(this.selfDrivenSessions.add(o),s&&this.selfDrivenLabels.set(o,s),this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(o),this.selfDrivenLabels.delete(o),i&&this.aibotHandle.sendSessionActivitySet({session_id:o,kind:"composing",active:!1})),(i!==t||t&&s!==void 0&&s!==n)&&this.pushQueueSnapshotForSession(o)}),this.pool.startIdleSweep(),u.info(this.name,`Ready (adapter: ${e}, poolMax: ${this.config.poolMaxSize??20})`)}async stop(){this.stopped=!0,this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer();const e=this.pool?.collectActiveEventIds()??[];e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const s of e)u.info(this.name,`Canceling active event on shutdown: ${s}`),this.sendEventResultWithCleanup(s,"canceled","process shutting down");e.length>0&&await new Promise(s=>setTimeout(s,100)),this.pool?.clearActiveEventsForShutdown();const o=this.deferredMgr.getAllDeferredEvents();for(const s of o)u.info(this.name,`Failing deferred event on shutdown: ${s.event_id}`),this.sendEventResultWithCleanup(s.event_id,"failed","process shutting down");const t=this.pool?.drainAllQueuedEvents()??[];for(const s of t)u.info(this.name,`Failing queued event on shutdown: ${s.event_id}`),this.sendEventResultWithCleanup(s.event_id,"failed","process shutting down");this.deferredMgr.clearAll(),await this.pool?.stop(),this.aibotHandle?.disconnect(),e.length>0&&this.activeEventStore&&await this.activeEventStore.save([]),this.eventSessionIndex.clear(),this.inflightEvents.clear(),this.restartCount.clear()}resolveSpawnEnv(){const e=me(this.config.agent.clientType,this.config.agent.provider),o=this.config.agent.env,t=Object.keys(e).length>0?{...e,...o}:o;return le(t,this.name,this.config.agent.clientType)}createAdapter(e,o){switch(e){case"claude":return this.createClaudeAdapter(o);case"codex":return this.createCodexAdapter(o);case"pi":return this.createPiAdapter(o);case"openhuman":return this.createOpenHumanAdapter(o);case"codewhale":return this.createCodeWhaleAdapter(o);case"cursor":return this.createCursorAdapter(o);case"opencode":return this.createOpenCodeAdapter(o);case"agy":return this.createAgyAdapter(o);default:return this.createAcpAdapter(o)}}createCursorAdapter(e){const o={...this.config.adapterOptions??{}};o.bindingStore=this.bindingStore,o.aibotSessionId=e;const t=this.bindingStore.get(e),s=this.resolveSessionModelId(e);s&&(o.model=s),t?.modeId&&(o.mode=t.modeId);const i={sendStreamChunk:(n,a,r,d,c)=>{this.sendStreamChunkByRuntimeConfig(n,a,r,d,c)},sendEventResult:(n,a,r)=>{this.sendEventResultWithCleanup(n,a,r)},sendEventAck:(n,a)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:a,received_at:Date.now()})},sendRawEventEnvelope:(n,a,r)=>{this.aibotHandle.sendMsg({event_id:n,session_id:a,msg_type:1,content:"[cursor] raw_event",extra:{channel_data:{cursor:{raw_event:r}},agent_api_origin:!0}})},agentInvoke:async(n,a,r)=>this.platformInvoke(n,a,r),sendLocalActionResult:(n,a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})}};return new H({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:o},i)}createClaudeAdapter(e){const o={sendReply:(i,n,a,r,d)=>{this.sendReplyByRuntimeConfig(i,n,a,r,d)},sendStreamChunk:(i,n,a,r,d,c,l)=>{this.sendStreamChunkByRuntimeConfig(i,n,a,r,d,c,l)},sendMedia:(i,n,a,r,d,c,l)=>{this.aibotHandle.sendMedia({event_id:i,session_id:n,content:a,msg_type:2,quoted_message_id:d||void 0,client_msg_id:c||void 0,extra:l?{media_caption:r,...l}:{media_caption:r}})},sendEventResult:(i,n,a,r)=>{this.sendEventResultWithCleanup(i,n,a,r)},sendEventAck:(i,n)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()})},agentInvoke:async(i,n,a)=>this.platformInvoke(i,n,a),sendLocalActionResult:(i,n,a,r,d)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...a!==void 0?{result:a}:{},...r?{error_code:r}:{},...d?{error_msg:d}:{}})},sendToolUse:(i,n,a,r)=>{this.sendToolExecutionCard(i,n,$(a,r))},sendToolResult:(i,n,a,r)=>{this.sendToolExecutionCard(i,n,y(a,r))},getWsUrl:()=>this.config.aibot.url,getAgentId:()=>this.config.aibot.agentId,getAgentProfile:()=>this.agentProfile,getApiKey:()=>this.config.aibot.apiKey,getActiveEventCount:()=>0,getPendingPermissionCount:()=>0,getPendingElicitationCount:()=>0,sendAgentQuestionCard:(i,n,a)=>{const r=a.questions.map(c=>c.header).join(", "),d=at(`[Agent Question] ${a.request_id}`,"agent_question",a);this.aibotHandle.sendText({event_id:i,session_id:n,content:d,msg_type:1,extra:{card_type:"agent_question",summary_text:r}})},sendPermissionCard:i=>{this.aibotHandle.sendMsg({event_id:i.eventId,session_id:i.sessionId,client_msg_id:`perm_${M()}`,msg_type:1,content:i.toolTitle?`Permission required: ${i.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:i.approvalId,approvalSlug:i.toolName},grix:{execApproval:{approval_command_id:i.approvalId,command:i.toolTitle||i.toolName,host:"claude"}}},agent_api_origin:!0}})},sendDirectMessage:i=>{this.aibotHandle.sendMsg({session_id:i.sessionId,msg_type:1,content:i.content,...i.clientMsgId?{client_msg_id:i.clientMsgId}:{},...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}})},onStatusLineUpdated:i=>{(i.rateLimits?.fiveHour||i.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=i);const n=this.bindingStore.get(e);n?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:n.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:i=>{this.aibotHandle.sendMcpFrame(e,i)}},t=this.config.adapterOptions??{},s={...t,sessionRuntimeResolver:()=>{const i=this.bindingStore.get(e);return{cwd:i?.cwd,modeId:i?.modeId??C.fullAuto,modelId:this.resolveSessionModelId(e),pluginDir:t.pluginDir,claudeSessionId:i?.claudeSessionId,onSessionIdAssigned:n=>{this.bindingStore.setClaudeSessionId(e,n),this.sessionScanCache.invalidate()}}}};return new T({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},o)}createCodexAdapter(e){let o=null;const t={sendEventResult:(n,a,r)=>{this.sendEventResultWithCleanup(n,a,r)},sendEventAck:(n,a)=>this.aibotHandle.sendEventAck({event_id:n,session_id:a,received_at:Date.now()}),sendCodexEvent:n=>{this.shouldDropCodexDisplayEvent(n.event_id,n.codex_method)||(this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(n)),this.logCodexEventToConversation(n))},sendCodexEventReliable:async n=>{if(!this.shouldDropCodexDisplayEvent(n.event_id,n.codex_method)){try{await this.aibotHandle.sendCodexEventReliable(this.stampCodexEventQuote(n))}catch(a){u.warn("bridge",`[codex] sendCodexEventReliable ACK failed event=${n.event_id}: ${a}`)}u.info("bridge",`[codex] sendCodexEventReliable done event=${n.event_id} method=${n.codex_method}`),this.logCodexEventToConversation(n)}},sendRunError:(n,a,r)=>{this.sendStreamChunkByRuntimeConfig(n,a,`
2
2
 
3
- Error: ${r}`,1,!1)},sendUpdateBindingCard:(n,a,r,d)=>{const c={...d??{}};if(!c.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const l=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);l&&(c.rate_limits=l.rateLimits,c.rate_limit_primary_percent=l.primaryPercent,c.rate_limit_secondary_percent=l.secondaryPercent,c.rate_limit_primary_window_min=l.primaryWindowMin,c.rate_limit_secondary_window_min=l.secondaryWindowMin)}!c.provider_quota&&this.cachedProviderQuota?.success&&(c.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:a,cwd:r,...Object.keys(c).length>0?{meta:c}:{}})},agentInvoke:async(n,a,r)=>this.platformInvoke(n,a,r),sendLocalActionResult:(n,a,r,d,c)=>this.aibotHandle.sendLocalActionResult({action_id:n,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}}),sendSessionActivitySet:(n,a,r,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:a,active:r,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,onRateLimitsUpdated:n=>{this.cachedRateLimits=n,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const r=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...n.primary.windowMinutes>0?{primary:n.primary}:{},...n.secondary.windowMinutes>0?{secondary:n.secondary}:{},sampledAt:r},rate_limit_primary_percent:n.primary.usedPercent,rate_limit_secondary_percent:n.secondary.usedPercent,rate_limit_primary_window_min:n.primary.windowMinutes,rate_limit_secondary_window_min:n.secondary.windowMinutes,...o?.getEffortMeta()};this.cachedProviderQuota?.success&&(d.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:d})}},onContextWindowUpdated:n=>{if(!n)return;this.cachedCodexContextWindow=n,this.cachedCodexUsageSampledAtMs=Date.now();const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:{context_window:n,...o?.getEffortMeta()}})},onTokenUsageUpdated:n=>{n&&(this.cachedCodexTokenUsage=n,this.cachedCodexUsageSampledAtMs=Date.now())}},s=this.config.adapterOptions??{},i=this.globalConfigStore?.get(this.name);return o=new J({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...s,model:this.resolveCodexSessionModelId(e)??s.model,collaborationMode:this.bindingStore.getCodexModeId(e)??s.collaborationMode,reasoningEffort:i?.codexReasoningEffort??s.reasoningEffort,serviceTier:this.bindingStore.getCodexServiceTier(e)??s.serviceTier,sandboxMode:i?.codexSandboxMode??s.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore}},t),o}createCodeWhaleAdapter(e){const o={sendEventResult:(s,i,n)=>{this.sendEventResultWithCleanup(s,i,n)},sendEventAck:(s,i)=>this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()}),sendStreamChunk:(s,i,n,a,r,d)=>{this.sendStreamChunkByRuntimeConfig(s,i,n,a,r,d)},sendUpdateBindingCard:(s,i,n,a)=>this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:i,cwd:n,...a?{meta:a}:{}}),sendLocalActionResult:(s,i,n,a,r)=>this.aibotHandle.sendLocalActionResult({action_id:s,status:i,...n!==void 0?{result:n}:{},...a?{error_code:a}:{},...r?{error_msg:r}:{}}),sendSessionActivitySet:(s,i,n,a)=>{this.aibotHandle.sendSessionActivitySet({session_id:s,kind:i,active:n,...a??{}})},sendToolUse:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,$(n,a))},sendToolResult:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,y(n,a))},agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new O({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...t,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},o)}createPiAdapter(e){const o={sendEventResult:(s,i,n)=>{this.sendEventResultWithCleanup(s,i,n),u.info("bridge",`[pi] sendEventResult event=${s} status=${i}`)},sendEventAck:(s,i)=>this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()}),sendUpdateBindingCard:(s,i,n,a)=>this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:i,cwd:n,...a?{meta:a}:{}}),agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),sendLocalActionResult:(s,i,n,a,r)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:i,...n!==void 0?{result:n}:{},...a?{error_code:a}:{},...r?{error_msg:r}:{}})},sendSessionActivitySet:(s,i,n,a)=>{this.aibotHandle.sendSessionActivitySet({session_id:s,kind:i,active:n,...a??{}})},sendToolUse:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,$(n,a))},sendToolResult:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,y(n,a))},sendStreamChunk:(s,i,n,a,r,d)=>{this.sendStreamChunkByRuntimeConfig(s,i,n,a,r,d),r&&u.info("bridge",`[pi] sendFinalStreamChunk event=${s} seq=${a}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(s,i,n)=>{this.sendThinkingByRuntimeConfig(s,i,n)},sendRunError:(s,i,n,a,r)=>{this.sendStreamChunkByRuntimeConfig(s,i,`
3
+ Error: ${r}`,1,!1)},sendUpdateBindingCard:(n,a,r,d)=>{const c={...d??{}};if(!c.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const l=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);l&&(c.rate_limits=l.rateLimits,c.rate_limit_primary_percent=l.primaryPercent,c.rate_limit_secondary_percent=l.secondaryPercent,c.rate_limit_primary_window_min=l.primaryWindowMin,c.rate_limit_secondary_window_min=l.secondaryWindowMin)}!c.provider_quota&&this.cachedProviderQuota?.success&&(c.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:a,cwd:r,...Object.keys(c).length>0?{meta:c}:{}})},agentInvoke:async(n,a,r)=>this.platformInvoke(n,a,r),sendLocalActionResult:(n,a,r,d,c)=>this.aibotHandle.sendLocalActionResult({action_id:n,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}}),sendSessionActivitySet:(n,a,r,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:a,active:r,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,onRateLimitsUpdated:n=>{this.cachedRateLimits=n,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const r=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...n.primary.windowMinutes>0?{primary:n.primary}:{},...n.secondary.windowMinutes>0?{secondary:n.secondary}:{},sampledAt:r},rate_limit_primary_percent:n.primary.usedPercent,rate_limit_secondary_percent:n.secondary.usedPercent,rate_limit_primary_window_min:n.primary.windowMinutes,rate_limit_secondary_window_min:n.secondary.windowMinutes,...o?.getEffortMeta()};this.cachedProviderQuota?.success&&(d.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:d})}},onContextWindowUpdated:n=>{if(!n)return;this.cachedCodexContextWindow=n,this.cachedCodexUsageSampledAtMs=Date.now();const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:{context_window:n,...o?.getEffortMeta()}})},onTokenUsageUpdated:n=>{n&&(this.cachedCodexTokenUsage=n,this.cachedCodexUsageSampledAtMs=Date.now())}},s=this.config.adapterOptions??{},i=this.globalConfigStore?.get(this.name);return o=new Z({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...s,model:this.resolveCodexSessionModelId(e)??s.model,collaborationMode:this.bindingStore.getCodexModeId(e)??s.collaborationMode,reasoningEffort:i?.codexReasoningEffort??s.reasoningEffort,serviceTier:this.bindingStore.getCodexServiceTier(e)??s.serviceTier,sandboxMode:i?.codexSandboxMode??s.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore}},t),o}createCodeWhaleAdapter(e){const o={sendEventResult:(s,i,n)=>{this.sendEventResultWithCleanup(s,i,n)},sendEventAck:(s,i)=>this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()}),sendStreamChunk:(s,i,n,a,r,d)=>{this.sendStreamChunkByRuntimeConfig(s,i,n,a,r,d)},sendUpdateBindingCard:(s,i,n,a)=>this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:i,cwd:n,...a?{meta:a}:{}}),sendLocalActionResult:(s,i,n,a,r)=>this.aibotHandle.sendLocalActionResult({action_id:s,status:i,...n!==void 0?{result:n}:{},...a?{error_code:a}:{},...r?{error_msg:r}:{}}),sendSessionActivitySet:(s,i,n,a)=>{this.aibotHandle.sendSessionActivitySet({session_id:s,kind:i,active:n,...a??{}})},sendToolUse:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,$(n,a))},sendToolResult:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,y(n,a))},agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new O({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...t,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},o)}createPiAdapter(e){const o={sendEventResult:(s,i,n)=>{this.sendEventResultWithCleanup(s,i,n),u.info("bridge",`[pi] sendEventResult event=${s} status=${i}`)},sendEventAck:(s,i)=>this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()}),sendUpdateBindingCard:(s,i,n,a)=>this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:i,cwd:n,...a?{meta:a}:{}}),agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),sendLocalActionResult:(s,i,n,a,r)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:i,...n!==void 0?{result:n}:{},...a?{error_code:a}:{},...r?{error_msg:r}:{}})},sendSessionActivitySet:(s,i,n,a)=>{this.aibotHandle.sendSessionActivitySet({session_id:s,kind:i,active:n,...a??{}})},sendToolUse:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,$(n,a))},sendToolResult:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,y(n,a))},sendStreamChunk:(s,i,n,a,r,d)=>{this.sendStreamChunkByRuntimeConfig(s,i,n,a,r,d),r&&u.info("bridge",`[pi] sendFinalStreamChunk event=${s} seq=${a}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(s,i,n)=>{this.sendThinkingByRuntimeConfig(s,i,n)},sendRunError:(s,i,n,a,r)=>{this.sendStreamChunkByRuntimeConfig(s,i,`
4
4
 
5
- Error: ${n}`,a,!1,r)},getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new Y({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...t,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},o)}createOpenHumanAdapter(e){const o={sendStreamChunk:(s,i,n,a,r,d)=>{this.finalizeThinking(s,i),this.sendStreamChunkByRuntimeConfig(s,i,n,a,r,d)},sendFinalStreamChunkReliable:async(s,i,n,a)=>{if(this.finalizeThinking(s,i),this.resolveEventRuntimeConfig(s).responseDelivery==="single_message"&&s){this.bufferStreamChunk(s,i,"",!0);return}try{await this.aibotHandle.sendStreamChunkRequest({event_id:s,session_id:i,delta_content:"",chunk_seq:n,is_finish:!0,...a?{client_msg_id:a}:{}})}catch(d){u.warn("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${s}: ${d}`)}},sendEventResult:(s,i,n)=>{this.sendEventResultWithCleanup(s,i,n),u.info("bridge",`[openhuman] sendEventResult event=${s} status=${i}`)},sendEventAck:(s,i)=>this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()}),sendToolUse:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,$(n,a))},sendToolResult:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,y(n,a))},sendThinking:(s,i,n)=>{this.sendThinkingByRuntimeConfig(s,i,n)},sendRunError:(s,i,n)=>{this.sendStreamChunkByRuntimeConfig(s,i,`
5
+ Error: ${n}`,a,!1,r)},getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new ee({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...t,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},o)}createOpenHumanAdapter(e){const o={sendStreamChunk:(s,i,n,a,r,d)=>{this.finalizeThinking(s,i),this.sendStreamChunkByRuntimeConfig(s,i,n,a,r,d)},sendFinalStreamChunkReliable:async(s,i,n,a)=>{if(this.finalizeThinking(s,i),this.resolveEventRuntimeConfig(s).responseDelivery==="single_message"&&s){this.bufferStreamChunk(s,i,"",!0);return}try{await this.aibotHandle.sendStreamChunkRequest({event_id:s,session_id:i,delta_content:"",chunk_seq:n,is_finish:!0,...a?{client_msg_id:a}:{}})}catch(d){u.warn("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${s}: ${d}`)}},sendEventResult:(s,i,n)=>{this.sendEventResultWithCleanup(s,i,n),u.info("bridge",`[openhuman] sendEventResult event=${s} status=${i}`)},sendEventAck:(s,i)=>this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()}),sendToolUse:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,$(n,a))},sendToolResult:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,y(n,a))},sendThinking:(s,i,n)=>{this.sendThinkingByRuntimeConfig(s,i,n)},sendRunError:(s,i,n)=>{this.sendStreamChunkByRuntimeConfig(s,i,`
6
6
 
7
- Error: ${n}`,0,!1)},sendUpdateBindingCard:(s,i,n)=>this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:i,cwd:n}),agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),sendLocalActionResult:(s,i,n,a,r)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:i,...n!==void 0?{result:n}:{},...a?{error_code:a}:{},...r?{error_msg:r}:{}})},getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new X({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},o,{port:t.port,host:t.host,workspaceDir:t.workspace_dir,sessionToken:t.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const o={sendStreamChunk:(s,i,n,a,r,d)=>{this.sendStreamChunkByRuntimeConfig(s,i,n,a,r,d)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(s,i,n)=>{this.sendEventResultWithCleanup(s,i,n),u.info("bridge",`[opencode] sendEventResult event=${s} status=${i}`)},sendEventAck:(s,i)=>this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()}),sendToolUse:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,$(n,a))},sendToolResult:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,y(n,a))},sendThinking:(s,i,n)=>{this.sendThinkingByRuntimeConfig(s,i,n)},sendRunError:(s,i,n)=>{this.sendStreamChunkByRuntimeConfig(s,i,`
7
+ Error: ${n}`,0,!1)},sendUpdateBindingCard:(s,i,n)=>this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:i,cwd:n}),agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),sendLocalActionResult:(s,i,n,a,r)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:i,...n!==void 0?{result:n}:{},...a?{error_code:a}:{},...r?{error_msg:r}:{}})},getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new te({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},o,{port:t.port,host:t.host,workspaceDir:t.workspace_dir,sessionToken:t.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const o={sendStreamChunk:(s,i,n,a,r,d)=>{this.sendStreamChunkByRuntimeConfig(s,i,n,a,r,d)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(s,i,n)=>{this.sendEventResultWithCleanup(s,i,n),u.info("bridge",`[opencode] sendEventResult event=${s} status=${i}`)},sendEventAck:(s,i)=>this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()}),sendToolUse:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,$(n,a))},sendToolResult:(s,i,n,a)=>{this.sendToolExecutionCard(s,i,y(n,a))},sendThinking:(s,i,n)=>{this.sendThinkingByRuntimeConfig(s,i,n)},sendRunError:(s,i,n)=>{this.sendStreamChunkByRuntimeConfig(s,i,`
8
8
 
9
- Error: ${n}`,0,!1)},sendUpdateBindingCard:(s,i,n)=>this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:i,cwd:n}),agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),sendLocalActionResult:(s,i,n,a,r)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:i,...n!==void 0?{result:n}:{},...a?{error_code:a}:{},...r?{error_msg:r}:{}})},getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new Z({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},o,{port:t.port,hostname:t.hostname,model:t.model,agent:t.agent,permissionPolicy:t.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const o={sendStreamChunk:(s,i,n,a,r,d)=>{this.sendStreamChunkByRuntimeConfig(s,i,n,a,r,d)},sendEventResult:(s,i,n)=>{this.sendEventResultWithCleanup(s,i,n)},sendEventAck:(s,i)=>{this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()})},agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),forceCompleteInternalEvent:(s,i)=>{this.pool.eventComplete(s,i),this.pushQueueSnapshotForSession(i)},persistConversationId:(s,i)=>{this.bindingStore.setAgyConversationId(s,i)},getAgentProfile:()=>this.agentProfile},t=s=>{const i=this.bindingStore.get(s);return{cwd:i?.cwd,modelId:this.resolveSessionModelId(s),conversationId:i?.agyConversationId}};return new U({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},o,t)}createAcpAdapter(e){const o=this.isAcpRawTransportEnabled(),t={sendStreamChunk:(r,d,c,l,h,m,v)=>{this.finalizeThinking(r,d),this.sendStreamChunkByRuntimeConfig(r,d,c,l,h,m,v)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(r,d,c)=>{this.sendEventResultWithCleanup(r,d,c)},sendEventAck:(r,d)=>{this.aibotHandle.sendEventAck({event_id:r,session_id:d,received_at:Date.now()})},agentInvoke:async(r,d,c)=>this.platformInvoke(r,d,c),sendLocalActionResult:(r,d,c,l,h)=>{this.aibotHandle.sendLocalActionResult({action_id:r,status:d,...c!==void 0?{result:c}:{},...l?{error_code:l}:{},...h?{error_msg:h}:{}})},sendRawEventEnvelope:(r,d,c)=>{this.sendAcpRawEventEnvelope(r,d,c)},sendToolUse:(r,d,c,l)=>{if(o){this.sendAcpRawEventEnvelope(r,d,{type:"tool_use",payload:{tool_name:c,tool_input:l??""}});return}this.sendToolExecutionCard(r,d,$(c,l))},sendToolResult:(r,d,c,l)=>{this.sendToolExecutionCard(r,d,y(c,l))},sendThinking:(r,d,c)=>{this.sendThinkingByRuntimeConfig(r,d,c)},sendRunError:(r,d,c)=>{this.sendStreamChunkByRuntimeConfig(r,d,`
9
+ Error: ${n}`,0,!1)},sendUpdateBindingCard:(s,i,n)=>this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:i,cwd:n}),agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),sendLocalActionResult:(s,i,n,a,r)=>{this.aibotHandle.sendLocalActionResult({action_id:s,status:i,...n!==void 0?{result:n}:{},...a?{error_code:a}:{},...r?{error_msg:r}:{}})},getAgentProfile:()=>this.agentProfile},t=this.config.adapterOptions??{};return new ie({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},o,{port:t.port,hostname:t.hostname,model:t.model,agent:t.agent,permissionPolicy:t.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const o={sendStreamChunk:(s,i,n,a,r,d)=>{this.sendStreamChunkByRuntimeConfig(s,i,n,a,r,d)},sendEventResult:(s,i,n)=>{this.sendEventResultWithCleanup(s,i,n)},sendEventAck:(s,i)=>{this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()})},agentInvoke:async(s,i,n)=>this.platformInvoke(s,i,n),forceCompleteInternalEvent:(s,i)=>{this.pool.eventComplete(s,i),this.pushQueueSnapshotForSession(i)},persistConversationId:(s,i)=>{this.bindingStore.setAgyConversationId(s,i)},getAgentProfile:()=>this.agentProfile},t=s=>{const i=this.bindingStore.get(s);return{cwd:i?.cwd,modelId:this.resolveSessionModelId(s),conversationId:i?.agyConversationId}};return new U({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},o,t)}createAcpAdapter(e){const o=this.isAcpRawTransportEnabled(),t={sendStreamChunk:(r,d,c,l,h,m,v)=>{this.finalizeThinking(r,d),this.sendStreamChunkByRuntimeConfig(r,d,c,l,h,m,v)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(r,d,c)=>{this.sendEventResultWithCleanup(r,d,c)},sendEventAck:(r,d)=>{this.aibotHandle.sendEventAck({event_id:r,session_id:d,received_at:Date.now()})},agentInvoke:async(r,d,c)=>this.platformInvoke(r,d,c),sendLocalActionResult:(r,d,c,l,h)=>{this.aibotHandle.sendLocalActionResult({action_id:r,status:d,...c!==void 0?{result:c}:{},...l?{error_code:l}:{},...h?{error_msg:h}:{}})},sendRawEventEnvelope:(r,d,c)=>{this.sendAcpRawEventEnvelope(r,d,c)},sendToolUse:(r,d,c,l)=>{if(o){this.sendAcpRawEventEnvelope(r,d,{type:"tool_use",payload:{tool_name:c,tool_input:l??""}});return}this.sendToolExecutionCard(r,d,$(c,l))},sendToolResult:(r,d,c,l)=>{this.sendToolExecutionCard(r,d,y(c,l))},sendThinking:(r,d,c)=>{this.sendThinkingByRuntimeConfig(r,d,c)},sendRunError:(r,d,c)=>{this.sendStreamChunkByRuntimeConfig(r,d,`
10
10
 
11
- Error: ${c}`,1,!1)},sendPermissionCard:r=>{if(u.info("bridge","sendPermissionCard callback entered",{rawTransport:o,eventId:r.eventId,sessionId:r.sessionId,toolCallId:r.toolCallId,toolName:r.toolName,toolTitle:r.toolTitle}),o){this.sendAcpRawEventEnvelope(r.eventId,r.sessionId,{type:"permission_request",payload:{tool_call_id:r.toolCallId,tool_name:r.toolName,tool_title:r.toolTitle,options:r.options}}),u.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:r.eventId,toolCallId:r.toolCallId});return}const d=`perm_${M()}`,c={event_id:r.eventId,session_id:r.sessionId,client_msg_id:d,msg_type:1,content:r.toolTitle?`Permission required: ${r.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:r.toolCallId,approvalSlug:r.toolName},grix:{execApproval:{approval_command_id:r.toolCallId,command:r.toolTitle||r.toolName,host:"acp"}}},agent_api_origin:!0}};u.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:r.eventId,sessionId:r.sessionId,clientMsgId:d,toolCallId:r.toolCallId,contentLength:c.content.length});try{this.aibotHandle.sendMsg(c),u.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:r.eventId,clientMsgId:d})}catch(l){u.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:r.eventId,clientMsgId:d,error:l instanceof Error?l.message:String(l)})}},sendAuthNotification:(r,d)=>{r&&this.aibotHandle.sendMsg({session_id:r,msg_type:1,content:d,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:d}}}}})},sendAgentMessage:(r,d)=>{r&&d&&this.aibotHandle.sendMsg({session_id:r,msg_type:1,content:d})},sendUpdateBindingCard:(r,d,c,l)=>{const h={...l??{}};if(!h.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const m=this.providerQuotaToRateLimits(this.cachedProviderQuota);m&&(h.rate_limits=m)}!h.provider_quota&&this.cachedProviderQuota?.success&&(h.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:d,cwd:c,...Object.keys(h).length>0?{meta:h}:{}})},onSkillsUpdate:r=>{try{this.aibotHandle.sendSkillsUpdate({skills:r})}catch(d){}},onContextWindowUpdated:r=>{this.cachedAcpContextWindow=r,this.cachedAcpContextWindowSampledAtMs=Date.now();const d="usedPercentage"in r?r.usedPercentage.toFixed(1):(r.used/r.size*100).toFixed(1);u.info(this.name,`[acp] context_window updated: ${d}%`);const c=this.bindingStore.get(e);if(c?.cwd){const l={context_window:"usedPercentage"in r?{usedPercentage:r.usedPercentage,remainingPercentage:100-r.usedPercentage}:r};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),l.provider_quota=this.cachedProviderQuota;const h=this.providerQuotaToRateLimits(this.cachedProviderQuota);h&&(l.rate_limits=h)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:c.cwd,meta:l})}},sendMcpFrame:r=>{this.aibotHandle.sendMcpFrame(e,r)},getAgentProfile:()=>this.agentProfile},s=e?this.bindingStore.get(e):void 0,i=this.globalConfigStore?.get(this.name),{initialModel:n,initialMode:a}=Ne({sessionBinding:s,globalDefaults:i,configInitialMode:this.config.acpInitialMode});return e&&n&&!s?.acpModelId&&this.bindingStore.setAcpModelId(e,n),(n||a)&&u.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${n??"<none>"} mode=${a??"<none>"}`),new A({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},t,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:a,acpInitialModel:n,acpMcpTools:this.config.acpMcpTools,rawTransport:o,eventResultsPath:this.config.eventResultsPath,approvalMode:this.config.approvalMode,bindingStore:this.config.enableSessionBinding?this.bindingStore:void 0,aibotSessionId:e,autoInjectArgs:this.config.autoInjectArgs,nativeProviderScope:this.name,bridgeLog:this.config.logDir?new Qe(this.config.logDir,`${this.name}-${e}`):null})}async connectAibot(){const e=new V;this.aibotHandle=await e.connect(this.aibotConfig,{aborted:()=>this.stopped,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});const o=this.aibotHandle.authAck;if(this.applyAgentProfile(o?.agent_name,o?.introduction,{source:"auth_ack",respawnOnChange:!1}),this.aibotHandle.onEvent(t=>{this.handleAibotEvent(t).catch(s=>{u.error(this.name,`handleAibotEvent failed: ${s}`),this.aibotHandle.sendEventAck({event_id:t.event_id,session_id:t.session_id,received_at:Date.now()});const i=s instanceof Error?s.message:String(s);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(i)&&t.session_id){this.bindingStore.delete(t.session_id),this.sessionBindings.delete(t.session_id);const a=this.pool.getSlot(t.session_id);a?.adapter instanceof A&&a.adapter.getSessionBindings().delete(t.session_id);const r=this.config.adapterType??"acp",d=this.resolveBindingChannelKey(r);this.aibotHandle.sendMsg({event_id:t.event_id,session_id:t.session_id,msg_type:1,content:i,extra:{channel_data:{[d]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:g.invalidCwd}}}},quoted_message_id:t.msg_id});return}this.aibotHandle.sendEventResult({event_id:t.event_id,status:"failed",msg:i,updated_at:Date.now()})})}),this.aibotHandle.onStop(t=>{try{this.handleAibotStop(t)}catch(s){u.error(this.name,`handleAibotStop failed: ${s}`)}}),this.aibotHandle.onAgentDeleted(t=>{u.warn(this.name,`agent deleted on platform (source=${t?.source??"unknown"}${t?.reason?` reason=${t.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(s){u.error(this.name,`agentDeletedHandler failed: ${s}`)}}),this.aibotHandle.onShareSet(t=>{try{this.shareSetHandler?.(Array.isArray(t?.shared_to)?t.shared_to:[])}catch(s){u.error(this.name,`onShareSet failed: ${s}`)}}),this.aibotHandle.onProfilePush(t=>{try{this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"profile_push",respawnOnChange:!0})}catch(s){u.error(this.name,`onProfilePush failed: ${s}`)}}),this.aibotHandle.onSkillSync(t=>{try{u.info(this.name,`skill_sync received owner=${t?.owner_id??""} name=${t?.name??""}`),this.skillSyncHandler?.()}catch(s){u.error(this.name,`onSkillSync failed: ${s}`)}}),this.aibotHandle.onRevoke(t=>{try{this.handleAibotRevoke(t)}catch(s){u.error(this.name,`handleAibotRevoke failed: ${s}`)}}),this.aibotHandle.onLocalAction(t=>{this.handleAibotLocalAction(t).catch(s=>{u.error(this.name,`handleAibotLocalAction failed: ${s}`)})}),this.aibotHandle.onEventCancel(t=>{u.info(this.name,`recv event_cancel event_id=${t.event_id} session_id=${t.session_id}`),this.handleEventCancel(t).catch(s=>{u.error(this.name,`handleEventCancel failed: ${s}`)})}),this.aibotHandle.onMcpFrame((t,s)=>{const i=this.pool.getSlot(t)?.adapter;i?.deliverMcpFrameToAgent?i.deliverMcpFrameToAgent(s):u.warn(this.name,`mcp_frame: no adapter for session=${t}`)}),this.aibotHandle.onQueueClear(t=>{const s=this.pool.clearQueue(t.session_id);this.aibotHandle.sendQueueClearResult({session_id:t.session_id,canceled_event_ids:s}),this.pushQueueSnapshotForSession(t.session_id)}),this.aibotHandle.onQueueReorder(t=>{const s=Array.isArray(t.ordered_event_ids)?t.ordered_event_ids.filter(n=>typeof n=="string"&&n.length>0):[],i=this.pool.reorderQueue(t.session_id,s);this.aibotHandle.sendQueueReorderResult({session_id:t.session_id,applied_event_ids:i}),this.pushQueueSnapshotForSession(t.session_id)}),this.aibotHandle.onQueueSnapshotQuery(t=>{this.replyQueueSnapshotForSession(t.session_id)}),u.info(this.name,"Connected to aibot"),this.activeEventStore){const t=await this.activeEventStore.drain();if(t.length>0){u.warn(this.name,`Recovering ${t.length} stale event(s) from previous run`);for(const s of t)u.info(this.name,`Failing stale event on startup: ${s}`),this.aibotHandle.sendEventResult({event_id:s,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.aibotHandle.onReconnected(()=>{this.pushQueueSnapshots();const t=this.aibotHandle.authAck;this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"reconnect",respawnOnChange:!0})}),this.aibotHandle.onStreamRejected((t,s)=>{this.sendCtrl.markEventRejected(t)})}applyAgentProfile(e,o,t){const s=String(e??"").trim(),i=String(o??"").trim(),n=s!==this.agentProfile.agentName||i!==this.agentProfile.introduction;this.agentProfile={agentName:s,introduction:i},s||i?u.info(this.name,`agent profile (${t.source}): GOT name="${s}" intro_len=${i.length} changed=${n}`):u.warn(this.name,`agent profile (${t.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),n&&t.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const o=this.pool.getAllSlots();let t=0;for(const a of o)if(a.adapter.onAgentProfileChanged)try{a.adapter.onAgentProfileChanged(),t++}catch(r){u.warn(this.name,`onAgentProfileChanged failed for session=${a.sessionId}: ${r}`)}const s=o.filter(a=>a.adapter instanceof T),i=s.filter(a=>{if(a.state!=="ready")return!1;const r=a.adapter.getStatus();return!r.busy&&!r.backgroundBusy}),n=s.length-i.length;u.info(this.name,`${e}: notified ${t} adapter(s) via hook; respawning ${i.length} idle Claude slot(s), skipping ${n} busy`);for(const a of i)this.pool.removeSlot(a.sessionId).catch(r=>{u.warn(this.name,`removeSlot failed during ${e}: ${r}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const o=this.pool?.getQueueSnapshot(e)??null,t=o?[...o.running]:[],s=o?o.running_items.map(n=>({event_id:n.event_id,...n.content_preview?{content_preview:n.content_preview}:{},...n.title?{title:n.title}:{},...n.summary?{summary:n.summary}:{},actions:[{type:"stop"}]})):[],i=o?o.queued.map(n=>({event_id:n.event_id,position:n.position,...n.content_preview?{content_preview:n.content_preview}:{},...n.title?{title:n.title}:{},...n.summary?{summary:n.summary}:{},actions:[{type:"cancel"}]})):[];if(t.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const n=`selfdrive_${e}`,a=this.selfDrivenLabels.get(e)??"Background task in progress";t.push(n),s.push({event_id:n,content_preview:a,title:a,summary:a,actions:[]})}return{session_id:e,running:t,running_items:s,queued:i}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const o=this.buildQueueSnapshotPayload(e);u.info(this.name,`[queue-debug] push snapshot session=${e} running=${o.running.length} queued=${o.queued.length} running_ids=[${o.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(o)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,o,t){return e==="file_link"?je(o):e==="file_upload"?this.uploadFileAndSendMedia(o):this.aibotHandle.agentInvoke(e,o,t)}async uploadFileAndSendMedia(e){const o=String(e.file_path??"").trim(),t=String(e.session_id??"").trim(),s=String(e.caption??"").trim(),i=String(e.reply_to_message_id??"").trim();if(!o)throw new Error("file_path is required");if(!t)throw new Error("session_id is required");const n=await Je({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:t,filePath:o}),a=await this.aibotHandle.sendMedia({session_id:t,msg_type:2,content:s||`[${n.attachment_type}]`,client_msg_id:`file_upload_${M()}`,...i?{quoted_message_id:i}:{},extra:n.extra});if(a.cmd!=="send_ack"){const d=a.payload??{},c=String(d.msg??a.cmd);throw new Error(`media message send failed: ${c}`)}const r=a.payload??{};return{ok:!0,file_name:n.file_name,attachment_type:n.attachment_type,access_url:n.access_url,message_id:r.msg_id!=null?String(r.msg_id):null}}sendReplyByRuntimeConfig(e,o,t,s,i){this.indexEventSession(e,o),this.sendCtrl.sendReply(e,o,t,s,i),t&&this.conversationLog?.logOutbound?.(o,e,"reply",t)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:t,...s}=e;return s}const o=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return o?{...e,quoted_message_id:o}:e}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,o){return async(t,s,i)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(t,s,i,o)}catch(n){u.warn("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${t}: ${n}`)}u.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${t}`)}}sendStreamChunkByRuntimeConfig(e,o,t,s,i,n,a){this.indexEventSession(e,o),this.sendCtrl.sendStreamChunk(e,o,t,s,i,n,a),(t||i)&&this.conversationLog?.logOutbound?.(o,e,i?"stream_chunk_finish":"stream_chunk",t)}sendRunErrorAsChunk(e,o,t){this.sendStreamChunkByRuntimeConfig(e,o,`
11
+ Error: ${c}`,1,!1)},sendPermissionCard:r=>{if(u.info("bridge","sendPermissionCard callback entered",{rawTransport:o,eventId:r.eventId,sessionId:r.sessionId,toolCallId:r.toolCallId,toolName:r.toolName,toolTitle:r.toolTitle}),o){this.sendAcpRawEventEnvelope(r.eventId,r.sessionId,{type:"permission_request",payload:{tool_call_id:r.toolCallId,tool_name:r.toolName,tool_title:r.toolTitle,options:r.options}}),u.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:r.eventId,toolCallId:r.toolCallId});return}const d=`perm_${M()}`,c={event_id:r.eventId,session_id:r.sessionId,client_msg_id:d,msg_type:1,content:r.toolTitle?`Permission required: ${r.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:r.toolCallId,approvalSlug:r.toolName},grix:{execApproval:{approval_command_id:r.toolCallId,command:r.toolTitle||r.toolName,host:"acp"}}},agent_api_origin:!0}};u.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:r.eventId,sessionId:r.sessionId,clientMsgId:d,toolCallId:r.toolCallId,contentLength:c.content.length});try{this.aibotHandle.sendMsg(c),u.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:r.eventId,clientMsgId:d})}catch(l){u.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:r.eventId,clientMsgId:d,error:l instanceof Error?l.message:String(l)})}},sendAuthNotification:(r,d)=>{r&&this.aibotHandle.sendMsg({session_id:r,msg_type:1,content:d,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:d}}}}})},sendAgentMessage:(r,d)=>{r&&d&&this.aibotHandle.sendMsg({session_id:r,msg_type:1,content:d})},sendUpdateBindingCard:(r,d,c,l)=>{const h={...l??{}};if(!h.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const m=this.providerQuotaToRateLimits(this.cachedProviderQuota);m&&(h.rate_limits=m)}!h.provider_quota&&this.cachedProviderQuota?.success&&(h.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:d,cwd:c,...Object.keys(h).length>0?{meta:h}:{}})},onSkillsUpdate:r=>{try{this.aibotHandle.sendSkillsUpdate({skills:W(r,N.skills)})}catch(d){}},onContextWindowUpdated:r=>{this.cachedAcpContextWindow=r,this.cachedAcpContextWindowSampledAtMs=Date.now();const d="usedPercentage"in r?r.usedPercentage.toFixed(1):(r.used/r.size*100).toFixed(1);u.info(this.name,`[acp] context_window updated: ${d}%`);const c=this.bindingStore.get(e);if(c?.cwd){const l="usedPercentage"in r?r.usedPercentage:Math.min(100,r.used/r.size*100),h={context_window:{..."usedPercentage"in r?{}:r,usedPercentage:l,remainingPercentage:100-l}};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),h.provider_quota=this.cachedProviderQuota;const m=this.providerQuotaToRateLimits(this.cachedProviderQuota);m&&(h.rate_limits=m)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:c.cwd,meta:h})}},sendMcpFrame:r=>{this.aibotHandle.sendMcpFrame(e,r)},getAgentProfile:()=>this.agentProfile},s=e?this.bindingStore.get(e):void 0,i=this.globalConfigStore?.get(this.name),{initialModel:n,initialMode:a}=Ke({sessionBinding:s,globalDefaults:i,configInitialMode:this.config.acpInitialMode});return e&&n&&!s?.acpModelId&&this.bindingStore.setAcpModelId(e,n),(n||a)&&u.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${n??"<none>"} mode=${a??"<none>"}`),new A({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},t,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:a,acpInitialModel:n,acpMcpTools:this.config.acpMcpTools,rawTransport:o,eventResultsPath:this.config.eventResultsPath,approvalMode:this.config.approvalMode,bindingStore:this.config.enableSessionBinding?this.bindingStore:void 0,aibotSessionId:e,autoInjectArgs:this.config.autoInjectArgs,nativeProviderScope:this.name,bridgeLog:this.config.logDir?new Oe(this.config.logDir,`${this.name}-${e}`):null})}async connectAibot(){const e=new X;this.aibotHandle=await e.connect(this.aibotConfig,{aborted:()=>this.stopped,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});const o=this.aibotHandle.authAck;if(this.applyAgentProfile(o?.agent_name,o?.introduction,{source:"auth_ack",respawnOnChange:!1}),this.aibotHandle.onEvent(t=>{this.handleAibotEvent(t).catch(s=>{u.error(this.name,`handleAibotEvent failed: ${s}`),this.aibotHandle.sendEventAck({event_id:t.event_id,session_id:t.session_id,received_at:Date.now()});const i=s instanceof Error?s.message:String(s);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(i)&&t.session_id){this.bindingStore.delete(t.session_id),this.sessionBindings.delete(t.session_id);const a=this.pool.getSlot(t.session_id);a?.adapter instanceof A&&a.adapter.getSessionBindings().delete(t.session_id);const r=this.config.adapterType??"acp",d=this.resolveBindingChannelKey(r);this.aibotHandle.sendMsg({event_id:t.event_id,session_id:t.session_id,msg_type:1,content:i,extra:{channel_data:{[d]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:g.invalidCwd}}}},quoted_message_id:t.msg_id});return}this.aibotHandle.sendEventResult({event_id:t.event_id,status:"failed",msg:i,updated_at:Date.now()})})}),this.aibotHandle.onStop(t=>{try{this.handleAibotStop(t)}catch(s){u.error(this.name,`handleAibotStop failed: ${s}`)}}),this.aibotHandle.onAgentDeleted(t=>{u.warn(this.name,`agent deleted on platform (source=${t?.source??"unknown"}${t?.reason?` reason=${t.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(s){u.error(this.name,`agentDeletedHandler failed: ${s}`)}}),this.aibotHandle.onShareSet(t=>{try{this.shareSetHandler?.(Array.isArray(t?.shared_to)?t.shared_to:[])}catch(s){u.error(this.name,`onShareSet failed: ${s}`)}}),this.aibotHandle.onProfilePush(t=>{try{this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"profile_push",respawnOnChange:!0})}catch(s){u.error(this.name,`onProfilePush failed: ${s}`)}}),this.aibotHandle.onSkillSync(t=>{try{u.info(this.name,`skill_sync received owner=${t?.owner_id??""} name=${t?.name??""}`),this.skillSyncHandler?.()}catch(s){u.error(this.name,`onSkillSync failed: ${s}`)}}),this.aibotHandle.onRevoke(t=>{try{this.handleAibotRevoke(t)}catch(s){u.error(this.name,`handleAibotRevoke failed: ${s}`)}}),this.aibotHandle.onLocalAction(t=>{this.handleAibotLocalAction(t).catch(s=>{u.error(this.name,`handleAibotLocalAction failed: ${s}`)})}),this.aibotHandle.onEventCancel(t=>{u.info(this.name,`recv event_cancel event_id=${t.event_id} session_id=${t.session_id}`),this.handleEventCancel(t).catch(s=>{u.error(this.name,`handleEventCancel failed: ${s}`)})}),this.aibotHandle.onMcpFrame((t,s)=>{const i=this.pool.getSlot(t)?.adapter;i?.deliverMcpFrameToAgent?i.deliverMcpFrameToAgent(s):u.warn(this.name,`mcp_frame: no adapter for session=${t}`)}),this.aibotHandle.onQueueClear(t=>{const s=this.pool.clearQueue(t.session_id);this.aibotHandle.sendQueueClearResult({session_id:t.session_id,canceled_event_ids:s}),this.pushQueueSnapshotForSession(t.session_id)}),this.aibotHandle.onQueueReorder(t=>{const s=Array.isArray(t.ordered_event_ids)?t.ordered_event_ids.filter(n=>typeof n=="string"&&n.length>0):[],i=this.pool.reorderQueue(t.session_id,s);this.aibotHandle.sendQueueReorderResult({session_id:t.session_id,applied_event_ids:i}),this.pushQueueSnapshotForSession(t.session_id)}),this.aibotHandle.onQueueSnapshotQuery(t=>{this.replyQueueSnapshotForSession(t.session_id)}),u.info(this.name,"Connected to aibot"),this.activeEventStore){const t=await this.activeEventStore.drain();if(t.length>0){u.warn(this.name,`Recovering ${t.length} stale event(s) from previous run`);for(const s of t)u.info(this.name,`Failing stale event on startup: ${s}`),this.aibotHandle.sendEventResult({event_id:s,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.aibotHandle.onReconnected(()=>{this.pushQueueSnapshots();const t=this.aibotHandle.authAck;this.applyAgentProfile(t?.agent_name,t?.introduction,{source:"reconnect",respawnOnChange:!0})}),this.aibotHandle.onStreamRejected((t,s)=>{this.sendCtrl.markEventRejected(t)})}applyAgentProfile(e,o,t){const s=String(e??"").trim(),i=String(o??"").trim(),n=s!==this.agentProfile.agentName||i!==this.agentProfile.introduction;this.agentProfile={agentName:s,introduction:i},s||i?u.info(this.name,`agent profile (${t.source}): GOT name="${s}" intro_len=${i.length} changed=${n}`):u.warn(this.name,`agent profile (${t.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),n&&t.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const o=this.pool.getAllSlots();let t=0;for(const a of o)if(a.adapter.onAgentProfileChanged)try{a.adapter.onAgentProfileChanged(),t++}catch(r){u.warn(this.name,`onAgentProfileChanged failed for session=${a.sessionId}: ${r}`)}const s=o.filter(a=>a.adapter instanceof T),i=s.filter(a=>{if(a.state!=="ready")return!1;const r=a.adapter.getStatus();return!r.busy&&!r.backgroundBusy}),n=s.length-i.length;u.info(this.name,`${e}: notified ${t} adapter(s) via hook; respawning ${i.length} idle Claude slot(s), skipping ${n} busy`);for(const a of i)this.pool.removeSlot(a.sessionId).catch(r=>{u.warn(this.name,`removeSlot failed during ${e}: ${r}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const o=this.pool?.getQueueSnapshot(e)??null,t=o?[...o.running]:[],s=o?o.running_items.map(n=>({event_id:n.event_id,...n.content_preview?{content_preview:n.content_preview}:{},...n.title?{title:n.title}:{},...n.summary?{summary:n.summary}:{},actions:[{type:"stop"}]})):[],i=o?o.queued.map(n=>({event_id:n.event_id,position:n.position,...n.content_preview?{content_preview:n.content_preview}:{},...n.title?{title:n.title}:{},...n.summary?{summary:n.summary}:{},actions:[{type:"cancel"}]})):[];if(t.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const n=`selfdrive_${e}`,a=this.selfDrivenLabels.get(e)??"Background task in progress";t.push(n),s.push({event_id:n,content_preview:a,title:a,summary:a,actions:[]})}return{session_id:e,running:t,running_items:s,queued:i}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const o=this.buildQueueSnapshotPayload(e);u.info(this.name,`[queue-debug] push snapshot session=${e} running=${o.running.length} queued=${o.queued.length} running_ids=[${o.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(o)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,o,t){return e==="file_link"?Ye(o):e==="file_upload"?this.uploadFileAndSendMedia(o):this.aibotHandle.agentInvoke(e,o,t)}async uploadFileAndSendMedia(e){const o=String(e.file_path??"").trim(),t=String(e.session_id??"").trim(),s=String(e.caption??"").trim(),i=String(e.reply_to_message_id??"").trim();if(!o)throw new Error("file_path is required");if(!t)throw new Error("session_id is required");const n=await Ze({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:t,filePath:o}),a=await this.aibotHandle.sendMedia({session_id:t,msg_type:2,content:s||`[${n.attachment_type}]`,client_msg_id:`file_upload_${M()}`,...i?{quoted_message_id:i}:{},extra:n.extra});if(a.cmd!=="send_ack"){const d=a.payload??{},c=String(d.msg??a.cmd);throw new Error(`media message send failed: ${c}`)}const r=a.payload??{};return{ok:!0,file_name:n.file_name,attachment_type:n.attachment_type,access_url:n.access_url,message_id:r.msg_id!=null?String(r.msg_id):null}}sendReplyByRuntimeConfig(e,o,t,s,i){this.indexEventSession(e,o),this.sendCtrl.sendReply(e,o,t,s,i),t&&this.conversationLog?.logOutbound?.(o,e,"reply",t)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:t,...s}=e;return s}const o=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return o?{...e,quoted_message_id:o}:e}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,o){return async(t,s,i)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(t,s,i,o)}catch(n){u.warn("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${t}: ${n}`)}u.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${t}`)}}sendStreamChunkByRuntimeConfig(e,o,t,s,i,n,a){this.indexEventSession(e,o),this.sendCtrl.sendStreamChunk(e,o,t,s,i,n,a),(t||i)&&this.conversationLog?.logOutbound?.(o,e,i?"stream_chunk_finish":"stream_chunk",t)}sendRunErrorAsChunk(e,o,t){this.sendStreamChunkByRuntimeConfig(e,o,`
12
12
 
13
- Error: ${t}`,1,!1)}sendEventResultWithCleanup(e,o,t,s){this.sendCtrl.sendEventResult(e,o,t,s);const i=this.eventSessionIndex.get(e);i&&(this.pool.eventComplete(e,i),this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,o,t),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),o==="responded"&&(this.cachedProviderQuotaSampledAtMs=null,this.maybeQueryProviderQuota().catch(()=>{}))}async handleSessionInternalError(e){const{eventId:o,sessionId:t,errorMsg:s}=e;if(this.stopped)return;const i=this.inflightEvents.get(o);if(!i){u.warn(this.name,`[recovery] no inflight event for internalError event=${o} session=${t}; surface failure directly`),this.sendRunErrorAsChunk(o,t,s),this.sendEventResultWithCleanup(o,"failed",s,"agent_stop_failure");return}const n=(this.restartCount.get(o)??0)+1;this.restartCount.set(o,n);const a=this.config.adapterType??"acp";if(n>F){u.error(this.name,`[recovery] adapter=${a} session=${t} event=${o} restart=${n}/${F} outcome=give-up err=${s}`),this.sendRunErrorAsChunk(o,t,s),this.sendEventResultWithCleanup(o,"failed",s,"agent_stop_failure");return}u.info(this.name,`[recovery] adapter=${a} session=${t} event=${o} restart=${n}/${F} outcome=restarting err=${s}`);const r=this.pool.drainQueuedForSession(t);r.length>0&&u.info(this.name,`[recovery] session=${t} preserved ${r.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(t)}catch(l){u.warn(this.name,`[recovery] removeSlot failed session=${t}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const d=this.resolveRecoveryPrompt(a,i),c={...i,content:d};try{await this.pool.deliverInboundEvent(c)}catch(l){u.error(this.name,`[recovery] redeliver failed event=${o} session=${t}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(o,"failed",l instanceof Error?l.message:String(l));return}for(const l of r){if(this.stopped)break;try{await this.pool.deliverInboundEvent(l)}catch(h){u.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${t}: ${h instanceof Error?h.message:String(h)}`),this.sendEventResultWithCleanup(l.event_id,"failed",h instanceof Error?h.message:String(h))}}}resolveRecoveryPrompt(e,o){return e==="acp"?"continue":o.content}sendThinkingByRuntimeConfig(e,o,t){this.sendCtrl.sendThinking(e,o,t)}bufferStreamChunk(e,o,t,s,i){this.sendCtrl.bufferOnly(e,o,t,s,i)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),e.event_id&&!this.inflightEvents.has(e.event_id)&&this.inflightEvents.set(e.event_id,e)}indexEventSession(e,o){!e||!o||this.eventSessionIndex.set(e,o)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,o){return this.sendCtrl.shouldDropCodexDisplayEvent(e,o)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params?.delta;if(!t)return;const s=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(s,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:t.length,content:t})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,o){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,o)}sendAcpRawEventEnvelope(e,o,t){this.shouldDropAcpRawDisplayEvent(e,t.type)||this.aibotHandle.sendMsg({event_id:e,session_id:o,msg_type:1,content:this.buildAcpRawEventFallbackText(t),extra:{channel_data:{acp:{raw_event:t}},agent_api_origin:!0}})}buildAcpRawEventFallbackText(e){const o=String(e.type??"").trim();if(!o)return"[acp] event";switch(o){case"permission_request":return`Permission required: ${String(e.payload?.tool_title??e.payload?.tool_name??"permission request")}`;case"tool_use":return`[tool] ${String(e.payload?.tool_name??"tool")}`;case"tool_result":return"[tool result]";case"thinking":return"[thinking]";case"error":return`[error] ${String(e.payload?.message??"agent error")}`;case"result":return"[result]";default:return`[acp] ${o}`}}sendToolExecutionCard(e,o,t,s){this.sendCtrl.sendToolExecutionCard(e,o,t,s)}async handleAibotEvent(e){if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const o=this.config.adapterType??"acp",t=et(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=Ue(e);if(i){if(i.verb===p.exec){await this.handleSessionControlCommand(i,e);return}if(i.verb===p.listSessions){await this.handleListSessionsTextCommand(e);return}if(o==="claude"){await this.handleSessionControlCommand(i,e);return}if(o==="codex"&&i.verb===p.open){await this.handleCodexSessionControlOpen(i,e);return}if(o==="pi"&&i.verb===p.open){await this.handlePiSessionControlOpen(i,e);return}if(o==="pi"&&i.verb===p.restart){await this.handlePiSessionControlRestart(e);return}if((o==="openhuman"||o==="opencode")&&i.verb===p.open){await this.handleOpenHumanSessionControlOpen(i,e);return}if(o==="codewhale"&&i.verb===p.open){await this.handleCodeWhaleSessionControlOpen(i,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),i.verb===p.open){const r=i.args.trim();if(!r){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const d=P.resolve(r);if(!(await L(d)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:`Path is not a directory: ${d}`,updated_at:Date.now()});return}}catch(d){const c=String(d?.code??""),l=c==="ENOENT"?`Directory does not exist: ${P.resolve(r)}`:c==="EACCES"||c==="EPERM"?"Directory is not accessible":`Invalid path: ${r}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:l,updated_at:Date.now()});return}}if(i.verb===p.open){const r=this.bindingStore.get(e.session_id);if(r?.cwd)try{await L(r.cwd)}catch{u.info("bridge",`Stale binding detected for session ${e.session_id}: ${r.cwd} no longer exists, clearing`),this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id);const d=this.pool.getSlot(e.session_id);d?.adapter instanceof A&&d.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(i,e),o==="acp"&&i.verb===p.stop){const d=this.bindingStore.get(e.session_id)?.cwd??"";await this.pool.removeSlot(e.session_id).catch(()=>{}),this.sessionBindings.delete(e.session_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${d}`,updated_at:Date.now()});return}if(q(i,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(),sendEventAck:()=>{}}),i.verb===p.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),o==="agy")){const r=this.bindingStore.get(e.session_id)?.cwd??"";r&&this.aibotHandle.sendUpdateBindingCard({session_id:e.session_id,worker_status:"ready",cwd:r,meta:this.buildAgyToolbarMeta(e.session_id)})}return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}if(ht.has(o)&&!this.bindingStore.get(e.session_id)?.cwd){const d=o;u.info(this.name,`[${d}] binding missing session_id=${e.session_id} event_id=${e.event_id}`),this.deferredMgr.defer(d,String(e.session_id??"").trim(),this.buildInboundEvent(e,s));const c=this.resolveBindingChannelKey(o);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[c]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:g.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const d=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(d){const[,c,l]=d,m=this.pool.getSlot(e.session_id)?.adapter;if(m?.execCommand&&(m.getSupportedCommands?.()??[]).some(_=>_.name===c||_.name===`/${c}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const _=await m.execCommand(c,l.trim(),e.session_id);_.status==="options"&&_.data&&this.handleExecCommandOptions(e.session_id,c,_.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:_.status==="failed"?"failed":"responded",msg:_.message,updated_at:Date.now()})}catch(_){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:_ instanceof Error?_.message:String(_),updated_at:Date.now()})}return}}}const a=this.buildInboundEvent(e,s);try{this.captureEventRuntimeConfig(a),await this.pool.deliverInboundEvent(a)}catch(r){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.discardEventTrackingState(e.event_id),r instanceof Oe)this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:r.message,updated_at:Date.now()});else throw r}}async handleCodexSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(a,r)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:a,...r,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const a=await this.resolveCwdForBinding(s),r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(r.cwd)===a){i(),n("responded",{msg:`Session already bound to ${r.cwd}`});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){i(),n("failed",{msg:`Session already bound to ${r.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,a),this.sessionBindings.set(t,a),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),i(),n("responded",{msg:`Session bound to ${a}`})}catch(a){i(),n("failed",{code:g.invalidCwd,msg:a instanceof Error?a.message:String(a)})}}async handleSessionControlForPool(e,o){e.verb===p.open&&await this.bindSessionForPool(o.session_id,e.args.trim())}async replayDeferredEventsForSession(e){await this.deferredMgr.release(e,this.deferredCallbacks())}async handleSessionControlLocalActionForPool(e){if(String(e.action_type??"")!==b.sessionControl)return;const o=e.params??{};if(String(o.verb??"").trim().toLowerCase()!==p.open)return;const s=String(o.session_id??"").trim(),i=String(o.cwd??"").trim();!s||!i||await this.bindSessionForPool(s,i)}async handleCodexSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){n("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const a=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,a);const r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(r.cwd);if(c===a){this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){n("failed",void 0,g.rebindForbidden,`Session already bound to ${r.cwd}`);return}}this.bindingStore.set(t,a),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,a),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,a)})}catch(a){n("failed",void 0,a?.sessionControlErrorCode??g.invalidCwd,a instanceof Error?a.message:String(a))}}async handleCursorSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){n("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const a=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,a);const r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(r.cwd);if(c===a){this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale cursor binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){n("failed",void 0,g.rebindForbidden,`Session already bound to ${r.cwd}`);return}}this.bindingStore.set(t,a),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,a),this.deferredMgr.sendCursorDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,a)})}catch(a){n("failed",void 0,a?.sessionControlErrorCode??g.invalidCwd,a instanceof Error?a.message:String(a))}}async handlePiSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(a,r)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:a,...r,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const a=await this.resolveCwdForBinding(s),r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(r.cwd)===a){i(),n("responded",{msg:`Session already bound to ${r.cwd}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Session already bound to \`${r.cwd}\``,quoted_message_id:o.msg_id});return}}catch{d=!0,u.info("bridge",`Stale pi binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){i(),n("failed",{msg:`Session already bound to ${r.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,a),this.sessionBindings.set(t,a),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),i(),n("responded",{msg:`Session bound to ${a}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Working directory bound: \`${a}\``,quoted_message_id:o.msg_id})}catch(a){i(),n("failed",{code:g.invalidCwd,msg:a instanceof Error?a.message:String(a)})}}async handlePiSessionControlRestart(e){const o=e.session_id,t=()=>this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:o,received_at:Date.now()}),s=(a,r)=>this.aibotHandle.sendEventResult({event_id:e.event_id,status:a,...r,updated_at:Date.now()}),n=this.bindingStore.get(o)?.cwd??"";if(!n){t(),s("failed",{msg:"session binding was not found",code:g.bindingMissing});return}t(),await this.pool.removeSlot(o).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:n}),s("responded",{msg:`Session worker restarted for ${n}`})}async handlePiSessionControlRestartLocalAction(e){const o=e.params??{},t=String(o.session_id??"").trim(),i=(t?this.bindingStore.get(t):void 0)?.cwd??"",n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t){n("failed",void 0,"session_id_required","session_id is required for restart");return}if(!i){n("failed",void 0,g.bindingMissing,"Session binding missing. Open a workspace first.");return}await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i}),n("ok",{outcome:"restarted",binding:{aibotSessionId:t,cwd:i,workerStatus:"ready"}})}async bindSessionForPool(e,o){const t=String(o??"").trim();if(!e||!t)return;const s=this.pool.getOrCreateSlot(e);if(!s||(s.startPromise&&await s.startPromise,!s.adapter))return;const i=s.adapter instanceof A?s.adapter:null;if(!i?.hasSessionBinding)return;const n=await this.resolveCwdForBinding(t);i.announceDeferredComposing(e),await i.bindSession(e,n),this.sessionBindings.set(e,n),this.sessionScanCache.invalidate(),i.replayDeferredEvents(e)}deferredCallbacks(){return{captureEventRuntimeConfig:e=>this.captureEventRuntimeConfig(e),deliverInboundEvent:e=>this.pool.deliverInboundEvent(e),sendEventResult:(e,o,t)=>this.sendEventResultWithCleanup(e,o,t),sendSessionComposing:(e,o,t)=>{const s={};o&&(s.ttl_ms=t?.ttlMs??3e4,t?.activity&&(s.activity=t.activity)),this.aibotHandle.sendSessionActivitySet({session_id:e,kind:"composing",active:o,...s})}}}async handleOpenHumanSessionControlOpen(e,o){const t=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:o.session_id,received_at:Date.now()});try{await this.resolveCwdForBinding(e.args.trim()),await this.handleSessionControlForPool(e,o),q(e,o,this.sessionControlCtx(o.session_id),this.sessionControlSenders()),await this.deferredMgr.release(o.session_id,this.deferredCallbacks())}catch(s){t(),this.aibotHandle.sendEventResult({event_id:o.event_id,status:"failed",code:s?.cwdErrorCode,msg:s instanceof Error?s.message:String(s),updated_at:Date.now()})}}async handleCodeWhaleSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(a,r)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:a,...r,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const a=await this.resolveCwdForBinding(s),r=this.bindingStore.get(t);if(r?.cwd){if(await this.resolveCwdForBinding(r.cwd)!==a){i(),n("failed",{msg:`Session already bound to ${r.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}i(),n("responded",{msg:`Session already bound to ${r.cwd}`});return}this.bindingStore.set(t,a),this.sessionBindings.set(t,a),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),i(),n("responded",{msg:`Session bound to ${a}`})}catch(a){i(),n("failed",{code:g.invalidCwd,msg:a instanceof Error?a.message:String(a)})}}async handleCodeWhaleSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){n("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const a=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,a);const r=this.bindingStore.get(t);if(r?.cwd){const d=await this.resolveCwdForBinding(r.cwd);if(d!==a){n("failed",void 0,g.rebindForbidden,`Session already bound to ${r.cwd}`);return}this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,d)});return}this.bindingStore.set(t,a),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,a),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,a)})}catch(a){n("failed",void 0,a?.sessionControlErrorCode??g.invalidCwd,a instanceof Error?a.message:String(a))}}normalizeClaudeModeId(e){return String(e??"").trim().toLowerCase()===C.approval?C.approval:C.fullAuto}handleExecCommandOptions(e,o,t){const s=Array.isArray(t?.options)?t.options:[];if(s.length===0)return;const n=this.bindingStore.get(e)?.cwd??"",a={};if(o==="model"){a.available_models=s.map(d=>({id:d.id,displayName:d.label}));const r=s.find(d=>d.current);r&&(a.model_id=r.id)}else if(o==="mode"){a.available_modes=s.map(d=>({id:d.id,displayName:d.label}));const r=s.find(d=>d.current);r&&(a.mode_id=r.id)}else a[`${o}_options`]=s;this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:n,meta:a})}resolveSessionModelId(e){const o=this.bindingStore.getModelId(e);if(o)return o;const t=String(this.globalConfigStore?.get(this.name)?.modelId??"").trim();if(t)return this.bindingStore.setModelId(e,t),t}resolveCodexSessionModelId(e){const o=this.bindingStore.getCodexModelId(e);if(o)return o;const t=String(this.globalConfigStore?.get(this.name)?.codexModelId??"").trim();if(t)return this.bindingStore.setCodexModelId(e,t),t}buildAgyToolbarMeta(e){if(!this.bindingStore.get(e))return;const t=ee(this.config.agent.command),s=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||s;t.length>0&&!t.some(a=>a.id===i)&&(i=s);const n=te();return{model_id:i,currentModelId:i,available_models:t.map(a=>({id:a.id,displayName:a.displayName})),...n.plan!==void 0&&{plan:n.plan},...n.quota_exhausted!==void 0&&{quota_exhausted:n.quota_exhausted},...n.quota_reset_at!==void 0&&{quota_reset_at:n.quota_reset_at},...n.available_credits!==void 0&&{available_credits:n.available_credits}}}async handleAgySetModel(e,o){const t=e.params??{},s=String(t.model_id??t.modelId??"").trim();if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for set_model"});return}if(!s){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"set_model_invalid",error_msg:"model_id is required"});return}const i=this.bindingStore.get(o);if(!i?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"session binding was not found"});return}i.modelId!==s&&(this.bindingStore.setModelId(o,s),this.globalConfigStore?.set(this.name,{modelId:s})),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:i.cwd,meta:this.buildAgyToolbarMeta(o)}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"model_set",model_id:s,binding:{cwd:i.cwd,model_id:s}}})}buildClaudeToolbarMeta(e){const o=this.bindingStore.get(e);if(!o)return;const t=Q(),s=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||s;t.length>0&&!t.some(l=>l.id===i)&&(i=s);const n=this.normalizeClaudeModeId(o.modeId),a={model_id:i,mode_id:n,currentModelId:i,currentModeId:n,available_models:t.map(l=>({id:l.id,displayName:l.displayName}))},r=this.pool.getSlot(e),d=r?.adapter instanceof T?r.adapter.getSessionState():null;(d?.rateLimits?.fiveHour||d?.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=d);const c=d??this.getFreshClaudeRateLimitState();if(c){const l=c.rateLimits;l&&(l.fiveHour||l.sevenDay)&&(a.rate_limits={...l.fiveHour?{fiveHour:l.fiveHour}:{},...l.sevenDay?{sevenDay:l.sevenDay}:{},sampledAt:c.sampledAt||Date.now()})}if(d){const l=d.contextWindow;l.usedPercentage!=null&&(a.context_window={usedPercentage:l.usedPercentage,remainingPercentage:l.remainingPercentage})}if(!a.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const l=this.providerQuotaToRateLimits(this.cachedProviderQuota);l&&(a.rate_limits=l),u.info(this.name,`[toolbar-meta] provider quota fallback: hasCached=${!!this.cachedProviderQuota} fromProvider=${JSON.stringify(l)}`)}return a.rate_limits&&u.info(this.name,`[toolbar-meta] rate_limits included: ${JSON.stringify(a.rate_limits)}`),a}providerQuotaToCodexRateLimits(e){const o=e.tiers.find(i=>i.name==="five_hour"),t=e.tiers.find(i=>i.name==="weekly_limit"),s=i=>i||null;if(o||t){const i={credits:{hasCredits:!0,unlimited:!1,balance:null},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()};let n=0,a=0,r=0,d=0;return o&&(i.primary={usedPercent:o.usedPercent,windowMinutes:300,resetsAt:s(o.resetsAt)},n=o.usedPercent,a=300),t&&(i.secondary={usedPercent:t.usedPercent,windowMinutes:10080,resetsAt:s(t.resetsAt)},r=t.usedPercent,d=10080),{rateLimits:i,primaryPercent:n,secondaryPercent:r,primaryWindowMin:a,secondaryWindowMin:d}}if(e.balance){const i=e.balance,n=i.total&&i.total>0?Math.min(100,(i.used??i.total-i.remaining)/i.total*100):0;return{rateLimits:{primary:{usedPercent:n,windowMinutes:0,resetsAt:null},secondary:{usedPercent:0,windowMinutes:0,resetsAt:null},credits:{hasCredits:!0,unlimited:!1,balance:i.remaining},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()},primaryPercent:n,secondaryPercent:0,primaryWindowMin:0,secondaryWindowMin:0}}return null}providerQuotaToRateLimits(e){const o=i=>{if(!i)return 0;const n=Date.parse(i);return Number.isFinite(n)?Math.floor(n/1e3):0},t=e.tiers.find(i=>i.name==="five_hour"),s=e.tiers.find(i=>i.name==="weekly_limit");if(t||s)return{...t?{fiveHour:{usedPercentage:t.usedPercent,resetsAt:o(t.resetsAt)}}:{},...s?{sevenDay:{usedPercentage:s.usedPercent,resetsAt:o(s.resetsAt)}}:{},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()};if(e.balance){const i=e.balance;return{credit:{remaining:i.remaining,total:i.total,used:i.used,unit:i.unit,resetsAt:i.resetsAt?o(i.resetsAt):0},planName:e.planName,sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()}}return null}async resolveCwdForBinding(e){const o=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(o)||/^\\\\/.test(o))){const i=new Error(`Specified path is not valid on this host: ${o}`);throw i.cwdErrorCode=g.invalidCwd,i}const t=P.resolve(o);let s;try{s=await L(t)}catch(i){const n=String(i?.code??"");if(n==="ENOENT"){const a=new Error(`Specified path does not exist: ${t}`);throw a.cwdErrorCode=g.invalidCwd,a}if(n==="EACCES"||n==="EPERM"){const a=new Error("Specified path is not accessible.");throw a.cwdErrorCode=g.invalidCwd,a}throw i}if(!s.isDirectory()){const i=new Error("Specified path is not a directory.");throw i.cwdErrorCode=g.invalidCwd,i}try{return await K(t)}catch{return t}}getClaudeWorkerStatus(e){const o=this.pool.getSlot(e);return o?o.state==="starting"?"starting":o.state==="stopped"?"stopped":o.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,o){const t=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,t),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:t,cwd:o,meta:this.buildClaudeToolbarMeta(e)}),t}reportSessionSkills(e){const o=ne(this.config.adapterType,this.config.aibot.clientType),t=this.bindingStore.get(e)?.cwd||this.sessionBindings.get(e)||void 0,s=o==="kiro"?t:t||process.cwd();let i;try{i=se({mode:o,projectDir:s})}catch{return}if(i.length===0)return;const n=JSON.stringify(i.map(a=>`${a.source}:${a.name}`));if(n!==this.lastReportedSkillsHash){this.lastReportedSkillsHash=n;try{this.aibotHandle.sendSkillsUpdate({skills:i})}catch{}}}async ensureSlotStarted(e,o=6e4){const t=this.pool.getOrCreateSlot(e);if(!t)throw new Error("Failed to allocate session slot");t.startPromise&&(u.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([t.startPromise,new Promise((s,i)=>setTimeout(()=>i(new Error(`ensureSlotStarted timeout (${o}ms) session=${e}`)),o))]),u.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveOrphanTitle(e){if(!e||!this.reasonixTitleScan)return;const o=ve(e);if(!o)return;const t=this.reasonixTitleScan.get().filter(s=>s.stamp===o);return t.length===1?t[0].title:void 0}resolveAgentSessionId(e){switch(this.config.adapterType??"acp"){case"claude":return e.claudeSessionId;case"codex":return e.codexThreadId;case"pi":return e.piSessionPath;case"codewhale":return e.codewhaleThreadId;case"agy":return e.agyConversationId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":return e;default:return"acp"}}setResolvedAgentSessionId(e,o){const t=String(e??"").trim(),s=String(o??"").trim();if(!t||!s)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(t,s);break;case"codex":this.bindingStore.setCodexThreadId(t,s);break;case"pi":this.bindingStore.setPiSessionPath(t,s);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(t,s);break;case"agy":this.bindingStore.setAgyConversationId(t,s);break;default:this.bindingStore.setAcpSessionId(t,s);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const o=String(e??"").trim();if(!o)return"";const t=P.resolve(o);return process.platform==="win32"?t.toLowerCase():t}ensureImportedAgentSession(e,o){const t=String(e??"").trim();if(!t)return;const s=this.normalizePathForCompare(o);let i="";const n=this.config.adapterType??"acp";if(n==="codex"?i=this.sessionScanCache.get().find(d=>d.threadId===t)?.cwd??"":n==="claude"?i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??"":n==="acp"&&(i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??""),!i){for(const[,r]of this.bindingStore.entries())if(this.resolveAgentSessionId(r)===t){i=r.cwd??"";break}}if(!i){const r=new Error(`agent session not found: ${t}`);throw r.sessionControlErrorCode=g.invalidAgentSession,r}const a=this.normalizePathForCompare(i);if(a&&s&&a!==s){const r=new Error(`agent session cwd mismatch: expected ${o}, got ${i}`);throw r.sessionControlErrorCode=g.invalidAgentSession,r}}buildOpenedBindingResult(e,o,t="ready"){const s=this.bindingStore.get(e),i=s?String(this.resolveAgentSessionId(s)??"").trim():"",n={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:o,workerStatus:t};return i&&(n.bindingId=i,n.agentSessionId=i),n}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"}async handleListSessionsTextCommand(e){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const o=this.config.adapterType??"acp",t=new Map;for(const r of this.pool.getAllSlots())t.set(r.sessionId,r);const s=Array.from(this.bindingStore.entries()),i=new Map;for(const[r,d]of s){const c=this.resolveAgentSessionId(d);if(c){const l=t.get(r),h=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(c,{aibotSessionId:r,workerStatus:h})}}const n=[],a=new Set;if(o==="codex"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.threadId);const c=i.get(d.threadId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.threadId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??(d.archived?"archived":"inactive")}`),n.push(` Created: ${new Date(d.createdAt).toISOString()}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="claude"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="acp"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="pi"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionPath);const c=i.get(d.sessionPath);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionPath}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="codewhale"||o==="cursor"||o==="opencode"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}for(const[r,d]of s){const c=this.resolveAgentSessionId(d);if(c&&a.has(c))continue;const l=t.get(r),h=l?l.adapter.getStatus().busy?"busy":"ready":"closed",m=this.resolveOrphanTitle(c)??(c?c.slice(0,8)+"\u2026":r.slice(0,8)+"\u2026");n.push(` Title: ${m}`),n.push(` AIBot: ${r}`),c&&n.push(` Agent: ${c}`),n.push(` CWD: ${d.cwd??"-"}`),n.push(` State: ${h}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}if(n.length===0){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:"No sessions found.",updated_at:Date.now()});return}this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Sessions (${n.filter(r=>r==="---").length}):
13
+ Error: ${t}`,1,!1)}sendEventResultWithCleanup(e,o,t,s){this.sendCtrl.sendEventResult(e,o,t,s);const i=this.eventSessionIndex.get(e);i&&(this.pool.eventComplete(e,i),this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,o,t),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),o==="responded"&&(this.cachedProviderQuotaSampledAtMs=null,this.maybeQueryProviderQuota().catch(()=>{}))}async handleSessionInternalError(e){const{eventId:o,sessionId:t,errorMsg:s}=e;if(this.stopped)return;const i=this.inflightEvents.get(o);if(!i){u.warn(this.name,`[recovery] no inflight event for internalError event=${o} session=${t}; surface failure directly`),this.sendRunErrorAsChunk(o,t,s),this.sendEventResultWithCleanup(o,"failed",s,"agent_stop_failure");return}const n=(this.restartCount.get(o)??0)+1;this.restartCount.set(o,n);const a=this.config.adapterType??"acp";if(n>F){u.error(this.name,`[recovery] adapter=${a} session=${t} event=${o} restart=${n}/${F} outcome=give-up err=${s}`),this.sendRunErrorAsChunk(o,t,s),this.sendEventResultWithCleanup(o,"failed",s,"agent_stop_failure");return}u.info(this.name,`[recovery] adapter=${a} session=${t} event=${o} restart=${n}/${F} outcome=restarting err=${s}`);const r=this.pool.drainQueuedForSession(t);r.length>0&&u.info(this.name,`[recovery] session=${t} preserved ${r.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(t)}catch(l){u.warn(this.name,`[recovery] removeSlot failed session=${t}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const d=this.resolveRecoveryPrompt(a,i),c={...i,content:d};try{await this.pool.deliverInboundEvent(c)}catch(l){u.error(this.name,`[recovery] redeliver failed event=${o} session=${t}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(o,"failed",l instanceof Error?l.message:String(l));return}for(const l of r){if(this.stopped)break;try{await this.pool.deliverInboundEvent(l)}catch(h){u.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${t}: ${h instanceof Error?h.message:String(h)}`),this.sendEventResultWithCleanup(l.event_id,"failed",h instanceof Error?h.message:String(h))}}}resolveRecoveryPrompt(e,o){return e==="acp"?"continue":o.content}sendThinkingByRuntimeConfig(e,o,t){this.sendCtrl.sendThinking(e,o,t)}bufferStreamChunk(e,o,t,s,i){this.sendCtrl.bufferOnly(e,o,t,s,i)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),e.event_id&&!this.inflightEvents.has(e.event_id)&&this.inflightEvents.set(e.event_id,e)}indexEventSession(e,o){!e||!o||this.eventSessionIndex.set(e,o)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,o){return this.sendCtrl.shouldDropCodexDisplayEvent(e,o)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params?.delta;if(!t)return;const s=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(s,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:t.length,content:t})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,o){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,o)}sendAcpRawEventEnvelope(e,o,t){this.shouldDropAcpRawDisplayEvent(e,t.type)||this.aibotHandle.sendMsg({event_id:e,session_id:o,msg_type:1,content:this.buildAcpRawEventFallbackText(t),extra:{channel_data:{acp:{raw_event:t}},agent_api_origin:!0}})}buildAcpRawEventFallbackText(e){const o=String(e.type??"").trim();if(!o)return"[acp] event";switch(o){case"permission_request":return`Permission required: ${String(e.payload?.tool_title??e.payload?.tool_name??"permission request")}`;case"tool_use":return`[tool] ${String(e.payload?.tool_name??"tool")}`;case"tool_result":return"[tool result]";case"thinking":return"[thinking]";case"error":return`[error] ${String(e.payload?.message??"agent error")}`;case"result":return"[result]";default:return`[acp] ${o}`}}sendToolExecutionCard(e,o,t,s){this.sendCtrl.sendToolExecutionCard(e,o,t,s)}async handleAibotEvent(e){if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const o=this.config.adapterType??"acp",t=nt(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=Ne(e);if(i){if(i.verb===p.exec){await this.handleSessionControlCommand(i,e);return}if(i.verb===p.listSessions){await this.handleListSessionsTextCommand(e);return}if(o==="claude"){await this.handleSessionControlCommand(i,e);return}if(o==="codex"&&i.verb===p.open){await this.handleCodexSessionControlOpen(i,e);return}if(o==="pi"&&i.verb===p.open){await this.handlePiSessionControlOpen(i,e);return}if(o==="pi"&&i.verb===p.restart){await this.handlePiSessionControlRestart(e);return}if((o==="openhuman"||o==="opencode")&&i.verb===p.open){await this.handleOpenHumanSessionControlOpen(i,e);return}if(o==="codewhale"&&i.verb===p.open){await this.handleCodeWhaleSessionControlOpen(i,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),i.verb===p.open){const r=i.args.trim();if(!r){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const d=P.resolve(r);if(!(await L(d)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:`Path is not a directory: ${d}`,updated_at:Date.now()});return}}catch(d){const c=String(d?.code??""),l=c==="ENOENT"?`Directory does not exist: ${P.resolve(r)}`:c==="EACCES"||c==="EPERM"?"Directory is not accessible":`Invalid path: ${r}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:g.invalidCwd,msg:l,updated_at:Date.now()});return}}if(i.verb===p.open){const r=this.bindingStore.get(e.session_id);if(r?.cwd)try{await L(r.cwd)}catch{u.info("bridge",`Stale binding detected for session ${e.session_id}: ${r.cwd} no longer exists, clearing`),this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id);const d=this.pool.getSlot(e.session_id);d?.adapter instanceof A&&d.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(i,e),o==="acp"&&i.verb===p.stop){const d=this.bindingStore.get(e.session_id)?.cwd??"";await this.pool.removeSlot(e.session_id).catch(()=>{}),this.sessionBindings.delete(e.session_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${d}`,updated_at:Date.now()});return}if(z(i,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(),sendEventAck:()=>{}}),i.verb===p.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),o==="agy")){const r=this.bindingStore.get(e.session_id)?.cwd??"";r&&this.aibotHandle.sendUpdateBindingCard({session_id:e.session_id,worker_status:"ready",cwd:r,meta:this.buildAgyToolbarMeta(e.session_id)})}return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}if(pt.has(o)&&!this.bindingStore.get(e.session_id)?.cwd){const d=o;u.info(this.name,`[${d}] binding missing session_id=${e.session_id} event_id=${e.event_id}`),this.deferredMgr.defer(d,String(e.session_id??"").trim(),this.buildInboundEvent(e,s));const c=this.resolveBindingChannelKey(o);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[c]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:g.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const d=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(d){const[,c,l]=d,m=this.pool.getSlot(e.session_id)?.adapter;if(m?.execCommand&&(m.getSupportedCommands?.()??[]).some(_=>_.name===c||_.name===`/${c}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const _=await m.execCommand(c,l.trim(),e.session_id);_.status==="options"&&_.data&&this.handleExecCommandOptions(e.session_id,c,_.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:_.status==="failed"?"failed":"responded",msg:_.message,updated_at:Date.now()})}catch(_){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:_ instanceof Error?_.message:String(_),updated_at:Date.now()})}return}}}const a=this.buildInboundEvent(e,s);try{this.captureEventRuntimeConfig(a),await this.pool.deliverInboundEvent(a)}catch(r){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.discardEventTrackingState(e.event_id),r instanceof We)this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:r.message,updated_at:Date.now()});else throw r}}async handleCodexSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(a,r)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:a,...r,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const a=await this.resolveCwdForBinding(s),r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(r.cwd)===a){i(),n("responded",{msg:`Session already bound to ${r.cwd}`});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){i(),n("failed",{msg:`Session already bound to ${r.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,a),this.sessionBindings.set(t,a),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),i(),n("responded",{msg:`Session bound to ${a}`})}catch(a){i(),n("failed",{code:g.invalidCwd,msg:a instanceof Error?a.message:String(a)})}}async handleSessionControlForPool(e,o){e.verb===p.open&&await this.bindSessionForPool(o.session_id,e.args.trim())}async replayDeferredEventsForSession(e){await this.deferredMgr.release(e,this.deferredCallbacks())}async handleSessionControlLocalActionForPool(e){if(String(e.action_type??"")!==b.sessionControl)return;const o=e.params??{};if(String(o.verb??"").trim().toLowerCase()!==p.open)return;const s=String(o.session_id??"").trim(),i=String(o.cwd??"").trim();!s||!i||await this.bindSessionForPool(s,i)}async handleCodexSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){n("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const a=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,a);const r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(r.cwd);if(c===a){this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale codex binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){n("failed",void 0,g.rebindForbidden,`Session already bound to ${r.cwd}`);return}}this.bindingStore.set(t,a),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,a),this.deferredMgr.sendCodexDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,a)})}catch(a){n("failed",void 0,a?.sessionControlErrorCode??g.invalidCwd,a instanceof Error?a.message:String(a))}}async handleCursorSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){n("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const a=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,a);const r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{const c=await this.resolveCwdForBinding(r.cwd);if(c===a){this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,c)});return}}catch{d=!0,u.info("bridge",`Stale cursor binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){n("failed",void 0,g.rebindForbidden,`Session already bound to ${r.cwd}`);return}}this.bindingStore.set(t,a),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,a),this.deferredMgr.sendCursorDeferredReplayComposing(t,this.deferredCallbacks()),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,a)})}catch(a){n("failed",void 0,a?.sessionControlErrorCode??g.invalidCwd,a instanceof Error?a.message:String(a))}}async handlePiSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(a,r)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:a,...r,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const a=await this.resolveCwdForBinding(s),r=this.bindingStore.get(t);if(r?.cwd){let d=!1;try{if(await this.resolveCwdForBinding(r.cwd)===a){i(),n("responded",{msg:`Session already bound to ${r.cwd}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Session already bound to \`${r.cwd}\``,quoted_message_id:o.msg_id});return}}catch{d=!0,u.info("bridge",`Stale pi binding for session ${t}: ${r.cwd} no longer exists, allowing rebind`)}if(!d){i(),n("failed",{msg:`Session already bound to ${r.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}}this.bindingStore.set(t,a),this.sessionBindings.set(t,a),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),i(),n("responded",{msg:`Session bound to ${a}`}),this.aibotHandle.sendMsg({event_id:o.event_id,session_id:t,msg_type:1,content:`\u2705 Working directory bound: \`${a}\``,quoted_message_id:o.msg_id})}catch(a){i(),n("failed",{code:g.invalidCwd,msg:a instanceof Error?a.message:String(a)})}}async handlePiSessionControlRestart(e){const o=e.session_id,t=()=>this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:o,received_at:Date.now()}),s=(a,r)=>this.aibotHandle.sendEventResult({event_id:e.event_id,status:a,...r,updated_at:Date.now()}),n=this.bindingStore.get(o)?.cwd??"";if(!n){t(),s("failed",{msg:"session binding was not found",code:g.bindingMissing});return}t(),await this.pool.removeSlot(o).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:n}),s("responded",{msg:`Session worker restarted for ${n}`})}async handlePiSessionControlRestartLocalAction(e){const o=e.params??{},t=String(o.session_id??"").trim(),i=(t?this.bindingStore.get(t):void 0)?.cwd??"",n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t){n("failed",void 0,"session_id_required","session_id is required for restart");return}if(!i){n("failed",void 0,g.bindingMissing,"Session binding missing. Open a workspace first.");return}await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:i}),n("ok",{outcome:"restarted",binding:{aibotSessionId:t,cwd:i,workerStatus:"ready"}})}async bindSessionForPool(e,o){const t=String(o??"").trim();if(!e||!t)return;const s=this.pool.getOrCreateSlot(e);if(!s||(s.startPromise&&await s.startPromise,!s.adapter))return;const i=s.adapter instanceof A?s.adapter:null;if(!i?.hasSessionBinding)return;const n=await this.resolveCwdForBinding(t);i.announceDeferredComposing(e),await i.bindSession(e,n),this.sessionBindings.set(e,n),this.sessionScanCache.invalidate(),i.replayDeferredEvents(e)}deferredCallbacks(){return{captureEventRuntimeConfig:e=>this.captureEventRuntimeConfig(e),deliverInboundEvent:e=>this.pool.deliverInboundEvent(e),sendEventResult:(e,o,t)=>this.sendEventResultWithCleanup(e,o,t),sendSessionComposing:(e,o,t)=>{const s={};o&&(s.ttl_ms=t?.ttlMs??3e4,t?.activity&&(s.activity=t.activity)),this.aibotHandle.sendSessionActivitySet({session_id:e,kind:"composing",active:o,...s})}}}async handleOpenHumanSessionControlOpen(e,o){const t=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:o.session_id,received_at:Date.now()});try{await this.resolveCwdForBinding(e.args.trim()),await this.handleSessionControlForPool(e,o),z(e,o,this.sessionControlCtx(o.session_id),this.sessionControlSenders()),await this.deferredMgr.release(o.session_id,this.deferredCallbacks())}catch(s){t(),this.aibotHandle.sendEventResult({event_id:o.event_id,status:"failed",code:s?.cwdErrorCode,msg:s instanceof Error?s.message:String(s),updated_at:Date.now()})}}async handleCodeWhaleSessionControlOpen(e,o){const t=o.session_id,s=e.args.trim(),i=()=>this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()}),n=(a,r)=>this.aibotHandle.sendEventResult({event_id:o.event_id,status:a,...r,updated_at:Date.now()});if(!s){i(),n("failed",{msg:"Usage: /grix open <working-directory>",code:g.cwdRequired});return}try{const a=await this.resolveCwdForBinding(s),r=this.bindingStore.get(t);if(r?.cwd){if(await this.resolveCwdForBinding(r.cwd)!==a){i(),n("failed",{msg:`Session already bound to ${r.cwd}. Rebinding is not allowed.`,code:g.rebindForbidden});return}i(),n("responded",{msg:`Session already bound to ${r.cwd}`});return}this.bindingStore.set(t,a),this.sessionBindings.set(t,a),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),i(),n("responded",{msg:`Session bound to ${a}`})}catch(a){i(),n("failed",{code:g.invalidCwd,msg:a instanceof Error?a.message:String(a)})}}async handleCodeWhaleSessionControlLocalActionOpen(e){const o=e.params??{},t=String(o.session_id??"").trim(),s=String(o.cwd??"").trim(),i=String(o.agent_session_id??"").trim(),n=(a,r,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:a,...r!==void 0?{result:r}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}})};if(!t||!s){n("failed",void 0,g.cwdRequired,"session cwd is required");return}try{const a=await this.resolveCwdForBinding(s);this.ensureImportedAgentSession(i,a);const r=this.bindingStore.get(t);if(r?.cwd){const d=await this.resolveCwdForBinding(r.cwd);if(d!==a){n("failed",void 0,g.rebindForbidden,`Session already bound to ${r.cwd}`);return}this.setResolvedAgentSessionId(t,i),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,d)});return}this.bindingStore.set(t,a),this.setResolvedAgentSessionId(t,i),this.sessionBindings.set(t,a),await this.bindSessionForPool(t,a),await this.deferredMgr.release(t,this.deferredCallbacks(),{announceComposing:!1}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:a}),n("ok",{outcome:"opened",binding:this.buildOpenedBindingResult(t,a)})}catch(a){n("failed",void 0,a?.sessionControlErrorCode??g.invalidCwd,a instanceof Error?a.message:String(a))}}normalizeClaudeModeId(e){return String(e??"").trim().toLowerCase()===C.approval?C.approval:C.fullAuto}handleExecCommandOptions(e,o,t){const s=Array.isArray(t?.options)?t.options:[];if(s.length===0)return;const n=this.bindingStore.get(e)?.cwd??"",a={};if(o==="model"){a.available_models=s.map(d=>({id:d.id,displayName:d.label}));const r=s.find(d=>d.current);r&&(a.model_id=r.id)}else if(o==="mode"){a.available_modes=s.map(d=>({id:d.id,displayName:d.label}));const r=s.find(d=>d.current);r&&(a.mode_id=r.id)}else a[`${o}_options`]=s;this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:n,meta:a})}resolveSessionModelId(e){const o=this.bindingStore.getModelId(e);if(o)return o;const t=String(this.globalConfigStore?.get(this.name)?.modelId??"").trim();if(t)return this.bindingStore.setModelId(e,t),t}resolveCodexSessionModelId(e){const o=this.bindingStore.getCodexModelId(e);if(o)return o;const t=String(this.globalConfigStore?.get(this.name)?.codexModelId??"").trim();if(t)return this.bindingStore.setCodexModelId(e,t),t}buildAgyToolbarMeta(e){if(!this.bindingStore.get(e))return;const t=ne(this.config.agent.command),s=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||s;t.length>0&&!t.some(a=>a.id===i)&&(i=s);const n=se();return{model_id:i,currentModelId:i,available_models:t.map(a=>({id:a.id,displayName:a.displayName})),...n.plan!==void 0&&{plan:n.plan},...n.quota_exhausted!==void 0&&{quota_exhausted:n.quota_exhausted},...n.quota_reset_at!==void 0&&{quota_reset_at:n.quota_reset_at},...n.available_credits!==void 0&&{available_credits:n.available_credits}}}async handleAgySetModel(e,o){const t=e.params??{},s=String(t.model_id??t.modelId??"").trim();if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for set_model"});return}if(!s){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"set_model_invalid",error_msg:"model_id is required"});return}const i=this.bindingStore.get(o);if(!i?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"session binding was not found"});return}i.modelId!==s&&(this.bindingStore.setModelId(o,s),this.globalConfigStore?.set(this.name,{modelId:s})),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:i.cwd,meta:this.buildAgyToolbarMeta(o)}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"model_set",model_id:s,binding:{cwd:i.cwd,model_id:s}}})}buildClaudeToolbarMeta(e){const o=this.bindingStore.get(e);if(!o)return;const t=Q(),s=t.length>0?t[0].id:"";let i=this.resolveSessionModelId(e)||s;t.length>0&&!t.some(l=>l.id===i)&&(i=s);const n=this.normalizeClaudeModeId(o.modeId),a={model_id:i,mode_id:n,currentModelId:i,currentModeId:n,available_models:t.map(l=>({id:l.id,displayName:l.displayName}))},r=this.pool.getSlot(e),d=r?.adapter instanceof T?r.adapter.getSessionState():null;(d?.rateLimits?.fiveHour||d?.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=d);const c=d??this.getFreshClaudeRateLimitState();if(c){const l=c.rateLimits;l&&(l.fiveHour||l.sevenDay)&&(a.rate_limits={...l.fiveHour?{fiveHour:l.fiveHour}:{},...l.sevenDay?{sevenDay:l.sevenDay}:{},sampledAt:c.sampledAt||Date.now()})}if(d){const l=d.contextWindow;l.usedPercentage!=null&&(a.context_window={usedPercentage:l.usedPercentage,remainingPercentage:l.remainingPercentage})}if(!a.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const l=this.providerQuotaToRateLimits(this.cachedProviderQuota);l&&(a.rate_limits=l),u.info(this.name,`[toolbar-meta] provider quota fallback: hasCached=${!!this.cachedProviderQuota} fromProvider=${JSON.stringify(l)}`)}return a.rate_limits&&u.info(this.name,`[toolbar-meta] rate_limits included: ${JSON.stringify(a.rate_limits)}`),a}providerQuotaToCodexRateLimits(e){const o=e.tiers.find(i=>i.name==="five_hour"),t=e.tiers.find(i=>i.name==="weekly_limit"),s=i=>i||null;if(o||t){const i={credits:{hasCredits:!0,unlimited:!1,balance:null},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()};let n=0,a=0,r=0,d=0;return o&&(i.primary={usedPercent:o.usedPercent,windowMinutes:300,resetsAt:s(o.resetsAt)},n=o.usedPercent,a=300),t&&(i.secondary={usedPercent:t.usedPercent,windowMinutes:10080,resetsAt:s(t.resetsAt)},r=t.usedPercent,d=10080),{rateLimits:i,primaryPercent:n,secondaryPercent:r,primaryWindowMin:a,secondaryWindowMin:d}}if(e.balance){const i=e.balance,n=i.total&&i.total>0?Math.min(100,(i.used??i.total-i.remaining)/i.total*100):0;return{rateLimits:{primary:{usedPercent:n,windowMinutes:0,resetsAt:null},secondary:{usedPercent:0,windowMinutes:0,resetsAt:null},credits:{hasCredits:!0,unlimited:!1,balance:i.remaining},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()},primaryPercent:n,secondaryPercent:0,primaryWindowMin:0,secondaryWindowMin:0}}return null}providerQuotaToRateLimits(e){const o=i=>{if(!i)return 0;const n=Date.parse(i);return Number.isFinite(n)?Math.floor(n/1e3):0},t=e.tiers.find(i=>i.name==="five_hour"),s=e.tiers.find(i=>i.name==="weekly_limit");if(t||s)return{...t?{fiveHour:{usedPercentage:t.usedPercent,resetsAt:o(t.resetsAt)}}:{},...s?{sevenDay:{usedPercentage:s.usedPercent,resetsAt:o(s.resetsAt)}}:{},sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()};if(e.balance){const i=e.balance;return{credit:{remaining:i.remaining,total:i.total,used:i.used,unit:i.unit,resetsAt:i.resetsAt?o(i.resetsAt):0},planName:e.planName,sampledAt:this.cachedProviderQuotaSampledAtMs??Date.now()}}return null}async resolveCwdForBinding(e){const o=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(o)||/^\\\\/.test(o))){const i=new Error(`Specified path is not valid on this host: ${o}`);throw i.cwdErrorCode=g.invalidCwd,i}const t=P.resolve(o);let s;try{s=await L(t)}catch(i){const n=String(i?.code??"");if(n==="ENOENT"){const a=new Error(`Specified path does not exist: ${t}`);throw a.cwdErrorCode=g.invalidCwd,a}if(n==="EACCES"||n==="EPERM"){const a=new Error("Specified path is not accessible.");throw a.cwdErrorCode=g.invalidCwd,a}throw i}if(!s.isDirectory()){const i=new Error("Specified path is not a directory.");throw i.cwdErrorCode=g.invalidCwd,i}try{return await J(t)}catch{return t}}getClaudeWorkerStatus(e){const o=this.pool.getSlot(e);return o?o.state==="starting"?"starting":o.state==="stopped"?"stopped":o.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,o){const t=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,t),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:t,cwd:o,meta:this.buildClaudeToolbarMeta(e)}),t}async handleSkillUploadLocalAction(e){const o=e.params??{},t=String(o.name??"").trim(),s=String(o.session_id??"").trim();if(!t){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_SKILL_NAME",error_msg:"name is required"});return}const i=q(this.config.adapterType,this.config.aibot.clientType),n=this.bindingStore.get(s)?.cwd||this.sessionBindings.get(s)||void 0,a=i==="kiro"?n:n||process.cwd();try{await ae(t,{mode:i,projectDir:a},{apiKey:this.config.aibot.apiKey,wsUrl:this.config.aibot.url}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{name:t}})}catch(r){u.warn(this.name,`skill_upload failed name=${t}: ${r instanceof Error?r.message:String(r)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"SKILL_UPLOAD_FAILED",error_msg:r instanceof Error?r.message:String(r)})}}reportSessionSkills(e){const o=q(this.config.adapterType,this.config.aibot.clientType),t=this.bindingStore.get(e)?.cwd||this.sessionBindings.get(e)||void 0,s=o==="kiro"?t:t||process.cwd();let i;try{i=re({mode:o,projectDir:s})}catch{return}if(i.length===0)return;const n=JSON.stringify(i.map(a=>`${a.source}:${a.name}`));if(n!==this.lastReportedSkillsHash){this.lastReportedSkillsHash=n;try{this.aibotHandle.sendSkillsUpdate({skills:W(i,N.skills)})}catch{}}}async ensureSlotStarted(e,o=6e4){const t=this.pool.getOrCreateSlot(e);if(!t)throw new Error("Failed to allocate session slot");t.startPromise&&(u.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([t.startPromise,new Promise((s,i)=>setTimeout(()=>i(new Error(`ensureSlotStarted timeout (${o}ms) session=${e}`)),o))]),u.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveOrphanTitle(e){if(!e||!this.reasonixTitleScan)return;const o=we(e);if(!o)return;const t=this.reasonixTitleScan.get().filter(s=>s.stamp===o);return t.length===1?t[0].title:void 0}resolveAgentSessionId(e){switch(this.config.adapterType??"acp"){case"claude":return e.claudeSessionId;case"codex":return e.codexThreadId;case"pi":return e.piSessionPath;case"codewhale":return e.codewhaleThreadId;case"agy":return e.agyConversationId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":return e;default:return"acp"}}setResolvedAgentSessionId(e,o){const t=String(e??"").trim(),s=String(o??"").trim();if(!t||!s)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(t,s);break;case"codex":this.bindingStore.setCodexThreadId(t,s);break;case"pi":this.bindingStore.setPiSessionPath(t,s);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(t,s);break;case"agy":this.bindingStore.setAgyConversationId(t,s);break;default:this.bindingStore.setAcpSessionId(t,s);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const o=String(e??"").trim();if(!o)return"";const t=P.resolve(o);return process.platform==="win32"?t.toLowerCase():t}ensureImportedAgentSession(e,o){const t=String(e??"").trim();if(!t)return;const s=this.normalizePathForCompare(o);let i="";const n=this.config.adapterType??"acp";if(n==="codex"?i=this.sessionScanCache.get().find(d=>d.threadId===t)?.cwd??"":n==="claude"?i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??"":n==="acp"&&(i=this.sessionScanCache.get().find(d=>d.sessionId===t)?.cwd??""),!i){for(const[,r]of this.bindingStore.entries())if(this.resolveAgentSessionId(r)===t){i=r.cwd??"";break}}if(!i){const r=new Error(`agent session not found: ${t}`);throw r.sessionControlErrorCode=g.invalidAgentSession,r}const a=this.normalizePathForCompare(i);if(a&&s&&a!==s){const r=new Error(`agent session cwd mismatch: expected ${o}, got ${i}`);throw r.sessionControlErrorCode=g.invalidAgentSession,r}}buildOpenedBindingResult(e,o,t="ready"){const s=this.bindingStore.get(e),i=s?String(this.resolveAgentSessionId(s)??"").trim():"",n={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:o,workerStatus:t};return i&&(n.bindingId=i,n.agentSessionId=i),n}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"}async handleListSessionsTextCommand(e){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const o=this.config.adapterType??"acp",t=new Map;for(const r of this.pool.getAllSlots())t.set(r.sessionId,r);const s=Array.from(this.bindingStore.entries()),i=new Map;for(const[r,d]of s){const c=this.resolveAgentSessionId(d);if(c){const l=t.get(r),h=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(c,{aibotSessionId:r,workerStatus:h})}}const n=[],a=new Set;if(o==="codex"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.threadId);const c=i.get(d.threadId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.threadId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??(d.archived?"archived":"inactive")}`),n.push(` Created: ${new Date(d.createdAt).toISOString()}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="claude"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="acp"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="pi"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionPath);const c=i.get(d.sessionPath);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionPath}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}else if(o==="codewhale"||o==="cursor"||o==="opencode"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId);d.title&&n.push(` Title: ${d.title}`),n.push(` Agent: ${d.sessionId}`),c&&n.push(` AIBot: ${c.aibotSessionId}`),n.push(` CWD: ${d.cwd||"-"}`),n.push(` State: ${c?.workerStatus??"inactive"}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}}for(const[r,d]of s){const c=this.resolveAgentSessionId(d);if(c&&a.has(c))continue;const l=t.get(r),h=l?l.adapter.getStatus().busy?"busy":"ready":"closed",m=this.resolveOrphanTitle(c)??(c?c.slice(0,8)+"\u2026":r.slice(0,8)+"\u2026");n.push(` Title: ${m}`),n.push(` AIBot: ${r}`),c&&n.push(` Agent: ${c}`),n.push(` CWD: ${d.cwd??"-"}`),n.push(` State: ${h}`),n.push(` Updated: ${new Date(d.updatedAt).toISOString()}`),n.push("---")}if(n.length===0){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:"No sessions found.",updated_at:Date.now()});return}this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Sessions (${n.filter(r=>r==="---").length}):
14
14
  ${n.join(`
15
15
  `)}`,updated_at:Date.now()})}async handleListSessionsLocalAction(e){const o=this.config.adapterType??"acp",t=new Map;for(const r of this.pool.getAllSlots())t.set(r.sessionId,r);const s=Array.from(this.bindingStore.entries()),i=new Map;for(const[r,d]of s){const c=this.resolveAgentSessionId(d);if(c){const l=t.get(r),h=l?l.adapter.getStatus().busy?"busy":"ready":"inactive";i.set(c,{aibotSessionId:r,workerStatus:h,bindingUpdatedAt:d.updatedAt??0})}}const n=[],a=new Set;if(o==="codex"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.threadId);const c=i.get(d.threadId),l={agentSessionId:d.threadId,cwd:d.cwd||null,workerStatus:c?.workerStatus??(d.archived?"archived":"inactive"),createdAt:d.createdAt,updatedAt:d.updatedAt,archived:d.archived};c&&(l.aibotSessionId=c.aibotSessionId),d.title&&(l.title=d.title),n.push(l)}}else if(o==="claude"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId),l={agentSessionId:d.sessionId,cwd:d.cwd||null,workerStatus:c?.workerStatus??"inactive",updatedAt:d.updatedAt};c&&(l.aibotSessionId=c.aibotSessionId),d.title&&(l.title=d.title),n.push(l)}}else if(o==="acp"){const r=this.sessionScanCache.get();for(const d of r){a.add(d.sessionId);const c=i.get(d.sessionId),l=c&&c.bindingUpdatedAt>0?c.bindingUpdatedAt:d.updatedAt,h={agentSessionId:d.sessionId,cwd:d.cwd||null,agentType:d.agentType,workerStatus:c?.workerStatus??"inactive",updatedAt:l};c&&(h.aibotSessionId=c.aibotSessionId),d.title&&(h.title=d.title),d.createdAt&&(h.createdAt=d.createdAt),n.push(h)}}else if(o==="pi"||o==="codewhale"||o==="cursor"||o==="opencode"){const r=this.sessionScanCache.get();for(const d of r){const c="sessionPath"in d?d.sessionPath:d.sessionId;a.add(c);const l=i.get(c),h={agentSessionId:c,cwd:d.cwd||null,workerStatus:l?.workerStatus??("archived"in d&&d.archived?"archived":"inactive"),updatedAt:l&&l.bindingUpdatedAt>0?l.bindingUpdatedAt:d.updatedAt};l&&(h.aibotSessionId=l.aibotSessionId),d.title&&(h.title=d.title),d.createdAt&&(h.createdAt=d.createdAt),"archived"in d&&(h.archived=d.archived),n.push(h)}}for(const[r,d]of s){const c=this.resolveAgentSessionId(d);if(c&&a.has(c))continue;const l=t.get(r),h=l?l.adapter.getStatus().busy?"busy":"ready":"closed",m={aibotSessionId:r,cwd:d.cwd??null,workerStatus:h,updatedAt:d.updatedAt,title:this.resolveOrphanTitle(c)??(c?`${c.slice(0,8)}\u2026`:`${r.slice(0,8)}\u2026`)};c&&(m.agentSessionId=c),n.push(m)}n.sort((r,d)=>d.updatedAt-r.updatedAt),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"sessions_listed",sessions:n,total:n.length}})}async handleSessionControlCommand(e,o){const t=o.session_id,s=(i,n,a)=>{this.aibotHandle.sendEventResult({event_id:o.event_id,status:i,...n?{msg:n}:{},...a?{code:a}:{},updated_at:Date.now()})};this.aibotHandle.sendEventAck({event_id:o.event_id,session_id:t,received_at:Date.now()});try{switch(e.verb){case p.open:{await D().catch(()=>{});const i=e.args.trim();if(!i){s("failed","Usage: /grix open <working-directory>",g.cwdRequired);return}let n="";try{n=await this.resolveCwdForBinding(i)}catch(r){s("failed",r instanceof Error?r.message:String(r),g.invalidCwd);return}const a=this.bindingStore.get(t);if(a?.cwd){const r=await this.resolveCwdForBinding(a.cwd);if(r!==n){s("failed","session binding cannot be changed to another working directory",g.rebindForbidden);return}this.bindingStore.ensureModeId(t,C.fullAuto),this.sessionBindings.set(t,r),await this.ensureSlotStarted(t),await this.deferredMgr.release(t,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(t,r),s("responded",`Working directory already bound: ${r}`);return}this.bindingStore.set(t,n,{modeId:C.fullAuto}),this.sessionBindings.set(t,n),await this.ensureSlotStarted(t),await this.deferredMgr.release(t,this.deferredCallbacks()),this.refreshClaudeWorkerStatusCard(t,n),s("responded",`Session bound to ${n}`);return}case p.where:{const i=this.bindingStore.get(t);if(!i?.cwd){s("failed","session binding was not found",g.bindingMissing);return}s("responded",`Working directory: ${i.cwd}`);return}case p.status:{const i=this.bindingStore.get(t);if(!i?.cwd){s("failed","session binding was not found",g.bindingMissing);return}const n=this.normalizeClaudeModeId(i.modeId),a=this.getClaudeWorkerStatus(t);s("responded",`Status: worker=${a} mode=${n} cwd=${i.cwd}`);return}case p.stop:{const i=this.bindingStore.get(t);if(!i?.cwd){s("failed","session binding was not found",g.bindingMissing);return}await this.pool.removeSlot(t),this.claudeWorkerStatus.set(t,"stopped"),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"stopped",cwd:i.cwd}),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"stopped",cwd:i.cwd,meta:this.buildClaudeToolbarMeta(t)}),s("responded",`Session worker stopped for ${i.cwd}`);return}case p.restart:{const i=this.bindingStore.get(t);if(!i?.cwd){s("failed","session binding was not found",g.bindingMissing);return}await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,i.cwd),s("responded",`Session worker restarted for ${i.cwd}`);return}case p.setMode:{const i=e.args.trim();if(!i){s("failed","Usage: /grix set_mode <mode-id>",x.modeInvalid);return}const n=this.normalizeClaudeModeId(i);if(n!==i.toLowerCase()){s("failed","set mode_id is invalid",x.modeInvalid);return}const a=this.bindingStore.get(t);if(!a?.cwd){s("failed","session binding was not found",g.bindingMissing);return}if(this.normalizeClaudeModeId(a.modeId)===n){s("responded",`Mode unchanged: ${n}`);return}if(this.getClaudeWorkerStatus(t)==="busy"){s("failed","\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148 /grix stop \u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u5F0F",g.workerBusy);return}this.bindingStore.setModeId(t,n),await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,a.cwd),s("responded",`Mode set to ${n}`);return}case p.setModel:{const i=e.args.trim();if(!i){s("failed","Usage: /grix set_model <model-id>");return}const n=this.bindingStore.get(t);if(!n?.cwd){s("failed","session binding was not found",g.bindingMissing);return}if((n.modelId??"")===i){s("responded",`Model unchanged: ${i}`);return}if(this.getClaudeWorkerStatus(t)==="busy"){s("failed","\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148 /grix stop \u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u578B",g.workerBusy);return}this.bindingStore.setModelId(t,i),this.globalConfigStore?.set(this.name,{modelId:i}),await this.pool.removeSlot(t),await this.ensureSlotStarted(t),this.refreshClaudeWorkerStatusCard(t,n.cwd),s("responded",`Model set to ${i}`);return}case p.listOptions:{const i=Q(),n=this.bindingStore.get(t),a=i.map(d=>d.id).join(", "),r=`${C.fullAuto}, ${C.approval}`;s("responded",`Modes (current: ${this.normalizeClaudeModeId(n?.modeId)}): ${r}
16
- Models (current: ${n?.modelId??"default"}): ${a}`);return}case p.exec:{const[i,...n]=e.args.trim().split(/\s+/);if(!i){s("failed","Usage: /grix exec <command> [args]",g.verbInvalid);return}const r=this.pool.getSlot(t)?.adapter;if(!r?.execCommand){s("failed","Agent does not support command execution",g.verbInvalid);return}const d=r.getSupportedCommands?.()??[];if(!d.some(c=>c.name===i)){s("failed",`Unknown command: ${i}. Supported: ${d.map(c=>c.name).join(", ")}`,g.verbInvalid);return}try{const c=await r.execCommand(i,n.join(" "),t);s(c.status==="ok"?"responded":"failed",c.message??`${i} ${c.status}`,c.status==="ok"?void 0:g.runtimeError)}catch(c){s("failed",`exec error: ${c instanceof Error?c.message:c}`,g.runtimeError)}return}default:s("failed",`Unsupported command for Claude: /grix ${e.verb}`,g.verbInvalid)}}catch(i){s("failed",i instanceof Error?i.message:String(i),g.runtimeError)}}async handleSessionControlLocalAction(e){const o=String(e.action_type??"").trim();if(o!==b.sessionControl&&o!==b.setMode&&o!=="set_mode"&&o!==b.setModel&&o!=="set_model")return!1;const t=e.params??{},s=String(t.session_id??"").trim(),i=o===b.setMode?p.setMode:o===b.setModel?p.setModel:String(t.verb??"").trim().toLowerCase();if(u.info(this.name,`handleSessionControlLocalAction verb=${i} action_id=${e.action_id} session_id=${s}`),!s)return this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:x.localActionRouteMissing,error_msg:"local action session_id is required"}),!0;const n=r=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:r})},a=(r,d)=>{u.warn(this.name,`session_control local_action failed action_id=${e.action_id} session_id=${s} verb=${i} code=${r} msg=${d}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:r,error_msg:d})};try{switch(i){case p.open:{await D().catch(()=>{});const r=String(t.cwd??"").trim(),d=String(t.agent_session_id??"").trim();if(!r)return a(g.cwdRequired,"session control cwd is required"),!0;u.info(this.name,`handleSessionControlLocalAction open cwd=${r} session_id=${s}`);const c=await this.resolveCwdForBinding(r);this.ensureImportedAgentSession(d,c);const l=this.bindingStore.get(s);if(l?.cwd){const h=await this.resolveCwdForBinding(l.cwd);return h!==c?(a(g.rebindForbidden,"session binding cannot be changed to another working directory"),!0):(this.bindingStore.ensureModeId(s,C.fullAuto),this.setResolvedAgentSessionId(s,d),this.sessionBindings.set(s,h),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,h),n({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,h),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0)}return this.bindingStore.set(s,c,{modeId:C.fullAuto}),this.setResolvedAgentSessionId(s,d),this.sessionBindings.set(s,c),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,c),n({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,c),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0}case p.status:case p.where:{const r=this.bindingStore.get(s);return r?.cwd?(n({outcome:i,binding:{cwd:r.cwd,mode_id:this.normalizeClaudeModeId(r.modeId),worker_status:this.getClaudeWorkerStatus(s)}}),!0):(a(g.bindingMissing,"session binding was not found"),!0)}case p.stop:{const r=this.bindingStore.get(s);return r?.cwd?(await this.pool.removeSlot(s),n({outcome:"stopped",binding:{cwd:r.cwd,mode_id:this.normalizeClaudeModeId(r.modeId),worker_status:"stopped"}}),!0):(a(g.bindingMissing,"session binding was not found"),!0)}case p.restart:{const r=this.bindingStore.get(s);return r?.cwd?(await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,r.cwd),n({outcome:"restarted",binding:{cwd:r.cwd,mode_id:this.normalizeClaudeModeId(r.modeId)}}),!0):(a(g.bindingMissing,"session binding was not found"),!0)}case p.setMode:{const r=String(t.mode_id??t.modeId??"").trim();if(!r)return a(x.modeInvalid,"set mode_id is invalid"),!0;const d=this.normalizeClaudeModeId(r);if(d!==r.toLowerCase())return a(x.modeInvalid,"set mode_id is invalid"),!0;const c=this.bindingStore.get(s);if(!c?.cwd)return a(g.bindingMissing,"session binding was not found"),!0;if(this.normalizeClaudeModeId(c.modeId)!==d){if(this.getClaudeWorkerStatus(s)==="busy")return a(g.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u5F0F"),!0;this.bindingStore.setModeId(s,d),await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,c.cwd)}return n({outcome:"mode_set",mode_id:d,binding:{cwd:c.cwd,mode_id:d}}),!0}case p.setModel:{const r=String(t.model_id??t.modelId??"").trim();if(!r)return a("set_model_invalid","model_id is required"),!0;const d=this.bindingStore.get(s);if(!d?.cwd)return a(g.bindingMissing,"session binding was not found"),!0;if((d.modelId??"")!==r){if(this.getClaudeWorkerStatus(s)==="busy")return a(g.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u578B"),!0;this.bindingStore.setModelId(s,r),this.globalConfigStore?.set(this.name,{modelId:r}),await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,d.cwd)}return n({outcome:"model_set",model_id:r,binding:{cwd:d.cwd,model_id:r}}),!0}case p.listOptions:{const r=Q(),d=this.pool.getSlot(s);return n({modes:[C.fullAuto,C.approval],currentModeId:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId),models:r.map(c=>({modelId:c.id,name:c.displayName})),currentModelId:this.bindingStore.get(s)?.modelId??"",available_models:r.map(c=>({id:c.id,displayName:c.displayName})),agent_commands:d?.adapter?.getSupportedCommands?.()??[]}),!0}case p.exec:{const[r,...d]=String(t.args??"").trim().split(/\s+/);if(!r)return a(g.verbInvalid,"Usage: exec <command> [args]"),!0;await this.ensureSlotStarted(s);const l=this.pool.getSlot(s)?.adapter;if(!l?.execCommand)return a(g.verbInvalid,"Agent does not support command execution"),!0;const h=l.getSupportedCommands?.()??[];if(!h.some(m=>m.name===r))return a(g.verbInvalid,`Unknown command: ${r}. Supported: ${h.map(m=>m.name).join(", ")}`),!0;try{const m=await l.execCommand(r,d.join(" "),s);m.status==="ok"?n({outcome:"exec",command:r,message:m.message,data:m.data}):a(g.runtimeError,m.message??`${r} failed`)}catch(m){a(g.runtimeError,`exec error: ${m instanceof Error?m.message:m}`)}return!0}default:return a(g.verbInvalid,`session control verb ${i} is not supported`),!0}}catch(r){const d=r instanceof Error&&r.cwdErrorCode?r.cwdErrorCode:r instanceof Error&&r.sessionControlErrorCode?r.sessionControlErrorCode:g.runtimeError;return u.error(this.name,`handleSessionControlLocalAction error verb=${i} session_id=${s}: ${r instanceof Error?r.message:r}`),a(d,r instanceof Error?r.message:String(r)),!0}}async handleEventCancel(e){const{event_id:o,session_id:t}=e;if(u.info(this.name,`handleEventCancel start event_id=${o} session_id=${t}`),this.pool.cancelEvent(o,t)){if(!(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(o)??!1)){this.sendEventResultWithCleanup(o,"canceled","canceled"),this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!0,final_state:"canceled"});return}await this.waitForEventDone(o,t,15e3),this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!0,final_state:"canceled"}),this.pushQueueSnapshotForSession(t);return}this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!1,reason:"event not found or not cancelable"})}waitForEventDone(e,o,t){return new Promise(s=>{const i=this.pool.getSlot(o);if(!i?.adapter){s();return}const n=setTimeout(()=>{i.adapter.removeListener("eventDone",a),s()},t),a=r=>{r===e&&(clearTimeout(n),i.adapter.removeListener("eventDone",a),s())};i.adapter.on("eventDone",a)})}handleAibotStop(e){if(u.info(this.name,`[stop-trace] handleAibotStop begin session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"} adapterType=${this.config.adapterType??"acp"}`),this.aibotHandle.sendEventStopAck({stop_id:e.stop_id,event_id:e.event_id,accepted:!0,updated_at:Date.now()}),this.pool.removeQueuedEvent(e.session_id,e.event_id)){u.info(this.name,`[stop-trace] handleAibotStop removed queued(not-running) event -> stopResult(stopped) session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"}`),this.discardEventTrackingState(e.event_id),this.pushQueueSnapshotForSession(e.session_id),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()});return}const o=this.pool.getSlot(e.session_id),t=o?.adapter?.getStatus().busy??!1,s=(this.config.adapterType??"acp")==="acp",i=o?.adapter?.getActiveEventIds,n=typeof i=="function"?i.call(o.adapter):[],a=n.length>0?n.includes(e.event_id):t,r=(s||(this.config.adapterType??"acp")==="codex"||(this.config.adapterType??"acp")==="claude")&&a;if(u.info(this.name,`[stop-trace] handleAibotStop decision session=${e.session_id} event=${e.event_id} slotExists=${!!o?.adapter} busy=${t} activeIds=[${n.join(",")}] stoppingActiveEvent=${a} killOnStop=${r}`),a&&this.sendCtrl.markEventStopped(e.event_id),o?.adapter&&t){const d=r?this.pool.drainQueuedForSession(e.session_id):[];let c=!1,l=null;const h=v=>{c||(c=!0,l&&(clearTimeout(l),l=null),o.adapter.removeListener("eventDone",m),u.info(this.name,`[stop-trace] handleAibotStop ${v} -> stopResult(stopped) session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"} killOnStop=${r}`),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()}),r&&this.killAndResumeStopSlot(e.session_id,d))},m=v=>{v===e.event_id&&h("eventDone")};o.adapter.on("eventDone",m),l=setTimeout(()=>h("timeout"),ut),this.pool.deliverStopEvent(e.event_id,e.session_id)}else u.info(this.name,`[stop-trace] handleAibotStop slot-not-busy -> immediate stopResult(stopped) session=${e.session_id} event=${e.event_id} slotExists=${!!o?.adapter}`),this.pool.deliverStopEvent(e.event_id,e.session_id),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()});(this.config.adapterType??"acp")==="pi"&&this.aibotHandle.sendText({event_id:e.event_id,session_id:e.session_id,content:"/stop",msg_type:0})}async killAndResumeStopSlot(e,o){if(!this.stopped){u.info(this.name,`[stop-trace] killAndResumeStopSlot begin session=${e} siblings=${o.length} -> removeSlot (kill process group)`);try{await this.pool.removeSlot(e),u.info(this.name,`[stop-trace] killAndResumeStopSlot removeSlot done session=${e} (process killed) -> redeliver ${o.length} sibling(s)`)}catch(t){u.warn(this.name,`[acp-stop] removeSlot failed session=${e}: ${t instanceof Error?t.message:String(t)}`)}if(!this.stopped)for(const t of o){if(this.stopped)break;try{await this.pool.deliverInboundEvent(t)}catch(s){u.error(this.name,`[acp-stop] sibling redeliver failed event=${t.event_id} session=${e}: ${s instanceof Error?s.message:String(s)}`),this.sendEventResultWithCleanup(t.event_id,"failed",s instanceof Error?s.message:String(s))}}}}handleAibotRevoke(e){if(!e.event_id||!this.revokeHandler.checkAndTrack(e.event_id))return;const o=e.event_id,t=e.session_id;if(t&&this.pool.cancelEvent(o,t)){(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(o)??!1)||this.sendEventResultWithCleanup(o,"canceled","revoked");return}if(this.deferredMgr.removeEvent(o)){this.aibotHandle.sendEventResult({event_id:o,status:"canceled",msg:"revoked",updated_at:Date.now()});return}this.pool.deliverStopEvent(o,t||void 0)}async handleConfigureGatewayProvider(e){const o=e.params??{},t=String(o.api_key??"").trim(),s=String(o.anthropic_base_url??"").trim(),i=String(o.openai_base_url??"").trim(),n=typeof o.model=="string"&&o.model.trim()||void 0;let a=!1;if(!t){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_API_KEY",error_msg:"api_key is required"});return}const r=this.config.adapterType??"acp",d=r==="claude"||r==="codex";try{if(d){const c=r==="claude"?s:i;if(!c){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_BASE_URL",error_msg:`${r==="claude"?"anthropic_base_url":"openai_base_url"} is required`});return}const l=de();if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"PROXY_UNAVAILABLE",error_msg:"MITM proxy manager not initialized"});return}const h=ce(r),m=le(r,c,t,{model:n});l.setRoute(m);for(const v of h)l.setHostDefaultRoute(v,m.routeKey);await l.setAgentRelayEnabled(this.name,!0,{relayHosts:h}),a=!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 "${r}" does not support Grix relay provider config`});return}await this.providerConfigHandler({base_url:i||void 0,api_key:t,model:n})}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0,restart_deferred:a}})}catch(c){u.error(this.name,`handleConfigureGatewayProvider failed: ${c}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"CONFIGURE_FAILED",error_msg:c instanceof Error?c.message:String(c)})}}async handleAibotLocalAction(e){const o=e.action_type??"",t=String((e.params??{}).session_id??""),s=String((e.params??{}).verb??"").trim().toLowerCase();u.debug(this.name,`local_action received action_type=${o} verb=${s||"-"} action_id=${e.action_id} session_id=${t}`);const i=(this.config.adapterType??"acp")==="claude";if(o===b.sessionControl&&s===p.exec&&await this.handleSessionControlLocalAction(e))return;if(o===b.sessionControl&&s===p.listSessions){await this.handleListSessionsLocalAction(e);return}if(i&&(o===b.interactionReply||o==="exec_approve"||o==="exec_reject")&&(await this.pool.deliverLocalAction(e)).handled||i&&await this.handleSessionControlLocalAction(e))return;if(o===b.sessionControl){const c=this.config.adapterType??"acp",l=c==="codex",h=c==="pi",m=String((e.params??{}).verb??"").trim().toLowerCase();if(l&&m===p.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(c==="cursor"&&m===p.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(l&&m==="restart"){const S=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:t,cwd:S,workerStatus:"ready"}}});return}if(h&&m===p.open){try{const f=e.params??{},S=String(f.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(S),R=String(f.agent_session_id??"").trim();this.ensureImportedAgentSession(R,w),this.bindingStore.set(t,w),this.setResolvedAgentSessionId(t,R),this.sessionBindings.set(t,w),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:w}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,w)}})}catch(f){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f?.sessionControlErrorCode??f?.cwdErrorCode??g.invalidCwd,error_msg:f instanceof Error?f.message:String(f)})}return}if(h&&m===p.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((c==="openhuman"||c==="opencode")&&m===p.open){try{const f=e.params??{},S=String(f.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(S),R=String(f.agent_session_id??"").trim();this.ensureImportedAgentSession(R,w),this.bindingStore.set(t,w),this.setResolvedAgentSessionId(t,R),this.sessionBindings.set(t,w),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,w)}})}catch(f){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f?.sessionControlErrorCode??f?.cwdErrorCode??g.invalidCwd,error_msg:f instanceof Error?f.message:String(f)})}return}if(c==="codewhale"&&m===p.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(c==="acp"&&m===p.stop){const S=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:t,cwd:S,workerStatus:"stopped"}}});return}try{if(m===p.open){const f=e.params??{},S=String(f.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=String(f.agent_session_id??"").trim();if(w){const R=await this.resolveCwdForBinding(S);this.ensureImportedAgentSession(w,R)}}await this.handleSessionControlLocalActionForPool(e)}catch(f){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f?.sessionControlErrorCode??f?.cwdErrorCode??g.runtimeError,error_msg:f instanceof Error?f.message:String(f)});return}if(m===p.open){const f=e.params??{},S=await this.resolveCwdForBinding(String(f.cwd??"").trim());this.setResolvedAgentSessionId(t,String(f.agent_session_id??"").trim()),c==="agy"&&(this.bindingStore.set(t,S),this.sessionBindings.set(t,S)),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,S)}}),(this.config.adapterType??"acp")==="agy"&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:S,meta:this.buildAgyToolbarMeta(t)})}else qe(e,this.sessionControlCtx(t),this.sessionControlSenders());return}if(o==="file_list"){const c=Date.now(),l=t?this.bindingStore.get(t)?.cwd:void 0,h=e.params??{},m=String(h.parent_id??"").trim(),v=Array.isArray(h.allowed_extensions)?h.allowed_extensions.filter(S=>typeof S=="string").map(S=>S.trim()).filter(S=>S.length>0):[];u.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${t} parent_id=${m||"<root>"} show_hidden=${!!h.show_hidden} ext_count=${v.length} bound_cwd=${l??"<none>"}`);const _=await Ge({parent_id:m||null,session_id:t,show_hidden:!!h.show_hidden,allowed_extensions:v},{resolveCwd:()=>l??this.config.agent.cwd??process.cwd(),fallbackDir:z()}),E=Date.now()-c,f=_.result?.files?.length??0;u.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${_.status} elapsed=${E}ms count=${f} current_path=${_.result?.current_path??""} error_code=${_.error_code??""} error_msg=${_.error_msg??""}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:_.status,..._.result?{result:{..._.result,machine_name:Ve()}}:{},..._.error_code?{error_code:_.error_code}:{},..._.error_msg?{error_msg:_.error_msg}:{}});return}if(o==="create_folder"){const c=t?this.bindingStore.get(t)?.cwd:void 0,l=String((e.params??{}).parent_id??"").trim(),h=String((e.params??{}).name??"").trim(),m=await Ke({parent_id:l||null,name:h,session_id:t},{resolveCwd:()=>c??this.config.agent.cwd??process.cwd(),fallbackDir:z()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:m.status,...m.result?{result:m.result}:{},...m.error_code?{error_code:m.error_code}:{},...m.error_msg?{error_msg:m.error_msg}:{}});return}if(o===b.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,t);return}if(o===b.getSessionUsage){await this.handleGetSessionUsage(e,t);return}if(o===b.getRateLimits){await this.handleGetRateLimits(e,t);return}const n=(this.config.adapterType??"acp")==="acp";if((i||n)&&o===b.threadCompact){await this.handleThreadCompact(e,t);return}if(o==="connector_rollback"){await this.handleConnectorRollback(e);return}if(o==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(o===b.getAgentGlobalConfig){const c=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...c?{config:c}:{config:null}}});return}if(o==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}const a=this.config.adapterType??"acp",r=(a==="codex"||a==="cursor"||a==="pi"||a==="openhuman"||a==="opencode"||a==="acp")&&!!t&&!!this.bindingStore.get(t)?.cwd,d=await this.pool.deliverLocalAction(e,{autoCreateSlot:r});if(d.handled){if(d.kind==="set_mode"){const c=String((e.params??{}).mode_id??"");c&&(a==="cursor"||a==="claude"?this.bindingStore.setModeId(t,c):I.has(a)||this.globalConfigStore?.set(this.name,{acpInitialMode:c}))}else if(d.kind==="set_model"){const c=String((e.params??{}).model_id??"");c&&(a==="cursor"?(this.bindingStore.setModelId(t,c),this.globalConfigStore?.set(this.name,{modelId:c})):a==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:c}):I.has(a)||this.globalConfigStore?.set(this.name,{modelId:c}))}else if(d.kind==="set_reasoning_effort"){const c=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");c&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:c})}else if(d.kind==="set_sandbox_mode"){const c=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(c){const l=c==="default"?void 0:c;this.globalConfigStore?.set(this.name,{codexSandboxMode:l})}}return}if((a==="codex"||a==="cursor"||a==="pi"||a==="openhuman"||a==="opencode")&&t&&!this.bindingStore.get(t)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(a==="acp"&&(o==="set_mode"||o==="set_model")){const c=this.sessionControlSenders(),l=this.pool.getSlot(t)?.adapter,h={bindingStore:this.bindingStore,acpAdapter:l instanceof A?l:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:u};if(o==="set_mode"){const m=String((e.params??{}).mode_id??""),v=await N(h,t,m);if(v.status==="failed")c.sendLocalActionResult(e.action_id,"failed",void 0,v.errorCode,v.errorMsg);else{const _=l instanceof A?l.buildToolbarContext(v.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,E=_?{..._,...v.result}:v.result;c.sendLocalActionResult(e.action_id,"ok",E)}}else{const m=String((e.params??{}).model_id??""),v=await W(h,t,m);if(v.status==="failed")c.sendLocalActionResult(e.action_id,"failed",void 0,v.errorCode,v.errorMsg);else{const _=l instanceof A?l.buildToolbarContext(v.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,E=_?{..._,...v.result}:v.result;c.sendLocalActionResult(e.action_id,"ok",E)}}return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:`action type ${o} is not supported`})}async handleGetSessionUsage(e,o){if(!o){u.warn(this.name,`[usage] get_session_usage rejected: no session_id in params, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for get_session_usage"});return}const t=this.config.adapterType??"acp",s=this.bindingStore.get(o),i=s?.cwd??this.config.agent.cwd??process.cwd();u.info(this.name,`[usage] get_session_usage action_id=${e.action_id} session_id=${o} adapterType=${t} hasBinding=${!!s} cwd=${i}`);let n=null,a,r;switch(t){case"claude":{if(a=s?.claudeSessionId,!a){u.warn(this.name,`[usage] no claude binding for session_id=${o}, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Claude session binding found"});return}u.info(this.name,`[usage] parsing claude usage: claudeSessionId=${a} cwd=${i}`),n=await ie(a,i),r="claude";break}case"agy":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"agy",available:!1,reason:"agy print-mode adapter does not track token usage"}});return}case"acp":default:{if(a=s?.acpSessionId,!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No ACP session binding found"});return}n=await re(a,i,this.config.aibot.clientType),r=t,(!r||r==="acp")&&(r="acp");break}case"codex":{if(a=s?.codexThreadId,!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Codex thread binding found"});return}n=await ge(a),r="codex";break}case"pi":{if(a=s?.piSessionPath,!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Pi session path binding found"});return}n=await Ee(a),r="pi";break}case"cursor":{const c=this.pool.getSlot(o)?.adapter;if(!(c instanceof H)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Cursor session found"});return}const l=c.getUsageSnapshot(o);if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"cursor",models:[{modelId:this.bindingStore.get(o)?.modelId??"auto",turns:l.turns,input:l.total.input,output:l.total.output,cacheRead:l.total.cacheRead,cacheWrite:l.total.cacheWrite}],total:{input:l.total.input,output:l.total.output,cacheRead:l.total.cacheRead,cacheWrite:l.total.cacheWrite},turns:l.turns,sampledAt:l.sampledAt}});return}case"codewhale":{const c=this.pool.getSlot(o)?.adapter;if(!(c instanceof O)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No CodeWhale session found"});return}const l=c.getUsageSnapshot();if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"codewhale",models:[{modelId:this.bindingStore.get(o)?.modelId??"codewhale",turns:l.turns,input:l.total.input,output:l.total.output}],total:{input:l.total.input,output:l.total.output},turns:l.turns,sampledAt:l.sampledAt}});return}}if(!n){u.info(this.name,`[usage] no usage data found: session_id=${o} adapterSessionId=${a} adapterType=${r}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}u.info(this.name,`[usage] result ok: session_id=${o} adapterSessionId=${a} turns=${n.turns} models=${n.models.length}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:a,adapterType:r,models:n.models,total:n.total,turns:n.turns,sampledAt:new Date().toISOString()}})}async handleThreadCompact(e,o){if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for thread_compact"});return}if(!this.bindingStore.get(o)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"session binding was not found"});return}try{await this.ensureSlotStarted(o);const i=this.pool.getSlot(o)?.adapter;if(!i?.execCommand){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:"Agent does not support command execution"});return}u.info(this.name,`thread_compact session_id=${o} action_id=${e.action_id}`);const n=await i.execCommand("compact","",o);n.status==="ok"?this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"compacted",message:n.message,data:n.data}}):this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:n.message??"compact failed"})}catch(s){u.warn(this.name,`thread_compact error session_id=${o}: ${s instanceof Error?s.message:s}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:s instanceof Error?s.message:String(s)})}}async handleGetRateLimits(e,o){const t=this.config.adapterType??"acp";if(this.config.aibot.clientType==="kiro"){const s=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs),i=this.cachedAcpContextWindow;if(s&&this.cachedProviderQuota){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!0,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:i,tokenUsage:null,providerQuota:this.cachedProviderQuota}});return}try{const n=await B();this.cachedProviderQuota=n,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[rate-limits] kiro quota queried: success=${n.success}`+(n.balance?` balance=${n.balance.remaining} ${n.balance.unit}`:"")+(n.error?` error=${n.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!1,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:i,tokenUsage:null,providerQuota:n}})}catch(n){u.warn(this.name,`[rate-limits] kiro quota query failed: ${n instanceof Error?n.message:String(n)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:i,tokenUsage:null}})}return}switch(t){case"codex":{const s=this.maybeQueryProviderQuota(),i=this.getFreshCodexGlobalRateLimitCache();if(i.hasData&&!this.isRateLimitsCacheFresh(this.cachedRateLimitsSampledAtMs)&&!this.isRateLimitsCacheFresh(this.cachedCodexUsageSampledAtMs)){const l=this.pool.getAllSlots().find(h=>h.state==="ready"&&h.adapter);if(l&&(u.info(this.name,`[rate-limits] codex cache stale, refreshing from slot: session=${l.sessionId}`),(await l.adapter.handleLocalAction?.(e))?.handled))return}if(i.hasData){i.rateLimits?u.info(this.name,`[rate-limits] codex cached: primary=${i.rateLimits.primary.usedPercent.toFixed(1)}% resetsAt=${i.rateLimits.primary.resetsAt} secondary=${i.rateLimits.secondary.usedPercent.toFixed(1)}% resetsAt=${i.rateLimits.secondary.resetsAt}`):u.info(this.name,`[rate-limits] codex cached context/token only: hasContext=${!!i.contextWindow} hasToken=${!!i.tokenUsage}`);const l=await s;this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:i.hasData||!!l,cached:!0,sampledAt:i.sampledAt,rateLimits:i.rateLimits,contextWindow:i.contextWindow,tokenUsage:i.tokenUsage,providerQuota:l}});return}const a=this.pool.getAllSlots().find(l=>l.state==="ready"&&l.adapter);if(a&&(u.info(this.name,`[rate-limits] codex reuse existing slot: session=${a.sessionId}`),(await a.adapter.handleLocalAction?.(e))?.handled))return;const r=this.resolveRateLimitWakeSessionId(o,t);if(r){const l=await this.wakeRateLimitSlot(r,t);if(l?.adapter&&(await l.adapter.handleLocalAction?.(e))?.handled)return}const d=await s,c=!!d;u.info(this.name,`[rate-limits] codex no native data, providerQuota=${d?d.provider:"none"} available=${c}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:c,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:d}});return}case"claude":{const s=this.maybeQueryProviderQuota(),i=this.getFreshClaudeRateLimitState();if(i){const c=i.rateLimits,l=await s;u.info(this.name,`[rate-limits] claude global cached: sampledAt=${i.sampledAt} hasRateLimits=${!!c}`+(l?` providerQuota=${l.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!0,sampledAt:i.sampledAt,rateLimits:i.rateLimits??null,contextWindow:i.contextWindow,tokenUsage:null,providerQuota:l}});return}let n=this.pool.getAllSlots().find(c=>c.state==="ready"&&c.adapter instanceof T)??null;if(!n){const c=this.resolveRateLimitWakeSessionId(o,t);c&&(n=await this.wakeRateLimitSlot(c,t))}u.info(this.name,`[rate-limits] handleGetRateLimits: session_id=${o} adapterType=claude hasSlot=${!!n} hasAdapter=${!!n?.adapter}`);const a=n?.adapter,r=a instanceof T?a.getSessionState():null,d=await s;if(r){(r.rateLimits?.fiveHour||r.rateLimits?.sevenDay||r.contextWindow?.usedPercentage!=null)&&(this.cachedClaudeRateLimitState=r);const c=this.getFreshClaudeRateLimitState(),l=c?.rateLimits&&!r.rateLimits?{...r,rateLimits:c.rateLimits}:r,h=l.rateLimits;u.info(this.name,`[rate-limits] claude global state: sampledAt=${l.sampledAt} hasRateLimits=${!!h}`+(h?` fiveHour=${h.fiveHour?.usedPercentage??"n/a"}% resetsAt=${h.fiveHour?.resetsAt??"n/a"} sevenDay=${h.sevenDay?.usedPercentage??"n/a"}% resetsAt=${h.sevenDay?.resetsAt??"n/a"}`:"")+(c?.rateLimits&&!r.rateLimits?" source=live+cached-fallback":" source=live")+(d?` providerQuota=${d.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!1,sampledAt:l.sampledAt,rateLimits:l.rateLimits??null,contextWindow:l.contextWindow,tokenUsage:null,providerQuota:d}})}else u.info(this.name,`[rate-limits] claude no global state: hasAdapter=${!!a} adapterType=${a?.constructor?.name??"n/a"}`+(d?` providerQuota=${d.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!!d,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:d}});return}case"cursor":{const i=(o?this.pool.getSlot(o):null)?.adapter,n=i instanceof H?i.getRateLimitsSnapshot():{adapterType:"cursor",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null};this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:n});return}default:{const s=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&!!this.cachedProviderQuota,i=await this.maybeQueryProviderQuota();if(!i){u.info(this.name,`[rate-limits] no provider quota available for adapterType=${t}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null}});return}u.info(this.name,`[rate-limits] provider quota ${s?"cached":"queried"}: provider=${i.provider} success=${i.success}`+(i.tiers.length>0?` tiers=${i.tiers.map(n=>`${n.name}=${n.usedPercent}%`).join(",")}`:"")+(i.balance?` balance=${i.balance.remaining} ${i.balance.unit}`:"")+(i.error?` error=${i.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:s,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null,providerQuota:i}});return}}}resolveRateLimitWakeSessionId(e,o){const t=String(e??"").trim(),s=this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0});return s?t&&t===s?t:o==="codex"||o==="claude"?(t&&t!==s&&u.info(this.name,`[rate-limits] ${o} remap wake session: requested=${t} use_recent=${s}`),s):t&&t!==s?(u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=not_recent_session recent=${s}`),null):t||null:(u.info(this.name,`[rate-limits] skip wake slot: adapterType=${o} reason=no_recent_binding`),null)}async wakeRateLimitSlot(e,o){const t=String(e??"").trim();if(!t)return null;if(!this.bindingStore.get(t)?.cwd)return u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=binding_cwd_missing`),null;try{const i=this.pool.getOrCreateSlot(t);if(!i)return u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=slot_unavailable`),null;if(i.startPromise){const n=o==="claude"?6e4:2e4;await Promise.race([i.startPromise,new Promise((a,r)=>setTimeout(()=>r(new Error(`wake rate-limits slot timeout (${n}ms)`)),n))])}return u.info(this.name,`[rate-limits] wake slot success: session=${t} adapterType=${o}`),this.pool.getSlot(t)??i}catch(i){return u.warn(this.name,`[rate-limits] wake slot failed: session=${t} adapterType=${o} err=${i instanceof Error?i.message:String(i)}`),null}}sessionControlCtx(e){const o=this.pool.getSlot(e),t=o?.adapter instanceof A?o.adapter:null,s=(this.config.adapterType??"acp")==="acp",i={bindingStore:this.bindingStore,acpAdapter:t,globalConfigStore:this.globalConfigStore,agentName:this.name,log:u};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(t)return t.getSessionBindings();const n=this.sessionBindings;if(e&&!n.has(e)){const a=this.bindingStore.get(e);a?.cwd&&n.set(e,a.cwd)}return n},getStatus:()=>this.getStatus(),isAcpAlive:!!t?.isAlive(),getAcpSessionOptions:()=>t?.acpSessionOptions??null,setMode:n=>t?t.setMode(n):Promise.resolve(!1),setModel:n=>t?t.setModel(n):Promise.resolve(!1),acpSetMode:s?(n,a)=>N(i,n,a):void 0,acpSetModel:s?(n,a)=>W(i,n,a):void 0,getPendingApproval:n=>{const a=t?.pendingApprovalEntries.get(n);return a?{requestId:a}:void 0},deletePendingApproval:n=>t?.pendingApprovalEntries.delete(n)??!1,respondPermission:(n,a)=>(t&&t.respondToPermission(n,a),Promise.resolve()),onSessionBound:(n,a)=>{this.bindingStore.set(n,a)},onSessionUnbound:n=>{const r=this.bindingStore.get(n)?.cwd??"";this.bindingStore.delete(n),this.sessionBindings.delete(n),this.claudeWorkerStatus.delete(n),this.deferredMgr.clearSession(n);for(const d of this.pool.drainQueuedForSession(n))this.discardEventTrackingState(d.event_id);r&&this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:"stopped",cwd:r})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&o?.adapter instanceof U?(o.adapter.cancelCurrentRun(),Promise.resolve()):o?.adapter?.cancel("")??Promise.resolve(),onModeSet:n=>{const a=this.config.adapterType??"acp";I.has(a)||this.globalConfigStore?.set(this.name,{acpInitialMode:n})},onModelSet:n=>{const a=this.config.adapterType??"acp";I.has(a)||this.globalConfigStore?.set(this.name,{modelId:n})}}}sessionControlSenders(){return{sendEventAck:(e,o)=>this.aibotHandle.sendEventAck({event_id:e,session_id:o,received_at:Date.now()}),sendEventResult:(e,o,t)=>this.aibotHandle.sendEventResult({event_id:e,status:o,...t?.msg?{msg:t.msg}:{},...t?.code?{code:t.code}:{},updated_at:Date.now()}),sendLocalActionResult:(e,o,t,s,i)=>this.aibotHandle.sendLocalActionResult({action_id:e,status:o,...t?{result:t}:{},...s?{error_code:s}:{},...i?{error_msg:i}:{}})}}resolveBindingChannelKey(e){switch(e){case"claude":return"grix-claude";case"codex":return"codex";case"cursor":return"cursor";case"pi":return"pi";case"openhuman":return"openhuman";case"codewhale":return"codewhale";case"opencode":return"opencode";case"agy":return"acp";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,o){this.sendCtrl.finalizeThinking(e,o)}logInboundConversation(e){const o=String(e.session_id??"").trim();o&&this.conversationLog?.logInbound(o,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}buildInboundEvent(e,o){const t=Ze(this.sendCtrl.getGlobalRuntimeConfig(),o);return{event_id:e.event_id,session_id:e.session_id,thread_id:e.thread_id,sender_id:e.sender_id,msg_id:e.msg_id,msg_type:e.msg_type,content:e.content??"",quoted_message_id:e.quoted_message_id,context_messages_json:this.buildContextMessagesJson(e.context_messages),extra_json:e.extra?JSON.stringify(e.extra):void 0,connector_runtime_config:{response_delivery:t.responseDelivery,tool_events:t.toolEvents,thinking_events:t.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const o=e.filter(t=>!We(String(t?.content??"")));if(o.length!==0)return JSON.stringify(o)}isStaleEvent(e){const o=Number(e.created_at);return!Number.isFinite(o)||o<=0?!1:Date.now()-o>ct}async handleConnectorRollback(e){const o=String((e.params??{}).target_version??"").trim(),t=String((e.params??{}).reason??"server_initiated");if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_VERSION",error_msg:"target_version is required for connector_rollback"});return}u.info(this.name,`connector_rollback: target=${o} reason=${t}`);try{const{npmInstall:s,writePending:i,removePending:n,upgradeLog:a}=await import("../core/upgrade/npm-upgrader.js"),{resolveClientVersion:r}=await import("../core/util/client-version.js"),d=r();a(`server rollback: ${d} -> ${o} reason=${t}`),i(d,o),await s("grix-connector",o),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{rolled_back_to:o}}),process.kill(process.pid,"SIGTERM")}catch(s){try{const{removePending:n}=await import("../core/upgrade/npm-upgrader.js");n()}catch{}const i=s instanceof Error?s.message:String(s);u.error(this.name,`connector_rollback failed: ${i}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"ROLLBACK_FAILED",error_msg:i})}}setUpgradeTrigger(e){this.upgradeTrigger=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setSkillSyncHandler(e){this.skillSyncHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}isSharedInstance(){return!!this.config.aibot.sharedOwnerId}}export{pi as AgentInstance};
16
+ Models (current: ${n?.modelId??"default"}): ${a}`);return}case p.exec:{const[i,...n]=e.args.trim().split(/\s+/);if(!i){s("failed","Usage: /grix exec <command> [args]",g.verbInvalid);return}const r=this.pool.getSlot(t)?.adapter;if(!r?.execCommand){s("failed","Agent does not support command execution",g.verbInvalid);return}const d=r.getSupportedCommands?.()??[];if(!d.some(c=>c.name===i)){s("failed",`Unknown command: ${i}. Supported: ${d.map(c=>c.name).join(", ")}`,g.verbInvalid);return}try{const c=await r.execCommand(i,n.join(" "),t);s(c.status==="ok"?"responded":"failed",c.message??`${i} ${c.status}`,c.status==="ok"?void 0:g.runtimeError)}catch(c){s("failed",`exec error: ${c instanceof Error?c.message:c}`,g.runtimeError)}return}default:s("failed",`Unsupported command for Claude: /grix ${e.verb}`,g.verbInvalid)}}catch(i){s("failed",i instanceof Error?i.message:String(i),g.runtimeError)}}async handleSessionControlLocalAction(e){const o=String(e.action_type??"").trim();if(o!==b.sessionControl&&o!==b.setMode&&o!=="set_mode"&&o!==b.setModel&&o!=="set_model")return!1;const t=e.params??{},s=String(t.session_id??"").trim(),i=o===b.setMode?p.setMode:o===b.setModel?p.setModel:String(t.verb??"").trim().toLowerCase();if(u.info(this.name,`handleSessionControlLocalAction verb=${i} action_id=${e.action_id} session_id=${s}`),!s)return this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:x.localActionRouteMissing,error_msg:"local action session_id is required"}),!0;const n=r=>{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:r})},a=(r,d)=>{u.warn(this.name,`session_control local_action failed action_id=${e.action_id} session_id=${s} verb=${i} code=${r} msg=${d}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:r,error_msg:d})};try{switch(i){case p.open:{await D().catch(()=>{});const r=String(t.cwd??"").trim(),d=String(t.agent_session_id??"").trim();if(!r)return a(g.cwdRequired,"session control cwd is required"),!0;u.info(this.name,`handleSessionControlLocalAction open cwd=${r} session_id=${s}`);const c=await this.resolveCwdForBinding(r);this.ensureImportedAgentSession(d,c);const l=this.bindingStore.get(s);if(l?.cwd){const h=await this.resolveCwdForBinding(l.cwd);return h!==c?(a(g.rebindForbidden,"session binding cannot be changed to another working directory"),!0):(this.bindingStore.ensureModeId(s,C.fullAuto),this.setResolvedAgentSessionId(s,d),this.sessionBindings.set(s,h),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,h),n({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,h),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0)}return this.bindingStore.set(s,c,{modeId:C.fullAuto}),this.setResolvedAgentSessionId(s,d),this.sessionBindings.set(s,c),await this.ensureSlotStarted(s),await this.replayDeferredEventsForSession(s),this.refreshClaudeWorkerStatusCard(s,c),n({outcome:"opened",binding:{...this.buildOpenedBindingResult(s,c),mode_id:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId)}}),!0}case p.status:case p.where:{const r=this.bindingStore.get(s);return r?.cwd?(n({outcome:i,binding:{cwd:r.cwd,mode_id:this.normalizeClaudeModeId(r.modeId),worker_status:this.getClaudeWorkerStatus(s)}}),!0):(a(g.bindingMissing,"session binding was not found"),!0)}case p.stop:{const r=this.bindingStore.get(s);return r?.cwd?(await this.pool.removeSlot(s),n({outcome:"stopped",binding:{cwd:r.cwd,mode_id:this.normalizeClaudeModeId(r.modeId),worker_status:"stopped"}}),!0):(a(g.bindingMissing,"session binding was not found"),!0)}case p.restart:{const r=this.bindingStore.get(s);return r?.cwd?(await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,r.cwd),n({outcome:"restarted",binding:{cwd:r.cwd,mode_id:this.normalizeClaudeModeId(r.modeId)}}),!0):(a(g.bindingMissing,"session binding was not found"),!0)}case p.setMode:{const r=String(t.mode_id??t.modeId??"").trim();if(!r)return a(x.modeInvalid,"set mode_id is invalid"),!0;const d=this.normalizeClaudeModeId(r);if(d!==r.toLowerCase())return a(x.modeInvalid,"set mode_id is invalid"),!0;const c=this.bindingStore.get(s);if(!c?.cwd)return a(g.bindingMissing,"session binding was not found"),!0;if(this.normalizeClaudeModeId(c.modeId)!==d){if(this.getClaudeWorkerStatus(s)==="busy")return a(g.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u5F0F"),!0;this.bindingStore.setModeId(s,d),await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,c.cwd)}return n({outcome:"mode_set",mode_id:d,binding:{cwd:c.cwd,mode_id:d}}),!0}case p.setModel:{const r=String(t.model_id??t.modelId??"").trim();if(!r)return a("set_model_invalid","model_id is required"),!0;const d=this.bindingStore.get(s);if(!d?.cwd)return a(g.bindingMissing,"session binding was not found"),!0;if((d.modelId??"")!==r){if(this.getClaudeWorkerStatus(s)==="busy")return a(g.workerBusy,"\u5F53\u524D\u6709\u6D88\u606F\u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u505C\u6B62\u6216\u7B49\u5F85\u5176\u5B8C\u6210\u540E\u518D\u5207\u6362\u6A21\u578B"),!0;this.bindingStore.setModelId(s,r),this.globalConfigStore?.set(this.name,{modelId:r}),await this.pool.removeSlot(s),await this.ensureSlotStarted(s),this.refreshClaudeWorkerStatusCard(s,d.cwd)}return n({outcome:"model_set",model_id:r,binding:{cwd:d.cwd,model_id:r}}),!0}case p.listOptions:{const r=Q(),d=this.pool.getSlot(s);return n({modes:[C.fullAuto,C.approval],currentModeId:this.normalizeClaudeModeId(this.bindingStore.get(s)?.modeId),models:r.map(c=>({modelId:c.id,name:c.displayName})),currentModelId:this.bindingStore.get(s)?.modelId??"",available_models:r.map(c=>({id:c.id,displayName:c.displayName})),agent_commands:d?.adapter?.getSupportedCommands?.()??[]}),!0}case p.exec:{const[r,...d]=String(t.args??"").trim().split(/\s+/);if(!r)return a(g.verbInvalid,"Usage: exec <command> [args]"),!0;await this.ensureSlotStarted(s);const l=this.pool.getSlot(s)?.adapter;if(!l?.execCommand)return a(g.verbInvalid,"Agent does not support command execution"),!0;const h=l.getSupportedCommands?.()??[];if(!h.some(m=>m.name===r))return a(g.verbInvalid,`Unknown command: ${r}. Supported: ${h.map(m=>m.name).join(", ")}`),!0;try{const m=await l.execCommand(r,d.join(" "),s);m.status==="ok"?n({outcome:"exec",command:r,message:m.message,data:m.data}):a(g.runtimeError,m.message??`${r} failed`)}catch(m){a(g.runtimeError,`exec error: ${m instanceof Error?m.message:m}`)}return!0}default:return a(g.verbInvalid,`session control verb ${i} is not supported`),!0}}catch(r){const d=r instanceof Error&&r.cwdErrorCode?r.cwdErrorCode:r instanceof Error&&r.sessionControlErrorCode?r.sessionControlErrorCode:g.runtimeError;return u.error(this.name,`handleSessionControlLocalAction error verb=${i} session_id=${s}: ${r instanceof Error?r.message:r}`),a(d,r instanceof Error?r.message:String(r)),!0}}async handleEventCancel(e){const{event_id:o,session_id:t}=e;if(u.info(this.name,`handleEventCancel start event_id=${o} session_id=${t}`),this.pool.cancelEvent(o,t)){if(!(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(o)??!1)){this.sendEventResultWithCleanup(o,"canceled","canceled"),this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!0,final_state:"canceled"});return}await this.waitForEventDone(o,t,15e3),this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!0,final_state:"canceled"}),this.pushQueueSnapshotForSession(t);return}this.aibotHandle.sendEventCancelResult({event_id:o,accepted:!1,reason:"event not found or not cancelable"})}waitForEventDone(e,o,t){return new Promise(s=>{const i=this.pool.getSlot(o);if(!i?.adapter){s();return}const n=setTimeout(()=>{i.adapter.removeListener("eventDone",a),s()},t),a=r=>{r===e&&(clearTimeout(n),i.adapter.removeListener("eventDone",a),s())};i.adapter.on("eventDone",a)})}handleAibotStop(e){if(u.info(this.name,`[stop-trace] handleAibotStop begin session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"} adapterType=${this.config.adapterType??"acp"}`),this.aibotHandle.sendEventStopAck({stop_id:e.stop_id,event_id:e.event_id,accepted:!0,updated_at:Date.now()}),this.pool.removeQueuedEvent(e.session_id,e.event_id)){u.info(this.name,`[stop-trace] handleAibotStop removed queued(not-running) event -> stopResult(stopped) session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"}`),this.discardEventTrackingState(e.event_id),this.pushQueueSnapshotForSession(e.session_id),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()});return}const o=this.pool.getSlot(e.session_id),t=o?.adapter?.getStatus().busy??!1,s=(this.config.adapterType??"acp")==="acp",i=o?.adapter?.getActiveEventIds,n=typeof i=="function"?i.call(o.adapter):[],a=n.length>0?n.includes(e.event_id):t,r=(s||(this.config.adapterType??"acp")==="codex"||(this.config.adapterType??"acp")==="claude")&&a;if(u.info(this.name,`[stop-trace] handleAibotStop decision session=${e.session_id} event=${e.event_id} slotExists=${!!o?.adapter} busy=${t} activeIds=[${n.join(",")}] stoppingActiveEvent=${a} killOnStop=${r}`),a&&this.sendCtrl.markEventStopped(e.event_id),o?.adapter&&t){const d=r?this.pool.drainQueuedForSession(e.session_id):[];let c=!1,l=null;const h=v=>{c||(c=!0,l&&(clearTimeout(l),l=null),o.adapter.removeListener("eventDone",m),u.info(this.name,`[stop-trace] handleAibotStop ${v} -> stopResult(stopped) session=${e.session_id} event=${e.event_id} stop_id=${e.stop_id||"-"} killOnStop=${r}`),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()}),r&&this.killAndResumeStopSlot(e.session_id,d))},m=v=>{v===e.event_id&&h("eventDone")};o.adapter.on("eventDone",m),l=setTimeout(()=>h("timeout"),mt),this.pool.deliverStopEvent(e.event_id,e.session_id)}else u.info(this.name,`[stop-trace] handleAibotStop slot-not-busy -> immediate stopResult(stopped) session=${e.session_id} event=${e.event_id} slotExists=${!!o?.adapter}`),this.pool.deliverStopEvent(e.event_id,e.session_id),this.aibotHandle.sendEventStopResult({stop_id:e.stop_id,event_id:e.event_id,status:"stopped",updated_at:Date.now()});(this.config.adapterType??"acp")==="pi"&&this.aibotHandle.sendText({event_id:e.event_id,session_id:e.session_id,content:"/stop",msg_type:0})}async killAndResumeStopSlot(e,o){if(!this.stopped){u.info(this.name,`[stop-trace] killAndResumeStopSlot begin session=${e} siblings=${o.length} -> removeSlot (kill process group)`);try{await this.pool.removeSlot(e),u.info(this.name,`[stop-trace] killAndResumeStopSlot removeSlot done session=${e} (process killed) -> redeliver ${o.length} sibling(s)`)}catch(t){u.warn(this.name,`[acp-stop] removeSlot failed session=${e}: ${t instanceof Error?t.message:String(t)}`)}if(!this.stopped)for(const t of o){if(this.stopped)break;try{await this.pool.deliverInboundEvent(t)}catch(s){u.error(this.name,`[acp-stop] sibling redeliver failed event=${t.event_id} session=${e}: ${s instanceof Error?s.message:String(s)}`),this.sendEventResultWithCleanup(t.event_id,"failed",s instanceof Error?s.message:String(s))}}}}handleAibotRevoke(e){if(!e.event_id||!this.revokeHandler.checkAndTrack(e.event_id))return;const o=e.event_id,t=e.session_id;if(t&&this.pool.cancelEvent(o,t)){(this.pool.getSlot(t)?.adapter?.getActiveEventIds().includes(o)??!1)||this.sendEventResultWithCleanup(o,"canceled","revoked");return}if(this.deferredMgr.removeEvent(o)){this.aibotHandle.sendEventResult({event_id:o,status:"canceled",msg:"revoked",updated_at:Date.now()});return}this.pool.deliverStopEvent(o,t||void 0)}async handleConfigureGatewayProvider(e){const o=e.params??{},t=String(o.api_key??"").trim(),s=String(o.anthropic_base_url??"").trim(),i=String(o.openai_base_url??"").trim(),n=typeof o.model=="string"&&o.model.trim()||void 0;let a=!1;if(!t){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_API_KEY",error_msg:"api_key is required"});return}const r=this.config.adapterType??"acp",d=r==="claude"||r==="codex";try{if(d){const c=r==="claude"?s:i;if(!c){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_BASE_URL",error_msg:`${r==="claude"?"anthropic_base_url":"openai_base_url"} is required`});return}const l=ue();if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"PROXY_UNAVAILABLE",error_msg:"MITM proxy manager not initialized"});return}const h=he(r),m=ge(r,c,t,{model:n});l.setRoute(m);for(const v of h)l.setHostDefaultRoute(v,m.routeKey);await l.setAgentRelayEnabled(this.name,!0,{relayHosts:h}),a=!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 "${r}" does not support Grix relay provider config`});return}await this.providerConfigHandler({base_url:i||void 0,api_key:t,model:n})}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0,restart_deferred:a}})}catch(c){u.error(this.name,`handleConfigureGatewayProvider failed: ${c}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"CONFIGURE_FAILED",error_msg:c instanceof Error?c.message:String(c)})}}async handleAibotLocalAction(e){const o=e.action_type??"",t=String((e.params??{}).session_id??""),s=String((e.params??{}).verb??"").trim().toLowerCase();u.debug(this.name,`local_action received action_type=${o} verb=${s||"-"} action_id=${e.action_id} session_id=${t}`);const i=(this.config.adapterType??"acp")==="claude";if(o===b.sessionControl&&s===p.exec&&await this.handleSessionControlLocalAction(e))return;if(o===b.sessionControl&&s===p.listSessions){await this.handleListSessionsLocalAction(e);return}if(o==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(i&&(o===b.interactionReply||o==="exec_approve"||o==="exec_reject")&&(await this.pool.deliverLocalAction(e)).handled||i&&await this.handleSessionControlLocalAction(e))return;if(o===b.sessionControl){const c=this.config.adapterType??"acp",l=c==="codex",h=c==="pi",m=String((e.params??{}).verb??"").trim().toLowerCase();if(l&&m===p.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(c==="cursor"&&m===p.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(l&&m==="restart"){const S=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:t,cwd:S,workerStatus:"ready"}}});return}if(h&&m===p.open){try{const f=e.params??{},S=String(f.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(S),R=String(f.agent_session_id??"").trim();this.ensureImportedAgentSession(R,w),this.bindingStore.set(t,w),this.setResolvedAgentSessionId(t,R),this.sessionBindings.set(t,w),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:w}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,w)}})}catch(f){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f?.sessionControlErrorCode??f?.cwdErrorCode??g.invalidCwd,error_msg:f instanceof Error?f.message:String(f)})}return}if(h&&m===p.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((c==="openhuman"||c==="opencode")&&m===p.open){try{const f=e.params??{},S=String(f.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=await this.resolveCwdForBinding(S),R=String(f.agent_session_id??"").trim();this.ensureImportedAgentSession(R,w),this.bindingStore.set(t,w),this.setResolvedAgentSessionId(t,R),this.sessionBindings.set(t,w),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,w)}})}catch(f){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f?.sessionControlErrorCode??f?.cwdErrorCode??g.invalidCwd,error_msg:f instanceof Error?f.message:String(f)})}return}if(c==="codewhale"&&m===p.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(c==="acp"&&m===p.stop){const S=this.bindingStore.get(t)?.cwd??"";await this.pool.removeSlot(t).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:t,cwd:S,workerStatus:"stopped"}}});return}try{if(m===p.open){const f=e.params??{},S=String(f.cwd??"").trim();if(!S){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const w=String(f.agent_session_id??"").trim();if(w){const R=await this.resolveCwdForBinding(S);this.ensureImportedAgentSession(w,R)}}await this.handleSessionControlLocalActionForPool(e)}catch(f){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:f?.sessionControlErrorCode??f?.cwdErrorCode??g.runtimeError,error_msg:f instanceof Error?f.message:String(f)});return}if(m===p.open){const f=e.params??{},S=await this.resolveCwdForBinding(String(f.cwd??"").trim());this.setResolvedAgentSessionId(t,String(f.agent_session_id??"").trim()),c==="agy"&&(this.bindingStore.set(t,S),this.sessionBindings.set(t,S)),await this.deferredMgr.release(t,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(t,S)}}),(this.config.adapterType??"acp")==="agy"&&this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:"ready",cwd:S,meta:this.buildAgyToolbarMeta(t)})}else ze(e,this.sessionControlCtx(t),this.sessionControlSenders());return}if(o==="file_list"){const c=Date.now(),l=t?this.bindingStore.get(t)?.cwd:void 0,h=e.params??{},m=String(h.parent_id??"").trim(),v=Array.isArray(h.allowed_extensions)?h.allowed_extensions.filter(S=>typeof S=="string").map(S=>S.trim()).filter(S=>S.length>0):[];u.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${t} parent_id=${m||"<root>"} show_hidden=${!!h.show_hidden} ext_count=${v.length} bound_cwd=${l??"<none>"}`);const _=await Ve({parent_id:m||null,session_id:t,show_hidden:!!h.show_hidden,allowed_extensions:v},{resolveCwd:()=>l??this.config.agent.cwd??process.cwd(),fallbackDir:j()}),E=Date.now()-c,f=_.result?.files?.length??0;u.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${_.status} elapsed=${E}ms count=${f} current_path=${_.result?.current_path??""} error_code=${_.error_code??""} error_msg=${_.error_msg??""}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:_.status,..._.result?{result:{..._.result,machine_name:Xe()}}:{},..._.error_code?{error_code:_.error_code}:{},..._.error_msg?{error_msg:_.error_msg}:{}});return}if(o==="create_folder"){const c=t?this.bindingStore.get(t)?.cwd:void 0,l=String((e.params??{}).parent_id??"").trim(),h=String((e.params??{}).name??"").trim(),m=await Je({parent_id:l||null,name:h,session_id:t},{resolveCwd:()=>c??this.config.agent.cwd??process.cwd(),fallbackDir:j()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:m.status,...m.result?{result:m.result}:{},...m.error_code?{error_code:m.error_code}:{},...m.error_msg?{error_msg:m.error_msg}:{}});return}if(o===b.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,t);return}if(o===b.getSessionUsage){await this.handleGetSessionUsage(e,t);return}if(o===b.getRateLimits){await this.handleGetRateLimits(e,t);return}const n=(this.config.adapterType??"acp")==="acp";if((i||n)&&o===b.threadCompact){await this.handleThreadCompact(e,t);return}if(o==="connector_rollback"){await this.handleConnectorRollback(e);return}if(o==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(o===b.getAgentGlobalConfig){const c=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...c?{config:c}:{config:null}}});return}if(o==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}const a=this.config.adapterType??"acp",r=(a==="codex"||a==="cursor"||a==="pi"||a==="openhuman"||a==="opencode"||a==="acp")&&!!t&&!!this.bindingStore.get(t)?.cwd,d=await this.pool.deliverLocalAction(e,{autoCreateSlot:r});if(d.handled){if(d.kind==="set_mode"){const c=String((e.params??{}).mode_id??"");c&&(a==="cursor"||a==="claude"?this.bindingStore.setModeId(t,c):I.has(a)||this.globalConfigStore?.set(this.name,{acpInitialMode:c}))}else if(d.kind==="set_model"){const c=String((e.params??{}).model_id??"");c&&(a==="cursor"?(this.bindingStore.setModelId(t,c),this.globalConfigStore?.set(this.name,{modelId:c})):a==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:c}):I.has(a)||this.globalConfigStore?.set(this.name,{modelId:c}))}else if(d.kind==="set_reasoning_effort"){const c=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");c&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:c})}else if(d.kind==="set_sandbox_mode"){const c=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(c){const l=c==="default"?void 0:c;this.globalConfigStore?.set(this.name,{codexSandboxMode:l})}}return}if((a==="codex"||a==="cursor"||a==="pi"||a==="openhuman"||a==="opencode")&&t&&!this.bindingStore.get(t)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(a==="acp"&&(o==="set_mode"||o==="set_model")){const c=this.sessionControlSenders(),l=this.pool.getSlot(t)?.adapter,h={bindingStore:this.bindingStore,acpAdapter:l instanceof A?l:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:u};if(o==="set_mode"){const m=String((e.params??{}).mode_id??""),v=await K(h,t,m);if(v.status==="failed")c.sendLocalActionResult(e.action_id,"failed",void 0,v.errorCode,v.errorMsg);else{const _=l instanceof A?l.buildToolbarContext(v.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,E=_?{..._,...v.result}:v.result;c.sendLocalActionResult(e.action_id,"ok",E)}}else{const m=String((e.params??{}).model_id??""),v=await G(h,t,m);if(v.status==="failed")c.sendLocalActionResult(e.action_id,"failed",void 0,v.errorCode,v.errorMsg);else{const _=l instanceof A?l.buildToolbarContext(v.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,E=_?{..._,...v.result}:v.result;c.sendLocalActionResult(e.action_id,"ok",E)}}return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:`action type ${o} is not supported`})}async handleGetSessionUsage(e,o){if(!o){u.warn(this.name,`[usage] get_session_usage rejected: no session_id in params, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for get_session_usage"});return}const t=this.config.adapterType??"acp",s=this.bindingStore.get(o),i=s?.cwd??this.config.agent.cwd??process.cwd();u.info(this.name,`[usage] get_session_usage action_id=${e.action_id} session_id=${o} adapterType=${t} hasBinding=${!!s} cwd=${i}`);let n=null,a,r;switch(t){case"claude":{if(a=s?.claudeSessionId,!a){u.warn(this.name,`[usage] no claude binding for session_id=${o}, action_id=${e.action_id}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Claude session binding found"});return}u.info(this.name,`[usage] parsing claude usage: claudeSessionId=${a} cwd=${i}`),n=await oe(a,i),r="claude";break}case"agy":{this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"agy",available:!1,reason:"agy print-mode adapter does not track token usage"}});return}case"acp":default:{if(a=s?.acpSessionId,!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No ACP session binding found"});return}n=await ce(a,i,this.config.aibot.clientType),r=t,(!r||r==="acp")&&(r="acp");break}case"codex":{if(a=s?.codexThreadId,!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Codex thread binding found"});return}n=await fe(a),r="codex";break}case"pi":{if(a=s?.piSessionPath,!a){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Pi session path binding found"});return}n=await Te(a),r="pi";break}case"cursor":{const c=this.pool.getSlot(o)?.adapter;if(!(c instanceof H)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No Cursor session found"});return}const l=c.getUsageSnapshot(o);if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"cursor",models:[{modelId:this.bindingStore.get(o)?.modelId??"auto",turns:l.turns,input:l.total.input,output:l.total.output,cacheRead:l.total.cacheRead,cacheWrite:l.total.cacheWrite}],total:{input:l.total.input,output:l.total.output,cacheRead:l.total.cacheRead,cacheWrite:l.total.cacheWrite},turns:l.turns,sampledAt:l.sampledAt}});return}case"codewhale":{const c=this.pool.getSlot(o)?.adapter;if(!(c instanceof O)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"no_binding",error_msg:"No CodeWhale session found"});return}const l=c.getUsageSnapshot();if(!l){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:o,adapterType:"codewhale",models:[{modelId:this.bindingStore.get(o)?.modelId??"codewhale",turns:l.turns,input:l.total.input,output:l.total.output}],total:{input:l.total.input,output:l.total.output},turns:l.turns,sampledAt:l.sampledAt}});return}}if(!n){u.info(this.name,`[usage] no usage data found: session_id=${o} adapterSessionId=${a} adapterType=${r}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"usage_not_found",error_msg:"No usage data found for this session"});return}u.info(this.name,`[usage] result ok: session_id=${o} adapterSessionId=${a} turns=${n.turns} models=${n.models.length}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{sessionId:a,adapterType:r,models:n.models,total:n.total,turns:n.turns,sampledAt:new Date().toISOString()}})}async handleThreadCompact(e,o){if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"session_id_required",error_msg:"session_id is required for thread_compact"});return}if(!this.bindingStore.get(o)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.bindingMissing,error_msg:"session binding was not found"});return}try{await this.ensureSlotStarted(o);const i=this.pool.getSlot(o)?.adapter;if(!i?.execCommand){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:"Agent does not support command execution"});return}u.info(this.name,`thread_compact session_id=${o} action_id=${e.action_id}`);const n=await i.execCommand("compact","",o);n.status==="ok"?this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"compacted",message:n.message,data:n.data}}):this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:n.message??"compact failed"})}catch(s){u.warn(this.name,`thread_compact error session_id=${o}: ${s instanceof Error?s.message:s}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:g.runtimeError,error_msg:s instanceof Error?s.message:String(s)})}}async handleGetRateLimits(e,o){const t=this.config.adapterType??"acp";if(this.config.aibot.clientType==="kiro"){const s=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs),i=this.cachedAcpContextWindow;if(s&&this.cachedProviderQuota){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!0,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:i,tokenUsage:null,providerQuota:this.cachedProviderQuota}});return}try{const n=await B();this.cachedProviderQuota=n,this.cachedProviderQuotaSampledAtMs=Date.now(),u.info(this.name,`[rate-limits] kiro quota queried: success=${n.success}`+(n.balance?` balance=${n.balance.remaining} ${n.balance.unit}`:"")+(n.error?` error=${n.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!0,cached:!1,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:i,tokenUsage:null,providerQuota:n}})}catch(n){u.warn(this.name,`[rate-limits] kiro quota query failed: ${n instanceof Error?n.message:String(n)}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"acp",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:i,tokenUsage:null}})}return}switch(t){case"codex":{const s=this.maybeQueryProviderQuota(),i=this.getFreshCodexGlobalRateLimitCache();if(i.hasData&&!this.isRateLimitsCacheFresh(this.cachedRateLimitsSampledAtMs)&&!this.isRateLimitsCacheFresh(this.cachedCodexUsageSampledAtMs)){const l=this.pool.getAllSlots().find(h=>h.state==="ready"&&h.adapter);if(l&&(u.info(this.name,`[rate-limits] codex cache stale, refreshing from slot: session=${l.sessionId}`),(await l.adapter.handleLocalAction?.(e))?.handled))return}if(i.hasData){i.rateLimits?u.info(this.name,`[rate-limits] codex cached: primary=${i.rateLimits.primary.usedPercent.toFixed(1)}% resetsAt=${i.rateLimits.primary.resetsAt} secondary=${i.rateLimits.secondary.usedPercent.toFixed(1)}% resetsAt=${i.rateLimits.secondary.resetsAt}`):u.info(this.name,`[rate-limits] codex cached context/token only: hasContext=${!!i.contextWindow} hasToken=${!!i.tokenUsage}`);const l=await s;this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:i.hasData||!!l,cached:!0,sampledAt:i.sampledAt,rateLimits:i.rateLimits,contextWindow:i.contextWindow,tokenUsage:i.tokenUsage,providerQuota:l}});return}const a=this.pool.getAllSlots().find(l=>l.state==="ready"&&l.adapter);if(a&&(u.info(this.name,`[rate-limits] codex reuse existing slot: session=${a.sessionId}`),(await a.adapter.handleLocalAction?.(e))?.handled))return;const r=this.resolveRateLimitWakeSessionId(o,t);if(r){const l=await this.wakeRateLimitSlot(r,t);if(l?.adapter&&(await l.adapter.handleLocalAction?.(e))?.handled)return}const d=await s,c=!!d;u.info(this.name,`[rate-limits] codex no native data, providerQuota=${d?d.provider:"none"} available=${c}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"codex",available:c,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:d}});return}case"claude":{const s=this.maybeQueryProviderQuota(),i=this.getFreshClaudeRateLimitState();if(i){const c=i.rateLimits,l=await s;u.info(this.name,`[rate-limits] claude global cached: sampledAt=${i.sampledAt} hasRateLimits=${!!c}`+(l?` providerQuota=${l.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!0,sampledAt:i.sampledAt,rateLimits:i.rateLimits??null,contextWindow:i.contextWindow,tokenUsage:null,providerQuota:l}});return}let n=this.pool.getAllSlots().find(c=>c.state==="ready"&&c.adapter instanceof T)??null;if(!n){const c=this.resolveRateLimitWakeSessionId(o,t);c&&(n=await this.wakeRateLimitSlot(c,t))}u.info(this.name,`[rate-limits] handleGetRateLimits: session_id=${o} adapterType=claude hasSlot=${!!n} hasAdapter=${!!n?.adapter}`);const a=n?.adapter,r=a instanceof T?a.getSessionState():null,d=await s;if(r){(r.rateLimits?.fiveHour||r.rateLimits?.sevenDay||r.contextWindow?.usedPercentage!=null)&&(this.cachedClaudeRateLimitState=r);const c=this.getFreshClaudeRateLimitState(),l=c?.rateLimits&&!r.rateLimits?{...r,rateLimits:c.rateLimits}:r,h=l.rateLimits;u.info(this.name,`[rate-limits] claude global state: sampledAt=${l.sampledAt} hasRateLimits=${!!h}`+(h?` fiveHour=${h.fiveHour?.usedPercentage??"n/a"}% resetsAt=${h.fiveHour?.resetsAt??"n/a"} sevenDay=${h.sevenDay?.usedPercentage??"n/a"}% resetsAt=${h.sevenDay?.resetsAt??"n/a"}`:"")+(c?.rateLimits&&!r.rateLimits?" source=live+cached-fallback":" source=live")+(d?` providerQuota=${d.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!0,cached:!1,sampledAt:l.sampledAt,rateLimits:l.rateLimits??null,contextWindow:l.contextWindow,tokenUsage:null,providerQuota:d}})}else u.info(this.name,`[rate-limits] claude no global state: hasAdapter=${!!a} adapterType=${a?.constructor?.name??"n/a"}`+(d?` providerQuota=${d.provider}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:"claude",available:!!d,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null,providerQuota:d}});return}case"cursor":{const i=(o?this.pool.getSlot(o):null)?.adapter,n=i instanceof H?i.getRateLimitsSnapshot():{adapterType:"cursor",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null};this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:n});return}default:{const s=this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)&&!!this.cachedProviderQuota,i=await this.maybeQueryProviderQuota();if(!i){u.info(this.name,`[rate-limits] no provider quota available for adapterType=${t}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null}});return}u.info(this.name,`[rate-limits] provider quota ${s?"cached":"queried"}: provider=${i.provider} success=${i.success}`+(i.tiers.length>0?` tiers=${i.tiers.map(n=>`${n.name}=${n.usedPercent}%`).join(",")}`:"")+(i.balance?` balance=${i.balance.remaining} ${i.balance.unit}`:"")+(i.error?` error=${i.error}`:"")),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{adapterType:t,available:!0,cached:s,sampledAt:this.cachedProviderQuotaSampledAtMs,rateLimits:null,contextWindow:this.cachedAcpContextWindow??null,tokenUsage:null,providerQuota:i}});return}}}resolveRateLimitWakeSessionId(e,o){const t=String(e??"").trim(),s=this.bindingStore.getMostRecentlyUpdatedSessionId({requireCwd:!0});return s?t&&t===s?t:o==="codex"||o==="claude"?(t&&t!==s&&u.info(this.name,`[rate-limits] ${o} remap wake session: requested=${t} use_recent=${s}`),s):t&&t!==s?(u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=not_recent_session recent=${s}`),null):t||null:(u.info(this.name,`[rate-limits] skip wake slot: adapterType=${o} reason=no_recent_binding`),null)}async wakeRateLimitSlot(e,o){const t=String(e??"").trim();if(!t)return null;if(!this.bindingStore.get(t)?.cwd)return u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=binding_cwd_missing`),null;try{const i=this.pool.getOrCreateSlot(t);if(!i)return u.info(this.name,`[rate-limits] skip wake slot: session=${t} adapterType=${o} reason=slot_unavailable`),null;if(i.startPromise){const n=o==="claude"?6e4:2e4;await Promise.race([i.startPromise,new Promise((a,r)=>setTimeout(()=>r(new Error(`wake rate-limits slot timeout (${n}ms)`)),n))])}return u.info(this.name,`[rate-limits] wake slot success: session=${t} adapterType=${o}`),this.pool.getSlot(t)??i}catch(i){return u.warn(this.name,`[rate-limits] wake slot failed: session=${t} adapterType=${o} err=${i instanceof Error?i.message:String(i)}`),null}}sessionControlCtx(e){const o=this.pool.getSlot(e),t=o?.adapter instanceof A?o.adapter:null,s=(this.config.adapterType??"acp")==="acp",i={bindingStore:this.bindingStore,acpAdapter:t,globalConfigStore:this.globalConfigStore,agentName:this.name,log:u};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(t)return t.getSessionBindings();const n=this.sessionBindings;if(e&&!n.has(e)){const a=this.bindingStore.get(e);a?.cwd&&n.set(e,a.cwd)}return n},getStatus:()=>this.getStatus(),isAcpAlive:!!t?.isAlive(),getAcpSessionOptions:()=>t?.acpSessionOptions??null,setMode:n=>t?t.setMode(n):Promise.resolve(!1),setModel:n=>t?t.setModel(n):Promise.resolve(!1),acpSetMode:s?(n,a)=>K(i,n,a):void 0,acpSetModel:s?(n,a)=>G(i,n,a):void 0,getPendingApproval:n=>{const a=t?.pendingApprovalEntries.get(n);return a?{requestId:a}:void 0},deletePendingApproval:n=>t?.pendingApprovalEntries.delete(n)??!1,respondPermission:(n,a)=>(t&&t.respondToPermission(n,a),Promise.resolve()),onSessionBound:(n,a)=>{this.bindingStore.set(n,a)},onSessionUnbound:n=>{const r=this.bindingStore.get(n)?.cwd??"";this.bindingStore.delete(n),this.sessionBindings.delete(n),this.claudeWorkerStatus.delete(n),this.deferredMgr.clearSession(n);for(const d of this.pool.drainQueuedForSession(n))this.discardEventTrackingState(d.event_id);r&&this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:"stopped",cwd:r})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&o?.adapter instanceof U?(o.adapter.cancelCurrentRun(),Promise.resolve()):o?.adapter?.cancel("")??Promise.resolve(),onModeSet:n=>{const a=this.config.adapterType??"acp";I.has(a)||this.globalConfigStore?.set(this.name,{acpInitialMode:n})},onModelSet:n=>{const a=this.config.adapterType??"acp";I.has(a)||this.globalConfigStore?.set(this.name,{modelId:n})}}}sessionControlSenders(){return{sendEventAck:(e,o)=>this.aibotHandle.sendEventAck({event_id:e,session_id:o,received_at:Date.now()}),sendEventResult:(e,o,t)=>this.aibotHandle.sendEventResult({event_id:e,status:o,...t?.msg?{msg:t.msg}:{},...t?.code?{code:t.code}:{},updated_at:Date.now()}),sendLocalActionResult:(e,o,t,s,i)=>this.aibotHandle.sendLocalActionResult({action_id:e,status:o,...t?{result:t}:{},...s?{error_code:s}:{},...i?{error_msg:i}:{}})}}resolveBindingChannelKey(e){switch(e){case"claude":return"grix-claude";case"codex":return"codex";case"cursor":return"cursor";case"pi":return"pi";case"openhuman":return"openhuman";case"codewhale":return"codewhale";case"opencode":return"opencode";case"agy":return"acp";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,o){this.sendCtrl.finalizeThinking(e,o)}logInboundConversation(e){const o=String(e.session_id??"").trim();o&&this.conversationLog?.logInbound(o,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}buildInboundEvent(e,o){const t=it(this.sendCtrl.getGlobalRuntimeConfig(),o);return{event_id:e.event_id,session_id:e.session_id,thread_id:e.thread_id,sender_id:e.sender_id,msg_id:e.msg_id,msg_type:e.msg_type,content:e.content??"",quoted_message_id:e.quoted_message_id,context_messages_json:this.buildContextMessagesJson(e.context_messages),extra_json:e.extra?JSON.stringify(e.extra):void 0,connector_runtime_config:{response_delivery:t.responseDelivery,tool_events:t.toolEvents,thinking_events:t.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const o=e.filter(t=>!Ge(String(t?.content??"")));if(o.length!==0)return JSON.stringify(o)}isStaleEvent(e){const o=Number(e.created_at);return!Number.isFinite(o)||o<=0?!1:Date.now()-o>ht}async handleConnectorRollback(e){const o=String((e.params??{}).target_version??"").trim(),t=String((e.params??{}).reason??"server_initiated");if(!o){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"MISSING_TARGET_VERSION",error_msg:"target_version is required for connector_rollback"});return}u.info(this.name,`connector_rollback: target=${o} reason=${t}`);try{const{npmInstall:s,writePending:i,removePending:n,upgradeLog:a}=await import("../core/upgrade/npm-upgrader.js"),{resolveClientVersion:r}=await import("../core/util/client-version.js"),d=r();a(`server rollback: ${d} -> ${o} reason=${t}`),i(d,o),await s("grix-connector",o),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{rolled_back_to:o}}),process.kill(process.pid,"SIGTERM")}catch(s){try{const{removePending:n}=await import("../core/upgrade/npm-upgrader.js");n()}catch{}const i=s instanceof Error?s.message:String(s);u.error(this.name,`connector_rollback failed: ${i}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"ROLLBACK_FAILED",error_msg:i})}}setUpgradeTrigger(e){this.upgradeTrigger=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setSkillSyncHandler(e){this.skillSyncHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}isSharedInstance(){return!!this.config.aibot.sharedOwnerId}}export{bi 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};
@@ -0,0 +1 @@
1
+ import{readFile as f}from"node:fs/promises";import{scanSkills as p}from"../../adapter/claude/skill-scanner.js";import{scanDefaultSkills as u}from"../../default-skills/index.js";const w=15e3;class e extends Error{}function h(o){return new URL(o.replace(/^wss:/,"https:").replace(/^ws:/,"http:")).origin}function m(o,r){const t=o.trim();if(!t)throw new e("skill name is required");const s=p(r),i=u(),a=[...s,...i].find(l=>l.name===t);if(!a)throw new e(`skill "${t}" not found`);if(a.managed)throw new e(`skill "${t}" is system-managed and cannot be uploaded`);if(!a.filePath)throw new e(`skill "${t}" has no local file`);return a}async function y(o,r,t,s=fetch){const i=m(o,r);let c;try{c=await f(i.filePath,"utf8")}catch(n){throw new e(`failed to read skill file: ${n instanceof Error?n.message:String(n)}`)}const a=`${h(t.wsUrl)}/v1/agent-api/skills/upload`;let l;try{l=await s(a,{method:"POST",headers:{Authorization:`Bearer ${t.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({name:i.name,content:c}),signal:AbortSignal.timeout(w)})}catch(n){throw new e(`upload request failed: ${n instanceof Error?n.message:String(n)}`)}if(!l.ok)throw new e(`upload rejected: HTTP ${l.status}`);const d=await l.json().catch(()=>null);if(!d||d.code!==0)throw new e(`upload rejected: ${d?.msg||"unknown error"}`)}export{e as SkillUploadError,m as findUploadableSkill,y as uploadSkill};
@@ -0,0 +1 @@
1
+ import{readFileSync as i}from"node:fs";import{join as f}from"node:path";import{createHash as u}from"node:crypto";const d=".grix-sync.json";function m(t){return u("sha256").update(t,"utf8").digest("hex")}function p(t){const n=new Map;try{const c=i(f(t,d),"utf8"),r=JSON.parse(c)?.skills;if(r&&typeof r=="object")for(const[s,o]of Object.entries(r))o&&typeof o.digest=="string"&&n.set(s,o.digest)}catch{}return n}function g(t,n){const c=p(n);return t.map(e=>{if(e.managed||!e.filePath)return e;let r;try{r=i(e.filePath,"utf8")}catch{return e}const s=m(r),o=c.get(e.name);let a;return o===void 0?a="unsynced":o===s?a="synced":a="modified",{...e,syncState:a}})}function y(t){return{name:t.name,description:t.description,trigger:t.trigger,source:t.source,managed:t.managed,sync_state:t.syncState}}function j(t,n){return g(t,n).map(y)}export{g as annotateSyncStates,j as buildWireSkills,m as computeContentDigest,y as toWireSkill};
@@ -1 +1 @@
1
- import{readFileSync as p,readdirSync as c,existsSync as a,mkdirSync as k,cpSync as y,writeFileSync as h,rmSync as g}from"node:fs";import{join as t,dirname as S}from"node:path";import{homedir as m}from"node:os";import{fileURLToPath as D}from"node:url";import{parseSkillFrontmatter as v,scanSkills as x,dedupeSkills as F}from"../adapter/claude/skill-scanner.js";import{resolveRuntimePaths as w}from"../core/config/index.js";import{log as u}from"../core/log/index.js";const l=S(D(import.meta.url)),f=".grix-managed";function d(){const e=[];let i;try{i=c(l,{withFileTypes:!0,encoding:"utf8"})}catch{return e}for(const r of i){if(!r.isDirectory())continue;const n=t(l,r.name,"SKILL.md");try{const s=p(n,"utf-8"),o=v(s);o?.name&&e.push({name:o.name,description:o.description,trigger:o.trigger,source:"connector"})}catch{}}return e}function T(e){let i=[];try{i=x(e)}catch{i=[]}return F([...i,...d()])}function j(e){const i=[];let r;try{r=c(l,{withFileTypes:!0,encoding:"utf8"})}catch{return i}for(const n of r){if(!n.isDirectory())continue;const s=t(l,n.name);if(a(t(s,"SKILL.md")))try{k(e,{recursive:!0});const o=t(e,n.name);y(s,o,{recursive:!0}),h(t(o,f),"","utf8"),i.push(n.name)}catch{}}return i}function C(){return(process.env.KIMI_CODE_HOME||"").trim()||t(m(),".kimi-code")}function L(){const e=m(),i=process.env.XDG_CONFIG_HOME||t(e,".config");return[t(w().dataDir,"claude-plugin","skills"),t(e,".codex","skills"),t(e,".gemini","skills"),t(e,".qwen","skills"),t(e,".pi","agent","skills"),t(e,".codewhale","skills"),t(i,"opencode","skills"),t(e,".cursor","skills"),t(e,".openhuman","skills"),t(e,".kiro","skills"),t(e,".reasonix","skills"),t(C(),"skills")]}function O(){const e=[];for(const i of L()){let r;try{r=c(i,{withFileTypes:!0,encoding:"utf8"})}catch{continue}for(const n of r){if(!n.isDirectory())continue;const s=t(i,n.name);if(a(t(s,f)))try{g(s,{recursive:!0,force:!0}),e.push(s)}catch{}}}return e.length>0&&u.info("default-skills",`Cleaned ${e.length} projected skill dir(s)`),e}function b(){const e=d();if(e.length===0){u.warn("default-skills","No connector system skills found \u2014 dist/default-skills/ may be missing SKILL.md files");return}u.info("default-skills",`Connector system skills available: [${e.map(i=>i.name).join(", ")}]`)}export{T as buildReportedSkills,O as cleanupProjectedSkills,b as logDefaultSkillsCheck,C as resolveKimiCodeHome,d as scanDefaultSkills,j as syncDefaultSkillsToDir};
1
+ import{readFileSync as p,readdirSync as c,existsSync as a,mkdirSync as k,cpSync as y,writeFileSync as h,rmSync as g}from"node:fs";import{join as t,dirname as S}from"node:path";import{homedir as m}from"node:os";import{fileURLToPath as D}from"node:url";import{parseSkillFrontmatter as v,scanSkills as x,dedupeSkills as F}from"../adapter/claude/skill-scanner.js";import{resolveRuntimePaths as w}from"../core/config/index.js";import{log as u}from"../core/log/index.js";const l=S(D(import.meta.url)),f=".grix-managed";function d(){const e=[];let i;try{i=c(l,{withFileTypes:!0,encoding:"utf8"})}catch{return e}for(const r of i){if(!r.isDirectory())continue;const n=t(l,r.name,"SKILL.md");try{const s=p(n,"utf-8"),o=v(s);o?.name&&e.push({name:o.name,description:o.description,trigger:o.trigger,source:"connector",managed:!0})}catch{}}return e}function T(e){let i=[];try{i=x(e)}catch{i=[]}return F([...i,...d()])}function j(e){const i=[];let r;try{r=c(l,{withFileTypes:!0,encoding:"utf8"})}catch{return i}for(const n of r){if(!n.isDirectory())continue;const s=t(l,n.name);if(a(t(s,"SKILL.md")))try{k(e,{recursive:!0});const o=t(e,n.name);y(s,o,{recursive:!0}),h(t(o,f),"","utf8"),i.push(n.name)}catch{}}return i}function C(){return(process.env.KIMI_CODE_HOME||"").trim()||t(m(),".kimi-code")}function L(){const e=m(),i=process.env.XDG_CONFIG_HOME||t(e,".config");return[t(w().dataDir,"claude-plugin","skills"),t(e,".codex","skills"),t(e,".gemini","skills"),t(e,".qwen","skills"),t(e,".pi","agent","skills"),t(e,".codewhale","skills"),t(i,"opencode","skills"),t(e,".cursor","skills"),t(e,".openhuman","skills"),t(e,".kiro","skills"),t(e,".reasonix","skills"),t(C(),"skills")]}function O(){const e=[];for(const i of L()){let r;try{r=c(i,{withFileTypes:!0,encoding:"utf8"})}catch{continue}for(const n of r){if(!n.isDirectory())continue;const s=t(i,n.name);if(a(t(s,f)))try{g(s,{recursive:!0,force:!0}),e.push(s)}catch{}}}return e.length>0&&u.info("default-skills",`Cleaned ${e.length} projected skill dir(s)`),e}function b(){const e=d();if(e.length===0){u.warn("default-skills","No connector system skills found \u2014 dist/default-skills/ may be missing SKILL.md files");return}u.info("default-skills",`Connector system skills available: [${e.map(i=>i.name).join(", ")}]`)}export{T as buildReportedSkills,O as cleanupProjectedSkills,b as logDefaultSkillsCheck,C as resolveKimiCodeHome,d as scanDefaultSkills,j as syncDefaultSkillsToDir};
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};
package/dist/manager.js CHANGED
@@ -1,2 +1,2 @@
1
- import{readFileSync as W,readdirSync as K,writeFileSync as G}from"node:fs";import{join as A}from"node:path";import{AgentInstance as I}from"./bridge/bridge.js";import{buildSharedInstanceConfig as z,diffSharedOwners as J,sharedInstanceKey as V,SharedOwnersCache as X}from"./manager-share-config.js";import{isAgentDeletedError as j}from"./core/aibot/errors.js";import{GRIX_PATHS as w,log as l}from"./core/log/index.js";import{resolveClientVersion as Y}from"./core/util/client-version.js";import{UpgradeChecker as Z}from"./core/upgrade/upgrade-checker.js";import{SkillSyncer as ee}from"./core/skill-sync/skill-syncer.js";import{AgentGlobalConfigStore as te}from"./core/persistence/agent-global-config-store.js";import{resolveSkillScanMode as ne}from"./adapter/claude/skill-scanner.js";import{buildReportedSkills as ae,logDefaultSkillsCheck as re,cleanupProjectedSkills as D}from"./default-skills/index.js";import{supportsDirectProviderConfig as se}from"./core/config/provider-env.js";import{resolveCopilotCommand as P}from"./core/runtime/copilot-resolve.js";import{resolveCursorCommand as O}from"./core/runtime/cursor-resolve.js";import{getCliVersion as oe,resolveCliPath as ie}from"./core/util/cli-probe.js";import{AgentInstaller as ce}from"./core/installer/installer.js";import{reportInstallFailure as le}from"./core/observability/sentry.js";const de=8e3;function pe(){const n=P();return[{clientType:"openclaw",command:"openclaw"},{clientType:"claude",command:"claude"},{clientType:"codex",command:"codex"},{clientType:"qwen",command:"qwen"},{clientType:"hermes",command:"hermes"},{clientType:"reasonix",command:"reasonix"},{clientType:"codewhale",command:"codewhale"},{clientType:"opencode",command:"opencode"},{clientType:"cursor",command:O()},{clientType:"pi",command:"pi"},{clientType:"openhuman",command:"openhuman-core"},{clientType:"kiro",command:"kiro-cli"},{clientType:"kimi",command:"kimi"},{clientType:"copilot",command:n.command},{clientType:"agy",command:"agy"}]}async function me(){return Promise.all(pe().map(async n=>{const e=await ie(n.command);if(!e)return{client_type:n.clientType,command:n.command,installed:!1,path:null,version:null};const t=await oe(e,n.versionArgs??["--version"]);return{client_type:n.clientType,command:n.command,installed:!0,path:e,version:t.version,error:t.error}}))}function ue(n){switch(n){case"claude":return{adapterType:"claude",command:"claude"};case"codex":return{adapterType:"codex",command:"codex",options:{sandboxMode:"danger-full-access"}};case"gemini":return{adapterType:"acp",command:"gemini",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"qwen":return{adapterType:"acp",command:"qwen",adapterHint:"qwen/base",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"pi":return{adapterType:"pi",command:"pi"};case"cursor":return{adapterType:"cursor",command:O()};case"reasonix":return{adapterType:"acp",command:"reasonix",args:["acp"],enableSessionBinding:!0};case"codewhale":return{adapterType:"codewhale",command:"codewhale",enableSessionBinding:!0};case"openhuman":return{adapterType:"openhuman",command:"openhuman-core",enableSessionBinding:!0};case"kiro":return{adapterType:"acp",command:"kiro-cli",args:["acp"],enableSessionBinding:!0};case"kimi":return{adapterType:"acp",command:"kimi",args:["acp"],options:{initial_mode:"yolo"},enableSessionBinding:!0};case"opencode":return{adapterType:"opencode",command:"opencode",args:["serve"],enableSessionBinding:!0};case"copilot":{const e=P();return{adapterType:"acp",command:e.command,args:[...e.prefixArgs,"--acp"],enableSessionBinding:!0}}case"agy":return{adapterType:"agy",command:"agy",enableSessionBinding:!0};case"hermes":return{adapterType:"acp",command:"hermes",args:["acp"],enableSessionBinding:!0};default:throw new Error(`Unsupported client_type: ${n}`)}}function H(n,e){return String(n??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||String(e??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"default"}function ge(n,e){return A(w.data,`session-bindings-${H(n,e)}.json`)}function he(n,e){return A(w.data,`active-events-${H(n,e)}.json`)}function fe(...n){const e=[],t=new Set;for(const r of n)for(const s of r??[]){const i=String(s??"").trim(),o=i.toLowerCase();!i||t.has(o)||(t.add(o),e.push(i))}return e.length>0?e:void 0}function _e(n,e){const t={claude:{maxConcurrent:1,maxQueued:5,queueTimeoutMs:0},codex:{maxConcurrent:1,maxQueued:5,queueTimeoutMs:0},cursor:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},acp:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},pi:{maxConcurrent:1,maxQueued:5,queueTimeoutMs:0},codewhale:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},openhuman:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},opencode:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},agy:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0}},r=t[n]??t.acp;return{maxConcurrent:e?.max_concurrent??r.maxConcurrent??1,maxQueued:e?.max_queued??r.maxQueued??3,queueTimeoutMs:e?.queue_timeout_ms??r.queueTimeoutMs??0,cancelableQueued:!0,cancelableRunning:!0}}function b(n,e={}){const t=Y(),r=String(n.client_type??"").trim().toLowerCase(),s=ue(r),i=String(n.ws_url??"").trim(),o="get_session_usage",p="get_rate_limits",c="get_agent_global_config";if(!n.name?.trim())throw new Error("agent name is required");if(!i)throw new Error(`agent ${n.name}: ws_url is required`);if(!n.agent_id?.trim())throw new Error(`agent ${n.name}: agent_id is required`);if(!n.api_key?.trim())throw new Error(`agent ${n.name}: api_key is required`);const a=s.adapterType,g=a==="acp",m=r==="qwen",_={...s.options??{}},S=a==="codex"?{capabilities:["local_action_v1","agent_invoke"],localActions:["session_control","get_context","set_model","set_mode","set_reasoning_effort","set_service_tier","set_sandbox_mode","exec_approve","exec_reject","file_list","create_folder","turn_interrupt","permission_approve","permission_reject","thread_compact",o,p]}:null,d=a==="claude"?{localActions:["session_control","set_mode","set_model","claude_interaction_reply","exec_approve","exec_reject","file_list","create_folder","thread_compact",o,p]}:null,f=m?{capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",o],adapterHint:"qwen/base"}:null,h=a==="pi"?{adapterHint:"pi/base",capabilities:["local_action_v1"],localActions:["session_control","set_model","get_context","file_list","create_folder",o]}:null,u=a==="openhuman"?{adapterHint:"openhuman/base",capabilities:["local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",o]}:null,y=a==="cursor"?{adapterHint:"cursor/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","set_mode","get_context","file_list","create_folder",o,p]}:null,v=a==="codewhale"?{capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",o]}:null,C=a==="opencode"?{adapterHint:"opencode/base",capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",o]}:null,$=a==="agy"?{adapterHint:"agy/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",o]}:null,N=g&&!m?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",o]}:null,R=r==="kiro"?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder","thread_compact",o,p]}:null,B=a==="codex"||a==="claude"||r==="gemini"?["session_control","set_model","set_mode"]:void 0,F=[o,p];g&&_.raw_transport===void 0&&(_.raw_transport=r==="gemini");const U=`${r}/base`,E=ne(a,r),L=E==="kiro"?void 0:process.cwd(),x=ae({mode:E,projectDir:L}),M=x.filter(T=>T.source==="connector").map(T=>T.name);M.length>0&&!e.quiet&&l.info("manager",`[${n.name}] injecting connector skills: [${M.join(", ")}]`);let Q=x.length>0?x:void 0;return{name:n.name,adapterType:a,aibot:{url:i,agentId:n.agent_id,apiKey:n.api_key,clientType:r,clientVersion:t,adapterHint:s.adapterHint??f?.adapterHint??h?.adapterHint??u?.adapterHint??y?.adapterHint??C?.adapterHint??$?.adapterHint??U,capabilities:S?.capabilities??v?.capabilities??h?.capabilities??u?.capabilities??y?.capabilities??C?.capabilities??$?.capabilities??f?.capabilities??["stream_chunk","local_action_v1","connector_upgrade"],localActions:fe(S?.localActions??v?.localActions??d?.localActions??h?.localActions??u?.localActions??y?.localActions??C?.localActions??$?.localActions??f?.localActions??R?.localActions??N?.localActions??["exec_approve","exec_reject"],B,F,["connector_rollback","connector_upgrade_push",c,"configure_gateway_provider"]),skills:Q},agent:{command:s.command,args:[...s.args??[],...n.args??[]],env:n.env,clientType:r,...n.provider?{provider:{...n.provider.base_url?.trim()?{baseUrl:n.provider.base_url.trim()}:{},...n.provider.api_key?.trim()?{apiKey:n.provider.api_key.trim()}:{},...n.provider.model?.trim()?{model:n.provider.model.trim()}:{}}}:{}},adapterOptions:_,acpAuthMethod:_.auth_method,acpInitialMode:_.initial_mode,acpMcpTools:_.acp_mcp_tools,promptTimeoutMs:n.prompt_timeout_ms,bindingsPath:ge(n.name,n.agent_id),activeEventStorePath:he(n.name,n.agent_id),...s.enableSessionBinding||g?{enableSessionBinding:!0}:{},...s.autoInjectArgs||r==="reasonix"&&n.provider?.model?.trim()?{autoInjectArgs:{...s.autoInjectArgs??{},...r==="reasonix"&&n.provider?.model?.trim()?{model:n.provider.model.trim()}:{}}}:{},poolMaxSize:n.pool?.maxSize,poolIdleTimeoutMs:n.pool?.idleTimeoutMs,eventQueue:_e(a,n.event_queue),logDir:w.log,providerBaseUrl:n.provider_base_url?.trim()||void 0,providerApiKey:n.provider_api_key?.trim()||void 0}}function ye(){const n=process.env.GRIX_AGENT_STARTUP_WAIT_MS,e=Number(n);return Number.isFinite(e)&&e>=500?Math.floor(e):de}function q(n){const e=[],t=[],r=[],s=K(n).filter(i=>i.endsWith(".json")).sort();for(const i of s)try{const o=JSON.parse(W(A(n,i),"utf-8"));if(o===null||typeof o!="object"||Array.isArray(o)||!("agents"in o)){r.push(i);continue}if(!Array.isArray(o.agents)){t.push({file:i,error:"agents is not an array"});continue}if(o.agents.length===0){t.push({file:i,error:"agents array is empty"});continue}for(const p of o.agents)e.push({entry:p,file:i})}catch(o){t.push({file:i,error:o instanceof Error?o.message:String(o)})}return{entries:e,fileErrors:t,skipped:r}}function k(n){if(n===null||typeof n!="object")return JSON.stringify(n)??"null";if(Array.isArray(n))return`[${n.map(k).join(",")}]`;const e=n;return`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${k(e[r])}`).join(",")}}`}function we(n,e){return k(n)===k(e)}class Be{instances=[];configMap=new Map;rawConfigMap=new Map;reloadChain=Promise.resolve();sharedInstances=new Map;shareSyncChains=new Map;stopping=!1;deletedAgentCleanups=new Set;upgradeChecker=null;skillSyncer=null;globalConfigStore;configDir=w.config;sharedOwnersCache=new X(w.data);installer=new ce;async start(e){const t=e??w.config;this.configDir=t,l.info("manager",`Loading configs from ${t}`),re(),D(),this.globalConfigStore=new te(A(w.data,"agent-global-configs.json")),this.globalConfigStore.load();const{entries:r,fileErrors:s,skipped:i}=q(t);for(const a of s)l.error("manager",`Failed to load ${a.file}: ${a.error}`);for(const a of i)l.info("manager",`Skipped ${a}: not an agent config (no "agents" key)`);if(r.length===0&&s.length===0&&i.length===0)throw new Error(`No config files found in ${t}`);const o=[];let p=s.length;for(const{entry:a,file:g}of r)try{const m=b(a);o.push({config:m,entry:a,file:g}),l.info("manager",`Loaded ${m.name} (${m.adapterType??"acp"}) from ${g}`)}catch(m){const _=typeof a?.name=="string"?a.name:"<unknown>";l.error("manager",`Invalid agent config in ${g} (name=${_}): ${m}`),p++}let c=0;if(o.length>0){const a=ye();l.info("manager",`Starting ${o.length} agent(s), startup wait=${a}ms`);const g=()=>this.upgradeChecker?.triggerCheck(),m=d=>{this.instances=this.instances.filter(f=>f!==d)},_=o.map(({config:d,entry:f,file:h})=>{const u=new I(d,this.globalConfigStore);return u.setUpgradeTrigger(g),u.setShareSetHandler(y=>this.onShareSet(d,y)),u.setAgentDeletedHandler(()=>this.onAgentDeletedByPlatform(d.name)),u.setSkillSyncHandler(()=>this.skillSyncer?.triggerSync()),this.instances.push(u),this.configMap.set(d.name,d),this.rawConfigMap.set(d.name,{entry:f,file:h}),{config:d,instance:u,startPromise:u.start()}}),S=await Promise.all(_.map(async d=>{const f=await new Promise(h=>{let u=!1;const y=setTimeout(()=>{u||(u=!0,h({kind:"timeout"}))},a);d.startPromise.then(()=>{u||(u=!0,clearTimeout(y),h({kind:"started"}))}).catch(v=>{u||(u=!0,clearTimeout(y),h({kind:"failed",error:v}))})});return{task:d,outcome:f}}));for(const{task:d,outcome:f}of S){if(f.kind==="started"){this.restoreCachedSharedInstances(d.config);continue}if(f.kind==="failed"){if(j(f.error)){this.onAgentDeletedByPlatform(d.config.name);continue}m(d.instance),l.error("manager",`Failed to start ${d.config.name}: ${f.error}`);continue}c++,l.warn("manager",`Startup pending for ${d.config.name}, continue retrying in background`),d.startPromise.then(()=>{l.info("manager",`Delayed start succeeded: ${d.config.name}`),this.restoreCachedSharedInstances(d.config)}).catch(h=>{if(j(h)){this.onAgentDeletedByPlatform(d.config.name);return}m(d.instance),l.error("manager",`Delayed start failed: ${d.config.name}: ${h}`)})}if(this.instances.length>0){const d=Math.max(0,this.instances.length-c);l.info("manager",`${d}/${o.length} agent(s) running now`)}c>0&&l.warn("manager",`${c} agent(s) still connecting in background`)}if(this.instances.length===0&&o.length>0)throw new Error("All agent configurations failed to start");o.length>0&&(this.upgradeChecker=new Z(o.map(({config:a})=>({apiKey:a.aibot.apiKey,wsUrl:a.aibot.url})),()=>this.instances.some(a=>a.hasPendingOrBackgroundWork())||[...this.sharedInstances.values()].some(a=>a.hasPendingOrBackgroundWork())),await this.upgradeChecker.start()),o.length>0&&(this.skillSyncer=new ee(o.map(({config:a})=>({apiKey:a.aibot.apiKey,wsUrl:a.aibot.url})),w.skills),await this.skillSyncer.start())}async stop(){l.info("manager","Stopping all agents..."),this.stopping=!0,this.upgradeChecker?.stop(),this.skillSyncer?.stop(),await Promise.allSettled([...this.shareSyncChains.values()]),this.shareSyncChains.clear();const e=[...this.sharedInstances.values()];this.sharedInstances.clear(),await Promise.allSettled([...this.instances.map(t=>t.stop()),...e.map(t=>t.stop())]),await this.globalConfigStore?.flush(),this.instances=[],D(),l.info("manager","All stopped")}onShareSet(e,t){this.sharedOwnersCache.save(e.name,t);const s=(this.shareSyncChains.get(e.name)??Promise.resolve()).catch(()=>{}).then(()=>this.syncSharedInstances(e,t));this.shareSyncChains.set(e.name,s)}async syncSharedInstances(e,t){if(this.stopping)return;const{toAdd:r,toRemove:s}=J(e.name,this.sharedInstances.keys(),t);for(const i of r){if(this.stopping)break;const o=V(e.name,i);try{const p=z(e,i),c=new I(p,this.globalConfigStore);this.sharedInstances.set(o,c),await c.start(),l.info("manager",`shared instance started: ${o}`)}catch(p){this.sharedInstances.delete(o);const c=p instanceof Error?p.message:String(p);/Auth failed/i.test(c)?(this.sharedOwnersCache.remove(e.name,i),l.warn("manager",`shared instance auth rejected, removed from cache: ${o}`)):l.error("manager",`start shared instance failed ${o}: ${p}`)}}for(const{key:i}of s){const o=this.sharedInstances.get(i);o&&(this.sharedInstances.delete(i),o.stop().catch(p=>l.error("manager",`stop shared instance failed ${i}: ${p}`)),l.info("manager",`shared instance stopped: ${i}`))}}restoreCachedSharedInstances(e){const t=this.sharedOwnersCache.load(e.name);t.length!==0&&(l.info("manager",`restoring ${t.length} cached shared instance(s) for ${e.name}`),this.onShareSet(e,t))}getAgentsStatus(){return this.instances.map(e=>e.getStatus())}async addAgent(e){await this.addAgentInternal(e,"agents.json"),this.persistAgentsConfig(),l.info("manager",`Added agent: ${e.name}`)}async addAgentInternal(e,t){const r=b(e);if(this.instances.some(s=>s.name===r.name))throw new Error(`Agent "${r.name}" already exists`);await this.startInstanceFromConfig(r,e,t)}async startInstanceFromConfig(e,t,r){const s=new I(e,this.globalConfigStore);s.setUpgradeTrigger(()=>this.upgradeChecker?.triggerCheck()),s.setShareSetHandler(i=>this.onShareSet(e,i)),s.setAgentDeletedHandler(()=>this.onAgentDeletedByPlatform(e.name)),s.setSkillSyncHandler(()=>this.skillSyncer?.triggerSync()),s.setProviderConfigHandler(i=>this.setAgentProvider(e.name,i)),s.setRelayEnvSettledHandler(()=>this.relayEnvSettledHandler?.()),await s.start(),this.instances.push(s),this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:t,file:r}),this.relayEnvSettledHandler?.()}async removeAgent(e){if(!this.instances.some(t=>t.name===e))throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});await this.removeAgentInternal(e),this.persistAgentsConfig(),l.info("manager",`Removed agent: ${e}`),this.relayEnvSettledHandler?.()}async removeAgentInternal(e,t){const r=this.instances.findIndex(p=>p.name===e),s=r===-1?void 0:this.instances[r];r!==-1&&this.instances.splice(r,1),this.configMap.delete(e),this.rawConfigMap.delete(e);const i=this.shareSyncChains.get(e);this.shareSyncChains.delete(e),i&&await i.catch(()=>{});const o=`${e}#shared:`;for(const[p,c]of[...this.sharedInstances.entries()])p.startsWith(o)&&(this.sharedInstances.delete(p),c.stop().catch(a=>l.error("manager",`stop shared instance failed ${p}: ${a}`)));t?.keepShareCache||this.sharedOwnersCache.delete(e),s&&await s.stop()}onAgentDeletedByPlatform(e){this.stopping||this.deletedAgentCleanups.has(e)||(this.deletedAgentCleanups.add(e),(async()=>{try{if(!(this.rawConfigMap.has(e)||this.instances.some(r=>r.name===e)))return;l.warn("manager",`Agent "${e}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u505C\u6B62\u5B9E\u4F8B\u5E76\u6E05\u7406\u672C\u5730\u914D\u7F6E`),await this.removeAgentInternal(e),this.persistAgentsConfig(),l.info("manager",`Agent "${e}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u672C\u5730\u914D\u7F6E\u5DF2\u6E05\u7406\uFF08agents.json \u5DF2\u79FB\u9664\u8BE5\u6761\u76EE\uFF09`)}catch(t){l.error("manager",`cleanup for deleted agent "${e}" failed: ${t}`)}finally{this.deletedAgentCleanups.delete(e)}})())}persistAgentsConfig(){const e=A(this.configDir,"agents.json");try{const t=[];for(const[,s]of this.configMap){const i=this.rawConfigMap.get(s.name)?.entry.provider;t.push({name:s.name,ws_url:s.aibot.url,agent_id:s.aibot.agentId,api_key:s.aibot.apiKey,client_type:s.aibot.clientType,...i?{provider:i}:{}})}G(e,JSON.stringify({agents:t},null,4)+`
2
- `,"utf-8")}catch(t){l.error("manager",`Failed to persist agents config: ${t}`)}}isAgentBusy(e){return this.instances.find(r=>r.name===e)?.hasPendingWork()??!1}getAgentsWithStaleRelayEnv(){return this.instances.filter(e=>e.hasStaleRelayEnv()).map(e=>e.name)}markAgentRelayEnvStale(e){const t=this.instances.find(r=>r.name===e);return t?(t.markRelayEnvStale(),!0):!1}relayEnvSettledHandler;setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}async restartAgent(e){const t=this.rawConfigMap.get(e);if(!t)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});await this.replaceInstance(e,t.entry,t.file),l.info("manager",`Restarted agent: ${e}`)}async setAgentProvider(e,t){const r=this.rawConfigMap.get(e);if(!r)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});const s={...r.entry,provider:t};await this.replaceInstance(e,s,r.file),this.persistAgentsConfig(),l.info("manager",`Updated provider config for agent: ${e}`)}async clearDirectProviderConfigs(){const e=[...this.rawConfigMap.entries()].filter(([,r])=>!!r.entry.provider&&se(r.entry.client_type)).map(([r])=>r),t=[];for(const r of e)try{await this.setAgentProvider(r,void 0),t.push(r)}catch(s){l.warn("manager",`Failed to clear provider config for "${r}": ${s instanceof Error?s.message:String(s)}`)}return t}async replaceInstance(e,t,r){const s=b(t);await this.removeAgentInternal(e,{keepShareCache:!0}),await this.startInstanceFromConfig(s,t,r),this.restoreCachedSharedInstances(s)}async reload(){const e=this.reloadChain.catch(()=>{}).then(()=>this.doReload());return this.reloadChain=e.catch(()=>{}),e}async doReload(){if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"RELOAD_UNSAFE"});const{entries:e,fileErrors:t,skipped:r}=q(this.configDir);for(const c of r)l.info("manager",`reload: skipped ${c}: not an agent config (no "agents" key)`);if(t.length>0){const c=t.map(a=>`${a.file}: ${a.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${t.length} config file(s) failed to parse [${c}]`),{code:"RELOAD_UNSAFE"})}if(e.length===0)throw Object.assign(new Error("reload aborted: no valid agent config found"),{code:"RELOAD_UNSAFE"});const s=[];for(const{entry:c}of e)try{b(c,{quiet:!0})}catch(a){const g=c?.name,m=typeof g=="string"&&g.trim()?g:"<unknown>";s.push({name:m,error:a instanceof Error?a.message:String(a)})}if(s.length>0){const c=s.map(a=>`${a.name}: ${a.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${s.length} agent config(s) invalid [${c}]`),{code:"RELOAD_UNSAFE"})}const i=new Map;for(const c of e){const a=String(c.entry?.name??"").trim();a&&(i.has(a)&&l.warn("manager",`reload: duplicate agent name "${a}", last one wins`),i.set(a,c))}const o={added:[],removed:[],restarted:[],unchanged:[],failed:[]},p=new Set(this.rawConfigMap.keys());for(const c of p)if(!i.has(c))try{await this.removeAgentInternal(c),o.removed.push(c)}catch(a){o.failed.push({name:c,error:a instanceof Error?a.message:String(a)})}for(const[c,a]of i){const g=this.rawConfigMap.get(c);if(g)if(we(g.entry,a.entry))this.rawConfigMap.set(c,a),o.unchanged.push(c);else try{await this.replaceInstance(c,a.entry,a.file),o.restarted.push(c)}catch(m){o.failed.push({name:c,error:m instanceof Error?m.message:String(m)})}else try{await this.addAgentInternal(a.entry,a.file),o.added.push(c)}catch(m){o.failed.push({name:c,error:m instanceof Error?m.message:String(m)})}}return l.info("manager",`reload done: +${o.added.length} -${o.removed.length} ~${o.restarted.length} =${o.unchanged.length} !${o.failed.length}`),o}async checkUpgrade(){return this.upgradeChecker?this.upgradeChecker.checkForUpdate():{available:!1}}triggerUpgrade(){this.upgradeChecker?.triggerCheck()}async probeAll(e={}){return Se(this.instances,e)}async probeOne(e,t={}){return Ae(this.instances,e,t)}listInstallable(){return this.installer.listInstallable()}async installAgent(e){const t=await this.installer.install(e);return le(t),t}getInstallProgress(e){return this.installer.getProgress(e)??null}}async function Se(n,e){const t=e.concurrency??4,r=Date.now(),s=new Array(n.length);await new Promise(a=>{let g=0,m=0;const _=n.length;if(_===0){a();return}function S(h){const u=n[h];u.probe(e).then(y=>{s[h]=y,d()},y=>{s[h]={agent_name:u.name,client_type:"unknown",adapter_type:"acp",ok:!1,status:"error",probed_at:Date.now(),duration_ms:0,cached:!1,cli:{command:"",installed:!1,path:null,version:null,error:{code:"internal",message:y?.message??String(y)}},conversation:{attempted:!1,ok:!1,latency_ms:null},config:{model:null,base_url:null,source:{model:"unknown",base_url:"unknown"}},process:{started:!1,alive:!1,busy:!1}},d()})}function d(){m++,g<_?S(g++):m===_&&a()}const f=Math.min(t,_);for(let h=0;h<f;h++)S(g++)});const i=s.filter(a=>a.status==="healthy").length,o=s.filter(a=>a.status==="degraded").length,p=s.filter(a=>a.status==="unavailable").length,c=await me();return{ok:i===s.length&&s.length>0,total:s.length,healthy:i,degraded:o,unavailable:p,installed_clients:c,agents:s,probed_at:r,duration_ms:Date.now()-r}}async function Ae(n,e,t){const r=n.find(s=>s.name===e);if(!r)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return r.probe(t)}export{Be as Manager,me as probeInstalledClientCommands,Se as probeInstances,Ae as probeOneInstance};
1
+ import{readFileSync as K,readdirSync as G,writeFileSync as z}from"node:fs";import{join as A}from"node:path";import{AgentInstance as T}from"./bridge/bridge.js";import{buildSharedInstanceConfig as J,diffSharedOwners as V,sharedInstanceKey as X,SharedOwnersCache as Y}from"./manager-share-config.js";import{isAgentDeletedError as D}from"./core/aibot/errors.js";import{GRIX_PATHS as w,log as l}from"./core/log/index.js";import{resolveClientVersion as Z}from"./core/util/client-version.js";import{UpgradeChecker as ee}from"./core/upgrade/upgrade-checker.js";import{SkillSyncer as te}from"./core/skill-sync/skill-syncer.js";import{AgentGlobalConfigStore as ne}from"./core/persistence/agent-global-config-store.js";import{resolveSkillScanMode as ae}from"./adapter/claude/skill-scanner.js";import{buildWireSkills as re}from"./core/skill-sync/sync-state.js";import{buildReportedSkills as se,logDefaultSkillsCheck as oe,cleanupProjectedSkills as P}from"./default-skills/index.js";import{supportsDirectProviderConfig as ie}from"./core/config/provider-env.js";import{resolveCopilotCommand as O}from"./core/runtime/copilot-resolve.js";import{resolveCursorCommand as H}from"./core/runtime/cursor-resolve.js";import{getCliVersion as ce,resolveCliPath as le}from"./core/util/cli-probe.js";import{AgentInstaller as de}from"./core/installer/installer.js";import{reportInstallFailure as pe}from"./core/observability/sentry.js";const me=8e3;function ue(){const n=O();return[{clientType:"openclaw",command:"openclaw"},{clientType:"claude",command:"claude"},{clientType:"codex",command:"codex"},{clientType:"qwen",command:"qwen"},{clientType:"hermes",command:"hermes"},{clientType:"reasonix",command:"reasonix"},{clientType:"codewhale",command:"codewhale"},{clientType:"opencode",command:"opencode"},{clientType:"cursor",command:H()},{clientType:"pi",command:"pi"},{clientType:"openhuman",command:"openhuman-core"},{clientType:"kiro",command:"kiro-cli"},{clientType:"kimi",command:"kimi"},{clientType:"copilot",command:n.command},{clientType:"agy",command:"agy"}]}async function ge(){return Promise.all(ue().map(async n=>{const e=await le(n.command);if(!e)return{client_type:n.clientType,command:n.command,installed:!1,path:null,version:null};const t=await ce(e,n.versionArgs??["--version"]);return{client_type:n.clientType,command:n.command,installed:!0,path:e,version:t.version,error:t.error}}))}function he(n){switch(n){case"claude":return{adapterType:"claude",command:"claude"};case"codex":return{adapterType:"codex",command:"codex",options:{sandboxMode:"danger-full-access"}};case"gemini":return{adapterType:"acp",command:"gemini",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"qwen":return{adapterType:"acp",command:"qwen",adapterHint:"qwen/base",autoInjectArgs:{acp:!0},enableSessionBinding:!0};case"pi":return{adapterType:"pi",command:"pi"};case"cursor":return{adapterType:"cursor",command:H()};case"reasonix":return{adapterType:"acp",command:"reasonix",args:["acp"],enableSessionBinding:!0};case"codewhale":return{adapterType:"codewhale",command:"codewhale",enableSessionBinding:!0};case"openhuman":return{adapterType:"openhuman",command:"openhuman-core",enableSessionBinding:!0};case"kiro":return{adapterType:"acp",command:"kiro-cli",args:["acp"],enableSessionBinding:!0};case"kimi":return{adapterType:"acp",command:"kimi",args:["acp"],options:{initial_mode:"yolo"},enableSessionBinding:!0};case"opencode":return{adapterType:"opencode",command:"opencode",args:["serve"],enableSessionBinding:!0};case"copilot":{const e=O();return{adapterType:"acp",command:e.command,args:[...e.prefixArgs,"--acp"],enableSessionBinding:!0}}case"agy":return{adapterType:"agy",command:"agy",enableSessionBinding:!0};case"hermes":return{adapterType:"acp",command:"hermes",args:["acp"],enableSessionBinding:!0};default:throw new Error(`Unsupported client_type: ${n}`)}}function q(n,e){return String(n??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||String(e??"").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"default"}function fe(n,e){return A(w.data,`session-bindings-${q(n,e)}.json`)}function _e(n,e){return A(w.data,`active-events-${q(n,e)}.json`)}function ye(...n){const e=[],t=new Set;for(const r of n)for(const s of r??[]){const i=String(s??"").trim(),o=i.toLowerCase();!i||t.has(o)||(t.add(o),e.push(i))}return e.length>0?e:void 0}function we(n,e){const t={claude:{maxConcurrent:1,maxQueued:5,queueTimeoutMs:0},codex:{maxConcurrent:1,maxQueued:5,queueTimeoutMs:0},cursor:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},acp:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},pi:{maxConcurrent:1,maxQueued:5,queueTimeoutMs:0},codewhale:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},openhuman:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},opencode:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0},agy:{maxConcurrent:1,maxQueued:3,queueTimeoutMs:0}},r=t[n]??t.acp;return{maxConcurrent:e?.max_concurrent??r.maxConcurrent??1,maxQueued:e?.max_queued??r.maxQueued??3,queueTimeoutMs:e?.queue_timeout_ms??r.queueTimeoutMs??0,cancelableQueued:!0,cancelableRunning:!0}}function b(n,e={}){const t=Z(),r=String(n.client_type??"").trim().toLowerCase(),s=he(r),i=String(n.ws_url??"").trim(),o="get_session_usage",p="get_rate_limits",c="get_agent_global_config";if(!n.name?.trim())throw new Error("agent name is required");if(!i)throw new Error(`agent ${n.name}: ws_url is required`);if(!n.agent_id?.trim())throw new Error(`agent ${n.name}: agent_id is required`);if(!n.api_key?.trim())throw new Error(`agent ${n.name}: api_key is required`);const a=s.adapterType,g=a==="acp",m=r==="qwen",_={...s.options??{}},S=a==="codex"?{capabilities:["local_action_v1","agent_invoke"],localActions:["session_control","get_context","set_model","set_mode","set_reasoning_effort","set_service_tier","set_sandbox_mode","exec_approve","exec_reject","file_list","create_folder","turn_interrupt","permission_approve","permission_reject","thread_compact",o,p]}:null,d=a==="claude"?{localActions:["session_control","set_mode","set_model","claude_interaction_reply","exec_approve","exec_reject","file_list","create_folder","thread_compact",o,p]}:null,f=m?{capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",o],adapterHint:"qwen/base"}:null,h=a==="pi"?{adapterHint:"pi/base",capabilities:["local_action_v1"],localActions:["session_control","set_model","get_context","file_list","create_folder",o]}:null,u=a==="openhuman"?{adapterHint:"openhuman/base",capabilities:["local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",o]}:null,y=a==="cursor"?{adapterHint:"cursor/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","set_mode","get_context","file_list","create_folder",o,p]}:null,v=a==="codewhale"?{capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",o]}:null,C=a==="opencode"?{adapterHint:"opencode/base",capabilities:["stream_chunk","local_action_v1"],localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",o]}:null,$=a==="agy"?{adapterHint:"agy/base",capabilities:["stream_chunk","local_action_v1"],localActions:["session_control","set_model","file_list","create_folder",o]}:null,R=g&&!m?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder",o]}:null,B=r==="kiro"?{localActions:["exec_approve","exec_reject","permission_approve","permission_reject","session_control","set_model","set_mode","file_list","create_folder","thread_compact",o,p]}:null,F=a==="codex"||a==="claude"||r==="gemini"?["session_control","set_model","set_mode"]:void 0,U=[o,p];g&&_.raw_transport===void 0&&(_.raw_transport=r==="gemini");const L=`${r}/base`,I=ae(a,r),Q=I==="kiro"?void 0:process.cwd(),E=se({mode:I,projectDir:Q}),M=E.filter(x=>x.source==="connector").map(x=>x.name);M.length>0&&!e.quiet&&l.info("manager",`[${n.name}] injecting connector skills: [${M.join(", ")}]`);const j=re(E,w.skills);let W=j.length>0?j:void 0;return{name:n.name,adapterType:a,aibot:{url:i,agentId:n.agent_id,apiKey:n.api_key,clientType:r,clientVersion:t,adapterHint:s.adapterHint??f?.adapterHint??h?.adapterHint??u?.adapterHint??y?.adapterHint??C?.adapterHint??$?.adapterHint??L,capabilities:S?.capabilities??v?.capabilities??h?.capabilities??u?.capabilities??y?.capabilities??C?.capabilities??$?.capabilities??f?.capabilities??["stream_chunk","local_action_v1","connector_upgrade"],localActions:ye(S?.localActions??v?.localActions??d?.localActions??h?.localActions??u?.localActions??y?.localActions??C?.localActions??$?.localActions??f?.localActions??B?.localActions??R?.localActions??["exec_approve","exec_reject"],F,U,["connector_rollback","connector_upgrade_push",c,"configure_gateway_provider","skill_upload"]),skills:W},agent:{command:s.command,args:[...s.args??[],...n.args??[]],env:n.env,clientType:r,...n.provider?{provider:{...n.provider.base_url?.trim()?{baseUrl:n.provider.base_url.trim()}:{},...n.provider.api_key?.trim()?{apiKey:n.provider.api_key.trim()}:{},...n.provider.model?.trim()?{model:n.provider.model.trim()}:{}}}:{}},adapterOptions:_,acpAuthMethod:_.auth_method,acpInitialMode:_.initial_mode,acpMcpTools:_.acp_mcp_tools,promptTimeoutMs:n.prompt_timeout_ms,bindingsPath:fe(n.name,n.agent_id),activeEventStorePath:_e(n.name,n.agent_id),...s.enableSessionBinding||g?{enableSessionBinding:!0}:{},...s.autoInjectArgs||r==="reasonix"&&n.provider?.model?.trim()?{autoInjectArgs:{...s.autoInjectArgs??{},...r==="reasonix"&&n.provider?.model?.trim()?{model:n.provider.model.trim()}:{}}}:{},poolMaxSize:n.pool?.maxSize,poolIdleTimeoutMs:n.pool?.idleTimeoutMs,eventQueue:we(a,n.event_queue),logDir:w.log,providerBaseUrl:n.provider_base_url?.trim()||void 0,providerApiKey:n.provider_api_key?.trim()||void 0}}function Se(){const n=process.env.GRIX_AGENT_STARTUP_WAIT_MS,e=Number(n);return Number.isFinite(e)&&e>=500?Math.floor(e):me}function N(n){const e=[],t=[],r=[],s=G(n).filter(i=>i.endsWith(".json")).sort();for(const i of s)try{const o=JSON.parse(K(A(n,i),"utf-8"));if(o===null||typeof o!="object"||Array.isArray(o)||!("agents"in o)){r.push(i);continue}if(!Array.isArray(o.agents)){t.push({file:i,error:"agents is not an array"});continue}if(o.agents.length===0){t.push({file:i,error:"agents array is empty"});continue}for(const p of o.agents)e.push({entry:p,file:i})}catch(o){t.push({file:i,error:o instanceof Error?o.message:String(o)})}return{entries:e,fileErrors:t,skipped:r}}function k(n){if(n===null||typeof n!="object")return JSON.stringify(n)??"null";if(Array.isArray(n))return`[${n.map(k).join(",")}]`;const e=n;return`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${k(e[r])}`).join(",")}}`}function Ae(n,e){return k(n)===k(e)}class Le{instances=[];configMap=new Map;rawConfigMap=new Map;reloadChain=Promise.resolve();sharedInstances=new Map;shareSyncChains=new Map;stopping=!1;deletedAgentCleanups=new Set;upgradeChecker=null;skillSyncer=null;globalConfigStore;configDir=w.config;sharedOwnersCache=new Y(w.data);installer=new de;async start(e){const t=e??w.config;this.configDir=t,l.info("manager",`Loading configs from ${t}`),oe(),P(),this.globalConfigStore=new ne(A(w.data,"agent-global-configs.json")),this.globalConfigStore.load();const{entries:r,fileErrors:s,skipped:i}=N(t);for(const a of s)l.error("manager",`Failed to load ${a.file}: ${a.error}`);for(const a of i)l.info("manager",`Skipped ${a}: not an agent config (no "agents" key)`);if(r.length===0&&s.length===0&&i.length===0)throw new Error(`No config files found in ${t}`);const o=[];let p=s.length;for(const{entry:a,file:g}of r)try{const m=b(a);o.push({config:m,entry:a,file:g}),l.info("manager",`Loaded ${m.name} (${m.adapterType??"acp"}) from ${g}`)}catch(m){const _=typeof a?.name=="string"?a.name:"<unknown>";l.error("manager",`Invalid agent config in ${g} (name=${_}): ${m}`),p++}let c=0;if(o.length>0){const a=Se();l.info("manager",`Starting ${o.length} agent(s), startup wait=${a}ms`);const g=()=>this.upgradeChecker?.triggerCheck(),m=d=>{this.instances=this.instances.filter(f=>f!==d)},_=o.map(({config:d,entry:f,file:h})=>{const u=new T(d,this.globalConfigStore);return u.setUpgradeTrigger(g),u.setShareSetHandler(y=>this.onShareSet(d,y)),u.setAgentDeletedHandler(()=>this.onAgentDeletedByPlatform(d.name)),u.setSkillSyncHandler(()=>this.skillSyncer?.triggerSync()),this.instances.push(u),this.configMap.set(d.name,d),this.rawConfigMap.set(d.name,{entry:f,file:h}),{config:d,instance:u,startPromise:u.start()}}),S=await Promise.all(_.map(async d=>{const f=await new Promise(h=>{let u=!1;const y=setTimeout(()=>{u||(u=!0,h({kind:"timeout"}))},a);d.startPromise.then(()=>{u||(u=!0,clearTimeout(y),h({kind:"started"}))}).catch(v=>{u||(u=!0,clearTimeout(y),h({kind:"failed",error:v}))})});return{task:d,outcome:f}}));for(const{task:d,outcome:f}of S){if(f.kind==="started"){this.restoreCachedSharedInstances(d.config);continue}if(f.kind==="failed"){if(D(f.error)){this.onAgentDeletedByPlatform(d.config.name);continue}m(d.instance),l.error("manager",`Failed to start ${d.config.name}: ${f.error}`);continue}c++,l.warn("manager",`Startup pending for ${d.config.name}, continue retrying in background`),d.startPromise.then(()=>{l.info("manager",`Delayed start succeeded: ${d.config.name}`),this.restoreCachedSharedInstances(d.config)}).catch(h=>{if(D(h)){this.onAgentDeletedByPlatform(d.config.name);return}m(d.instance),l.error("manager",`Delayed start failed: ${d.config.name}: ${h}`)})}if(this.instances.length>0){const d=Math.max(0,this.instances.length-c);l.info("manager",`${d}/${o.length} agent(s) running now`)}c>0&&l.warn("manager",`${c} agent(s) still connecting in background`)}if(this.instances.length===0&&o.length>0)throw new Error("All agent configurations failed to start");o.length>0&&(this.upgradeChecker=new ee(o.map(({config:a})=>({apiKey:a.aibot.apiKey,wsUrl:a.aibot.url})),()=>this.instances.some(a=>a.hasPendingOrBackgroundWork())||[...this.sharedInstances.values()].some(a=>a.hasPendingOrBackgroundWork())),await this.upgradeChecker.start()),o.length>0&&(this.skillSyncer=new te(o.map(({config:a})=>({apiKey:a.aibot.apiKey,wsUrl:a.aibot.url})),w.skills),await this.skillSyncer.start())}async stop(){l.info("manager","Stopping all agents..."),this.stopping=!0,this.upgradeChecker?.stop(),this.skillSyncer?.stop(),await Promise.allSettled([...this.shareSyncChains.values()]),this.shareSyncChains.clear();const e=[...this.sharedInstances.values()];this.sharedInstances.clear(),await Promise.allSettled([...this.instances.map(t=>t.stop()),...e.map(t=>t.stop())]),await this.globalConfigStore?.flush(),this.instances=[],P(),l.info("manager","All stopped")}onShareSet(e,t){this.sharedOwnersCache.save(e.name,t);const s=(this.shareSyncChains.get(e.name)??Promise.resolve()).catch(()=>{}).then(()=>this.syncSharedInstances(e,t));this.shareSyncChains.set(e.name,s)}async syncSharedInstances(e,t){if(this.stopping)return;const{toAdd:r,toRemove:s}=V(e.name,this.sharedInstances.keys(),t);for(const i of r){if(this.stopping)break;const o=X(e.name,i);try{const p=J(e,i),c=new T(p,this.globalConfigStore);this.sharedInstances.set(o,c),await c.start(),l.info("manager",`shared instance started: ${o}`)}catch(p){this.sharedInstances.delete(o);const c=p instanceof Error?p.message:String(p);/Auth failed/i.test(c)?(this.sharedOwnersCache.remove(e.name,i),l.warn("manager",`shared instance auth rejected, removed from cache: ${o}`)):l.error("manager",`start shared instance failed ${o}: ${p}`)}}for(const{key:i}of s){const o=this.sharedInstances.get(i);o&&(this.sharedInstances.delete(i),o.stop().catch(p=>l.error("manager",`stop shared instance failed ${i}: ${p}`)),l.info("manager",`shared instance stopped: ${i}`))}}restoreCachedSharedInstances(e){const t=this.sharedOwnersCache.load(e.name);t.length!==0&&(l.info("manager",`restoring ${t.length} cached shared instance(s) for ${e.name}`),this.onShareSet(e,t))}getAgentsStatus(){return this.instances.map(e=>e.getStatus())}async addAgent(e){await this.addAgentInternal(e,"agents.json"),this.persistAgentsConfig(),l.info("manager",`Added agent: ${e.name}`)}async addAgentInternal(e,t){const r=b(e);if(this.instances.some(s=>s.name===r.name))throw new Error(`Agent "${r.name}" already exists`);await this.startInstanceFromConfig(r,e,t)}async startInstanceFromConfig(e,t,r){const s=new T(e,this.globalConfigStore);s.setUpgradeTrigger(()=>this.upgradeChecker?.triggerCheck()),s.setShareSetHandler(i=>this.onShareSet(e,i)),s.setAgentDeletedHandler(()=>this.onAgentDeletedByPlatform(e.name)),s.setSkillSyncHandler(()=>this.skillSyncer?.triggerSync()),s.setProviderConfigHandler(i=>this.setAgentProvider(e.name,i)),s.setRelayEnvSettledHandler(()=>this.relayEnvSettledHandler?.()),await s.start(),this.instances.push(s),this.configMap.set(e.name,e),this.rawConfigMap.set(e.name,{entry:t,file:r}),this.relayEnvSettledHandler?.()}async removeAgent(e){if(!this.instances.some(t=>t.name===e))throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});await this.removeAgentInternal(e),this.persistAgentsConfig(),l.info("manager",`Removed agent: ${e}`),this.relayEnvSettledHandler?.()}async removeAgentInternal(e,t){const r=this.instances.findIndex(p=>p.name===e),s=r===-1?void 0:this.instances[r];r!==-1&&this.instances.splice(r,1),this.configMap.delete(e),this.rawConfigMap.delete(e);const i=this.shareSyncChains.get(e);this.shareSyncChains.delete(e),i&&await i.catch(()=>{});const o=`${e}#shared:`;for(const[p,c]of[...this.sharedInstances.entries()])p.startsWith(o)&&(this.sharedInstances.delete(p),c.stop().catch(a=>l.error("manager",`stop shared instance failed ${p}: ${a}`)));t?.keepShareCache||this.sharedOwnersCache.delete(e),s&&await s.stop()}onAgentDeletedByPlatform(e){this.stopping||this.deletedAgentCleanups.has(e)||(this.deletedAgentCleanups.add(e),(async()=>{try{if(!(this.rawConfigMap.has(e)||this.instances.some(r=>r.name===e)))return;l.warn("manager",`Agent "${e}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u505C\u6B62\u5B9E\u4F8B\u5E76\u6E05\u7406\u672C\u5730\u914D\u7F6E`),await this.removeAgentInternal(e),this.persistAgentsConfig(),l.info("manager",`Agent "${e}" \u5DF2\u5728\u5E73\u53F0\u5220\u9664\uFF0C\u672C\u5730\u914D\u7F6E\u5DF2\u6E05\u7406\uFF08agents.json \u5DF2\u79FB\u9664\u8BE5\u6761\u76EE\uFF09`)}catch(t){l.error("manager",`cleanup for deleted agent "${e}" failed: ${t}`)}finally{this.deletedAgentCleanups.delete(e)}})())}persistAgentsConfig(){const e=A(this.configDir,"agents.json");try{const t=[];for(const[,s]of this.configMap){const i=this.rawConfigMap.get(s.name)?.entry.provider;t.push({name:s.name,ws_url:s.aibot.url,agent_id:s.aibot.agentId,api_key:s.aibot.apiKey,client_type:s.aibot.clientType,...i?{provider:i}:{}})}z(e,JSON.stringify({agents:t},null,4)+`
2
+ `,"utf-8")}catch(t){l.error("manager",`Failed to persist agents config: ${t}`)}}isAgentBusy(e){return this.instances.find(r=>r.name===e)?.hasPendingWork()??!1}getAgentsWithStaleRelayEnv(){return this.instances.filter(e=>e.hasStaleRelayEnv()).map(e=>e.name)}markAgentRelayEnvStale(e){const t=this.instances.find(r=>r.name===e);return t?(t.markRelayEnvStale(),!0):!1}relayEnvSettledHandler;setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}async restartAgent(e){const t=this.rawConfigMap.get(e);if(!t)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});await this.replaceInstance(e,t.entry,t.file),l.info("manager",`Restarted agent: ${e}`)}async setAgentProvider(e,t){const r=this.rawConfigMap.get(e);if(!r)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});const s={...r.entry,provider:t};await this.replaceInstance(e,s,r.file),this.persistAgentsConfig(),l.info("manager",`Updated provider config for agent: ${e}`)}async clearDirectProviderConfigs(){const e=[...this.rawConfigMap.entries()].filter(([,r])=>!!r.entry.provider&&ie(r.entry.client_type)).map(([r])=>r),t=[];for(const r of e)try{await this.setAgentProvider(r,void 0),t.push(r)}catch(s){l.warn("manager",`Failed to clear provider config for "${r}": ${s instanceof Error?s.message:String(s)}`)}return t}async replaceInstance(e,t,r){const s=b(t);await this.removeAgentInternal(e,{keepShareCache:!0}),await this.startInstanceFromConfig(s,t,r),this.restoreCachedSharedInstances(s)}async reload(){const e=this.reloadChain.catch(()=>{}).then(()=>this.doReload());return this.reloadChain=e.catch(()=>{}),e}async doReload(){if(this.stopping)throw Object.assign(new Error("manager is stopping"),{code:"RELOAD_UNSAFE"});const{entries:e,fileErrors:t,skipped:r}=N(this.configDir);for(const c of r)l.info("manager",`reload: skipped ${c}: not an agent config (no "agents" key)`);if(t.length>0){const c=t.map(a=>`${a.file}: ${a.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${t.length} config file(s) failed to parse [${c}]`),{code:"RELOAD_UNSAFE"})}if(e.length===0)throw Object.assign(new Error("reload aborted: no valid agent config found"),{code:"RELOAD_UNSAFE"});const s=[];for(const{entry:c}of e)try{b(c,{quiet:!0})}catch(a){const g=c?.name,m=typeof g=="string"&&g.trim()?g:"<unknown>";s.push({name:m,error:a instanceof Error?a.message:String(a)})}if(s.length>0){const c=s.map(a=>`${a.name}: ${a.error}`).join("; ");throw Object.assign(new Error(`reload aborted: ${s.length} agent config(s) invalid [${c}]`),{code:"RELOAD_UNSAFE"})}const i=new Map;for(const c of e){const a=String(c.entry?.name??"").trim();a&&(i.has(a)&&l.warn("manager",`reload: duplicate agent name "${a}", last one wins`),i.set(a,c))}const o={added:[],removed:[],restarted:[],unchanged:[],failed:[]},p=new Set(this.rawConfigMap.keys());for(const c of p)if(!i.has(c))try{await this.removeAgentInternal(c),o.removed.push(c)}catch(a){o.failed.push({name:c,error:a instanceof Error?a.message:String(a)})}for(const[c,a]of i){const g=this.rawConfigMap.get(c);if(g)if(Ae(g.entry,a.entry))this.rawConfigMap.set(c,a),o.unchanged.push(c);else try{await this.replaceInstance(c,a.entry,a.file),o.restarted.push(c)}catch(m){o.failed.push({name:c,error:m instanceof Error?m.message:String(m)})}else try{await this.addAgentInternal(a.entry,a.file),o.added.push(c)}catch(m){o.failed.push({name:c,error:m instanceof Error?m.message:String(m)})}}return l.info("manager",`reload done: +${o.added.length} -${o.removed.length} ~${o.restarted.length} =${o.unchanged.length} !${o.failed.length}`),o}async checkUpgrade(){return this.upgradeChecker?this.upgradeChecker.checkForUpdate():{available:!1}}triggerUpgrade(){this.upgradeChecker?.triggerCheck()}async probeAll(e={}){return ve(this.instances,e)}async probeOne(e,t={}){return be(this.instances,e,t)}listInstallable(){return this.installer.listInstallable()}async installAgent(e){const t=await this.installer.install(e);return pe(t),t}getInstallProgress(e){return this.installer.getProgress(e)??null}}async function ve(n,e){const t=e.concurrency??4,r=Date.now(),s=new Array(n.length);await new Promise(a=>{let g=0,m=0;const _=n.length;if(_===0){a();return}function S(h){const u=n[h];u.probe(e).then(y=>{s[h]=y,d()},y=>{s[h]={agent_name:u.name,client_type:"unknown",adapter_type:"acp",ok:!1,status:"error",probed_at:Date.now(),duration_ms:0,cached:!1,cli:{command:"",installed:!1,path:null,version:null,error:{code:"internal",message:y?.message??String(y)}},conversation:{attempted:!1,ok:!1,latency_ms:null},config:{model:null,base_url:null,source:{model:"unknown",base_url:"unknown"}},process:{started:!1,alive:!1,busy:!1}},d()})}function d(){m++,g<_?S(g++):m===_&&a()}const f=Math.min(t,_);for(let h=0;h<f;h++)S(g++)});const i=s.filter(a=>a.status==="healthy").length,o=s.filter(a=>a.status==="degraded").length,p=s.filter(a=>a.status==="unavailable").length,c=await ge();return{ok:i===s.length&&s.length>0,total:s.length,healthy:i,degraded:o,unavailable:p,installed_clients:c,agents:s,probed_at:r,duration_ms:Date.now()-r}}async function be(n,e,t){const r=n.find(s=>s.name===e);if(!r)throw Object.assign(new Error(`Agent "${e}" not found`),{code:"NOT_FOUND"});return r.probe(t)}export{Le as Manager,ge as probeInstalledClientCommands,ve as probeInstances,be as probeOneInstance};
@@ -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.10.0",
3
+ "version": "3.10.1",
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",