grix-connector 5.0.0 → 5.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const 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
+ import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const n of t)e.push(n);const r=Buffer.concat(e).toString("utf8").trim();return r?JSON.parse(r):{}}function k(t){const e=(t.headers.authorization??"").trim();return e.toLowerCase().startsWith("bearer ")?e.slice(7).trim():""}class w{host="127.0.0.1";port=0;token;callbacks;server=null;address=null;constructor(e){this.token=d(),this.callbacks=e}getToken(){return this.token}getURL(){return this.address?`http://${this.address.address}:${this.address.port}`:""}async start(){this.server||(this.server=c.createServer(async(e,r)=>{try{await this.handleRequest(e,r)}catch(n){h(r,n instanceof Error?n.message:String(n))}}),await new Promise((e,r)=>{this.server.once("error",r),this.server.listen(this.port,this.host,()=>{this.server.off("error",r),e()})}),this.address=this.server.address(),o.info("claude-bridge",`Bridge server listening on ${this.getURL()}`))}async stop(){if(!this.server)return;const e=this.server;this.server=null,this.address=null,e.closeIdleConnections?.(),e.closeAllConnections?.(),await new Promise((r,n)=>{e.close(s=>s?n(s):r())})}async handleRequest(e,r){if(k(e)!==this.token){l(r);return}if(e.method!=="POST"){r.writeHead(405,{"content-type":"application/json"}),r.end(JSON.stringify({error:"method_not_allowed"}));return}const n=new URL(e.url,"http://localhost").pathname,s=await v(e),i=f.get(n);if(!i){u(r);return}const a=await i(this.callbacks,s);p(r,a??{ok:!0})}}const f=new Map([["/v1/worker/register",async(t,e)=>(o.info("claude-bridge",`Worker registered: ${e.worker_id} (pid=${e.pid})`),t.onRegisterWorker(e))],["/v1/worker/status",async(t,e)=>(o.info("claude-bridge",`Worker status: ${e.status}`),t.onStatusUpdate(e))],["/v1/worker/send-text",async(t,e)=>t.onSendText(e)],["/v1/worker/send-stream-chunk",async(t,e)=>t.onSendStreamChunk(e)],["/v1/worker/send-media",async(t,e)=>t.onSendMedia(e)],["/v1/worker/delete-message",async(t,e)=>t.onDeleteMessage(e)],["/v1/worker/ack-event",async(t,e)=>t.onAckEvent(e)],["/v1/worker/event-result",async(t,e)=>t.onSendEventResult(e)],["/v1/worker/event-stop-ack",async(t,e)=>t.onSendEventStopAck(e)],["/v1/worker/event-stop-result",async(t,e)=>t.onSendEventStopResult(e)],["/v1/worker/session-composing",async(t,e)=>t.onSetSessionComposing(e)],["/v1/worker/agent-invoke",async(t,e)=>t.onAgentInvoke(e)],["/v1/worker/local-action-result",async(t,e)=>t.onLocalActionResult(e)]]);export{w as ClaudeBridgeServer};
@@ -1 +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(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
+ 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 +1 @@
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
+ import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(t,e){this.controlURL=t.replace(/\/+$/,""),this.token=e.trim(),l.info("claude-worker-client",`Configured with control URL: ${this.controlURL}`)}async post(t,e,s){if(!this.isConfigured())throw new Error("worker control not configured");const i=new AbortController,o=setTimeout(()=>i.abort(),s);try{const r=await fetch(`${this.controlURL}${t}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.token}`},body:JSON.stringify(e),signal:i.signal}),n=await r.text(),a=n.trim()?JSON.parse(n):{};if(!r.ok)throw new Error(a.error||`worker control failed ${r.status}`);return a}finally{clearTimeout(o)}}isRetryableError(t){const e=t instanceof Error?t.message:String(t);return/fetch failed|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|aborted/i.test(e)}async postWithRetry(t,e,s,i=1){let o;for(let r=0;r<=i;r++)try{return r>0&&l.info("claude-worker-client",`Retrying ${t} attempt=${r+1}`),await this.post(t,e,s)}catch(n){if(o=n,r>=i||!this.isRetryableError(n))break;await new Promise(a=>setTimeout(a,150))}throw o instanceof Error?o:new Error(String(o))}async deliverEvent(t){return this.postWithRetry("/v1/worker/deliver-event",{payload:t},1e4,1)}async deliverStop(t){return this.postWithRetry("/v1/worker/deliver-stop",{payload:t},1e4,1)}async deliverLocalAction(t){return this.postWithRetry("/v1/worker/deliver-local-action",{payload:t},1e4,1)}async ping(){try{return await this.postWithRetry("/v1/worker/ping",{},5e3,1),!0}catch{return!1}}}export{c as ClaudeWorkerClient};
@@ -1,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 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
+ import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as l}from"./protocol-contract.js";function P(e){let t=null,r=0,n=!1,i=!1;const a=v(),s=e.gatewayUrl??"http://127.0.0.1:19580/mcp";return{async start(){await F(e.command,s,e.env);const c=E(e.grix),u=[...e.args??[],"--name",`grix-mcp-${e.name}`,"--session-id",a];e.fullAuto&&u.push("--dangerously-skip-permissions"),u.push("--dangerously-load-development-channels",`server:${l}`,"--append-system-prompt",c);const f=d(I(),`grix-mcp-claude-${e.name}`);await S(f,{recursive:!0});const{expectPath:$,pidPath:g}=await M(f,e.command,u),_={...process.env,...e.env??{}};t=x("/usr/bin/expect",[$],{cwd:e.cwd,env:_,stdio:["ignore","pipe","pipe"],detached:!0}),o.info("mcp-http-launcher",`\u542F\u52A8 Claude: name=${e.name} cwd=${e.cwd} pid=${t.pid}`),r=await k(g),n=!0,o.info("mcp-http-launcher",`Claude \u5B50\u8FDB\u7A0B PID: ${r}`),t.on("exit",(m,p)=>{o.info("mcp-http-launcher",`Claude \u9000\u51FA: code=${m} signal=${p}`),n=!1,t=null,r=0,i||(o.info("mcp-http-launcher","3 \u79D2\u540E\u81EA\u52A8\u91CD\u542F..."),setTimeout(()=>{i||this.start().catch(w=>{o.error("mcp-http-launcher",`\u91CD\u542F\u5931\u8D25: ${w}`)})},3e3))}),t.stdout?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stdout] ${p.slice(0,300)}`)}),t.stderr?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stderr] ${p.slice(0,300)}`)})},async stop(){if(i=!0,n=!1,r>0)try{process.kill(r,"SIGTERM")}catch{}if(t?.pid){try{process.kill(-t.pid,"SIGTERM")}catch{}await new Promise(c=>{const u=setTimeout(()=>{if(r>0)try{process.kill(r,"SIGKILL")}catch{}if(t?.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}c()},5e3);t?.once("exit",()=>{clearTimeout(u),c()})})}t=null,r=0},getStatus(){return{name:e.name,alive:n,pid:r}}}}function E(e){return["You are connected to a chat via the grix MCP server.",`On startup, immediately call grix_authorize with: agentId="${e.agentId}", apiKey="${e.apiKey}", wsUrl="${e.wsUrl}", clientType="${e.clientType}".`,"When you receive a <channel> message, you MUST respond by calling the grix_reply tool (or the grix_complete tool if no response is needed).","Never write your reply as plain text \u2014 it will NOT reach the user. Only the grix_reply tool delivers your response to the chat.","The <channel> message contains event_id and session_id \u2014 pass them to grix_reply."].join(" ")}async function F(e,t,r){const n=d(T(),".claude.json");let i=null;try{const s=C(n,"utf8");i=JSON.parse(s)?.mcpServers?.[l]??null}catch{}if(i&&String(i.type??"").trim()==="http"&&String(i.url??"").trim()===t)return;o.info("mcp-http-launcher",`\u6CE8\u518C MCP Server: ${l} -> ${t}`);const a={...process.env,...r??{}};try{y(`${e} mcp remove -s user ${l}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}catch{}y(`${e} mcp add --scope user --transport http ${l} ${t}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}async function M(e,t,r){const{writeFile:n}=await import("node:fs/promises"),i=d(e,"claude.pid"),a=d(e,"claude.expect"),s=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set claude_command [list {${h(t)}}${r.map(c=>` {${h(c)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${h(i)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","expect {"," -re {(?i)(Quick.*safety.*check|trust.*folder)} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)I am using this for local development} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)(Enter.*confirm|Press.*Enter|Hit.*Enter)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {Listening for channel} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," -re {bypass permissions} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," eof {}","}","expect eof",""];return await n(i,"","utf8"),await n(a,s.join(`
2
+ `),"utf8"),{expectPath:a,pidPath:i}}function h(e){return e.replace(/[\\{}$\[\]"]/g,"\\$&")}async function k(e,t=1e4){const{readFile:r}=await import("node:fs/promises"),n=Math.ceil(t/100);for(let i=0;i<n;i++){try{const a=await r(e,"utf8"),s=parseInt(String(a).trim(),10);if(Number.isFinite(s)&&s>0)return s}catch{}await new Promise(a=>setTimeout(a,100))}return 0}export{P as createMcpHttpLauncher};
@@ -1 +1 @@
1
- class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(e){this.defaultTimeoutMs=e.defaultTimeoutMs??9e4,this.onTimeout=e.onTimeout}arm(e,t){this.cancel(e);const s=t?.timeoutMs??this.defaultTimeoutMs,i=Date.now()+s,o=setTimeout(()=>{this.timers.delete(e),this.onTimeout(e).catch(()=>{})},s);return this.timers.set(e,o),i}cancel(e){const t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}has(e){return this.timers.has(e)}close(){for(const e of this.timers.values())clearTimeout(e);this.timers.clear()}}export{m as ResultTimeoutManager};
1
+ class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(t){this.defaultTimeoutMs=t.defaultTimeoutMs??9e4,this.onTimeout=t.onTimeout}arm(t,e){this.cancel(t);const s=e?.timeoutMs??this.defaultTimeoutMs,i=Date.now()+s,o=setTimeout(()=>{this.timers.delete(t),this.onTimeout(t).catch(()=>{})},s);return this.timers.set(t,o),i}cancel(t){const e=this.timers.get(t);e&&(clearTimeout(e),this.timers.delete(t))}has(t){return this.timers.has(t)}close(){for(const t of this.timers.values())clearTimeout(t);this.timers.clear()}}export{m as ResultTimeoutManager};
@@ -1,13 +1,14 @@
1
- import{EventEmitter as y}from"node:events";import{stat as C}from"node:fs/promises";import{mkdirSync as B,writeFileSync as G,unlinkSync as D,statSync as v,existsSync as S}from"node:fs";import{join as u,resolve as F,delimiter as w}from"node:path";import{fileURLToPath as I}from"node:url";import{tmpdir as O,homedir as b}from"node:os";import{resolveCommandPath as N,spawnCommand as L,killProcessGroup as _,hasChildProcesses as j}from"../../core/runtime/spawn.js";import{InternalApiServer as z}from"../../core/mcp/internal-api-server.js";import{TOOLS as E}from"../../core/mcp/tools.js";import{IdentityInjector as q}from"../shared/identity-injector.js";import{compactToolInputForWire as J}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as K}from"../../default-skills/index.js";import{PiTransport as U}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as H}from"../claude/skill-scanner.js";import{listLivingDescendants as X,countLivingDescendantsOutsideBaseline as Y}from"../cursor/living-descendants.js";import{SessionBindingStore as V}from"../../core/persistence/session-binding-store.js";import{AgentGlobalConfigStore as W}from"../../core/persistence/agent-global-config-store.js";import{splitTextForAibotProtocol as Q}from"../../core/protocol/index.js";import{InboundMessageIdInjector as Z}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as tt}from"../shared/probe-util.js";import{piGrixProviderId as et,removePiGrixProvider as it,writePiGrixProvider as st}from"./pi-provider-config.js";import{agentIdOf as nt}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as rt,recordOmpMcpEntryPid as ot,removeOmpMcpEntry as at}from"./omp-mcp-config.js";import{PI_GRIX_TOOLS_READY_PREFIX as P}from"./pi-grix-tools-extension.js";function dt(c){return nt(c)==="omp"}function lt(c){return process.platform!=="win32"?"PATH":Object.keys(c).find(t=>t.toLowerCase()==="path")??"PATH"}function ct(c){const t=lt(c),e=String(c[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(w).some(r=>r.trim()&&S(u(r.trim(),i))))return c;const n=u(b(),".bun","bin");return S(u(n,i))?(o.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${n}`),{...c,[t]:e?`${n}${w}${e}`:n}):c}class ht extends y{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const pt=12e4,T=90*1e3,$=1800*1e3;function A(c){try{return process.kill(c,0),!0}catch(t){return t.code==="EPERM"}}const ut=500,mt=2e3,x=3,ft=500,gt=1e4;function R(c){return new Promise(t=>setTimeout(t,c))}function vt(c){const t=new Set,e=[];for(const i of c){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function m(c){if(c===void 0)return"undefined";if(c===null)return"null";if(typeof c=="string")return c.length>500?`${c.slice(0,500)}...`:c;try{const t=JSON.stringify(c);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(c)}}class M extends y{type="pi";config;callbacks;process=null;transport=new U;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;piGrixToolsExtensionPath=null;piGrixToolsReady=!1;piGrixToolsReadyError=null;piGrixToolsStderrBuffer="";cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new Z;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;abortBarrier=null;promptGeneration=0;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;descendantBaseline;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;globalConfigStore=null;modelSelectionRevision=0;initializationPromise=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new q("pi-adapter",e.getAgentProfile);const i=t.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.agentName=String(i.agentName??"").trim(),this.clientType=String(i.clientType??"").trim().toLowerCase(),this.provider=i.provider,this.bindingStore=i.bindingStore instanceof V?i.bindingStore:null,this.globalConfigStore=i.globalConfigStore instanceof W?i.globalConfigStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t=this.config.command||"pi"){return this.clientType?this.clientType==="omp":dt(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||u(b(),".pi","agent")}start(){return this.initializationPromise=this.initializeSession(),this.initializationPromise}async initializeSession(){const t=this.resolveInitialModel();if(await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),t)try{await this.setModelSelection(t.provider,t.modelId,!1)}catch(e){o.warn("pi-adapter",`Failed to restore model selection: ${e instanceof Error?e.message:String(e)}`)}o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(!this.aibotSessionId)return;const t=this.modelSelectionRevision;for(let e=1;e<=x;e++)try{const[i,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]);if(t!==this.modelSelectionRevision)return;const n=i.data?.models;if(!n||n.length===0){if(e<x){await R(ft);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${x} attempts, giving up`);return}const r=s.data?.model,a=this.bindingStore?.get(this.aibotSessionId);s.success&&r?.provider&&r.id&&!(a?.piProviderId&&a.piModelId)&&this.bindingStore?.setPiModel(this.aibotSessionId,r.provider,r.id);const d={available_models:n.map(p=>({id:p.id,display_name:p.name??p.id,...p.provider?{provider:p.provider}:{}}))},h=vt(n);h.length>0&&(d.available_providers=h),r?.id&&(d.model_id=r.id),r?.provider&&(d.provider_id=r.provider,d.model_provider=r.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),d),o.info("pi-adapter",`synced model binding: ${n.length} models, current=${r?.id??"unknown"} (attempt ${e})`);return}catch(i){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${i instanceof Error?i.message:String(i)}`);return}}resolveInitialModel(){const t=this.bindingStore?.get(this.aibotSessionId);if(t?.piProviderId&&t.piModelId)return{provider:t.piProviderId,modelId:t.piModelId};if(this.piSessionPath)return;const e=this.globalConfigStore?.get(this.agentName);if(e?.piProviderId&&e.piModelId)return{provider:e.piProviderId,modelId:e.piModelId}}async setModelSelection(t,e,i){const s=await this.transport.send("set_model",{provider:t,modelId:e});if(!s.success)throw new Error(s.error||"set_model failed");this.modelSelectionRevision++,this.aibotSessionId&&this.bindingStore?.setPiModel(this.aibotSessionId,t,e),i&&this.agentName&&this.globalConfigStore?.set(this.agentName,{piProviderId:t,piModelId:e})}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.promptGeneration++,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{D(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.cwdMcpJsonDir&&this.cwdMcpJsonKey){const t=this.cwdMcpJsonDir,e=this.cwdMcpJsonKey;this.cwdMcpJsonDir=null,this.cwdMcpJsonKey=null;try{await at(t,e)}catch(i){o.warn("pi-adapter",`\u6E05\u7406 omp cwd .mcp.json \u6761\u76EE\u5931\u8D25 key=${e}: ${i instanceof Error?i.message:String(i)}`)}}if(this.process){const t=this.process;try{_(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{_(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new ht(t.adapterSessionId),i=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:i})).then(s=>{s.success||e.emitDone({status:"failed",error:s.error})}).catch(s=>{e.emitError(s instanceof Error?s:new Error(String(s)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:i,content:s}=t,n=++this.promptGeneration,r=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const a=this.activeEventId;o.info("pi-adapter",`steer: cancel ${a} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(a,"canceled","steered to new event"),this.activeAuditCapture?.eventId===a&&(this.snapshotAuditBoundary(a),this.emit("eventDone",a))}this.activeEventId=e,this.activeSessionId=i,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,n,{message:r,streamingBehavior:"steer"})}else o.info("pi-adapter",`prompt: event=${e} session=${i}`),this.activeEventId=e,this.activeSessionId=i,this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,n,{message:r})}sendInboundPrompt(t,e,i){const s=t.event_id,n=()=>!this.stopped&&this.promptGeneration===e&&this.activeEventId===s;(async()=>{if(this.abortBarrier&&await this.abortBarrier,!n())return;this.beginAuditCapture(t);const a=await this.transport.send("prompt",i);if(!a.success)throw new Error(a.error||"prompt rejected")})().catch(a=>{if(!n())return;const d=a instanceof Error?a.message:String(a);o.error("pi-adapter",`prompt error event=${s}: ${d}`),this.isStreaming=!1,this.cancelDoneGuard(),this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(s,"failed",d)})}beginAbortBarrier(){if(this.abortBarrier)return;const t=Promise.resolve().then(()=>this.transport.send("abort")).then(e=>{if(!e.success)throw new Error(e.error||"abort rejected")});this.abortBarrier=t,t.then(()=>{this.abortBarrier===t&&(this.abortBarrier=null)},e=>{o.error("pi-adapter",`abort failed: ${e}`)})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.promptGeneration++,this.beginAbortBarrier(),this.cancelDoneGuard(),this.flushTextBuffer();const i=this.nextStreamSeq(),s=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",i,!0,s),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(t,"canceled","stopped by user")}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const i=t.params??{},s=(i.modelId??i.model_id??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{await this.initializationPromise;let n=(i.provider_id??i.provider??i.model_provider)?.trim();if(!n){const d=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.id===s&&h.provider?.trim());if(d.length>1){const h=(await this.currentModel())?.provider?.trim();n=d.find(p=>p.provider?.trim()===h)?.provider?.trim()}n=n??d[0]?.provider?.trim()}return n?(await this.setModelSelection(n,s,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:s}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${s}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const i=t.params??{},s=(i.provider_id??i.provider??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{await this.initializationPromise;const a=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.provider?.trim()===s);if(a.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${s}`),{handled:!0,kind:"set_provider_error"};const d=(await this.currentModel())?.id,h=a.find(p=>p.id===d)?.id??a[0].id;return await this.setModelSelection(s,h,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:h}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const i=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:i}),{handled:!0,kind:"get_context"}}catch(i){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",i instanceof Error?i.message:String(i)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi||!this.isOmp())return null;const t=F(I(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?j(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await tt(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=v(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,i){try{if(t==="model"&&e.trim()&&await this.initializationPromise,!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const a=s.indexOf(":");if(a<1)return{status:"failed",message:"Format: provider:model_id"};const d=s.slice(0,a),h=s.slice(a+1);return h?(await this.setModelSelection(d,h,!0),this.syncModelBinding(),{status:"ok",message:`Model set to ${d}:${h}`}):{status:"failed",message:"Format: provider:model_id"}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
2
- ${r.map(d=>` ${d.provider??"unknown"}:${d.id} (${d.name??d.id})`).join(`
3
- `)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const s=this.getStatus();return{status:"ok",message:`Alive: ${s.alive}, Busy: ${s.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:s.alive,busy:s.busy,sessions:s.sessions,sessionPath:this.piSessionPath}}}case"skills":{const s=H({mode:"pi"}),n=s.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""} [${r.source}]: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
4
- `):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){const t=this.isOmp();try{this.internalApi=new z,this.internalApi.setInvokeHandler(async(n,r,a,d)=>this.callbacks.agentInvoke(n,r,d)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.resolvePiConfigDir();if(t){const n=this.getMcpConfig(),r=u(O(),"grix-pi-mcp");B(r,{recursive:!0}),this.mcpConfigPath=u(r,`mcp-${process.pid}-${Date.now()}.json`),G(this.mcpConfigPath,JSON.stringify({mcpServers:{[n.name]:{command:n.command,args:n.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`)}else{const n=I(new URL("./pi-grix-tools-extension.js",import.meta.url)),r=I(new URL("./pi-grix-tools-extension.ts",import.meta.url));if(this.piGrixToolsExtensionPath=S(n)?n:r,!S(this.piGrixToolsExtensionPath))throw new Error(`Pi Grix tools extension not found: ${this.piGrixToolsExtensionPath}`);o.info("pi-adapter",`Pi Grix direct tools extension: ${this.piGrixToolsExtensionPath}`)}const i=u(e,"skills"),s=K(i);s.length>0&&o.info("pi-adapter",`Synced connector skills to ${i}: [${s.join(", ")}]`)}catch(e){if(this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}throw o.error("pi-adapter",`Failed to start Pi Grix tools: ${e instanceof Error?e.message:String(e)}`),e}}async writeOmpCwdMcpConfig(t){if(!this.mcpConfigPath)return;const e=this.getMcpConfig();if(e)try{const i=await rt(t,{name:e.name,command:e.command,args:e.args});this.cwdMcpJsonDir=t,this.cwdMcpJsonKey=i}catch(i){o.warn("pi-adapter",`\u5199\u5165 omp <cwd>/.omp/mcp.json \u5931\u8D25: ${i instanceof Error?i.message:String(i)}`)}}async spawnPi(){const t=this.config.command||"pi",e=N(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),i=this.config.args??[],n=i.some(l=>l.startsWith("--mode"))?[...i]:["--mode","rpc",...i],r=this.resolvePiConfigDir(),a=et(this.agentName);if(this.provider){const l=this.isOmp(e)?"bare":"dollar";await st(r,a,this.provider,l)?(n.includes("--provider")||n.push("--provider",a),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):o.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied")}else await it(r,a).then(l=>{l&&o.info("pi-adapter",`Removed stale Grix provider "${a}" from models.json`)}).catch(l=>{o.warn("pi-adapter",`Failed to clean up Grix provider config: ${l instanceof Error?l.message:String(l)}`)});const d=this.isOmp(e);if(!d){if(!this.internalApi||!this.piGrixToolsExtensionPath)throw new Error("Pi Grix tools are not initialized");n.some((g,k)=>(g==="--extension"||g==="-e")&&n[k+1]===this.piGrixToolsExtensionPath)||n.push("--extension",this.piGrixToolsExtensionPath),this.piGrixToolsReady=!1,this.piGrixToolsReadyError=null,this.piGrixToolsStderrBuffer=""}let h={...process.env,...this.config.env};d?h=ct(h):h.GRIX_CONNECTOR_INTERNAL_API=this.internalApi.url;const p=this.provider?.apiKey?.trim();p&&!h.GRIX_PROVIDER_API_KEY?.trim()&&(h.GRIX_PROVIDER_API_KEY=p);const f=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await C(f)).isDirectory())throw new Error(`Bound path is not a directory: ${f}`)}catch(l){throw String(l?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${f}. Please rebind with /grix open <valid-directory>.`):l}d&&await this.writeOmpCwdMcpConfig(f);try{this.process=L(e,n,{env:h,cwd:f}).process}catch(l){throw o.error("pi-adapter",`PI spawn threw: ${l}`),this.alive=!1,l}if(d&&this.cwdMcpJsonDir&&this.cwdMcpJsonKey&&this.process.pid&&ot(this.cwdMcpJsonDir,this.cwdMcpJsonKey,this.process.pid).catch(l=>{o.warn("pi-adapter",`\u8BB0\u5F55 omp \u5B50\u8FDB\u7A0B pid \u5230 mcp \u72B6\u6001\u6587\u4EF6\u5931\u8D25: ${l instanceof Error?l.message:String(l)}`)}),this.process.on("error",l=>{o.error("pi-adapter",`Spawn error: ${l.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${l.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",l=>{o.info("pi-adapter",`PI process exited (code=${l})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${l})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",l??1)}),this.process.stderr?.on("data",l=>{d||this.observePiGrixToolsStderr(l.toString());const g=l.toString().trim();g&&o.info("pi-adapter",`[pi stderr] ${g}`)}),this.transport.on("event",l=>this.handlePiEvent(l)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0,!d)try{await this.waitForPiGrixToolsReady()}catch(l){throw await this.stop(),l}}observePiGrixToolsStderr(t){const e=this.piGrixToolsStderrBuffer+t;this.piGrixToolsStderrBuffer=e.slice(-4096);const i=e.indexOf(P);if(i<0)return;const s=e.indexOf(`
5
- `,i);if(s<0)return;const n=e.slice(i+P.length,s).trim();if(this.piGrixToolsStderrBuffer="",!/^\d+$/.test(n)||Number(n)!==E.length){this.piGrixToolsReadyError=`Pi Grix tools count mismatch: expected ${E.length}, got ${n||"invalid"}`;return}this.piGrixToolsReady=!0,o.info("pi-adapter",`Pi Grix direct tools ready: ${n} tools`)}async waitForPiGrixToolsReady(t=gt){const e=Date.now()+t;for(;!this.piGrixToolsReady;){if(this.piGrixToolsReadyError)throw new Error(this.piGrixToolsReadyError);if(!this.process||!this.alive)throw new Error("Pi exited before Grix tools were ready");if(Date.now()>=e)throw new Error(`Timed out waiting for ${E.length} Pi Grix tools to become ready`);await R(25)}}handlePiEvent(t){if(this.stopped||this.abortBarrier)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const i=t;this.descendantBaseline===void 0&&this.captureDescendantBaseline(),i.toolCallId&&this.toolCallsInFlight.add(i.toolCallId)}else if(t.type==="tool_execution_end"){const i=t;i.toolCallId&&this.toolCallsInFlight.delete(i.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const i=t.assistantMessageEvent;if(!i)break;const s=i.type;if(s==="text_delta"){const n=i.delta;if(n){const r=typeof i.contentIndex=="number"?i.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(s==="text_end"){const n=i.content,r=typeof i.contentIndex=="number"?i.contentIndex:0;n&&this.appendMissingText(r,n)}else if(s==="thinking_delta"){const n=i.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(s==="done"||s==="error"){if(this.flushTextBuffer(),s==="error"){const n=this.piMessageError(i.error,i.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(i.error)} reason=${m(i.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const i=t.message;i?.role==="assistant"&&i.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${m(i.errorMessage)} message=${m(i)}`),this.recordRunError(this.piMessageError(i,i.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const i=t;if(i.toolName){const s=J(i.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,i.toolName,s)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const i=t;i.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,i.toolName,"(failed)");break}case"agent_end":{if(o.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){o.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.captureOmpAuditMessages(t.messages),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(o.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=mt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},ut))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of Q(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const s=JSON.parse(t.context_messages_json);if(Array.isArray(s)&&s.length>0){const n=s.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
1
+ import{EventEmitter as w}from"node:events";import{stat as D}from"node:fs/promises";import{mkdirSync as F,writeFileSync as O,unlinkSync as N,statSync as S,existsSync as I}from"node:fs";import{join as m,resolve as L,delimiter as _}from"node:path";import{fileURLToPath as y}from"node:url";import{tmpdir as j,homedir as b}from"node:os";import{resolveCommandPath as z,spawnCommand as K,killProcessGroup as P,hasChildProcesses as q}from"../../core/runtime/spawn.js";import{InternalApiServer as J}from"../../core/mcp/internal-api-server.js";import{TOOLS as E}from"../../core/mcp/tools.js";import{IdentityInjector as U}from"../shared/identity-injector.js";import{compactToolInputForWire as Y}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as H}from"../../default-skills/index.js";import{PiTransport as X}from"./pi-transport.js";import{log as a}from"../../core/log/index.js";import{scanSkills as V}from"../claude/skill-scanner.js";import{listLivingDescendants as W,countLivingDescendantsOutsideBaseline as Q}from"../cursor/living-descendants.js";import{SessionBindingStore as Z}from"../../core/persistence/session-binding-store.js";import{AgentGlobalConfigStore as tt}from"../../core/persistence/agent-global-config-store.js";import{splitTextForAibotProtocol as et}from"../../core/protocol/index.js";import{InboundMessageIdInjector as it}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as st}from"../shared/probe-util.js";import{piGrixProviderId as rt,removePiGrixProvider as nt,writePiGrixProvider as ot}from"./pi-provider-config.js";import{agentIdOf as at}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as dt,recordOmpMcpEntryPid as lt,removeOmpMcpEntry as ct}from"./omp-mcp-config.js";import{PI_GRIX_TOOLS_READY_PREFIX as T}from"./pi-grix-tools-extension.js";function ht(c){return at(c)==="omp"}function pt(c){return process.platform!=="win32"?"PATH":Object.keys(c).find(t=>t.toLowerCase()==="path")??"PATH"}function ut(c){const t=pt(c),e=String(c[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(_).some(n=>n.trim()&&I(m(n.trim(),i))))return c;const r=m(b(),".bun","bin");return I(m(r,i))?(a.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${r}`),{...c,[t]:e?`${r}${_}${e}`:r}):c}class mt extends w{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){a.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const ft=12e4,$=90*1e3,R=1800*1e3;function A(c){try{return process.kill(c,0),!0}catch(t){return t.code==="EPERM"}}const gt=500,vt=2e3,x=3,St=500,It=1e4,yt=[6e3,15e3,3e4];function M(c){return new Promise(t=>setTimeout(t,c))}function Et(c){const t=new Set,e=[];for(const i of c){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function C(c){if(!c)return{mode:"none"};const t=c.baseUrl?.trim(),e=c.apiKey?.trim(),i=c.providerId?.trim(),s=c.model?.trim();return t&&s&&(!i||e)?{mode:"relay"}:i&&s?{mode:"native",providerId:i,modelId:s}:{mode:"none"}}function k(c){return c.trim().toLowerCase().replace(/_/g,"-")}function f(c){if(c===void 0)return"undefined";if(c===null)return"null";if(typeof c=="string")return c.length>500?`${c.slice(0,500)}...`:c;try{const t=JSON.stringify(c);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(c)}}class B extends w{type="pi";config;callbacks;process=null;transport=new X;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;piGrixToolsExtensionPath=null;piGrixToolsReady=!1;piGrixToolsReadyError=null;piGrixToolsStderrBuffer="";cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new it;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;abortBarrier=null;promptGeneration=0;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;descendantBaseline;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;globalConfigStore=null;modelSelectionRevision=0;catalogResyncTimers=[];catalogSignature="";initializationPromise=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new U("pi-adapter",e.getAgentProfile);const i=t.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.agentName=String(i.agentName??"").trim(),this.clientType=String(i.clientType??"").trim().toLowerCase(),this.provider=i.provider,this.bindingStore=i.bindingStore instanceof Z?i.bindingStore:null,this.globalConfigStore=i.globalConfigStore instanceof tt?i.globalConfigStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t=this.config.command||"pi"){return this.clientType?this.clientType==="omp":ht(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||m(b(),".pi","agent")}start(){return this.initializationPromise=this.initializeSession(),this.initializationPromise}async initializeSession(){const t=this.resolveInitialModel();await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady();let e;if(t)try{await this.tryRestoreModelSelection(t)}catch(i){e=t,a.warn("pi-adapter",`Failed to restore model selection: ${i instanceof Error?i.message:String(i)}; retrying after catalog refresh`)}a.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding(!!e),this.scheduleCatalogResync(e)}scheduleCatalogResync(t){if(this.catalogResyncTimers.length>0)return;let e=this.modelSelectionRevision,i=this.catalogSignature;for(const s of yt){const r=setTimeout(()=>{(async()=>{if(!(this.stopped||e!==this.modelSelectionRevision)){if(t){const n=t;try{await this.tryRestoreModelSelection(n),t=void 0,e=this.modelSelectionRevision,a.info("pi-adapter",`Applied configured model after catalog refresh: ${n.provider}:${n.modelId}`)}catch(o){a.warn("pi-adapter",`Model selection retry after catalog refresh failed: ${o instanceof Error?o.message:String(o)}`)}}if(await this.syncModelBinding(),!t&&this.catalogSignature===i){this.clearCatalogResyncTimers();return}i=this.catalogSignature}})()},s);this.catalogResyncTimers.push(r)}}clearCatalogResyncTimers(){for(const t of this.catalogResyncTimers)clearTimeout(t);this.catalogResyncTimers=[]}async tryRestoreModelSelection(t){try{await this.setModelSelection(t.provider,t.modelId,!1);return}catch(e){const i=await this.resolveProviderIdForModel(t.modelId,t.provider);if(!i)throw e;a.info("pi-adapter",`Provider "${t.provider}" unmatched for model ${t.modelId}; using "${i}"`),await this.setModelSelection(i,t.modelId,!1)}}async resolveProviderIdForModel(t,e){try{const s=(await this.transport.send("get_available_models")).data?.models??[];if(new Set(s.map(d=>d.provider?.trim()).filter(d=>!!d)).has(e))return;const n=k(e);return s.find(d=>d.id===t&&d.provider&&k(d.provider)===n)?.provider?.trim()||void 0}catch{return}}async syncModelBinding(t=!1){if(!this.aibotSessionId)return;const e=this.modelSelectionRevision;for(let i=1;i<=x;i++)try{const[s,r]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]);if(e!==this.modelSelectionRevision)return;const n=s.data?.models;if(!n||n.length===0){if(i<x){await M(St);continue}a.warn("pi-adapter",`syncModelBinding: empty model list after ${x} attempts, giving up`);return}const o=r.data?.model,d=this.bindingStore?.get(this.aibotSessionId);!t&&r.success&&o?.provider&&o.id&&!(d?.piProviderId&&d.piModelId)&&this.bindingStore?.setPiModel(this.aibotSessionId,o.provider,o.id);const h={available_models:n.map(u=>({id:u.id,display_name:u.name??u.id,...u.provider?{provider:u.provider}:{}}))},p=Et(n);p.length>0&&(h.available_providers=p),o?.id&&(h.model_id=o.id),o?.provider&&(h.provider_id=o.provider,h.model_provider=o.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),h),this.catalogSignature=n.map(u=>`${u.provider??""}\0${u.id}`).sort().join(`
2
+ `),a.info("pi-adapter",`synced model binding: ${n.length} models, current=${o?.id??"unknown"} (attempt ${i})`);return}catch(s){a.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${s instanceof Error?s.message:String(s)}`);return}}resolveInitialModel(){const t=this.bindingStore?.get(this.aibotSessionId);if(t?.piProviderId&&t.piModelId)return{provider:t.piProviderId,modelId:t.piModelId};if(this.piSessionPath)return;const e=C(this.provider);if(e.mode==="native")return{provider:e.providerId,modelId:e.modelId};const i=this.globalConfigStore?.get(this.agentName);if(i?.piProviderId&&i.piModelId)return{provider:i.piProviderId,modelId:i.piModelId}}async setModelSelection(t,e,i){const s=await this.transport.send("set_model",{provider:t,modelId:e});if(!s.success)throw new Error(s.error||"set_model failed");this.modelSelectionRevision++,this.aibotSessionId&&this.bindingStore?.setPiModel(this.aibotSessionId,t,e),i&&this.agentName&&this.globalConfigStore?.set(this.agentName,{piProviderId:t,piModelId:e})}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.promptGeneration++,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.clearCatalogResyncTimers(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{N(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.cwdMcpJsonDir&&this.cwdMcpJsonKey){const t=this.cwdMcpJsonDir,e=this.cwdMcpJsonKey;this.cwdMcpJsonDir=null,this.cwdMcpJsonKey=null;try{await ct(t,e)}catch(i){a.warn("pi-adapter",`\u6E05\u7406 omp cwd .mcp.json \u6761\u76EE\u5931\u8D25 key=${e}: ${i instanceof Error?i.message:String(i)}`)}}if(this.process){const t=this.process;try{P(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{P(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return a.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new mt(t.adapterSessionId),i=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:i})).then(s=>{s.success||e.emitDone({status:"failed",error:s.error})}).catch(s=>{e.emitError(s instanceof Error?s:new Error(String(s)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:i,content:s}=t,r=++this.promptGeneration,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const o=this.activeEventId;a.info("pi-adapter",`steer: cancel ${o} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(o,"canceled","steered to new event"),this.activeAuditCapture?.eventId===o&&(this.snapshotAuditBoundary(o),this.emit("eventDone",o))}this.activeEventId=e,this.activeSessionId=i,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,r,{message:n,streamingBehavior:"steer"})}else a.info("pi-adapter",`prompt: event=${e} session=${i}`),this.activeEventId=e,this.activeSessionId=i,this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,r,{message:n})}sendInboundPrompt(t,e,i){const s=t.event_id,r=()=>!this.stopped&&this.promptGeneration===e&&this.activeEventId===s;(async()=>{if(this.abortBarrier&&await this.abortBarrier,!r())return;this.beginAuditCapture(t);const o=await this.transport.send("prompt",i);if(!o.success)throw new Error(o.error||"prompt rejected")})().catch(o=>{if(!r())return;const d=o instanceof Error?o.message:String(o);a.error("pi-adapter",`prompt error event=${s}: ${d}`),this.isStreaming=!1,this.cancelDoneGuard(),this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(s,"failed",d)})}beginAbortBarrier(){if(this.abortBarrier)return;const t=Promise.resolve().then(()=>this.transport.send("abort")).then(e=>{if(!e.success)throw new Error(e.error||"abort rejected")});this.abortBarrier=t,t.then(()=>{this.abortBarrier===t&&(this.abortBarrier=null)},e=>{a.error("pi-adapter",`abort failed: ${e}`)})}deliverStopEvent(t,e){if(this.activeEventId===t){a.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.promptGeneration++,this.beginAbortBarrier(),this.cancelDoneGuard(),this.flushTextBuffer();const i=this.nextStreamSeq(),s=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",i,!0,s),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(t,"canceled","stopped by user")}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const i=t.params??{},s=(i.modelId??i.model_id??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{await this.initializationPromise;let r=(i.provider_id??i.provider??i.model_provider)?.trim();if(!r){const d=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.id===s&&h.provider?.trim());if(d.length>1){const h=(await this.currentModel())?.provider?.trim();r=d.find(p=>p.provider?.trim()===h)?.provider?.trim()}r=r??d[0]?.provider?.trim()}return r?(await this.setModelSelection(r,s,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:r,modelId:s}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${s}`),{handled:!0,kind:"set_model_error"})}catch(r){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",r instanceof Error?r.message:String(r)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const i=t.params??{},s=(i.provider_id??i.provider??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{await this.initializationPromise;const o=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.provider?.trim()===s);if(o.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${s}`),{handled:!0,kind:"set_provider_error"};const d=(await this.currentModel())?.id,h=o.find(p=>p.id===d)?.id??o[0].id;return await this.setModelSelection(s,h,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:h}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(r){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",r instanceof Error?r.message:String(r)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const i=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:i}),{handled:!0,kind:"get_context"}}catch(i){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",i instanceof Error?i.message:String(i)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi||!this.isOmp())return null;const t=L(y(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?q(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await st(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=S(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,i){try{if(t==="model"&&e.trim()&&await this.initializationPromise,!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const o=s.indexOf(":");if(o<1)return{status:"failed",message:"Format: provider:model_id"};const d=s.slice(0,o),h=s.slice(o+1);return h?(await this.setModelSelection(d,h,!0),this.syncModelBinding(),{status:"ok",message:`Model set to ${d}:${h}`}):{status:"failed",message:"Format: provider:model_id"}}const n=(await this.transport.send("get_available_models"))?.data?.models;return n&&n.length>0?{status:"ok",message:`Available models:
3
+ ${n.map(d=>` ${d.provider??"unknown"}:${d.id} (${d.name??d.id})`).join(`
4
+ `)}`,data:n}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const s=this.getStatus();return{status:"ok",message:`Alive: ${s.alive}, Busy: ${s.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:s.alive,busy:s.busy,sessions:s.sessions,sessionPath:this.piSessionPath}}}case"skills":{const s=V({mode:"pi"}),r=s.map(n=>`- ${n.name}${n.trigger?` (${n.trigger})`:""} [${n.source}]: ${n.description}`);return{status:"ok",message:r.length>0?r.join(`
5
+ `):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){const t=this.isOmp();try{this.internalApi=new J,this.internalApi.setInvokeHandler(async(r,n,o,d)=>this.callbacks.agentInvoke(r,n,d)),await this.internalApi.start(0),a.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.resolvePiConfigDir();if(t){const r=this.getMcpConfig(),n=m(j(),"grix-pi-mcp");F(n,{recursive:!0}),this.mcpConfigPath=m(n,`mcp-${process.pid}-${Date.now()}.json`),O(this.mcpConfigPath,JSON.stringify({mcpServers:{[r.name]:{command:r.command,args:r.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),a.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`)}else{const r=y(new URL("./pi-grix-tools-extension.js",import.meta.url)),n=y(new URL("./pi-grix-tools-extension.ts",import.meta.url));if(this.piGrixToolsExtensionPath=I(r)?r:n,!I(this.piGrixToolsExtensionPath))throw new Error(`Pi Grix tools extension not found: ${this.piGrixToolsExtensionPath}`);a.info("pi-adapter",`Pi Grix direct tools extension: ${this.piGrixToolsExtensionPath}`)}const i=m(e,"skills"),s=H(i);s.length>0&&a.info("pi-adapter",`Synced connector skills to ${i}: [${s.join(", ")}]`)}catch(e){if(this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),t){a.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}throw a.error("pi-adapter",`Failed to start Pi Grix tools: ${e instanceof Error?e.message:String(e)}`),e}}async writeOmpCwdMcpConfig(t){if(!this.mcpConfigPath)return;const e=this.getMcpConfig();if(e)try{const i=await dt(t,{name:e.name,command:e.command,args:e.args});this.cwdMcpJsonDir=t,this.cwdMcpJsonKey=i}catch(i){a.warn("pi-adapter",`\u5199\u5165 omp <cwd>/.omp/mcp.json \u5931\u8D25: ${i instanceof Error?i.message:String(i)}`)}}async spawnPi(){const t=this.config.command||"pi",e=z(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),i=this.config.args??[],r=i.some(l=>l.startsWith("--mode"))?[...i]:["--mode","rpc",...i],n=this.resolvePiConfigDir(),o=rt(this.agentName),d=C(this.provider);if(d.mode==="relay"){const l=this.isOmp(e)?"bare":"dollar";await ot(n,o,this.provider,l)?(r.includes("--provider")||r.push("--provider",o),!r.includes("--model")&&this.provider.model?.trim()&&r.push("--model",this.provider.model.trim())):a.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied")}else d.mode==="native"&&a.info("pi-adapter",`Native provider ${d.providerId}:${d.modelId}; applying model via RPC (no models.json injection)`),await nt(n,o).then(l=>{l&&a.info("pi-adapter",`Removed stale Grix provider "${o}" from models.json`)}).catch(l=>{a.warn("pi-adapter",`Failed to clean up Grix provider config: ${l instanceof Error?l.message:String(l)}`)});const h=this.isOmp(e);if(!h){if(!this.internalApi||!this.piGrixToolsExtensionPath)throw new Error("Pi Grix tools are not initialized");r.some((v,G)=>(v==="--extension"||v==="-e")&&r[G+1]===this.piGrixToolsExtensionPath)||r.push("--extension",this.piGrixToolsExtensionPath),this.piGrixToolsReady=!1,this.piGrixToolsReadyError=null,this.piGrixToolsStderrBuffer=""}let p={...process.env,...this.config.env};h?p=ut(p):p.GRIX_CONNECTOR_INTERNAL_API=this.internalApi.url;const u=this.provider?.apiKey?.trim();u&&!p.GRIX_PROVIDER_API_KEY?.trim()&&(p.GRIX_PROVIDER_API_KEY=u);const g=this.resolveCwd();a.info("pi-adapter",`Spawning: ${e} ${r.join(" ")}`);try{if(!(await D(g)).isDirectory())throw new Error(`Bound path is not a directory: ${g}`)}catch(l){throw String(l?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${g}. Please rebind with /grix open <valid-directory>.`):l}h&&await this.writeOmpCwdMcpConfig(g);try{this.process=K(e,r,{env:p,cwd:g}).process}catch(l){throw a.error("pi-adapter",`PI spawn threw: ${l}`),this.alive=!1,l}if(h&&this.cwdMcpJsonDir&&this.cwdMcpJsonKey&&this.process.pid&&lt(this.cwdMcpJsonDir,this.cwdMcpJsonKey,this.process.pid).catch(l=>{a.warn("pi-adapter",`\u8BB0\u5F55 omp \u5B50\u8FDB\u7A0B pid \u5230 mcp \u72B6\u6001\u6587\u4EF6\u5931\u8D25: ${l instanceof Error?l.message:String(l)}`)}),this.process.on("error",l=>{a.error("pi-adapter",`Spawn error: ${l.message}`),this.alive=!1,this.clearCatalogResyncTimers(),this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${l.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",l=>{a.info("pi-adapter",`PI process exited (code=${l})`),this.alive=!1,this.clearCatalogResyncTimers(),this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${l})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",l??1)}),this.process.stderr?.on("data",l=>{h||this.observePiGrixToolsStderr(l.toString());const v=l.toString().trim();v&&a.info("pi-adapter",`[pi stderr] ${v}`)}),this.transport.on("event",l=>this.handlePiEvent(l)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0,!h)try{await this.waitForPiGrixToolsReady()}catch(l){throw await this.stop(),l}}observePiGrixToolsStderr(t){const e=this.piGrixToolsStderrBuffer+t;this.piGrixToolsStderrBuffer=e.slice(-4096);const i=e.indexOf(T);if(i<0)return;const s=e.indexOf(`
6
+ `,i);if(s<0)return;const r=e.slice(i+T.length,s).trim();if(this.piGrixToolsStderrBuffer="",!/^\d+$/.test(r)||Number(r)!==E.length){this.piGrixToolsReadyError=`Pi Grix tools count mismatch: expected ${E.length}, got ${r||"invalid"}`;return}this.piGrixToolsReady=!0,a.info("pi-adapter",`Pi Grix direct tools ready: ${r} tools`)}async waitForPiGrixToolsReady(t=It){const e=Date.now()+t;for(;!this.piGrixToolsReady;){if(this.piGrixToolsReadyError)throw new Error(this.piGrixToolsReadyError);if(!this.process||!this.alive)throw new Error("Pi exited before Grix tools were ready");if(Date.now()>=e)throw new Error(`Timed out waiting for ${E.length} Pi Grix tools to become ready`);await M(25)}}handlePiEvent(t){if(this.stopped||this.abortBarrier)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const i=t;this.descendantBaseline===void 0&&this.captureDescendantBaseline(),i.toolCallId&&this.toolCallsInFlight.add(i.toolCallId)}else if(t.type==="tool_execution_end"){const i=t;i.toolCallId&&this.toolCallsInFlight.delete(i.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const i=t.assistantMessageEvent;if(!i)break;const s=i.type;if(s==="text_delta"){const r=i.delta;if(r){const n=typeof i.contentIndex=="number"?i.contentIndex:0;this.rememberEmittedText(n,r),this.appendText(r)}}else if(s==="text_end"){const r=i.content,n=typeof i.contentIndex=="number"?i.contentIndex:0;r&&this.appendMissingText(n,r)}else if(s==="thinking_delta"){const r=i.delta;r&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,r))}else if(s==="done"||s==="error"){if(this.flushTextBuffer(),s==="error"){const r=this.piMessageError(i.error,i.reason);a.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${f(i.error)} reason=${f(i.reason)}`),this.recordRunError(r)}this.scheduleDoneGuard()}break}case"message_end":{const i=t.message;i?.role==="assistant"&&i.stopReason==="error"&&(a.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${f(i.errorMessage)} message=${f(i)}`),this.recordRunError(this.piMessageError(i,i.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const i=t;if(i.toolName){const s=Y(i.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,i.toolName,s)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const i=t;i.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,i.toolName,"(failed)");break}case"agent_end":{if(a.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){a.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.captureOmpAuditMessages(t.messages),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(a.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=vt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},gt))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of et(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const s=JSON.parse(t.context_messages_json);if(Array.isArray(s)&&s.length>0){const r=s.map(n=>`[context] ${n.sender_id??"unknown"}: ${n.content}`).join(`
6
7
  `);e=`${e}
7
8
 
8
9
  [Conversation context]
9
- ${n}`}}catch{}const i=this.identity.injectOnce(t.session_id,e);return this.inboundMessageIds.inject(t.session_id,i,t.msg_id)}buildPromptTextFromRequest(t){let e=t.text;if(t.contextMessages&&t.contextMessages.length>0){const i=t.contextMessages.map(s=>`[context] ${s.senderId}: ${s.content}`).join(`
10
+ ${r}`}}catch{}const i=this.identity.injectOnce(t.session_id,e);return this.inboundMessageIds.inject(t.session_id,i,t.msg_id)}buildPromptTextFromRequest(t){let e=t.text;if(t.contextMessages&&t.contextMessages.length>0){const i=t.contextMessages.map(s=>`[context] ${s.senderId}: ${s.content}`).join(`
10
11
  `);e=`${e}
11
12
 
12
13
  [Conversation context]
13
- ${i}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.descendantBaseline=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let i;if(e)try{i=v(e).size}catch{i=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...i===void 0?{}:{transcriptStartOffset:i},...this.isOmp(this.config.command??"")?{eventRecords:[]}:{}}}captureOmpAuditMessages(t){const e=this.activeAuditCapture;if(!(!e?.eventRecords||e.eventId!==this.activeEventId)&&Array.isArray(t))for(const i of t){if(!i||typeof i!="object"||Array.isArray(i))continue;const s=i,n=s.timestamp;e.eventRecords.push({type:"message",message:s,timestamp:typeof n=="number"&&Number.isFinite(n)?new Date(n).toISOString():new Date().toISOString()})}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const i={adapterType:"pi"};if(e.transcriptPath){let s=e.transcriptStartOffset??0;try{s=v(e.transcriptPath).size}catch{}i.transcriptPath=e.transcriptPath,i.transcriptStartOffset=e.transcriptStartOffset??0,i.transcriptEndOffset=s,i.providerSessionId=this.piSessionPath??e.transcriptPath}else e.eventRecords&&e.eventRecords.length>0&&(i.eventRecords=e.eventRecords);this.completedAuditBoundaries.set(t,i)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`,this.descendantBaseline=void 0}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",i=this.activeClientMsgId??void 0,s=this.activeRunError??void 0;s&&this.emitPendingRunError();const n=this.runErrorEmitted;this.clearActive(),this.finalizeEvent(t,e,i,s,n)}finalizeEvent(t,e,i,s,n=!1){const r=this.nextStreamSeq(),a=s?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${a} clientMsgId=${i??""} terminalError=${s?m(s):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,i).then(()=>{this.callbacks.sendEventResult(t,a,s,void 0,n),o.info("pi-adapter",`event ${a} (reliable) event=${t}`)}).catch(d=>{o.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${d}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${d instanceof Error?d.message:String(d)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",r,!0,i),this.callbacks.sendEventResult(t,a,s,void 0,n),o.info("pi-adapter",`event ${a} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,o.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const i=t.errorMessage;if(typeof i=="string"&&i.trim())return i.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const i=this.emittedTextByIndex.get(t)??"";if(e!==i){if(e.startsWith(i)){const s=e.slice(i.length);s&&(this.rememberEmittedText(t,s),this.appendText(s));return}if(!i){this.rememberEmittedText(t,e),this.appendText(e);return}o.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(o.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},M.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!A(t))return!1;if(this.toolCallsInFlight.size>0&&this.descendantBaseline instanceof Set){let a=0;try{a=Y(t,this.descendantBaseline)}catch{a=0}if(a>0)return this.livenessExtendStartAt=void 0,o.info("pi-adapter",`Liveness check: tool descendants for ${this.activeEventId} (descendants=${a}, toolsInFlight=${this.toolCallsInFlight.size}), extending without budget`),!0}const e=Date.now(),i=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY,s=this.transcriptFreshMs();if(i<T||s!==null&&s<T)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh progress for ${this.activeEventId} (rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const r=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=r),e-r>$?(o.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-r)/6e4)}min), allowing idle fail`),!1):(o.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}), extending`),!0)}captureDescendantBaseline(){const t=this.process?.pid;if(!t){this.descendantBaseline=null;return}try{this.descendantBaseline=new Set(X(t)),o.info("pi-adapter",`Liveness baseline captured for ${this.activeEventId}: ${this.descendantBaseline.size} resident descendant(s)`)}catch{this.descendantBaseline=null}}transcriptFreshMs(){const t=this.piSessionPath;if(!t)return null;try{return Date.now()-v(t).mtimeMs}catch{return null}}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,i=!!(this.alive&&t&&A(t))?`liveness budget exhausted after ${$/6e4}min`:"process not alive";o.error("pi-adapter",`Idle timeout (${i}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${i}`,void 0,this.runErrorEmitted)),this.clearActive(),this.emit("exit",-1)},pt))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&o.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const s=await this.transport.send("get_state");s.success&&(e=s.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{M as PiAdapter};
14
+ ${i}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.descendantBaseline=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let i;if(e)try{i=S(e).size}catch{i=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...i===void 0?{}:{transcriptStartOffset:i},...this.isOmp(this.config.command??"")?{eventRecords:[]}:{}}}captureOmpAuditMessages(t){const e=this.activeAuditCapture;if(!(!e?.eventRecords||e.eventId!==this.activeEventId)&&Array.isArray(t))for(const i of t){if(!i||typeof i!="object"||Array.isArray(i))continue;const s=i,r=s.timestamp;e.eventRecords.push({type:"message",message:s,timestamp:typeof r=="number"&&Number.isFinite(r)?new Date(r).toISOString():new Date().toISOString()})}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const i={adapterType:"pi"};if(e.transcriptPath){let s=e.transcriptStartOffset??0;try{s=S(e.transcriptPath).size}catch{}i.transcriptPath=e.transcriptPath,i.transcriptStartOffset=e.transcriptStartOffset??0,i.transcriptEndOffset=s,i.providerSessionId=this.piSessionPath??e.transcriptPath}else e.eventRecords&&e.eventRecords.length>0&&(i.eventRecords=e.eventRecords);this.completedAuditBoundaries.set(t,i)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`,this.descendantBaseline=void 0}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",i=this.activeClientMsgId??void 0,s=this.activeRunError??void 0;s&&this.emitPendingRunError();const r=this.runErrorEmitted;this.clearActive(),this.finalizeEvent(t,e,i,s,r)}finalizeEvent(t,e,i,s,r=!1){const n=this.nextStreamSeq(),o=s?"failed":"responded";a.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${o} clientMsgId=${i??""} terminalError=${s?f(s):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,i).then(()=>{this.callbacks.sendEventResult(t,o,s,void 0,r),a.info("pi-adapter",`event ${o} (reliable) event=${t}`)}).catch(d=>{a.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${d}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${d instanceof Error?d.message:String(d)}`),a.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",n,!0,i),this.callbacks.sendEventResult(t,o,s,void 0,r),a.info("pi-adapter",`event ${o} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,a.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${f(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const i=t.errorMessage;if(typeof i=="string"&&i.trim())return i.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const i=this.emittedTextByIndex.get(t)??"";if(e!==i){if(e.startsWith(i)){const s=e.slice(i.length);s&&(this.rememberEmittedText(t,s),this.appendText(s));return}if(!i){this.rememberEmittedText(t,e),this.appendText(e);return}a.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(a.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},B.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!A(t))return!1;if(this.toolCallsInFlight.size>0&&this.descendantBaseline instanceof Set){let o=0;try{o=Q(t,this.descendantBaseline)}catch{o=0}if(o>0)return this.livenessExtendStartAt=void 0,a.info("pi-adapter",`Liveness check: tool descendants for ${this.activeEventId} (descendants=${o}, toolsInFlight=${this.toolCallsInFlight.size}), extending without budget`),!0}const e=Date.now(),i=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY,s=this.transcriptFreshMs();if(i<$||s!==null&&s<$)return this.livenessExtendStartAt=e,a.info("pi-adapter",`Liveness check: fresh progress for ${this.activeEventId} (rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),e-n>R?(a.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-n)/6e4)}min), allowing idle fail`),!1):(a.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}), extending`),!0)}captureDescendantBaseline(){const t=this.process?.pid;if(!t){this.descendantBaseline=null;return}try{this.descendantBaseline=new Set(W(t)),a.info("pi-adapter",`Liveness baseline captured for ${this.activeEventId}: ${this.descendantBaseline.size} resident descendant(s)`)}catch{this.descendantBaseline=null}}transcriptFreshMs(){const t=this.piSessionPath;if(!t)return null;try{return Date.now()-S(t).mtimeMs}catch{return null}}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,i=!!(this.alive&&t&&A(t))?`liveness budget exhausted after ${R/6e4}min`:"process not alive";a.error("pi-adapter",`Idle timeout (${i}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${i}`,void 0,this.runErrorEmitted)),this.clearActive(),this.emit("exit",-1)},ft))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&a.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const s=await this.transport.send("get_state");s.success&&(e=s.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{B as PiAdapter,C as planPiProvider};
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "5.0.0",
4
- "tarball": "grix-dsh-bridge-5.0.0.tgz",
5
- "size": 24832,
3
+ "bridgeVersion": "5.1.1",
4
+ "tarball": "grix-dsh-bridge-5.1.1.tgz",
5
+ "size": 24834,
6
6
  "unpackedSize": 99264,
7
- "shasum": "0867e92da306e96b93752742a31c5f5bf8c6e39b",
8
- "integrity": "sha512-y1r24p2trMT8GRLMDX8TPiLf0fiZBaASocMSjW5UuDQ2DKm2JLeDL+L9TFLP/OWXHAbB8fjpqrrxgeNcMJKNrA=="
7
+ "shasum": "c7aeee9e8dcbac7d5dad5b756f4a3865bd57ec99",
8
+ "integrity": "sha512-82JOoTDi1odUF4372cqNTEH0cuyixDJnO7bez5OEaUMlqcI8jyr45CTyA110L9J53SPK8SR0C6MkHmhJXhRc6Q=="
9
9
  }