grix-connector 4.2.8 → 4.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const n of t)e.push(n);const r=Buffer.concat(e).toString("utf8").trim();return r?JSON.parse(r):{}}function k(t){const e=(t.headers.authorization??"").trim();return e.toLowerCase().startsWith("bearer ")?e.slice(7).trim():""}class w{host="127.0.0.1";port=0;token;callbacks;server=null;address=null;constructor(e){this.token=d(),this.callbacks=e}getToken(){return this.token}getURL(){return this.address?`http://${this.address.address}:${this.address.port}`:""}async start(){this.server||(this.server=c.createServer(async(e,r)=>{try{await this.handleRequest(e,r)}catch(n){h(r,n instanceof Error?n.message:String(n))}}),await new Promise((e,r)=>{this.server.once("error",r),this.server.listen(this.port,this.host,()=>{this.server.off("error",r),e()})}),this.address=this.server.address(),o.info("claude-bridge",`Bridge server listening on ${this.getURL()}`))}async stop(){if(!this.server)return;const e=this.server;this.server=null,this.address=null,e.closeIdleConnections?.(),e.closeAllConnections?.(),await new Promise((r,n)=>{e.close(s=>s?n(s):r())})}async handleRequest(e,r){if(k(e)!==this.token){l(r);return}if(e.method!=="POST"){r.writeHead(405,{"content-type":"application/json"}),r.end(JSON.stringify({error:"method_not_allowed"}));return}const n=new URL(e.url,"http://localhost").pathname,s=await v(e),i=f.get(n);if(!i){u(r);return}const a=await i(this.callbacks,s);p(r,a??{ok:!0})}}const f=new Map([["/v1/worker/register",async(t,e)=>(o.info("claude-bridge",`Worker registered: ${e.worker_id} (pid=${e.pid})`),t.onRegisterWorker(e))],["/v1/worker/status",async(t,e)=>(o.info("claude-bridge",`Worker status: ${e.status}`),t.onStatusUpdate(e))],["/v1/worker/send-text",async(t,e)=>t.onSendText(e)],["/v1/worker/send-stream-chunk",async(t,e)=>t.onSendStreamChunk(e)],["/v1/worker/send-media",async(t,e)=>t.onSendMedia(e)],["/v1/worker/delete-message",async(t,e)=>t.onDeleteMessage(e)],["/v1/worker/ack-event",async(t,e)=>t.onAckEvent(e)],["/v1/worker/event-result",async(t,e)=>t.onSendEventResult(e)],["/v1/worker/event-stop-ack",async(t,e)=>t.onSendEventStopAck(e)],["/v1/worker/event-stop-result",async(t,e)=>t.onSendEventStopResult(e)],["/v1/worker/session-composing",async(t,e)=>t.onSetSessionComposing(e)],["/v1/worker/agent-invoke",async(t,e)=>t.onAgentInvoke(e)],["/v1/worker/local-action-result",async(t,e)=>t.onLocalActionResult(e)]]);export{w as ClaudeBridgeServer};
1
+ import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const r of t)e.push(r);const n=Buffer.concat(e).toString("utf8").trim();return n?JSON.parse(n):{}}function k(t){const e=(t.headers.authorization??"").trim();return e.toLowerCase().startsWith("bearer ")?e.slice(7).trim():""}class w{host="127.0.0.1";port=0;token;callbacks;server=null;address=null;constructor(e){this.token=d(),this.callbacks=e}getToken(){return this.token}getURL(){return this.address?`http://${this.address.address}:${this.address.port}`:""}async start(){this.server||(this.server=c.createServer(async(e,n)=>{try{await this.handleRequest(e,n)}catch(r){h(n,r instanceof Error?r.message:String(r))}}),await new Promise((e,n)=>{this.server.once("error",n),this.server.listen(this.port,this.host,()=>{this.server.off("error",n),e()})}),this.address=this.server.address(),o.info("claude-bridge",`Bridge server listening on ${this.getURL()}`))}async stop(){if(!this.server)return;const e=this.server;this.server=null,this.address=null,e.closeIdleConnections?.(),e.closeAllConnections?.(),await new Promise((n,r)=>{e.close(s=>s?r(s):n())})}async handleRequest(e,n){if(k(e)!==this.token){l(n);return}if(e.method!=="POST"){n.writeHead(405,{"content-type":"application/json"}),n.end(JSON.stringify({error:"method_not_allowed"}));return}const r=new URL(e.url,"http://localhost").pathname,s=await v(e),i=f.get(r);if(!i){u(n);return}const a=await i(this.callbacks,s);p(n,a??{ok:!0})}}const f=new Map([["/v1/worker/register",async(t,e)=>(o.info("claude-bridge",`Worker registered: ${e.worker_id} (pid=${e.pid})`),t.onRegisterWorker(e))],["/v1/worker/status",async(t,e)=>(o.info("claude-bridge",`Worker status: ${e.status}`),t.onStatusUpdate(e))],["/v1/worker/send-text",async(t,e)=>t.onSendText(e)],["/v1/worker/send-stream-chunk",async(t,e)=>t.onSendStreamChunk(e)],["/v1/worker/send-media",async(t,e)=>t.onSendMedia(e)],["/v1/worker/delete-message",async(t,e)=>t.onDeleteMessage(e)],["/v1/worker/ack-event",async(t,e)=>t.onAckEvent(e)],["/v1/worker/event-result",async(t,e)=>t.onSendEventResult(e)],["/v1/worker/event-stop-ack",async(t,e)=>t.onSendEventStopAck(e)],["/v1/worker/event-stop-result",async(t,e)=>t.onSendEventStopResult(e)],["/v1/worker/session-composing",async(t,e)=>t.onSetSessionComposing(e)],["/v1/worker/agent-invoke",async(t,e)=>t.onAgentInvoke(e)],["/v1/worker/local-action-result",async(t,e)=>t.onLocalActionResult(e)]]);export{w as ClaudeBridgeServer};
@@ -1 +1 @@
1
- import{randomUUID as x}from"node:crypto";import{CallToolRequestSchema as S,ListToolsRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{log as f}from"../../core/log/index.js";import{toolCallToInvoke as k}from"../../core/mcp/tools.js";const E=new Set(["contact_search","session_search","message_history","message_search","group_create","group_detail_read","group_leave_self","group_member_add","group_member_remove","group_member_role_update","group_all_members_muted_update","group_member_speaking_update","group_dissolve","send_msg","delete_msg","agent_api_create","agent_category_list","agent_category_create","agent_category_update","agent_category_assign","agent_api_key_rotate"]),y=3e4,I=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},files:{type:"array",items:{type:"string"},description:"Optional absolute local file paths. Each file is uploaded through Agent API OSS presign before sending."},final:{type:"boolean",description:"Whether this is the final reply for the event. Defaults to false \u2014 the event stays open while Claude continues working, and auto-completes after inactivity. Set true only when this is definitively the last message for the event."}},required:["chat_id","event_id"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},code:{type:"string"},msg:{type:"string"}},required:["event_id","status"]}},{name:"delete_message",description:"Delete a previously sent message in the same grix-claude chat.",inputSchema:{type:"object",properties:{chat_id:{type:"string"},message_id:{type:"string"}},required:["chat_id","message_id"]}},{name:"status",description:"Show grix-claude runtime status, upstream access state, bridge health, and startup hints.",inputSchema:{type:"object",properties:{}}},{name:"send",description:"Send a message to a chat session proactively, without requiring an inbound event. Use for notifications or scheduled reports.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The target chat/session id."},text:{type:"string",description:"The message text to send."}},required:["chat_id","text"]}},{name:"access_pair",description:"Forward a sender pairing approval code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"access_deny",description:"Forward a sender pairing denial code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"allow_sender",description:"Ask upstream access control to allow a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"remove_sender",description:"Ask upstream access control to remove a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"access_policy",description:"Ask upstream access control to update the sender access policy.",inputSchema:{type:"object",properties:{policy:{type:"string",enum:["allowlist","open","disabled"]}},required:["policy"]}},{name:"grix_query",description:"Search contacts, sessions, message history, or messages by keyword in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},keyword:{type:"string"},id:{type:"string"},sessionId:{type:"string"},limit:{type:"number"},offset:{type:"number"},beforeId:{type:"string"}},required:["action"]}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string"},memberIds:{type:"array",items:{type:"string"}},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer",description:"Member type (for update_member_role / update_member_speaking)."},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted (for update_member_speaking)."}},required:["action"]}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},content:{type:"string"},msgType:{type:"number"},quotedMessageId:{type:"string"},threadId:{type:"string"}},required:["sessionId","content"]}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},msgId:{type:"string"}},required:["sessionId","msgId"]}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentId:{type:"string"},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"number"}},required:["action"]}}];function q(n,e){n.setRequestHandler(w,async()=>({tools:I})),n.setRequestHandler(S,async i=>{const{name:r,arguments:t}=i.params,s=t??{};try{switch(r){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(r,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(r,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${r}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${r} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(n,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const r=String(n.text??""),t=String(n.chat_id??""),s=String(n.event_id??i.eventId),a=n.reply_to,d=n.files,_=n.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!r.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,r),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(n,e){const i=e.getActiveEvent(),r=String(n.event_id??""),t=n.status??"",s=n.code,a=n.msg;if(!r||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(r)?(e.bridge.sendEventResult(r,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(n,e){const i=String(n.chat_id??""),r=String(n.message_id??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:r},y),c(`deleted (${r})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(n){const e=n.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(n,e){const i=String(n.chat_id??""),r=String(n.text??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(r),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(n,e,i){try{const r=C[n];if(!r)throw new Error(`Unknown access control tool: ${n}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:r.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}async function O(n,e,i){try{const r=k(n,e);if(!E.has(r.action))throw new Error(`Action not allowed: ${r.action}`);const t=await i.bridge.agentInvoke(r.action,r.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}function c(n){return{content:[{type:"text",text:n}]}}export{q as registerClaudeTools};
1
+ import{randomUUID as x}from"node:crypto";import{CallToolRequestSchema as S,ListToolsRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{log as f}from"../../core/log/index.js";import{toolCallToInvoke as k}from"../../core/mcp/tools.js";const E=new Set(["contact_search","session_search","message_history","message_search","group_create","group_detail_read","group_leave_self","group_member_add","group_member_remove","group_member_role_update","group_all_members_muted_update","group_member_speaking_update","group_dissolve","send_msg","delete_msg","agent_api_create","agent_category_list","agent_category_create","agent_category_update","agent_category_assign","agent_api_key_rotate"]),y=3e4,I=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},files:{type:"array",items:{type:"string"},description:"Optional absolute local file paths. Each file is uploaded through Agent API OSS presign before sending."},final:{type:"boolean",description:"Whether this is the final reply for the event. Defaults to false \u2014 the event stays open while Claude continues working, and auto-completes after inactivity. Set true only when this is definitively the last message for the event."}},required:["chat_id","event_id"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},code:{type:"string"},msg:{type:"string"}},required:["event_id","status"]}},{name:"delete_message",description:"Delete a previously sent message in the same grix-claude chat.",inputSchema:{type:"object",properties:{chat_id:{type:"string"},message_id:{type:"string"}},required:["chat_id","message_id"]}},{name:"status",description:"Show grix-claude runtime status, upstream access state, bridge health, and startup hints.",inputSchema:{type:"object",properties:{}}},{name:"send",description:"Send a message to a chat session proactively, without requiring an inbound event. Use for notifications or scheduled reports.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The target chat/session id."},text:{type:"string",description:"The message text to send."}},required:["chat_id","text"]}},{name:"access_pair",description:"Forward a sender pairing approval code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"access_deny",description:"Forward a sender pairing denial code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"allow_sender",description:"Ask upstream access control to allow a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"remove_sender",description:"Ask upstream access control to remove a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"access_policy",description:"Ask upstream access control to update the sender access policy.",inputSchema:{type:"object",properties:{policy:{type:"string",enum:["allowlist","open","disabled"]}},required:["policy"]}},{name:"grix_query",description:"Search contacts, sessions, message history, or messages by keyword in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},keyword:{type:"string"},id:{type:"string"},sessionId:{type:"string"},limit:{type:"number"},offset:{type:"number"},beforeId:{type:"string"}},required:["action"]}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string"},memberIds:{type:"array",items:{type:"string"}},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer",description:"Member type (for update_member_role / update_member_speaking)."},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted (for update_member_speaking)."}},required:["action"]}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},content:{type:"string"},msgType:{type:"number"},quotedMessageId:{type:"string"},threadId:{type:"string"}},required:["sessionId","content"]}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},msgId:{type:"string"}},required:["sessionId","msgId"]}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentId:{type:"string"},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"number"}},required:["action"]}}];function q(r,e){r.setRequestHandler(w,async()=>({tools:I})),r.setRequestHandler(S,async i=>{const{name:n,arguments:t}=i.params,s=t??{};try{switch(n){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(n,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(n,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${n}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${n} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(r,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const n=String(r.text??""),t=String(r.chat_id??""),s=String(r.event_id??i.eventId),a=r.reply_to,d=r.files,_=r.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!n.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,n),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(r,e){const i=e.getActiveEvent(),n=String(r.event_id??""),t=r.status??"",s=r.code,a=r.msg;if(!n||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(n)?(e.bridge.sendEventResult(n,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(r,e){const i=String(r.chat_id??""),n=String(r.message_id??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:n},y),c(`deleted (${n})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(r){const e=r.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(r,e){const i=String(r.chat_id??""),n=String(r.text??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(n),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(r,e,i){try{const n=C[r];if(!n)throw new Error(`Unknown access control tool: ${r}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:n.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}async function O(r,e,i){try{const n=k(r,e);if(!E.has(n.action))throw new Error(`Action not allowed: ${n.action}`);const t=await i.bridge.agentInvoke(n.action,n.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}function c(r){return{content:[{type:"text",text:r}]}}export{q as registerClaudeTools};
@@ -1 +1 @@
1
- import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(t,e){this.controlURL=t.replace(/\/+$/,""),this.token=e.trim(),l.info("claude-worker-client",`Configured with control URL: ${this.controlURL}`)}async post(t,e,s){if(!this.isConfigured())throw new Error("worker control not configured");const i=new AbortController,o=setTimeout(()=>i.abort(),s);try{const r=await fetch(`${this.controlURL}${t}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.token}`},body:JSON.stringify(e),signal:i.signal}),n=await r.text(),a=n.trim()?JSON.parse(n):{};if(!r.ok)throw new Error(a.error||`worker control failed ${r.status}`);return a}finally{clearTimeout(o)}}isRetryableError(t){const e=t instanceof Error?t.message:String(t);return/fetch failed|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|aborted/i.test(e)}async postWithRetry(t,e,s,i=1){let o;for(let r=0;r<=i;r++)try{return r>0&&l.info("claude-worker-client",`Retrying ${t} attempt=${r+1}`),await this.post(t,e,s)}catch(n){if(o=n,r>=i||!this.isRetryableError(n))break;await new Promise(a=>setTimeout(a,150))}throw o instanceof Error?o:new Error(String(o))}async deliverEvent(t){return this.postWithRetry("/v1/worker/deliver-event",{payload:t},1e4,1)}async deliverStop(t){return this.postWithRetry("/v1/worker/deliver-stop",{payload:t},1e4,1)}async deliverLocalAction(t){return this.postWithRetry("/v1/worker/deliver-local-action",{payload:t},1e4,1)}async ping(){try{return await this.postWithRetry("/v1/worker/ping",{},5e3,1),!0}catch{return!1}}}export{c as ClaudeWorkerClient};
1
+ import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(r,e){this.controlURL=r.replace(/\/+$/,""),this.token=e.trim(),l.info("claude-worker-client",`Configured with control URL: ${this.controlURL}`)}async post(r,e,s){if(!this.isConfigured())throw new Error("worker control not configured");const i=new AbortController,o=setTimeout(()=>i.abort(),s);try{const t=await fetch(`${this.controlURL}${r}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.token}`},body:JSON.stringify(e),signal:i.signal}),n=await t.text(),a=n.trim()?JSON.parse(n):{};if(!t.ok)throw new Error(a.error||`worker control failed ${t.status}`);return a}finally{clearTimeout(o)}}isRetryableError(r){const e=r instanceof Error?r.message:String(r);return/fetch failed|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|aborted/i.test(e)}async postWithRetry(r,e,s,i=1){let o;for(let t=0;t<=i;t++)try{return t>0&&l.info("claude-worker-client",`Retrying ${r} attempt=${t+1}`),await this.post(r,e,s)}catch(n){if(o=n,t>=i||!this.isRetryableError(n))break;await new Promise(a=>setTimeout(a,150))}throw o instanceof Error?o:new Error(String(o))}async deliverEvent(r){return this.postWithRetry("/v1/worker/deliver-event",{payload:r},1e4,1)}async deliverStop(r){return this.postWithRetry("/v1/worker/deliver-stop",{payload:r},1e4,1)}async deliverLocalAction(r){return this.postWithRetry("/v1/worker/deliver-local-action",{payload:r},1e4,1)}async ping(){try{return await this.postWithRetry("/v1/worker/ping",{},5e3,1),!0}catch{return!1}}}export{c as ClaudeWorkerClient};
@@ -1,2 +1,2 @@
1
- import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as l}from"./protocol-contract.js";function P(e){let t=null,r=0,n=!1,i=!1;const a=v(),s=e.gatewayUrl??"http://127.0.0.1:19580/mcp";return{async start(){await F(e.command,s,e.env);const c=E(e.grix),u=[...e.args??[],"--name",`grix-mcp-${e.name}`,"--session-id",a];e.fullAuto&&u.push("--dangerously-skip-permissions"),u.push("--dangerously-load-development-channels",`server:${l}`,"--append-system-prompt",c);const f=d(I(),`grix-mcp-claude-${e.name}`);await S(f,{recursive:!0});const{expectPath:$,pidPath:g}=await M(f,e.command,u),_={...process.env,...e.env??{}};t=x("/usr/bin/expect",[$],{cwd:e.cwd,env:_,stdio:["ignore","pipe","pipe"],detached:!0}),o.info("mcp-http-launcher",`\u542F\u52A8 Claude: name=${e.name} cwd=${e.cwd} pid=${t.pid}`),r=await k(g),n=!0,o.info("mcp-http-launcher",`Claude \u5B50\u8FDB\u7A0B PID: ${r}`),t.on("exit",(m,p)=>{o.info("mcp-http-launcher",`Claude \u9000\u51FA: code=${m} signal=${p}`),n=!1,t=null,r=0,i||(o.info("mcp-http-launcher","3 \u79D2\u540E\u81EA\u52A8\u91CD\u542F..."),setTimeout(()=>{i||this.start().catch(w=>{o.error("mcp-http-launcher",`\u91CD\u542F\u5931\u8D25: ${w}`)})},3e3))}),t.stdout?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stdout] ${p.slice(0,300)}`)}),t.stderr?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stderr] ${p.slice(0,300)}`)})},async stop(){if(i=!0,n=!1,r>0)try{process.kill(r,"SIGTERM")}catch{}if(t?.pid){try{process.kill(-t.pid,"SIGTERM")}catch{}await new Promise(c=>{const u=setTimeout(()=>{if(r>0)try{process.kill(r,"SIGKILL")}catch{}if(t?.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}c()},5e3);t?.once("exit",()=>{clearTimeout(u),c()})})}t=null,r=0},getStatus(){return{name:e.name,alive:n,pid:r}}}}function E(e){return["You are connected to a chat via the grix MCP server.",`On startup, immediately call grix_authorize with: agentId="${e.agentId}", apiKey="${e.apiKey}", wsUrl="${e.wsUrl}", clientType="${e.clientType}".`,"When you receive a <channel> message, you MUST respond by calling the grix_reply tool (or the grix_complete tool if no response is needed).","Never write your reply as plain text \u2014 it will NOT reach the user. Only the grix_reply tool delivers your response to the chat.","The <channel> message contains event_id and session_id \u2014 pass them to grix_reply."].join(" ")}async function F(e,t,r){const n=d(T(),".claude.json");let i=null;try{const s=C(n,"utf8");i=JSON.parse(s)?.mcpServers?.[l]??null}catch{}if(i&&String(i.type??"").trim()==="http"&&String(i.url??"").trim()===t)return;o.info("mcp-http-launcher",`\u6CE8\u518C MCP Server: ${l} -> ${t}`);const a={...process.env,...r??{}};try{y(`${e} mcp remove -s user ${l}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}catch{}y(`${e} mcp add --scope user --transport http ${l} ${t}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}async function M(e,t,r){const{writeFile:n}=await import("node:fs/promises"),i=d(e,"claude.pid"),a=d(e,"claude.expect"),s=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set claude_command [list {${h(t)}}${r.map(c=>` {${h(c)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${h(i)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","expect {"," -re {(?i)(Quick.*safety.*check|trust.*folder)} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)I am using this for local development} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)(Enter.*confirm|Press.*Enter|Hit.*Enter)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {Listening for channel} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," -re {bypass permissions} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," eof {}","}","expect eof",""];return await n(i,"","utf8"),await n(a,s.join(`
2
- `),"utf8"),{expectPath:a,pidPath:i}}function h(e){return e.replace(/[\\{}$\[\]"]/g,"\\$&")}async function k(e,t=1e4){const{readFile:r}=await import("node:fs/promises"),n=Math.ceil(t/100);for(let i=0;i<n;i++){try{const a=await r(e,"utf8"),s=parseInt(String(a).trim(),10);if(Number.isFinite(s)&&s>0)return s}catch{}await new Promise(a=>setTimeout(a,100))}return 0}export{P as createMcpHttpLauncher};
1
+ import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as m}from"./protocol-contract.js";function P(t){let e=null,r=0,n=!1,i=!1;const a=v(),s=t.gatewayUrl??"http://127.0.0.1:19580/mcp";return{async start(){await F(t.command,s,t.env);const c=E(t.grix),u=[...t.args??[],"--name",`grix-mcp-${t.name}`,"--session-id",a];t.fullAuto&&u.push("--dangerously-skip-permissions"),u.push("--dangerously-load-development-channels",`server:${m}`,"--append-system-prompt",c);const f=d(I(),`grix-mcp-claude-${t.name}`);await S(f,{recursive:!0});const{expectPath:$,pidPath:g}=await M(f,t.command,u),_={...process.env,...t.env??{}};e=x("/usr/bin/expect",[$],{cwd:t.cwd,env:_,stdio:["ignore","pipe","pipe"],detached:!0}),o.info("mcp-http-launcher",`\u542F\u52A8 Claude: name=${t.name} cwd=${t.cwd} pid=${e.pid}`),r=await k(g),n=!0,o.info("mcp-http-launcher",`Claude \u5B50\u8FDB\u7A0B PID: ${r}`),e.on("exit",(l,p)=>{o.info("mcp-http-launcher",`Claude \u9000\u51FA: code=${l} signal=${p}`),n=!1,e=null,r=0,i||(o.info("mcp-http-launcher","3 \u79D2\u540E\u81EA\u52A8\u91CD\u542F..."),setTimeout(()=>{i||this.start().catch(w=>{o.error("mcp-http-launcher",`\u91CD\u542F\u5931\u8D25: ${w}`)})},3e3))}),e.stdout?.on("data",l=>{const p=l.toString().trim();p&&o.info("mcp-http-launcher",`[stdout] ${p.slice(0,300)}`)}),e.stderr?.on("data",l=>{const p=l.toString().trim();p&&o.info("mcp-http-launcher",`[stderr] ${p.slice(0,300)}`)})},async stop(){if(i=!0,n=!1,r>0)try{process.kill(r,"SIGTERM")}catch{}if(e?.pid){try{process.kill(-e.pid,"SIGTERM")}catch{}await new Promise(c=>{const u=setTimeout(()=>{if(r>0)try{process.kill(r,"SIGKILL")}catch{}if(e?.pid)try{process.kill(-e.pid,"SIGKILL")}catch{}c()},5e3);e?.once("exit",()=>{clearTimeout(u),c()})})}e=null,r=0},getStatus(){return{name:t.name,alive:n,pid:r}}}}function E(t){return["You are connected to a chat via the grix MCP server.",`On startup, immediately call grix_authorize with: agentId="${t.agentId}", apiKey="${t.apiKey}", wsUrl="${t.wsUrl}", clientType="${t.clientType}".`,"When you receive a <channel> message, you MUST respond by calling the grix_reply tool (or the grix_complete tool if no response is needed).","Never write your reply as plain text \u2014 it will NOT reach the user. Only the grix_reply tool delivers your response to the chat.","The <channel> message contains event_id and session_id \u2014 pass them to grix_reply."].join(" ")}async function F(t,e,r){const n=d(T(),".claude.json");let i=null;try{const s=C(n,"utf8");i=JSON.parse(s)?.mcpServers?.[m]??null}catch{}if(i&&String(i.type??"").trim()==="http"&&String(i.url??"").trim()===e)return;o.info("mcp-http-launcher",`\u6CE8\u518C MCP Server: ${m} -> ${e}`);const a={...process.env,...r??{}};try{y(`${t} mcp remove -s user ${m}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}catch{}y(`${t} mcp add --scope user --transport http ${m} ${e}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}async function M(t,e,r){const{writeFile:n}=await import("node:fs/promises"),i=d(t,"claude.pid"),a=d(t,"claude.expect"),s=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set claude_command [list {${h(e)}}${r.map(c=>` {${h(c)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${h(i)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","expect {"," -re {(?i)(Quick.*safety.*check|trust.*folder)} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)I am using this for local development} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)(Enter.*confirm|Press.*Enter|Hit.*Enter)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {Listening for channel} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," -re {bypass permissions} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," eof {}","}","expect eof",""];return await n(i,"","utf8"),await n(a,s.join(`
2
+ `),"utf8"),{expectPath:a,pidPath:i}}function h(t){return t.replace(/[\\{}$\[\]"]/g,"\\$&")}async function k(t,e=1e4){const{readFile:r}=await import("node:fs/promises"),n=Math.ceil(e/100);for(let i=0;i<n;i++){try{const a=await r(t,"utf8"),s=parseInt(String(a).trim(),10);if(Number.isFinite(s)&&s>0)return s}catch{}await new Promise(a=>setTimeout(a,100))}return 0}export{P as createMcpHttpLauncher};
@@ -1 +1 @@
1
- class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(t){this.defaultTimeoutMs=t.defaultTimeoutMs??9e4,this.onTimeout=t.onTimeout}arm(t,e){this.cancel(t);const s=e?.timeoutMs??this.defaultTimeoutMs,i=Date.now()+s,o=setTimeout(()=>{this.timers.delete(t),this.onTimeout(t).catch(()=>{})},s);return this.timers.set(t,o),i}cancel(t){const e=this.timers.get(t);e&&(clearTimeout(e),this.timers.delete(t))}has(t){return this.timers.has(t)}close(){for(const t of this.timers.values())clearTimeout(t);this.timers.clear()}}export{m as ResultTimeoutManager};
1
+ class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(e){this.defaultTimeoutMs=e.defaultTimeoutMs??9e4,this.onTimeout=e.onTimeout}arm(e,t){this.cancel(e);const s=t?.timeoutMs??this.defaultTimeoutMs,i=Date.now()+s,o=setTimeout(()=>{this.timers.delete(e),this.onTimeout(e).catch(()=>{})},s);return this.timers.set(e,o),i}cancel(e){const t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}has(e){return this.timers.has(e)}close(){for(const e of this.timers.values())clearTimeout(e);this.timers.clear()}}export{m as ResultTimeoutManager};
@@ -1,6 +1,6 @@
1
- import{execFile as j}from"node:child_process";import{createHash as A,randomUUID as R}from"node:crypto";import{closeSync as V,copyFileSync as p,cpSync as S,existsSync as d,mkdirSync as y,openSync as N,readFileSync as h,rmSync as f,statSync as m,writeFileSync as b}from"node:fs";import{join as o,resolve as I}from"node:path";import{fileURLToPath as D}from"node:url";import{promisify as O}from"node:util";import{log as G}from"../../core/log/index.js";import{resolveCliPath as _}from"../../core/util/cli-probe.js";import{bridgeDiscoveryDirectory as C,discoverDshBridgeEndpoints as M,resolveDshProfileIdentity as T}from"./profile-resolver.js";const J=O(j),L=2*1024*1024,u="@grix/dsh-bridge",F="deepseek-harness-bridge-installer",w=2,z=1e3;class se{options;command;identity;constructor(e={}){this.options=e,this.command=e.command?.trim()||"dsh",this.identity=T({dshHome:e.dshHome,profileName:e.profileName})}async status(){const e=await _(this.command),r=this.bridgeAsset(),t=this.readInstalledBridgeVersion(),n=r.version,s=M(this.identity),a=s[0]?.bridgeVersion??null,l=s[0]?.dshVersion??null,B=e?await q(e,this.options.dshHome):null;let c;return e?d(this.identity.profileRoot)?t?t!==n||this.installedBridgeContentStale(r)?c="bridge_update_required":s.length===0||a!==t||this.runningBridgePredatesInstalledContent(s[0])?c="profile_restart_required":c="ready":c="bridge_missing":c="profile_missing":c="dsh_missing",{readiness:c,command:this.command,commandPath:e,dshVersion:B,runningDshVersion:l,identity:this.identity,installedBridgeVersion:t,bundledBridgeVersion:n,runningBridgeVersion:a,endpointCount:s.length}}async install(){const e=await _(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});const r=this.bridgeAsset();return E(this.identity,async()=>{await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const t=this.readInstalledBridgeVersion();if(t===r.version&&!this.installedBridgeContentStale(r))return this.status();const n=o(this.identity.dshHome,"assets","grix-dsh-bridge");y(n,{recursive:!0,mode:448});const s=this.captureInstallBackup(n,t),a=o(n,`grix-dsh-bridge-${r.version}.tgz`);p(r.tarball,a);try{if(t===r.version&&d(this.bridgePackageRoot())&&(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),d(this.bridgePackageRoot())))throw Object.assign(new Error(`dsh plugin remove left ${u} in place; refusing to attest an unverified reinstall`),{code:"bridge_install_failed"});await this.runPluginAdd(e,a),await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const l=this.readInstalledBridgeVersion();if(l!==r.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${l??"none"}, expected ${r.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(r.integrity)}catch(l){await this.rollbackInstall(e,n,s,t);try{f(a,{force:!0})}catch{}throw Object.assign(new Error(`Bridge install failed: ${P(l)}`),{code:"bridge_install_failed"})}return this.discardInstallBackup(s),this.status()})}async uninstall(){const e=await _(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});return E(this.identity,async()=>(this.readInstalledBridgeVersion()&&await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),this.status()))}async runPluginAdd(e,r){const t=["plugin","--profile",this.identity.profileName,"add",r];let n;for(let s=1;s<=w;s++)try{await g(e,t,this.options.dshHome);return}catch(a){n=a,G.warn(F,`dsh plugin add attempt ${s}/${w} failed for profile ${this.identity.profileName}
2
- ${X(a)}`),s<w&&await new Promise(l=>setTimeout(l,z))}throw n}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,r){const t=o(e,"rollback",`${Date.now()}-${R()}`);y(t,{recursive:!0,mode:448});const n=this.bridgePackageRoot(),s=d(n);s&&S(n,o(t,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),l=d(a);l&&p(a,o(t,"package.json"));const B=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const c of B){const v=o(this.identity.profileRoot,c);d(v)&&p(v,o(t,c))}return b(o(t,"manifest.json"),`${JSON.stringify({priorVersion:r,hadBridge:s,hadPackageJson:l})}
1
+ import{execFile as A}from"node:child_process";import{createHash as R,randomUUID as V}from"node:crypto";import{closeSync as N,copyFileSync as p,cpSync as S,existsSync as d,mkdirSync as y,openSync as O,readFileSync as h,rmSync as f,statSync as m,writeFileSync as b}from"node:fs";import{join as o,resolve as I}from"node:path";import{fileURLToPath as D}from"node:url";import{promisify as G}from"node:util";import{log as C}from"../../core/log/index.js";import{resolveCliPath as B}from"../../core/util/cli-probe.js";import{bridgeDiscoveryDirectory as M,discoverDshBridgeEndpoints as T,resolveDshProfileIdentity as J}from"./profile-resolver.js";const L=G(A),F=2*1024*1024,u="@grix/dsh-bridge",z="deepseek-harness-bridge-installer",w=2,U=1e3;class se{options;command;identity;constructor(e={}){this.options=e,this.command=e.command?.trim()||"dsh",this.identity=J({dshHome:e.dshHome,profileName:e.profileName})}async status(){const e=await B(this.command),r=this.bridgeAsset(),t=this.readInstalledBridgeVersion(),n=r.version,s=T(this.identity),a=s[0]?.bridgeVersion??null,l=s[0]?.dshVersion??null,_=e?await j(e,this.options.dshHome):null;let c;return e?d(this.identity.profileRoot)?t?t!==n||this.installedBridgeContentStale(r)?c="bridge_update_required":s.length===0||a!==t||this.runningBridgePredatesInstalledContent(s[0])?c="profile_restart_required":c="ready":c="bridge_missing":c="profile_missing":c="dsh_missing",{readiness:c,command:this.command,commandPath:e,dshVersion:_,runningDshVersion:l,identity:this.identity,installedBridgeVersion:t,bundledBridgeVersion:n,runningBridgeVersion:a,endpointCount:s.length}}async install(){const e=await B(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});const r=this.bridgeAsset();return E(this.identity,async()=>{await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const t=this.readInstalledBridgeVersion();if(t===r.version&&!this.installedBridgeContentStale(r))return this.status();const n=o(this.identity.dshHome,"assets","grix-dsh-bridge");y(n,{recursive:!0,mode:448});const s=this.captureInstallBackup(n,t),a=o(n,`grix-dsh-bridge-${r.version}.tgz`);p(r.tarball,a);try{if(t===r.version&&d(this.bridgePackageRoot())&&(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),d(this.bridgePackageRoot())))throw Object.assign(new Error(`dsh plugin remove left ${u} in place; refusing to attest an unverified reinstall`),{code:"bridge_install_failed"});await this.runPluginAdd(e,a),await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const l=this.readInstalledBridgeVersion();if(l!==r.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${l??"none"}, expected ${r.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(r.integrity)}catch(l){await this.rollbackInstall(e,n,s,t);try{f(a,{force:!0})}catch{}throw Object.assign(new Error(`Bridge install failed: ${P(l)}`),{code:"bridge_install_failed"})}return this.discardInstallBackup(s),this.status()})}async uninstall(){const e=await B(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});return E(this.identity,async()=>(this.readInstalledBridgeVersion()&&await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),this.status()))}async runPluginAdd(e,r){const t=["plugin","--profile",this.identity.profileName,"add",r];let n;for(let s=1;s<=w;s++)try{await g(e,t,this.options.dshHome);return}catch(a){n=a,C.warn(z,`dsh plugin add attempt ${s}/${w} failed for profile ${this.identity.profileName}
2
+ ${X(a)}`),s<w&&await new Promise(l=>setTimeout(l,U))}throw n}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,r){const t=o(e,"rollback",`${Date.now()}-${V()}`);y(t,{recursive:!0,mode:448});const n=this.bridgePackageRoot(),s=d(n);s&&S(n,o(t,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),l=d(a);l&&p(a,o(t,"package.json"));const _=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const c of _){const v=o(this.identity.profileRoot,c);d(v)&&p(v,o(t,c))}return b(o(t,"manifest.json"),`${JSON.stringify({priorVersion:r,hadBridge:s,hadPackageJson:l})}
3
3
  `,{mode:384}),{root:t,priorVersion:r,hadBridge:s,hadPackageJson:l}}async rollbackInstall(e,r,t,n){const s=n?o(r,`grix-dsh-bridge-${n}.tgz`):null;if(s&&d(s)&&await g(e,["plugin","--profile",this.identity.profileName,"add",s],this.options.dshHome).then(()=>!0).catch(()=>!1)){this.discardInstallBackup(t);return}if(t.hadBridge&&d(o(t.root,"dsh-bridge"))){this.restoreFilesystemBackup(t),this.discardInstallBackup(t);return}n?t.hadPackageJson&&this.restoreFilesystemBackup(t):(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome).catch(()=>{}),this.cleanHalfInstalledBridge()),this.discardInstallBackup(t)}restoreFilesystemBackup(e){const r=this.bridgePackageRoot(),t=o(e.root,"dsh-bridge");e.hadBridge&&d(t)&&(f(r,{recursive:!0,force:!0}),y(o(this.identity.profileRoot,"node_modules","@grix"),{recursive:!0,mode:448}),S(t,r,{recursive:!0})),e.hadPackageJson&&d(o(e.root,"package.json"))&&p(o(e.root,"package.json"),this.profilePackageJsonPath());for(const n of["pnpm-lock.yaml","package-lock.json","yarn.lock"]){const s=o(e.root,n);d(s)&&p(s,o(this.identity.profileRoot,n))}}cleanHalfInstalledBridge(){try{f(this.bridgePackageRoot(),{recursive:!0,force:!0})}catch{}const e=this.profilePackageJsonPath();if(d(e))try{const r=JSON.parse(h(e,"utf8"));let t=!1;for(const n of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){const s=r[n];s&&typeof s=="object"&&!Array.isArray(s)&&u in s&&(delete s[u],t=!0)}t&&b(e,`${JSON.stringify(r,null,2)}
4
4
  `,{mode:384})}catch{}}discardInstallBackup(e){try{f(e.root,{recursive:!0,force:!0})}catch{}}readInstalledBridgeVersion(){const e=o(this.bridgePackageRoot(),"package.json");try{const r=JSON.parse(h(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=h(this.installedIntegrityPath(),"utf8").trim();return e.startsWith("sha512-")?e:null}catch{return null}}writeInstalledBridgeIntegrity(e){b(this.installedIntegrityPath(),`${e}
5
- `,{encoding:"utf8",mode:384})}installedBridgeContentStale(e=this.bridgeAsset()){return d(this.bridgePackageRoot())?this.readInstalledBridgeIntegrity()!==e.integrity:!0}runningBridgePredatesInstalledContent(e){try{const r=m(this.installedIntegrityPath()).mtimeMs,t=Date.parse(e.startedAt);return Number.isFinite(t)?r>t:!0}catch{return!1}}bridgeAsset(){return this.options.tarballPath?x(I(this.options.tarballPath)):$()}}function ne(i){if(i.readiness==="ready")return null;const e=i.identity.profileName,r=`dsh --profile ${e}`,t=i.endpointCount>0&&i.runningBridgeVersion&&i.installedBridgeVersion&&i.runningBridgeVersion!==i.installedBridgeVersion?`Grix Bridge in DSH profile "${e}" is running version ${i.runningBridgeVersion}, but ${i.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}`,n={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 ${i.installedBridgeVersion??"none"}, expected ${i.bundledBridgeVersion}${i.installedBridgeVersion===i.bundledBridgeVersion?", content hash mismatch":""}). Update from the toolbar, then restart the profile \u2014 dsh does not hot-load plugin upgrades.`,profile_restart_required:t};return Object.assign(new Error(n[i.readiness]),{code:i.readiness})}function oe(){return $().tarball}function $(){const i=[D(new URL("../../assets/dsh-bridge/",import.meta.url)),D(new URL("../../../dist/assets/dsh-bridge/",import.meta.url))].find(t=>d(o(t,"manifest.json")));if(!i)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(h(o(i,"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=x(o(i,e.tarball),e.bridgeVersion);if(Number(e.size)!==m(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 x(i,e){if(!d(i)||!m(i).isFile())throw Object.assign(new Error(`Grix DSH Bridge asset is missing: ${i}`),{code:"bridge_asset_missing"});if(m(i).size>L)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(i)?.[1];if(!r)throw Object.assign(new Error("Cannot determine Grix DSH Bridge version"),{code:"bridge_asset_invalid"});const t=`sha512-${A("sha512").update(h(i)).digest("base64")}`;return{tarball:i,version:r,integrity:t}}async function E(i,e){const r=C(i);y(r,{recursive:!0,mode:448});const t=o(r,"install.lock");let n=H(t);if(n===null){let s=0;try{s=Number(h(t,"utf8").trim())}catch{}let a=!1;try{a=s===0&&Date.now()-m(t).mtimeMs>5*6e4}catch{}if(a||Number.isSafeInteger(s)&&s>0&&!U(s)){try{f(t,{force:!0})}catch{}n=H(t)}}if(n===null)throw Object.assign(new Error(`Another Grix DSH Bridge install is active for profile ${i.profileName}`),{code:"bridge_install_busy"});try{return b(n,`${process.pid}
6
- `,"utf8"),await e()}finally{V(n);try{f(t,{force:!0})}catch{}}}function H(i){try{return N(i,"wx",384)}catch(e){if(e.code==="EEXIST")return null;throw Object.assign(new Error(`Cannot acquire Grix DSH Bridge install lock: ${P(e)}`),{code:"bridge_install_failed"})}}function U(i){try{return process.kill(i,0),!0}catch(e){return e.code==="EPERM"}}async function q(i,e){try{return(await g(i,["--version"],e)).trim().split(/\s+/)[0]||null}catch{return null}}async function g(i,e,r){try{return(await J(i,e,{env:{...process.env,...r?{DSH_HOME:I(r)}:{}},timeout:6e4,maxBuffer:8388608})).stdout}catch(t){const n=t&&typeof t=="object"?t:{};throw Object.assign(new Error(P(t)),{code:"dsh_command_failed",stderr:typeof n.stderr=="string"?k(n.stderr):void 0})}}function k(i){return i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]")}function P(i){const e=i&&typeof i=="object"?i:{};return k(String(e.stderr??e.message??i??"unknown error")).replace(/[\r\n]+/g," ").slice(0,1024)}function X(i){const e=i&&typeof i=="object"?i:{};return k(String(e.stderr??e.message??i??"unknown error")).slice(0,8*1024)}export{se as DshBridgeInstaller,oe as defaultBridgeTarball,ne as errorForDshBridgeReadiness};
5
+ `,{encoding:"utf8",mode:384})}installedBridgeContentStale(e=this.bridgeAsset()){return d(this.bridgePackageRoot())?this.readInstalledBridgeIntegrity()!==e.integrity:!0}runningBridgePredatesInstalledContent(e){try{const r=m(this.installedIntegrityPath()).mtimeMs,t=Date.parse(e.startedAt);return Number.isFinite(t)?r>t:!0}catch{return!1}}bridgeAsset(){return this.options.tarballPath?x(I(this.options.tarballPath)):$()}}function ne(i){if(i.readiness==="ready")return null;const e=i.identity.profileName,r=`dsh --profile ${e}`,t=i.endpointCount>0&&i.runningBridgeVersion&&i.installedBridgeVersion&&i.runningBridgeVersion!==i.installedBridgeVersion?`Grix Bridge in DSH profile "${e}" is running version ${i.runningBridgeVersion}, but ${i.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}`,n={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 ${i.installedBridgeVersion??"none"}, expected ${i.bundledBridgeVersion}${i.installedBridgeVersion===i.bundledBridgeVersion?", content hash mismatch":""}). Update from the toolbar, then restart the profile \u2014 dsh does not hot-load plugin upgrades.`,profile_restart_required:t};return Object.assign(new Error(n[i.readiness]),{code:i.readiness})}function oe(){return $().tarball}function $(){const i=[D(new URL("../../assets/dsh-bridge/",import.meta.url)),D(new URL("../../../dist/assets/dsh-bridge/",import.meta.url))].find(t=>d(o(t,"manifest.json")));if(!i)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(h(o(i,"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=x(o(i,e.tarball),e.bridgeVersion);if(Number(e.size)!==m(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 x(i,e){if(!d(i)||!m(i).isFile())throw Object.assign(new Error(`Grix DSH Bridge asset is missing: ${i}`),{code:"bridge_asset_missing"});if(m(i).size>F)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(i)?.[1];if(!r)throw Object.assign(new Error("Cannot determine Grix DSH Bridge version"),{code:"bridge_asset_invalid"});const t=`sha512-${R("sha512").update(h(i)).digest("base64")}`;return{tarball:i,version:r,integrity:t}}async function E(i,e){const r=M(i);y(r,{recursive:!0,mode:448});const t=o(r,"install.lock");let n=H(t);if(n===null){let s=0;try{s=Number(h(t,"utf8").trim())}catch{}let a=!1;try{a=s===0&&Date.now()-m(t).mtimeMs>5*6e4}catch{}if(a||Number.isSafeInteger(s)&&s>0&&!q(s)){try{f(t,{force:!0})}catch{}n=H(t)}}if(n===null)throw Object.assign(new Error(`Another Grix DSH Bridge install is active for profile ${i.profileName}`),{code:"bridge_install_busy"});try{return b(n,`${process.pid}
6
+ `,"utf8"),await e()}finally{N(n);try{f(t,{force:!0})}catch{}}}function H(i){try{return O(i,"wx",384)}catch(e){if(e.code==="EEXIST")return null;throw Object.assign(new Error(`Cannot acquire Grix DSH Bridge install lock: ${P(e)}`),{code:"bridge_install_failed"})}}function q(i){try{return process.kill(i,0),!0}catch(e){return e.code==="EPERM"}}async function ae(i,e){const r=await B(i?.trim()||"dsh");return r?j(r,e):null}async function j(i,e){try{return(await g(i,["--version"],e)).trim().split(/\s+/)[0]||null}catch{return null}}async function g(i,e,r){try{return(await L(i,e,{env:{...process.env,...r?{DSH_HOME:I(r)}:{}},timeout:6e4,maxBuffer:8388608})).stdout}catch(t){const n=t&&typeof t=="object"?t:{};throw Object.assign(new Error(P(t)),{code:"dsh_command_failed",stderr:typeof n.stderr=="string"?k(n.stderr):void 0})}}function k(i){return i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]")}function P(i){const e=i&&typeof i=="object"?i:{};return k(String(e.stderr??e.message??i??"unknown error")).replace(/[\r\n]+/g," ").slice(0,1024)}function X(i){const e=i&&typeof i=="object"?i:{};return k(String(e.stderr??e.message??i??"unknown error")).slice(0,8*1024)}export{se as DshBridgeInstaller,oe as defaultBridgeTarball,ne as errorForDshBridgeReadiness,ae as readDshCliVersion};
@@ -1,8 +1,8 @@
1
- import{mkdir as F,readFile as Y,writeFile as x}from"node:fs/promises";import{join as $}from"node:path";import{log as S}from"../../core/log/index.js";import{DEFAULT_DSH_MODELS as M}from"./toolbar-state.js";const Q="grix",g="GRIX_PROVIDER_API_KEY",N="settings.yaml",_=".credentials.yaml",O="dsh-provider",W="llm-pi-ai",k=new Map;function A(t,e){const r=(k.get(t)??Promise.resolve()).then(e,e);return k.set(t,r.catch(()=>{})),r}function f(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}class p extends Error{code="yaml_incomplete";constructor(e){super(e),this.name="IncompleteYamlError"}}async function w(t){try{return f(V(await Y(t,"utf8")))}catch(e){if(e.code==="ENOENT")return{};throw e}}async function Z(t){const e=$(t,_);return A(e,async()=>f((await w(e)).refs))}const T=1;function P(t){t.version===void 0&&(t.version=T);const e=f(t.refs);return t.refs=e,e}const K=Object.freeze({thinkingFormat:"deepseek",supportsDeveloperRole:!1,maxTokensField:"max_tokens"}),C=Object.freeze({off:null,high:"high",max:"max"});function L(t){const e=t.baseUrl?.trim(),r=t.model?.trim();if(!e||!r)return;const o=()=>({...C}),n=new Map;n.set(r,{id:r,name:r,contextWindow:1e6,reasoningEfforts:o()});for(const s of M)n.has(s.id)||n.set(s.id,{id:s.id,name:s.displayName,contextWindow:s.contextWindow,reasoningEfforts:o()});return{displayName:"Grix",apiKeyEnv:g,api:"openai-completions",baseURL:e,compat:{...K},models:[...n.values()]}}function R(t){return f(t).apiKeyEnv===g}function U(t,e){const r=f(t);if(r.displayName!==e.displayName||r.apiKeyEnv!==e.apiKeyEnv||r.api!==e.api||r.baseURL!==e.baseURL||!G(r.compat,e.compat))return!1;const o=Array.isArray(e.models)?e.models:[],n=Array.isArray(r.models)?r.models:[];if(o.length!==n.length)return!1;const s=new Map(n.map(i=>[String(i.id??""),i]));return o.every(i=>{const c=s.get(String(i.id??""));return!!c&&c.name===i.name&&Number(c.contextWindow)===Number(i.contextWindow)&&G(c.reasoningEfforts,i.reasoningEfforts)})}function G(t,e){const r=f(t),o=f(e),n=new Set([...Object.keys(r),...Object.keys(o)]);for(const s of n)if((r[s]??null)!==(o[s]??null))return!1;return!0}function tt(t){return!!t&&!!L(t)&&!!t.apiKey?.trim()}async function et(t,e,r){const o=L(r),n=r.apiKey?.trim();if(!o||!n||!e.trim())return"skipped";const s=$(t,N),i=$(t,_);return A(s,async()=>{let c,a;try{c=await w(s),a=await w(i)}catch(y){if(y instanceof p)return S.warn(O,`Refusing to rewrite incomplete DSH YAML: ${y.message}`),"skipped";throw y}const l=f(c[W]),d=f(l.providers),u=d[e];if(u!==void 0&&!R(u))return"skipped";const h=P(a);return R(u)&&U(u,o)&&h[g]===n?"unchanged":(d[e]=o,l.providers=d,c[W]=l,h[g]=n,await F(t,{recursive:!0,mode:448}),await x(s,b(c),{encoding:"utf8",mode:384}),await x(i,b(a),{encoding:"utf8",mode:384}),S.info(O,`Wrote Grix provider providerId=${e} baseURL=${o.baseURL} api=openai-completions apiKeyEnv=${g} path=${s}`),"written")})}async function nt(t,e){const r=$(t,N),o=$(t,_);return A(r,async()=>{let n,s;try{n=await w(r),s=await w(o)}catch(l){if(l instanceof p)return S.warn(O,`Refusing to rewrite incomplete DSH YAML: ${l.message}`),!1;throw l}const i=f(n[W]),c=f(i.providers);if(!R(c[e]))return!1;delete c[e],i.providers=c,n[W]=i;const a=P(s);return delete a[g],Object.keys(a).length===0&&delete s.refs,await x(r,b(n),{encoding:"utf8",mode:384}),await x(o,b(s),{encoding:"utf8",mode:384}),!0})}function V(t){const e=t.replace(/^\uFEFF/,"");H(e);const r=X(e,0);return f(r.value)}function H(t){const e=t.split(/\r?\n/);for(let r=0;r<e.length;r++){const o=e[r]??"";if(o.includes(" "))throw new p(`tab indent at line ${r+1}`);const n=o.trim();if(!n||n.startsWith("#"))continue;if(n==="---"||n==="..."||n.startsWith("%"))throw new p(`document marker at line ${r+1}`);if((o.length-o.trimStart().length)%2!==0)throw new p(`odd indent at line ${r+1}`);const i=n.startsWith("- ")?n.slice(2):n;if(i.startsWith("&")||i.startsWith("*")||i.startsWith("!!")||i.startsWith("|")||i.startsWith(">"))throw new p(`unsupported yaml construct at line ${r+1}`);const c=i.indexOf(":");if(!n.startsWith("- ")&&c===-1)throw new p(`non-mapping line ${r+1}`);const a=c===-1?i:i.slice(c+1).trim();if(a&&a!=="[]"&&a!=="{}"&&!(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))&&(a.startsWith("{")||a.startsWith("[")||a.startsWith("|")||a.startsWith(">")||a.startsWith("&")||a.startsWith("*")||a.startsWith("!!")))throw new p(`unsupported inline yaml at line ${r+1}`)}}function b(t){const e=m(t,0);return e?`${e}
2
- `:""}function X(t,e){const r=t.split(/\r?\n/),o=[];for(let s=e;s<r.length;s++){const i=r[s]??"";if(!i.trim()||i.trimStart().startsWith("#"))continue;const c=i.length-i.trimStart().length;o.push({indent:c,content:i.trim()})}if(o.length===0)return{value:{},nextLine:r.length};const n=E(o,0,o[0].indent);if(n.next<o.length)throw new p("unconsumed yaml lines");return{value:n.value,nextLine:r.length}}function E(t,e,r){if(e>=t.length||t[e].indent<r)return{value:{},next:e};if(t[e].content.startsWith("- ")){const s=[];let i=e;for(;i<t.length&&t[i].indent===r&&t[i].content.startsWith("- ");){const c=t[i].content.slice(2),a=c.indexOf(":");if(a===-1){s.push(I(c)),i+=1;continue}const l=c.slice(0,a).trim(),d=c.slice(a+1).trim(),u=r+2;if(d){const y=E(t,i+1,u),D=f(y.value);D[l]=I(d),s.push(D),i=y.next;continue}const h=E(t,i+1,u);s.push({[l]:h.value}),i=h.next}return{value:s,next:i}}const o={};let n=e;for(;n<t.length&&t[n].indent===r&&!t[n].content.startsWith("- ");){const s=t[n].content.indexOf(":");if(s===-1)throw new p(`non-mapping entry: ${t[n].content}`);const i=t[n].content.slice(0,s).trim(),c=t[n].content.slice(s+1).trim();if(c){o[i]=I(c),n+=1;continue}const a=E(t,n+1,r+2);o[i]=a.value,n=a.next}return{value:o,next:n}}function I(t){return t==="~"||t==="null"?null:t==="true"?!0:t==="false"?!1:t==="[]"?[]:t==="{}"?{}:t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/\\"/g,'"'):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t}function m(t,e){if(t==null)return"null";if(typeof t=="boolean"||typeof t=="number")return String(t);if(typeof t=="string")return v(t);if(Array.isArray(t))return t.length===0?"[]":t.map(n=>{if(n&&typeof n=="object"&&!Array.isArray(n)){const s=Object.entries(n);if(s.length===0)return`${" ".repeat(e)}- {}`;const[i,c]=s[0],l=j(c)?`${" ".repeat(e)}- ${i}: ${m(c,0)}`:`${" ".repeat(e)}- ${i}:
3
- ${m(c,e+4)}`,d=s.slice(1).map(([u,h])=>j(h)?`${" ".repeat(e+2)}${u}: ${m(h,0)}`:`${" ".repeat(e+2)}${u}:
4
- ${m(h,e+4)}`);return[l,...d].join(`
1
+ import{chmod as C,mkdir as K,readFile as V,writeFile as A}from"node:fs/promises";import{join as w}from"node:path";import{log as $}from"../../core/log/index.js";import{DEFAULT_DSH_MODELS as U}from"./toolbar-state.js";import{compareDshVersions as v}from"./dsh-version.js";const ot="grix",g="GRIX_PROVIDER_API_KEY",P="settings.yaml",I=".credentials.yaml",x="dsh-provider",W="llm-pi-ai",F=new Map;function D(t,e){const r=(F.get(t)??Promise.resolve()).then(e,e);return F.set(t,r.catch(()=>{})),r}function f(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}class p extends Error{code="yaml_incomplete";constructor(e){super(e),this.name="IncompleteYamlError"}}async function E(t){try{return f(J(await V(t,"utf8")))}catch(e){if(e.code==="ENOENT")return{};throw e}}const H="0.1.1-rc.1";function ct(t){const e=v(t,H);return e!==null&&e<0?"flat":"refs"}function b(t){return"version"in t||"refs"in t?"refs":"flat"}async function at(t){const e=w(t,I);return D(e,async()=>{const r=await E(e);return b(r)==="refs"?f(r.refs):r})}const X=1;function G(t,e){const o={...b(t)==="refs"?f(t.refs):t};if(e==="flat")return Object.keys(f(t.records)).length>0?null:{doc:o,entries:o};const n={version:X,refs:o};return t.records!==void 0&&(n.records=t.records),{doc:n,entries:o}}const z=Object.freeze({thinkingFormat:"deepseek",supportsDeveloperRole:!1,maxTokensField:"max_tokens"}),B=Object.freeze({off:null,high:"high",max:"max"});function M(t){const e=t.baseUrl?.trim(),r=t.model?.trim();if(!e||!r)return;const o=()=>({...B}),n=new Map;n.set(r,{id:r,name:r,contextWindow:1e6,reasoningEfforts:o()});for(const i of U)n.has(i.id)||n.set(i.id,{id:i.id,name:i.displayName,contextWindow:i.contextWindow,reasoningEfforts:o()});return{displayName:"Grix",apiKeyEnv:g,api:"openai-completions",baseURL:e,compat:{...z},models:[...n.values()]}}function N(t){return f(t).apiKeyEnv===g}function q(t,e){const r=f(t);if(r.displayName!==e.displayName||r.apiKeyEnv!==e.apiKeyEnv||r.api!==e.api||r.baseURL!==e.baseURL||!T(r.compat,e.compat))return!1;const o=Array.isArray(e.models)?e.models:[],n=Array.isArray(r.models)?r.models:[];if(o.length!==n.length)return!1;const i=new Map(n.map(s=>[String(s.id??""),s]));return o.every(s=>{const a=i.get(String(s.id??""));return!!a&&a.name===s.name&&Number(a.contextWindow)===Number(s.contextWindow)&&T(a.reasoningEfforts,s.reasoningEfforts)})}function T(t,e){const r=f(t),o=f(e),n=new Set([...Object.keys(r),...Object.keys(o)]);for(const i of n)if((r[i]??null)!==(o[i]??null))return!1;return!0}async function Y(t,e){await A(t,e,{encoding:"utf8",mode:384}),await C(t,384)}function ft(t){return!!t&&!!M(t)&&!!t.apiKey?.trim()}async function lt(t,e,r,o){const n=M(r),i=r.apiKey?.trim();if(!n||!i||!e.trim())return"skipped";const s=w(t,P),a=w(t,I);return D(s,async()=>{let c,l;try{c=await E(s),l=await E(a)}catch(R){if(R instanceof p)return $.warn(x,`Refusing to rewrite incomplete DSH YAML: ${R.message}`),"skipped";throw R}const u=f(c[W]),h=f(u.providers),d=h[e];if(d!==void 0&&!N(d))return"skipped";const S=b(l)===o,y=G(l,o);if(!y)return $.warn(x,'Refusing to flatten .credentials.yaml: it carries a "records" section this dsh cannot read'),"skipped";const k=y.entries;return S&&N(d)&&q(d,n)&&k[g]===i?"unchanged":(h[e]=n,u.providers=h,c[W]=u,k[g]=i,await K(t,{recursive:!0,mode:448}),await A(s,_(c),{encoding:"utf8",mode:384}),await Y(a,_(y.doc)),$.info(x,`Wrote Grix provider providerId=${e} baseURL=${n.baseURL} api=openai-completions apiKeyEnv=${g} credentialsLayout=${o} path=${s}`),"written")})}async function ut(t,e){const r=w(t,P),o=w(t,I);return D(r,async()=>{let n,i;try{n=await E(r),i=await E(o)}catch(u){if(u instanceof p)return $.warn(x,`Refusing to rewrite incomplete DSH YAML: ${u.message}`),!1;throw u}const s=f(n[W]),a=f(s.providers);if(!N(a[e]))return!1;delete a[e],s.providers=a,n[W]=s;const c=b(i),l=G(i,c);return l?(delete l.entries[g],c==="refs"&&Object.keys(l.entries).length===0&&delete l.doc.refs,await A(r,_(n),{encoding:"utf8",mode:384}),await Y(o,_(l.doc)),!0):($.warn(x,'Refusing to flatten .credentials.yaml: it carries a "records" section this dsh cannot read'),!1)})}function J(t){const e=t.replace(/^\uFEFF/,"");Q(e);const r=Z(e,0);return f(r.value)}function Q(t){const e=t.split(/\r?\n/);for(let r=0;r<e.length;r++){const o=e[r]??"";if(o.includes(" "))throw new p(`tab indent at line ${r+1}`);const n=o.trim();if(!n||n.startsWith("#"))continue;if(n==="---"||n==="..."||n.startsWith("%"))throw new p(`document marker at line ${r+1}`);if((o.length-o.trimStart().length)%2!==0)throw new p(`odd indent at line ${r+1}`);const s=n.startsWith("- ")?n.slice(2):n;if(s.startsWith("&")||s.startsWith("*")||s.startsWith("!!")||s.startsWith("|")||s.startsWith(">"))throw new p(`unsupported yaml construct at line ${r+1}`);const a=s.indexOf(":");if(!n.startsWith("- ")&&a===-1)throw new p(`non-mapping line ${r+1}`);const c=a===-1?s:s.slice(a+1).trim();if(c&&c!=="[]"&&c!=="{}"&&!(c.startsWith('"')&&c.endsWith('"')||c.startsWith("'")&&c.endsWith("'"))&&(c.startsWith("{")||c.startsWith("[")||c.startsWith("|")||c.startsWith(">")||c.startsWith("&")||c.startsWith("*")||c.startsWith("!!")))throw new p(`unsupported inline yaml at line ${r+1}`)}}function _(t){const e=m(t,0);return e?`${e}
2
+ `:""}function Z(t,e){const r=t.split(/\r?\n/),o=[];for(let i=e;i<r.length;i++){const s=r[i]??"";if(!s.trim()||s.trimStart().startsWith("#"))continue;const a=s.length-s.trimStart().length;o.push({indent:a,content:s.trim()})}if(o.length===0)return{value:{},nextLine:r.length};const n=O(o,0,o[0].indent);if(n.next<o.length)throw new p("unconsumed yaml lines");return{value:n.value,nextLine:r.length}}function O(t,e,r){if(e>=t.length||t[e].indent<r)return{value:{},next:e};if(t[e].content.startsWith("- ")){const i=[];let s=e;for(;s<t.length&&t[s].indent===r&&t[s].content.startsWith("- ");){const a=t[s].content.slice(2),c=a.indexOf(":");if(c===-1){i.push(j(a)),s+=1;continue}const l=a.slice(0,c).trim(),u=a.slice(c+1).trim(),h=r+2;if(u){const S=O(t,s+1,h),y=f(S.value);y[l]=j(u),i.push(y),s=S.next;continue}const d=O(t,s+1,h);i.push({[l]:d.value}),s=d.next}return{value:i,next:s}}const o={};let n=e;for(;n<t.length&&t[n].indent===r&&!t[n].content.startsWith("- ");){const i=t[n].content.indexOf(":");if(i===-1)throw new p(`non-mapping entry: ${t[n].content}`);const s=t[n].content.slice(0,i).trim(),a=t[n].content.slice(i+1).trim();if(a){o[s]=j(a),n+=1;continue}const c=O(t,n+1,r+2);o[s]=c.value,n=c.next}return{value:o,next:n}}function j(t){return t==="~"||t==="null"?null:t==="true"?!0:t==="false"?!1:t==="[]"?[]:t==="{}"?{}:t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/\\"/g,'"'):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t}function m(t,e){if(t==null)return"null";if(typeof t=="boolean"||typeof t=="number")return String(t);if(typeof t=="string")return tt(t);if(Array.isArray(t))return t.length===0?"[]":t.map(n=>{if(n&&typeof n=="object"&&!Array.isArray(n)){const i=Object.entries(n);if(i.length===0)return`${" ".repeat(e)}- {}`;const[s,a]=i[0],l=L(a)?`${" ".repeat(e)}- ${s}: ${m(a,0)}`:`${" ".repeat(e)}- ${s}:
3
+ ${m(a,e+4)}`,u=i.slice(1).map(([h,d])=>L(d)?`${" ".repeat(e+2)}${h}: ${m(d,0)}`:`${" ".repeat(e+2)}${h}:
4
+ ${m(d,e+4)}`);return[l,...u].join(`
5
5
  `)}return`${" ".repeat(e)}- ${m(n,0)}`}).join(`
6
- `);const r=f(t),o=Object.keys(r);return o.length===0?"{}":o.map(n=>{const s=r[n];if(j(s))return`${" ".repeat(e)}${n}: ${m(s,0)}`;const i=m(s,e+2);return`${" ".repeat(e)}${n}:
7
- ${i}`}).join(`
8
- `)}function j(t){return t==null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"||Array.isArray(t)&&t.length===0?!0:!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0}function v(t){return t===""||/[:#{}[\],&*!|>'"%@`]|^\s|\s$|^(?:true|false|null|~)$/i.test(t)||/^-?\d+(?:\.\d+)?$/.test(t)?JSON.stringify(t):t}export{_ as DSH_CREDENTIALS_FILE,g as DSH_GRIX_API_KEY_ENV,Q as DSH_GRIX_PROVIDER_ID,N as DSH_SETTINGS_FILE,p as IncompleteYamlError,tt as isDshGrixProviderConfigured,V as parseYamlMapping,Z as readDshCredentials,nt as removeDshGrixProvider,b as stringifyYamlMapping,et as writeDshGrixProvider};
6
+ `);const r=f(t),o=Object.keys(r);return o.length===0?"{}":o.map(n=>{const i=r[n];if(L(i))return`${" ".repeat(e)}${n}: ${m(i,0)}`;const s=m(i,e+2);return`${" ".repeat(e)}${n}:
7
+ ${s}`}).join(`
8
+ `)}function L(t){return t==null||typeof t=="string"||typeof t=="number"||typeof t=="boolean"||Array.isArray(t)&&t.length===0?!0:!!t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0}function tt(t){return t===""||/[:#{}[\],&*!|>'"%@`]|^\s|\s$|^(?:true|false|null|~)$/i.test(t)||/^-?\d+(?:\.\d+)?$/.test(t)?JSON.stringify(t):t}export{I as DSH_CREDENTIALS_FILE,H as DSH_CREDENTIALS_REFS_MIN_VERSION,g as DSH_GRIX_API_KEY_ENV,ot as DSH_GRIX_PROVIDER_ID,P as DSH_SETTINGS_FILE,p as IncompleteYamlError,ct as dshCredentialsLayoutFor,ft as isDshGrixProviderConfigured,J as parseYamlMapping,at as readDshCredentials,ut as removeDshGrixProvider,_ as stringifyYamlMapping,lt as writeDshGrixProvider};
@@ -0,0 +1 @@
1
+ function d(t){const e=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(String(t??"").trim());return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),...e[4]?{prerelease:e[4]}:{}}:null}function a(t,e){const r=d(t),n=d(e);return!r||!n?null:r.major-n.major||r.minor-n.minor||r.patch-n.patch||f(r.prerelease,n.prerelease)}function f(t,e){if(t===e)return 0;if(t===void 0)return 1;if(e===void 0)return-1;const r=t.split("."),n=e.split(".");for(let s=0;s<Math.max(r.length,n.length);s+=1){const i=r[s],u=n[s];if(i===u)continue;if(i===void 0)return-1;if(u===void 0)return 1;const o=/^\d+$/.test(i),c=/^\d+$/.test(u);return o&&c?Number(i)-Number(u):o!==c?o?-1:1:i<u?-1:1}return 0}export{a as compareDshVersions,d as parseDshVersion};