grix-connector 3.29.2 → 3.29.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +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,6 +1,6 @@
1
- import{execFile as R}from"node:child_process";import{createHash as O,randomUUID as N}from"node:crypto";import{closeSync as G,copyFileSync as m,cpSync as P,existsSync as d,mkdirSync as b,openSync as C,readFileSync as f,rmSync as u,statSync as y,writeFileSync as B}from"node:fs";import{join as o,resolve as I}from"node:path";import{fileURLToPath as $}from"node:url";import{promisify as M}from"node:util";import{log as T}from"../../core/log/index.js";import{resolveCliPath as _}from"../../core/util/cli-probe.js";import{COMPATIBLE_DSH_VERSIONS as H,isCompatibleDshVersion as w}from"./bridge-session-reliability.js";import{bridgeDiscoveryDirectory as J,discoverDshBridgeEndpoints as L,resolveDshProfileIdentity as F}from"./profile-resolver.js";const z=M(R),U=2*1024*1024,p="@grix/dsh-bridge",q="deepseek-harness-bridge-installer",k=2,X=1e3;class ae{options;command;identity;constructor(e={}){this.options=e,this.command=e.command?.trim()||"dsh",this.identity=F({dshHome:e.dshHome,profileName:e.profileName})}async status(){const e=await _(this.command),r=this.bridgeAsset(),i=this.readInstalledBridgeVersion(),s=r.version,n=L(this.identity),a=n.length===1?n[0].bridgeVersion:null,c=n.length===1?n[0].dshVersion:null,g=e?await A(e,this.options.dshHome):null;let l;return e?!w(g)||c!==null&&!w(c)?l="bridge_incompatible":d(this.identity.profileRoot)?i?i!==s||this.installedBridgeContentStale(r)?l="bridge_update_required":n.length===0?l="profile_restart_required":n.length!==1?l="bridge_incompatible":a!==i||this.runningBridgePredatesInstalledContent(n[0])?l="profile_restart_required":l="ready":l="bridge_missing":l="profile_missing":l="dsh_missing",{readiness:l,command:this.command,commandPath:e,dshVersion:g,runningDshVersion:c,identity:this.identity,installedBridgeVersion:i,bundledBridgeVersion:s,runningBridgeVersion:a,endpointCount:n.length,compatibleDshVersions:H}}async install(){const e=await _(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});const r=await A(e,this.options.dshHome);if(!w(r))throw Object.assign(new Error(`DSH ${r??"unknown"} is outside the verified Bridge compatibility matrix (${H.join(", ")})`),{code:"bridge_incompatible"});const i=this.bridgeAsset();return j(this.identity,async()=>{await h(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const s=this.readInstalledBridgeVersion();if(s===i.version&&!this.installedBridgeContentStale(i))return this.status();const n=o(this.identity.dshHome,"assets","grix-dsh-bridge");b(n,{recursive:!0,mode:448});const a=this.captureInstallBackup(n,s),c=o(n,`grix-dsh-bridge-${i.version}.tgz`);m(i.tarball,c);try{if(s===i.version&&d(this.bridgePackageRoot())&&(await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome),d(this.bridgePackageRoot())))throw Object.assign(new Error(`dsh plugin remove left ${p} in place; refusing to attest an unverified reinstall`),{code:"bridge_install_failed"});await this.runPluginAdd(e,c),await h(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const g=this.readInstalledBridgeVersion();if(g!==i.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${g??"none"}, expected ${i.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(i.integrity)}catch(g){await this.rollbackInstall(e,n,a,s);try{u(c,{force:!0})}catch{}throw Object.assign(new Error(`Bridge install failed: ${D(g)}`),{code:"bridge_install_failed"})}return this.discardInstallBackup(a),this.status()})}async uninstall(){const e=await _(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});return j(this.identity,async()=>(this.readInstalledBridgeVersion()&&await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome),this.status()))}async runPluginAdd(e,r){const i=["plugin","--profile",this.identity.profileName,"add",r];let s;for(let n=1;n<=k;n++)try{await h(e,i,this.options.dshHome);return}catch(a){s=a,T.warn(q,`dsh plugin add attempt ${n}/${k} failed for profile ${this.identity.profileName}
2
- ${W(a)}`),n<k&&await new Promise(c=>setTimeout(c,X))}throw s}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,r){const i=o(e,"rollback",`${Date.now()}-${N()}`);b(i,{recursive:!0,mode:448});const s=this.bridgePackageRoot(),n=d(s);n&&P(s,o(i,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),c=d(a);c&&m(a,o(i,"package.json"));const g=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const l of g){const v=o(this.identity.profileRoot,l);d(v)&&m(v,o(i,l))}return B(o(i,"manifest.json"),`${JSON.stringify({priorVersion:r,hadBridge:n,hadPackageJson:c})}
3
- `,{mode:384}),{root:i,priorVersion:r,hadBridge:n,hadPackageJson:c}}async rollbackInstall(e,r,i,s){const n=s?o(r,`grix-dsh-bridge-${s}.tgz`):null;if(n&&d(n)&&await h(e,["plugin","--profile",this.identity.profileName,"add",n],this.options.dshHome).then(()=>!0).catch(()=>!1)){this.discardInstallBackup(i);return}if(i.hadBridge&&d(o(i.root,"dsh-bridge"))){this.restoreFilesystemBackup(i),this.discardInstallBackup(i);return}s?i.hadPackageJson&&this.restoreFilesystemBackup(i):(await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome).catch(()=>{}),this.cleanHalfInstalledBridge()),this.discardInstallBackup(i)}restoreFilesystemBackup(e){const r=this.bridgePackageRoot(),i=o(e.root,"dsh-bridge");e.hadBridge&&d(i)&&(u(r,{recursive:!0,force:!0}),b(o(this.identity.profileRoot,"node_modules","@grix"),{recursive:!0,mode:448}),P(i,r,{recursive:!0})),e.hadPackageJson&&d(o(e.root,"package.json"))&&m(o(e.root,"package.json"),this.profilePackageJsonPath());for(const s of["pnpm-lock.yaml","package-lock.json","yarn.lock"]){const n=o(e.root,s);d(n)&&m(n,o(this.identity.profileRoot,s))}}cleanHalfInstalledBridge(){try{u(this.bridgePackageRoot(),{recursive:!0,force:!0})}catch{}const e=this.profilePackageJsonPath();if(d(e))try{const r=JSON.parse(f(e,"utf8"));let i=!1;for(const s of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){const n=r[s];n&&typeof n=="object"&&!Array.isArray(n)&&p in n&&(delete n[p],i=!0)}i&&B(e,`${JSON.stringify(r,null,2)}
1
+ import{execFile as R}from"node:child_process";import{createHash as O,randomUUID as N}from"node:crypto";import{closeSync as G,copyFileSync as m,cpSync as P,existsSync as d,mkdirSync as b,openSync as C,readFileSync as f,rmSync as u,statSync as y,writeFileSync as B}from"node:fs";import{join as o,resolve as I}from"node:path";import{fileURLToPath as $}from"node:url";import{promisify as M}from"node:util";import{log as T}from"../../core/log/index.js";import{resolveCliPath as _}from"../../core/util/cli-probe.js";import{COMPATIBLE_DSH_VERSIONS as H,isCompatibleDshVersion as w}from"./bridge-session-reliability.js";import{bridgeDiscoveryDirectory as J,discoverDshBridgeEndpoints as L,resolveDshProfileIdentity as F}from"./profile-resolver.js";const z=M(R),U=2*1024*1024,p="@grix/dsh-bridge",q="deepseek-harness-bridge-installer",k=2,X=1e3;class ae{options;command;identity;constructor(e={}){this.options=e,this.command=e.command?.trim()||"dsh",this.identity=F({dshHome:e.dshHome,profileName:e.profileName})}async status(){const e=await _(this.command),r=this.bridgeAsset(),i=this.readInstalledBridgeVersion(),s=r.version,n=L(this.identity),a=n[0]?.bridgeVersion??null,l=n[0]?.dshVersion??null,g=e?await A(e,this.options.dshHome):null;let c;return e?!w(g)||l!==null&&!w(l)?c="bridge_incompatible":d(this.identity.profileRoot)?i?i!==s||this.installedBridgeContentStale(r)?c="bridge_update_required":n.length===0||a!==i||this.runningBridgePredatesInstalledContent(n[0])?c="profile_restart_required":c="ready":c="bridge_missing":c="profile_missing":c="dsh_missing",{readiness:c,command:this.command,commandPath:e,dshVersion:g,runningDshVersion:l,identity:this.identity,installedBridgeVersion:i,bundledBridgeVersion:s,runningBridgeVersion:a,endpointCount:n.length,compatibleDshVersions:H}}async install(){const e=await _(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});const r=await A(e,this.options.dshHome);if(!w(r))throw Object.assign(new Error(`DSH ${r??"unknown"} is outside the verified Bridge compatibility matrix (${H.join(", ")})`),{code:"bridge_incompatible"});const i=this.bridgeAsset();return j(this.identity,async()=>{await h(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const s=this.readInstalledBridgeVersion();if(s===i.version&&!this.installedBridgeContentStale(i))return this.status();const n=o(this.identity.dshHome,"assets","grix-dsh-bridge");b(n,{recursive:!0,mode:448});const a=this.captureInstallBackup(n,s),l=o(n,`grix-dsh-bridge-${i.version}.tgz`);m(i.tarball,l);try{if(s===i.version&&d(this.bridgePackageRoot())&&(await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome),d(this.bridgePackageRoot())))throw Object.assign(new Error(`dsh plugin remove left ${p} in place; refusing to attest an unverified reinstall`),{code:"bridge_install_failed"});await this.runPluginAdd(e,l),await h(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const g=this.readInstalledBridgeVersion();if(g!==i.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${g??"none"}, expected ${i.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(i.integrity)}catch(g){await this.rollbackInstall(e,n,a,s);try{u(l,{force:!0})}catch{}throw Object.assign(new Error(`Bridge install failed: ${D(g)}`),{code:"bridge_install_failed"})}return this.discardInstallBackup(a),this.status()})}async uninstall(){const e=await _(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});return j(this.identity,async()=>(this.readInstalledBridgeVersion()&&await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome),this.status()))}async runPluginAdd(e,r){const i=["plugin","--profile",this.identity.profileName,"add",r];let s;for(let n=1;n<=k;n++)try{await h(e,i,this.options.dshHome);return}catch(a){s=a,T.warn(q,`dsh plugin add attempt ${n}/${k} failed for profile ${this.identity.profileName}
2
+ ${W(a)}`),n<k&&await new Promise(l=>setTimeout(l,X))}throw s}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,r){const i=o(e,"rollback",`${Date.now()}-${N()}`);b(i,{recursive:!0,mode:448});const s=this.bridgePackageRoot(),n=d(s);n&&P(s,o(i,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),l=d(a);l&&m(a,o(i,"package.json"));const g=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const c of g){const v=o(this.identity.profileRoot,c);d(v)&&m(v,o(i,c))}return B(o(i,"manifest.json"),`${JSON.stringify({priorVersion:r,hadBridge:n,hadPackageJson:l})}
3
+ `,{mode:384}),{root:i,priorVersion:r,hadBridge:n,hadPackageJson:l}}async rollbackInstall(e,r,i,s){const n=s?o(r,`grix-dsh-bridge-${s}.tgz`):null;if(n&&d(n)&&await h(e,["plugin","--profile",this.identity.profileName,"add",n],this.options.dshHome).then(()=>!0).catch(()=>!1)){this.discardInstallBackup(i);return}if(i.hadBridge&&d(o(i.root,"dsh-bridge"))){this.restoreFilesystemBackup(i),this.discardInstallBackup(i);return}s?i.hadPackageJson&&this.restoreFilesystemBackup(i):(await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome).catch(()=>{}),this.cleanHalfInstalledBridge()),this.discardInstallBackup(i)}restoreFilesystemBackup(e){const r=this.bridgePackageRoot(),i=o(e.root,"dsh-bridge");e.hadBridge&&d(i)&&(u(r,{recursive:!0,force:!0}),b(o(this.identity.profileRoot,"node_modules","@grix"),{recursive:!0,mode:448}),P(i,r,{recursive:!0})),e.hadPackageJson&&d(o(e.root,"package.json"))&&m(o(e.root,"package.json"),this.profilePackageJsonPath());for(const s of["pnpm-lock.yaml","package-lock.json","yarn.lock"]){const n=o(e.root,s);d(n)&&m(n,o(this.identity.profileRoot,s))}}cleanHalfInstalledBridge(){try{u(this.bridgePackageRoot(),{recursive:!0,force:!0})}catch{}const e=this.profilePackageJsonPath();if(d(e))try{const r=JSON.parse(f(e,"utf8"));let i=!1;for(const s of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){const n=r[s];n&&typeof n=="object"&&!Array.isArray(n)&&p in n&&(delete n[p],i=!0)}i&&B(e,`${JSON.stringify(r,null,2)}
4
4
  `,{mode:384})}catch{}}discardInstallBackup(e){try{u(e.root,{recursive:!0,force:!0})}catch{}}readInstalledBridgeVersion(){const e=o(this.bridgePackageRoot(),"package.json");try{const r=JSON.parse(f(e,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}installedIntegrityPath(){return o(this.bridgePackageRoot(),".grix-bridge-integrity")}readInstalledBridgeIntegrity(){try{const e=f(this.installedIntegrityPath(),"utf8").trim();return e.startsWith("sha512-")?e:null}catch{return null}}writeInstalledBridgeIntegrity(e){B(this.installedIntegrityPath(),`${e}
5
5
  `,{encoding:"utf8",mode:384})}installedBridgeContentStale(e=this.bridgeAsset()){return d(this.bridgePackageRoot())?this.readInstalledBridgeIntegrity()!==e.integrity:!0}runningBridgePredatesInstalledContent(e){try{const r=y(this.installedIntegrityPath()).mtimeMs,i=Date.parse(e.startedAt);return Number.isFinite(i)?r>i:!0}catch{return!1}}bridgeAsset(){return this.options.tarballPath?E(I(this.options.tarballPath)):x()}}function de(t){if(t.readiness==="ready")return null;const e=t.identity.profileName,r=`dsh --profile ${e}`,i=t.endpointCount>0&&t.runningBridgeVersion&&t.installedBridgeVersion&&t.runningBridgeVersion!==t.installedBridgeVersion?`Grix Bridge in DSH profile "${e}" is running version ${t.runningBridgeVersion}, but ${t.installedBridgeVersion} is installed on disk. dsh does not hot-load plugin upgrades: stop the running profile process, then start it again with: ${r}`:`Grix Bridge is installed in DSH profile "${e}", but no live Bridge endpoint is available. dsh does not hot-load plugins: stop the running profile process, then start it again with: ${r}`,s={dsh_missing:"dsh is not installed or not on PATH. Install DeepSeek Harness (dsh), then retry.",profile_missing:`DSH profile "${e}" does not exist yet. Create/boot it once with: ${r}`,bridge_missing:`Grix Bridge is not installed in DSH profile "${e}". Install it from the DeepSeek Harness toolbar (or the dsh_install_bridge action), then restart the profile if it is already running.`,bridge_update_required:`Grix Bridge in DSH profile "${e}" needs an update (installed ${t.installedBridgeVersion??"none"}, expected ${t.bundledBridgeVersion}${t.installedBridgeVersion===t.bundledBridgeVersion?", content hash mismatch":""}). Update from the toolbar, then restart the profile \u2014 dsh does not hot-load plugin upgrades.`,profile_restart_required:i,bridge_incompatible:`DSH / Grix Bridge versions are incompatible for profile "${e}" (dsh=${t.dshVersion??"unknown"}, running=${t.runningDshVersion??"none"}, bridge=${t.runningBridgeVersion??t.installedBridgeVersion??"none"}). Supported DSH: ${t.compatibleDshVersions.join(", ")}.`};return Object.assign(new Error(s[t.readiness]),{code:t.readiness})}function le(){return x().tarball}function x(){const t=[$(new URL("../../assets/dsh-bridge/",import.meta.url)),$(new URL("../../../dist/assets/dsh-bridge/",import.meta.url))].find(i=>d(o(i,"manifest.json")));if(!t)throw Object.assign(new Error("Bundled Grix DSH Bridge asset is unavailable; run the Connector build first"),{code:"bridge_asset_missing"});const e=JSON.parse(f(o(t,"manifest.json"),"utf8"));if(typeof e.tarball!="string"||!e.tarball||typeof e.bridgeVersion!="string"||!e.bridgeVersion)throw Object.assign(new Error("Invalid Grix DSH Bridge asset manifest"),{code:"bridge_asset_invalid"});const r=E(o(t,e.tarball),e.bridgeVersion);if(Number(e.size)!==y(r.tarball).size)throw Object.assign(new Error("Grix DSH Bridge asset size mismatch"),{code:"bridge_asset_invalid"});if(typeof e.integrity=="string"&&e.integrity.startsWith("sha512-")&&e.integrity!==r.integrity)throw Object.assign(new Error("Grix DSH Bridge asset integrity mismatch"),{code:"bridge_asset_invalid"});return r}function E(t,e){if(!d(t)||!y(t).isFile())throw Object.assign(new Error(`Grix DSH Bridge asset is missing: ${t}`),{code:"bridge_asset_missing"});if(y(t).size>U)throw Object.assign(new Error("Grix DSH Bridge asset exceeds the 2 MiB safety limit"),{code:"bridge_asset_invalid"});const r=e??/grix-dsh-bridge-([0-9A-Za-z.+-]+)\.tgz$/.exec(t)?.[1];if(!r)throw Object.assign(new Error("Cannot determine Grix DSH Bridge version"),{code:"bridge_asset_invalid"});const i=`sha512-${O("sha512").update(f(t)).digest("base64")}`;return{tarball:t,version:r,integrity:i}}async function j(t,e){const r=J(t);b(r,{recursive:!0,mode:448});const i=o(r,"install.lock");let s=V(i);if(s===null){let n=0;try{n=Number(f(i,"utf8").trim())}catch{}let a=!1;try{a=n===0&&Date.now()-y(i).mtimeMs>5*6e4}catch{}if(a||Number.isSafeInteger(n)&&n>0&&!Y(n)){try{u(i,{force:!0})}catch{}s=V(i)}}if(s===null)throw Object.assign(new Error(`Another Grix DSH Bridge install is active for profile ${t.profileName}`),{code:"bridge_install_busy"});try{return B(s,`${process.pid}
6
6
  `,"utf8"),await e()}finally{G(s);try{u(i,{force:!0})}catch{}}}function V(t){try{return C(t,"wx",384)}catch(e){if(e.code==="EEXIST")return null;throw Object.assign(new Error(`Cannot acquire Grix DSH Bridge install lock: ${D(e)}`),{code:"bridge_install_failed"})}}function Y(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}async function A(t,e){try{return(await h(t,["--version"],e)).trim().split(/\s+/)[0]||null}catch{return null}}async function h(t,e,r){try{return(await z(t,e,{env:{...process.env,...r?{DSH_HOME:I(r)}:{}},timeout:6e4,maxBuffer:8388608})).stdout}catch(i){const s=i&&typeof i=="object"?i:{};throw Object.assign(new Error(D(i)),{code:"dsh_command_failed",stderr:typeof s.stderr=="string"?S(s.stderr):void 0})}}function S(t){return t.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]")}function D(t){const e=t&&typeof t=="object"?t:{};return S(String(e.stderr??e.message??t??"unknown error")).replace(/[\r\n]+/g," ").slice(0,1024)}function W(t){const e=t&&typeof t=="object"?t:{};return S(String(e.stderr??e.message??t??"unknown error")).slice(0,8*1024)}export{ae as DshBridgeInstaller,le as defaultBridgeTarball,de as errorForDshBridgeReadiness};
@@ -1,3 +1,3 @@
1
- import{createHash as D,randomUUID as M}from"node:crypto";import{EventEmitter as j}from"node:events";import{copyFileSync as oe,existsSync as L,mkdirSync as ne}from"node:fs";import{dirname as re,join as T,resolve as U}from"node:path";import{fileURLToPath as O}from"node:url";import{log as m}from"../../core/log/index.js";import{syncDefaultSkillsToDir as ae}from"../../default-skills/index.js";import{resolveCliPath as de}from"../../core/util/cli-probe.js";import{DshWireCapture as le}from"./audit-boundary.js";import{dsmlToolCallKey as he,projectVisibleDsmlText as ce}from"./dsml-text-filter.js";import{mapDshSessionEvent as ue,unwrapDshSessionEvent as pe}from"./event-mapper.js";import{buildDshUserPrompt as V,extractQuotedMessageMarker as W}from"./prompt-builder.js";import{DshProcessRuntime as ge}from"./process-runtime.js";import{DshProfileRuntime as me}from"./profile-runtime.js";import{createDshWebProfile as fe}from"./profile-catalog.js";import{listDshPlugins as E,resolveDshPlugin as ve,updateDshPluginIds as be}from"./plugin-manager.js";import{prepareDshSessionPluginOverlay as _e}from"./session-plugin-overlay.js";import{assertSelectableDshProfileName as Se,discoverDshBridgeEndpoints as Ie,listDshProfiles as ke,resolveDshConnectorProfileDataDir as Pe,resolveDshHome as Te,resolveDshSelectedProfileName as we}from"./profile-resolver.js";import{DshBridgeInstaller as R,errorForDshBridgeReadiness as A}from"./bridge-installer.js";import{ensureDshBridgeReady as ye,prepareDshProfileBridge as xe}from"./profile-supervisor.js";import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as G,dshRuntimeEnsureBackoffMs as Ce,isRetryableDshRuntimeError as De}from"./runtime-ensure.js";import{runDshProtocolProbe as Me}from"./probe.js";import{buildDshSystemPrompt as Ee,describeDshSystemPrompt as Re}from"./system-prompt.js";import{DshActionCoordinator as Ae}from"./toolbar-actions.js";import{adoptDshProfileModels as He,adoptLiveDshProviderSelection as $e,buildDshToolbarMeta as Be,DEFAULT_DSH_MAX_TOKENS as qe,DEFAULT_DSH_MODELS as Fe,DEFAULT_DSH_PRESETS as Ne,DEFAULT_DSH_PROVIDER_ID as H,normalizeDshPresets as je,normalizeDshProviders as Le,permissionModeFor as z,resolveDshAgentPreset as Q,resolveDshModeId as Ue,resolveDshProviderId as Oe,retainRequestedDshProvider as Ve}from"./toolbar-state.js";import{modelsForDshProvider as We,resolveDshCatalogForToolbar as Ge,writeDshCatalogCache as ze}from"./catalog-cache.js";import{TurnCorrelator as Qe}from"./turn-correlator.js";import{getDshSessionUsageStore as Ke,normalizeDshUsage as K}from"./usage.js";import{toolCallToInvoke as Xe}from"../../core/mcp/tools.js";import{isDshBridgedGrixTool as Je}from"./grix-tool-bridge.js";import{DSH_GRIX_PROVIDER_ID as b,buildDshManagedProvider as X}from"./dsh-provider-config.js";const f="deepseek-harness-adapter",J=20*6e4,Y=6e4,Z=9e4,ee=30*6e4;class Ye extends j{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class Ft extends j{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;hardTimeoutTimer=null;activeTimeoutMs=J;intentionalRuntimeStop=!1;personaDirty=!1;profileRevision=0;appliedProfileRevision=-1;rebuildPromise=null;runtimeStartPromise=null;contextWindow=null;reportedContextCapacity=null;providerQuota=null;settingsState="applied";settingsErrorCode=null;injectedMessageIds=new Set;auditBoundaries=new Map;actionCoordinator=new Ae;activeWireStart=0;activeUsage=te();activeUsageSeq=-1;activeCommittedUsageSeqs=new Set;permissionHandler=null;quotedMessageId;cancelRequested=!1;runtimeReadiness="unknown";bridgeCapabilities=null;bridgeAckCursor=0;pendingFinalBridgeAck=null;finishingTurn=!1;pendingApprovals=new Map;options;models=Fe;providers=[];presets=[...Ne];catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.hydrateCatalogFromCache()}async start(){this.alive=!0,this.stopped=!1,this.settingsState="applied",this.settingsErrorCode=null,this.hydrateCatalogFromCache();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&this.seedSessionToolbarFromGlobal(),this.syncGrixProvider(),e&&await this.options.bindingStore.flush(),this.resolveIntegrationMode()==="profile_bridge")try{const t=await this.attachSelectedProfile();await this.healBridgeUpdate(t)}catch(t){this.runtimeReadiness=String(t?.code??"bridge_probe_failed"),this.settingsErrorCode=this.runtimeReadiness}else this.runtimeReadiness="ready";this.pushToolbarMeta(),this.refreshProviderQuota(!1)}async stop(){this.stopped=!0,this.clearPendingApprovals("cancelled"),this.clearTimeout(),this.active&&this.finishActive("canceled","connector shutdown"),this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="pending",this.settingsErrorCode=null,this.pushToolbarMeta(),await this.rebuildPromise?.catch(()=>{}),await this.stopRuntime(!0),await this.usageStore().flush(),this.alive=!1}isAlive(){return this.alive&&!this.stopped}async createSession(e){return this.options.aibotSessionId}async resumeSession(e,t){}async destroySession(e){e===this.options.aibotSessionId&&(this.usageStore().delete(e),await this.usageStore().flush(),await this.stopRuntime(!0))}sendPrompt(e){const t=new Ye(e.adapterSessionId,()=>this.cancel(e.adapterSessionId));return queueMicrotask(()=>t.emit("done",{status:"failed",error:"Use deliverInboundEvent for platform prompts"})),t}async cancel(e){await this.cancelActive("user canceled")}deliverInboundEvent(e){if(!this.isAlive()){this.failEvent(e,"adapter is not alive");return}if(e.attachments_json&&e.attachments_json!=="[]"){this.failEvent(e,"DeepSeek Harness first version supports text only; attachments must be materialized in the bound workspace");return}if(this.active){this.failEvent(e,"concurrent prompt rejected");return}this.runInboundEvent(e)}deliverStopEvent(e,t){this.active&&e===this.active.inbound.event_id&&(t&&t!==this.active.inbound.session_id||this.cancelActive("user canceled"))}async handleLocalAction(e){if(!["set_model","set_mode","set_provider","set_preset","set_profile","create_profile","get_session_usage","get_rate_limits","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals","exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type))return{handled:!1,kind:""};const t=await this.actionCoordinator.run(e.action_id,()=>this.executeLocalAction(e));return this.callbacks.sendLocalActionResult(e.action_id,t.status,t.result,t.errorCode,t.errorMsg),{handled:!0,kind:e.action_type}}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.isAlive()&&(!this.runtime||this.runtime.isConnected())}getStatus(){return{alive:this.isAlive()&&!!this.runtime,busy:!!this.active||this.intentionalRuntimeStop||!!this.rebuildPromise||!!this.runtimeStartPromise,backgroundBusy:!1,sessions:this.runtime?1:0,details:{runtimeGeneration:this.runtimeGeneration,runtimeSessionId:this.runtimeSessionId||void 0}}}getActiveEventIds(){return this.active?[this.active.inbound.event_id]:[]}takeAuditBoundary(e){const t=this.auditBoundaries.get(e);return this.auditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.active=null,this.correlator=null,this.clearTimeout()}getMcpConfig(){return null}async hasBackgroundWork(){return this.runtime?.hasBackgroundWork()??!1}onAgentProfileChanged(){this.profileRevision+=1,this.personaDirty=!0,!this.active&&this.runtime&&this.rebuildRuntime("persona_changed")}updateProviderQuotaSnapshot(e){this.providerQuota=e??null,this.pushToolbarMeta()}async probe(e={}){const t=this.resolveIntegrationMode(),i=t==="embedded_jsonrpc"?this.config.command||"dsh-jsonrpc-agent":"dsh",s=await de(i),o=!!s;let d={ok:e.conversation!==!0,latency:null};if(o&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const l=await Me({command:s,args:this.config.args,cordisPath:U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});d={ok:!0,latency:l.latencyMs,serverName:l.serverName,serverVersion:l.serverVersion}}catch(l){d={ok:!1,latency:null,error:this.redactError(l)}}else{const l=Date.now();try{const a=new R({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),p=await ye({installer:a,autoStart:!1}),c=A(p);if(c)throw c;const n=Ie(p.identity);if(n.length!==1)throw Object.assign(new Error(n.length===0?`No live Grix Bridge endpoint in DSH profile "${p.identity.profileName}"`:`Multiple live Grix Bridge endpoints for DSH profile "${p.identity.profileName}"`),{code:n.length===0?"bridge_missing":"profile_instance_ambiguous"});d={ok:!0,latency:Date.now()-l,serverName:"grix-dsh-profile-bridge",serverVersion:n[0].bridgeVersion}}catch(a){d={ok:!1,latency:null,error:this.redactError(a)}}}return{cli:{command:i,installed:o,path:s,version:null,...o?{}:{error:{code:"cli_not_found",message:`${i} not found`}}},conversation:{attempted:e.conversation===!0,ok:d.ok,latency_ms:d.latency,...d.ok?{}:{error:{code:"conversation_failed",message:d.error??"initialize/shutdown probe failed"}}},config:{model:this.resolveDesiredSettings().modelId,base_url:this.config.env?.DEEPSEEK_BASE_URL??null,source:{model:"config",base_url:this.config.env?.DEEPSEEK_BASE_URL?"env":"unknown"},extras:{protocol:t==="profile_bridge"?"grix-dsh/1":"jsonrpc-v1",profile:this.resolveSelectedProfile(),serverName:d.serverName,serverVersion:d.serverVersion}},process:{started:!!this.runtime,alive:this.runtime?.isConnected()??!1,busy:!!this.active}}}async runInboundEvent(e){const t={inbound:e,admitted:!1,claimed:!1,turnEnded:!1,rootIdle:!1,text:"",sentText:"",seq:0,startedAt:Date.now()};this.active=t,this.correlator=new Qe(t),this.activeUsage=te(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{if(await this.ensureRuntimeWithRetry(),this.cancelRequested||this.active!==t)return;this.activeWireStart=this.capture?.offset??0;const i=V(e,this.injectedMessageIds);this.startTimeout(e.timeoutMs);const s=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:i.text}]});if(!s?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(s.messageId)}catch(i){const s=this.redactError(i,e.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":s)}}async ensureRuntime(){if(this.stopped)throw new Error("adapter stopped");if(this.runtime)return;this.syncGrixProvider();const t=this.options.bindingStore.get(this.options.aibotSessionId)?.cwd;if(!t)throw Object.assign(new Error("Session binding missing. Open a workspace first."),{code:"binding_missing"});this.projectConnectorSkills();let i=this.resolveDesiredSettings();const s=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),o={};s?.modelId||(o.modelId=i.modelId),!s?.providerId&&i.providerId&&(o.providerId=i.providerId),(o.modelId||o.providerId)&&(this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,o),await this.options.bindingStore.flush(),i=this.resolveDesiredSettings());const d=this.callbacks.getAgentProfile(),l=this.profileRevision,a=Ee({...d,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),p=Re(a);this.runtimeGeneration+=1;const c=this.resolveIntegrationMode(),n=this.resolveSelectedProfile();if(c==="profile_bridge")try{await this.ensureProfileReadyForChat(),this.pushToolbarMeta()}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),g}let r=c==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,n):void 0;c==="profile_bridge"&&!r&&(r={profileName:n,sessionId:it(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r),await this.options.bindingStore.flush()),this.runtimeSessionId=r?.sessionId??tt(this.options.aibotSessionId,this.runtimeGeneration);const u=this.profileDataDir(n),v=U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),$=_e({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:n,pluginIds:i.pluginIds??[],overlayId:D("sha256").update(this.options.aibotSessionId).digest("hex").slice(0,24),baseCordisPath:v}),se=T(u,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new le(se);const _=c==="embedded_jsonrpc"?new ge({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:$.embeddedCordisPath??v,home:u,sessionRoot:T(u,"sessions"),env:this.config.env,systemPrompt:a,settings:i,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new me({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:n,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:r?.sessionCreated===!0,lastAckCursor:r?.eventCursor??0,systemPrompt:a,settings:i,pluginOverlayPath:$.bridgeOverlayPath,managedProvider:i.providerId===b?X(this.options.provider??{}):void 0,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:g=>this.handleBridgeApproval(g),onToolInvoke:(g,w,k)=>this.invokeGrixTool(g,w,k),onCursorAck:g=>{!r||g<=r.eventCursor||(r={...r,eventCursor:g},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r))}});this.runtime=_,this.bridgeAckCursor=r?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const g=await _.start();if(!_.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});_.client?.on("notification",(S,I)=>this.onNotification(S,I)),_.client?.on("protocolError",S=>this.onProtocolError(S)),_.onExit(()=>this.onRuntimeExit()),_.client?.activateNotifications?.();let w=!1;if(c==="profile_bridge"){const S=Le(g.providers),I=$e({requestedProviderId:i.providerId,liveProviders:S,liveSelectedProvider:String(g.selectedProvider??"")});this.providers=Ve(S,I.providerId,this.providers),i={...i,providerId:I.providerId},w=I.persistFallback;const x=I.providerId,q=Object.prototype.hasOwnProperty.call(g,"models")?g.models:void 0,F=!!this.catalogProviderId&&!!x&&x!==this.catalogProviderId;this.models=He({current:this.models,fetched:q,providerChanged:F}),(q!==void 0||F)&&(this.catalogProviderId=x||this.catalogProviderId);const C=String(g.selectedModel??"");C&&C!==i.modelId&&(i={...i,modelId:C});const N=je(g.presets);N.length>0&&(this.presets=N);const y=String(g.selectedPreset??"");y&&y!==i.agentPreset&&(i={...i,agentPreset:y},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,y))}const k=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),B=(k?.revision??0)!==i.revision,P={};!B&&w&&(k?.providerId??"")!==(i.providerId??"")&&(P.providerId=i.providerId),!B&&(k?.modelId??"")!==i.modelId&&(P.modelId=i.modelId),(P.providerId||P.modelId)&&(i.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,P)??i.revision,await this.options.bindingStore.flush(),m.warn(f,`replaced unavailable persisted DSH catalog selection provider=${i.providerId} model=${i.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:i.revision,providerId:i.providerId??H,modelId:i.modelId,modeId:i.modeId},this.runtimeReadiness="ready",this.bridgeCapabilities=g.capabilities??null,c==="profile_bridge"&&r&&!r.sessionCreated&&(r={...r,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===i.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=l,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,m.info(f,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${p.schemaVersion} prompt_sha256=${p.sha256} prompt_length=${p.length}`),await this.persistCatalogCache(i.providerId??H),this.pushToolbarMeta(),this.settingsState==="pending"&&!this.active&&!this.stopped&&this.rebuildRuntime("settings_changed_during_start")}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),g}}ensureRuntimeWithRetry(){if(this.runtimeStartPromise)return this.runtimeStartPromise;const e=this.ensureRuntimeWithRetryLoop();this.runtimeStartPromise=e;const t=()=>{this.runtimeStartPromise===e&&(this.runtimeStartPromise=null)};return e.then(t,t),e}async ensureRuntimeWithRetryLoop(){let e;for(let t=1;t<=G;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||!De(s)||t===G)throw i;m.warn(f,`runtime ensure retry attempt=${t} code=${s||"unknown"}`),this.settingsState="pending",this.settingsErrorCode=s||"runtime_initialize_failed",this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),await this.stopRuntime(!0),await et(Ce(t))}throw e}onNotification(e,t){const i=Ze(t);if(e==="session.event"){const s=pe(t);if(!s){this.onProtocolError(new Error("malformed session.event"));return}const o=this.onSessionEvent(s);this.advanceBridgeAck(i,o);return}if(e==="session.status"){const s=t&&typeof t=="object"?t:{};if(String(s.sessionId??"")===this.runtimeSessionId){this.touchActivity(),this.correlator?.markRootStatus(String(s.status??"")),s.status==="idle"&&this.active&&this.correlator&&m.debug(f,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const d=!!this.correlator?.complete;d&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,d)}else i>0&&this.advanceBridgeAck(i,!1);return}if(e==="subagent.started"||e==="subagent.finished"){this.touchActivity(3);const s=t&&typeof t=="object"?t:{},o=String(s.childSessionId??s.sessionId??"");o&&this.capture?.addChild(o),this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:s},e==="subagent.started"?"[subagent started]":"[subagent finished]"),this.advanceBridgeAck(i,!1);return}this.onProtocolError(new Error(`unknown required JSON-RPC notification: ${e}`))}onSessionEvent(e){if(!this.active||!this.correlator)return!1;this.touchActivity(e.type==="tool/call"||e.type==="tool/result"?3:1);const t=ue(e);if(t.kind==="unknown"&&!rt(e)&&e.ignorable!==!0)return this.onProtocolError(new Error(`unknown required SessionEvent: ${e.type}`)),!1;if(e.sessionId&&e.sessionId!==this.runtimeSessionId)return!1;const i=this.correlator.accept(e);if((e.type==="agent/inbox/spliced"||e.type==="user/message"||e.type==="turn/end")&&m.debug(f,`turn correlation event=${e.type} belongs=${i} admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded}`),e.type==="agent/inbox/spliced"&&this.active.admitted){const s=V(this.active.inbound,this.injectedMessageIds);for(const o of s.contextIds)this.injectedMessageIds.add(o);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?st(e)?(this.flushPendingTextAsThinking(),!1):t.kind==="text"?(t.payload?.committed===!0?(t.payload?.hasToolCall===!0?this.applyCommittedToolStepText(t.text??""):this.applyCommittedText(t.text??""),t.usage&&this.collectCommittedUsage(t.usage,Number(e.seq??e.step??Date.now()))):this.applyTextDelta(t.text??""),!1):t.kind==="thinking"?(this.thinkingEnabled()&&this.callbacks.sendThinking(this.active.inbound.event_id,this.active.inbound.session_id,t.text??""),!1):t.kind==="tool_call"?(this.flushPendingTextAsThinking(),this.toolEventsEnabled()&&this.sendRaw("tool_call",{call_id:t.callId,tool_name:t.name,tool_input:t.input},`[tool] ${t.name}`),!1):t.kind==="tool_result"?(this.toolEventsEnabled()&&this.sendRaw("tool_result",{call_id:t.callId,result:t.output},`[tool result] ${t.callId??""}`),!1):t.kind==="todo"||t.kind==="compaction"?!1:t.kind==="context"?(this.updateContextCapacity(t.payload),!1):t.kind==="usage"?(this.updateContextWindow(t.usage),!1):t.kind==="turn_end"&&this.correlator.complete?(this.finishFromTurnOutcome(),!0):!1:!1}applyTextDelta(e){this.active.pendingText=`${this.active.pendingText??""}${e}`}applyCommittedText(e){const t=this.active;if(t.pendingText=void 0,e.startsWith(t.text))t.text=e;else if(!t.text.startsWith(e)){m.warn(f,`committed assistant text diverged event=${t.inbound.event_id}`);const i=W(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}flushPendingTextAsThinking(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,this.thinkingEnabled()&&t.trim()&&this.callbacks.sendThinking(e.inbound.event_id,e.inbound.session_id,t),e.lastThinkingText=t)}applyCommittedToolStepText(e){const t=this.active;t&&(t.pendingText=void 0,e.trim()&&t.lastThinkingText!==e&&this.thinkingEnabled()&&(this.callbacks.sendThinking(t.inbound.event_id,t.inbound.session_id,e),t.lastThinkingText=e))}promotePendingTextToVisible(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,e.text+=t)}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=W(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const o=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),d=ce(o,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(d.suppressedToolCalls);const l=d.visible;this.observeVisibleTextAfterToolCall(l);let a="";l.startsWith(i.sentText)?a=l.slice(i.sentText.length):(e||t.finalizeDsml)&&(a=l),!(!a&&!e)&&(i.seq+=1,this.callbacks.sendStreamChunk(i.inbound.event_id,i.inbound.session_id,a,i.seq,e,`${i.inbound.event_id}-dsh`,this.quotedMessageId),i.sentText=l)}surfaceSuppressedDsmlToolCalls(e){if(!this.active||e.length===0)return;const t=this.active.dsmlSuppressedKeys??new Set;this.active.dsmlSuppressedKeys=t;for(const i of e){const s=he(i);if(t.has(s)||(t.add(s),this.markToolCallAwaitingFinalText(),m.warn(f,`suppressed leaked DSML tool markup name=${i.name} event=${this.active.inbound.event_id}`),!this.toolEventsEnabled()))continue;let o=i.arguments;try{o=JSON.parse(i.arguments)}catch{}this.sendRaw("tool_call",{call_id:`dsml-${t.size}`,tool_name:i.name,tool_input:o,source:"dsml_text_leak",executed:!1},`[tool] ${i.name}`)}}markToolCallAwaitingFinalText(){const e=this.active;e&&(e.toolCallAwaitingFinalText=!0,e.toolCallVisibleTextLength=e.sentText.length)}observeVisibleTextAfterToolCall(e){const t=this.active;if(!t?.toolCallAwaitingFinalText)return;const i=t.toolCallVisibleTextLength??t.sentText.length;e.slice(i).trim().length!==0&&(t.toolCallAwaitingFinalText=!1,t.toolCallVisibleTextLength=void 0)}collectCommittedUsage(e,t){if(this.activeCommittedUsageSeqs.has(t))return;this.activeCommittedUsageSeqs.add(t);const i=K(e);this.activeUsage.inputTokens+=i.inputTokens,this.activeUsage.outputTokens+=i.outputTokens,this.activeUsage.cacheReadInputTokens+=i.cacheReadInputTokens,this.activeUsage.cacheCreationInputTokens+=i.cacheCreationInputTokens,this.activeUsage.reasoningTokens+=i.reasoningTokens,this.activeUsageSeq=Math.max(this.activeUsageSeq,t),this.updateContextWindow(i)}updateContextWindow(e){const t=K(e),i=this.resolveDesiredSettings(),s=this.models.find(d=>d.id===i.modelId),o=this.reportedContextCapacity??s?.contextWindow;if(o&&o>0){const d=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:d,totalTokens:o,remainingTokens:Math.max(0,o-d),usedPercentage:d/o*100,remainingPercentage:Math.max(0,100-d/o*100)},this.pushToolbarMeta()}}updateContextCapacity(e){const t=Number(e?.contextWindow);if(!Number.isFinite(t)||t<=0)return;this.reportedContextCapacity=t;const i=this.contextWindow&&typeof this.contextWindow=="object"?this.contextWindow:{},s=Math.max(0,Number(i.usedTokens)||0);this.contextWindow={usedTokens:s,totalTokens:t,remainingTokens:Math.max(0,t-s),usedPercentage:s/t*100,remainingPercentage:Math.max(0,100-s/t*100)},this.pushToolbarMeta()}finishFromTurnOutcome(){if(!this.active)return;this.finishingTurn=!0;const e=this.active.outcome??"completed",t=this.active.outcomeDetail?.trim();e==="completed"?this.finishActive("responded"):e==="aborted"?this.finishActive("canceled"):e==="max-tokens"&&this.active.sentText?this.finishActive("responded","Response truncated at model token limit"):this.finishActive("failed",t?t.toLowerCase().includes(e.toLowerCase())?`Harness turn ended: ${t}`:`Harness turn ended: ${e}: ${t}`:`Harness turn ended: ${e}`)}finishActive(e,t){const i=this.active;if(!i)return;let s=e,o=t;this.finishingTurn=!0,this.clearTimeout(),this.promotePendingTextToVisible(),this.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&(s="failed",o="DeepSeek Harness ended after a tool call without returning final assistant text",m.warn(f,`${o} event=${i.inbound.event_id}`)),i.text=i.sentText;const d=s==="failed"&&!!o?.trim();d&&(i.text+=`
1
+ import{createHash as D,randomUUID as M}from"node:crypto";import{EventEmitter as j}from"node:events";import{copyFileSync as oe,existsSync as L,mkdirSync as ne}from"node:fs";import{dirname as re,join as T,resolve as U}from"node:path";import{fileURLToPath as O}from"node:url";import{log as m}from"../../core/log/index.js";import{syncDefaultSkillsToDir as ae}from"../../default-skills/index.js";import{resolveCliPath as de}from"../../core/util/cli-probe.js";import{DshWireCapture as le}from"./audit-boundary.js";import{dsmlToolCallKey as he,projectVisibleDsmlText as ce}from"./dsml-text-filter.js";import{mapDshSessionEvent as ue,unwrapDshSessionEvent as pe}from"./event-mapper.js";import{buildDshUserPrompt as V,extractQuotedMessageMarker as W}from"./prompt-builder.js";import{DshProcessRuntime as ge}from"./process-runtime.js";import{DshProfileRuntime as me}from"./profile-runtime.js";import{createDshWebProfile as fe}from"./profile-catalog.js";import{listDshPlugins as E,resolveDshPlugin as ve,updateDshPluginIds as be}from"./plugin-manager.js";import{prepareDshSessionPluginOverlay as _e}from"./session-plugin-overlay.js";import{assertSelectableDshProfileName as Se,discoverDshBridgeEndpoints as Ie,listDshProfiles as ke,resolveDshConnectorProfileDataDir as Pe,resolveDshHome as Te,resolveDshSelectedProfileName as we}from"./profile-resolver.js";import{DshBridgeInstaller as R,errorForDshBridgeReadiness as A}from"./bridge-installer.js";import{ensureDshBridgeReady as ye,prepareDshProfileBridge as xe}from"./profile-supervisor.js";import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as G,dshRuntimeEnsureBackoffMs as Ce,isRetryableDshRuntimeError as De}from"./runtime-ensure.js";import{runDshProtocolProbe as Me}from"./probe.js";import{buildDshSystemPrompt as Ee,describeDshSystemPrompt as Re}from"./system-prompt.js";import{DshActionCoordinator as Ae}from"./toolbar-actions.js";import{adoptDshProfileModels as He,adoptLiveDshProviderSelection as $e,buildDshToolbarMeta as Be,DEFAULT_DSH_MAX_TOKENS as qe,DEFAULT_DSH_MODELS as Fe,DEFAULT_DSH_PRESETS as Ne,DEFAULT_DSH_PROVIDER_ID as H,normalizeDshPresets as je,normalizeDshProviders as Le,permissionModeFor as z,resolveDshAgentPreset as Q,resolveDshModeId as Ue,resolveDshProviderId as Oe,retainRequestedDshProvider as Ve}from"./toolbar-state.js";import{modelsForDshProvider as We,resolveDshCatalogForToolbar as Ge,writeDshCatalogCache as ze}from"./catalog-cache.js";import{TurnCorrelator as Qe}from"./turn-correlator.js";import{getDshSessionUsageStore as Ke,normalizeDshUsage as K}from"./usage.js";import{toolCallToInvoke as Xe}from"../../core/mcp/tools.js";import{isDshBridgedGrixTool as Je}from"./grix-tool-bridge.js";import{DSH_GRIX_PROVIDER_ID as b,buildDshManagedProvider as X}from"./dsh-provider-config.js";const f="deepseek-harness-adapter",J=20*6e4,Y=6e4,Z=9e4,ee=30*6e4;class Ye extends j{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class Ft extends j{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;hardTimeoutTimer=null;activeTimeoutMs=J;intentionalRuntimeStop=!1;personaDirty=!1;profileRevision=0;appliedProfileRevision=-1;rebuildPromise=null;runtimeStartPromise=null;contextWindow=null;reportedContextCapacity=null;providerQuota=null;settingsState="applied";settingsErrorCode=null;injectedMessageIds=new Set;auditBoundaries=new Map;actionCoordinator=new Ae;activeWireStart=0;activeUsage=te();activeUsageSeq=-1;activeCommittedUsageSeqs=new Set;permissionHandler=null;quotedMessageId;cancelRequested=!1;runtimeReadiness="unknown";bridgeCapabilities=null;bridgeAckCursor=0;pendingFinalBridgeAck=null;finishingTurn=!1;pendingApprovals=new Map;options;models=Fe;providers=[];presets=[...Ne];catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.hydrateCatalogFromCache()}async start(){this.alive=!0,this.stopped=!1,this.settingsState="applied",this.settingsErrorCode=null,this.hydrateCatalogFromCache();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&this.seedSessionToolbarFromGlobal(),this.syncGrixProvider(),e&&await this.options.bindingStore.flush(),this.resolveIntegrationMode()==="profile_bridge")try{const t=await this.attachSelectedProfile();await this.healBridgeUpdate(t)}catch(t){this.runtimeReadiness=String(t?.code??"bridge_probe_failed"),this.settingsErrorCode=this.runtimeReadiness}else this.runtimeReadiness="ready";this.pushToolbarMeta(),this.refreshProviderQuota(!1)}async stop(){this.stopped=!0,this.clearPendingApprovals("cancelled"),this.clearTimeout(),this.active&&this.finishActive("canceled","connector shutdown"),this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="pending",this.settingsErrorCode=null,this.pushToolbarMeta(),await this.rebuildPromise?.catch(()=>{}),await this.stopRuntime(!0),await this.usageStore().flush(),this.alive=!1}isAlive(){return this.alive&&!this.stopped}async createSession(e){return this.options.aibotSessionId}async resumeSession(e,t){}async destroySession(e){e===this.options.aibotSessionId&&(this.usageStore().delete(e),await this.usageStore().flush(),await this.stopRuntime(!0))}sendPrompt(e){const t=new Ye(e.adapterSessionId,()=>this.cancel(e.adapterSessionId));return queueMicrotask(()=>t.emit("done",{status:"failed",error:"Use deliverInboundEvent for platform prompts"})),t}async cancel(e){await this.cancelActive("user canceled")}deliverInboundEvent(e){if(!this.isAlive()){this.failEvent(e,"adapter is not alive");return}if(e.attachments_json&&e.attachments_json!=="[]"){this.failEvent(e,"DeepSeek Harness first version supports text only; attachments must be materialized in the bound workspace");return}if(this.active){this.failEvent(e,"concurrent prompt rejected");return}this.runInboundEvent(e)}deliverStopEvent(e,t){this.active&&e===this.active.inbound.event_id&&(t&&t!==this.active.inbound.session_id||this.cancelActive("user canceled"))}async handleLocalAction(e){if(!["set_model","set_mode","set_provider","set_preset","set_profile","create_profile","get_session_usage","get_rate_limits","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals","exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type))return{handled:!1,kind:""};const t=await this.actionCoordinator.run(e.action_id,()=>this.executeLocalAction(e));return this.callbacks.sendLocalActionResult(e.action_id,t.status,t.result,t.errorCode,t.errorMsg),{handled:!0,kind:e.action_type}}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.isAlive()&&(!this.runtime||this.runtime.isConnected())}getStatus(){return{alive:this.isAlive()&&!!this.runtime,busy:!!this.active||this.intentionalRuntimeStop||!!this.rebuildPromise||!!this.runtimeStartPromise,backgroundBusy:!1,sessions:this.runtime?1:0,details:{runtimeGeneration:this.runtimeGeneration,runtimeSessionId:this.runtimeSessionId||void 0}}}getActiveEventIds(){return this.active?[this.active.inbound.event_id]:[]}takeAuditBoundary(e){const t=this.auditBoundaries.get(e);return this.auditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.active=null,this.correlator=null,this.clearTimeout()}getMcpConfig(){return null}async hasBackgroundWork(){return this.runtime?.hasBackgroundWork()??!1}onAgentProfileChanged(){this.profileRevision+=1,this.personaDirty=!0,!this.active&&this.runtime&&this.rebuildRuntime("persona_changed")}updateProviderQuotaSnapshot(e){this.providerQuota=e??null,this.pushToolbarMeta()}async probe(e={}){const t=this.resolveIntegrationMode(),i=t==="embedded_jsonrpc"?this.config.command||"dsh-jsonrpc-agent":"dsh",s=await de(i),o=!!s;let d={ok:e.conversation!==!0,latency:null};if(o&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const l=await Me({command:s,args:this.config.args,cordisPath:U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});d={ok:!0,latency:l.latencyMs,serverName:l.serverName,serverVersion:l.serverVersion}}catch(l){d={ok:!1,latency:null,error:this.redactError(l)}}else{const l=Date.now();try{const a=new R({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),p=await ye({installer:a,autoStart:!1}),c=A(p);if(c)throw c;const n=Ie(p.identity);if(n.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${p.identity.profileName}"`),{code:"bridge_missing"});d={ok:!0,latency:Date.now()-l,serverName:"grix-dsh-profile-bridge",serverVersion:n[0].bridgeVersion}}catch(a){d={ok:!1,latency:null,error:this.redactError(a)}}}return{cli:{command:i,installed:o,path:s,version:null,...o?{}:{error:{code:"cli_not_found",message:`${i} not found`}}},conversation:{attempted:e.conversation===!0,ok:d.ok,latency_ms:d.latency,...d.ok?{}:{error:{code:"conversation_failed",message:d.error??"initialize/shutdown probe failed"}}},config:{model:this.resolveDesiredSettings().modelId,base_url:this.config.env?.DEEPSEEK_BASE_URL??null,source:{model:"config",base_url:this.config.env?.DEEPSEEK_BASE_URL?"env":"unknown"},extras:{protocol:t==="profile_bridge"?"grix-dsh/1":"jsonrpc-v1",profile:this.resolveSelectedProfile(),serverName:d.serverName,serverVersion:d.serverVersion}},process:{started:!!this.runtime,alive:this.runtime?.isConnected()??!1,busy:!!this.active}}}async runInboundEvent(e){const t={inbound:e,admitted:!1,claimed:!1,turnEnded:!1,rootIdle:!1,text:"",sentText:"",seq:0,startedAt:Date.now()};this.active=t,this.correlator=new Qe(t),this.activeUsage=te(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{if(await this.ensureRuntimeWithRetry(),this.cancelRequested||this.active!==t)return;this.activeWireStart=this.capture?.offset??0;const i=V(e,this.injectedMessageIds);this.startTimeout(e.timeoutMs);const s=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:i.text}]});if(!s?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(s.messageId)}catch(i){const s=this.redactError(i,e.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":s)}}async ensureRuntime(){if(this.stopped)throw new Error("adapter stopped");if(this.runtime)return;this.syncGrixProvider();const t=this.options.bindingStore.get(this.options.aibotSessionId)?.cwd;if(!t)throw Object.assign(new Error("Session binding missing. Open a workspace first."),{code:"binding_missing"});this.projectConnectorSkills();let i=this.resolveDesiredSettings();const s=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),o={};s?.modelId||(o.modelId=i.modelId),!s?.providerId&&i.providerId&&(o.providerId=i.providerId),(o.modelId||o.providerId)&&(this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,o),await this.options.bindingStore.flush(),i=this.resolveDesiredSettings());const d=this.callbacks.getAgentProfile(),l=this.profileRevision,a=Ee({...d,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),p=Re(a);this.runtimeGeneration+=1;const c=this.resolveIntegrationMode(),n=this.resolveSelectedProfile();if(c==="profile_bridge")try{await this.ensureProfileReadyForChat(),this.pushToolbarMeta()}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),g}let r=c==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,n):void 0;c==="profile_bridge"&&!r&&(r={profileName:n,sessionId:it(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r),await this.options.bindingStore.flush()),this.runtimeSessionId=r?.sessionId??tt(this.options.aibotSessionId,this.runtimeGeneration);const u=this.profileDataDir(n),v=U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),$=_e({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:n,pluginIds:i.pluginIds??[],overlayId:D("sha256").update(this.options.aibotSessionId).digest("hex").slice(0,24),baseCordisPath:v}),se=T(u,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new le(se);const _=c==="embedded_jsonrpc"?new ge({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:$.embeddedCordisPath??v,home:u,sessionRoot:T(u,"sessions"),env:this.config.env,systemPrompt:a,settings:i,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new me({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:n,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:r?.sessionCreated===!0,lastAckCursor:r?.eventCursor??0,systemPrompt:a,settings:i,pluginOverlayPath:$.bridgeOverlayPath,managedProvider:i.providerId===b?X(this.options.provider??{}):void 0,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:g=>this.handleBridgeApproval(g),onToolInvoke:(g,w,k)=>this.invokeGrixTool(g,w,k),onCursorAck:g=>{!r||g<=r.eventCursor||(r={...r,eventCursor:g},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r))}});this.runtime=_,this.bridgeAckCursor=r?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const g=await _.start();if(!_.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});_.client?.on("notification",(S,I)=>this.onNotification(S,I)),_.client?.on("protocolError",S=>this.onProtocolError(S)),_.onExit(()=>this.onRuntimeExit()),_.client?.activateNotifications?.();let w=!1;if(c==="profile_bridge"){const S=Le(g.providers),I=$e({requestedProviderId:i.providerId,liveProviders:S,liveSelectedProvider:String(g.selectedProvider??"")});this.providers=Ve(S,I.providerId,this.providers),i={...i,providerId:I.providerId},w=I.persistFallback;const x=I.providerId,q=Object.prototype.hasOwnProperty.call(g,"models")?g.models:void 0,F=!!this.catalogProviderId&&!!x&&x!==this.catalogProviderId;this.models=He({current:this.models,fetched:q,providerChanged:F}),(q!==void 0||F)&&(this.catalogProviderId=x||this.catalogProviderId);const C=String(g.selectedModel??"");C&&C!==i.modelId&&(i={...i,modelId:C});const N=je(g.presets);N.length>0&&(this.presets=N);const y=String(g.selectedPreset??"");y&&y!==i.agentPreset&&(i={...i,agentPreset:y},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,y))}const k=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),B=(k?.revision??0)!==i.revision,P={};!B&&w&&(k?.providerId??"")!==(i.providerId??"")&&(P.providerId=i.providerId),!B&&(k?.modelId??"")!==i.modelId&&(P.modelId=i.modelId),(P.providerId||P.modelId)&&(i.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,P)??i.revision,await this.options.bindingStore.flush(),m.warn(f,`replaced unavailable persisted DSH catalog selection provider=${i.providerId} model=${i.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:i.revision,providerId:i.providerId??H,modelId:i.modelId,modeId:i.modeId},this.runtimeReadiness="ready",this.bridgeCapabilities=g.capabilities??null,c==="profile_bridge"&&r&&!r.sessionCreated&&(r={...r,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===i.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=l,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,m.info(f,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${p.schemaVersion} prompt_sha256=${p.sha256} prompt_length=${p.length}`),await this.persistCatalogCache(i.providerId??H),this.pushToolbarMeta(),this.settingsState==="pending"&&!this.active&&!this.stopped&&this.rebuildRuntime("settings_changed_during_start")}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),g}}ensureRuntimeWithRetry(){if(this.runtimeStartPromise)return this.runtimeStartPromise;const e=this.ensureRuntimeWithRetryLoop();this.runtimeStartPromise=e;const t=()=>{this.runtimeStartPromise===e&&(this.runtimeStartPromise=null)};return e.then(t,t),e}async ensureRuntimeWithRetryLoop(){let e;for(let t=1;t<=G;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||!De(s)||t===G)throw i;m.warn(f,`runtime ensure retry attempt=${t} code=${s||"unknown"}`),this.settingsState="pending",this.settingsErrorCode=s||"runtime_initialize_failed",this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),await this.stopRuntime(!0),await et(Ce(t))}throw e}onNotification(e,t){const i=Ze(t);if(e==="session.event"){const s=pe(t);if(!s){this.onProtocolError(new Error("malformed session.event"));return}const o=this.onSessionEvent(s);this.advanceBridgeAck(i,o);return}if(e==="session.status"){const s=t&&typeof t=="object"?t:{};if(String(s.sessionId??"")===this.runtimeSessionId){this.touchActivity(),this.correlator?.markRootStatus(String(s.status??"")),s.status==="idle"&&this.active&&this.correlator&&m.debug(f,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const d=!!this.correlator?.complete;d&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,d)}else i>0&&this.advanceBridgeAck(i,!1);return}if(e==="subagent.started"||e==="subagent.finished"){this.touchActivity(3);const s=t&&typeof t=="object"?t:{},o=String(s.childSessionId??s.sessionId??"");o&&this.capture?.addChild(o),this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:s},e==="subagent.started"?"[subagent started]":"[subagent finished]"),this.advanceBridgeAck(i,!1);return}this.onProtocolError(new Error(`unknown required JSON-RPC notification: ${e}`))}onSessionEvent(e){if(!this.active||!this.correlator)return!1;this.touchActivity(e.type==="tool/call"||e.type==="tool/result"?3:1);const t=ue(e);if(t.kind==="unknown"&&!rt(e)&&e.ignorable!==!0)return this.onProtocolError(new Error(`unknown required SessionEvent: ${e.type}`)),!1;if(e.sessionId&&e.sessionId!==this.runtimeSessionId)return!1;const i=this.correlator.accept(e);if((e.type==="agent/inbox/spliced"||e.type==="user/message"||e.type==="turn/end")&&m.debug(f,`turn correlation event=${e.type} belongs=${i} admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded}`),e.type==="agent/inbox/spliced"&&this.active.admitted){const s=V(this.active.inbound,this.injectedMessageIds);for(const o of s.contextIds)this.injectedMessageIds.add(o);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?st(e)?(this.flushPendingTextAsThinking(),!1):t.kind==="text"?(t.payload?.committed===!0?(t.payload?.hasToolCall===!0?this.applyCommittedToolStepText(t.text??""):this.applyCommittedText(t.text??""),t.usage&&this.collectCommittedUsage(t.usage,Number(e.seq??e.step??Date.now()))):this.applyTextDelta(t.text??""),!1):t.kind==="thinking"?(this.thinkingEnabled()&&this.callbacks.sendThinking(this.active.inbound.event_id,this.active.inbound.session_id,t.text??""),!1):t.kind==="tool_call"?(this.flushPendingTextAsThinking(),this.toolEventsEnabled()&&this.sendRaw("tool_call",{call_id:t.callId,tool_name:t.name,tool_input:t.input},`[tool] ${t.name}`),!1):t.kind==="tool_result"?(this.toolEventsEnabled()&&this.sendRaw("tool_result",{call_id:t.callId,result:t.output},`[tool result] ${t.callId??""}`),!1):t.kind==="todo"||t.kind==="compaction"?!1:t.kind==="context"?(this.updateContextCapacity(t.payload),!1):t.kind==="usage"?(this.updateContextWindow(t.usage),!1):t.kind==="turn_end"&&this.correlator.complete?(this.finishFromTurnOutcome(),!0):!1:!1}applyTextDelta(e){this.active.pendingText=`${this.active.pendingText??""}${e}`}applyCommittedText(e){const t=this.active;if(t.pendingText=void 0,e.startsWith(t.text))t.text=e;else if(!t.text.startsWith(e)){m.warn(f,`committed assistant text diverged event=${t.inbound.event_id}`);const i=W(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}flushPendingTextAsThinking(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,this.thinkingEnabled()&&t.trim()&&this.callbacks.sendThinking(e.inbound.event_id,e.inbound.session_id,t),e.lastThinkingText=t)}applyCommittedToolStepText(e){const t=this.active;t&&(t.pendingText=void 0,e.trim()&&t.lastThinkingText!==e&&this.thinkingEnabled()&&(this.callbacks.sendThinking(t.inbound.event_id,t.inbound.session_id,e),t.lastThinkingText=e))}promotePendingTextToVisible(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,e.text+=t)}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=W(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const o=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),d=ce(o,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(d.suppressedToolCalls);const l=d.visible;this.observeVisibleTextAfterToolCall(l);let a="";l.startsWith(i.sentText)?a=l.slice(i.sentText.length):(e||t.finalizeDsml)&&(a=l),!(!a&&!e)&&(i.seq+=1,this.callbacks.sendStreamChunk(i.inbound.event_id,i.inbound.session_id,a,i.seq,e,`${i.inbound.event_id}-dsh`,this.quotedMessageId),i.sentText=l)}surfaceSuppressedDsmlToolCalls(e){if(!this.active||e.length===0)return;const t=this.active.dsmlSuppressedKeys??new Set;this.active.dsmlSuppressedKeys=t;for(const i of e){const s=he(i);if(t.has(s)||(t.add(s),this.markToolCallAwaitingFinalText(),m.warn(f,`suppressed leaked DSML tool markup name=${i.name} event=${this.active.inbound.event_id}`),!this.toolEventsEnabled()))continue;let o=i.arguments;try{o=JSON.parse(i.arguments)}catch{}this.sendRaw("tool_call",{call_id:`dsml-${t.size}`,tool_name:i.name,tool_input:o,source:"dsml_text_leak",executed:!1},`[tool] ${i.name}`)}}markToolCallAwaitingFinalText(){const e=this.active;e&&(e.toolCallAwaitingFinalText=!0,e.toolCallVisibleTextLength=e.sentText.length)}observeVisibleTextAfterToolCall(e){const t=this.active;if(!t?.toolCallAwaitingFinalText)return;const i=t.toolCallVisibleTextLength??t.sentText.length;e.slice(i).trim().length!==0&&(t.toolCallAwaitingFinalText=!1,t.toolCallVisibleTextLength=void 0)}collectCommittedUsage(e,t){if(this.activeCommittedUsageSeqs.has(t))return;this.activeCommittedUsageSeqs.add(t);const i=K(e);this.activeUsage.inputTokens+=i.inputTokens,this.activeUsage.outputTokens+=i.outputTokens,this.activeUsage.cacheReadInputTokens+=i.cacheReadInputTokens,this.activeUsage.cacheCreationInputTokens+=i.cacheCreationInputTokens,this.activeUsage.reasoningTokens+=i.reasoningTokens,this.activeUsageSeq=Math.max(this.activeUsageSeq,t),this.updateContextWindow(i)}updateContextWindow(e){const t=K(e),i=this.resolveDesiredSettings(),s=this.models.find(d=>d.id===i.modelId),o=this.reportedContextCapacity??s?.contextWindow;if(o&&o>0){const d=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:d,totalTokens:o,remainingTokens:Math.max(0,o-d),usedPercentage:d/o*100,remainingPercentage:Math.max(0,100-d/o*100)},this.pushToolbarMeta()}}updateContextCapacity(e){const t=Number(e?.contextWindow);if(!Number.isFinite(t)||t<=0)return;this.reportedContextCapacity=t;const i=this.contextWindow&&typeof this.contextWindow=="object"?this.contextWindow:{},s=Math.max(0,Number(i.usedTokens)||0);this.contextWindow={usedTokens:s,totalTokens:t,remainingTokens:Math.max(0,t-s),usedPercentage:s/t*100,remainingPercentage:Math.max(0,100-s/t*100)},this.pushToolbarMeta()}finishFromTurnOutcome(){if(!this.active)return;this.finishingTurn=!0;const e=this.active.outcome??"completed",t=this.active.outcomeDetail?.trim();e==="completed"?this.finishActive("responded"):e==="aborted"?this.finishActive("canceled"):e==="max-tokens"&&this.active.sentText?this.finishActive("responded","Response truncated at model token limit"):this.finishActive("failed",t?t.toLowerCase().includes(e.toLowerCase())?`Harness turn ended: ${t}`:`Harness turn ended: ${e}: ${t}`:`Harness turn ended: ${e}`)}finishActive(e,t){const i=this.active;if(!i)return;let s=e,o=t;this.finishingTurn=!0,this.clearTimeout(),this.promotePendingTextToVisible(),this.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&(s="failed",o="DeepSeek Harness ended after a tool call without returning final assistant text",m.warn(f,`${o} event=${i.inbound.event_id}`)),i.text=i.sentText;const d=s==="failed"&&!!o?.trim();d&&(i.text+=`
2
2
 
3
3
  Error: ${o}`,this.flushVisibleText(!1,{finalizeDsml:!0})),s==="responded"&&this.activeUsageSeq>=0&&(this.usageStore().commit(i.inbound.session_id,this.runtimeSessionId,this.activeUsageSeq,this.applied?.modelId??this.resolveDesiredSettings().modelId,this.activeUsage),this.usageStore().flush()),i.inbound.audit?.enabled&&this.capture&&this.auditBoundaries.set(i.inbound.event_id,this.capture.boundary({runtimeSessionId:this.runtimeSessionId,rootSessionId:this.runtimeSessionId,startOffset:this.activeWireStart,turn:i.turn,messageId:i.messageId}));const l=this.personaDirty&&!!this.runtime,a=!!this.runtime&&!!this.applied&&this.applied.appliedRevision!==this.resolveDesiredSettings().revision;l&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const p=`${i.inbound.event_id}-dsh`,c=(n,r,u=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,n,r,u),this.emit("eventDone",i.inbound.event_id),l?this.rebuildRuntime("persona_changed"):a&&this.rebuildRuntime("settings_changed")};this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,p).then(async()=>{await this.flushPendingFinalBridgeAck(!0),c(s,o,d)},async n=>{await this.flushPendingFinalBridgeAck(!1),c(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(n,i.inbound.content)}`:o)})}advanceBridgeAck(e,t){if(!(e<=0)){if(t||this.finishingTurn||this.pendingFinalBridgeAck!==null){this.pendingFinalBridgeAck=Math.max(this.pendingFinalBridgeAck??0,e);return}this.ackBridgeCursor(e)}}async flushPendingFinalBridgeAck(e){const t=this.pendingFinalBridgeAck;this.pendingFinalBridgeAck=null,this.finishingTurn=!1,!(!e||t===null)&&await this.ackBridgeCursor(t)}async ackBridgeCursor(e){if(e<=this.bridgeAckCursor)return;const t=this.runtime?.client?.ack;if(!t){this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e);return}try{await t.call(this.runtime.client,e),this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e)}catch(i){this.onProtocolError(i instanceof Error?i:new Error(String(i)))}}async cancelActive(e){this.active&&(this.cancelRequested=!0,this.clearPendingApprovals("cancelled"),this.resolveIntegrationMode()==="embedded_jsonrpc"?(this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.pushToolbarMeta(),this.runtimeStartPromise&&this.runtime&&await this.runtime.terminate().catch(()=>{}),await this.runtimeStartPromise?.catch(()=>{}),await this.stopRuntime(!0)):(await this.runtimeStartPromise?.catch(()=>{}),await this.runtime?.cancel(this.runtimeSessionId).catch(()=>{}),this.runtime&&!this.runtime.isConnected()&&await this.stopRuntime(!0)),this.finishActive("canceled",e))}async handleBridgeApproval(e){const t=this.permissionHandler,i=String(e.interactionId??e.callId??M());if(t)try{return await t({adapterSessionId:this.options.aibotSessionId,requestId:i,description:String(e.reason??`Allow ${String(e.toolName??"operation")}?`),options:[{id:"allow_once",label:"Allow once",isAllow:!0},{id:"reject",label:"Reject",isAllow:!1}]})==="allow_once"?"allowed-once":"rejected"}catch{return"cancelled"}const s=this.active;return s?(this.callbacks.sendPermissionCard({eventId:s.inbound.event_id,sessionId:s.inbound.session_id,approvalId:i,toolName:String(e.toolName??"operation"),toolTitle:String(e.reason??`Allow ${String(e.toolName??"operation")}?`)}),new Promise(o=>{const d=setTimeout(()=>{this.pendingApprovals.delete(i),o("unavailable")},3e5);d.unref?.(),this.pendingApprovals.set(i,{resolve:o,timer:d})})):"unavailable"}async invokeGrixTool(e,t,i){if(!Je(e))throw Object.assign(new Error(`grix tool "${e}" is not exposed to DSH`),{code:"capability_unavailable"});if(!this.callbacks.agentInvoke)throw Object.assign(new Error(`grix tool "${e}" has no connector-side action runner`),{code:"capability_unavailable"});const s=Xe(e,t);return this.callbacks.agentInvoke(s.action,s.params,i??s.timeoutMs)}projectConnectorSkills(){const e=Te(this.options.dshHome??this.config.env?.DSH_HOME,{...process.env,...this.config.env}),t=T(e,"skills"),i=ae(t);i.length>0&&m.info(f,`Synced connector skills to ${t}: [${i.join(", ")}]`)}rebuildRuntime(e){if(this.stopped||this.active)return Promise.resolve();if(this.rebuildPromise)return this.rebuildPromise;const t=(async()=>{this.emit("pauseIntake","barrier"),this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="pending",this.pushToolbarMeta();try{await this.stopRuntime(!0),await this.ensureRuntime()}catch(i){m.warn(f,`${e} rebuild failed: ${this.redactError(i)}`)}finally{this.emit("resumeIntake","barrier")}})();return this.rebuildPromise=t.finally(()=>{this.rebuildPromise=null;const i=this.resolveDesiredSettings().revision;!this.stopped&&!this.active&&(this.personaDirty||this.applied&&this.applied.appliedRevision!==i)&&this.rebuildRuntime("coalesced_state_changed")}),this.rebuildPromise}async stopRuntime(e){const t=this.runtime;t&&(this.intentionalRuntimeStop=e,this.runtime=null,await t.shutdown().catch(()=>t.terminate()),this.capture?.close(),this.capture=null,this.intentionalRuntimeStop=!1)}onRuntimeExit(){this.intentionalRuntimeStop||this.stopped||(this.runtime=null,this.capture?.close(),this.capture=null,this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="runtime_exited",this.pushToolbarMeta(),this.active&&this.finishActive("failed","Harness runtime exited; prompt was not replayed"),this.emit("exit",1))}onProtocolError(e){if(this.stopped||!this.runtime&&!this.active)return;const t=this.redactError(e,this.active?.inbound.content);this.clearPendingApprovals("unavailable"),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="protocol_error",this.pushToolbarMeta();const i=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,i?.client?.close(e),this.active&&this.finishActive("failed",`Harness protocol error: ${t}`),i?.terminate().finally(()=>{this.intentionalRuntimeStop=!1}),this.emit("exit",1)}async executeLocalAction(e){const t=e.params??{},i=String(t.session_id??"");if(!i||i!==this.options.aibotSessionId)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing"};if(["exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type)){const n=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),r=this.pendingApprovals.get(n);if(!r)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(r.timer),this.pendingApprovals.delete(n);const u=e.action_type==="exec_approve"||e.action_type==="permission_approve";return r.resolve(u?"allowed-once":"rejected"),{status:"ok",result:{approval_id:n,decision:u?"allow-once":"deny"}}}if(e.action_type==="get_session_usage")return{status:"ok",result:{adapterType:"deepseek-harness",available:!0,dsh_profile:this.resolveSelectedProfile(),...this.usageStore().get(i)}};if(e.action_type==="get_rate_limits"){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(!0)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch(n){this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:this.redactError(n)}}return this.pushToolbarMeta(),{status:"ok",result:{sampledAt:new Date().toISOString(),contextWindow:this.contextWindow,providerQuota:this.providerQuota}}}if(e.action_type==="dsh_bridge_status"||e.action_type==="dsh_install_bridge"){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"Bridge management requires Profile Bridge mode"};if(this.active||this.runtime)return{status:"failed",errorCode:"worker_busy",errorMsg:"Stop the active DSH session before changing its Profile plugin"};try{const n=new R({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),r=e.action_type==="dsh_install_bridge"?await n.install():await n.status();return this.runtimeReadiness=r.readiness,this.settingsErrorCode=r.readiness==="ready"?null:r.readiness,this.pushToolbarMeta(),{status:"ok",result:ot(r)}}catch(n){const r=String(n?.code??"bridge_install_failed");return this.runtimeReadiness=r,this.settingsErrorCode=r,this.pushToolbarMeta(),{status:"failed",errorCode:r,errorMsg:this.redactError(n)}}}if(e.action_type==="dsh_list_plugins"||e.action_type==="dsh_refresh_plugins"||e.action_type==="dsh_enable_plugin"||e.action_type==="dsh_disable_plugin")return this.executePluginAction(e.action_type,t,i);const o={dsh_list_skills:"skills/list",dsh_list_mcp:"mcp/list",dsh_list_tools:"tools/list",dsh_list_jobs:"jobs/list",dsh_list_goals:"goals/list"}[e.action_type];if(o){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"DSH resources require Profile Bridge mode"};if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot query DSH resources during an active turn"};try{return await this.ensureRuntimeWithRetry(),{status:"ok",result:await this.runtime?.client?.call(o,{cwd:this.options.bindingStore.get(i)?.cwd})}}catch(n){const r=String(n?.code??"resource_query_failed");return{status:r==="capability_unavailable"?"unsupported":"failed",errorCode:r,errorMsg:this.redactError(n)}}}if(e.action_type==="set_profile"||e.action_type==="create_profile"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness Profile during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};let n;try{n=Se(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(u){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(u)}}if(this.options.bindingStore.isDshProfileLocked(i)){const u=this.resolveSelectedProfile();return e.action_type==="create_profile"||u!==n?{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:this.finishProfileSelection(n,!1)}if(e.action_type==="create_profile")try{const u=this.options.createDshProfile?await this.options.createDshProfile(n):await fe({profileName:n,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),v=u.identity?.profileName??n;return this.persistSelectedProfile(v)?(await this.flushSelectedProfile(),this.finishProfileSelection(v,u.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(u){return{status:"failed",errorCode:String(u?.code??"profile_create_failed"),errorMsg:this.redactError(u)}}return this.listProfiles().some(u=>u.id===n)?this.persistSelectedProfile(n)?(await this.flushSelectedProfile(),this.finishProfileSelection(n,!1)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:{status:"failed",errorCode:"profile_not_found",errorMsg:"Requested DSH profile is not in the local catalog"}}if(e.action_type==="set_preset"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const r=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(v=>v.id===r))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const u=Q(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?u===r?{status:"ok",result:this.presetActionResult(r,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:u===r?(this.options.bindingStore.setDshAgentPreset(i,r),await this.persistGlobalToolbarDefaults({dshAgentPreset:r}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(r,!1)}):this.options.bindingStore.setDshAgentPreset(i,r)?(await this.persistGlobalToolbarDefaults({dshAgentPreset:r}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(r,!1)}):{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}}if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const l=this.resolveDesiredSettings();let a;if(e.action_type==="set_provider"){const n=String(t.provider_id??"").trim();if(!this.providers.some(r=>r.id===n))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};a={providerId:n},n!==l.providerId&&(this.models=We(this.options.dataRoot,n),this.catalogProviderId=n,this.models.some(r=>r.id===l.modelId)||(a.modelId=this.models[0]?.id))}else if(e.action_type==="set_model"){const n=String(t.model_id??"").trim();if(!this.models.some(r=>r.id===n))return{status:"failed",errorCode:"model_not_found",errorMsg:"Requested model is not in the Harness catalog"};a={modelId:n}}else{const n=String(t.mode_id??"").trim();if(n!=="approval"&&n!=="full_auto")return{status:"failed",errorCode:"mode_invalid",errorMsg:"mode_id must be approval or full_auto"};a={modeId:n}}if((a.providerId===void 0||a.providerId===l.providerId)&&(a.modelId===void 0||a.modelId===l.modelId)&&(a.modeId===void 0||a.modeId===l.modeId)&&this.applied?.appliedRevision===l.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,a,l.revision,"already_applied",!0)};const c=this.options.bindingStore.updateDshSettings(i,a)??l.revision;if(await this.options.bindingStore.flush(),(a.providerId||a.modelId||a.modeId)&&await this.persistGlobalToolbarDefaults({...a.providerId?{dshProviderId:a.providerId}:{},...a.modelId?{dshModelId:a.modelId}:{},...a.modeId?{dshModeId:a.modeId}:{}}),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsErrorCode=null,this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"applied",!1)};if(this.active)return this.applied&&this.applied.appliedRevision>=c?(this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"applied",!0)}):(this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"pending",!0)});this.settingsState="pending",this.pushToolbarMeta();try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<c)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"applied",!0)}}catch(n){return{status:"failed",result:this.settingsActionResult(e.action_type,a,c,"failed",!1,this.redactError(n)),errorCode:"settings_apply_failed",errorMsg:this.redactError(n)}}}async finishProfileSelection(e,t){if(this.resolveIntegrationMode()==="profile_bridge")try{await this.prepareSelectedProfile()}catch(i){const s=String(i?.code??"profile_start_failed");return this.runtimeReadiness=s,this.settingsErrorCode=s,this.pushToolbarMeta(),{status:"failed",errorCode:s,errorMsg:this.redactError(i)}}return this.pushToolbarMeta(),{status:"ok",result:this.profileActionResult(e,t)}}createBridgeInstaller(){const e=this.options.bridgeInstallerOptions??{};return new R({command:e.command??"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),...e.tarballPath?{tarballPath:e.tarballPath}:{}})}async healBridgeUpdate(e){return e.readiness!=="bridge_update_required"||this.options.autoInstallBridge===!1?e:(m.info(f,`auto-updating stale Bridge profile=${e.identity.profileName} installed=${e.installedBridgeVersion??"none"} bundled=${e.bundledBridgeVersion}`),await this.prepareSelectedProfile(),this.attachSelectedProfile())}async ensureProfileReadyForChat(){if(!(this.options.autoInstallBridge!==!1||this.options.autoStartProfile!==!1)){const s=await this.attachSelectedProfile(),o=A(s);if(o)throw o;return}this.settingsState="pending",this.pushToolbarMeta(),await this.prepareSelectedProfile();let t=await this.attachSelectedProfile();t.readiness==="bridge_update_required"&&(t=await this.healBridgeUpdate(t));const i=A(t);if(i)throw i}async attachSelectedProfile(){const t=await this.createBridgeInstaller().status();return this.runtimeReadiness=t.readiness,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness,t}async prepareSelectedProfile(){const e=this.createBridgeInstaller(),t=await xe({installer:e,autoInstall:this.options.autoInstallBridge!==!1,autoStart:this.options.autoStartProfile!==!1});this.runtimeReadiness=t.readiness,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness}profileActionResult(e,t){return{outcome:t?"profile_created":"profile_set",profile_id:e,dsh_profile:e,created:t,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),available_profiles:this.listProfiles(),session_context:{dsh_profile:e,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId)}}}persistSelectedProfile(e){return this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,e)?(this.options.globalConfigStore?.set(this.options.agentName,{dshProfile:e}),!0):!1}async persistGlobalToolbarDefaults(e){this.options.globalConfigStore&&Object.values(e).some(t=>t!==void 0)&&(this.options.globalConfigStore.set(this.options.agentName,e),await this.options.globalConfigStore.flush())}seedSessionToolbarFromGlobal(){const e=this.options.aibotSessionId,t=this.options.bindingStore.get(e);if(!t?.cwd)return;const i=this.resolveDesiredSettings(),s={};t.dshProviderId||(s.providerId=i.providerId),t.dshModelId||(s.modelId=i.modelId),t.dshModeId||(s.modeId=i.modeId),Object.keys(s).length>0&&this.options.bindingStore.updateDshSettings(e,s),!this.options.bindingStore.getDshAgentPreset(e)&&i.agentPreset&&this.options.bindingStore.setDshAgentPreset(e,i.agentPreset),this.options.bindingStore.getDshSelectedProfile(e)||this.options.bindingStore.setDshSelectedProfile(e,this.resolveSelectedProfile())}async flushSelectedProfile(){await this.options.bindingStore.flush(),await this.options.globalConfigStore?.flush()}listProfiles(){return ke({dshHome:this.options.dshHome??this.config.env?.DSH_HOME})}pluginCommandContext(){return{dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),enabledPluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId)}}currentPlugins(){try{return E(this.pluginCommandContext())}catch{return[]}}pluginRestartRequired(){return!1}async executePluginAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek plugins during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const s=this.pluginCommandContext();try{if(e==="dsh_list_plugins"||e==="dsh_refresh_plugins"){const n=E(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(n,!1)}}const o=String(t.name??t.plugin_name??"").trim(),d=this.options.bindingStore.getDshEnabledPlugins(i);let l=o;try{const{plugin:n}=ve({...s,name:o});l=n.name}catch(n){const r=String(n?.code??"");if(e!=="dsh_disable_plugin"||r!=="plugin_not_found"||!d.includes(o))throw n}const a=be(d,l,e==="dsh_enable_plugin"),p=this.options.bindingStore.setDshEnabledPlugins(i,a.pluginIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const c=E({...s,enabledPluginIds:a.pluginIds});if(!a.changed)return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!0,"skipped")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("plugin_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested plugin revision");return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!0,"restarted")}}catch(o){return{status:"failed",errorCode:String(o?.code??"plugin_action_failed"),errorMsg:this.redactError(o)}}}pluginActionResult(e,t,i="skipped"){const s=this.resolveSelectedProfile(),o=this.pluginRestartRequired();return{outcome:t?i==="restarted"?"plugin_applied":"plugin_updated":"plugin_unchanged",dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:o,restart:i,session_context:{dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:o}}}resolveSelectedProfile(){const e=this.options.bindingStore.getDshSelectedProfile(this.options.aibotSessionId),t=we({binding:e,global:this.options.globalConfigStore?.get(this.options.agentName)?.dshProfile,adapter:this.options.dshProfile});return this.options.bindingStore.get(this.options.aibotSessionId)&&e!==t&&this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,t),t}profileDataDir(e=this.resolveSelectedProfile()){return Pe(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=T(this.profileDataDir(e),"session-usage.json"),i=T(this.options.dataRoot,"session-usage.json");return!L(t)&&L(i)&&(ne(re(t),{recursive:!0,mode:448}),oe(i,t)),Ke(t)}presetActionResult(e,t){const i=this.resolveDesiredSettings();return{outcome:"preset_set",agentPreset:e,agent_preset_id:e,agent_preset_locked:t,available_presets:[...this.presets],session_context:{agent_preset_id:i.agentPreset??e,agent_preset_locked:t}}}settingsActionResult(e,t,i,s,o,d){const l=this.resolveDesiredSettings(),a=l.revision||i,p={provider_id:l.providerId,model_id:l.modelId,mode_id:l.modeId,applied_provider_id:this.applied?.providerId??null,applied_model_id:this.applied?.modelId??null,applied_mode_id:this.applied?.modeId??null,applied_settings_revision:this.applied?.appliedRevision??null,settings_state:this.settingsState,settings_revision:a};return e==="set_mode"&&(p.sandbox_mode=z(l.modeId),p.approval_policy=l.modeId==="full_auto"?"never":"ask"),{outcome:`${e==="set_provider"?"provider":e==="set_model"?"model":"mode"}_set${s==="pending"||s==="failed"?"_pending":""}`,...t.providerId?{providerId:t.providerId,provider_id:t.providerId}:{},...t.modelId?{modelId:t.modelId,model_id:t.modelId}:{},...t.modeId?{modeId:t.modeId,mode_id:t.modeId,sandbox_mode:z(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},settingsRevision:a,settings_revision:a,sessionAlive:o,available_providers:[...this.providers],available_models:[...this.models],session_context:p,...d?{error:d}:{}}}hydrateCatalogFromCache(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=Ge({dataRoot:this.options.dataRoot,providerId:e?.providerId??t?.dshProviderId});this.providers=i.providers,this.models=this.options.models?.length?this.options.models:i.models,this.catalogProviderId=i.providerId}async persistCatalogCache(e){try{await ze({dataRoot:this.options.dataRoot,providers:this.providers,providerId:e,models:this.models})}catch(t){m.warn(f,`failed to persist DSH catalog cache: ${t instanceof Error?t.message:String(t)}`)}}syncGrixProvider(){const e=X(this.options.provider??{});if(e){this.providers.some(o=>o.id===b)||(this.providers=[{id:b,displayName:e.displayName},...this.providers]);const t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId;(!s||s===H||s===b)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:b});return}this.providers=this.providers.filter(t=>t.id!==b)}resolveDesiredSettings(){const e=this.options.bindingStore.get(this.options.aibotSessionId),t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId,o=this.providers.some(p=>p.id===b)?b:void 0,d=Oe(s||o,this.providers),l=[t?.modelId,i?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(p=>!!p&&this.models.some(c=>c.id===p))??"deepseek-chat",a=Q(t?.agentPreset??i?.dshAgentPreset,this.presets);return{providerId:d,modelId:l,modeId:Ue(e?.dshModeId,i?.dshModeId),agentPreset:a,pluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId),maxTokens:t?.maxTokens??this.options.maxTokens??qe,revision:t?.revision??0}}resolveIntegrationMode(){return this.options.integrationMode?this.options.integrationMode:(this.config.command||"").includes("dsh-jsonrpc-agent")?"embedded_jsonrpc":"profile_bridge"}pushToolbarMeta(){const e=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",e?.cwd,Be({desired:this.resolveDesiredSettings(),applied:this.applied,models:this.models,providers:this.providers,presets:this.presets,agentPresetLocked:this.options.bindingStore.isDshAgentPresetLocked(this.options.aibotSessionId),state:this.settingsState,errorCode:this.settingsErrorCode,contextWindow:this.contextWindow,providerQuota:this.providerQuota,integrationMode:this.resolveIntegrationMode(),profileName:this.resolveSelectedProfile(),profiles:this.listProfiles(),profileLocked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),plugins:this.currentPlugins(),pluginRestartRequired:this.pluginRestartRequired(),runtimeReadiness:this.runtimeReadiness,bridgeCapabilities:this.bridgeCapabilities}))}async refreshProviderQuota(e){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(e)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch{this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}this.pushToolbarMeta()}clearPendingApprovals(e){for(const t of this.pendingApprovals.values())clearTimeout(t.timer),t.resolve(e);this.pendingApprovals.clear()}thinkingEnabled(){const e=this.active?.inbound.connector_runtime_config?.thinking_events??this.active?.inbound.connector_runtime_config?.thinkingEvents;return e!=="off"&&e!=="hidden"&&e!=="none"}toolEventsEnabled(){const e=this.active?.inbound.connector_runtime_config?.tool_events;return e!=="off"&&e!=="hidden"&&e!=="none"}sendRaw(e,t,i){this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:t},i)}failEvent(e,t){this.callbacks.sendEventResult(e.event_id,"failed",t),this.emit("eventDone",e.event_id)}startTimeout(e){this.activeTimeoutMs=e??this.options.promptTimeoutMs??J,this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()),this.armHardTimeout(this.activeTimeoutMs)}touchActivity(e=1){!this.active||!this.timeoutTimer||(this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()))}noteRuntimeActivity(){this.active&&(this.active.lastRuntimeActivityAt=Date.now(),this.active.livenessExtendStartAt=void 0)}activeIdleTimeoutMs(){const e=this.options.activeIdleTimeoutMs??Y,t=Number.isFinite(e)&&e>0?e:Y;return Math.min(t,this.activeTimeoutMs)}livenessFreshMs(){const e=this.options.livenessFreshMs??Z;return Number.isFinite(e)&&e>0?e:Z}livenessMaxExtendMs(){const e=this.options.livenessMaxExtendMs??ee;return Number.isFinite(e)&&e>0?e:ee}armTimeout(e){this.clearIdleTimeout(),this.timeoutTimer=setTimeout(()=>{this.handlePromptTimeout()},e),this.timeoutTimer.unref?.()}armHardTimeout(e){this.clearHardTimeout(),this.hardTimeoutTimer=setTimeout(()=>{this.handlePromptHardTimeout()},e),this.hardTimeoutTimer.unref?.()}async handlePromptTimeout(){const e=this.active;if(e){if(this.pendingApprovals.size>0){m.info(f,`Idle timeout skipped: pendingApprovals=${this.pendingApprovals.size} event=${e.inbound.event_id}`),this.armTimeout(this.activeIdleTimeoutMs());return}if(this.shouldExtendByLiveness(e.inbound.event_id)){this.armTimeout(this.activeIdleTimeoutMs());return}await this.failActiveTimeout("idle","Harness prompt idle timeout and the runtime was terminated")}}async handlePromptHardTimeout(){const e=this.active;if(e&&this.shouldExtendByLiveness(e.inbound.event_id)){this.armHardTimeout(this.activeTimeoutMs);return}await this.failActiveTimeout("hard","Harness prompt exceeded max duration and the runtime was terminated")}shouldExtendByLiveness(e){const t=this.active;if(!t||t.inbound.event_id!==e||!this.runtime?.isConnected()||!(!t.turnEnded&&(!!t.messageId||t.admitted||t.claimed)))return!1;const s=Date.now(),o=t.lastRuntimeActivityAt??t.startedAt,d=Math.max(0,s-o);if(d<this.livenessFreshMs())return t.livenessExtendStartAt=s,m.info(f,`Liveness check: recent DSH activity for ${e} (quietMs=${d}), extending`),!0;const l=t.livenessExtendStartAt??o;t.livenessExtendStartAt=l;const a=s-l;return a>this.livenessMaxExtendMs()?(m.warn(f,`Liveness extension budget exhausted for ${e} (quietMs=${d}, extendMs=${a}), allowing close`),!1):(m.info(f,`Liveness check: DSH turn still open for ${e} (claimed=${t.claimed}, turnEnded=${t.turnEnded}, quietMs=${d}), extending`),!0)}async failActiveTimeout(e,t){if(!this.active)return;const i=this.active;this.clearTimeout();const s=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.settingsErrorCode=null,this.pushToolbarMeta(),await s?.cancel(this.runtimeSessionId).catch(()=>{}),s&&!s.isConnected()&&await s.terminate().catch(()=>{}),this.intentionalRuntimeStop=!1,!(this.active!==i||this.stopped)&&(m.error(f,`Active DSH turn ${e} timeout: ${i.inbound.event_id}`),this.finishActive("failed",t),this.emit("exit",1))}clearTimeout(){this.clearIdleTimeout(),this.clearHardTimeout()}clearIdleTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=null}clearHardTimeout(){this.hardTimeoutTimer&&clearTimeout(this.hardTimeoutTimer),this.hardTimeoutTimer=null}redactError(e,t){let i=e instanceof Error?e.message:String(e);const s=this.config.env?.DEEPSEEK_API_KEY;return s&&(i=i.split(s).join("[REDACTED]")),i=i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]"),t&&t.length>=16&&i.includes(t)&&(i="Harness request failed (prompt echo redacted)"),(i.includes("[aibot-system-prompt]")||i.includes("[base-behavior]"))&&(i="Harness runtime failed (system prompt echo redacted)"),i.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"").slice(0,2e3)}}function Ze(h){const e=Number(h&&typeof h=="object"?h.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function et(h){return new Promise(e=>setTimeout(e,h))}function tt(h,e){return`grix-${D("sha256").update(h).digest("hex").slice(0,12)}-${e}-${M().slice(0,8)}`}function it(h){return`grix-${D("sha256").update(h).digest("hex").slice(0,16)}-${M().slice(0,8)}`}function te(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function ie(h){const e=h.data?.chunk&&typeof h.data.chunk=="object"?h.data.chunk:h.data;return String(e?.type??"")}function st(h){return h.type==="assistant/chunk:tool-call-delta"||h.type==="assistant/chunk"&&ie(h)==="tool-call-delta"}function ot(h){return{readiness:h.readiness,profile:h.identity.profileName,dshVersion:h.dshVersion,runningDshVersion:h.runningDshVersion,installedBridgeVersion:h.installedBridgeVersion,bundledBridgeVersion:h.bundledBridgeVersion,runningBridgeVersion:h.runningBridgeVersion,endpointCount:h.endpointCount,requiresProfileRestart:h.readiness==="profile_restart_required",compatibleDshVersions:h.compatibleDshVersions}}const nt=new Set(["turn/start","step/start","step/end","agent/inbox/spliced","user/message","request/header","session/title","session/title-llm-request","session/end-seed","web/deepseek-search-llm-request","assistant/chunk:tool-call-delta","permission/preset","sandbox/mode","approval/policy","approval/asked","approval/decided","plan/mode","agent-preset/selected","llm/retry","llm/retry-started","goal/change","schedule/change","feedback/record","hook/invoked","hook/result","command/run","command/done","subagent/descriptor","tool-workflow/agent-start","tool-workflow/agent-end","tool-workflow/run-start","tool-workflow/run-end","tool/code-dispatch","tool/code-dispatch-start"]);function rt(h){const e=ie(h);return nt.has(h.type)||h.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(e)}export{Ft as DshJsonRpcAdapter};
@@ -1 +1 @@
1
- import{createHash as N}from"node:crypto";import{existsSync as f,readFileSync as a,readdirSync as g,realpathSync as y,statSync as d}from"node:fs";import{homedir as H}from"node:os";import{basename as m,dirname as c,join as i,resolve as l}from"node:path";import{fileURLToPath as P}from"node:url";function u(e,r=process.env){const t=e?.trim()||r.DSH_HOME?.trim()||i(H(),".dsh");return l(t)}const s="web",S="headless";function h(e){return O(String(e??"").trim())}function E(e){const r=h(e);if(r===S)throw Object.assign(new Error("headless is a one-shot DSH profile and cannot be used as a Grix Profile"),{code:"profile_invalid"});return r}function G(e,r){return i(l(e),"profiles",h(r))}function J(e={}){for(const r of[e.binding,e.global,e.adapter]){const t=String(r??"").trim();if(t)try{return E(t)}catch{continue}}return s}function D(e){return e===s?"Web":e}function w(e,r){if(r===s)return!0;try{const n=JSON.parse(a(i(e,"package.json"),"utf8")).dsh?.profile?.bundles;return Array.isArray(n)&&n.some(o=>String(o).includes("dsh-web-app"))}catch{return!1}}function V(e={}){const r=u(e.dshHome,e.env),t=new Map;t.set(s,{id:s,displayName:D(s),webApp:!0});const n=i(r,"profiles");if(!f(n)||!d(n).isDirectory())return[...t.values()];for(const o of g(n).sort()){if(o===S||o===s||o==="node_modules")continue;try{h(o)}catch{continue}const p=i(n,o);try{if(!d(p).isDirectory()||!JSON.parse(a(i(p,"package.json"),"utf8")).dsh?.profile)continue}catch{continue}t.set(o,{id:o,displayName:D(o),webApp:w(p,o)})}return[...t.values()]}function _(e){const r=u(e.dshHome,e.env),t=h(e.profileName?.trim()||s),n=l(r,"profiles",t),o=f(n)?y(n):n;return{dshHome:r,profileName:t,profileRoot:o,profileKey:b(o)}}function b(e){return N("sha256").update(l(e)).digest("hex")}function R(e){return i(e.dshHome,"run","grix-dsh-bridge",e.profileKey)}function I(e){const r=R(e);if(!f(r)||!d(r).isDirectory())return[];const t=[];for(const n of g(r).filter(o=>o.endsWith(".json")).sort())try{const o=JSON.parse(a(i(r,n),"utf8"));if(!A(o)||o.profileKey!==e.profileKey||!M(o.pid)||!f(o.tokenPath)||!d(o.tokenPath).isFile())continue;t.push(o)}catch{}return t}function W(e){const r=I(e);if(r.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${e.profileName}". If Bridge is already installed, restart the profile (stop it, then: dsh --profile ${e.profileName}); otherwise install the Grix Bridge plugin first.`),{code:"bridge_missing"});if(r.length>1)throw Object.assign(new Error(`Multiple live Grix Bridge endpoints found for DSH profile "${e.profileName}". Stop extra profile processes so only one instance remains.`),{code:"profile_instance_ambiguous"});return r[0]}function $(e){let r=c(P(e)),t;for(;c(r)!==r;){const o=i(r,"package.json");if(f(o))try{if(JSON.parse(a(o,"utf8")).dsh?.profile)return x(r)}catch{}m(r)==="node_modules"&&(t=c(r)),r=c(r)}if(t)return x(t);const n=u();return _({dshHome:n,profileName:process.env.GRIX_DSH_PROFILE||s})}function x(e){const r=y(e),t=m(r),n=c(r);return{dshHome:m(n)==="profiles"?c(n):u(),profileName:t,profileRoot:r,profileKey:b(r)}}function O(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw Object.assign(new Error("Invalid DSH profile name"),{code:"profile_invalid"});return e}function A(e){return e.schemaVersion===1&&(e.transport==="unix"||e.transport==="pipe")&&typeof e.address=="string"&&e.address.length>0&&Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&typeof e.startedAt=="string"&&typeof e.profileKey=="string"&&typeof e.profileName=="string"&&typeof e.dshVersion=="string"&&typeof e.bridgeVersion=="string"&&Number.isSafeInteger(e.protocolMin)&&Number.isSafeInteger(e.protocolMax)&&typeof e.instanceId=="string"&&typeof e.tokenPath=="string"}function M(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}export{s as DEFAULT_DSH_PROFILE_NAME,S as DSH_HEADLESS_PROFILE_NAME,E as assertSelectableDshProfileName,R as bridgeDiscoveryDirectory,I as discoverDshBridgeEndpoints,D as dshProfileDisplayName,$ as inferProfileIdentityFromModule,V as listDshProfiles,h as parseDshProfileName,w as profileHasWebApp,b as profileKeyFor,G as resolveDshConnectorProfileDataDir,u as resolveDshHome,_ as resolveDshProfileIdentity,J as resolveDshSelectedProfileName,W as selectDshBridgeEndpoint};
1
+ import{createHash as H}from"node:crypto";import{existsSync as p,readFileSync as a,readdirSync as y,realpathSync as g,statSync as d}from"node:fs";import{homedir as P}from"node:os";import{basename as h,dirname as c,join as i,resolve as l}from"node:path";import{fileURLToPath as E}from"node:url";function u(e,r=process.env){const t=e?.trim()||r.DSH_HOME?.trim()||i(P(),".dsh");return l(t)}const s="web",D="headless";function m(e){return O(String(e??"").trim())}function A(e){const r=m(e);if(r===D)throw Object.assign(new Error("headless is a one-shot DSH profile and cannot be used as a Grix Profile"),{code:"profile_invalid"});return r}function J(e,r){return i(l(e),"profiles",m(r))}function C(e={}){for(const r of[e.binding,e.global,e.adapter]){const t=String(r??"").trim();if(t)try{return A(t)}catch{continue}}return s}function S(e){return e===s?"Web":e}function R(e,r){if(r===s)return!0;try{const n=JSON.parse(a(i(e,"package.json"),"utf8")).dsh?.profile?.bundles;return Array.isArray(n)&&n.some(o=>String(o).includes("dsh-web-app"))}catch{return!1}}function V(e={}){const r=u(e.dshHome,e.env),t=new Map;t.set(s,{id:s,displayName:S(s),webApp:!0});const n=i(r,"profiles");if(!p(n)||!d(n).isDirectory())return[...t.values()];for(const o of y(n).sort()){if(o===D||o===s||o==="node_modules")continue;try{m(o)}catch{continue}const f=i(n,o);try{if(!d(f).isDirectory()||!JSON.parse(a(i(f,"package.json"),"utf8")).dsh?.profile)continue}catch{continue}t.set(o,{id:o,displayName:S(o),webApp:R(f,o)})}return[...t.values()]}function w(e){const r=u(e.dshHome,e.env),t=m(e.profileName?.trim()||s),n=l(r,"profiles",t),o=p(n)?g(n):n;return{dshHome:r,profileName:t,profileRoot:o,profileKey:N(o)}}function N(e){return H("sha256").update(l(e)).digest("hex")}function I(e){return i(e.dshHome,"run","grix-dsh-bridge",e.profileKey)}function _(e){const r=I(e);if(!p(r)||!d(r).isDirectory())return[];const t=[];for(const n of y(r).filter(o=>o.endsWith(".json")).sort())try{const o=JSON.parse(a(i(r,n),"utf8"));if(!F(o)||o.profileKey!==e.profileKey||!M(o.pid)||!p(o.tokenPath)||!d(o.tokenPath).isFile())continue;t.push(o)}catch{}return t.sort((n,o)=>b(o)-b(n)||o.instanceId.localeCompare(n.instanceId))}function W(e){const r=_(e);if(r.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${e.profileName}". If Bridge is already installed, restart the profile (stop it, then: dsh --profile ${e.profileName}); otherwise install the Grix Bridge plugin first.`),{code:"bridge_missing"});return r[0]}function b(e){const r=Date.parse(e.startedAt);return Number.isFinite(r)?r:0}function T(e){let r=c(E(e)),t;for(;c(r)!==r;){const o=i(r,"package.json");if(p(o))try{if(JSON.parse(a(o,"utf8")).dsh?.profile)return x(r)}catch{}h(r)==="node_modules"&&(t=c(r)),r=c(r)}if(t)return x(t);const n=u();return w({dshHome:n,profileName:process.env.GRIX_DSH_PROFILE||s})}function x(e){const r=g(e),t=h(r),n=c(r);return{dshHome:h(n)==="profiles"?c(n):u(),profileName:t,profileRoot:r,profileKey:N(r)}}function O(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw Object.assign(new Error("Invalid DSH profile name"),{code:"profile_invalid"});return e}function F(e){return e.schemaVersion===1&&(e.transport==="unix"||e.transport==="pipe")&&typeof e.address=="string"&&e.address.length>0&&Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&typeof e.startedAt=="string"&&typeof e.profileKey=="string"&&typeof e.profileName=="string"&&typeof e.dshVersion=="string"&&typeof e.bridgeVersion=="string"&&Number.isSafeInteger(e.protocolMin)&&Number.isSafeInteger(e.protocolMax)&&typeof e.instanceId=="string"&&typeof e.tokenPath=="string"}function M(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}export{s as DEFAULT_DSH_PROFILE_NAME,D as DSH_HEADLESS_PROFILE_NAME,A as assertSelectableDshProfileName,I as bridgeDiscoveryDirectory,_ as discoverDshBridgeEndpoints,S as dshProfileDisplayName,T as inferProfileIdentityFromModule,V as listDshProfiles,m as parseDshProfileName,R as profileHasWebApp,N as profileKeyFor,J as resolveDshConnectorProfileDataDir,u as resolveDshHome,w as resolveDshProfileIdentity,C as resolveDshSelectedProfileName,W as selectDshBridgeEndpoint};
@@ -1,2 +1,2 @@
1
- import{createWriteStream as T,existsSync as k,mkdirSync as K,readFileSync as A,renameSync as C,rmSync as F,writeFileSync as H}from"node:fs";import{join as x}from"node:path";import{log as c}from"../../core/log/index.js";import{resolveCliPath as j}from"../../core/util/cli-probe.js";import{killProcessGroup as B,spawnCommand as G}from"../../core/runtime/spawn.js";import{errorForDshBridgeReadiness as R}from"./bridge-installer.js";import{bridgeDiscoveryDirectory as D,discoverDshBridgeEndpoints as y,profileHasWebApp as q}from"./profile-resolver.js";const f="deepseek-harness-profile-supervisor",I=45e3,U=500;function J(e){return{...process.env,DSH_HOME:e}}const m=new Map,u=new Map;function h(e,r,n="coalesce"){const t=m.get(e.profileKey);if(t&&n==="coalesce")return t.promise;const o=(t?t.promise.catch(()=>{}).then(()=>r()):r()).finally(()=>{m.get(e.profileKey)?.promise===o&&m.delete(e.profileKey)});return m.set(e.profileKey,{promise:o}),o}async function de(e){return h(e.installer.identity,()=>O(e))}async function ce(e){return h(e.installer.identity,()=>W(e))}async function W(e){const r=e.autoInstall!==!1;let n=await e.installer.status();return r&&["profile_missing","bridge_missing","bridge_update_required"].includes(n.readiness)&&(n=await e.installer.install()),n.readiness==="ready"&&!e.reloadManaged?n:O(e)}async function O(e){const r=e.installer,n=e.autoStart!==!1,t=e.readyTimeoutMs??I;let i=await r.status();if(e.reloadManaged&&(i=await Y(r,i,t),i.readiness==="ready")||i.readiness==="ready")return i;if(!n){const a=R(i);if(a)throw a;return i}if(i.readiness==="profile_restart_required"&&i.endpointCount===0)await b(r,i.identity),i=await _(a=>a.readiness==="ready"||a.readiness==="bridge_incompatible",r,t),i.readiness!=="ready"&&i.readiness!=="bridge_incompatible"&&await M(i.identity,"bridge endpoint did not appear");else if(i.readiness==="profile_restart_required"&&i.endpointCount===1&&i.runningBridgeVersion&&i.installedBridgeVersion){const a=y(i.identity)[0],s=g(i.identity);if(a&&s&&s.pid===a.pid&&l(s.pid)){const p=i.runningBridgeVersion!==i.installedBridgeVersion?"bridge upgrade":"bridge content refresh";c.info(f,`restarting connector-managed profile=${i.identity.profileName} pid=${s.pid} for ${p}`),await w(i.identity,s.pid),await b(r,i.identity),i=await _(S=>S.readiness==="ready"||S.readiness==="bridge_incompatible",r,t),i.readiness!=="ready"&&i.readiness!=="bridge_incompatible"&&await M(i.identity,"bridge endpoint did not appear after upgrade restart")}}if(i.readiness==="ready")return z(i),i;const o=R(i);if(o)throw o;return i}async function Y(e,r,n){const t=r.identity,i=g(t);if(!i||!l(i.pid))return r;const o=y(t);if(!o.some(p=>p.pid===i.pid)&&o.length>0)return r;c.info(f,`reloading connector-managed profile=${t.profileName} pid=${i.pid} after settings write`),await w(t,i.pid),await b(e,t);const s=await _(p=>p.readiness==="ready"||p.readiness==="bridge_incompatible",e,n);return s.readiness!=="ready"&&s.readiness!=="bridge_incompatible"&&await M(t,"bridge endpoint did not appear after settings reload"),s}function z(e){c.info(f,`bridge ready profile=${e.identity.profileName} endpoints=${e.endpointCount} bridge=${e.runningBridgeVersion}`)}async function b(e,r){const n=g(r);if(n&&l(n.pid)){if(y(r).some(E=>E.pid===n.pid)){c.info(f,`reusing connector-managed profile=${r.profileName} pid=${n.pid}`);return}c.warn(f,`restarting stuck connector-managed profile=${r.profileName} pid=${n.pid} (alive without endpoint)`),await w(r,n.pid)}else n&&P(r);const t=await j(e.command);if(!t)throw Object.assign(new Error("dsh is not installed or not on PATH"),{code:"dsh_missing"});const i=Q(r),o=D(r);K(o,{recursive:!0,mode:448});const a=x(o,"managed-profile.log"),s=T(a,{flags:"a",mode:384}),p=J(r.dshHome),d=G(t,i,{cwd:r.profileRoot,env:p,stdio:["ignore","pipe","pipe"],detached:!0}).process;if(!d.pid)throw s.end(),Object.assign(new Error(`Failed to start DSH profile "${r.profileName}"`),{code:"profile_start_failed"});d.stdout?.pipe(s,{end:!1}),d.stderr?.pipe(s,{end:!1}),d.once("exit",(N,v)=>{c.warn(f,`managed profile exited profile=${r.profileName} pid=${d.pid} code=${N} signal=${v}`),u.get(r.profileKey)===d&&u.delete(r.profileKey),g(r)?.pid===d.pid&&P(r);try{s.end()}catch{}}),d.unref(),u.set(r.profileKey,d),X(r,{schemaVersion:1,profileKey:r.profileKey,profileName:r.profileName,pid:d.pid,startedAt:new Date().toISOString(),command:t,args:i}),c.info(f,`started connector-managed profile=${r.profileName} pid=${d.pid} args=${i.join(" ")}`)}async function M(e,r){const n=g(e);n&&(c.warn(f,`stopping stuck connector-managed profile=${e.profileName} pid=${n.pid} reason=${r}`),await w(e,n.pid))}async function w(e,r){const n=u.get(e.profileKey);if(n?.pid===r){try{B(n,"SIGTERM")}catch{}u.delete(e.profileKey)}else if(l(r))try{process.kill(r,"SIGTERM")}catch{}const t=Date.now()+5e3;for(;Date.now()<t&&l(r);)await V(100);if(l(r))try{process.kill(r,"SIGKILL")}catch{}P(e)}function Q(e){return q(e.profileRoot,e.profileName)?["--profile",e.profileName,"--port","0"]:["--profile",e.profileName]}async function _(e,r,n){const t=Date.now()+n;let i=await r.status();for(;Date.now()<t;){if(e(i))return i;const o=g(r.identity);if(o&&!l(o.pid))throw P(r.identity),Object.assign(new Error(`Connector-managed DSH profile "${r.identity.profileName}" exited before Bridge became ready`),{code:"profile_start_failed"});await V(U),i=await r.status()}return i}function $(e){return x(D(e),"managed-profile.json")}function g(e){try{const r=JSON.parse(A($(e),"utf8"));return r.schemaVersion!==1||typeof r.pid!="number"||r.profileKey!==e.profileKey?null:r}catch{return null}}function X(e,r){const n=D(e);K(n,{recursive:!0,mode:448});const t=$(e),i=`${t}.${process.pid}.tmp`;H(i,`${JSON.stringify(r,null,2)}
2
- `,{mode:384}),C(i,t)}function P(e){try{F($(e),{force:!0})}catch{}}function l(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}function V(e){return new Promise(r=>setTimeout(r,e))}function fe(){m.clear();for(const e of u.values())try{e.pid&&B(e,"SIGKILL")}catch{}u.clear()}function pe(e){return k($(e))}async function le(e){const r=m.get(e.profileKey);r&&await r.promise.catch(()=>{})}async function ue(e,r=I){let n="failed";return await h(e.identity,async()=>(n=await Z(e,r),L(e,n==="restarted"?"ready":"profile_restart_required")),"queue"),n}async function Z(e,r){const n=e.identity,t=g(n);if(!t||!l(t.pid))return"not_managed";const i=y(n);if(i.length>0&&!i.some(o=>o.pid===t.pid))return"not_managed";try{return c.info(f,`restarting connector-managed profile=${n.profileName} pid=${t.pid} for plugin toggle`),await w(n,t.pid),await b(e,n),(await _(a=>a.readiness==="ready"||a.readiness==="bridge_incompatible",e,r)).readiness==="ready"?"restarted":"failed"}catch(o){return c.warn(f,`plugin-toggle restart failed profile=${n.profileName}: ${o instanceof Error?o.message:String(o)}`),"failed"}}function ge(e,r){return h(e.identity,async()=>(await r,L(e,"ready")))}function L(e,r){return{readiness:r,command:e.command,commandPath:null,dshVersion:null,runningDshVersion:null,identity:e.identity,installedBridgeVersion:null,bundledBridgeVersion:"",runningBridgeVersion:null,endpointCount:0,compatibleDshVersions:[]}}export{le as awaitDshProfileIdle,Q as buildDshProfileBootArgs,de as ensureDshBridgeReady,ge as holdDshProfileInflightForTests,pe as managedProfileRecordExists,J as managedProfileSpawnEnv,ce as prepareDshProfileBridge,fe as resetDshProfileSupervisorForTests,ue as restartManagedProfileIfOwned};
1
+ import{createWriteStream as k,existsSync as A,mkdirSync as K,readFileSync as C,renameSync as F,rmSync as H,writeFileSync as j}from"node:fs";import{join as R}from"node:path";import{log as d}from"../../core/log/index.js";import{resolveCliPath as G}from"../../core/util/cli-probe.js";import{killProcessGroup as B,spawnCommand as q}from"../../core/runtime/spawn.js";import{errorForDshBridgeReadiness as I}from"./bridge-installer.js";import{bridgeDiscoveryDirectory as M,discoverDshBridgeEndpoints as y,profileHasWebApp as U}from"./profile-resolver.js";const c="deepseek-harness-profile-supervisor",O=45e3,J=500;function W(e){return{...process.env,DSH_HOME:e}}const m=new Map,p=new Map;function $(e,r,i="coalesce"){const t=m.get(e.profileKey);if(t&&i==="coalesce")return t.promise;const o=(t?t.promise.catch(()=>{}).then(()=>r()):r()).finally(()=>{m.get(e.profileKey)?.promise===o&&m.delete(e.profileKey)});return m.set(e.profileKey,{promise:o}),o}async function ce(e){return $(e.installer.identity,()=>V(e))}async function fe(e){return $(e.installer.identity,()=>Y(e))}async function Y(e){const r=e.autoInstall!==!1;let i=await e.installer.status();return r&&["profile_missing","bridge_missing","bridge_update_required"].includes(i.readiness)&&(i=await e.installer.install()),i.readiness==="ready"&&!e.reloadManaged?i:V(e)}async function V(e){const r=e.installer,i=e.autoStart!==!1,t=e.readyTimeoutMs??O;let n=await r.status();if(e.reloadManaged&&(n=await z(r,n,t),n.readiness==="ready")||n.readiness==="ready")return n;if(!i){const l=I(n);if(l)throw l;return n}if(n.readiness==="profile_restart_required"&&n.endpointCount===0)await P(r,n.identity),n=await S(g,r,t),g(n)||await N(n.identity,"bridge endpoint did not appear");else if(n.readiness==="profile_restart_required"&&n.endpointCount>0&&n.runningBridgeVersion&&n.installedBridgeVersion){const l=y(n.identity),a=u(n.identity),w=a&&l.find(s=>s.pid===a.pid),b=n.runningBridgeVersion!==n.installedBridgeVersion?"bridge upgrade":"bridge content refresh";w&&a&&f(a.pid)?(d.info(c,`restarting connector-managed profile=${n.identity.profileName} pid=${a.pid} for ${b}`),await h(n.identity,a.pid)):d.info(c,`starting connector-managed profile=${n.identity.profileName} for ${b}; external profile processes are left untouched`),await P(r,n.identity),n=await S(g,r,t),g(n)||await N(n.identity,"bridge endpoint did not appear after upgrade restart")}if(n.readiness==="ready")return Q(n),n;const o=I(n);if(o)throw o;return n}async function z(e,r,i){const t=r.identity,n=u(t);if(!n||!f(n.pid))return r;const o=y(t);if(!o.some(w=>w.pid===n.pid)&&o.length>0)return r;d.info(c,`reloading connector-managed profile=${t.profileName} pid=${n.pid} after settings write`),await h(t,n.pid),await P(e,t);const a=await S(g,e,i);return g(a)||await N(t,"bridge endpoint did not appear after settings reload"),a}function Q(e){d.info(c,`bridge ready profile=${e.identity.profileName} endpoints=${e.endpointCount} bridge=${e.runningBridgeVersion}`)}async function P(e,r){const i=u(r);if(i&&f(i.pid)){if(y(r).some(x=>x.pid===i.pid)){d.info(c,`reusing connector-managed profile=${r.profileName} pid=${i.pid}`);return}d.warn(c,`restarting stuck connector-managed profile=${r.profileName} pid=${i.pid} (alive without endpoint)`),await h(r,i.pid)}else i&&D(r);const t=await G(e.command);if(!t)throw Object.assign(new Error("dsh is not installed or not on PATH"),{code:"dsh_missing"});const n=X(r),o=M(r);K(o,{recursive:!0,mode:448});const l=R(o,"managed-profile.log"),a=k(l,{flags:"a",mode:384}),w=W(r.dshHome),s=q(t,n,{cwd:r.profileRoot,env:w,stdio:["ignore","pipe","pipe"],detached:!0}).process;if(!s.pid)throw a.end(),Object.assign(new Error(`Failed to start DSH profile "${r.profileName}"`),{code:"profile_start_failed"});s.stdout?.pipe(a,{end:!1}),s.stderr?.pipe(a,{end:!1}),s.once("exit",(E,v)=>{d.warn(c,`managed profile exited profile=${r.profileName} pid=${s.pid} code=${E} signal=${v}`),p.get(r.profileKey)===s&&p.delete(r.profileKey),u(r)?.pid===s.pid&&D(r);try{a.end()}catch{}}),s.unref(),p.set(r.profileKey,s),Z(r,{schemaVersion:1,profileKey:r.profileKey,profileName:r.profileName,pid:s.pid,startedAt:new Date().toISOString(),command:t,args:n}),d.info(c,`started connector-managed profile=${r.profileName} pid=${s.pid} args=${n.join(" ")}`)}async function N(e,r){const i=u(e);i&&(d.warn(c,`stopping stuck connector-managed profile=${e.profileName} pid=${i.pid} reason=${r}`),await h(e,i.pid))}async function h(e,r){const i=p.get(e.profileKey);if(i?.pid===r){try{B(i,"SIGTERM")}catch{}p.delete(e.profileKey)}else if(f(r))try{process.kill(r,"SIGTERM")}catch{}const t=Date.now()+5e3;for(;Date.now()<t&&f(r);)await T(100);if(f(r))try{process.kill(r,"SIGKILL")}catch{}D(e)}function X(e){return U(e.profileRoot,e.profileName)?["--profile",e.profileName,"--port","0"]:["--profile",e.profileName]}async function S(e,r,i){const t=Date.now()+i;let n=await r.status();for(;Date.now()<t;){if(e(n))return n;const o=u(r.identity);if(o&&!f(o.pid))throw D(r.identity),Object.assign(new Error(`Connector-managed DSH profile "${r.identity.profileName}" exited before Bridge became ready`),{code:"profile_start_failed"});await T(J),n=await r.status()}return n}function _(e){return R(M(e),"managed-profile.json")}function u(e){try{const r=JSON.parse(C(_(e),"utf8"));return r.schemaVersion!==1||typeof r.pid!="number"||r.profileKey!==e.profileKey?null:r}catch{return null}}function Z(e,r){const i=M(e);K(i,{recursive:!0,mode:448});const t=_(e),n=`${t}.${process.pid}.tmp`;j(n,`${JSON.stringify(r,null,2)}
2
+ `,{mode:384}),F(n,t)}function D(e){try{H(_(e),{force:!0})}catch{}}function f(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}function T(e){return new Promise(r=>setTimeout(r,e))}function le(){m.clear();for(const e of p.values())try{e.pid&&B(e,"SIGKILL")}catch{}p.clear()}function pe(e){return A(_(e))}async function ue(e){const r=m.get(e.profileKey);r&&await r.promise.catch(()=>{})}async function ge(e,r=O){let i="failed";return await $(e.identity,async()=>(i=await ee(e,r),L(e,i==="restarted"?"ready":"profile_restart_required")),"queue"),i}async function ee(e,r){const i=e.identity,t=u(i);if(!t||!f(t.pid))return"not_managed";const n=y(i);if(n.length>0&&!n.some(o=>o.pid===t.pid))return"not_managed";try{return d.info(c,`restarting connector-managed profile=${i.profileName} pid=${t.pid} for plugin toggle`),await h(i,t.pid),await P(e,i),(await S(g,e,r)).readiness==="ready"?"restarted":"failed"}catch(o){return d.warn(c,`plugin-toggle restart failed profile=${i.profileName}: ${o instanceof Error?o.message:String(o)}`),"failed"}}function g(e){return e.readiness==="ready"||e.readiness==="bridge_incompatible"}function me(e,r){return $(e.identity,async()=>(await r,L(e,"ready")))}function L(e,r){return{readiness:r,command:e.command,commandPath:null,dshVersion:null,runningDshVersion:null,identity:e.identity,installedBridgeVersion:null,bundledBridgeVersion:"",runningBridgeVersion:null,endpointCount:0,compatibleDshVersions:[]}}export{ue as awaitDshProfileIdle,X as buildDshProfileBootArgs,ce as ensureDshBridgeReady,me as holdDshProfileInflightForTests,pe as managedProfileRecordExists,W as managedProfileSpawnEnv,fe as prepareDshProfileBridge,le as resetDshProfileSupervisorForTests,ge as restartManagedProfileIfOwned};
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "3.29.2",
4
- "tarball": "grix-dsh-bridge-3.29.2.tgz",
3
+ "bridgeVersion": "3.29.3",
4
+ "tarball": "grix-dsh-bridge-3.29.3.tgz",
5
5
  "size": 13786,
6
6
  "unpackedSize": 52666,
7
- "shasum": "32a6ea0a5fe2fafcef8d8d5a5a41c3d1884d1556",
8
- "integrity": "sha512-oTf9yBGzZZH/pyH76Kk/pK8MSbMH49etkDHkXKZCs3Iq+tN8v1f1JyosdeS8a4+m6CV1omq2ubFNOEwUN99kyw=="
7
+ "shasum": "7029b8b50ae0b7bf9030177e7f8db880b3e07491",
8
+ "integrity": "sha512-yuTQbvf3JBmmf4N+NNg8MmDlqt7R93q5T1duHXwtI5GyIEtaniGcj29Zvj5RmhoECGwXXvI6CbmN0MUsLrwIGQ=="
9
9
  }
@@ -1 +1 @@
1
- import{readJSONFile as o,writeJSONFileAtomic as i}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(e=>typeof e=="string"&&e.trim().length>0):[]}async function s(t,r){await i(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
1
+ import{readJSONFile as o,writeJSONFileAtomic as e}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(i=>typeof i=="string"&&i.trim().length>0):[]}async function s(t,r){await e(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
@@ -1 +1 @@
1
- import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const i of c){if(!p&&i.name.startsWith("."))continue;const t=l(a,i.name),e={id:t,name:i.name,is_directory:i.isDirectory()};try{if(i.isDirectory()){const o=await m(t);e.modified_at=o.mtime.toISOString()}else{const o=await m(t);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(i.name)}}catch{}s.push(e)}return s.sort((i,t)=>i.is_directory!==t.is_directory?i.is_directory?-1:1:i.name.localeCompare(t.name)),s}export{f as listFiles,n as resolveMimeType};
1
+ import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const t of c){if(!p&&t.name.startsWith("."))continue;const i=l(a,t.name),e={id:i,name:t.name,is_directory:t.isDirectory()};try{if(t.isDirectory()){const o=await m(i);e.modified_at=o.mtime.toISOString()}else{const o=await m(i);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(t.name)}}catch{}s.push(e)}return s.sort((t,i)=>t.is_directory!==i.is_directory?t.is_directory?-1:1:t.name.localeCompare(i.name)),s}export{f as listFiles,n as resolveMimeType};
package/dist/log.js CHANGED
@@ -1,3 +1,3 @@
1
- import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as i}from"node:path";import{homedir as m}from"node:os";const n=i(m(),".grix"),s={base:n,config:i(n,"config"),log:i(n,"log"),data:i(n,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=i(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...t){const e=`${c()} [${o}] ${r}${t.length?" "+t.map(String).join(" "):""}`;console.log(e),a?.write(e+`
2
- `)},error(o,r,...t){const e=`${c()} [${o}] ERROR ${r}${t.length?" "+t.map(String).join(" "):""}`;console.error(e),a?.write(e+`
1
+ import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as t}from"node:path";import{homedir as m}from"node:os";const i=t(m(),".grix"),s={base:i,config:t(i,"config"),log:t(i,"log"),data:t(i,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=t(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...n){const e=`${c()} [${o}] ${r}${n.length?" "+n.map(String).join(" "):""}`;console.log(e),a?.write(e+`
2
+ `)},error(o,r,...n){const e=`${c()} [${o}] ERROR ${r}${n.length?" "+n.map(String).join(" "):""}`;console.error(e),a?.write(e+`
3
3
  `)}};export{s as GRIX_PATHS,S as ensureGrixDirs,$ as initLogger,u as log};
@@ -1 +1 @@
1
- import*as n from"node:net";const i={bind:"127.0.0.1",port:0,endpoint:"/mcp",sessionTimeoutMs:18e5,invokeTimeoutMs:3e4};function s(u){const e={bind:u?.bind??i.bind,port:u?.port??i.port,endpoint:u?.endpoint??i.endpoint,sessionTimeoutMs:u?.sessionTimeoutMs??i.sessionTimeoutMs,invokeTimeoutMs:u?.invokeTimeoutMs??i.invokeTimeoutMs,allowedOrigins:u?.allowedOrigins,allowedHosts:u?.allowedHosts};return t(e.bind),e.port!==0&&o(e.port),r(e.sessionTimeoutMs),e}function t(u){if(!u||!n.isIPv4(u)&&!n.isIPv6(u))throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: bind \u5730\u5740 "${u}" \u4E0D\u662F\u5408\u6CD5\u7684 IPv4 \u6216 IPv6 \u5730\u5740`)}function o(u){if(!Number.isInteger(u)||u<1||u>65535)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: port \u503C ${u} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1-65535 \u5185\u6216\u4E0D\u662F\u6574\u6570`)}function r(u){if(!Number.isInteger(u)||u<1e3||u>864e5)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: session_timeout_ms \u503C ${u} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1000-86400000 \u5185`)}export{s as createDefaultGatewayConfig};
1
+ import*as i from"node:net";const e={bind:"127.0.0.1",port:0,endpoint:"/mcp",sessionTimeoutMs:18e5,invokeTimeoutMs:3e4};function n(o){const u={bind:o?.bind??e.bind,port:o?.port??e.port,endpoint:o?.endpoint??e.endpoint,sessionTimeoutMs:o?.sessionTimeoutMs??e.sessionTimeoutMs,invokeTimeoutMs:o?.invokeTimeoutMs??e.invokeTimeoutMs,allowedOrigins:o?.allowedOrigins,allowedHosts:o?.allowedHosts};return s(u.bind),u.port!==0&&t(u.port),r(u.sessionTimeoutMs),u}function s(o){if(!o||!i.isIPv4(o)&&!i.isIPv6(o))throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: bind \u5730\u5740 "${o}" \u4E0D\u662F\u5408\u6CD5\u7684 IPv4 \u6216 IPv6 \u5730\u5740`)}function t(o){if(!Number.isInteger(o)||o<1||o>65535)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: port \u503C ${o} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1-65535 \u5185\u6216\u4E0D\u662F\u6574\u6570`)}function r(o){if(!Number.isInteger(o)||o<1e3||o>864e5)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: session_timeout_ms \u503C ${o} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1000-86400000 \u5185`)}export{n as createDefaultGatewayConfig};
@@ -1 +1 @@
1
- const a=3e4;class c{connectionManager;onDisconnected;bindings=new Map;constructor(n,i){this.connectionManager=n,this.onDisconnected=i}async bind(n,i){if(this.bindings.has(n))throw new Error(`Session ${n} is already bound to a connection`);const e=await this.connectWithTimeout(i),t=[],s=e.onDisconnected(()=>{this.removeBinding(n),this.onDisconnected(n)});return t.push(s),this.bindings.set(n,{sessionId:n,handle:e,subscriptions:t}),e}getHandle(n){return this.bindings.get(n)?.handle}unbind(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e();i.handle.disconnect()}}unbindAll(){const n=[...this.bindings.keys()];for(const i of n)this.unbind(i)}connectWithTimeout(n){return new Promise((i,e)=>{let t=!1;const s=setTimeout(()=>{t||(t=!0,e(new Error("Connection bind timeout after 30000ms")))},3e4);this.connectionManager.connect({agentId:n.agentId,apiKey:n.apiKey,url:n.wsUrl,clientType:n.clientType,capabilities:["agent_invoke"],adapterHint:`${n.clientType}/base`},{maxRetries:0}).then(o=>{t?o.disconnect():(t=!0,clearTimeout(s),i(o))}).catch(o=>{t||(t=!0,clearTimeout(s),e(o))})})}removeBinding(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e()}}}export{c as ConnectionBindingImpl};
1
+ const r=3e4;class c{connectionManager;onDisconnected;bindings=new Map;constructor(n,i){this.connectionManager=n,this.onDisconnected=i}async bind(n,i){if(this.bindings.has(n))throw new Error(`Session ${n} is already bound to a connection`);const e=await this.connectWithTimeout(i),t=[],s=e.onDisconnected(()=>{this.removeBinding(n),this.onDisconnected(n)});return t.push(s),this.bindings.set(n,{sessionId:n,handle:e,subscriptions:t}),e}getHandle(n){return this.bindings.get(n)?.handle}unbind(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e();i.handle.disconnect()}}unbindAll(){const n=[...this.bindings.keys()];for(const i of n)this.unbind(i)}connectWithTimeout(n){return new Promise((i,e)=>{let t=!1;const s=setTimeout(()=>{t||(t=!0,e(new Error("Connection bind timeout after 30000ms")))},3e4);this.connectionManager.connect({agentId:n.agentId,apiKey:n.apiKey,url:n.wsUrl,clientType:n.clientType,capabilities:["agent_invoke"],adapterHint:`${n.clientType}/base`},{maxRetries:0}).then(o=>{t?o.disconnect():(t=!0,clearTimeout(s),i(o))}).catch(o=>{t||(t=!0,clearTimeout(s),e(o))})})}removeBinding(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e()}}}export{c as ConnectionBindingImpl};
@@ -1 +1 @@
1
- function a(e){const t=new Set([`http://127.0.0.1:${e.serverPort}`,`http://localhost:${e.serverPort}`,...e.allowedOrigins]),o=new Set([`127.0.0.1:${e.serverPort}`,`localhost:${e.serverPort}`,...e.allowedHosts]);return{validateRequest(s){const r=i(s,t);if(!r.ok)return r;const n=l(s,o);return n.ok?{ok:!0}:n}}}function i(e,t){const o=e.headers.origin;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${o}`}:{ok:!0}}function l(e,t){const o=e.headers.host;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${o}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
1
+ function a(o){const e=new Set([`http://127.0.0.1:${o.serverPort}`,`http://localhost:${o.serverPort}`,...o.allowedOrigins]),t=new Set([`127.0.0.1:${o.serverPort}`,`localhost:${o.serverPort}`,...o.allowedHosts]);return{validateRequest(s){const r=i(s,e);if(!r.ok)return r;const n=l(s,t);return n.ok?{ok:!0}:n}}}function i(o,e){const t=o.headers.origin;return t?e.has(t)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${t}`}:{ok:!0}}function l(o,e){const t=o.headers.host;return t?e.has(t)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${t}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
@@ -1 +1 @@
1
- import{toolCallToInvoke as i}from"../../core/mcp/tools.js";import{ToolRegistryImpl as l}from"./tool-registry.js";import{validateToolArgs as a}from"./tool-schemas.js";import{isEventTool as p,executeEventTool as d}from"./event-tool-executor.js";class y{registry;constructor(){this.registry=new l}async execute(r,e,t,n){if(!this.registry.hasTool(e))return this.errorResult(`\u672A\u77E5\u5DE5\u5177: ${e}`);const s=a(e,t);if(!s.valid)return this.errorResult(`\u53C2\u6570\u6821\u9A8C\u5931\u8D25: ${s.error}`);if(r.status!=="ready")return this.errorResult(`\u8FDE\u63A5\u4E0D\u53EF\u7528: \u5F53\u524D\u72B6\u6001\u4E3A ${r.status}`);if(p(e))return this.executeEventTool(r,e,t);const o=i(e,t);try{const u=await r.agentInvoke(o.action,o.params,n);return this.normalizeResult(u)}catch(u){const c=u instanceof Error?u.message:String(u);return c.toLowerCase().includes("timeout")?this.errorResult(`\u8C03\u7528\u8D85\u65F6: ${c}`):this.errorResult(`\u8C03\u7528\u5931\u8D25: ${c}`)}}normalizeResult(r){if(r==null||typeof r!="object")return this.successResult(r??null);const e=r,t=typeof e.code=="number"?e.code:0;if(t===0){const s="data"in e?e.data:null;return this.successResult(s??null)}const n=typeof e.msg=="string"?e.msg:"\u672A\u77E5\u9519\u8BEF";return this.errorResult(`\u4E0A\u6E38\u9519\u8BEF [code=${t}]: ${n}`)}successResult(r){return{content:[{type:"text",text:JSON.stringify(r)}],isError:!1}}errorResult(r){return{content:[{type:"text",text:r}],isError:!0}}async executeEventTool(r,e,t){return e==="grix_access_control"?this.executeAccessControl(r,t):d(r,e,t)}async executeAccessControl(r,e){const t=String(e.action??""),n={pair_approve:"pair_approve",pair_deny:"pair_deny",allow_sender:"sender_allow",remove_sender:"sender_remove",set_policy:"policy_set"}[t];if(!n)return this.errorResult(`\u672A\u77E5 access_control action: ${t}`);const s={};e.code!=null&&(s.code=e.code),e.sender_id!=null&&(s.sender_id=e.sender_id),e.policy!=null&&(s.policy=e.policy);try{const o=await r.agentInvoke("claude_access_control",{verb:n,payload:s},3e4);return this.successResult(o)}catch(o){const u=o instanceof Error?o.message:String(o);return this.errorResult(`access_control \u8C03\u7528\u5931\u8D25: ${u}`)}}}export{y as ToolExecutorImpl};
1
+ import{toolCallToInvoke as i}from"../../core/mcp/tools.js";import{ToolRegistryImpl as l}from"./tool-registry.js";import{validateToolArgs as a}from"./tool-schemas.js";import{isEventTool as p,executeEventTool as d}from"./event-tool-executor.js";class y{registry;constructor(){this.registry=new l}async execute(t,e,r,n){if(!this.registry.hasTool(e))return this.errorResult(`\u672A\u77E5\u5DE5\u5177: ${e}`);const s=a(e,r);if(!s.valid)return this.errorResult(`\u53C2\u6570\u6821\u9A8C\u5931\u8D25: ${s.error}`);if(t.status!=="ready")return this.errorResult(`\u8FDE\u63A5\u4E0D\u53EF\u7528: \u5F53\u524D\u72B6\u6001\u4E3A ${t.status}`);if(p(e))return this.executeEventTool(t,e,r);const o=i(e,r);try{const u=await t.agentInvoke(o.action,o.params,n);return this.normalizeResult(u)}catch(u){const c=u instanceof Error?u.message:String(u);return c.toLowerCase().includes("timeout")?this.errorResult(`\u8C03\u7528\u8D85\u65F6: ${c}`):this.errorResult(`\u8C03\u7528\u5931\u8D25: ${c}`)}}normalizeResult(t){if(t==null||typeof t!="object")return this.successResult(t??null);const e=t,r=typeof e.code=="number"?e.code:0;if(r===0){const s="data"in e?e.data:null;return this.successResult(s??null)}const n=typeof e.msg=="string"?e.msg:"\u672A\u77E5\u9519\u8BEF";return this.errorResult(`\u4E0A\u6E38\u9519\u8BEF [code=${r}]: ${n}`)}successResult(t){return{content:[{type:"text",text:JSON.stringify(t)}],isError:!1}}errorResult(t){return{content:[{type:"text",text:t}],isError:!0}}async executeEventTool(t,e,r){return e==="grix_access_control"?this.executeAccessControl(t,r):d(t,e,r)}async executeAccessControl(t,e){const r=String(e.action??""),n={pair_approve:"pair_approve",pair_deny:"pair_deny",allow_sender:"sender_allow",remove_sender:"sender_remove",set_policy:"policy_set"}[r];if(!n)return this.errorResult(`\u672A\u77E5 access_control action: ${r}`);const s={};e.code!=null&&(s.code=e.code),e.sender_id!=null&&(s.sender_id=e.sender_id),e.policy!=null&&(s.policy=e.policy);try{const o=await t.agentInvoke("claude_access_control",{verb:n,payload:s},3e4);return this.successResult(o)}catch(o){const u=o instanceof Error?o.message:String(o);return this.errorResult(`access_control \u8C03\u7528\u5931\u8D25: ${u}`)}}}export{y as ToolExecutorImpl};
@@ -1 +1 @@
1
- import{TOOLS as o,EVENT_TOOLS as s}from"../../core/mcp/tools.js";const e=new Set(["grix_query","grix_group","grix_message_send","grix_message_unsend","grix_admin"]),r=new Set(["grix_reply","grix_complete","grix_event_ack","grix_composing","grix_access_control","grix_status"]);class a{tools;toolMap;constructor(){this.tools=[...o.filter(t=>e.has(t.name)),...s.filter(t=>r.has(t.name))],this.toolMap=new Map(this.tools.map(t=>[t.name,t]))}getTools(){return this.tools}getTool(t){return this.toolMap.get(t)}hasTool(t){return this.toolMap.has(t)}}export{a as ToolRegistryImpl};
1
+ import{TOOLS as s,EVENT_TOOLS as t}from"../../core/mcp/tools.js";const e=new Set(["grix_query","grix_group","grix_message_send","grix_message_unsend","grix_admin"]),r=new Set(["grix_reply","grix_complete","grix_event_ack","grix_composing","grix_access_control","grix_status"]);class a{tools;toolMap;constructor(){this.tools=[...s.filter(o=>e.has(o.name)),...t.filter(o=>r.has(o.name))],this.toolMap=new Map(this.tools.map(o=>[o.name,o]))}getTools(){return this.tools}getTool(o){return this.toolMap.get(o)}hasTool(o){return this.toolMap.has(o)}}export{a as ToolRegistryImpl};
@@ -1 +1 @@
1
- const o={required:["action"],properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},id:{type:"string"},keyword:{type:"string",maxLength:200},limit:{type:"integer",minimum:1,maximum:100},offset:{type:"integer",minimum:0},sessionId:{type:"string"},beforeId:{type:"string"}}},a={required:["action"],properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string",maxLength:128},memberIds:{type:"array",items:{type:"string"},maxItems:100},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer"},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean"}}},p={required:["sessionId","content"],properties:{sessionId:{type:"string"},content:{type:"string",maxLength:1e4},msgType:{type:"integer"},quotedMessageId:{type:"string"},threadId:{type:"string"}}},m={required:["sessionId","msgId"],properties:{sessionId:{type:"string"},msgId:{type:"string"}}},g={required:["action"],properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},agentId:{type:"string"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"integer"}}},y={required:["session_id","text"],properties:{event_id:{type:"string"},session_id:{type:"string"},text:{type:"string",maxLength:5e4},quoted_message_id:{type:"string"},is_final:{type:"boolean"}}},d={required:["event_id","status"],properties:{event_id:{type:"string"},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string",maxLength:500}}},c={required:["event_id"],properties:{event_id:{type:"string"},session_id:{type:"string"}}},l={required:["session_id","active"],properties:{session_id:{type:"string"},active:{type:"boolean"},event_id:{type:"string"}}},_={required:["action"],properties:{action:{type:"string",enum:["pair_approve","pair_deny","allow_sender","remove_sender","set_policy"]},code:{type:"string"},sender_id:{type:"string"},policy:{type:"string",enum:["allowlist","open","disabled"]}}},f={required:[],properties:{}},C={grix_query:o,grix_group:a,grix_message_send:p,grix_message_unsend:m,grix_admin:g,grix_reply:y,grix_complete:d,grix_event_ack:c,grix_composing:l,grix_access_control:_,grix_status:f};function B(r,t){const e=C[r];if(!e)return{valid:!1,error:`\u672A\u77E5\u5DE5\u5177: ${r}`};for(const i of e.required)if(t[i]===void 0||t[i]===null)return{valid:!1,error:`\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570: ${i}`};for(const[i,u]of Object.entries(t)){if(u==null)continue;const n=e.properties[i];if(!n)continue;const s=$(i,u,n);if(s)return{valid:!1,error:s}}return{valid:!0}}function $(r,t,e){switch(e.type){case"string":if(typeof t!="string")return`\u53C2\u6570 ${r} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxLength!==void 0&&t.length>e.maxLength)return`\u53C2\u6570 ${r} \u8D85\u8FC7\u6700\u5927\u957F\u5EA6 ${e.maxLength}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${r} \u503C "${t}" \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"integer":if(typeof t!="number"||!Number.isInteger(t))return`\u53C2\u6570 ${r} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof t=="number"?"\u6D6E\u70B9\u6570":typeof t}`;if(e.minimum!==void 0&&t<e.minimum)return`\u53C2\u6570 ${r} \u503C ${t} \u5C0F\u4E8E\u6700\u5C0F\u503C ${e.minimum}`;if(e.maximum!==void 0&&t>e.maximum)return`\u53C2\u6570 ${r} \u503C ${t} \u5927\u4E8E\u6700\u5927\u503C ${e.maximum}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${r} \u503C ${t} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"boolean":if(typeof t!="boolean")return`\u53C2\u6570 ${r} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B boolean\uFF0C\u5B9E\u9645 ${typeof t}`;break;case"array":if(!Array.isArray(t))return`\u53C2\u6570 ${r} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B array\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxItems!==void 0&&t.length>e.maxItems)return`\u53C2\u6570 ${r} \u8D85\u8FC7\u6700\u5927\u5143\u7D20\u6570 ${e.maxItems}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.items)for(let i=0;i<t.length;i++){const u=t[i];if(e.items.type==="string"&&typeof u!="string")return`\u53C2\u6570 ${r}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof u}`;if(e.items.type==="integer"){if(typeof u!="number"||!Number.isInteger(u))return`\u53C2\u6570 ${r}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof u}`;if(e.items.enum&&!e.items.enum.includes(u))return`\u53C2\u6570 ${r}[${i}] \u503C ${u} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.items.enum.join(", ")}]`}}break}}export{B as validateToolArgs};
1
+ const o={required:["action"],properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},id:{type:"string"},keyword:{type:"string",maxLength:200},limit:{type:"integer",minimum:1,maximum:100},offset:{type:"integer",minimum:0},sessionId:{type:"string"},beforeId:{type:"string"}}},a={required:["action"],properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string",maxLength:128},memberIds:{type:"array",items:{type:"string"},maxItems:100},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer"},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean"}}},p={required:["sessionId","content"],properties:{sessionId:{type:"string"},content:{type:"string",maxLength:1e4},msgType:{type:"integer"},quotedMessageId:{type:"string"},threadId:{type:"string"}}},m={required:["sessionId","msgId"],properties:{sessionId:{type:"string"},msgId:{type:"string"}}},g={required:["action"],properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},agentId:{type:"string"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"integer"}}},y={required:["session_id","text"],properties:{event_id:{type:"string"},session_id:{type:"string"},text:{type:"string",maxLength:5e4},quoted_message_id:{type:"string"},is_final:{type:"boolean"}}},d={required:["event_id","status"],properties:{event_id:{type:"string"},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string",maxLength:500}}},c={required:["event_id"],properties:{event_id:{type:"string"},session_id:{type:"string"}}},l={required:["session_id","active"],properties:{session_id:{type:"string"},active:{type:"boolean"},event_id:{type:"string"}}},_={required:["action"],properties:{action:{type:"string",enum:["pair_approve","pair_deny","allow_sender","remove_sender","set_policy"]},code:{type:"string"},sender_id:{type:"string"},policy:{type:"string",enum:["allowlist","open","disabled"]}}},f={required:[],properties:{}},C={grix_query:o,grix_group:a,grix_message_send:p,grix_message_unsend:m,grix_admin:g,grix_reply:y,grix_complete:d,grix_event_ack:c,grix_composing:l,grix_access_control:_,grix_status:f};function B(u,t){const e=C[u];if(!e)return{valid:!1,error:`\u672A\u77E5\u5DE5\u5177: ${u}`};for(const i of e.required)if(t[i]===void 0||t[i]===null)return{valid:!1,error:`\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570: ${i}`};for(const[i,r]of Object.entries(t)){if(r==null)continue;const n=e.properties[i];if(!n)continue;const s=$(i,r,n);if(s)return{valid:!1,error:s}}return{valid:!0}}function $(u,t,e){switch(e.type){case"string":if(typeof t!="string")return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxLength!==void 0&&t.length>e.maxLength)return`\u53C2\u6570 ${u} \u8D85\u8FC7\u6700\u5927\u957F\u5EA6 ${e.maxLength}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${u} \u503C "${t}" \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"integer":if(typeof t!="number"||!Number.isInteger(t))return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof t=="number"?"\u6D6E\u70B9\u6570":typeof t}`;if(e.minimum!==void 0&&t<e.minimum)return`\u53C2\u6570 ${u} \u503C ${t} \u5C0F\u4E8E\u6700\u5C0F\u503C ${e.minimum}`;if(e.maximum!==void 0&&t>e.maximum)return`\u53C2\u6570 ${u} \u503C ${t} \u5927\u4E8E\u6700\u5927\u503C ${e.maximum}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${u} \u503C ${t} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"boolean":if(typeof t!="boolean")return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B boolean\uFF0C\u5B9E\u9645 ${typeof t}`;break;case"array":if(!Array.isArray(t))return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B array\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxItems!==void 0&&t.length>e.maxItems)return`\u53C2\u6570 ${u} \u8D85\u8FC7\u6700\u5927\u5143\u7D20\u6570 ${e.maxItems}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.items)for(let i=0;i<t.length;i++){const r=t[i];if(e.items.type==="string"&&typeof r!="string")return`\u53C2\u6570 ${u}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof r}`;if(e.items.type==="integer"){if(typeof r!="number"||!Number.isInteger(r))return`\u53C2\u6570 ${u}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof r}`;if(e.items.enum&&!e.items.enum.includes(r))return`\u53C2\u6570 ${u}[${i}] \u503C ${r} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.items.enum.join(", ")}]`}}break}}export{B as validateToolArgs};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grix-connector",
3
- "version": "3.29.2",
3
+ "version": "3.29.3",
4
4
  "description": "Connect local AI coding agents (Claude, Codex, Gemini, Qwen, DeepSeek, Cursor, OpenCode, Pi, OpenHuman, Reasonix) to the Grix scheduling platform. Also serves as an OpenClaw plugin for Grix channel transport.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",