grix-connector 4.3.2 → 4.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/claude/claude-bridge-server.js +1 -1
- package/dist/adapter/claude/claude-tools.js +1 -1
- package/dist/adapter/claude/claude-worker-client.js +1 -1
- package/dist/adapter/claude/mcp-http-launcher.js +2 -2
- package/dist/adapter/claude/result-timeout.js +1 -1
- package/dist/assets/dsh-bridge/{grix-dsh-bridge-4.3.2.tgz → grix-dsh-bridge-4.3.3.tgz} +0 -0
- package/dist/assets/dsh-bridge/manifest.json +4 -4
- package/dist/bridge/bridge.js +5 -5
- package/dist/bridge/dsh-toolbar.js +1 -0
- package/dist/bridge/inbound-audit-gate.js +1 -0
- package/dist/bridge/inbound-binding-gate.js +1 -0
- package/dist/bridge/local-action-files.js +1 -0
- package/dist/bridge/local-action-session-control.js +1 -0
- package/dist/bridge/local-action-toolbar.js +1 -0
- package/dist/bridge/session-identity.js +1 -0
- package/dist/bridge/session-open-helpers.js +1 -0
- package/dist/bridge/text-command-session-control.js +1 -0
- package/dist/core/access/allowlist-store.js +1 -1
- package/dist/core/file-ops/list-files.js +1 -1
- package/dist/log.js +2 -2
- package/dist/mcp/stream-http/config.js +1 -1
- package/dist/mcp/stream-http/connection-binding.js +1 -1
- package/dist/mcp/stream-http/security.js +1 -1
- package/dist/mcp/stream-http/tool-executor.js +1 -1
- package/dist/mcp/stream-http/tool-registry.js +1 -1
- package/dist/mcp/stream-http/tool-schemas.js +1 -1
- package/package.json +1 -1
|
@@ -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
|
|
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(
|
|
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
|
|
2
|
-
`),"utf8"),{expectPath:a,pidPath:i}}function h(
|
|
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(
|
|
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};
|
|
Binary file
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"bridgeVersion": "4.3.
|
|
4
|
-
"tarball": "grix-dsh-bridge-4.3.
|
|
3
|
+
"bridgeVersion": "4.3.3",
|
|
4
|
+
"tarball": "grix-dsh-bridge-4.3.3.tgz",
|
|
5
5
|
"size": 22532,
|
|
6
6
|
"unpackedSize": 89865,
|
|
7
|
-
"shasum": "
|
|
8
|
-
"integrity": "sha512-
|
|
7
|
+
"shasum": "134139721d37b4d493f5da3c92c3cc99069fea4e",
|
|
8
|
+
"integrity": "sha512-Xzh4MiY7zJBq/P+N/mpNKCnrLqIggl4voSvV7PNu/Vj//RdkBJH75Wo+7rFBkV7nVyyhJj7nD4z4XWBX28P3Ag=="
|
|
9
9
|
}
|
package/dist/bridge/bridge.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import T from"node:path";import{realpath as te,stat as Q}from"node:fs/promises";import{tmpdir as ne}from"node:os";import{createHash as O,randomUUID as B}from"node:crypto";import{ConnectionManager as ie}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as se}from"../core/aibot/types.js";import{ClaudeAdapter as N}from"../adapter/claude/index.js";import{CodexAdapter as W}from"../adapter/codex/index.js";import"../adapter/claude/session-history.js";import"../adapter/codex/session-history.js";import"../adapter/pi/session-history.js";import"../adapter/opencode/session-history.js";import"../adapter/codewhale/session-history.js";import"../adapter/deepseek-harness/session-history.js";import{PiAdapter as oe}from"../adapter/pi/index.js";import{AcpAdapter as y}from"../adapter/acp/index.js";import{OpenHumanAdapter as re}from"../adapter/openhuman/index.js";import{CursorAdapter as ae}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as de}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as F}from"../adapter/opencode/index.js";import{AgyAdapter as G}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as le,buildDshBindingToolbarMeta as ce,DEFAULT_DSH_PRESETS as he,listDshPlugins as ue,listDshSkills as pe,listDshProfiles as ge,normalizeDshReasoningEffort as fe,normalizeDshThinking as me,resolveDshAgentPreset as ve,resolveDshCatalogForToolbar as _e,resolveDshModeId as j,resolveDshSelectedProfileName as Se}from"../adapter/deepseek-harness/index.js";import{LOCAL_ACTION_TYPES as k,SESSION_CONTROL_ERROR_CODES as E,SESSION_CONTROL_VERBS as S,SESSION_MODE_IDS as be}from"../adapter/claude/protocol-contract.js";import{isAuditLocalActionType as Ce}from"../audit/query/audit-local-actions.js";import{shouldEnableRawApiCapture as K}from"../audit/raw-capture/types.js";import{syncDefaultSkillsToDir as we}from"../default-skills/index.js";import{buildWireSkills as Ae}from"../core/skill-sync/sync-state.js";import{executeEventTool as Ee}from"../core/mcp/event-tool-executor.js";import{fetchAvailableModels as ke}from"../adapter/claude/model-list.js";import{applyProxyEnv as Re,getProxyManager as ye}from"../core/proxy/index.js";import{getKiroRelaySpawnEnv as Pe}from"../core/proxy/kiro-relay.js";import{supportsKiroCwRelay as Te}from"../core/config/provider-env.js";import{buildProviderEnv as xe}from"../core/config/provider-env.js";import{isClaudeDirectEnv as De,stripGrixRelayEnv as Me}from"../core/config/claude-direct-env.js";import{sweepNativeProviderResidue as He}from"./native-provider-sweep.js";import{scanCodexSessions as Le}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as $e}from"../adapter/claude/session-scanner.js";import{reasonixStampFromSessionId as Ie,resolveAcpAgentTypes as Qe,scanAcpSessions as Oe,scanReasonixSessionTitles as Be}from"../adapter/acp/session-scanner.js";import{scanPiSessions as Fe}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as qe}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as Ue}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as Ne}from"../adapter/opencode/session-scanner.js";import{scanDshSessions as We}from"../adapter/deepseek-harness/session-scanner.js";import{SessionScanCache as P,resolveCodexLeafDirs as Ge,resolveClaudeLeafDirs as je,resolveAcpLeafDirs as Ke,resolvePiLeafDirs as ze,resolveCodeWhaleLeafDirs as Je,resolveCursorLeafDirs as Ye,resolveOpenCodeLeafDirs as Xe,resolveDshLeafDirs as Ve,resolveReasonixLeafDirs as Ze}from"./session-scan-cache.js";import{log as p,ConversationLog as et,AgentApiPacketLog as tt,BridgeEventLog as nt,GRIX_PATHS as L}from"../core/log/index.js";import{routeSessionControlCommand as it,routeSessionControlLocalAction as st}from"./session-control-router.js";import{maybeOfferCliInstall as ot,handleCliInstallQuestionReply as rt,handleCliInstallInteractionReply as at,runConfirmedCliInstall as dt}from"./cli-install-flow.js";import{handleEventCancel as lt,waitForEventDone as ct,handleAibotStop as ht,killAndResumeStopSlot as ut,handleAibotRevoke as pt}from"./event-stop.js";import{handleConfigureGatewayProvider as gt,getAuditLocalActionHandler as ft,handleAuditLocalAction as mt,handleConnectorRollback as vt,getRelayStateSyncer as _t,relayStateSyncOnConnect as St,reportRelayStateLocalChange as bt,handleApplyRelayState as Ct,fetchRelayCredential as wt,isSharedInstance as At}from"./connector-ops.js";import{unbindSession as Et,handleUnbindTextCommand as kt,handleUnbindLocalAction as Rt,handleListSessionsTextCommand as yt,handleListSessionsLocalAction as Pt,handleSyncHistoryLocalAction as Tt}from"./session-list.js";import{handleCodexSessionControlOpen as xt,handleSessionControlForPool as Dt,handleSessionControlLocalActionForPool as Mt,handleCodexSessionControlLocalActionOpen as Ht,handleCursorSessionControlLocalActionOpen as Lt,handlePiSessionControlOpen as $t,handlePiSessionControlRestart as It,handlePiSessionControlRestartLocalAction as Qt,syncOpenCodeBinding as Ot,isWorkspaceFreeClient as Bt,ensureDefaultBindingForWorkspaceFreeClient as Ft,bindSessionForPool as qt,deferredCallbacks as Ut,handleOpenHumanSessionControlOpen as Nt,handleCodeWhaleSessionControlOpen as Wt,handleCodeWhaleSessionControlLocalActionOpen as Gt,handleDeepSeekSessionControlLocalActionOpen as jt}from"./session-control-open.js";import{handleGetSessionUsage as Kt,handleThreadCompact as zt}from"./session-usage.js";import{handleSkillDeleteLocalAction as Jt,handleSkillUploadLocalAction as Yt,handleSkillEnableLocalAction as Xt,handleSkillRefreshLocalAction as Vt,handleSkillDisableLocalAction as Zt,computeSkillReport as en,reportSessionSkills as tn,skillsSyncGroupKey as nn,forceRefreshSkills as sn,adoptSkillsWireHashFromDisk as on,buildLibrarySkillsReport as rn,skillLookupEnv as an}from"./skill-actions.js";import{normalizeClaudeModeId as dn,handleExecCommandOptions as ln,resolveSessionModelId as cn,resolveSessionModeId as hn,resolveCursorSessionModeId as un,resolveClaudeSessionEffort as pn,resolveClaudeSessionModeId as gn,currentClaudeModeId as fn,resolveCodexSessionModelId as mn,resolveCodexNewSessionGlobalDefault as vn,pinCodexGlobalDefault as _n,buildCursorToolbarMeta as Sn,buildAgyToolbarMeta as bn,buildAgyQuotaMeta as Cn,sendAgyBindingCard as wn,refreshAndPushAgyQuota as An,handleAgySetModel as En,buildClaudeToolbarMeta as kn}from"./toolbar-meta.js";import{resolveProviderQuotaSource as Rn,maybeQueryProviderQuota as yn,startProviderQuotaTimer as Pn,stopProviderQuotaTimer as Tn,refreshAndPushProviderQuota as xn,pushProviderQuotaToBindings as Dn,enrichProviderQuotaMeta as Mn,providerQuotaMetaPayload as Hn,refreshProviderQuotaForSession as Ln,refreshQuotaAfterModelSwitch as $n,doRefreshQuotaAfterModelSwitch as In}from"./provider-quota.js";import{handleGetRateLimits as Qn,resolveRateLimitWakeSessionId as On,wakeRateLimitSlot as Bn}from"./rate-limits.js";import{RevokeHandler as Fn}from"./revoke-handler.js";import{AdapterPool as qn}from"./adapter-pool.js";import{parseSessionControlCommand as Un,handleSessionControlCommand as Nn,handleSessionControlLocalAction as Wn}from"./session-controller.js";import{isOpenSessionDirectiveMessage as Gn,parseExecApprovalResolutionMessage as jn,parseAgentQuestionReplyMessage as Kn}from"../core/protocol/interaction-parser.js";import{isCliMissingError as zn,sessionControlOpenFailure as Jn}from"./cli-install-offer.js";import{handleAcpSetModel as z,handleAcpSetMode as J,resolveAcpInitialDefaults as Yn}from"./acp-toolbar-persist.js";import{SessionBindingStore as Xn}from"../core/persistence/session-binding-store.js";import{handleFileListAction as Vn,handleCreateFolderAction as Zn,serveLocalFile as ei,realHomeDir as Y}from"../core/files/index.js";import{getMachineName as ti}from"../core/util/index.js";import{uploadReplyFileToAgentMedia as ni}from"../core/protocol/agent-api-media.js";import{ActiveEventStore as ii}from"../core/persistence/active-event-store.js";import{PendingEventCoordinator as si}from"./pending-event-coordinator.js";import{LifecycleBarrier as oi}from"./lifecycle-barrier.js";import{QUEUE_COMPOSING_TTL_MS as ri}from"./event-queue.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as ai,applyConnectorRuntimeConfigPatch as di,extractConnectorRuntimeConfigPatch as li}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as ci,SendController as hi}from"./send-controller.js";import{providerQuotaToRateLimits as ui,providerQuotaToCodexRateLimits as pi}from"../core/provider-quota/index.js";import{buildToolUseCard as D,buildToolResultCard as M,buildDshOnlineToolCard as gi,buildLocalGrixCardLink as X}from"./tool-card-utils.js";import{planRawEventDelivery as fi,buildAuxiliaryDetailText as mi}from"./raw-event-delivery.js";import{DeferredEventManager as vi}from"./deferred-events.js";import{buildAgentProbeResult as _i,PROBE_CACHE_TTL_STATIC_MS as Si,PROBE_CACHE_TTL_FULL_MS as bi}from"./probe-helper.js";import{BridgeAuditController as Ci}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as wi,NoopAuditProducer as Ai}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as $,AuditPreparationFailedError as Ei,AuditTurnScopeUnsupportedError as ki}from"../audit/core/audit-state.js";import{extractAuditOptions as V,freezeAuditOptions as Ri,stripAuditOptions as yi}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as Pi}from"../audit/core/audit-session-registry.js";const Ti=600*1e3,Z=1800*1e3,xi=60*1e3,Di=4e3;function Mi(U,e,t){const s=O("sha256").update(U).update("\0").update(e).update("\0").update(t).digest("hex");return T.join(L.data,"audit-source","reasonix",`${s}.jsonl`)}const I=new Set(["claude","acp","agy","cursor","codex","deepseek-harness"]),ee=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),q=3;class ao{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new Fn;sessionBindings=new Map;deferredMgr;sendCtrl=new hi(ai);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;pendingCliInstalls=new Map;agentDeletedHandler=null;shareSetHandler=null;skillSyncHandler=null;providerConfigHandler=null;relayStateApplyPorts=null;relayStateSyncer=null;agentProfile={agentName:"",introduction:""};agentSystemPrompt="";activeEventStore;pendingEvents;pendingStartedEventIds=new Set;lifecycleBarrier=new oi;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;cachedProviderQuotaKey=null;sessionProviderHints=new Map;sessionProviderQuotas=new Map;sessionProviderMeta=new Map;lastModelSwitchQuotaRefresh=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";lastReportedSkillsWireHash="";conversationLog=null;packetLog=null;providerQuotaTimer=null;eventSessionIndex=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;auditController;auditLocalActionHandler=null;sessionScanCache;reasonixTitleScan=null;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const t=Number(e);return t>0&&Date.now()-t<=xi}resolveProviderQuotaSource(e){return Rn(this,e)}maybeQueryProviderQuota(e=!1,t){return yn(this,e,t)}startProviderQuotaTimer(){Pn(this)}stopProviderQuotaTimer(){Tn(this)}refreshAndPushProviderQuota(e=!1){return xn(this,e)}pushProviderQuotaToBindings(e,t=!1){Dn(this,e,t)}enrichProviderQuotaMeta(e,t="standard",s=this.cachedProviderQuota,i=this.cachedProviderQuotaSampledAtMs){return Mn(this,e,t,s,i)}providerQuotaMetaPayload(e,t,s){return Hn(this,e,t,s)}refreshProviderQuotaForSession(e,t,s){return Ln(this,e,t,s)}refreshQuotaAfterModelSwitch(e,t,s){$n(this,e,t,s)}doRefreshQuotaAfterModelSwitch(e,t,s){return In(this,e,t,s)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,t=this.cachedCodexContextWindow,s=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:t,tokenUsage:s,hasData:!!(e||t||s)}}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,wsConnected:this.aibotHandle?.status==="ready",exhausted:this.pool?[...this.pool.getAllSlots()].some(t=>t.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}hasPendingOrBackgroundWork(){return this.lifecycleBarrier.hasActiveAdmissions()||(this.pool?.hasPendingOrBackgroundWork()??!1)}async waitUntilLifecycleIdle(e){const t=()=>this.lifecycleBusyChecker?.()??this.hasPendingOrBackgroundWork();if(t()){const s=Math.round(Z/6e4);p.info(this.name,`${e}: active tasks detected, waiting up to ${s}min until idle before restart (admission stays open while waiting)`);const i=Date.now()+Z,n=5e3,o=600*1e3;let r=Date.now();for(;t()&&!this.stopped;){if(Date.now()>=i)return p.warn(this.name,`${e}: idle wait exceeded ${s}min; abandoning this restart. Admission was never closed, so agents kept serving. A busy state that never clears usually means an adapter leaked its busy flag \u2014 check for a turn that never completed.`),!1;await new Promise(a=>setTimeout(a,n)),Date.now()-r>=o&&(r=Date.now(),p.info(this.name,`${e}: still waiting for active tasks to finish before restart`))}}return this.stopped?!1:(this.closeLifecycleAdmissionForRestart(),t()?(p.warn(this.name,`${e}: work arrived while closing admission; reopening and abandoning this restart`),this.reopenLifecycleAdmissionAfterAbort(),!1):(p.info(this.name,`${e}: all tasks completed, proceeding with restart`),!0))}reopenLifecycleAdmissionAfterAbort(){if(this.lifecycleAdmissionRestorer){this.lifecycleAdmissionRestorer();return}this.openLifecycleAdmission()}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,p.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 t=0,s=!1;for(const i of e){if(this.hasPendingWork())return this.relayEnvStale=!0,p.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let n=!1;await this.pool.removeSlot(i.sessionId).catch(o=>{s=!0,n=!0,p.warn(this.name,`failed to recycle adapter slot ${i.sessionId} after relay change: ${o}`)}),n||(t+=1)}return t>0&&p.info(this.name,`recycled ${t} adapter slot(s) so the new Grix relay env takes effect`),s?(this.relayEnvStale=!0,!1):(this.relayEnvStale=!1,this.relayEnvSettledHandler?.(),!0)}setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}providerResolver;setProviderResolver(e){this.providerResolver=e}hasStaleRelayEnv(){return this.relayEnvStale}markRelayEnvStale(){this.relayEnvStale=!0}async probe(e={}){const t=e.conversation?"full":"static",s=e.conversation?bi:Si;if(!e.fresh){const a=this.probeCache.get(t);if(a&&Date.now()-a.sampledAt<s)return{...a.result,cached:!0}}const i=this.config.adapterType??"acp",n=this.createAdapter(i,"__probe__"),o=e.conversation&&i==="acp"?()=>this.runAcpConversationProbe(n,e.timeoutMs??1e4):void 0;let r;try{r=await _i({adapter:n,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:i,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:o})}finally{n.stop().catch(()=>{})}return this.probeCache.set(t,{result:r,sampledAt:r.probed_at}),r}async runAcpConversationProbe(e,t){const s=Date.now(),i="__probe__",n=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=this.config.agent.cwd||ne(),r=()=>Date.now()-s;try{await e.start()}catch(h){return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_failed",message:`start failed: ${h instanceof Error?h.message:String(h)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof y)try{await e.bindSession(i,o)}catch{}let a=null;const c=new Promise(h=>{a=g=>{g===n&&h()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:n,session_id:i,content:"ping",msg_id:n}),e.deliverStopEvent(n,i);let d=null;const l=await Promise.race([c.then(()=>!1),new Promise(h=>{d=setTimeout(()=>h(!0),t)})]);return d&&clearTimeout(d),a&&e.removeListener("eventDone",a),l?{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_timeout",message:`no eventDone within ${t}ms`}}:{attempted:!0,ok:!0,latency_ms:r()}}constructor(e,t,s=new Ai){this.config=e,this.auditController=new Ci(s,{onAuditState:n=>{try{this.aibotHandle.sendAuditState($(n,Date.now()))}catch{}}}),wi(s)&&s.addJobSettledHandler((n,o)=>{this.auditController.handleJobSettled(n,o)}),this.name=e.name;const i=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(ci[i]),this.aibotConfig={...e.aibot,...i==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","set_reasoning_effort","thread_compact","get_agent_global_config",...se]}:{}},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 et(e.logDir):null,this.packetLog=e.logDir?new tt(e.logDir):null,this.bindingStore=new Xn(e.bindingsPath,e.legacyBindingsPath),this.bindingStore.load(),this.globalConfigStore=t??null,this.deferredMgr=new vi(this.name),this.activeEventStore=e.activeEventStorePath?new ii(e.activeEventStorePath):null,this.pendingEvents=new si(e.pendingEventStorePath),i==="codex")this.sessionScanCache=new P(Le,Ge);else if(i==="claude")this.sessionScanCache=new P($e,je);else if(i==="pi"){const n=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new P(()=>Fe(void 0,n),()=>ze(void 0,n))}else if(i==="codewhale")this.sessionScanCache=new P(qe,Je);else if(i==="cursor")this.sessionScanCache=new P(Ue,Ye);else if(i==="opencode")this.sessionScanCache=new P(Ne,Xe);else if(i==="deepseek-harness"){const n=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new P(()=>We(n),()=>Ve(n))}else if(i==="agy")this.sessionScanCache=new P(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new P(Be,Ze));const n=Qe(e.aibot.clientType);this.sessionScanCache=n?new P(()=>Oe(void 0,n),()=>Ke(void 0,n)):new P(()=>[],()=>[])}}async start(){if(this.stopped)throw new Error("agent start aborted");if(await He({agentName:this.name,adapterType:this.config.adapterType??"acp",command:this.config.agent.command,piConfigDir:this.config.agent.env?.PI_CODING_AGENT_DIR,dshHome:typeof this.config.adapterOptions?.dshHome=="string"?this.config.adapterOptions.dshHome:this.config.agent.env?.DSH_HOME,hasProvider:!!this.config.agent.provider,boundCwds:[...this.bindingStore.entries()].map(([,n])=>String(n.cwd??""))}).then(n=>{n.length>0&&p.info(this.name,`restored native provider config after relay disable: ${n.join(", ")}`)}).catch(n=>{p.warn(this.name,`native provider residue sweep failed: ${n instanceof Error?n.message:String(n)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await ke().catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}if(this.stopped)throw new Error("agent start aborted");const e=!!(this.config.providerBaseUrl&&this.config.providerApiKey||this.config.agent.provider?.baseUrl&&this.config.agent.provider?.apiKey),t=(this.config.adapterType??"acp")==="pi",s=(this.config.adapterType??"acp")==="opencode";if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(t||s)&&this.startProviderQuotaTimer(),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),(this.config.adapterType??"acp")==="opencode"&&this.maybeQueryProviderQuota().catch(()=>{}),this.stopped)throw new Error("agent start aborted");if(await this.connectAibot(),this.stopped)throw this.aibotHandle?.disconnect(),new Error("agent start aborted");this.sendCtrl.bind(this.aibotHandle);const i=this.config.adapterType??"acp";if(this.pool=new qn({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},n=>{const o=this.createAdapter(i,n);return o instanceof y&&o.on("acpSessionReady",r=>{this.bindingStore.setAcpSessionId(n,r),this.sessionScanCache.invalidate()}),o},(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})}),this.pool.setEventStateHandler((n,o,r,a)=>{if(p.info(this.name,`[queue-debug] send event_state session=${o} event=${n} state=${r} queue_pos=${a?.queue_position??""} queue_total=${a?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:n,session_id:o,state:r,content_preview:a?.content_preview,content:a?.content,queue_position:a?.queue_position,queue_total:a?.queue_total,actions:a?.actions,reason:a?.reason,held:a?.held,held_reason:a?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(o),r==="running"&&(this.pendingStartedEventIds.add(n),this.pendingEvents.remove(n).catch(c=>{p.warn(this.name,`Failed to remove running event from pending store event=${n}: ${c instanceof Error?c.message:String(c)}`)})),r==="canceled"||r==="failed"){const c=r==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:n,status:c,msg:a?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(n,c,a?.reason,{queueTerminalState:r}),this.discardEventTrackingState(n),this.pendingEvents.remove(n).catch(d=>{p.warn(this.name,`Failed to remove queued terminal event from pending store event=${n}: ${d instanceof Error?d.message:String(d)}`)})}}),this.pool.setQueueComposingHandler((n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:o,...o?{ttl_ms:ri,ref_event_id:r}:{}})}),this.pool.setInternalErrorHandler(n=>{this.handleSessionInternalError(n).catch(o=>{p.error(this.name,`[recovery] handleSessionInternalError failed event=${n.eventId} session=${n.sessionId}: ${o instanceof Error?o.message:String(o)}`)})}),this.pool.setEventStartedHandler((n,o)=>{if(this.reportSessionSkills(o),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(o,"busy");const r=this.bindingStore.get(o);r?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"busy",cwd:r.cwd,meta:this.buildClaudeToolbarMeta(o)})}),this.pool.setEventDoneHandler((n,o)=>{this.markAuditAdapterClosed(n,o);const r=this.config.adapterType??"acp";if(r==="claude"){this.claudeWorkerStatus.set(o,"ready");const a=this.bindingStore.get(o);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(o)})}else if(r==="agy"){const a=this.bindingStore.get(o);if(a?.cwd){const c=this.buildAgyToolbarMeta(o),d=c?.available_models??[];p.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${o} model_id=${String(c?.model_id??"")} available_models=${d.length} meta_keys=${c?Object.keys(c).join(","):"<none>"}`),this.sendAgyBindingCard(o,a.cwd,c),this.refreshAndPushAgyQuota(o)}else p.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${o}`)}}),this.pool.setSessionActivityHandler((n,o,r)=>{const a=this.selfDrivenSessions.has(n),c=this.selfDrivenLabels.get(n);o?(this.selfDrivenSessions.add(n),r&&this.selfDrivenLabels.set(n,r),this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(n),this.selfDrivenLabels.delete(n),a&&this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:!1})),(a!==o||o&&r!==void 0&&r!==c)&&this.pushQueueSnapshotForSession(n)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),p.info(this.name,`Ready (adapter: ${i}, poolMax: ${this.config.poolMaxSize??20})`)}requestStop(){this.stopped=!0,this.lifecycleBarrier.close(),this.startupAbortController.abort(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown")}async stop(e){if(e?.dropPendingEvents&&(this.dropPendingEventsRequested=!0),this.requestStop(),!this.stopPromise){const t=this.stopOnce();this.stopPromise=t,t.catch(()=>{this.stopPromise===t&&(this.stopPromise=null)})}await this.stopPromise,this.dropPendingEventsRequested&&!this.pendingEventsDropped&&await this.dropPendingEventsBestEffort()}async stopOnce(){this.lifecycleBarrier.close(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown");const e=this.pool?.collectActiveEventIds()??[],t=new Map(e.map(r=>[r,this.eventSessionIndex.get(r)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const r of e)p.info(this.name,`Canceling active event on shutdown: ${r}`),this.sendEventResultWithCleanup(r,"canceled","process shutting down");e.length>0&&await new Promise(r=>setTimeout(r,100)),this.pool?.clearActiveEventsForShutdown();for(const r of e){const a=t.get(r),c=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(r,c?.adapter.takeAuditBoundary?.(r)??{processTerminated:!0})}const s=this.deferredMgr.getAllDeferredEntries(),i=this.pool?.drainAllQueuedEvents()??[],n=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...s.map(r=>({kind:"deferred",channel:r.channel,sessionId:r.sessionId,event:r.event})),...i.map(r=>({kind:"queued",event:r}))]);let o=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(r){p.warn(this.name,`Failed to clear pending event store on removal: ${r instanceof Error?r.message:String(r)}`)}else try{o=await this.pendingEvents.mergeForShutdown(n)}catch(r){p.error(this.name,`Failed to persist pending events on shutdown: ${r instanceof Error?r.message:String(r)}`)}if(!o)for(const r of n){const a=r.event;p.info(this.name,`Failing pending event on shutdown: ${a.event_id}`),this.sendEventResultWithCleanup(a.event_id,"failed","process shutting down"),this.auditController.markAdapterClosed(a.event_id,{adapterNotStarted:!0,processTerminated:!0})}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(),this.auditController.dispose()}async dropPendingEventsBestEffort(){try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(e){p.warn(this.name,`Failed to clear pending event store on removal: ${e instanceof Error?e.message:String(e)}`)}}resolveSpawnEnv(){const e=this.providerResolver?this.providerResolver():this.config.agent.provider,t=xe(this.config.agent.clientType,e),s=this.config.agent.env;let i=Object.keys(t).length>0?{...t,...s}:s;if(De(t)){const n=ye()?.getRuntimeInfo(),o={...s??{},...t},r=Me(o,{proxyUrl:n?.proxyUrl,caCertPath:n?.caCertPath,caBundlePath:n?.caBundlePath});return delete r.ANTHROPIC_API_KEY,delete r.CLAUDE_CODE_OAUTH_TOKEN,r}if(Te(this.config.agent.clientType)){const n=Pe(this.name);n&&(i={...i??{},...n})}return Re(i,this.name,this.config.agent.clientType)}createAdapter(e,t){switch(e){case"claude":return this.createClaudeAdapter(t);case"codex":return this.createCodexAdapter(t);case"pi":return this.createPiAdapter(t);case"openhuman":return this.createOpenHumanAdapter(t);case"codewhale":return this.createCodeWhaleAdapter(t);case"cursor":return this.createCursorAdapter(t);case"opencode":return this.createOpenCodeAdapter(t);case"agy":return this.createAgyAdapter(t);case"deepseek-harness":return this.createDshAdapter(t);default:return this.createAcpAdapter(t)}}createDshAdapter(e){const t={sendStreamChunk:(n,o,r,a,c,d,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,r,a,c,d,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",Di),sendThinking:(n,o,r)=>this.sendThinkingByRuntimeConfig(n,o,r),sendEventResult:(n,o,r,a)=>{this.sendEventResultWithCleanup(n,o,r,void 0,a)},sendRawEventEnvelope:(n,o,r,a)=>{const c=gi(r);if(c){this.sendToolExecutionCard(n,o,c);return}this.deliverRawEventEnvelope(n,o,r,"deepseek",a)},sendLocalActionResult:(n,o,r,a,c)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...c?{error_msg:c}:{}},e)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"deepseek")},sendUpdateBindingCard:(n,o,r,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:r,meta:a})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:n=>this.maybeQueryProviderQuota(n===!0,{providerId:"deepseek"}),agentInvoke:async(n,o,r)=>this.platformInvoke(n,o,r),eventToolInvoke:async(n,o)=>this.invokeDshEventTool(n,o)},s=O("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),i=this.config.adapterOptions??{};return new le({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},t,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:T.join(L.data,"deepseek-harness",s),...typeof i.cordisPath=="string"?{cordisPath:i.cordisPath}:{},...typeof i.defaultModel=="string"?{defaultModel:i.defaultModel}:{},...typeof i.maxTokens=="number"?{maxTokens:i.maxTokens}:{},...typeof i.maxLineBytes=="number"?{maxLineBytes:i.maxLineBytes}:{},...i.integrationMode==="embedded_jsonrpc"||i.integrationMode==="profile_bridge"?{integrationMode:i.integrationMode}:{},...typeof i.dshHome=="string"?{dshHome:i.dshHome}:{},...typeof i.dshProfile=="string"?{dshProfile:i.dshProfile}:{},...typeof i.autoInstallBridge=="boolean"?{autoInstallBridge:i.autoInstallBridge}:{},...typeof i.autoStartProfile=="boolean"?{autoStartProfile:i.autoStartProfile}:{},...this.config.agent.provider?{provider:this.config.agent.provider}:{},promptTimeoutMs:this.config.promptTimeoutMs})}createCursorAdapter(e){const t={...this.config.adapterOptions??{}};t.bindingStore=this.bindingStore,t.aibotSessionId=e;const s=this.bindingStore.get(e),i=this.resolveSessionModelId(e);i&&(t.model=i);const n=this.resolveCursorSessionModeId(e),o=n??"full_auto";n||this.bindingStore.setCursorModeId(e,o),t.mode=o,s?.cwd&&(t.workspace=s.cwd);const r={sendStreamChunk:(a,c,d,l,h,g,u)=>{this.sendStreamChunkByRuntimeConfig(a,c,d,l,h,g,u)},sendEventResult:(a,c,d)=>{this.sendEventResultWithCleanup(a,c,d)},sendEventAck:(a,c)=>{this.aibotHandle.sendEventAck({event_id:a,session_id:c,received_at:Date.now()})},sendRawEventEnvelope:(a,c,d)=>{this.deliverRawEventEnvelope(a,c,d,"cursor",this.buildCursorRawEventFallbackText(d))},sendAgentQuestionCard:(a,c,d)=>{const l=d.questions.map(g=>g.header).join(", "),h=X(`[Agent Question] ${d.request_id}`,"agent_question",d);this.aibotHandle.sendText({event_id:a,session_id:c,content:h,msg_type:1,extra:{card_type:"agent_question",summary_text:l}})},agentInvoke:async(a,c,d)=>this.platformInvoke(a,c,d),sendLocalActionResult:(a,c,d,l,h)=>{this.aibotHandle.sendLocalActionResult({action_id:a,status:c,...d!==void 0?{result:d}:{},...l?{error_code:l}:{},...h?{error_msg:h}:{}},e)},sendUpdateBindingCard:(a,c,d,l)=>{this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:c,cwd:d,...l?{meta:l}:{}})},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId};return new ae({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},r)}createClaudeAdapter(e){const t={sendReply:(n,o,r,a,c)=>{this.sendReplyByRuntimeConfig(n,o,r,a,c)},sendStreamChunk:(n,o,r,a,c,d,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,r,a,c,d,l)},sendMedia:(n,o,r,a,c,d,l)=>{this.aibotHandle.sendMedia({event_id:n,session_id:o,content:r,msg_type:2,quoted_message_id:c||void 0,client_msg_id:d||void 0,extra:l?{media_caption:a,...l}:{media_caption:a}})},sendEventResult:(n,o,r,a)=>{this.sendEventResultWithCleanup(n,o,r,a)},sendEventAck:(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})},agentInvoke:async(n,o,r)=>this.platformInvoke(n,o,r),sendLocalActionResult:(n,o,r,a,c)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...c?{error_msg:c}:{}},e)},sendToolUse:(n,o,r,a)=>{this.sendToolExecutionCard(n,o,D(r,a))},sendToolResult:(n,o,r,a)=>{this.sendToolExecutionCard(n,o,M(r,a))},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:(n,o,r)=>{this.sendGrixAgentQuestionCard(n,o,r)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"claude")},sendDirectMessage:n=>{this.aibotHandle.sendMsg({session_id:n.sessionId,msg_type:1,content:n.content,...n.clientMsgId?{client_msg_id:n.clientMsgId}:{},...n.quotedMessageId?{quoted_message_id:n.quotedMessageId}:{}})},onStatusLineUpdated:n=>{(n.rateLimits?.fiveHour||n.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=n);const o=this.bindingStore.get(e);o?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:o.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:n=>{this.aibotHandle.sendMcpFrame(e,n)}},s=this.config.adapterOptions??{},i={...s,sessionRuntimeResolver:()=>{const n=this.bindingStore.get(e),o=this.auditController.getSession(e);return{cwd:n?.cwd,modeId:this.resolveClaudeSessionModeId(e)??be.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:s.pluginDir,claudeSessionId:n?.claudeSessionId,...o?{audit:{enabled:!0,profile:o.options.profile,capture:o.options.capture}}:{},onSessionIdAssigned:r=>{this.bindingStore.setClaudeSessionId(e,r),this.sessionScanCache.invalidate()}}}};return new N({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},t)}createCodexAdapter(e){let t=null;const s={sendEventResult:(r,a,c)=>{if(a!=="responded"){this.sendEventResultWithCleanup(r,a,c);return}this.sendCtrl.sendFinalStreamChunkReliable(r,e,`codex_terminal_fence_${r}`,5e3,!0,!0).then(()=>this.sendEventResultWithCleanup(r,a,c),d=>{const l=`codex output acceptance fence failed: ${d instanceof Error?d.message:String(d)}`;this.sendEventResultWithCleanup(r,a==="responded"?"failed":a,a==="responded"?l:c)})},sendEventAck:(r,a)=>this.aibotHandle.sendEventAck({event_id:r,session_id:a,received_at:Date.now()}),sendCodexEvent:r=>{this.shouldDropCodexDisplayEvent(r.event_id,r.codex_method)||(this.captureCodexAuditOutput(r),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(r)),this.logCodexEventToConversation(r))},sendThinking:(r,a,c)=>{this.sendThinkingByRuntimeConfig(r,a,c)},sendRunError:(r,a,c)=>{this.sendRunErrorAsChunk(r,a,c)},sendUpdateBindingCard:(r,a,c,d)=>{const l={...d??{}};if(!l.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const h=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);h&&(l.rate_limits=h.rateLimits,l.rate_limit_primary_percent=h.primaryPercent,l.rate_limit_secondary_percent=h.secondaryPercent,l.rate_limit_primary_window_min=h.primaryWindowMin,l.rate_limit_secondary_window_min=h.secondaryWindowMin)}!l.provider_quota&&this.cachedProviderQuota?.success&&(l.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:a,cwd:c,...Object.keys(l).length>0?{meta:l}:{}})},agentInvoke:async(r,a,c)=>this.platformInvoke(r,a,c),sendLocalActionResult:(r,a,c,d,l)=>this.aibotHandle.sendLocalActionResult({action_id:r,status:a,...c!==void 0?{result:c}:{},...d?{error_code:d}:{},...l?{error_msg:l}:{}},e),sendSessionActivitySet:(r,a,c,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:r,kind:a,active:c,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:r=>{this.cachedRateLimits=r,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const c=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...r.primary.windowMinutes>0?{primary:r.primary}:{},...r.secondary.windowMinutes>0?{secondary:r.secondary}:{},sampledAt:c},rate_limit_primary_percent:r.primary.usedPercent,rate_limit_secondary_percent:r.secondary.usedPercent,rate_limit_primary_window_min:r.primary.windowMinutes,rate_limit_secondary_window_min:r.secondary.windowMinutes,credits:r.credits,...r.extras&&r.extras.length>0?{extra_limits:r.extras}:{},...t?.getEffortMeta()};this.cachedProviderQuota?.success&&(d.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:d})}},onContextWindowUpdated:r=>{if(!r)return;this.cachedCodexContextWindow=r,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:r,...t?.getEffortMeta()}})},onTokenUsageUpdated:r=>{r&&(this.cachedCodexTokenUsage=r,this.cachedCodexUsageSampledAtMs=Date.now())}},i=this.config.adapterOptions??{},n=this.globalConfigStore?.get(this.name),o=this.auditController.getAdapterPreparation(e);return t=new W({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...i,model:this.resolveCodexSessionModelId(e)??i.model,collaborationMode:this.bindingStore.getCodexModeId(e)??this.resolveCodexNewSessionGlobalDefault(e,n?.codexModeId,r=>this.bindingStore.setCodexModeId(e,r))??i.collaborationMode,reasoningEffort:this.bindingStore.getCodexReasoningEffort(e)??this.pinCodexGlobalDefault(n?.codexReasoningEffort,r=>this.bindingStore.setCodexReasoningEffort(e,r))??i.reasoningEffort,serviceTier:this.bindingStore.getCodexServiceTier(e)??this.resolveCodexNewSessionGlobalDefault(e,n?.codexServiceTier,r=>this.bindingStore.setCodexServiceTier(e,r))??i.serviceTier,sandboxMode:this.bindingStore.getCodexSandboxMode(e)??this.pinCodexGlobalDefault(n?.codexSandboxMode,r=>this.bindingStore.setCodexSandboxMode(e,r))??i.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...K(o?.options)?{rawApiCapture:{auditId:o.auditId,sessionId:e,spoolRootDir:T.join(L.data,"audit-replay","raw-spool")}}:{}}},s),t}createCodeWhaleAdapter(e){const t={sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),sendLocalActionResult:(i,n,o,r,a)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(i,n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:n,active:o,...r??{}})},sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=this.config.adapterOptions??{};return new de({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...s,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??s.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createPiAdapter(e){const t={sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o),p.info("bridge",`[pi] sendEventResult event=${i} status=${n}`)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),sendLocalActionResult:(i,n,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(i,n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:n,active:o,...r??{}})},sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c),a&&p.info("bridge",`[pi] sendFinalStreamChunk event=${i} seq=${r}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(i,n,o)=>{this.sendThinkingByRuntimeConfig(i,n,o)},sendRunError:(i,n,o,r,a)=>{this.sendStreamChunkByRuntimeConfig(i,n,`
|
|
1
|
+
import y from"node:path";import{tmpdir as U}from"node:os";import{createHash as M,randomUUID as R}from"node:crypto";import{ConnectionManager as q}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as N}from"../core/aibot/types.js";import{ClaudeAdapter as L}from"../adapter/claude/index.js";import{CodexAdapter as D}from"../adapter/codex/index.js";import"../adapter/claude/session-history.js";import"../adapter/codex/session-history.js";import"../adapter/pi/session-history.js";import"../adapter/opencode/session-history.js";import"../adapter/codewhale/session-history.js";import"../adapter/deepseek-harness/session-history.js";import{PiAdapter as W}from"../adapter/pi/index.js";import{AcpAdapter as S}from"../adapter/acp/index.js";import{OpenHumanAdapter as G}from"../adapter/openhuman/index.js";import{CursorAdapter as j}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as K}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as k}from"../adapter/opencode/index.js";import{AgyAdapter as H}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as z}from"../adapter/deepseek-harness/index.js";import{LOCAL_ACTION_TYPES as f,SESSION_CONTROL_ERROR_CODES as $,SESSION_CONTROL_VERBS as E,SESSION_MODE_IDS as J}from"../adapter/claude/protocol-contract.js";import{isAuditLocalActionType as Y}from"../audit/query/audit-local-actions.js";import{shouldEnableRawApiCapture as Q}from"../audit/raw-capture/types.js";import{buildWireSkills as X}from"../core/skill-sync/sync-state.js";import{executeEventTool as V}from"../core/mcp/event-tool-executor.js";import{fetchAvailableModels as Z}from"../adapter/claude/model-list.js";import{applyProxyEnv as ee,getProxyManager as te}from"../core/proxy/index.js";import{getKiroRelaySpawnEnv as ne}from"../core/proxy/kiro-relay.js";import{supportsKiroCwRelay as ie}from"../core/config/provider-env.js";import{buildProviderEnv as se}from"../core/config/provider-env.js";import{isClaudeDirectEnv as oe,stripGrixRelayEnv as re}from"../core/config/claude-direct-env.js";import{sweepNativeProviderResidue as ae}from"./native-provider-sweep.js";import{scanCodexSessions as de}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as le}from"../adapter/claude/session-scanner.js";import{resolveAcpAgentTypes as ce,scanAcpSessions as he,scanReasonixSessionTitles as ue}from"../adapter/acp/session-scanner.js";import{scanPiSessions as pe}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as ge}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as fe}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as me}from"../adapter/opencode/session-scanner.js";import{scanDshSessions as ve}from"../adapter/deepseek-harness/session-scanner.js";import{SessionScanCache as v,resolveCodexLeafDirs as _e,resolveClaudeLeafDirs as Se,resolveAcpLeafDirs as Ce,resolvePiLeafDirs as be,resolveCodeWhaleLeafDirs as Ae,resolveCursorLeafDirs as Ee,resolveOpenCodeLeafDirs as we,resolveDshLeafDirs as ye,resolveReasonixLeafDirs as Re}from"./session-scan-cache.js";import{log as h,ConversationLog as ke,AgentApiPacketLog as Te,BridgeEventLog as Pe,GRIX_PATHS as w}from"../core/log/index.js";import{routeSessionControlCommand as xe,routeSessionControlLocalAction as Me}from"./session-control-router.js";import{maybeOfferCliInstall as Le,handleCliInstallQuestionReply as De,handleCliInstallInteractionReply as He,runConfirmedCliInstall as $e}from"./cli-install-flow.js";import{handleEventCancel as Qe,waitForEventDone as Ie,handleAibotStop as Oe,killAndResumeStopSlot as Be,handleAibotRevoke as Fe}from"./event-stop.js";import{handleConfigureGatewayProvider as Ue,getAuditLocalActionHandler as qe,handleAuditLocalAction as Ne,handleConnectorRollback as We,getRelayStateSyncer as Ge,relayStateSyncOnConnect as je,reportRelayStateLocalChange as Ke,handleApplyRelayState as ze,fetchRelayCredential as Je,isSharedInstance as Ye}from"./connector-ops.js";import{unbindSession as Xe,handleUnbindTextCommand as Ve,handleUnbindLocalAction as Ze,handleListSessionsTextCommand as et,handleListSessionsLocalAction as tt,handleSyncHistoryLocalAction as nt}from"./session-list.js";import{handleCodexSessionControlOpen as it,handleSessionControlForPool as st,handleSessionControlLocalActionForPool as ot,handleCodexSessionControlLocalActionOpen as rt,handleCursorSessionControlLocalActionOpen as at,handlePiSessionControlOpen as dt,handlePiSessionControlRestart as lt,handlePiSessionControlRestartLocalAction as ct,syncOpenCodeBinding as ht,isWorkspaceFreeClient as ut,ensureDefaultBindingForWorkspaceFreeClient as pt,bindSessionForPool as gt,deferredCallbacks as ft,handleOpenHumanSessionControlOpen as mt,handleCodeWhaleSessionControlOpen as vt,handleCodeWhaleSessionControlLocalActionOpen as _t,handleDeepSeekSessionControlLocalActionOpen as St}from"./session-control-open.js";import{handleGetSessionUsage as Ct,handleThreadCompact as bt}from"./session-usage.js";import{handleSkillDeleteLocalAction as At,handleSkillUploadLocalAction as Et,handleSkillEnableLocalAction as wt,handleSkillRefreshLocalAction as yt,handleSkillDisableLocalAction as Rt,computeSkillReport as kt,reportSessionSkills as Tt,skillsSyncGroupKey as Pt,forceRefreshSkills as xt,adoptSkillsWireHashFromDisk as Mt,buildLibrarySkillsReport as Lt,skillLookupEnv as Dt}from"./skill-actions.js";import{normalizeClaudeModeId as Ht,handleExecCommandOptions as $t,resolveSessionModelId as Qt,resolveSessionModeId as It,resolveCursorSessionModeId as Ot,resolveClaudeSessionEffort as Bt,resolveClaudeSessionModeId as Ft,currentClaudeModeId as Ut,resolveCodexSessionModelId as qt,resolveCodexNewSessionGlobalDefault as Nt,pinCodexGlobalDefault as Wt,buildCursorToolbarMeta as Gt,buildAgyToolbarMeta as jt,buildAgyQuotaMeta as Kt,sendAgyBindingCard as zt,refreshAndPushAgyQuota as Jt,handleAgySetModel as Yt,buildClaudeToolbarMeta as Xt}from"./toolbar-meta.js";import{resolveProviderQuotaSource as Vt,maybeQueryProviderQuota as Zt,startProviderQuotaTimer as en,stopProviderQuotaTimer as tn,refreshAndPushProviderQuota as nn,pushProviderQuotaToBindings as sn,enrichProviderQuotaMeta as on,providerQuotaMetaPayload as rn,refreshProviderQuotaForSession as an,refreshQuotaAfterModelSwitch as dn,doRefreshQuotaAfterModelSwitch as ln}from"./provider-quota.js";import{handleGetRateLimits as cn,resolveRateLimitWakeSessionId as hn,wakeRateLimitSlot as un}from"./rate-limits.js";import{RevokeHandler as pn}from"./revoke-handler.js";import{AdapterPool as gn}from"./adapter-pool.js";import{parseSessionControlCommand as fn}from"./session-controller.js";import{isOpenSessionDirectiveMessage as mn,parseExecApprovalResolutionMessage as vn,parseAgentQuestionReplyMessage as _n}from"../core/protocol/interaction-parser.js";import{rejectUnusableAuditOptions as Sn}from"./inbound-audit-gate.js";import{interceptUnboundInboundEvent as Cn}from"./inbound-binding-gate.js";import{dispatchSessionControlTextCommand as bn}from"./text-command-session-control.js";import{dispatchSessionControlLocalAction as An}from"./local-action-session-control.js";import{handleCreateFolderLocalAction as En,handleFileListLocalAction as wn}from"./local-action-files.js";import{handleAcpToolbarLocalAction as yn,persistToolbarSelection as Rn}from"./local-action-toolbar.js";import{buildOpenedBindingResult as kn,ensureImportedAgentSession as Tn,hasDiskScanner as Pn,normalizePathForCompare as xn,providerKeyForAdapter as Mn,resolveAgentSessionId as Ln,resolveOrphanTitle as Dn,setResolvedAgentSessionId as Hn}from"./session-identity.js";import{buildDshOpenedToolbarMeta as $n,dshCatalogDataRoot as Qn}from"./dsh-toolbar.js";import{ensureSlotStarted as In,failSessionOpen as On,getClaudeWorkerStatus as Bn,refreshClaudeWorkerStatusCard as Fn,resolveCwdForBinding as Un}from"./session-open-helpers.js";import{handleAcpSetModel as qn,handleAcpSetMode as Nn,resolveAcpInitialDefaults as Wn}from"./acp-toolbar-persist.js";import{SessionBindingStore as Gn}from"../core/persistence/session-binding-store.js";import{serveLocalFile as jn}from"../core/files/index.js";import{uploadReplyFileToAgentMedia as Kn}from"../core/protocol/agent-api-media.js";import{ActiveEventStore as zn}from"../core/persistence/active-event-store.js";import{PendingEventCoordinator as Jn}from"./pending-event-coordinator.js";import{LifecycleBarrier as Yn}from"./lifecycle-barrier.js";import{QUEUE_COMPOSING_TTL_MS as Xn}from"./event-queue.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as Vn,applyConnectorRuntimeConfigPatch as Zn,extractConnectorRuntimeConfigPatch as ei}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as ti,SendController as ni}from"./send-controller.js";import{providerQuotaToRateLimits as ii,providerQuotaToCodexRateLimits as si}from"../core/provider-quota/index.js";import{buildToolUseCard as C,buildToolResultCard as b,buildDshOnlineToolCard as oi,buildLocalGrixCardLink as I}from"./tool-card-utils.js";import{planRawEventDelivery as ri,buildAuxiliaryDetailText as ai}from"./raw-event-delivery.js";import{DeferredEventManager as di}from"./deferred-events.js";import{buildAgentProbeResult as li,PROBE_CACHE_TTL_STATIC_MS as ci,PROBE_CACHE_TTL_FULL_MS as hi}from"./probe-helper.js";import{BridgeAuditController as ui}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as pi,NoopAuditProducer as gi}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as O,AuditPreparationFailedError as fi,AuditTurnScopeUnsupportedError as mi}from"../audit/core/audit-state.js";import{extractAuditOptions as B,freezeAuditOptions as vi,stripAuditOptions as _i}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as Si}from"../audit/core/audit-session-registry.js";const Ci=600*1e3,F=1800*1e3,bi=60*1e3,Ai=4e3;function Ei(x,e,i){const r=M("sha256").update(x).update("\0").update(e).update("\0").update(i).digest("hex");return y.join(w.data,"audit-source","reasonix",`${r}.jsonl`)}const T=new Set(["claude","acp","agy","cursor","codex","deepseek-harness"]),wi=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),P=3;class oo{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new pn;sessionBindings=new Map;deferredMgr;sendCtrl=new ni(Vn);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;pendingCliInstalls=new Map;agentDeletedHandler=null;shareSetHandler=null;skillSyncHandler=null;providerConfigHandler=null;relayStateApplyPorts=null;relayStateSyncer=null;agentProfile={agentName:"",introduction:""};agentSystemPrompt="";activeEventStore;pendingEvents;pendingStartedEventIds=new Set;lifecycleBarrier=new Yn;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;cachedProviderQuotaKey=null;sessionProviderHints=new Map;sessionProviderQuotas=new Map;sessionProviderMeta=new Map;lastModelSwitchQuotaRefresh=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";lastReportedSkillsWireHash="";conversationLog=null;packetLog=null;providerQuotaTimer=null;eventSessionIndex=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;auditController;auditLocalActionHandler=null;sessionScanCache;reasonixTitleScan=null;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const i=Number(e);return i>0&&Date.now()-i<=bi}resolveProviderQuotaSource(e){return Vt(this,e)}maybeQueryProviderQuota(e=!1,i){return Zt(this,e,i)}startProviderQuotaTimer(){en(this)}stopProviderQuotaTimer(){tn(this)}refreshAndPushProviderQuota(e=!1){return nn(this,e)}pushProviderQuotaToBindings(e,i=!1){sn(this,e,i)}enrichProviderQuotaMeta(e,i="standard",r=this.cachedProviderQuota,n=this.cachedProviderQuotaSampledAtMs){return on(this,e,i,r,n)}providerQuotaMetaPayload(e,i,r){return rn(this,e,i,r)}refreshProviderQuotaForSession(e,i,r){return an(this,e,i,r)}refreshQuotaAfterModelSwitch(e,i,r){dn(this,e,i,r)}doRefreshQuotaAfterModelSwitch(e,i,r){return ln(this,e,i,r)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,i=this.cachedCodexContextWindow,r=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:i,tokenUsage:r,hasData:!!(e||i||r)}}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,wsConnected:this.aibotHandle?.status==="ready",exhausted:this.pool?[...this.pool.getAllSlots()].some(i=>i.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}hasPendingOrBackgroundWork(){return this.lifecycleBarrier.hasActiveAdmissions()||(this.pool?.hasPendingOrBackgroundWork()??!1)}async waitUntilLifecycleIdle(e){const i=()=>this.lifecycleBusyChecker?.()??this.hasPendingOrBackgroundWork();if(i()){const r=Math.round(F/6e4);h.info(this.name,`${e}: active tasks detected, waiting up to ${r}min until idle before restart (admission stays open while waiting)`);const n=Date.now()+F,t=5e3,s=600*1e3;let o=Date.now();for(;i()&&!this.stopped;){if(Date.now()>=n)return h.warn(this.name,`${e}: idle wait exceeded ${r}min; abandoning this restart. Admission was never closed, so agents kept serving. A busy state that never clears usually means an adapter leaked its busy flag \u2014 check for a turn that never completed.`),!1;await new Promise(a=>setTimeout(a,t)),Date.now()-o>=s&&(o=Date.now(),h.info(this.name,`${e}: still waiting for active tasks to finish before restart`))}}return this.stopped?!1:(this.closeLifecycleAdmissionForRestart(),i()?(h.warn(this.name,`${e}: work arrived while closing admission; reopening and abandoning this restart`),this.reopenLifecycleAdmissionAfterAbort(),!1):(h.info(this.name,`${e}: all tasks completed, proceeding with restart`),!0))}reopenLifecycleAdmissionAfterAbort(){if(this.lifecycleAdmissionRestorer){this.lifecycleAdmissionRestorer();return}this.openLifecycleAdmission()}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,h.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 i=0,r=!1;for(const n of e){if(this.hasPendingWork())return this.relayEnvStale=!0,h.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let t=!1;await this.pool.removeSlot(n.sessionId).catch(s=>{r=!0,t=!0,h.warn(this.name,`failed to recycle adapter slot ${n.sessionId} after relay change: ${s}`)}),t||(i+=1)}return i>0&&h.info(this.name,`recycled ${i} adapter slot(s) so the new Grix relay env takes effect`),r?(this.relayEnvStale=!0,!1):(this.relayEnvStale=!1,this.relayEnvSettledHandler?.(),!0)}setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}providerResolver;setProviderResolver(e){this.providerResolver=e}hasStaleRelayEnv(){return this.relayEnvStale}markRelayEnvStale(){this.relayEnvStale=!0}async probe(e={}){const i=e.conversation?"full":"static",r=e.conversation?hi:ci;if(!e.fresh){const a=this.probeCache.get(i);if(a&&Date.now()-a.sampledAt<r)return{...a.result,cached:!0}}const n=this.config.adapterType??"acp",t=this.createAdapter(n,"__probe__"),s=e.conversation&&n==="acp"?()=>this.runAcpConversationProbe(t,e.timeoutMs??1e4):void 0;let o;try{o=await li({adapter:t,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:n,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:s})}finally{t.stop().catch(()=>{})}return this.probeCache.set(i,{result:o,sampledAt:o.probed_at}),o}async runAcpConversationProbe(e,i){const r=Date.now(),n="__probe__",t=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=this.config.agent.cwd||U(),o=()=>Date.now()-r;try{await e.start()}catch(u){return{attempted:!0,ok:!1,latency_ms:o(),error:{code:"conversation_failed",message:`start failed: ${u instanceof Error?u.message:String(u)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:o(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof S)try{await e.bindSession(n,s)}catch{}let a=null;const l=new Promise(u=>{a=g=>{g===t&&u()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:t,session_id:n,content:"ping",msg_id:t}),e.deliverStopEvent(t,n);let d=null;const c=await Promise.race([l.then(()=>!1),new Promise(u=>{d=setTimeout(()=>u(!0),i)})]);return d&&clearTimeout(d),a&&e.removeListener("eventDone",a),c?{attempted:!0,ok:!1,latency_ms:o(),error:{code:"conversation_timeout",message:`no eventDone within ${i}ms`}}:{attempted:!0,ok:!0,latency_ms:o()}}constructor(e,i,r=new gi){this.config=e,this.auditController=new ui(r,{onAuditState:t=>{try{this.aibotHandle.sendAuditState(O(t,Date.now()))}catch{}}}),pi(r)&&r.addJobSettledHandler((t,s)=>{this.auditController.handleJobSettled(t,s)}),this.name=e.name;const n=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(ti[n]),this.aibotConfig={...e.aibot,...n==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","set_reasoning_effort","thread_compact","get_agent_global_config",...N]}:{}},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 ke(e.logDir):null,this.packetLog=e.logDir?new Te(e.logDir):null,this.bindingStore=new Gn(e.bindingsPath,e.legacyBindingsPath),this.bindingStore.load(),this.globalConfigStore=i??null,this.deferredMgr=new di(this.name),this.activeEventStore=e.activeEventStorePath?new zn(e.activeEventStorePath):null,this.pendingEvents=new Jn(e.pendingEventStorePath),n==="codex")this.sessionScanCache=new v(de,_e);else if(n==="claude")this.sessionScanCache=new v(le,Se);else if(n==="pi"){const t=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new v(()=>pe(void 0,t),()=>be(void 0,t))}else if(n==="codewhale")this.sessionScanCache=new v(ge,Ae);else if(n==="cursor")this.sessionScanCache=new v(fe,Ee);else if(n==="opencode")this.sessionScanCache=new v(me,we);else if(n==="deepseek-harness"){const t=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new v(()=>ve(t),()=>ye(t))}else if(n==="agy")this.sessionScanCache=new v(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new v(ue,Re));const t=ce(e.aibot.clientType);this.sessionScanCache=t?new v(()=>he(void 0,t),()=>Ce(void 0,t)):new v(()=>[],()=>[])}}async start(){if(this.stopped)throw new Error("agent start aborted");if(await ae({agentName:this.name,adapterType:this.config.adapterType??"acp",command:this.config.agent.command,piConfigDir:this.config.agent.env?.PI_CODING_AGENT_DIR,dshHome:typeof this.config.adapterOptions?.dshHome=="string"?this.config.adapterOptions.dshHome:this.config.agent.env?.DSH_HOME,hasProvider:!!this.config.agent.provider,boundCwds:[...this.bindingStore.entries()].map(([,t])=>String(t.cwd??""))}).then(t=>{t.length>0&&h.info(this.name,`restored native provider config after relay disable: ${t.join(", ")}`)}).catch(t=>{h.warn(this.name,`native provider residue sweep failed: ${t instanceof Error?t.message:String(t)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await Z().catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}if(this.stopped)throw new Error("agent start aborted");const e=!!(this.config.providerBaseUrl&&this.config.providerApiKey||this.config.agent.provider?.baseUrl&&this.config.agent.provider?.apiKey),i=(this.config.adapterType??"acp")==="pi",r=(this.config.adapterType??"acp")==="opencode";if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(i||r)&&this.startProviderQuotaTimer(),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),(this.config.adapterType??"acp")==="opencode"&&this.maybeQueryProviderQuota().catch(()=>{}),this.stopped)throw new Error("agent start aborted");if(await this.connectAibot(),this.stopped)throw this.aibotHandle?.disconnect(),new Error("agent start aborted");this.sendCtrl.bind(this.aibotHandle);const n=this.config.adapterType??"acp";if(this.pool=new gn({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},t=>{const s=this.createAdapter(n,t);return s instanceof S&&s.on("acpSessionReady",o=>{this.bindingStore.setAcpSessionId(t,o),this.sessionScanCache.invalidate()}),s},(t,s)=>{this.aibotHandle.sendEventAck({event_id:t,session_id:s,received_at:Date.now()})}),this.pool.setEventStateHandler((t,s,o,a)=>{if(h.info(this.name,`[queue-debug] send event_state session=${s} event=${t} state=${o} queue_pos=${a?.queue_position??""} queue_total=${a?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:t,session_id:s,state:o,content_preview:a?.content_preview,content:a?.content,queue_position:a?.queue_position,queue_total:a?.queue_total,actions:a?.actions,reason:a?.reason,held:a?.held,held_reason:a?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(s),o==="running"&&(this.pendingStartedEventIds.add(t),this.pendingEvents.remove(t).catch(l=>{h.warn(this.name,`Failed to remove running event from pending store event=${t}: ${l instanceof Error?l.message:String(l)}`)})),o==="canceled"||o==="failed"){const l=o==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:t,status:l,msg:a?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(t,l,a?.reason,{queueTerminalState:o}),this.discardEventTrackingState(t),this.pendingEvents.remove(t).catch(d=>{h.warn(this.name,`Failed to remove queued terminal event from pending store event=${t}: ${d instanceof Error?d.message:String(d)}`)})}}),this.pool.setQueueComposingHandler((t,s,o)=>{this.aibotHandle.sendSessionActivitySet({session_id:t,kind:"composing",active:s,...s?{ttl_ms:Xn,ref_event_id:o}:{}})}),this.pool.setInternalErrorHandler(t=>{this.handleSessionInternalError(t).catch(s=>{h.error(this.name,`[recovery] handleSessionInternalError failed event=${t.eventId} session=${t.sessionId}: ${s instanceof Error?s.message:String(s)}`)})}),this.pool.setEventStartedHandler((t,s)=>{if(this.reportSessionSkills(s),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(s,"busy");const o=this.bindingStore.get(s);o?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:"busy",cwd:o.cwd,meta:this.buildClaudeToolbarMeta(s)})}),this.pool.setEventDoneHandler((t,s)=>{this.markAuditAdapterClosed(t,s);const o=this.config.adapterType??"acp";if(o==="claude"){this.claudeWorkerStatus.set(s,"ready");const a=this.bindingStore.get(s);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(s)})}else if(o==="agy"){const a=this.bindingStore.get(s);if(a?.cwd){const l=this.buildAgyToolbarMeta(s),d=l?.available_models??[];h.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${s} model_id=${String(l?.model_id??"")} available_models=${d.length} meta_keys=${l?Object.keys(l).join(","):"<none>"}`),this.sendAgyBindingCard(s,a.cwd,l),this.refreshAndPushAgyQuota(s)}else h.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${s}`)}}),this.pool.setSessionActivityHandler((t,s,o)=>{const a=this.selfDrivenSessions.has(t),l=this.selfDrivenLabels.get(t);s?(this.selfDrivenSessions.add(t),o&&this.selfDrivenLabels.set(t,o),this.aibotHandle.sendSessionActivitySet({session_id:t,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(t),this.selfDrivenLabels.delete(t),a&&this.aibotHandle.sendSessionActivitySet({session_id:t,kind:"composing",active:!1})),(a!==s||s&&o!==void 0&&o!==l)&&this.pushQueueSnapshotForSession(t)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),h.info(this.name,`Ready (adapter: ${n}, poolMax: ${this.config.poolMaxSize??20})`)}requestStop(){this.stopped=!0,this.lifecycleBarrier.close(),this.startupAbortController.abort(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown")}async stop(e){if(e?.dropPendingEvents&&(this.dropPendingEventsRequested=!0),this.requestStop(),!this.stopPromise){const i=this.stopOnce();this.stopPromise=i,i.catch(()=>{this.stopPromise===i&&(this.stopPromise=null)})}await this.stopPromise,this.dropPendingEventsRequested&&!this.pendingEventsDropped&&await this.dropPendingEventsBestEffort()}async stopOnce(){this.lifecycleBarrier.close(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown");const e=this.pool?.collectActiveEventIds()??[],i=new Map(e.map(o=>[o,this.eventSessionIndex.get(o)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const o of e)h.info(this.name,`Canceling active event on shutdown: ${o}`),this.sendEventResultWithCleanup(o,"canceled","process shutting down");e.length>0&&await new Promise(o=>setTimeout(o,100)),this.pool?.clearActiveEventsForShutdown();for(const o of e){const a=i.get(o),l=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(o,l?.adapter.takeAuditBoundary?.(o)??{processTerminated:!0})}const r=this.deferredMgr.getAllDeferredEntries(),n=this.pool?.drainAllQueuedEvents()??[],t=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...r.map(o=>({kind:"deferred",channel:o.channel,sessionId:o.sessionId,event:o.event})),...n.map(o=>({kind:"queued",event:o}))]);let s=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(o){h.warn(this.name,`Failed to clear pending event store on removal: ${o instanceof Error?o.message:String(o)}`)}else try{s=await this.pendingEvents.mergeForShutdown(t)}catch(o){h.error(this.name,`Failed to persist pending events on shutdown: ${o instanceof Error?o.message:String(o)}`)}if(!s)for(const o of t){const a=o.event;h.info(this.name,`Failing pending event on shutdown: ${a.event_id}`),this.sendEventResultWithCleanup(a.event_id,"failed","process shutting down"),this.auditController.markAdapterClosed(a.event_id,{adapterNotStarted:!0,processTerminated:!0})}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(),this.auditController.dispose()}async dropPendingEventsBestEffort(){try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(e){h.warn(this.name,`Failed to clear pending event store on removal: ${e instanceof Error?e.message:String(e)}`)}}resolveSpawnEnv(){const e=this.providerResolver?this.providerResolver():this.config.agent.provider,i=se(this.config.agent.clientType,e),r=this.config.agent.env;let n=Object.keys(i).length>0?{...i,...r}:r;if(oe(i)){const t=te()?.getRuntimeInfo(),s={...r??{},...i},o=re(s,{proxyUrl:t?.proxyUrl,caCertPath:t?.caCertPath,caBundlePath:t?.caBundlePath});return delete o.ANTHROPIC_API_KEY,delete o.CLAUDE_CODE_OAUTH_TOKEN,o}if(ie(this.config.agent.clientType)){const t=ne(this.name);t&&(n={...n??{},...t})}return ee(n,this.name,this.config.agent.clientType)}createAdapter(e,i){switch(e){case"claude":return this.createClaudeAdapter(i);case"codex":return this.createCodexAdapter(i);case"pi":return this.createPiAdapter(i);case"openhuman":return this.createOpenHumanAdapter(i);case"codewhale":return this.createCodeWhaleAdapter(i);case"cursor":return this.createCursorAdapter(i);case"opencode":return this.createOpenCodeAdapter(i);case"agy":return this.createAgyAdapter(i);case"deepseek-harness":return this.createDshAdapter(i);default:return this.createAcpAdapter(i)}}createDshAdapter(e){const i={sendStreamChunk:(t,s,o,a,l,d,c)=>{this.sendStreamChunkByRuntimeConfig(t,s,o,a,l,d,c)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",Ai),sendThinking:(t,s,o)=>this.sendThinkingByRuntimeConfig(t,s,o),sendEventResult:(t,s,o,a)=>{this.sendEventResultWithCleanup(t,s,o,void 0,a)},sendRawEventEnvelope:(t,s,o,a)=>{const l=oi(o);if(l){this.sendToolExecutionCard(t,s,l);return}this.deliverRawEventEnvelope(t,s,o,"deepseek",a)},sendLocalActionResult:(t,s,o,a,l)=>{this.aibotHandle.sendLocalActionResult({action_id:t,status:s,...o!==void 0?{result:o}:{},...a?{error_code:a}:{},...l?{error_msg:l}:{}},e)},sendPermissionCard:t=>{this.sendGrixApprovalCard(t,"deepseek")},sendUpdateBindingCard:(t,s,o,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:s,cwd:o,meta:a})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:t=>this.maybeQueryProviderQuota(t===!0,{providerId:"deepseek"}),agentInvoke:async(t,s,o)=>this.platformInvoke(t,s,o),eventToolInvoke:async(t,s)=>this.invokeDshEventTool(t,s)},r=M("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),n=this.config.adapterOptions??{};return new z({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:n},i,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:y.join(w.data,"deepseek-harness",r),...typeof n.cordisPath=="string"?{cordisPath:n.cordisPath}:{},...typeof n.defaultModel=="string"?{defaultModel:n.defaultModel}:{},...typeof n.maxTokens=="number"?{maxTokens:n.maxTokens}:{},...typeof n.maxLineBytes=="number"?{maxLineBytes:n.maxLineBytes}:{},...n.integrationMode==="embedded_jsonrpc"||n.integrationMode==="profile_bridge"?{integrationMode:n.integrationMode}:{},...typeof n.dshHome=="string"?{dshHome:n.dshHome}:{},...typeof n.dshProfile=="string"?{dshProfile:n.dshProfile}:{},...typeof n.autoInstallBridge=="boolean"?{autoInstallBridge:n.autoInstallBridge}:{},...typeof n.autoStartProfile=="boolean"?{autoStartProfile:n.autoStartProfile}:{},...this.config.agent.provider?{provider:this.config.agent.provider}:{},promptTimeoutMs:this.config.promptTimeoutMs})}createCursorAdapter(e){const i={...this.config.adapterOptions??{}};i.bindingStore=this.bindingStore,i.aibotSessionId=e;const r=this.bindingStore.get(e),n=this.resolveSessionModelId(e);n&&(i.model=n);const t=this.resolveCursorSessionModeId(e),s=t??"full_auto";t||this.bindingStore.setCursorModeId(e,s),i.mode=s,r?.cwd&&(i.workspace=r.cwd);const o={sendStreamChunk:(a,l,d,c,u,g,p)=>{this.sendStreamChunkByRuntimeConfig(a,l,d,c,u,g,p)},sendEventResult:(a,l,d)=>{this.sendEventResultWithCleanup(a,l,d)},sendEventAck:(a,l)=>{this.aibotHandle.sendEventAck({event_id:a,session_id:l,received_at:Date.now()})},sendRawEventEnvelope:(a,l,d)=>{this.deliverRawEventEnvelope(a,l,d,"cursor",this.buildCursorRawEventFallbackText(d))},sendAgentQuestionCard:(a,l,d)=>{const c=d.questions.map(g=>g.header).join(", "),u=I(`[Agent Question] ${d.request_id}`,"agent_question",d);this.aibotHandle.sendText({event_id:a,session_id:l,content:u,msg_type:1,extra:{card_type:"agent_question",summary_text:c}})},agentInvoke:async(a,l,d)=>this.platformInvoke(a,l,d),sendLocalActionResult:(a,l,d,c,u)=>{this.aibotHandle.sendLocalActionResult({action_id:a,status:l,...d!==void 0?{result:d}:{},...c?{error_code:c}:{},...u?{error_msg:u}:{}},e)},sendUpdateBindingCard:(a,l,d,c)=>{this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:l,cwd:d,...c?{meta:c}:{}})},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId};return new j({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},o)}createClaudeAdapter(e){const i={sendReply:(t,s,o,a,l)=>{this.sendReplyByRuntimeConfig(t,s,o,a,l)},sendStreamChunk:(t,s,o,a,l,d,c)=>{this.sendStreamChunkByRuntimeConfig(t,s,o,a,l,d,c)},sendMedia:(t,s,o,a,l,d,c)=>{this.aibotHandle.sendMedia({event_id:t,session_id:s,content:o,msg_type:2,quoted_message_id:l||void 0,client_msg_id:d||void 0,extra:c?{media_caption:a,...c}:{media_caption:a}})},sendEventResult:(t,s,o,a)=>{this.sendEventResultWithCleanup(t,s,o,a)},sendEventAck:(t,s)=>{this.aibotHandle.sendEventAck({event_id:t,session_id:s,received_at:Date.now()})},agentInvoke:async(t,s,o)=>this.platformInvoke(t,s,o),sendLocalActionResult:(t,s,o,a,l)=>{this.aibotHandle.sendLocalActionResult({action_id:t,status:s,...o!==void 0?{result:o}:{},...a?{error_code:a}:{},...l?{error_msg:l}:{}},e)},sendToolUse:(t,s,o,a)=>{this.sendToolExecutionCard(t,s,C(o,a))},sendToolResult:(t,s,o,a)=>{this.sendToolExecutionCard(t,s,b(o,a))},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:(t,s,o)=>{this.sendGrixAgentQuestionCard(t,s,o)},sendPermissionCard:t=>{this.sendGrixApprovalCard(t,"claude")},sendDirectMessage:t=>{this.aibotHandle.sendMsg({session_id:t.sessionId,msg_type:1,content:t.content,...t.clientMsgId?{client_msg_id:t.clientMsgId}:{},...t.quotedMessageId?{quoted_message_id:t.quotedMessageId}:{}})},onStatusLineUpdated:t=>{(t.rateLimits?.fiveHour||t.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=t);const s=this.bindingStore.get(e);s?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:s.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:t=>{this.aibotHandle.sendMcpFrame(e,t)}},r=this.config.adapterOptions??{},n={...r,sessionRuntimeResolver:()=>{const t=this.bindingStore.get(e),s=this.auditController.getSession(e);return{cwd:t?.cwd,modeId:this.resolveClaudeSessionModeId(e)??J.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:r.pluginDir,claudeSessionId:t?.claudeSessionId,...s?{audit:{enabled:!0,profile:s.options.profile,capture:s.options.capture}}:{},onSessionIdAssigned:o=>{this.bindingStore.setClaudeSessionId(e,o),this.sessionScanCache.invalidate()}}}};return new L({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:n},i)}createCodexAdapter(e){let i=null;const r={sendEventResult:(o,a,l)=>{if(a!=="responded"){this.sendEventResultWithCleanup(o,a,l);return}this.sendCtrl.sendFinalStreamChunkReliable(o,e,`codex_terminal_fence_${o}`,5e3,!0,!0).then(()=>this.sendEventResultWithCleanup(o,a,l),d=>{const c=`codex output acceptance fence failed: ${d instanceof Error?d.message:String(d)}`;this.sendEventResultWithCleanup(o,a==="responded"?"failed":a,a==="responded"?c:l)})},sendEventAck:(o,a)=>this.aibotHandle.sendEventAck({event_id:o,session_id:a,received_at:Date.now()}),sendCodexEvent:o=>{this.shouldDropCodexDisplayEvent(o.event_id,o.codex_method)||(this.captureCodexAuditOutput(o),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(o)),this.logCodexEventToConversation(o))},sendThinking:(o,a,l)=>{this.sendThinkingByRuntimeConfig(o,a,l)},sendRunError:(o,a,l)=>{this.sendRunErrorAsChunk(o,a,l)},sendUpdateBindingCard:(o,a,l,d)=>{const c={...d??{}};if(!c.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const u=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);u&&(c.rate_limits=u.rateLimits,c.rate_limit_primary_percent=u.primaryPercent,c.rate_limit_secondary_percent=u.secondaryPercent,c.rate_limit_primary_window_min=u.primaryWindowMin,c.rate_limit_secondary_window_min=u.secondaryWindowMin)}!c.provider_quota&&this.cachedProviderQuota?.success&&(c.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:a,cwd:l,...Object.keys(c).length>0?{meta:c}:{}})},agentInvoke:async(o,a,l)=>this.platformInvoke(o,a,l),sendLocalActionResult:(o,a,l,d,c)=>this.aibotHandle.sendLocalActionResult({action_id:o,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e),sendSessionActivitySet:(o,a,l,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:o,kind:a,active:l,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:o=>{this.cachedRateLimits=o,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const l=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...o.primary.windowMinutes>0?{primary:o.primary}:{},...o.secondary.windowMinutes>0?{secondary:o.secondary}:{},sampledAt:l},rate_limit_primary_percent:o.primary.usedPercent,rate_limit_secondary_percent:o.secondary.usedPercent,rate_limit_primary_window_min:o.primary.windowMinutes,rate_limit_secondary_window_min:o.secondary.windowMinutes,credits:o.credits,...o.extras&&o.extras.length>0?{extra_limits:o.extras}:{},...i?.getEffortMeta()};this.cachedProviderQuota?.success&&(d.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:d})}},onContextWindowUpdated:o=>{if(!o)return;this.cachedCodexContextWindow=o,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:o,...i?.getEffortMeta()}})},onTokenUsageUpdated:o=>{o&&(this.cachedCodexTokenUsage=o,this.cachedCodexUsageSampledAtMs=Date.now())}},n=this.config.adapterOptions??{},t=this.globalConfigStore?.get(this.name),s=this.auditController.getAdapterPreparation(e);return i=new D({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...n,model:this.resolveCodexSessionModelId(e)??n.model,collaborationMode:this.bindingStore.getCodexModeId(e)??this.resolveCodexNewSessionGlobalDefault(e,t?.codexModeId,o=>this.bindingStore.setCodexModeId(e,o))??n.collaborationMode,reasoningEffort:this.bindingStore.getCodexReasoningEffort(e)??this.pinCodexGlobalDefault(t?.codexReasoningEffort,o=>this.bindingStore.setCodexReasoningEffort(e,o))??n.reasoningEffort,serviceTier:this.bindingStore.getCodexServiceTier(e)??this.resolveCodexNewSessionGlobalDefault(e,t?.codexServiceTier,o=>this.bindingStore.setCodexServiceTier(e,o))??n.serviceTier,sandboxMode:this.bindingStore.getCodexSandboxMode(e)??this.pinCodexGlobalDefault(t?.codexSandboxMode,o=>this.bindingStore.setCodexSandboxMode(e,o))??n.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...Q(s?.options)?{rawApiCapture:{auditId:s.auditId,sessionId:e,spoolRootDir:y.join(w.data,"audit-replay","raw-spool")}}:{}}},r),i}createCodeWhaleAdapter(e){const i={sendEventResult:(n,t,s)=>{this.sendEventResultWithCleanup(n,t,s)},sendEventAck:(n,t)=>this.aibotHandle.sendEventAck({event_id:n,session_id:t,received_at:Date.now()}),sendStreamChunk:(n,t,s,o,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,t,s,o,a,l)},sendUpdateBindingCard:(n,t,s,o)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:t,cwd:s,...this.providerQuotaMetaPayload(o,n,s)}),sendLocalActionResult:(n,t,s,o,a)=>this.aibotHandle.sendLocalActionResult({action_id:n,status:t,...s!==void 0?{result:s}:{},...o?{error_code:o}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(n,t,s,o)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:t,active:s,...o??{}})},sendToolUse:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,C(s,o))},sendToolResult:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,b(s,o))},agentInvoke:async(n,t,s)=>this.platformInvoke(n,t,s),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new K({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...r,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??r.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},i)}createPiAdapter(e){const i={sendEventResult:(n,t,s)=>{this.sendEventResultWithCleanup(n,t,s),h.info("bridge",`[pi] sendEventResult event=${n} status=${t}`)},sendEventAck:(n,t)=>this.aibotHandle.sendEventAck({event_id:n,session_id:t,received_at:Date.now()}),sendUpdateBindingCard:(n,t,s,o)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:t,cwd:s,...this.providerQuotaMetaPayload(o,n,s)}),agentInvoke:async(n,t,s)=>this.platformInvoke(n,t,s),sendLocalActionResult:(n,t,s,o,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:t,...s!==void 0?{result:s}:{},...o?{error_code:o}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(n,t,s,o)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:t,active:s,...o??{}})},sendToolUse:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,C(s,o))},sendToolResult:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,b(s,o))},sendStreamChunk:(n,t,s,o,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,t,s,o,a,l),a&&h.info("bridge",`[pi] sendFinalStreamChunk event=${n} seq=${o}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(n,t,s)=>{this.sendThinkingByRuntimeConfig(n,t,s)},sendRunError:(n,t,s,o,a)=>{this.sendStreamChunkByRuntimeConfig(n,t,`
|
|
2
2
|
|
|
3
|
-
Error: ${
|
|
3
|
+
Error: ${s}`,o,!1,a)},getAgentProfile:()=>this.agentProfile},r=this.config.adapterOptions??{};return new W({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...r,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},i)}createOpenHumanAdapter(e){const i={sendStreamChunk:(n,t,s,o,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,t,s,o,a,l)},sendFinalStreamChunkReliable:async(n,t,s,o)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(n,t,o)}catch(a){throw h.error("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${n}: ${a}`),a}},sendEventResult:(n,t,s)=>{this.sendEventResultWithCleanup(n,t,s),h.info("bridge",`[openhuman] sendEventResult event=${n} status=${t}`)},sendEventAck:(n,t)=>this.aibotHandle.sendEventAck({event_id:n,session_id:t,received_at:Date.now()}),sendToolUse:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,C(s,o))},sendToolResult:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,b(s,o))},sendThinking:(n,t,s)=>{this.sendThinkingByRuntimeConfig(n,t,s)},sendRunError:(n,t,s)=>{this.sendStreamChunkByRuntimeConfig(n,t,`
|
|
4
4
|
|
|
5
|
-
Error: ${
|
|
5
|
+
Error: ${s}`,0,!1)},sendUpdateBindingCard:(n,t,s,o)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:t,cwd:s,...this.providerQuotaMetaPayload(o,n,s)}),agentInvoke:async(n,t,s)=>this.platformInvoke(n,t,s),sendLocalActionResult:(n,t,s,o,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:t,...s!==void 0?{result:s}:{},...o?{error_code:o}:{},...a?{error_msg:a}:{}},e)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new G({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},i,{port:r.port,host:r.host,workspaceDir:r.workspace_dir,sessionToken:r.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const i={sendStreamChunk:(n,t,s,o,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,t,s,o,a,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(n,t,s)=>{this.sendEventResultWithCleanup(n,t,s),h.info("bridge",`[opencode] sendEventResult event=${n} status=${t}`)},sendEventAck:(n,t)=>this.aibotHandle.sendEventAck({event_id:n,session_id:t,received_at:Date.now()}),sendToolUse:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,C(s,o))},sendToolResult:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,b(s,o))},sendThinking:(n,t,s)=>{this.sendThinkingByRuntimeConfig(n,t,s)},sendRunError:(n,t,s)=>{this.sendRunErrorAsChunk(n,t,s)},sendUpdateBindingCard:(n,t,s,o)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:t,cwd:s,...this.providerQuotaMetaPayload(o,n,s)}),agentInvoke:async(n,t,s)=>this.platformInvoke(n,t,s),sendLocalActionResult:(n,t,s,o,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:t,...s!==void 0?{result:s}:{},...o?{error_code:o}:{},...a?{error_msg:a}:{}},e)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"opencode")},sendAgentQuestionCard:(n,t,s)=>{this.sendGrixAgentQuestionCard(n,t,s)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new k({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},i,{port:r.port,hostname:r.hostname,model:r.model??this.resolveSessionModelId(e),agent:r.agent,permissionPolicy:r.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const i={sendStreamChunk:(n,t,s,o,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,t,s,o,a,l)},sendEventResult:(n,t,s)=>{this.sendEventResultWithCleanup(n,t,s)},sendEventAck:(n,t)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:t,received_at:Date.now()})},agentInvoke:async(n,t,s)=>this.platformInvoke(n,t,s),forceCompleteInternalEvent:(n,t)=>{this.pool.eventComplete(n,t),this.pushQueueSnapshotForSession(t)},persistConversationId:(n,t)=>{this.bindingStore.setAgyConversationId(n,t)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=n=>{const t=this.bindingStore.get(n);return{cwd:t?.cwd,modelId:this.resolveSessionModelId(n),conversationId:t?.agyConversationId}};return new H({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},i,r)}createAcpAdapter(e){const i=this.isAcpRawTransportEnabled(),r={sendStreamChunk:(d,c,u,g,p,_,A)=>{this.sendStreamChunkByRuntimeConfig(d,c,u,g,p,_,A)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(d,c,u)=>{this.sendEventResultWithCleanup(d,c,u)},sendEventAck:(d,c)=>{this.aibotHandle.sendEventAck({event_id:d,session_id:c,received_at:Date.now()})},agentInvoke:async(d,c,u)=>this.platformInvoke(d,c,u),sendLocalActionResult:(d,c,u,g,p)=>{this.aibotHandle.sendLocalActionResult({action_id:d,status:c,...u!==void 0?{result:u}:{},...g?{error_code:g}:{},...p?{error_msg:p}:{}},e)},sendRawEventEnvelope:(d,c,u)=>{this.sendAcpRawEventEnvelope(d,c,u)},sendToolUse:(d,c,u,g)=>{if(i){this.sendAcpRawEventEnvelope(d,c,{type:"tool_use",payload:{tool_name:u,tool_input:g??""}});return}this.sendToolExecutionCard(d,c,C(u,g))},sendToolResult:(d,c,u,g)=>{this.sendToolExecutionCard(d,c,b(u,g))},sendThinking:(d,c,u)=>{this.sendThinkingByRuntimeConfig(d,c,u)},sendRunError:(d,c,u)=>{this.sendStreamChunkByRuntimeConfig(d,c,`
|
|
6
6
|
|
|
7
|
-
Error: ${h}`,1,!1)},sendAgentQuestionCard:(d,l,h)=>{this.sendGrixAgentQuestionCard(d,l,h)},sendPermissionCard:d=>{p.info("bridge","sendPermissionCard callback entered",{rawTransport:t,eventId:d.eventId,sessionId:d.sessionId,toolCallId:d.toolCallId,toolName:d.toolName,toolTitle:d.toolTitle});const l=d.toolInput&&d.toolTitle&&d.toolInput!==d.toolTitle?`${d.toolTitle}: ${d.toolInput}`:d.toolTitle||d.toolInput||d.toolName;if(t){this.sendAcpRawEventEnvelope(d.eventId,d.sessionId,{type:"permission_request",payload:{tool_call_id:d.toolCallId,tool_name:d.toolName,tool_title:d.toolTitle,...d.toolInput?{tool_input:d.toolInput}:{},options:d.options}}),p.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const h=`perm_${B()}`,g={event_id:d.eventId,session_id:d.sessionId,client_msg_id:h,msg_type:1,content:d.toolTitle?`Permission required: ${d.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:d.toolCallId,approvalSlug:d.toolName},grix:{execApproval:{approval_command_id:d.toolCallId,approval_type:"permission",command:l,host:"acp"}}},agent_api_origin:!0}};p.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:d.eventId,sessionId:d.sessionId,clientMsgId:h,toolCallId:d.toolCallId,contentLength:g.content.length});try{this.aibotHandle.sendMsg(g),p.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:h})}catch(u){p.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:h,error:u instanceof Error?u.message:String(u)})}},sendAuthNotification:(d,l)=>{d&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:l,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:l}}}}})},sendAgentMessage:(d,l)=>{d&&l&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:l})},sendUpdateBindingCard:(d,l,h,g)=>{const u={...g??{}};if(!u.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const f=this.providerQuotaToRateLimits(this.cachedProviderQuota);f&&(u.rate_limits=f)}!u.provider_quota&&this.cachedProviderQuota?.success&&(u.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:l,cwd:h,...Object.keys(u).length>0?{meta:u}:{}})},onSkillsUpdate:(d,l)=>{try{this.aibotHandle.sendSkillsUpdate({skills:Ae(d,L.skills),library_skills:this.buildLibrarySkillsReport(l)})}catch(h){}},onContextWindowUpdated:d=>{this.cachedAcpContextWindow=d,this.cachedAcpContextWindowSampledAtMs=Date.now();const l="usedPercentage"in d?d.usedPercentage.toFixed(1):(d.used/d.size*100).toFixed(1);p.info(this.name,`[acp] context_window updated: ${l}%`);const h=this.bindingStore.get(e);if(h?.cwd){const g="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),u={context_window:{..."usedPercentage"in d?{}:d,usedPercentage:g,remainingPercentage:100-g}};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),u.provider_quota=this.cachedProviderQuota;const f=this.providerQuotaToRateLimits(this.cachedProviderQuota);f&&(u.rate_limits=f)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:h.cwd,meta:u})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},i=e?this.bindingStore.get(e):void 0,n=e?this.auditController.getSession(e):void 0,o=this.config.aibot.clientType==="reasonix"&&n?Mi(this.name,e,n.auditId):void 0,r=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:c}=Yn({sessionBinding:i,globalDefaults:r,configInitialMode:this.config.acpInitialMode});return e&&a&&!i?.acpModelId&&this.bindingStore.setAcpModelId(e,a),e&&c&&!i?.acpModeId&&this.bindingStore.setAcpModeId(e,c),(a||c)&&p.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${c??"<none>"}`),new y({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},s,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:c,acpInitialModel:a,acpMcpTools:this.config.acpMcpTools,rawTransport:t,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 nt(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:o,agentType:this.config.aibot.clientType})}async connectAibot(){const t=await new ie().connect(this.aibotConfig,{aborted:()=>this.stopped,signal:this.startupAbortController.signal,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});if(this.stopped)throw t.disconnect(),new Error("connection aborted");this.aibotHandle=t;const s=this.aibotHandle.authAck;if(this.applyAgentProfile(s?.agent_name,s?.introduction,{source:"auth_ack",respawnOnChange:!1},s?.system_prompt),this.aibotHandle.onEvent(i=>{this.handleAibotEvent(i).catch(n=>{p.error(this.name,`handleAibotEvent failed: ${n}`),this.aibotHandle.sendEventAck({event_id:i.event_id,session_id:i.session_id,received_at:Date.now()});const o=n instanceof Error?n.message:String(n);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(o)&&i.session_id){this.bindingStore.delete(i.session_id),this.sessionBindings.delete(i.session_id),this.sessionProviderHints.delete(i.session_id),this.sessionProviderQuotas.delete(i.session_id),this.sessionProviderMeta.delete(i.session_id);const a=this.pool.getSlot(i.session_id);a?.adapter instanceof y&&a.adapter.getSessionBindings().delete(i.session_id);const c=this.config.adapterType??"acp",d=this.resolveBindingChannelKey(c);this.aibotHandle.sendMsg({event_id:i.event_id,session_id:i.session_id,msg_type:1,content:o,extra:{channel_data:{[d]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:E.invalidCwd}}}},quoted_message_id:i.msg_id});return}this.aibotHandle.sendEventResult({event_id:i.event_id,status:"failed",msg:o,updated_at:Date.now()})})}),this.aibotHandle.onStop(i=>{try{this.handleAibotStop(i)}catch(n){p.error(this.name,`handleAibotStop failed: ${n}`)}}),this.aibotHandle.onAgentDeleted(i=>{p.warn(this.name,`agent deleted on platform (source=${i?.source??"unknown"}${i?.reason?` reason=${i.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(n){p.error(this.name,`agentDeletedHandler failed: ${n}`)}}),this.aibotHandle.onShareSet(i=>{try{this.shareSetHandler?.(Array.isArray(i?.shared_to)?i.shared_to:[])}catch(n){p.error(this.name,`onShareSet failed: ${n}`)}}),this.aibotHandle.onProfilePush(i=>{try{this.applyAgentProfile(i?.agent_name,i?.introduction,{source:"profile_push",respawnOnChange:!0},i?.system_prompt)}catch(n){p.error(this.name,`onProfilePush failed: ${n}`)}}),this.aibotHandle.onSkillSync(i=>{if(!this.stopped)try{p.info(this.name,`skill_sync received owner=${i?.owner_id??""} name=${i?.name??""}`),this.skillSyncHandler?.()}catch(n){p.error(this.name,`onSkillSync failed: ${n}`)}}),this.aibotHandle.onRevoke(i=>{this.handleAibotRevoke(i).catch(n=>{p.error(this.name,`handleAibotRevoke failed: ${n}`)})}),this.aibotHandle.onLocalAction(i=>{this.handleAibotLocalAction(i).catch(n=>{p.error(this.name,`handleAibotLocalAction failed: ${n}`)})}),this.aibotHandle.onEventCancel(i=>{p.info(this.name,`recv event_cancel event_id=${i.event_id} session_id=${i.session_id}`),this.handleEventCancel(i).catch(n=>{p.error(this.name,`handleEventCancel failed: ${n}`)})}),this.aibotHandle.onMcpFrame((i,n)=>{const o=this.pool.getSlot(i)?.adapter;o?.deliverMcpFrameToAgent?o.deliverMcpFrameToAgent(n):p.warn(this.name,`mcp_frame: no adapter for session=${i}`)}),this.aibotHandle.onQueueClear(i=>{const n=this.pool.clearQueue(i.session_id);this.aibotHandle.sendQueueClearResult({session_id:i.session_id,canceled_event_ids:n}),this.pushQueueSnapshotForSession(i.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(i=>{const n=Array.isArray(i.ordered_event_ids)?i.ordered_event_ids.filter(r=>typeof r=="string"&&r.length>0):[],o=this.pool.reorderQueue(i.session_id,n);this.aibotHandle.sendQueueReorderResult({session_id:i.session_id,applied_event_ids:o}),this.pushQueueSnapshotForSession(i.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(i=>{const n=typeof i.session_id=="string"?i.session_id:"",o=typeof i.event_id=="string"?i.event_id:"",r=i.hold!==!1;if(p.info(this.name,`recv event_hold event_id=${o} session_id=${n} hold=${r} reason=${i.reason??""}`),!n||!o){this.aibotHandle.sendEventHoldResult({session_id:n,event_id:o,ok:!1,held:!1,error:"bad_request"});return}const a=typeof i.reason=="string"?i.reason:"",c=typeof i.ttl_ms=="number"?i.ttl_ms:void 0,d=this.pool.holdEvent(n,o,r,a,c),l=d==="ok";this.aibotHandle.sendEventHoldResult({session_id:n,event_id:o,ok:l,held:l?r:!1,...l?{}:{error:d}}),l&&this.pushQueueSnapshotForSession(n)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(i=>{const n=typeof i.session_id=="string"?i.session_id:"",o=typeof i.event_id=="string"?i.event_id:"";if(p.info(this.name,`recv queue_edit event_id=${o} session_id=${n}`),!n||!o){this.aibotHandle.sendQueueEditResult({session_id:n,event_id:o,ok:!1,error:"bad_request"});return}const r=typeof i.content=="string"?i.content:"",a=this.pool.editQueuedEvent(n,o,r),c=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:n,event_id:o,ok:c,...c?{}:{error:a}}),c&&this.pushQueueSnapshotForSession(n)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(i=>{this.replyQueueSnapshotForSession(i.session_id)}),p.info(this.name,"Connected to aibot"),this.activeEventStore){const i=await this.activeEventStore.drain();if(i.length>0){p.warn(this.name,`Recovering ${i.length} stale event(s) from previous run`);for(const n of i)p.info(this.name,`Failing stale event on startup: ${n}`),this.aibotHandle.sendEventResult({event_id:n,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.relayStateSyncOnConnect(),this.aibotHandle.onReconnected(()=>{if(this.stopped)return;this.pushQueueSnapshots();const i=this.aibotHandle.authAck;this.applyAgentProfile(i?.agent_name,i?.introduction,{source:"reconnect",respawnOnChange:!0},i?.system_prompt),this.forceRefreshSkills(void 0,{force:!0}),this.skillSyncHandler?.(),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((i,n)=>{this.sendCtrl.markEventRejected(i)})}applyAgentProfile(e,t,s,i){const n=String(e??"").trim(),o=String(t??"").trim(),r=i===void 0?this.agentSystemPrompt:String(i),a=n!==this.agentProfile.agentName||o!==this.agentProfile.introduction||r!==this.agentSystemPrompt;this.agentProfile={agentName:n,introduction:o},this.agentSystemPrompt=r,n||o?p.info(this.name,`agent profile (${s.source}): GOT name="${n}" intro_len=${o.length} system_prompt_len=${r.length} changed=${a}`):p.warn(this.name,`agent profile (${s.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),a&&s.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const t=this.pool.getAllSlots();let s=0;for(const r of t)if(r.adapter.onAgentProfileChanged)try{r.adapter.onAgentProfileChanged(),s++}catch(a){p.warn(this.name,`onAgentProfileChanged failed for session=${r.sessionId}: ${a}`)}const i=t.filter(r=>r.adapter instanceof N),n=i.filter(r=>{if(r.state!=="ready")return!1;const a=r.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),o=i.length-n.length;p.info(this.name,`${e}: notified ${s} adapter(s) via hook; respawning ${n.length} idle Claude slot(s), skipping ${o} busy`);for(const r of n)this.pool.removeSlot(r.sessionId).catch(a=>{p.warn(this.name,`removeSlot failed during ${e}: ${a}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const t=this.pool?.getQueueSnapshot(e)??null,s=t?[...t.running]:[],i=t?t.running_items.map(o=>({event_id:o.event_id,...o.content_preview?{content_preview:o.content_preview}:{},...o.title?{title:o.title}:{},...o.summary?{summary:o.summary}:{},actions:[{type:"stop"}]})):[],n=t?t.queued.map(o=>({event_id:o.event_id,position:o.position,...o.content_preview?{content_preview:o.content_preview}:{},...typeof o.content=="string"?{content:o.content}:{},...o.title?{title:o.title}:{},...o.summary?{summary:o.summary}:{},held:o.held===!0,held_reason:o.held_reason??"",actions:[{type:"cancel"}]})):[];if(s.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const o=`selfdrive_${e}`,r=this.selfDrivenLabels.get(e)??"Background task in progress";s.push(o),i.push({event_id:o,content_preview:r,title:r,summary:r,actions:[]})}return{session_id:e,running:s,running_items:i,queued:n}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const t=this.buildQueueSnapshotPayload(e);p.info(this.name,`[queue-debug] push snapshot session=${e} running=${t.running.length} queued=${t.queued.length} running_ids=[${t.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(t)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,t,s){return e==="file_link"?ei(t):e==="file_upload"?this.uploadFileAndSendMedia(t):this.aibotHandle.agentInvoke(e,t,s)}invokeDshEventTool(e,t){const s=Ee(this.aibotHandle,e,t),i=s.content[0]?.text??"";if(s.isError)throw new Error(i||`grix event tool "${e}" failed`);try{return JSON.parse(i)}catch{return i}}async uploadFileAndSendMedia(e){const t=String(e.file_path??"").trim(),s=String(e.session_id??"").trim(),i=String(e.caption??"").trim(),n=String(e.reply_to_message_id??"").trim();if(!t)throw new Error("file_path is required");if(!s)throw new Error("session_id is required");const o=await ni({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:s,filePath:t}),r=await this.aibotHandle.sendMedia({session_id:s,msg_type:2,content:i||`[${o.attachment_type}]`,client_msg_id:`file_upload_${B()}`,...n?{quoted_message_id:n}:{},extra:o.extra});if(r.cmd!=="send_ack"){const c=r.payload??{},d=String(c.msg??r.cmd);throw new Error(`media message send failed: ${d}`)}const a=r.payload??{};return{ok:!0,file_name:o.file_name,attachment_type:o.attachment_type,access_url:o.access_url,message_id:a.msg_id!=null?String(a.msg_id):null}}sendReplyByRuntimeConfig(e,t,s,i,n){const o=this.indexEventSession(e,t)??t;this.auditController.captureReply(e,s),this.sendCtrl.sendReply(e,o,s,i,n),s&&this.conversationLog?.logOutbound?.(o,e,"reply",s)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:o,...r}=e;return r}const t=e;if(t.codex_method!=="item/agentMessage/delta")return e;const i=t.codex_payload?.params?.phase;if(typeof i=="string"&&i.trim()&&i.trim().toLowerCase()!=="final_answer")return e;const n=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return n?{...e,quoted_message_id:n}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params,s=typeof t?.phase=="string"?t.phase.trim().toLowerCase():"";if(s&&s!=="final_answer")return;const i=t?.delta;typeof i!="string"||!i||this.auditController.captureUnsequencedStreamChunk(e.event_id,i)}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.pendingStartedEventIds.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,t){return async(s,i,n)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(s,i,n,t)}catch(o){throw p.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${s}: ${o}`),o}p.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${s}`)}}sendStreamChunkByRuntimeConfig(e,t,s,i,n,o,r){const a=this.indexEventSession(e,t)??t;this.auditController.captureStreamChunk(e,i,s),this.sendCtrl.sendStreamChunk(e,a,s,i,n,o,r),(s||n)&&this.conversationLog?.logOutbound?.(a,e,n?"stream_chunk_finish":"stream_chunk",s)}surfacedRunErrorEvents=new Set;sendRunErrorAsChunk(e,t,s){this.surfacedRunErrorEvents.has(e)||(this.surfacedRunErrorEvents.add(e),this.sendStreamChunkByRuntimeConfig(e,t,`
|
|
7
|
+
Error: ${u}`,1,!1)},sendAgentQuestionCard:(d,c,u)=>{this.sendGrixAgentQuestionCard(d,c,u)},sendPermissionCard:d=>{h.info("bridge","sendPermissionCard callback entered",{rawTransport:i,eventId:d.eventId,sessionId:d.sessionId,toolCallId:d.toolCallId,toolName:d.toolName,toolTitle:d.toolTitle});const c=d.toolInput&&d.toolTitle&&d.toolInput!==d.toolTitle?`${d.toolTitle}: ${d.toolInput}`:d.toolTitle||d.toolInput||d.toolName;if(i){this.sendAcpRawEventEnvelope(d.eventId,d.sessionId,{type:"permission_request",payload:{tool_call_id:d.toolCallId,tool_name:d.toolName,tool_title:d.toolTitle,...d.toolInput?{tool_input:d.toolInput}:{},options:d.options}}),h.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const u=`perm_${R()}`,g={event_id:d.eventId,session_id:d.sessionId,client_msg_id:u,msg_type:1,content:d.toolTitle?`Permission required: ${d.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:d.toolCallId,approvalSlug:d.toolName},grix:{execApproval:{approval_command_id:d.toolCallId,approval_type:"permission",command:c,host:"acp"}}},agent_api_origin:!0}};h.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:d.eventId,sessionId:d.sessionId,clientMsgId:u,toolCallId:d.toolCallId,contentLength:g.content.length});try{this.aibotHandle.sendMsg(g),h.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:u})}catch(p){h.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:u,error:p instanceof Error?p.message:String(p)})}},sendAuthNotification:(d,c)=>{d&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:c,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:c}}}}})},sendAgentMessage:(d,c)=>{d&&c&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:c})},sendUpdateBindingCard:(d,c,u,g)=>{const p={...g??{}};if(!p.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const _=this.providerQuotaToRateLimits(this.cachedProviderQuota);_&&(p.rate_limits=_)}!p.provider_quota&&this.cachedProviderQuota?.success&&(p.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:c,cwd:u,...Object.keys(p).length>0?{meta:p}:{}})},onSkillsUpdate:(d,c)=>{try{this.aibotHandle.sendSkillsUpdate({skills:X(d,w.skills),library_skills:this.buildLibrarySkillsReport(c)})}catch(u){}},onContextWindowUpdated:d=>{this.cachedAcpContextWindow=d,this.cachedAcpContextWindowSampledAtMs=Date.now();const c="usedPercentage"in d?d.usedPercentage.toFixed(1):(d.used/d.size*100).toFixed(1);h.info(this.name,`[acp] context_window updated: ${c}%`);const u=this.bindingStore.get(e);if(u?.cwd){const g="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),p={context_window:{..."usedPercentage"in d?{}:d,usedPercentage:g,remainingPercentage:100-g}};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),p.provider_quota=this.cachedProviderQuota;const _=this.providerQuotaToRateLimits(this.cachedProviderQuota);_&&(p.rate_limits=_)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:u.cwd,meta:p})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},n=e?this.bindingStore.get(e):void 0,t=e?this.auditController.getSession(e):void 0,s=this.config.aibot.clientType==="reasonix"&&t?Ei(this.name,e,t.auditId):void 0,o=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:l}=Wn({sessionBinding:n,globalDefaults:o,configInitialMode:this.config.acpInitialMode});return e&&a&&!n?.acpModelId&&this.bindingStore.setAcpModelId(e,a),e&&l&&!n?.acpModeId&&this.bindingStore.setAcpModeId(e,l),(a||l)&&h.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${l??"<none>"}`),new S({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},r,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:l,acpInitialModel:a,acpMcpTools:this.config.acpMcpTools,rawTransport:i,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 Pe(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:s,agentType:this.config.aibot.clientType})}async connectAibot(){const i=await new q().connect(this.aibotConfig,{aborted:()=>this.stopped,signal:this.startupAbortController.signal,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});if(this.stopped)throw i.disconnect(),new Error("connection aborted");this.aibotHandle=i;const r=this.aibotHandle.authAck;if(this.applyAgentProfile(r?.agent_name,r?.introduction,{source:"auth_ack",respawnOnChange:!1},r?.system_prompt),this.aibotHandle.onEvent(n=>{this.handleAibotEvent(n).catch(t=>{h.error(this.name,`handleAibotEvent failed: ${t}`),this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:n.session_id,received_at:Date.now()});const s=t instanceof Error?t.message:String(t);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(s)&&n.session_id){this.bindingStore.delete(n.session_id),this.sessionBindings.delete(n.session_id),this.sessionProviderHints.delete(n.session_id),this.sessionProviderQuotas.delete(n.session_id),this.sessionProviderMeta.delete(n.session_id);const a=this.pool.getSlot(n.session_id);a?.adapter instanceof S&&a.adapter.getSessionBindings().delete(n.session_id);const l=this.config.adapterType??"acp",d=this.resolveBindingChannelKey(l);this.aibotHandle.sendMsg({event_id:n.event_id,session_id:n.session_id,msg_type:1,content:s,extra:{channel_data:{[d]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:$.invalidCwd}}}},quoted_message_id:n.msg_id});return}this.aibotHandle.sendEventResult({event_id:n.event_id,status:"failed",msg:s,updated_at:Date.now()})})}),this.aibotHandle.onStop(n=>{try{this.handleAibotStop(n)}catch(t){h.error(this.name,`handleAibotStop failed: ${t}`)}}),this.aibotHandle.onAgentDeleted(n=>{h.warn(this.name,`agent deleted on platform (source=${n?.source??"unknown"}${n?.reason?` reason=${n.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(t){h.error(this.name,`agentDeletedHandler failed: ${t}`)}}),this.aibotHandle.onShareSet(n=>{try{this.shareSetHandler?.(Array.isArray(n?.shared_to)?n.shared_to:[])}catch(t){h.error(this.name,`onShareSet failed: ${t}`)}}),this.aibotHandle.onProfilePush(n=>{try{this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"profile_push",respawnOnChange:!0},n?.system_prompt)}catch(t){h.error(this.name,`onProfilePush failed: ${t}`)}}),this.aibotHandle.onSkillSync(n=>{if(!this.stopped)try{h.info(this.name,`skill_sync received owner=${n?.owner_id??""} name=${n?.name??""}`),this.skillSyncHandler?.()}catch(t){h.error(this.name,`onSkillSync failed: ${t}`)}}),this.aibotHandle.onRevoke(n=>{this.handleAibotRevoke(n).catch(t=>{h.error(this.name,`handleAibotRevoke failed: ${t}`)})}),this.aibotHandle.onLocalAction(n=>{this.handleAibotLocalAction(n).catch(t=>{h.error(this.name,`handleAibotLocalAction failed: ${t}`)})}),this.aibotHandle.onEventCancel(n=>{h.info(this.name,`recv event_cancel event_id=${n.event_id} session_id=${n.session_id}`),this.handleEventCancel(n).catch(t=>{h.error(this.name,`handleEventCancel failed: ${t}`)})}),this.aibotHandle.onMcpFrame((n,t)=>{const s=this.pool.getSlot(n)?.adapter;s?.deliverMcpFrameToAgent?s.deliverMcpFrameToAgent(t):h.warn(this.name,`mcp_frame: no adapter for session=${n}`)}),this.aibotHandle.onQueueClear(n=>{const t=this.pool.clearQueue(n.session_id);this.aibotHandle.sendQueueClearResult({session_id:n.session_id,canceled_event_ids:t}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(n=>{const t=Array.isArray(n.ordered_event_ids)?n.ordered_event_ids.filter(o=>typeof o=="string"&&o.length>0):[],s=this.pool.reorderQueue(n.session_id,t);this.aibotHandle.sendQueueReorderResult({session_id:n.session_id,applied_event_ids:s}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(n=>{const t=typeof n.session_id=="string"?n.session_id:"",s=typeof n.event_id=="string"?n.event_id:"",o=n.hold!==!1;if(h.info(this.name,`recv event_hold event_id=${s} session_id=${t} hold=${o} reason=${n.reason??""}`),!t||!s){this.aibotHandle.sendEventHoldResult({session_id:t,event_id:s,ok:!1,held:!1,error:"bad_request"});return}const a=typeof n.reason=="string"?n.reason:"",l=typeof n.ttl_ms=="number"?n.ttl_ms:void 0,d=this.pool.holdEvent(t,s,o,a,l),c=d==="ok";this.aibotHandle.sendEventHoldResult({session_id:t,event_id:s,ok:c,held:c?o:!1,...c?{}:{error:d}}),c&&this.pushQueueSnapshotForSession(t)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(n=>{const t=typeof n.session_id=="string"?n.session_id:"",s=typeof n.event_id=="string"?n.event_id:"";if(h.info(this.name,`recv queue_edit event_id=${s} session_id=${t}`),!t||!s){this.aibotHandle.sendQueueEditResult({session_id:t,event_id:s,ok:!1,error:"bad_request"});return}const o=typeof n.content=="string"?n.content:"",a=this.pool.editQueuedEvent(t,s,o),l=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:t,event_id:s,ok:l,...l?{}:{error:a}}),l&&this.pushQueueSnapshotForSession(t)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(n=>{this.replyQueueSnapshotForSession(n.session_id)}),h.info(this.name,"Connected to aibot"),this.activeEventStore){const n=await this.activeEventStore.drain();if(n.length>0){h.warn(this.name,`Recovering ${n.length} stale event(s) from previous run`);for(const t of n)h.info(this.name,`Failing stale event on startup: ${t}`),this.aibotHandle.sendEventResult({event_id:t,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.relayStateSyncOnConnect(),this.aibotHandle.onReconnected(()=>{if(this.stopped)return;this.pushQueueSnapshots();const n=this.aibotHandle.authAck;this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"reconnect",respawnOnChange:!0},n?.system_prompt),this.forceRefreshSkills(void 0,{force:!0}),this.skillSyncHandler?.(),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((n,t)=>{this.sendCtrl.markEventRejected(n)})}applyAgentProfile(e,i,r,n){const t=String(e??"").trim(),s=String(i??"").trim(),o=n===void 0?this.agentSystemPrompt:String(n),a=t!==this.agentProfile.agentName||s!==this.agentProfile.introduction||o!==this.agentSystemPrompt;this.agentProfile={agentName:t,introduction:s},this.agentSystemPrompt=o,t||s?h.info(this.name,`agent profile (${r.source}): GOT name="${t}" intro_len=${s.length} system_prompt_len=${o.length} changed=${a}`):h.warn(this.name,`agent profile (${r.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),a&&r.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const i=this.pool.getAllSlots();let r=0;for(const o of i)if(o.adapter.onAgentProfileChanged)try{o.adapter.onAgentProfileChanged(),r++}catch(a){h.warn(this.name,`onAgentProfileChanged failed for session=${o.sessionId}: ${a}`)}const n=i.filter(o=>o.adapter instanceof L),t=n.filter(o=>{if(o.state!=="ready")return!1;const a=o.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),s=n.length-t.length;h.info(this.name,`${e}: notified ${r} adapter(s) via hook; respawning ${t.length} idle Claude slot(s), skipping ${s} busy`);for(const o of t)this.pool.removeSlot(o.sessionId).catch(a=>{h.warn(this.name,`removeSlot failed during ${e}: ${a}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const i=this.pool?.getQueueSnapshot(e)??null,r=i?[...i.running]:[],n=i?i.running_items.map(s=>({event_id:s.event_id,...s.content_preview?{content_preview:s.content_preview}:{},...s.title?{title:s.title}:{},...s.summary?{summary:s.summary}:{},actions:[{type:"stop"}]})):[],t=i?i.queued.map(s=>({event_id:s.event_id,position:s.position,...s.content_preview?{content_preview:s.content_preview}:{},...typeof s.content=="string"?{content:s.content}:{},...s.title?{title:s.title}:{},...s.summary?{summary:s.summary}:{},held:s.held===!0,held_reason:s.held_reason??"",actions:[{type:"cancel"}]})):[];if(r.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const s=`selfdrive_${e}`,o=this.selfDrivenLabels.get(e)??"Background task in progress";r.push(s),n.push({event_id:s,content_preview:o,title:o,summary:o,actions:[]})}return{session_id:e,running:r,running_items:n,queued:t}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const i=this.buildQueueSnapshotPayload(e);h.info(this.name,`[queue-debug] push snapshot session=${e} running=${i.running.length} queued=${i.queued.length} running_ids=[${i.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(i)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,i,r){return e==="file_link"?jn(i):e==="file_upload"?this.uploadFileAndSendMedia(i):this.aibotHandle.agentInvoke(e,i,r)}invokeDshEventTool(e,i){const r=V(this.aibotHandle,e,i),n=r.content[0]?.text??"";if(r.isError)throw new Error(n||`grix event tool "${e}" failed`);try{return JSON.parse(n)}catch{return n}}async uploadFileAndSendMedia(e){const i=String(e.file_path??"").trim(),r=String(e.session_id??"").trim(),n=String(e.caption??"").trim(),t=String(e.reply_to_message_id??"").trim();if(!i)throw new Error("file_path is required");if(!r)throw new Error("session_id is required");const s=await Kn({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:r,filePath:i}),o=await this.aibotHandle.sendMedia({session_id:r,msg_type:2,content:n||`[${s.attachment_type}]`,client_msg_id:`file_upload_${R()}`,...t?{quoted_message_id:t}:{},extra:s.extra});if(o.cmd!=="send_ack"){const l=o.payload??{},d=String(l.msg??o.cmd);throw new Error(`media message send failed: ${d}`)}const a=o.payload??{};return{ok:!0,file_name:s.file_name,attachment_type:s.attachment_type,access_url:s.access_url,message_id:a.msg_id!=null?String(a.msg_id):null}}sendReplyByRuntimeConfig(e,i,r,n,t){const s=this.indexEventSession(e,i)??i;this.auditController.captureReply(e,r),this.sendCtrl.sendReply(e,s,r,n,t),r&&this.conversationLog?.logOutbound?.(s,e,"reply",r)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:s,...o}=e;return o}const i=e;if(i.codex_method!=="item/agentMessage/delta")return e;const n=i.codex_payload?.params?.phase;if(typeof n=="string"&&n.trim()&&n.trim().toLowerCase()!=="final_answer")return e;const t=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return t?{...e,quoted_message_id:t}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const i=e.codex_payload?.params,r=typeof i?.phase=="string"?i.phase.trim().toLowerCase():"";if(r&&r!=="final_answer")return;const n=i?.delta;typeof n!="string"||!n||this.auditController.captureUnsequencedStreamChunk(e.event_id,n)}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.pendingStartedEventIds.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,i){return async(r,n,t)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(r,n,t,i)}catch(s){throw h.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${r}: ${s}`),s}h.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${r}`)}}sendStreamChunkByRuntimeConfig(e,i,r,n,t,s,o){const a=this.indexEventSession(e,i)??i;this.auditController.captureStreamChunk(e,n,r),this.sendCtrl.sendStreamChunk(e,a,r,n,t,s,o),(r||t)&&this.conversationLog?.logOutbound?.(a,e,t?"stream_chunk_finish":"stream_chunk",r)}surfacedRunErrorEvents=new Set;sendRunErrorAsChunk(e,i,r){this.surfacedRunErrorEvents.has(e)||(this.surfacedRunErrorEvents.add(e),this.sendStreamChunkByRuntimeConfig(e,i,`
|
|
8
8
|
|
|
9
|
-
Error: ${s}`,1,!1))}sendEventResultWithCleanup(e,t,s,i,n=!1){const o=this.eventSessionIndex.get(e);n&&this.surfacedRunErrorEvents.add(e),t==="failed"&&o&&s?.trim()&&this.sendRunErrorAsChunk(e,o,s),this.auditController.markResponded(e,t,s),this.sendCtrl.sendEventResult(e,t,s,i),o&&(this.pool.eventComplete(e,o)===!1&&p.error(this.name,`Event terminal result could not release queue slot event=${e} session=${o} status=${t}`),this.pushQueueSnapshotForSession(o),this.conversationLog?.logResult?.(o,e,t,s),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorEvents.delete(e),this.pendingStartedEventIds.delete(e),this.pendingEvents.remove(e).catch(r=>{p.warn(this.name,`Failed to remove terminal event from pending store event=${e}: ${r instanceof Error?r.message:String(r)}`)}),t==="responded"&&(this.config.adapterType??"acp")!=="agy"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:t,sessionId:s,errorMsg:i}=e;if(this.stopped)return;const n=this.inflightEvents.get(t);if(!n){p.warn(this.name,`[recovery] no inflight event for internalError event=${t} session=${s}; surface failure directly`),this.sendRunErrorAsChunk(t,s,i),this.sendEventResultWithCleanup(t,"failed",i,"agent_stop_failure");return}const o=(this.restartCount.get(t)??0)+1;this.restartCount.set(t,o);const r=this.config.adapterType??"acp";if(o>q){p.error(this.name,`[recovery] adapter=${r} session=${s} event=${t} restart=${o}/${q} outcome=give-up err=${i}`),this.sendRunErrorAsChunk(t,s,i),this.sendEventResultWithCleanup(t,"failed",i,"agent_stop_failure");return}p.info(this.name,`[recovery] adapter=${r} session=${s} event=${t} restart=${o}/${q} outcome=restarting err=${i}`);const a=this.pool.drainQueuedForSession(s);a.length>0&&p.info(this.name,`[recovery] session=${s} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(s)}catch(l){p.warn(this.name,`[recovery] removeSlot failed session=${s}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const c=e.replayOriginalContent?n.content:this.resolveRecoveryPrompt(r,n),d={...n,content:c};try{await this.pool.deliverInboundEvent(d)}catch(l){p.error(this.name,`[recovery] redeliver failed event=${t} session=${s}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(t,"failed",l instanceof Error?l.message:String(l));return}for(const l of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(l)}catch(h){p.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${s}: ${h instanceof Error?h.message:String(h)}`),this.sendEventResultWithCleanup(l.event_id,"failed",h instanceof Error?h.message:String(h))}}}resolveRecoveryPrompt(e,t){return e==="acp"?"continue":t.content}sendThinkingByRuntimeConfig(e,t,s){this.sendCtrl.sendThinking(e,t,s)}bufferStreamChunk(e,t,s,i,n){this.auditController.captureUnsequencedStreamChunk(e,s),this.sendCtrl.bufferOnly(e,t,s,i,n)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),this.auditController.markRecording(e.event_id),e.event_id&&!this.inflightEvents.has(e.event_id)&&this.inflightEvents.set(e.event_id,e)}async replayPendingEventsOnStartup(){const e=await this.pendingEvents.loadForReplay();if(e.length===0)return;const t=new Set(e.map(i=>i.event.event_id).filter(Boolean)),s=[];p.warn(this.name,`Replaying ${e.length} pending event(s) from previous run`);for(const i of e){if(this.stopped)break;const n=i.event;this.pendingEvents.startReplay(i);try{if(i.kind==="deferred"){const o=this.bindingStore.get(i.sessionId);o?.cwd?(await this.prepareBoundDeferredReplay(i,o.cwd),await this.deliverPendingReplayEvent(n),this.pendingStartedEventIds.has(n.event_id)||s.push(i)):(this.restorePendingReplayAuditTurn(n),this.deferredMgr.defer(i.channel,i.sessionId,n),s.push(i))}else await this.deliverPendingReplayEvent(n),this.pendingStartedEventIds.has(n.event_id)||s.push(i)}catch(o){const r=o instanceof Error?o.message:String(o);p.error(this.name,`Pending event replay failed event=${n.event_id}: ${r}`),this.sendEventResultWithCleanup(n.event_id,"failed",r),this.pendingEvents.markCanceled(n.event_id),await this.pendingEvents.remove(n.event_id).catch(()=>{})}finally{this.pendingEvents.finishReplay(i),await this.pendingEvents.checkpointReplay(t,[...s,...this.pendingEvents.replaySnapshot()])}if(this.stopped)break}this.stopped||(this.pendingEvents.finishAllReplay(),await this.pendingEvents.checkpointReplay(t,s))}failEventIfLifecycleDraining(e,t="connector is draining for restart; control command was not executed"){return this.lifecycleBarrier.isClosed()?(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_lifecycle_draining",msg:t,updated_at:Date.now()}),!0):!1}sendCanceledPendingEventResult(e,t){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),this.sendEventResultWithCleanup(e.event_id,"canceled",t),this.auditController.markAdapterClosed(e.event_id,{adapterNotStarted:!0})}async deliverPendingReplayEvent(e){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),await this.pool.deliverInboundEvent(e)}async prepareBoundDeferredReplay(e,t){this.sessionBindings.set(e.sessionId,t),e.channel==="acp"?await this.bindSessionForPool(e.sessionId,t):e.channel==="opencode"&&await this.syncOpenCodeBinding(e.sessionId,t)}restorePendingReplayAuditTurn(e){const t=e.audit;if(!t?.enabled||!t.auditId||!t.capture||!t.profile||!t.scope)return;const s=Ri({enabled:!0,scope:t.scope,profile:t.profile,capture:t.capture,...t.retentionDays===void 0?{}:{retentionDays:t.retentionDays}});if(!s.enabled)return;const i=Object.freeze({auditId:t.auditId,businessSessionId:e.session_id,provider:this.resolveAuditProvider(),options:s,createdAt:new Date().toISOString()}),n=this.auditController.startTurn({session:i,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...Number.isFinite(Number(e.created_at))&&Number(e.created_at)>0?{startedAt:new Date(Number(e.created_at)).toISOString()}:{},boundary:{adapterType:this.config.adapterType??"acp"}});n&&(e.audit={...t,auditId:n.auditId,turnId:n.turnId,profile:i.options.profile,capture:{...i.options.capture},rawProviderBody:i.options.capture.rawProviderBody})}indexEventSession(e,t){if(!e||!t)return;const s=this.eventSessionIndex.get(e);return s?(s!==t&&p.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${s} supplied=${t}`),s):(this.eventSessionIndex.set(e,t),t)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,t){return this.sendCtrl.shouldDropCodexDisplayEvent(e,t)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const s=e.codex_payload?.params?.delta;if(!s)return;const i=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(i,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:s.length,content:s})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,t){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,t)}sendAcpRawEventEnvelope(e,t,s){this.shouldDropAcpRawDisplayEvent(e,s.type)||this.deliverRawEventEnvelope(e,t,s,"acp",this.buildAcpRawEventFallbackText(s))}buildAcpRawEventFallbackText(e){const t=String(e.type??"").trim();if(!t)return"[acp] event";switch(t){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] ${t}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,t,s,i,n){const o=fi({envelope:s,fallbackText:n,channelKey:i,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),r=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:t,msg_type:1,content:o.fallbackText,extra:{channel_data:{[i]:{raw_event:o.envelope}},agent_api_origin:!0}})};if(!o.sharded){r();return}p.info("bridge",`${i} raw_event oversized, sharded delivery: event=${e} fields=${o.oversizedFields.map(a=>a.field).join(",")}`),(async()=>{for(const a of o.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,t,mi({envelopeType:s.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);r()})().catch(a=>{p.warn("bridge",`${i} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const t=String(e?.type??"").trim(),s=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(t){case"permission_request":return`Permission required: ${String(s.tool_title??s.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(s.tool_name??s.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(s.message??"agent error")}`;default:return t?`[cursor] ${t}`:"[cursor] event"}}sendToolExecutionCard(e,t,s,i){this.sendCtrl.sendToolExecutionCard(e,t,s,i)}sendGrixApprovalCard(e,t){this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${B()}`,msg_type:1,content:e.toolTitle?`Permission required: ${e.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:e.approvalId,approvalSlug:e.toolName},grix:{execApproval:{approval_command_id:e.approvalId,command:e.toolTitle||e.toolName,host:t}}},agent_api_origin:!0}})}sendGrixAgentQuestionCard(e,t,s){const i=s.questions.map(o=>o.header).join(", "),n=X(`[Agent Question] ${s.request_id}`,"agent_question",s);this.aibotHandle.sendText({event_id:e,session_id:t,content:n,msg_type:1,extra:{card_type:"agent_question",summary_text:i}})}async handleAgentQuestionReplyEvent(e){const t=Kn(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const i=this.pool.getSlot(e.session_id)?.adapter,n=i instanceof y?"acp":i instanceof F?"opencode":this.config.adapterType??"unknown",o=i instanceof F?i.handleQuestionReplyEvent(t):i instanceof y?await i.handleQuestionReplyEvent(t):{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};return o.delivered?(p.info(this.name,`[${n}] question reply delivered event=${e.event_id} session=${e.session_id} request=${t.request_id}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(p.warn(this.name,`[${n}] question reply rejected event=${e.event_id} session=${e.session_id} request=${t.request_id} code=${o.errorCode??"interaction_reply_failed"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:o.errorCode??"interaction_reply_failed",msg:o.errorMsg??"The question reply was not delivered.",updated_at:Date.now()})),!0}async handleExecApprovalResolutionEvent(e){const t=jn(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const i=this.pool.getSlot(e.session_id)?.adapter,n=t.params,o=String(n.tool_call_id??n.approval_command_id??n.approval_id??n.exec_context_id??""),r=i?.handleExecApprovalEvent?await i.handleExecApprovalEvent({...n,event_id:e.event_id,session_id:e.session_id}):{delivered:!1,errorCode:"approval_not_supported",errorMsg:"The current adapter does not support exec approval resolution events."};return r.delivered?(p.info(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution delivered event=${e.event_id} session=${e.session_id} approval=${o||"-"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(p.warn(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution rejected event=${e.event_id} session=${e.session_id} approval=${o||"-"} code=${r.errorCode}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:r.errorCode,msg:r.errorMsg,updated_at:Date.now()})),!0}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 t=this.config.adapterType??"acp",s=Un(e);let i;if(s&&(i=this.lifecycleBarrier.tryEnter()??void 0,!i)){this.failEventIfLifecycleDraining(e);return}try{if(await this.handleCliInstallQuestionReply(e)||(t==="opencode"||t==="acp")&&await this.handleAgentQuestionReplyEvent(e)||await this.handleExecApprovalResolutionEvent(e))return;const n=li(e.extra);if(n.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:n.error,updated_at:Date.now()});return}const o=n.patch,r=V(e.extra);if((r.state!=="absent"||r.error)&&p.info(this.name,`[audit-marker] event=${e.event_id} session=${e.session_id} msg=${e.msg_id??""} state=${r.state??"error"} scope=${r.options?.enabled?r.options.scope:""} error=${r.error??""}`),r.error){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_config_invalid",msg:r.error,updated_at:Date.now()}),(()=>{try{if(!e.extra||typeof e.extra!="object")return!1;const h=e.extra,g=h.extra,u=h.audit??(g&&typeof g=="object"?g.audit:void 0);return!u||typeof u!="object"?!1:u.scope==="turn"}catch{return!1}})())try{this.aibotHandle.sendAuditState($({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_config_invalid",errorMessage:r.error},Date.now()))}catch{}return}if(r.state==="enabled"&&t!=="claude"&&t!=="codex"&&t!=="cursor"&&t!=="opencode"&&t!=="pi"&&t!=="codewhale"&&t!=="deepseek-harness"&&t!=="agy"&&t!=="acp"){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_provider_unsupported",msg:`Audit replay is not supported for adapter: ${t}`,updated_at:Date.now()}),r.options?.enabled&&r.options.scope==="turn")try{this.aibotHandle.sendAuditState($({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_provider_unsupported",errorMessage:`Audit replay is not supported for adapter: ${t}`},Date.now()))}catch{}return}if(s){if(r.state!=="absent"||s.verb===S.open)try{this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra})}catch(l){this.sendAuditConfigurationError(e,l);return}if(s.verb===S.exec){await this.handleSessionControlCommand(s,e);return}if(s.verb===S.listSessions){await this.handleListSessionsTextCommand(e);return}if(s.verb===S.unbind){await this.handleUnbindTextCommand(e);return}if(t==="claude"){await this.handleSessionControlCommand(s,e);return}if(t==="codex"&&s.verb===S.open){await this.handleCodexSessionControlOpen(s,e);return}if(t==="pi"&&s.verb===S.open){await this.handlePiSessionControlOpen(s,e);return}if(t==="pi"&&s.verb===S.restart){await this.handlePiSessionControlRestart(e);return}if((t==="openhuman"||t==="opencode")&&s.verb===S.open){await this.handleOpenHumanSessionControlOpen(s,e);return}if(t==="codewhale"&&s.verb===S.open){await this.handleCodeWhaleSessionControlOpen(s,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),s.verb===S.open){const l=s.args.trim();if(!l){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:E.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const h=T.resolve(l);if(!(await Q(h)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:E.invalidCwd,msg:`Path is not a directory: ${h}`,updated_at:Date.now()});return}}catch(h){const g=String(h?.code??""),u=g==="ENOENT"?`Directory does not exist: ${T.resolve(l)}`:g==="EACCES"||g==="EPERM"?"Directory is not accessible":`Invalid path: ${l}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:E.invalidCwd,msg:u,updated_at:Date.now()});return}}if(s.verb===S.open){const l=this.bindingStore.get(e.session_id);if(l?.cwd)try{await Q(l.cwd)}catch{p.info("bridge",`Stale binding detected for session ${e.session_id}: ${l.cwd} no longer exists, clearing`),this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id);const h=this.pool.getSlot(e.session_id);h?.adapter instanceof y&&h.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(s,e),t==="acp"&&s.verb===S.stop){const h=this.bindingStore.get(e.session_id)?.cwd??"";await this.pool.removeSlot(e.session_id).catch(()=>{}),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${h}`,updated_at:Date.now()});return}if(Nn(s,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(e.session_id),sendEventAck:()=>{}}),s.verb===S.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),t==="agy")){const l=this.bindingStore.get(e.session_id)?.cwd??"";l&&(this.sendAgyBindingCard(e.session_id,l),this.refreshAndPushAgyQuota(e.session_id,!0))}return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}let a;try{a=this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra,eventId:e.event_id}).session}catch(l){this.sendAuditConfigurationError(e,l);return}if(ee.has(t)&&await this.ensureDefaultBindingForWorkspaceFreeClient(e.session_id,t),ee.has(t)&&!this.bindingStore.get(e.session_id)?.cwd){const h=t,g=this.prepareAuditedInboundEvent(e,o,a);p.info(this.name,`[${h}] binding missing session_id=${e.session_id} event_id=${e.event_id}`);try{const f=await this.pendingEvents.append({kind:"deferred",channel:h,sessionId:String(e.session_id??"").trim(),event:g});if(this.lifecycleBarrier.isClosed()&&!f)throw new Error("pending event store unavailable during lifecycle drain")}catch(f){const b=f instanceof Error?f.message:String(f);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",b,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:b,updated_at:Date.now()});return}if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(g,"canceled");return}this.deferredMgr.defer(h,String(e.session_id??"").trim(),g);const u=this.resolveBindingChannelKey(t);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[u]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:E.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const h=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(h){const[,g,u]=h,b=this.pool.getSlot(e.session_id)?.adapter;if(b?.execCommand&&(b.getSupportedCommands?.()??[]).some(m=>m.name===g||m.name===`/${g}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const m=await b.execCommand(g,u.trim(),e.session_id);m.status==="options"&&m.data&&this.handleExecCommandOptions(e.session_id,g,m.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:m.status==="failed"?"failed":"responded",msg:m.message,updated_at:Date.now()})}catch(m){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:m instanceof Error?m.message:String(m),updated_at:Date.now()})}return}}}if(t==="codex"&&K(a?.options)){const l=this.pool.getSlot(e.session_id);if(l?.adapter instanceof W&&!l.adapter.hasRawApiCaptureRelay()){const h=l.eventQueue.snapshot(e.session_id);h.running.length===0&&h.queued.length===0?(p.info(this.name,`[audit-raw-capture] recreating idle Codex adapter before event=${e.event_id} session=${e.session_id}`),await this.pool.removeSlot(e.session_id)):p.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${h.running.length} queued=${h.queued.length}`)}}const d=this.prepareAuditedInboundEvent(e,o,a);try{const l=await this.pendingEvents.append({kind:"queued",event:d});if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(d,"canceled");return}if(this.lifecycleBarrier.isClosed()){if(!l)throw new Error("pending event store unavailable during lifecycle drain");this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),p.info(this.name,`Persisted inbound event during lifecycle drain: ${e.event_id}`);return}this.captureEventRuntimeConfig(d),await this.pool.deliverInboundEvent(d)}catch(l){await this.pendingEvents.remove(e.event_id).catch(h=>{p.warn(this.name,`Failed to remove undelivered pending event=${e.event_id}: ${h instanceof Error?h.message:String(h)}`)}),this.failUndeliveredInboundEvent(e,l)}}finally{i?.()}}failUndeliveredInboundEvent(e,t){const s=t instanceof Error?t.message:String(t);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",s,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:s,updated_at:Date.now()})}handleCodexSessionControlOpen(e,t){return xt(this,e,t)}handleSessionControlForPool(e,t){return Dt(this,e,t)}handleSessionControlLocalActionForPool(e){return Mt(this,e)}handleCodexSessionControlLocalActionOpen(e){return Ht(this,e)}handleCursorSessionControlLocalActionOpen(e){return Lt(this,e)}handlePiSessionControlOpen(e,t){return $t(this,e,t)}handlePiSessionControlRestart(e){return It(this,e)}handlePiSessionControlRestartLocalAction(e){return Qt(this,e)}syncOpenCodeBinding(e,t){return Ot(this,e,t)}isWorkspaceFreeClient(){return Bt(this)}ensureDefaultBindingForWorkspaceFreeClient(e,t){return Ft(this,e,t)}bindSessionForPool(e,t){return qt(this,e,t)}deferredCallbacks(){return Ut(this)}handleOpenHumanSessionControlOpen(e,t){return Nt(this,e,t)}handleCodeWhaleSessionControlOpen(e,t){return Wt(this,e,t)}handleCodeWhaleSessionControlLocalActionOpen(e){return Gt(this,e)}handleDeepSeekSessionControlLocalActionOpen(e){return jt(this,e)}normalizeClaudeModeId(e){return dn(this,e)}handleExecCommandOptions(e,t,s){ln(this,e,t,s)}resolveSessionModelId(e){return cn(this,e)}resolveSessionModeId(e){return hn(this,e)}resolveCursorSessionModeId(e){return un(this,e)}resolveClaudeSessionEffort(e){return pn(this,e)}resolveClaudeSessionModeId(e){return gn(this,e)}currentClaudeModeId(e){return fn(this,e)}resolveCodexSessionModelId(e){return mn(this,e)}resolveCodexNewSessionGlobalDefault(e,t,s){return vn(this,e,t,s)}pinCodexGlobalDefault(e,t){return _n(this,e,t)}buildCursorToolbarMeta(e){return Sn(this,e)}buildAgyToolbarMeta(e,t){return bn(this,e,t)}buildAgyQuotaMeta(e){return Cn(this,e)}sendAgyBindingCard(e,t,s){return wn(this,e,t,s)}refreshAndPushAgyQuota(e,t=!1){return An(this,e,t)}handleAgySetModel(e,t){return En(this,e,t)}buildClaudeToolbarMeta(e){return kn(this,e)}providerQuotaToCodexRateLimits(e){return pi(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return ui(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){const t=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(t)||/^\\\\/.test(t))){const n=new Error(`Specified path is not valid on this host: ${t}`);throw n.cwdErrorCode=E.invalidCwd,n}const s=T.resolve(t);let i;try{i=await Q(s)}catch(n){const o=String(n?.code??"");if(o==="ENOENT"){const r=new Error(`Specified path does not exist: ${s}`);throw r.cwdErrorCode=E.invalidCwd,r}if(o==="EACCES"||o==="EPERM"){const r=new Error("Specified path is not accessible.");throw r.cwdErrorCode=E.invalidCwd,r}throw n}if(!i.isDirectory()){const n=new Error("Specified path is not a directory.");throw n.cwdErrorCode=E.invalidCwd,n}try{return await te(s)}catch{return s}}failSessionOpen(e,t){const{code:s,msg:i}=Jn(e);return this.maybeOfferCliInstall({sessionId:t.sessionId,eventId:t.eventId,quotedMessageId:t.quotedMessageId,cwd:t.cwd,err:e}),t.send?.(s,i),{code:s,msg:i}}maybeOfferCliInstall(e){ot(this,e)}handleCliInstallQuestionReply(e){return rt(this,e)}handleCliInstallInteractionReply(e){return at(this,e)}runConfirmedCliInstall(e,t){return dt(this,e,t)}getClaudeWorkerStatus(e){const t=this.pool.getSlot(e);return t?t.state==="starting"?"starting":t.state==="stopped"?"stopped":t.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,t){const s=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,s),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:s,cwd:t,meta:this.buildClaudeToolbarMeta(e)}),s}handleSkillDeleteLocalAction(e){return Jt(this,e)}handleSkillUploadLocalAction(e){return Yt(this,e)}handleSkillEnableLocalAction(e){return Xt(this,e)}handleSkillRefreshLocalAction(e){Vt(this,e)}handleSkillDisableLocalAction(e){return Zt(this,e)}computeSkillReport(e){return en(this,e)}reportSessionSkills(e){tn(this,e)}skillsSyncGroupKey(){return nn(this)}forceRefreshSkills(e,t){return sn(this,e,t)}adoptSkillsWireHashFromDisk(){on(this)}buildLibrarySkillsReport(e){return rn(this,e)}skillLookupEnv(){return an(this)}async ensureSlotStarted(e,t=6e4){const s=await this.pool.getOrCreateSlot(e);if(!s)throw new Error("Failed to allocate session slot");s.startPromise&&(p.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([s.startPromise,new Promise((i,n)=>setTimeout(()=>n(new Error(`ensureSlotStarted timeout (${t}ms) session=${e}`)),t))]),p.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveOrphanTitle(e){if(e){if(this.reasonixTitleScan){const t=Ie(e);if(!t)return;const s=this.reasonixTitleScan.get().filter(i=>i.stamp===t);return s.length===1?s[0].title:void 0}if((this.config.adapterType??"acp")==="cursor")return this.sessionScanCache.get().find(s=>s.sessionId===e)?.title}}resolveAgentSessionId(e){switch(this.config.adapterType??"acp"){case"claude":return e.claudeSessionId;case"codex":return e.codexThreadId;case"pi":return e.piSessionPath;case"codewhale":return e.codewhaleThreadId;case"agy":return e.agyConversationId;case"deepseek-harness":return e.dshProfileSessionId??e.acpSessionId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":case"deepseek-harness":return e;default:return"acp"}}setResolvedAgentSessionId(e,t){const s=String(e??"").trim(),i=String(t??"").trim();if(!s||!i)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(s,i);break;case"codex":this.bindingStore.setCodexThreadId(s,i);break;case"pi":this.bindingStore.setPiSessionPath(s,i);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(s,i);break;case"agy":this.bindingStore.setAgyConversationId(s,i);break;default:this.bindingStore.setAcpSessionId(s,i);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const t=String(e??"").trim();if(!t)return"";const s=T.resolve(t);return process.platform==="win32"?s.toLowerCase():s}ensureImportedAgentSession(e,t){const s=String(e??"").trim();if(!s)return;const i=this.normalizePathForCompare(t);let n="";const o=this.config.adapterType??"acp";if(o==="codex"?n=this.sessionScanCache.get().find(c=>c.threadId===s)?.cwd??"":o==="claude"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="cursor"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="acp"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="deepseek-harness"&&(n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??""),!n){for(const[,a]of this.bindingStore.entries())if(this.resolveAgentSessionId(a)===s){n=a.cwd??"";break}}if(!n){const a=new Error(`agent session not found: ${s}`);throw a.sessionControlErrorCode=E.invalidAgentSession,a}const r=this.normalizePathForCompare(n);if(r&&i&&r!==i){const a=new Error(`agent session cwd mismatch: expected ${t}, got ${n}`);throw a.sessionControlErrorCode=E.invalidAgentSession,a}}buildOpenedBindingResult(e,t,s="ready"){const i=this.bindingStore.get(e),n=i?String(this.resolveAgentSessionId(i)??"").trim():"",o={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:t,workerStatus:s};return n&&(o.bindingId=n,o.agentSessionId=n),(this.config.adapterType??"acp")==="deepseek-harness"&&Object.assign(o,this.buildDshOpenedToolbarMeta(e)),o}buildDshOpenedToolbarMeta(e){const t=this.globalConfigStore?.get(this.name),s=this.bindingStore.get(e),i=this.config.adapterOptions??{},n=typeof i.dshHome=="string"?i.dshHome:void 0;if(!this.bindingStore.getDshAgentPreset(e)){const R=ve(t?.dshAgentPreset,he);this.bindingStore.setDshAgentPreset(e,R)}const o=this.bindingStore.getDshSelectedProfile(e),r=Se({binding:o,global:t?.dshProfile,adapter:typeof i.dshProfile=="string"?i.dshProfile:void 0});o||this.bindingStore.setDshSelectedProfile(e,r);const a=this.dshCatalogDataRoot(),c=this.bindingStore.getDshSettings(e),d=c?.providerId??t?.dshProviderId,l=_e({dataRoot:a,providerId:d}),h=[c?.modelId,t?.dshModelId,l.models[0]?.id].find(R=>!!R&&l.models.some(C=>C.id===R))??l.models[0]?.id,g=j(s?.dshModeId,t?.dshModeId),u={};!s?.dshProviderId&&l.providerId&&(u.providerId=l.providerId),!s?.dshModelId&&h&&(u.modelId=h),s?.dshModeId||(u.modeId=g),s?.dshThinking||(u.thinking=me(t?.dshThinking)??"enabled"),s?.dshReasoningEffort||(u.reasoningEffort=fe(t?.dshReasoningEffort)??"high"),Object.keys(u).length>0&&this.bindingStore.updateDshSettings(e,u);const f=this.bindingStore.getDshSettings(e);let b=[],v=[],m=!1;try{b=ue({dshHome:n,profileName:r,enabledPluginIds:this.bindingStore.getDshEnabledPlugins(e)}),m=!1}catch{}const w=T.join(a,"dsh-session-skills");return we(w),v=pe({skillsDir:w,enabledSkillIds:this.bindingStore.getDshEnabledSkills(e)}),ce({agentPreset:f?.agentPreset,agentPresetLocked:this.bindingStore.isDshAgentPresetLocked(e),profileName:r,profiles:ge({dshHome:n}),profileLocked:this.bindingStore.isDshProfileLocked(e),plugins:b,skills:v,pluginRestartRequired:m,providerId:f?.providerId??l.providerId,modelId:f?.modelId??h,modeId:j(this.bindingStore.get(e)?.dshModeId,t?.dshModeId),thinking:f?.thinking,reasoningEffort:f?.reasoningEffort,providers:l.providers,models:l.models})}dshCatalogDataRoot(){const e=O("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24);return T.join(L.data,"deepseek-harness",e)}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"||e==="deepseek-harness"}unbindSession(e){return Et(this,e)}handleUnbindTextCommand(e){return kt(this,e)}handleUnbindLocalAction(e){return Rt(this,e)}handleListSessionsTextCommand(e){return yt(this,e)}handleListSessionsLocalAction(e){return Pt(this,e)}handleSyncHistoryLocalAction(e){return Tt(this,e)}handleSessionControlCommand(e,t){return it(this,e,t)}handleSessionControlLocalAction(e){return st(this,e)}handleEventCancel(e){return lt(this,e)}waitForEventDone(e,t,s){return ct(this,e,t,s)}handleAibotStop(e){ht(this,e)}killAndResumeStopSlot(e,t){return ut(this,e,t)}handleAibotRevoke(e){return pt(this,e)}handleConfigureGatewayProvider(e){return gt(this,e)}getAuditLocalActionHandler(){return ft(this)}handleAuditLocalAction(e){return mt(this,e)}handleConnectorRollback(e){return vt(this,e)}getRelayStateSyncer(){return _t(this)}relayStateSyncOnConnect(){St(this)}reportRelayStateLocalChange(){bt(this)}handleApplyRelayState(e){return Ct(this,e)}fetchRelayCredential(e){return wt(this,e)}isSharedInstance(){return At(this)}async handleAibotLocalAction(e){if(this.stopped){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is shutting down; local action was not executed"});return}const t=e.action_type??"",s=String((e.params??{}).session_id??""),i=String((e.params??{}).verb??"").trim().toLowerCase();p.debug(this.name,`local_action received action_type=${t} verb=${i||"-"} action_id=${e.action_id} session_id=${s}`);let n;if(t===k.sessionControl&&(n=this.lifecycleBarrier.tryEnter()??void 0,!n)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is draining for restart; session control was not executed"});return}try{if(t===k.interactionReply&&await this.handleCliInstallInteractionReply(e))return;if(Ce(t)){await this.handleAuditLocalAction(e);return}const o=(this.config.adapterType??"acp")==="claude";if(t===k.sessionControl&&i===S.exec&&await this.handleSessionControlLocalAction(e))return;if(t===k.sessionControl&&i===S.listSessions){await this.handleListSessionsLocalAction(e);return}if(t===k.sessionControl&&i===S.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(t===k.sessionControl&&i===S.unbind){await this.handleUnbindLocalAction(e);return}if(t==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(t==="skill_delete"){await this.handleSkillDeleteLocalAction(e);return}if(t==="skill_enable"){await this.handleSkillEnableLocalAction(e);return}if(t==="skill_disable"){await this.handleSkillDisableLocalAction(e);return}if(t==="skill_refresh"){this.handleSkillRefreshLocalAction(e);return}const r=(this.config.adapterType??"acp")==="opencode";if((o&&(t===k.interactionReply||t==="exec_approve"||t==="exec_reject")||r&&t===k.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||o&&await this.handleSessionControlLocalAction(e))return;if(t===k.sessionControl){const u=this.config.adapterType??"acp",f=u==="codex",b=u==="pi",v=String((e.params??{}).verb??"").trim().toLowerCase();if(f&&v===S.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(u==="cursor"&&v===S.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(f&&v==="restart"){const _=this.bindingStore.get(s)?.cwd??"";await this.pool.removeSlot(s).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:s,cwd:_,workerStatus:"ready"}}});return}if(b&&v===S.open){try{const C=e.params??{},_=String(C.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.cwdRequired,error_msg:"session cwd is required"});return}const A=await this.resolveCwdForBinding(_),x=String(C.agent_session_id??"").trim();this.ensureImportedAgentSession(x,A),this.bindingStore.set(s,A),this.setResolvedAgentSessionId(s,x),this.sessionBindings.set(s,A),await this.ensureSlotStarted(s).catch(H=>{if(zn(H))throw H;p.warn("bridge",`pi ensureSlotStarted on local-action bind failed (non-fatal): ${H instanceof Error?H.message:String(H)}`)}),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:"ready",cwd:A}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,A)}})}catch(C){this.failSessionOpen(C,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:A})})}return}if(b&&v===S.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((u==="openhuman"||u==="opencode")&&v===S.open){try{const C=e.params??{},_=String(C.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.cwdRequired,error_msg:"session cwd is required"});return}const A=await this.resolveCwdForBinding(_),x=String(C.agent_session_id??"").trim();this.ensureImportedAgentSession(x,A),this.bindingStore.set(s,A),this.setResolvedAgentSessionId(s,x),this.sessionBindings.set(s,A),await this.syncOpenCodeBinding(s,A),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,A)}})}catch(C){this.failSessionOpen(C,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:A})})}return}if(u==="codewhale"&&v===S.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(u==="deepseek-harness"&&v===S.open){await this.handleDeepSeekSessionControlLocalActionOpen(e);return}if(u==="acp"&&v===S.stop){const _=this.bindingStore.get(s)?.cwd??"";await this.pool.removeSlot(s).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:s,cwd:_,workerStatus:"stopped"}}});return}try{if(v===S.open){const C=e.params??{},_=String(C.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.cwdRequired,error_msg:"session cwd is required"});return}const A=String(C.agent_session_id??"").trim();if(A){const x=await this.resolveCwdForBinding(_);this.ensureImportedAgentSession(A,x)}}await this.handleSessionControlLocalActionForPool(e)}catch(C){this.failSessionOpen(C,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:A})});return}if(v===S.open){const C=e.params??{},_=await this.resolveCwdForBinding(String(C.cwd??"").trim());this.setResolvedAgentSessionId(s,String(C.agent_session_id??"").trim()),u==="agy"&&(this.bindingStore.set(s,_),this.sessionBindings.set(s,_)),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,_)}}),(this.config.adapterType??"acp")==="agy"&&(this.sendAgyBindingCard(s,_),this.refreshAndPushAgyQuota(s,!0))}else Wn(e,this.sessionControlCtx(s),this.sessionControlSenders(s));return}if(t==="file_list"){const u=Date.now(),f=s?this.bindingStore.get(s)?.cwd:void 0,b=e.params??{},v=String(b.parent_id??"").trim(),m=Array.isArray(b.allowed_extensions)?b.allowed_extensions.filter(_=>typeof _=="string").map(_=>_.trim()).filter(_=>_.length>0):[];p.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${s} parent_id=${v||"<root>"} show_hidden=${!!b.show_hidden} ext_count=${m.length} bound_cwd=${f??"<none>"}`);const w=await Vn({parent_id:v||null,session_id:s,show_hidden:!!b.show_hidden,allowed_extensions:m},{resolveCwd:()=>f??this.config.agent.cwd??process.cwd(),fallbackDir:Y()}),R=Date.now()-u,C=w.result?.files?.length??0;p.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${w.status} elapsed=${R}ms count=${C} current_path=${w.result?.current_path??""} error_code=${w.error_code??""} error_msg=${w.error_msg??""}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:w.status,...w.result?{result:{...w.result,machine_name:ti()}}:{},...w.error_code?{error_code:w.error_code}:{},...w.error_msg?{error_msg:w.error_msg}:{}});return}if(t==="create_folder"){const u=s?this.bindingStore.get(s)?.cwd:void 0,f=String((e.params??{}).parent_id??"").trim(),b=String((e.params??{}).name??"").trim(),v=await Zn({parent_id:f||null,name:b,session_id:s},{resolveCwd:()=>u??this.config.agent.cwd??process.cwd(),fallbackDir:Y()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:v.status,...v.result?{result:v.result}:{},...v.error_code?{error_code:v.error_code}:{},...v.error_msg?{error_msg:v.error_msg}:{}});return}if(t===k.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,s);return}if(t===k.getSessionUsage){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!s&&!!this.bindingStore.get(s)?.cwd})).handled)return;await this.handleGetSessionUsage(e,s);return}if(t===k.getRateLimits){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!s&&!!this.bindingStore.get(s)?.cwd})).handled)return;await this.handleGetRateLimits(e,s);return}const a=(this.config.adapterType??"acp")==="acp",c=(this.config.adapterType??"acp")==="cursor";if((o||a||c)&&t===k.threadCompact){await this.handleThreadCompact(e,s);return}if(t==="connector_rollback"){await this.handleConnectorRollback(e);return}if(t==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(t===k.getAgentGlobalConfig){const u=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...u?{config:u}:{config:null}}});return}if(t==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}if(t==="apply_relay_state"){await this.handleApplyRelayState(e);return}const d=this.config.adapterType??"acp",l=(d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness"||d==="acp")&&!!s&&!!this.bindingStore.get(s)?.cwd,h=await this.pool.deliverLocalAction(e,{autoCreateSlot:l});if(h.handled){if(h.kind==="set_mode"){const u=String((e.params??{}).mode_id??"");u&&(d==="cursor"?(this.bindingStore.setCursorModeId(s,u),this.globalConfigStore?.set(this.name,{cursorModeId:u})):d==="claude"?(this.bindingStore.setModeId(s,u),this.globalConfigStore?.set(this.name,{modeId:u})):d==="opencode"?(this.bindingStore.setModeId(s,u),this.globalConfigStore?.set(this.name,{modeId:u})):I.has(d)?d==="codex"&&this.globalConfigStore?.set(this.name,{codexModeId:u}):this.globalConfigStore?.set(this.name,{acpInitialMode:u}))}else if(h.kind==="set_model"){const u=String((e.params??{}).model_id??"").trim();if(u){d==="cursor"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="opencode"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="codewhale"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:u,codexReasoningEffort:void 0}):I.has(d)||this.globalConfigStore?.set(this.name,{modelId:u});const f=String((e.params??{}).provider??(e.params??{}).model_provider??"").trim()||void 0;this.refreshQuotaAfterModelSwitch(s,u,f)}}else if(h.kind==="set_reasoning_effort"){const u=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");u&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:u})}else if(h.kind==="set_sandbox_mode"){const u=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(u){const f=u==="default"?void 0:u;this.globalConfigStore?.set(this.name,{codexSandboxMode:f})}}else if(h.kind==="set_service_tier"){const u=String((e.params??{}).service_tier??(e.params??{}).serviceTier??(e.params??{}).value??"").trim();if(u){const f=u.toLowerCase()==="default"?void 0:u;this.globalConfigStore?.set(this.name,{codexServiceTier:f})}}return}if((d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness")&&s&&!this.bindingStore.get(s)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(d==="acp"&&(t==="set_mode"||t==="set_model")){const u=this.sessionControlSenders(s),f=this.pool.getSlot(s)?.adapter,b={bindingStore:this.bindingStore,acpAdapter:f instanceof y?f:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:p};if(t==="set_mode"){const v=String((e.params??{}).mode_id??""),m=await J(b,s,v);if(m.status==="failed")u.sendLocalActionResult(e.action_id,"failed",void 0,m.errorCode,m.errorMsg);else{const w=f instanceof y?f.buildToolbarContext(m.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,R=w?{...w,...m.result}:m.result;u.sendLocalActionResult(e.action_id,"ok",R)}}else{const v=String((e.params??{}).model_id??""),m=await z(b,s,v);if(m.status==="failed")u.sendLocalActionResult(e.action_id,"failed",void 0,m.errorCode,m.errorMsg);else{const w=f instanceof y?f.buildToolbarContext(m.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,R=w?{...w,...m.result}:m.result;u.sendLocalActionResult(e.action_id,"ok",R),m.result?.outcome==="model_set"&&this.refreshQuotaAfterModelSwitch(s,v)}}return}const g=!!s&&!!this.pool.getSlot(s);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:g?`Action type "${t}" is not supported by the current agent process.`:`No active agent process for this session. The reply to action "${t}" could not be delivered \u2014 please resend it as a new message.`})}finally{n?.()}}handleGetSessionUsage(e,t){return Kt(this,e,t)}handleThreadCompact(e,t){return zt(this,e,t)}handleGetRateLimits(e,t){return Qn(this,e,t)}resolveRateLimitWakeSessionId(e,t){return On(this,e,t)}wakeRateLimitSlot(e,t){return Bn(this,e,t)}sessionControlCtx(e){const t=this.pool.getSlot(e),s=t?.adapter instanceof y?t.adapter:null,i=(this.config.adapterType??"acp")==="acp",n={bindingStore:this.bindingStore,acpAdapter:s,globalConfigStore:this.globalConfigStore,agentName:this.name,log:p};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(s)return s.getSessionBindings();const o=this.sessionBindings;if(e&&!o.has(e)){const r=this.bindingStore.get(e);r?.cwd&&o.set(e,r.cwd)}return o},getStatus:()=>this.getStatus(),isAcpAlive:!!s?.isAlive(),getAcpSessionOptions:()=>s?.acpSessionOptions??null,setMode:o=>s?s.setMode(o):Promise.resolve(!1),setModel:o=>s?s.setModel(o):Promise.resolve(!1),acpSetMode:i?(o,r)=>J(n,o,r):void 0,acpSetModel:i?(o,r)=>z(n,o,r):void 0,getPendingApproval:o=>{const r=s?.pendingApprovalEntries.get(o);return r?{requestId:r}:void 0},deletePendingApproval:o=>s?.pendingApprovalEntries.delete(o)??!1,respondPermission:(o,r)=>(s&&s.respondToPermission(o,r),Promise.resolve()),onSessionBound:(o,r)=>{this.bindingStore.set(o,r)},onSessionUnbound:o=>{this.unbindSession(o).catch(r=>{p.warn(this.name,`session unbind cleanup failed: ${r instanceof Error?r.message:String(r)}`)})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&t?.adapter instanceof G?(t.adapter.cancelCurrentRun(),Promise.resolve()):t?.adapter?.cancel("")??Promise.resolve(),onModeSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModeId:o}):r==="opencode"?this.bindingStore.setModeId(e,o):I.has(r)||this.globalConfigStore?.set(this.name,{acpInitialMode:o})},onModelSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:o}):r==="opencode"?this.bindingStore.setModelId(e,o):I.has(r)||this.globalConfigStore?.set(this.name,{modelId:o}),this.refreshQuotaAfterModelSwitch(e,o)}}}sessionControlSenders(e){return{sendEventAck:(t,s)=>this.aibotHandle.sendEventAck({event_id:t,session_id:s,received_at:Date.now()}),sendEventResult:(t,s,i)=>this.aibotHandle.sendEventResult({event_id:t,status:s,...i?.msg?{msg:i.msg}:{},...i?.code?{code:i.code}:{},updated_at:Date.now()}),sendLocalActionResult:(t,s,i,n,o)=>this.aibotHandle.sendLocalActionResult({action_id:t,status:s,...i?{result:i}:{},...n?{error_code:n}:{},...o?{error_msg:o}:{}},e)}}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"deepseek-harness":return"deepseek";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,t){this.sendCtrl.finalizeThinking(e,t)}logInboundConversation(e){const t=String(e.session_id??"").trim();t&&this.conversationLog?.logInbound(t,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}resolveAuditProvider(){const e=this.config.adapterType??"acp";return e==="claude"||e==="codex"||e==="cursor"||e==="opencode"||e==="pi"||e==="codewhale"||e==="deepseek-harness"||e==="agy"?e:"acp"}sendAuditConfigurationError(e,t){const s=t instanceof Error?t.message:String(t),i=(()=>{const a=V(e.extra);return a.options?.enabled===!0&&a.options.scope==="turn"})(),n=t instanceof ki||t instanceof Ei,o=t instanceof Pi&&i,r=o?"audit_config_invalid":n?t.code:"audit_config_conflict";if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:r,msg:s,updated_at:Date.now()}),n||o)try{this.aibotHandle.sendAuditState($({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:r,errorMessage:s},Date.now()))}catch{}}markAuditAdapterClosed(e,t){const i=this.pool.getSlot(t)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,i)}prepareAuditedInboundEvent(e,t,s){const i=this.buildInboundEvent(e,t),n=this.bindingStore.get(e.session_id),o=n?this.resolveAgentSessionId(n):void 0,r=Number(e.created_at),a=Number.isFinite(r)&&r>0?new Date(r).toISOString():void 0,c=this.auditController.startTurn({session:s,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...a===void 0?{}:{startedAt:a},boundary:{adapterType:this.config.adapterType??"acp",...o?{providerSessionId:o}:{}}});return c&&(i.audit={enabled:!0,auditId:c.auditId,turnId:c.turnId,...s?{scope:s.options.scope,profile:s.options.profile,...s.options.retentionDays===void 0?{}:{retentionDays:s.options.retentionDays},capture:{...s.options.capture}}:{},rawProviderBody:s?.options.capture.rawProviderBody===!0}),i}buildInboundEvent(e,t){const s=di(this.sendCtrl.getGlobalRuntimeConfig(),t),i=yi(e.extra);return{event_id:e.event_id,session_id:e.session_id,thread_id:e.thread_id,sender_id:e.sender_id,msg_id:e.msg_id,msg_type:e.msg_type,content:e.content??"",quoted_message_id:e.quoted_message_id,context_messages_json:this.buildContextMessagesJson(e.context_messages),extra_json:i===void 0?void 0:JSON.stringify(i),connector_runtime_config:{response_delivery:s.responseDelivery,tool_events:s.toolEvents,thinking_events:s.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const t=e.filter(s=>!Gn(String(s?.content??"")));if(t.length!==0)return JSON.stringify(t)}isStaleEvent(e){const t=Number(e.created_at);return!Number.isFinite(t)||t<=0?!1:Date.now()-t>Ti}setUpgradeTrigger(e){this.upgradeTrigger=e}setDaemonShutdownRequester(e){this.daemonShutdownRequester=e}setLifecycleBusyChecker(e){this.lifecycleBusyChecker=e}setLifecycleAdmissionCloser(e){this.lifecycleAdmissionCloser=e}setLifecycleAdmissionRestorer(e){this.lifecycleAdmissionRestorer=e}closeLifecycleAdmission(){this.lifecycleBarrier.setAutoOpenHandler(e=>{p.warn(this.name,`Lifecycle admission auto-reopened after ${Math.round(e/1e3)}s: a restart was expected but never happened. Admission is open again and events flow; the pending restart or upgrade did not complete.`)}),this.lifecycleBarrier.close()}openLifecycleAdmission(){this.lifecycleBarrier.open()}closeLifecycleAdmissionForRestart(){this.lifecycleAdmissionCloser?this.lifecycleAdmissionCloser():this.closeLifecycleAdmission()}setInstallAgentHandler(e){this.installAgentHandler=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setSkillSyncHandler(e){this.skillSyncHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}setRelayStateApplyPorts(e){this.relayStateApplyPorts=e}}export{ao as AgentInstance};
|
|
9
|
+
Error: ${r}`,1,!1))}sendEventResultWithCleanup(e,i,r,n,t=!1){const s=this.eventSessionIndex.get(e);t&&this.surfacedRunErrorEvents.add(e),i==="failed"&&s&&r?.trim()&&this.sendRunErrorAsChunk(e,s,r),this.auditController.markResponded(e,i,r),this.sendCtrl.sendEventResult(e,i,r,n),s&&(this.pool.eventComplete(e,s)===!1&&h.error(this.name,`Event terminal result could not release queue slot event=${e} session=${s} status=${i}`),this.pushQueueSnapshotForSession(s),this.conversationLog?.logResult?.(s,e,i,r),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorEvents.delete(e),this.pendingStartedEventIds.delete(e),this.pendingEvents.remove(e).catch(o=>{h.warn(this.name,`Failed to remove terminal event from pending store event=${e}: ${o instanceof Error?o.message:String(o)}`)}),i==="responded"&&(this.config.adapterType??"acp")!=="agy"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:i,sessionId:r,errorMsg:n}=e;if(this.stopped)return;const t=this.inflightEvents.get(i);if(!t){h.warn(this.name,`[recovery] no inflight event for internalError event=${i} session=${r}; surface failure directly`),this.sendRunErrorAsChunk(i,r,n),this.sendEventResultWithCleanup(i,"failed",n,"agent_stop_failure");return}const s=(this.restartCount.get(i)??0)+1;this.restartCount.set(i,s);const o=this.config.adapterType??"acp";if(s>P){h.error(this.name,`[recovery] adapter=${o} session=${r} event=${i} restart=${s}/${P} outcome=give-up err=${n}`),this.sendRunErrorAsChunk(i,r,n),this.sendEventResultWithCleanup(i,"failed",n,"agent_stop_failure");return}h.info(this.name,`[recovery] adapter=${o} session=${r} event=${i} restart=${s}/${P} outcome=restarting err=${n}`);const a=this.pool.drainQueuedForSession(r);a.length>0&&h.info(this.name,`[recovery] session=${r} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(r)}catch(c){h.warn(this.name,`[recovery] removeSlot failed session=${r}: ${c instanceof Error?c.message:String(c)}`)}if(this.stopped)return;const l=e.replayOriginalContent?t.content:this.resolveRecoveryPrompt(o,t),d={...t,content:l};try{await this.pool.deliverInboundEvent(d)}catch(c){h.error(this.name,`[recovery] redeliver failed event=${i} session=${r}: ${c instanceof Error?c.message:String(c)}`),this.sendEventResultWithCleanup(i,"failed",c instanceof Error?c.message:String(c));return}for(const c of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(c)}catch(u){h.error(this.name,`[recovery] sibling redeliver failed event=${c.event_id} session=${r}: ${u instanceof Error?u.message:String(u)}`),this.sendEventResultWithCleanup(c.event_id,"failed",u instanceof Error?u.message:String(u))}}}resolveRecoveryPrompt(e,i){return e==="acp"?"continue":i.content}sendThinkingByRuntimeConfig(e,i,r){this.sendCtrl.sendThinking(e,i,r)}bufferStreamChunk(e,i,r,n,t){this.auditController.captureUnsequencedStreamChunk(e,r),this.sendCtrl.bufferOnly(e,i,r,n,t)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),this.auditController.markRecording(e.event_id),e.event_id&&!this.inflightEvents.has(e.event_id)&&this.inflightEvents.set(e.event_id,e)}async replayPendingEventsOnStartup(){const e=await this.pendingEvents.loadForReplay();if(e.length===0)return;const i=new Set(e.map(n=>n.event.event_id).filter(Boolean)),r=[];h.warn(this.name,`Replaying ${e.length} pending event(s) from previous run`);for(const n of e){if(this.stopped)break;const t=n.event;this.pendingEvents.startReplay(n);try{if(n.kind==="deferred"){const s=this.bindingStore.get(n.sessionId);s?.cwd?(await this.prepareBoundDeferredReplay(n,s.cwd),await this.deliverPendingReplayEvent(t),this.pendingStartedEventIds.has(t.event_id)||r.push(n)):(this.restorePendingReplayAuditTurn(t),this.deferredMgr.defer(n.channel,n.sessionId,t),r.push(n))}else await this.deliverPendingReplayEvent(t),this.pendingStartedEventIds.has(t.event_id)||r.push(n)}catch(s){const o=s instanceof Error?s.message:String(s);h.error(this.name,`Pending event replay failed event=${t.event_id}: ${o}`),this.sendEventResultWithCleanup(t.event_id,"failed",o),this.pendingEvents.markCanceled(t.event_id),await this.pendingEvents.remove(t.event_id).catch(()=>{})}finally{this.pendingEvents.finishReplay(n),await this.pendingEvents.checkpointReplay(i,[...r,...this.pendingEvents.replaySnapshot()])}if(this.stopped)break}this.stopped||(this.pendingEvents.finishAllReplay(),await this.pendingEvents.checkpointReplay(i,r))}failEventIfLifecycleDraining(e,i="connector is draining for restart; control command was not executed"){return this.lifecycleBarrier.isClosed()?(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_lifecycle_draining",msg:i,updated_at:Date.now()}),!0):!1}sendCanceledPendingEventResult(e,i){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),this.sendEventResultWithCleanup(e.event_id,"canceled",i),this.auditController.markAdapterClosed(e.event_id,{adapterNotStarted:!0})}async deliverPendingReplayEvent(e){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),await this.pool.deliverInboundEvent(e)}async prepareBoundDeferredReplay(e,i){this.sessionBindings.set(e.sessionId,i),e.channel==="acp"?await this.bindSessionForPool(e.sessionId,i):e.channel==="opencode"&&await this.syncOpenCodeBinding(e.sessionId,i)}restorePendingReplayAuditTurn(e){const i=e.audit;if(!i?.enabled||!i.auditId||!i.capture||!i.profile||!i.scope)return;const r=vi({enabled:!0,scope:i.scope,profile:i.profile,capture:i.capture,...i.retentionDays===void 0?{}:{retentionDays:i.retentionDays}});if(!r.enabled)return;const n=Object.freeze({auditId:i.auditId,businessSessionId:e.session_id,provider:this.resolveAuditProvider(),options:r,createdAt:new Date().toISOString()}),t=this.auditController.startTurn({session:n,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...Number.isFinite(Number(e.created_at))&&Number(e.created_at)>0?{startedAt:new Date(Number(e.created_at)).toISOString()}:{},boundary:{adapterType:this.config.adapterType??"acp"}});t&&(e.audit={...i,auditId:t.auditId,turnId:t.turnId,profile:n.options.profile,capture:{...n.options.capture},rawProviderBody:n.options.capture.rawProviderBody})}indexEventSession(e,i){if(!e||!i)return;const r=this.eventSessionIndex.get(e);return r?(r!==i&&h.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${r} supplied=${i}`),r):(this.eventSessionIndex.set(e,i),i)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,i){return this.sendCtrl.shouldDropCodexDisplayEvent(e,i)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const r=e.codex_payload?.params?.delta;if(!r)return;const n=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(n,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:r.length,content:r})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,i){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,i)}sendAcpRawEventEnvelope(e,i,r){this.shouldDropAcpRawDisplayEvent(e,r.type)||this.deliverRawEventEnvelope(e,i,r,"acp",this.buildAcpRawEventFallbackText(r))}buildAcpRawEventFallbackText(e){const i=String(e.type??"").trim();if(!i)return"[acp] event";switch(i){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] ${i}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,i,r,n,t){const s=ri({envelope:r,fallbackText:t,channelKey:n,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),o=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:i,msg_type:1,content:s.fallbackText,extra:{channel_data:{[n]:{raw_event:s.envelope}},agent_api_origin:!0}})};if(!s.sharded){o();return}h.info("bridge",`${n} raw_event oversized, sharded delivery: event=${e} fields=${s.oversizedFields.map(a=>a.field).join(",")}`),(async()=>{for(const a of s.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,i,ai({envelopeType:r.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);o()})().catch(a=>{h.warn("bridge",`${n} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const i=String(e?.type??"").trim(),r=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(i){case"permission_request":return`Permission required: ${String(r.tool_title??r.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(r.tool_name??r.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(r.message??"agent error")}`;default:return i?`[cursor] ${i}`:"[cursor] event"}}sendToolExecutionCard(e,i,r,n){this.sendCtrl.sendToolExecutionCard(e,i,r,n)}sendGrixApprovalCard(e,i){this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${R()}`,msg_type:1,content:e.toolTitle?`Permission required: ${e.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:e.approvalId,approvalSlug:e.toolName},grix:{execApproval:{approval_command_id:e.approvalId,command:e.toolTitle||e.toolName,host:i}}},agent_api_origin:!0}})}sendGrixAgentQuestionCard(e,i,r){const n=r.questions.map(s=>s.header).join(", "),t=I(`[Agent Question] ${r.request_id}`,"agent_question",r);this.aibotHandle.sendText({event_id:e,session_id:i,content:t,msg_type:1,extra:{card_type:"agent_question",summary_text:n}})}async handleAgentQuestionReplyEvent(e){const i=_n(String(e.content??""));if(!i)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const n=this.pool.getSlot(e.session_id)?.adapter,t=n instanceof S?"acp":n instanceof k?"opencode":this.config.adapterType??"unknown",s=n instanceof k?n.handleQuestionReplyEvent(i):n instanceof S?await n.handleQuestionReplyEvent(i):{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};return s.delivered?(h.info(this.name,`[${t}] question reply delivered event=${e.event_id} session=${e.session_id} request=${i.request_id}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(h.warn(this.name,`[${t}] question reply rejected event=${e.event_id} session=${e.session_id} request=${i.request_id} code=${s.errorCode??"interaction_reply_failed"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:s.errorCode??"interaction_reply_failed",msg:s.errorMsg??"The question reply was not delivered.",updated_at:Date.now()})),!0}async handleExecApprovalResolutionEvent(e){const i=vn(String(e.content??""));if(!i)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const n=this.pool.getSlot(e.session_id)?.adapter,t=i.params,s=String(t.tool_call_id??t.approval_command_id??t.approval_id??t.exec_context_id??""),o=n?.handleExecApprovalEvent?await n.handleExecApprovalEvent({...t,event_id:e.event_id,session_id:e.session_id}):{delivered:!1,errorCode:"approval_not_supported",errorMsg:"The current adapter does not support exec approval resolution events."};return o.delivered?(h.info(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution delivered event=${e.event_id} session=${e.session_id} approval=${s||"-"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(h.warn(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution rejected event=${e.event_id} session=${e.session_id} approval=${s||"-"} code=${o.errorCode}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:o.errorCode,msg:o.errorMsg,updated_at:Date.now()})),!0}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 i=this.config.adapterType??"acp",r=fn(e);let n;if(r&&(n=this.lifecycleBarrier.tryEnter()??void 0,!n)){this.failEventIfLifecycleDraining(e);return}try{if(await this.handleCliInstallQuestionReply(e)||(i==="opencode"||i==="acp")&&await this.handleAgentQuestionReplyEvent(e)||await this.handleExecApprovalResolutionEvent(e))return;const t=ei(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,o=B(e.extra);if(Sn(this,e,i,o))return;if(r){await bn(this,r,e,i,o);return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}let a;try{a=this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra,eventId:e.event_id}).session}catch(c){this.sendAuditConfigurationError(e,c);return}if(await Cn(this,e,i,wi.has(i),s,a))return;if((this.config.adapterType??"acp")==="acp"){const u=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(u){const[,g,p]=u,A=this.pool.getSlot(e.session_id)?.adapter;if(A?.execCommand&&(A.getSupportedCommands?.()??[]).some(m=>m.name===g||m.name===`/${g}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const m=await A.execCommand(g,p.trim(),e.session_id);m.status==="options"&&m.data&&this.handleExecCommandOptions(e.session_id,g,m.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:m.status==="failed"?"failed":"responded",msg:m.message,updated_at:Date.now()})}catch(m){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:m instanceof Error?m.message:String(m),updated_at:Date.now()})}return}}}if(i==="codex"&&Q(a?.options)){const c=this.pool.getSlot(e.session_id);if(c?.adapter instanceof D&&!c.adapter.hasRawApiCaptureRelay()){const u=c.eventQueue.snapshot(e.session_id);u.running.length===0&&u.queued.length===0?(h.info(this.name,`[audit-raw-capture] recreating idle Codex adapter before event=${e.event_id} session=${e.session_id}`),await this.pool.removeSlot(e.session_id)):h.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${u.running.length} queued=${u.queued.length}`)}}const d=this.prepareAuditedInboundEvent(e,s,a);try{const c=await this.pendingEvents.append({kind:"queued",event:d});if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(d,"canceled");return}if(this.lifecycleBarrier.isClosed()){if(!c)throw new Error("pending event store unavailable during lifecycle drain");this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),h.info(this.name,`Persisted inbound event during lifecycle drain: ${e.event_id}`);return}this.captureEventRuntimeConfig(d),await this.pool.deliverInboundEvent(d)}catch(c){await this.pendingEvents.remove(e.event_id).catch(u=>{h.warn(this.name,`Failed to remove undelivered pending event=${e.event_id}: ${u instanceof Error?u.message:String(u)}`)}),this.failUndeliveredInboundEvent(e,c)}}finally{n?.()}}failUndeliveredInboundEvent(e,i){const r=i instanceof Error?i.message:String(i);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",r,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:r,updated_at:Date.now()})}handleCodexSessionControlOpen(e,i){return it(this,e,i)}handleSessionControlForPool(e,i){return st(this,e,i)}handleSessionControlLocalActionForPool(e){return ot(this,e)}handleCodexSessionControlLocalActionOpen(e){return rt(this,e)}handleCursorSessionControlLocalActionOpen(e){return at(this,e)}handlePiSessionControlOpen(e,i){return dt(this,e,i)}handlePiSessionControlRestart(e){return lt(this,e)}handlePiSessionControlRestartLocalAction(e){return ct(this,e)}syncOpenCodeBinding(e,i){return ht(this,e,i)}isWorkspaceFreeClient(){return ut(this)}ensureDefaultBindingForWorkspaceFreeClient(e,i){return pt(this,e,i)}bindSessionForPool(e,i){return gt(this,e,i)}deferredCallbacks(){return ft(this)}handleOpenHumanSessionControlOpen(e,i){return mt(this,e,i)}handleCodeWhaleSessionControlOpen(e,i){return vt(this,e,i)}handleCodeWhaleSessionControlLocalActionOpen(e){return _t(this,e)}handleDeepSeekSessionControlLocalActionOpen(e){return St(this,e)}normalizeClaudeModeId(e){return Ht(this,e)}handleExecCommandOptions(e,i,r){$t(this,e,i,r)}resolveSessionModelId(e){return Qt(this,e)}resolveSessionModeId(e){return It(this,e)}resolveCursorSessionModeId(e){return Ot(this,e)}resolveClaudeSessionEffort(e){return Bt(this,e)}resolveClaudeSessionModeId(e){return Ft(this,e)}currentClaudeModeId(e){return Ut(this,e)}resolveCodexSessionModelId(e){return qt(this,e)}resolveCodexNewSessionGlobalDefault(e,i,r){return Nt(this,e,i,r)}pinCodexGlobalDefault(e,i){return Wt(this,e,i)}buildCursorToolbarMeta(e){return Gt(this,e)}buildAgyToolbarMeta(e,i){return jt(this,e,i)}buildAgyQuotaMeta(e){return Kt(this,e)}sendAgyBindingCard(e,i,r){return zt(this,e,i,r)}refreshAndPushAgyQuota(e,i=!1){return Jt(this,e,i)}handleAgySetModel(e,i){return Yt(this,e,i)}buildClaudeToolbarMeta(e){return Xt(this,e)}providerQuotaToCodexRateLimits(e){return si(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return ii(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){return Un(e)}failSessionOpen(e,i){return On(this,e,i)}getClaudeWorkerStatus(e){return Bn(this,e)}refreshClaudeWorkerStatusCard(e,i){return Fn(this,e,i)}async ensureSlotStarted(e,i=6e4){return In(this,e,i)}maybeOfferCliInstall(e){Le(this,e)}handleCliInstallQuestionReply(e){return De(this,e)}handleCliInstallInteractionReply(e){return He(this,e)}runConfirmedCliInstall(e,i){return $e(this,e,i)}handleSkillDeleteLocalAction(e){return At(this,e)}handleSkillUploadLocalAction(e){return Et(this,e)}handleSkillEnableLocalAction(e){return wt(this,e)}handleSkillRefreshLocalAction(e){yt(this,e)}handleSkillDisableLocalAction(e){return Rt(this,e)}computeSkillReport(e){return kt(this,e)}reportSessionSkills(e){Tt(this,e)}skillsSyncGroupKey(){return Pt(this)}forceRefreshSkills(e,i){return xt(this,e,i)}adoptSkillsWireHashFromDisk(){Mt(this)}buildLibrarySkillsReport(e){return Lt(this,e)}skillLookupEnv(){return Dt(this)}resolveOrphanTitle(e){return Dn(this,e)}resolveAgentSessionId(e){return Ln(this,e)}providerKeyForAdapter(){return Mn(this)}setResolvedAgentSessionId(e,i){Hn(this,e,i)}normalizePathForCompare(e){return xn(e)}ensureImportedAgentSession(e,i){Tn(this,e,i)}buildOpenedBindingResult(e,i,r="ready"){return kn(this,e,i,r)}buildDshOpenedToolbarMeta(e){return $n(this,e)}dshCatalogDataRoot(){return Qn(this)}hasDiskScanner(){return Pn(this)}unbindSession(e){return Xe(this,e)}handleUnbindTextCommand(e){return Ve(this,e)}handleUnbindLocalAction(e){return Ze(this,e)}handleListSessionsTextCommand(e){return et(this,e)}handleListSessionsLocalAction(e){return tt(this,e)}handleSyncHistoryLocalAction(e){return nt(this,e)}handleSessionControlCommand(e,i){return xe(this,e,i)}handleSessionControlLocalAction(e){return Me(this,e)}handleEventCancel(e){return Qe(this,e)}waitForEventDone(e,i,r){return Ie(this,e,i,r)}handleAibotStop(e){Oe(this,e)}killAndResumeStopSlot(e,i){return Be(this,e,i)}handleAibotRevoke(e){return Fe(this,e)}handleConfigureGatewayProvider(e){return Ue(this,e)}getAuditLocalActionHandler(){return qe(this)}handleAuditLocalAction(e){return Ne(this,e)}handleConnectorRollback(e){return We(this,e)}getRelayStateSyncer(){return Ge(this)}relayStateSyncOnConnect(){je(this)}reportRelayStateLocalChange(){Ke(this)}handleApplyRelayState(e){return ze(this,e)}fetchRelayCredential(e){return Je(this,e)}isSharedInstance(){return Ye(this)}async handleAibotLocalAction(e){if(this.stopped){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is shutting down; local action was not executed"});return}const i=e.action_type??"",r=String((e.params??{}).session_id??""),n=String((e.params??{}).verb??"").trim().toLowerCase();h.debug(this.name,`local_action received action_type=${i} verb=${n||"-"} action_id=${e.action_id} session_id=${r}`);let t;if(i===f.sessionControl&&(t=this.lifecycleBarrier.tryEnter()??void 0,!t)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is draining for restart; session control was not executed"});return}try{if(i===f.interactionReply&&await this.handleCliInstallInteractionReply(e))return;if(Y(i)){await this.handleAuditLocalAction(e);return}const s=(this.config.adapterType??"acp")==="claude";if(i===f.sessionControl&&n===E.exec&&await this.handleSessionControlLocalAction(e))return;if(i===f.sessionControl&&n===E.listSessions){await this.handleListSessionsLocalAction(e);return}if(i===f.sessionControl&&n===E.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(i===f.sessionControl&&n===E.unbind){await this.handleUnbindLocalAction(e);return}if(i==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(i==="skill_delete"){await this.handleSkillDeleteLocalAction(e);return}if(i==="skill_enable"){await this.handleSkillEnableLocalAction(e);return}if(i==="skill_disable"){await this.handleSkillDisableLocalAction(e);return}if(i==="skill_refresh"){this.handleSkillRefreshLocalAction(e);return}const o=(this.config.adapterType??"acp")==="opencode";if((s&&(i===f.interactionReply||i==="exec_approve"||i==="exec_reject")||o&&i===f.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||s&&await this.handleSessionControlLocalAction(e))return;if(i===f.sessionControl){await An(this,e,r);return}if(i==="file_list"){await wn(this,e,r);return}if(i==="create_folder"){await En(this,e,r);return}if(i===f.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,r);return}if(i===f.getSessionUsage){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!r&&!!this.bindingStore.get(r)?.cwd})).handled)return;await this.handleGetSessionUsage(e,r);return}if(i===f.getRateLimits){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!r&&!!this.bindingStore.get(r)?.cwd})).handled)return;await this.handleGetRateLimits(e,r);return}const a=(this.config.adapterType??"acp")==="acp",l=(this.config.adapterType??"acp")==="cursor";if((s||a||l)&&i===f.threadCompact){await this.handleThreadCompact(e,r);return}if(i==="connector_rollback"){await this.handleConnectorRollback(e);return}if(i==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(i===f.getAgentGlobalConfig){const p=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...p?{config:p}:{config:null}}});return}if(i==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}if(i==="apply_relay_state"){await this.handleApplyRelayState(e);return}const d=this.config.adapterType??"acp",c=(d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness"||d==="acp")&&!!r&&!!this.bindingStore.get(r)?.cwd,u=await this.pool.deliverLocalAction(e,{autoCreateSlot:c});if(u.handled){Rn(this,e,r,d,u,p=>T.has(p));return}if((d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness")&&r&&!this.bindingStore.get(r)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:$.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(d==="acp"&&(i==="set_mode"||i==="set_model")){await yn(this,e,r,i);return}const g=!!r&&!!this.pool.getSlot(r);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:g?`Action type "${i}" is not supported by the current agent process.`:`No active agent process for this session. The reply to action "${i}" could not be delivered \u2014 please resend it as a new message.`})}finally{t?.()}}handleGetSessionUsage(e,i){return Ct(this,e,i)}handleThreadCompact(e,i){return bt(this,e,i)}handleGetRateLimits(e,i){return cn(this,e,i)}resolveRateLimitWakeSessionId(e,i){return hn(this,e,i)}wakeRateLimitSlot(e,i){return un(this,e,i)}sessionControlCtx(e){const i=this.pool.getSlot(e),r=i?.adapter instanceof S?i.adapter:null,n=(this.config.adapterType??"acp")==="acp",t={bindingStore:this.bindingStore,acpAdapter:r,globalConfigStore:this.globalConfigStore,agentName:this.name,log:h};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(r)return r.getSessionBindings();const s=this.sessionBindings;if(e&&!s.has(e)){const o=this.bindingStore.get(e);o?.cwd&&s.set(e,o.cwd)}return s},getStatus:()=>this.getStatus(),isAcpAlive:!!r?.isAlive(),getAcpSessionOptions:()=>r?.acpSessionOptions??null,setMode:s=>r?r.setMode(s):Promise.resolve(!1),setModel:s=>r?r.setModel(s):Promise.resolve(!1),acpSetMode:n?(s,o)=>Nn(t,s,o):void 0,acpSetModel:n?(s,o)=>qn(t,s,o):void 0,getPendingApproval:s=>{const o=r?.pendingApprovalEntries.get(s);return o?{requestId:o}:void 0},deletePendingApproval:s=>r?.pendingApprovalEntries.delete(s)??!1,respondPermission:(s,o)=>(r&&r.respondToPermission(s,o),Promise.resolve()),onSessionBound:(s,o)=>{this.bindingStore.set(s,o)},onSessionUnbound:s=>{this.unbindSession(s).catch(o=>{h.warn(this.name,`session unbind cleanup failed: ${o instanceof Error?o.message:String(o)}`)})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&i?.adapter instanceof H?(i.adapter.cancelCurrentRun(),Promise.resolve()):i?.adapter?.cancel("")??Promise.resolve(),onModeSet:s=>{const o=this.config.adapterType??"acp";o==="codex"?this.globalConfigStore?.set(this.name,{codexModeId:s}):o==="opencode"?this.bindingStore.setModeId(e,s):T.has(o)||this.globalConfigStore?.set(this.name,{acpInitialMode:s})},onModelSet:s=>{const o=this.config.adapterType??"acp";o==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:s}):o==="opencode"?this.bindingStore.setModelId(e,s):T.has(o)||this.globalConfigStore?.set(this.name,{modelId:s}),this.refreshQuotaAfterModelSwitch(e,s)}}}sessionControlSenders(e){return{sendEventAck:(i,r)=>this.aibotHandle.sendEventAck({event_id:i,session_id:r,received_at:Date.now()}),sendEventResult:(i,r,n)=>this.aibotHandle.sendEventResult({event_id:i,status:r,...n?.msg?{msg:n.msg}:{},...n?.code?{code:n.code}:{},updated_at:Date.now()}),sendLocalActionResult:(i,r,n,t,s)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:r,...n?{result:n}:{},...t?{error_code:t}:{},...s?{error_msg:s}:{}},e)}}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"deepseek-harness":return"deepseek";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,i){this.sendCtrl.finalizeThinking(e,i)}logInboundConversation(e){const i=String(e.session_id??"").trim();i&&this.conversationLog?.logInbound(i,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}resolveAuditProvider(){const e=this.config.adapterType??"acp";return e==="claude"||e==="codex"||e==="cursor"||e==="opencode"||e==="pi"||e==="codewhale"||e==="deepseek-harness"||e==="agy"?e:"acp"}sendAuditConfigurationError(e,i){const r=i instanceof Error?i.message:String(i),n=(()=>{const a=B(e.extra);return a.options?.enabled===!0&&a.options.scope==="turn"})(),t=i instanceof mi||i instanceof fi,s=i instanceof Si&&n,o=s?"audit_config_invalid":t?i.code:"audit_config_conflict";if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:o,msg:r,updated_at:Date.now()}),t||s)try{this.aibotHandle.sendAuditState(O({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:o,errorMessage:r},Date.now()))}catch{}}markAuditAdapterClosed(e,i){const n=this.pool.getSlot(i)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,n)}prepareAuditedInboundEvent(e,i,r){const n=this.buildInboundEvent(e,i),t=this.bindingStore.get(e.session_id),s=t?this.resolveAgentSessionId(t):void 0,o=Number(e.created_at),a=Number.isFinite(o)&&o>0?new Date(o).toISOString():void 0,l=this.auditController.startTurn({session:r,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...a===void 0?{}:{startedAt:a},boundary:{adapterType:this.config.adapterType??"acp",...s?{providerSessionId:s}:{}}});return l&&(n.audit={enabled:!0,auditId:l.auditId,turnId:l.turnId,...r?{scope:r.options.scope,profile:r.options.profile,...r.options.retentionDays===void 0?{}:{retentionDays:r.options.retentionDays},capture:{...r.options.capture}}:{},rawProviderBody:r?.options.capture.rawProviderBody===!0}),n}buildInboundEvent(e,i){const r=Zn(this.sendCtrl.getGlobalRuntimeConfig(),i),n=_i(e.extra);return{event_id:e.event_id,session_id:e.session_id,thread_id:e.thread_id,sender_id:e.sender_id,msg_id:e.msg_id,msg_type:e.msg_type,content:e.content??"",quoted_message_id:e.quoted_message_id,context_messages_json:this.buildContextMessagesJson(e.context_messages),extra_json:n===void 0?void 0:JSON.stringify(n),connector_runtime_config:{response_delivery:r.responseDelivery,tool_events:r.toolEvents,thinking_events:r.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const i=e.filter(r=>!mn(String(r?.content??"")));if(i.length!==0)return JSON.stringify(i)}isStaleEvent(e){const i=Number(e.created_at);return!Number.isFinite(i)||i<=0?!1:Date.now()-i>Ci}setUpgradeTrigger(e){this.upgradeTrigger=e}setDaemonShutdownRequester(e){this.daemonShutdownRequester=e}setLifecycleBusyChecker(e){this.lifecycleBusyChecker=e}setLifecycleAdmissionCloser(e){this.lifecycleAdmissionCloser=e}setLifecycleAdmissionRestorer(e){this.lifecycleAdmissionRestorer=e}closeLifecycleAdmission(){this.lifecycleBarrier.setAutoOpenHandler(e=>{h.warn(this.name,`Lifecycle admission auto-reopened after ${Math.round(e/1e3)}s: a restart was expected but never happened. Admission is open again and events flow; the pending restart or upgrade did not complete.`)}),this.lifecycleBarrier.close()}openLifecycleAdmission(){this.lifecycleBarrier.open()}closeLifecycleAdmissionForRestart(){this.lifecycleAdmissionCloser?this.lifecycleAdmissionCloser():this.closeLifecycleAdmission()}setInstallAgentHandler(e){this.installAgentHandler=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setSkillSyncHandler(e){this.skillSyncHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}setRelayStateApplyPorts(e){this.relayStateApplyPorts=e}}export{oo as AgentInstance,T as PER_SESSION_ADAPTERS};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import P from"node:path";import{createHash as T}from"node:crypto";import{buildDshBindingToolbarMeta as E,DEFAULT_DSH_PRESETS as H,listDshPlugins as M,listDshSkills as O,listDshProfiles as R,normalizeDshReasoningEffort as A,normalizeDshThinking as _,resolveDshAgentPreset as L,resolveDshCatalogForToolbar as y,resolveDshModeId as k,resolveDshSelectedProfileName as x}from"../adapter/deepseek-harness/index.js";import{syncDefaultSkillsToDir as B}from"../default-skills/index.js";import{GRIX_PATHS as C}from"../core/log/index.js";const G=[],K=["name","config","bindingStore","globalConfigStore"];function j(e){const o=T("sha256").update(e.config.aibot.agentId).digest("hex").slice(0,24);return P.join(C.data,"deepseek-harness",o)}function U(e,o){const i=e.globalConfigStore?.get(e.name),n=e.bindingStore.get(o),s=e.config.adapterOptions??{},f=typeof s.dshHome=="string"?s.dshHome:void 0;if(!e.bindingStore.getDshAgentPreset(o)){const l=L(i?.dshAgentPreset,H);e.bindingStore.setDshAgentPreset(o,l)}const h=e.bindingStore.getDshSelectedProfile(o),g=x({binding:h,global:i?.dshProfile,adapter:typeof s.dshProfile=="string"?s.dshProfile:void 0});h||e.bindingStore.setDshSelectedProfile(o,g);const c=j(e),p=e.bindingStore.getDshSettings(o),u=p?.providerId??i?.dshProviderId,d=y({dataRoot:c,providerId:u}),a=[p?.modelId,i?.dshModelId,d.models[0]?.id].find(l=>!!l&&d.models.some(v=>v.id===l))??d.models[0]?.id,I=k(n?.dshModeId,i?.dshModeId),t={};!n?.dshProviderId&&d.providerId&&(t.providerId=d.providerId),!n?.dshModelId&&a&&(t.modelId=a),n?.dshModeId||(t.modeId=I),n?.dshThinking||(t.thinking=_(i?.dshThinking)??"enabled"),n?.dshReasoningEffort||(t.reasoningEffort=A(i?.dshReasoningEffort)??"high"),Object.keys(t).length>0&&e.bindingStore.updateDshSettings(o,t);const r=e.bindingStore.getDshSettings(o);let S=[],m=[],b=!1;try{S=M({dshHome:f,profileName:g,enabledPluginIds:e.bindingStore.getDshEnabledPlugins(o)}),b=!1}catch{}const D=P.join(c,"dsh-session-skills");return B(D),m=O({skillsDir:D,enabledSkillIds:e.bindingStore.getDshEnabledSkills(o)}),E({agentPreset:r?.agentPreset,agentPresetLocked:e.bindingStore.isDshAgentPresetLocked(o),profileName:g,profiles:R({dshHome:f}),profileLocked:e.bindingStore.isDshProfileLocked(o),plugins:S,skills:m,pluginRestartRequired:b,providerId:r?.providerId??d.providerId,modelId:r?.modelId??a,modeId:k(e.bindingStore.get(o)?.dshModeId,i?.dshModeId),thinking:r?.thinking,reasoningEffort:r?.reasoningEffort,providers:d.providers,models:d.models})}export{K as DSH_TOOLBAR_HOST_FIELDS,G as DSH_TOOLBAR_HOST_METHODS,U as buildDshOpenedToolbarMeta,j as dshCatalogDataRoot};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{log as _}from"../core/log/index.js";import{buildAuditStatePayload as d}from"../audit/core/audit-state.js";const v=[],a=["name","aibotHandle"];function m(i,e,n,t){if((t.state!=="absent"||t.error)&&_.info(i.name,`[audit-marker] event=${e.event_id} session=${e.session_id} msg=${e.msg_id??""} state=${t.state??"error"} scope=${t.options?.enabled?t.options.scope:""} error=${t.error??""}`),t.error){if(i.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),i.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_config_invalid",msg:t.error,updated_at:Date.now()}),(()=>{try{if(!e.extra||typeof e.extra!="object")return!1;const o=e.extra,s=o.extra,r=o.audit??(s&&typeof s=="object"?s.audit:void 0);return!r||typeof r!="object"?!1:r.scope==="turn"}catch{return!1}})())try{i.aibotHandle.sendAuditState(d({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_config_invalid",errorMessage:t.error},Date.now()))}catch{}return!0}if(t.state==="enabled"&&n!=="claude"&&n!=="codex"&&n!=="cursor"&&n!=="opencode"&&n!=="pi"&&n!=="codewhale"&&n!=="deepseek-harness"&&n!=="agy"&&n!=="acp"){if(i.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),i.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_provider_unsupported",msg:`Audit replay is not supported for adapter: ${n}`,updated_at:Date.now()}),t.options?.enabled&&t.options.scope==="turn")try{i.aibotHandle.sendAuditState(d({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_provider_unsupported",errorMessage:`Audit replay is not supported for adapter: ${n}`},Date.now()))}catch{}return!0}return!1}export{a as INBOUND_AUDIT_GATE_HOST_FIELDS,v as INBOUND_AUDIT_GATE_HOST_METHODS,m as rejectUnusableAuditOptions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SESSION_CONTROL_ERROR_CODES as o}from"../adapter/claude/protocol-contract.js";import{log as a}from"../core/log/index.js";const l=["discardEventTrackingState","ensureDefaultBindingForWorkspaceFreeClient","prepareAuditedInboundEvent","resolveBindingChannelKey","sendCanceledPendingEventResult"],b=["name","aibotHandle","bindingStore","deferredMgr","pendingEvents","lifecycleBarrier","auditController"];async function m(n,e,t,r,c,v){if(r&&await n.ensureDefaultBindingForWorkspaceFreeClient(e.session_id,t),r&&!n.bindingStore.get(e.session_id)?.cwd){const s=t,d=n.prepareAuditedInboundEvent(e,c,v);a.info(n.name,`[${s}] binding missing session_id=${e.session_id} event_id=${e.event_id}`);try{const i=await n.pendingEvents.append({kind:"deferred",channel:s,sessionId:String(e.session_id??"").trim(),event:d});if(n.lifecycleBarrier.isClosed()&&!i)throw new Error("pending event store unavailable during lifecycle drain")}catch(i){const _=i instanceof Error?i.message:String(i);return n.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),n.auditController.closeWithoutAdapter(e.event_id,"failed",_,{deliveryFailed:!0}),n.discardEventTrackingState(e.event_id),n.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:_,updated_at:Date.now()}),!0}if(n.pendingEvents.isCanceled(e.event_id))return await n.pendingEvents.remove(e.event_id),n.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),n.sendCanceledPendingEventResult(d,"canceled"),!0;n.deferredMgr.defer(s,String(e.session_id??"").trim(),d);const g=n.resolveBindingChannelKey(t);return n.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),n.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[g]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:o.bindingMissing}}}},quoted_message_id:e.msg_id}),!0}return!1}export{b as INBOUND_BINDING_GATE_HOST_FIELDS,l as INBOUND_BINDING_GATE_HOST_METHODS,m as interceptUnboundInboundEvent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{handleFileListAction as m,handleCreateFolderAction as p,realHomeDir as l}from"../core/files/index.js";import{getMachineName as w}from"../core/util/index.js";import{log as _}from"../core/log/index.js";const L=[],$=["config","aibotHandle","bindingStore"];async function S(o,t,n){const c=Date.now(),a=n?o.bindingStore.get(n)?.cwd:void 0,i=t.params??{},r=String(i.parent_id??"").trim(),d=Array.isArray(i.allowed_extensions)?i.allowed_extensions.filter(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.length>0):[];_.info("file-list-diag",`plugin << recv action_id=${t.action_id} session_id=${n} parent_id=${r||"<root>"} show_hidden=${!!i.show_hidden} ext_count=${d.length} bound_cwd=${a??"<none>"}`);const e=await m({parent_id:r||null,session_id:n,show_hidden:!!i.show_hidden,allowed_extensions:d},{resolveCwd:()=>a??o.config.agent.cwd??process.cwd(),fallbackDir:l()}),u=Date.now()-c,g=e.result?.files?.length??0;_.info("file-list-diag",`plugin -> reply action_id=${t.action_id} status=${e.status} elapsed=${u}ms count=${g} current_path=${e.result?.current_path??""} error_code=${e.error_code??""} error_msg=${e.error_msg??""}`),o.aibotHandle.sendLocalActionResult({action_id:t.action_id,status:e.status,...e.result?{result:{...e.result,machine_name:w()}}:{},...e.error_code?{error_code:e.error_code}:{},...e.error_msg?{error_msg:e.error_msg}:{}})}async function b(o,t,n){const c=n?o.bindingStore.get(n)?.cwd:void 0,a=String((t.params??{}).parent_id??"").trim(),i=String((t.params??{}).name??"").trim(),r=await p({parent_id:a||null,name:i,session_id:n},{resolveCwd:()=>c??o.config.agent.cwd??process.cwd(),fallbackDir:l()});o.aibotHandle.sendLocalActionResult({action_id:t.action_id,status:r.status,...r.result?{result:r.result}:{},...r.error_code?{error_code:r.error_code}:{},...r.error_msg?{error_msg:r.error_msg}:{}})}export{$ as LOCAL_ACTION_FILES_HOST_FIELDS,L as LOCAL_ACTION_FILES_HOST_METHODS,b as handleCreateFolderLocalAction,S as handleFileListLocalAction};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SESSION_CONTROL_ERROR_CODES as g,SESSION_CONTROL_VERBS as a}from"../adapter/claude/protocol-contract.js";import{log as w}from"../core/log/index.js";import{handleSessionControlLocalAction as C}from"./session-controller.js";import{isCliMissingError as _}from"./cli-install-offer.js";const R=["buildOpenedBindingResult","deferredCallbacks","ensureImportedAgentSession","ensureSlotStarted","failSessionOpen","handleCodeWhaleSessionControlLocalActionOpen","handleCodexSessionControlLocalActionOpen","handleCursorSessionControlLocalActionOpen","handleDeepSeekSessionControlLocalActionOpen","handlePiSessionControlRestartLocalAction","handleSessionControlLocalActionForPool","refreshAndPushAgyQuota","resolveCwdForBinding","sendAgyBindingCard","sessionControlCtx","sessionControlSenders","setResolvedAgentSessionId","syncOpenCodeBinding"],v=["config","aibotHandle","pool","bindingStore","sessionBindings","deferredMgr"];async function B(e,i,n){const c=e.config.adapterType??"acp",S=c==="codex",u=c==="pi",d=String((i.params??{}).verb??"").trim().toLowerCase();if(S&&d===a.open){await e.handleCodexSessionControlLocalActionOpen(i);return}if(c==="cursor"&&d===a.open){await e.handleCursorSessionControlLocalActionOpen(i);return}if(S&&d==="restart"){const t=e.bindingStore.get(n)?.cwd??"";await e.pool.removeSlot(n).catch(()=>{}),e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:n,cwd:t,workerStatus:"ready"}}});return}if(u&&d===a.open){try{const o=i.params??{},t=String(o.cwd??"").trim();if(!t){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const r=await e.resolveCwdForBinding(t),s=String(o.agent_session_id??"").trim();e.ensureImportedAgentSession(s,r),e.bindingStore.set(n,r),e.setResolvedAgentSessionId(n,s),e.sessionBindings.set(n,r),await e.ensureSlotStarted(n).catch(l=>{if(_(l))throw l;w.warn("bridge",`pi ensureSlotStarted on local-action bind failed (non-fatal): ${l instanceof Error?l.message:String(l)}`)}),await e.deferredMgr.release(n,e.deferredCallbacks()),e.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:"ready",cwd:r}),e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"ok",result:{outcome:"opened",binding:e.buildOpenedBindingResult(n,r)}})}catch(o){e.failSessionOpen(o,{sessionId:n,eventId:i.action_id,cwd:e.bindingStore.get(n)?.cwd||String((i.params??{}).cwd??"").trim(),send:(t,r)=>e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:t,error_msg:r})})}return}if(u&&d===a.restart){await e.handlePiSessionControlRestartLocalAction(i);return}if((c==="openhuman"||c==="opencode")&&d===a.open){try{const o=i.params??{},t=String(o.cwd??"").trim();if(!t){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const r=await e.resolveCwdForBinding(t),s=String(o.agent_session_id??"").trim();e.ensureImportedAgentSession(s,r),e.bindingStore.set(n,r),e.setResolvedAgentSessionId(n,s),e.sessionBindings.set(n,r),await e.syncOpenCodeBinding(n,r),await e.deferredMgr.release(n,e.deferredCallbacks()),e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"ok",result:{outcome:"opened",binding:e.buildOpenedBindingResult(n,r)}})}catch(o){e.failSessionOpen(o,{sessionId:n,eventId:i.action_id,cwd:e.bindingStore.get(n)?.cwd||String((i.params??{}).cwd??"").trim(),send:(t,r)=>e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:t,error_msg:r})})}return}if(c==="codewhale"&&d===a.open){await e.handleCodeWhaleSessionControlLocalActionOpen(i);return}if(c==="deepseek-harness"&&d===a.open){await e.handleDeepSeekSessionControlLocalActionOpen(i);return}if(c==="acp"&&d===a.stop){const t=e.bindingStore.get(n)?.cwd??"";await e.pool.removeSlot(n).catch(()=>{}),e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:n,cwd:t,workerStatus:"stopped"}}});return}try{if(d===a.open){const o=i.params??{},t=String(o.cwd??"").trim();if(!t){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const r=String(o.agent_session_id??"").trim();if(r){const s=await e.resolveCwdForBinding(t);e.ensureImportedAgentSession(r,s)}}await e.handleSessionControlLocalActionForPool(i)}catch(o){e.failSessionOpen(o,{sessionId:n,eventId:i.action_id,cwd:e.bindingStore.get(n)?.cwd||String((i.params??{}).cwd??"").trim(),send:(t,r)=>e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:t,error_msg:r})});return}if(d===a.open){const o=i.params??{},t=await e.resolveCwdForBinding(String(o.cwd??"").trim());e.setResolvedAgentSessionId(n,String(o.agent_session_id??"").trim()),c==="agy"&&(e.bindingStore.set(n,t),e.sessionBindings.set(n,t)),await e.deferredMgr.release(n,e.deferredCallbacks()),e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"ok",result:{outcome:"opened",binding:e.buildOpenedBindingResult(n,t)}}),(e.config.adapterType??"acp")==="agy"&&(e.sendAgyBindingCard(n,t),e.refreshAndPushAgyQuota(n,!0))}else C(i,e.sessionControlCtx(n),e.sessionControlSenders(n))}export{v as LOCAL_ACTION_SESSION_CONTROL_HOST_FIELDS,R as LOCAL_ACTION_SESSION_CONTROL_HOST_METHODS,B as dispatchSessionControlLocalAction};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AcpAdapter as s}from"../adapter/acp/index.js";import{log as m}from"../core/log/index.js";import{handleAcpSetModel as g,handleAcpSetMode as S}from"./acp-toolbar-persist.js";const C=["refreshQuotaAfterModelSwitch","sessionControlSenders"],x=["name","pool","bindingStore","globalConfigStore"];function M(e,n,r,t,l,f){if(l.kind==="set_mode"){const o=String((n.params??{}).mode_id??"");o&&(t==="cursor"?(e.bindingStore.setCursorModeId(r,o),e.globalConfigStore?.set(e.name,{cursorModeId:o})):t==="claude"?(e.bindingStore.setModeId(r,o),e.globalConfigStore?.set(e.name,{modeId:o})):t==="opencode"?(e.bindingStore.setModeId(r,o),e.globalConfigStore?.set(e.name,{modeId:o})):f(t)?t==="codex"&&e.globalConfigStore?.set(e.name,{codexModeId:o}):e.globalConfigStore?.set(e.name,{acpInitialMode:o}))}else if(l.kind==="set_model"){const o=String((n.params??{}).model_id??"").trim();if(o){t==="cursor"?(e.bindingStore.setModelId(r,o),e.globalConfigStore?.set(e.name,{modelId:o})):t==="opencode"?(e.bindingStore.setModelId(r,o),e.globalConfigStore?.set(e.name,{modelId:o})):t==="codewhale"?(e.bindingStore.setModelId(r,o),e.globalConfigStore?.set(e.name,{modelId:o})):t==="codex"?e.globalConfigStore?.set(e.name,{codexModelId:o,codexReasoningEffort:void 0}):f(t)||e.globalConfigStore?.set(e.name,{modelId:o});const d=String((n.params??{}).provider??(n.params??{}).model_provider??"").trim()||void 0;e.refreshQuotaAfterModelSwitch(r,o,d)}}else if(l.kind==="set_reasoning_effort"){const o=String((n.params??{}).reasoning_effort??(n.params??{}).reasoning_eff??(n.params??{}).effort??"");o&&e.globalConfigStore?.set(e.name,{codexReasoningEffort:o})}else if(l.kind==="set_sandbox_mode"){const o=String((n.params??{}).sandbox_mode??(n.params??{}).sandboxMode??"");if(o){const d=o==="default"?void 0:o;e.globalConfigStore?.set(e.name,{codexSandboxMode:d})}}else if(l.kind==="set_service_tier"){const o=String((n.params??{}).service_tier??(n.params??{}).serviceTier??(n.params??{}).value??"").trim();if(o){const d=o.toLowerCase()==="default"?void 0:o;e.globalConfigStore?.set(e.name,{codexServiceTier:d})}}}async function A(e,n,r,t){const l=e.sessionControlSenders(r),f=e.pool.getSlot(r)?.adapter,o={bindingStore:e.bindingStore,acpAdapter:f instanceof s?f:null,globalConfigStore:e.globalConfigStore,agentName:e.name,log:m};if(t==="set_mode"){const d=String((n.params??{}).mode_id??""),i=await S(o,r,d);if(i.status==="failed")l.sendLocalActionResult(n.action_id,"failed",void 0,i.errorCode,i.errorMsg);else{const a=f instanceof s?f.buildToolbarContext(i.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,c=a?{...a,...i.result}:i.result;l.sendLocalActionResult(n.action_id,"ok",c)}}else{const d=String((n.params??{}).model_id??""),i=await g(o,r,d);if(i.status==="failed")l.sendLocalActionResult(n.action_id,"failed",void 0,i.errorCode,i.errorMsg);else{const a=f instanceof s?f.buildToolbarContext(i.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,c=a?{...a,...i.result}:i.result;l.sendLocalActionResult(n.action_id,"ok",c),i.result?.outcome==="model_set"&&e.refreshQuotaAfterModelSwitch(r,d)}}}export{x as LOCAL_ACTION_TOOLBAR_HOST_FIELDS,C as LOCAL_ACTION_TOOLBAR_HOST_METHODS,A as handleAcpToolbarLocalAction,M as persistToolbarSelection};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import u from"node:path";import{SESSION_CONTROL_ERROR_CODES as p}from"../adapter/claude/protocol-contract.js";import{reasonixStampFromSessionId as l}from"../adapter/acp/session-scanner.js";const T=["buildDshOpenedToolbarMeta"],x=["config","bindingStore","sessionScanCache","reasonixTitleScan"];function C(e,n){if(n){if(e.reasonixTitleScan){const a=l(n);if(!a)return;const t=e.reasonixTitleScan.get().filter(s=>s.stamp===a);return t.length===1?t[0].title:void 0}if((e.config.adapterType??"acp")==="cursor")return e.sessionScanCache.get().find(t=>t.sessionId===n)?.title}}function S(e,n){switch(e.config.adapterType??"acp"){case"claude":return n.claudeSessionId;case"codex":return n.codexThreadId;case"pi":return n.piSessionPath;case"codewhale":return n.codewhaleThreadId;case"agy":return n.agyConversationId;case"deepseek-harness":return n.dshProfileSessionId??n.acpSessionId;default:return n.acpSessionId}}function g(e){const n=e.config.adapterType??"acp";switch(n){case"claude":case"codex":case"pi":case"codewhale":case"deepseek-harness":return n;default:return"acp"}}function w(e,n,a){const t=String(n??"").trim(),s=String(a??"").trim();if(!t||!s)return;switch(e.config.adapterType??"acp"){case"claude":e.bindingStore.setClaudeSessionId(t,s);break;case"codex":e.bindingStore.setCodexThreadId(t,s);break;case"pi":e.bindingStore.setPiSessionPath(t,s);break;case"codewhale":e.bindingStore.setCodeWhaleThreadId(t,s);break;case"agy":e.bindingStore.setAgyConversationId(t,s);break;default:e.bindingStore.setAcpSessionId(t,s);break}e.sessionScanCache.invalidate()}function f(e){const n=String(e??"").trim();if(!n)return"";const a=u.resolve(n);return process.platform==="win32"?a.toLowerCase():a}function b(e,n,a){const t=String(n??"").trim();if(!t)return;const s=f(a);let r="";const o=e.config.adapterType??"acp";if(o==="codex"?r=e.sessionScanCache.get().find(c=>c.threadId===t)?.cwd??"":o==="claude"?r=e.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??"":o==="cursor"?r=e.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??"":o==="acp"?r=e.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??"":o==="deepseek-harness"&&(r=e.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??""),!r){for(const[,i]of e.bindingStore.entries())if(S(e,i)===t){r=i.cwd??"";break}}if(!r){const i=new Error(`agent session not found: ${t}`);throw i.sessionControlErrorCode=p.invalidAgentSession,i}const d=f(r);if(d&&s&&d!==s){const i=new Error(`agent session cwd mismatch: expected ${a}, got ${r}`);throw i.sessionControlErrorCode=p.invalidAgentSession,i}}function y(e,n,a,t="ready"){const s=e.bindingStore.get(n),r=s?String(S(e,s)??"").trim():"",o={aibotSessionId:n,providerKey:g(e),cwd:a,workerStatus:t};return r&&(o.bindingId=r,o.agentSessionId=r),(e.config.adapterType??"acp")==="deepseek-harness"&&Object.assign(o,e.buildDshOpenedToolbarMeta(n)),o}function O(e){const n=e.config.adapterType??"acp";return n==="codex"||n==="claude"||n==="acp"||n==="deepseek-harness"}export{x as SESSION_IDENTITY_HOST_FIELDS,T as SESSION_IDENTITY_HOST_METHODS,y as buildOpenedBindingResult,b as ensureImportedAgentSession,O as hasDiskScanner,f as normalizePathForCompare,g as providerKeyForAdapter,S as resolveAgentSessionId,C as resolveOrphanTitle,w as setResolvedAgentSessionId};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import l from"node:path";import{realpath as c,stat as S}from"node:fs/promises";import{SESSION_CONTROL_ERROR_CODES as s}from"../adapter/claude/protocol-contract.js";import{log as d}from"../core/log/index.js";import{sessionControlOpenFailure as u}from"./cli-install-offer.js";const O=["maybeOfferCliInstall","buildClaudeToolbarMeta"],g=["name","aibotHandle","pool","claudeWorkerStatus"];async function _(r){const e=String(r??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(e)||/^\\\\/.test(e))){const a=new Error(`Specified path is not valid on this host: ${e}`);throw a.cwdErrorCode=s.invalidCwd,a}const t=l.resolve(e);let o;try{o=await S(t)}catch(a){const i=String(a?.code??"");if(i==="ENOENT"){const n=new Error(`Specified path does not exist: ${t}`);throw n.cwdErrorCode=s.invalidCwd,n}if(i==="EACCES"||i==="EPERM"){const n=new Error("Specified path is not accessible.");throw n.cwdErrorCode=s.invalidCwd,n}throw a}if(!o.isDirectory()){const a=new Error("Specified path is not a directory.");throw a.cwdErrorCode=s.invalidCwd,a}try{return await c(t)}catch{return t}}function h(r,e,t){const{code:o,msg:a}=u(e);return r.maybeOfferCliInstall({sessionId:t.sessionId,eventId:t.eventId,quotedMessageId:t.quotedMessageId,cwd:t.cwd,err:e}),t.send?.(o,a),{code:o,msg:a}}function p(r,e){const t=r.pool.getSlot(e);return t?t.state==="starting"?"starting":t.state==="stopped"?"stopped":t.adapter.getStatus().busy?"busy":"ready":"stopped"}function P(r,e,t){const o=p(r,e);return r.claudeWorkerStatus.set(e,o),r.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:o,cwd:t,meta:r.buildClaudeToolbarMeta(e)}),o}async function b(r,e,t=6e4){const o=await r.pool.getOrCreateSlot(e);if(!o)throw new Error("Failed to allocate session slot");o.startPromise&&(d.info(r.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([o.startPromise,new Promise((a,i)=>setTimeout(()=>i(new Error(`ensureSlotStarted timeout (${t}ms) session=${e}`)),t))]),d.info(r.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}export{g as SESSION_OPEN_HELPERS_HOST_FIELDS,O as SESSION_OPEN_HELPERS_HOST_METHODS,b as ensureSlotStarted,h as failSessionOpen,p as getClaudeWorkerStatus,P as refreshClaudeWorkerStatusCard,_ as resolveCwdForBinding};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import _ from"node:path";import{stat as v}from"node:fs/promises";import{SESSION_CONTROL_ERROR_CODES as u,SESSION_CONTROL_VERBS as r}from"../adapter/claude/protocol-contract.js";import{AcpAdapter as g}from"../adapter/acp/index.js";import{log as l}from"../core/log/index.js";import{handleSessionControlCommand as c}from"./session-controller.js";const P=["deferredCallbacks","handleCodeWhaleSessionControlOpen","handleCodexSessionControlOpen","handleListSessionsTextCommand","handleOpenHumanSessionControlOpen","handlePiSessionControlOpen","handlePiSessionControlRestart","handleSessionControlCommand","handleSessionControlForPool","handleUnbindTextCommand","refreshAndPushAgyQuota","resolveAuditProvider","sendAgyBindingCard","sendAuditConfigurationError","sessionControlCtx","sessionControlSenders"],x=["aibotHandle","pool","bindingStore","sessionBindings","sessionProviderHints","sessionProviderQuotas","sessionProviderMeta","deferredMgr","auditController"];async function A(i,s,e,t,S){if(S.state!=="absent"||s.verb===r.open)try{i.auditController.resolveSession({sessionId:e.session_id,provider:i.resolveAuditProvider(),extra:e.extra})}catch(n){return i.sendAuditConfigurationError(e,n),!0}if(s.verb===r.exec)return await i.handleSessionControlCommand(s,e),!0;if(s.verb===r.listSessions)return await i.handleListSessionsTextCommand(e),!0;if(s.verb===r.unbind)return await i.handleUnbindTextCommand(e),!0;if(t==="claude")return await i.handleSessionControlCommand(s,e),!0;if(t==="codex"&&s.verb===r.open)return await i.handleCodexSessionControlOpen(s,e),!0;if(t==="pi"&&s.verb===r.open)return await i.handlePiSessionControlOpen(s,e),!0;if(t==="pi"&&s.verb===r.restart)return await i.handlePiSessionControlRestart(e),!0;if((t==="openhuman"||t==="opencode")&&s.verb===r.open)return await i.handleOpenHumanSessionControlOpen(s,e),!0;if(t==="codewhale"&&s.verb===r.open)return await i.handleCodeWhaleSessionControlOpen(s,e),!0;if(i.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),s.verb===r.open){const n=s.args.trim();if(!n)return i.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:u.cwdRequired,msg:"cwd is required",updated_at:Date.now()}),!0;try{const d=_.resolve(n);if(!(await v(d)).isDirectory())return i.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:u.invalidCwd,msg:`Path is not a directory: ${d}`,updated_at:Date.now()}),!0}catch(d){const o=String(d?.code??""),f=o==="ENOENT"?`Directory does not exist: ${_.resolve(n)}`:o==="EACCES"||o==="EPERM"?"Directory is not accessible":`Invalid path: ${n}`;return i.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:u.invalidCwd,msg:f,updated_at:Date.now()}),!0}}if(s.verb===r.open){const n=i.bindingStore.get(e.session_id);if(n?.cwd)try{await v(n.cwd)}catch{l.info("bridge",`Stale binding detected for session ${e.session_id}: ${n.cwd} no longer exists, clearing`),i.bindingStore.delete(e.session_id),i.sessionBindings.delete(e.session_id),i.sessionProviderHints.delete(e.session_id),i.sessionProviderQuotas.delete(e.session_id),i.sessionProviderMeta.delete(e.session_id);const d=i.pool.getSlot(e.session_id);d?.adapter instanceof g&&d.adapter.getSessionBindings().delete(e.session_id)}}if(await i.handleSessionControlForPool(s,e),t==="acp"&&s.verb===r.stop){const d=i.bindingStore.get(e.session_id)?.cwd??"";return await i.pool.removeSlot(e.session_id).catch(()=>{}),i.sessionBindings.delete(e.session_id),i.sessionProviderHints.delete(e.session_id),i.sessionProviderQuotas.delete(e.session_id),i.sessionProviderMeta.delete(e.session_id),i.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${d}`,updated_at:Date.now()}),!0}if(c(s,e,i.sessionControlCtx(e.session_id),{...i.sessionControlSenders(e.session_id),sendEventAck:()=>{}}),s.verb===r.open&&(await i.deferredMgr.release(e.session_id,i.deferredCallbacks()),t==="agy")){const n=i.bindingStore.get(e.session_id)?.cwd??"";n&&(i.sendAgyBindingCard(e.session_id,n),i.refreshAndPushAgyQuota(e.session_id,!0))}return!0}export{x as TEXT_COMMAND_SESSION_CONTROL_HOST_FIELDS,P as TEXT_COMMAND_SESSION_CONTROL_HOST_METHODS,A as dispatchSessionControlTextCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readJSONFile as o,writeJSONFileAtomic as
|
|
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
|
|
1
|
+
import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const i of c){if(!p&&i.name.startsWith("."))continue;const t=l(a,i.name),e={id:t,name:i.name,is_directory:i.isDirectory()};try{if(i.isDirectory()){const o=await m(t);e.modified_at=o.mtime.toISOString()}else{const o=await m(t);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(i.name)}}catch{}s.push(e)}return s.sort((i,t)=>i.is_directory!==t.is_directory?i.is_directory?-1:1:i.name.localeCompare(t.name)),s}export{f as listFiles,n as resolveMimeType};
|
package/dist/log.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as
|
|
2
|
-
`)},error(o,r,...
|
|
1
|
+
import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as i}from"node:path";import{homedir as m}from"node:os";const n=i(m(),".grix"),s={base:n,config:i(n,"config"),log:i(n,"log"),data:i(n,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=i(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...t){const e=`${c()} [${o}] ${r}${t.length?" "+t.map(String).join(" "):""}`;console.log(e),a?.write(e+`
|
|
2
|
+
`)},error(o,r,...t){const e=`${c()} [${o}] ERROR ${r}${t.length?" "+t.map(String).join(" "):""}`;console.error(e),a?.write(e+`
|
|
3
3
|
`)}};export{s as GRIX_PATHS,S as ensureGrixDirs,$ as initLogger,u as log};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as
|
|
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
|
|
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(
|
|
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(
|
|
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
|
|
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(
|
|
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": "4.3.
|
|
3
|
+
"version": "4.3.3",
|
|
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",
|