grix-connector 3.26.13 → 3.27.0

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.
Files changed (29) hide show
  1. package/dist/adapter/claude/claude-bridge-server.js +1 -1
  2. package/dist/adapter/claude/claude-tools.js +1 -1
  3. package/dist/adapter/claude/claude-worker-client.js +1 -1
  4. package/dist/adapter/claude/mcp-http-launcher.js +2 -2
  5. package/dist/adapter/claude/result-timeout.js +1 -1
  6. package/dist/adapter/deepseek-harness/catalog-cache.js +1 -0
  7. package/dist/adapter/deepseek-harness/event-mapper.js +1 -1
  8. package/dist/adapter/deepseek-harness/index.js +1 -1
  9. package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +2 -2
  10. package/dist/adapter/deepseek-harness/runtime-ensure.js +1 -0
  11. package/dist/adapter/deepseek-harness/toolbar-state.js +1 -1
  12. package/dist/adapter/deepseek-harness/usage.js +1 -1
  13. package/dist/assets/dsh-bridge/grix-dsh-bridge-3.27.0.tgz +0 -0
  14. package/dist/assets/dsh-bridge/manifest.json +6 -6
  15. package/dist/audit/adapters/deepseek-harness/deepseek-harness-audit-adapter.js +2 -2
  16. package/dist/bridge/bridge.js +7 -7
  17. package/dist/core/access/allowlist-store.js +1 -1
  18. package/dist/core/aibot/binding-card-meta-cache.js +1 -1
  19. package/dist/core/file-ops/list-files.js +1 -1
  20. package/dist/core/persistence/session-binding-store.js +1 -1
  21. package/dist/log.js +2 -2
  22. package/dist/mcp/stream-http/config.js +1 -1
  23. package/dist/mcp/stream-http/connection-binding.js +1 -1
  24. package/dist/mcp/stream-http/security.js +1 -1
  25. package/dist/mcp/stream-http/tool-executor.js +1 -1
  26. package/dist/mcp/stream-http/tool-registry.js +1 -1
  27. package/dist/mcp/stream-http/tool-schemas.js +1 -1
  28. package/package.json +1 -1
  29. package/dist/assets/dsh-bridge/grix-dsh-bridge-3.26.13.tgz +0 -0
@@ -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};
@@ -0,0 +1 @@
1
+ import{mkdirSync as u}from"node:fs";import{dirname as y,join as D}from"node:path";import{readJSONFile as g,writeJSONFileAtomic as P}from"../../core/util/json-file.js";import{DEFAULT_DSH_MODELS as l,DEFAULT_DSH_PROVIDER_ID as a,normalizeDshModels as m,normalizeDshProviders as p}from"./toolbar-state.js";const h=1;function v(r){return D(r,"catalog-cache.json")}function f(){return[{id:a,displayName:"DeepSeek Official"}]}function c(r){const o=g(v(r));if(!o||typeof o!="object"||Array.isArray(o))return null;const s=p(o.providers),e={},t=o.modelsByProvider;if(t&&typeof t=="object"&&!Array.isArray(t))for(const[i,n]of Object.entries(t)){const d=String(i??"").trim();d&&(e[d]=m(n))}return{schemaVersion:h,providers:s,modelsByProvider:e,updatedAt:Number.isFinite(Number(o.updatedAt))?Number(o.updatedAt):0}}function I(r){const o=c(r.dataRoot),s=o?.providers?.length?[...o.providers]:f(),e=String(r.providerId??"").trim(),t=e&&s.some(d=>d.id===e)?e:s.some(d=>d.id===a)?a:s[0]?.id||a,i=o?.modelsByProvider?.[t],n=i&&i.length>0?[...i]:[...l];return{providers:s,models:n,providerId:t,fromCache:!!o&&(o.providers.length>0||Object.keys(o.modelsByProvider).length>0)}}function O(r,o){const e=c(r)?.modelsByProvider?.[o];return e&&e.length>0?[...e]:[...l]}async function w(r){const o=p(r.providers),s=m(r.models),e=String(r.providerId??"").trim()||a,t=c(r.dataRoot),i={...t?.modelsByProvider??{}};i[e]=s;const n={schemaVersion:h,providers:o.length>0?o:t?.providers??f(),modelsByProvider:i,updatedAt:Date.now()},d=v(r.dataRoot);u(y(d),{recursive:!0,mode:448}),await P(d,n)}export{f as defaultDshCatalogProviders,v as dshCatalogCachePath,O as modelsForDshProvider,c as readDshCatalogCache,I as resolveDshCatalogForToolbar,w as writeDshCatalogCache};
@@ -1 +1 @@
1
- function a(e){return e.data&&typeof e.data=="object"?e.data:{}}function f(e){const t=a(e),n=t.chunk&&typeof t.chunk=="object"?t.chunk:t,r=String(n.type??t.chunkType??"").toLowerCase();if(e.type==="assistant/chunk:text-delta"||e.type==="assistant/chunk"&&r==="text-delta")return{kind:"text",text:String(n.delta??n.text??"")};if(e.type==="assistant/chunk:reasoning-delta"||e.type==="assistant/chunk"&&r==="reasoning-delta")return{kind:"thinking",text:String(n.delta??n.text??"")};if(e.type==="assistant/chunk:usage"||e.type==="assistant/chunk"&&r==="usage")return{kind:"usage",usage:n.usage??n};if(e.type==="assistant/message"){const o=t.message&&typeof t.message=="object"?t.message:t;return{kind:"text",text:Array.isArray(o.content)?o.content.filter(i=>i&&typeof i=="object"&&String(i.type??"")==="text").map(i=>String(i.text??"")).join(""):String(o.content??o.text??""),usage:o.usage??t.usage,payload:{committed:!0}}}if(e.type==="request/context")return{kind:"context",payload:{provider:String(t.provider??""),model:String(t.model??""),...Number.isFinite(Number(t.contextWindow))?{contextWindow:Number(t.contextWindow)}:{}}};if(e.type==="tool/call")return{kind:"tool_call",callId:String(t.callId??t.id??""),name:String(t.name??t.toolName??"tool"),input:u(t.arguments??t.input),payload:t};if(e.type==="tool/result")return{kind:"tool_result",callId:String(t.callId??t.id??""),output:p(t.result??t.output??t.message),payload:t};if(e.type==="todo/write")return{kind:"todo",payload:t};if(e.type.startsWith("compaction/"))return{kind:"compaction",payload:{eventType:e.type,...t}};if(e.type==="turn/end"){const o=t.reason,s=c(o),i=d(o);return{kind:"turn_end",reason:s,...i?{detail:i}:{},payload:t}}return{kind:"unknown",payload:t}}function c(e){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object"){const t=e.kind;if(typeof t=="string"&&t)return t}return"completed"}function d(e){if(typeof e=="string"||!e||typeof e!="object")return;const t=e,n=t.error;if(typeof n=="string"&&n.trim())return n.trim().slice(0,500);if(n&&typeof n=="object"){const r=n.message;if(typeof r=="string"&&r.trim())return r.trim().slice(0,500)}if(typeof t.message=="string"&&t.message.trim())return t.message.trim().slice(0,500)}function u(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function p(e){if(!e||typeof e!="object")return e;const t=e;return Array.isArray(t.content)?t.content.filter(r=>r&&typeof r=="object"&&String(r.type??"")==="text").map(r=>String(r.text??"")).join("")||e:t.content??e}function y(e){if(!e||typeof e!="object")return null;const t=e,n=t.event&&typeof t.event=="object"?t.event:t,r=String(n.type??n.eventType??"").trim();return r?{...n,type:r,sessionId:String(n.sessionId??t.sessionId??"").trim()||void 0,data:n.data&&typeof n.data=="object"?n.data:n}:null}export{d as finishReasonDetail,c as finishReasonKind,f as mapDshSessionEvent,y as unwrapDshSessionEvent};
1
+ function u(e){return e.data&&typeof e.data=="object"?e.data:{}}function l(e){const t=u(e),n=t.chunk&&typeof t.chunk=="object"?t.chunk:t,o=String(n.type??t.chunkType??"").toLowerCase();if(e.type==="assistant/chunk:text-delta"||e.type==="assistant/chunk"&&o==="text-delta")return{kind:"text",text:String(n.delta??n.text??"")};if(e.type==="assistant/chunk:reasoning-delta"||e.type==="assistant/chunk"&&o==="reasoning-delta")return{kind:"thinking",text:String(n.delta??n.text??"")};if(e.type==="assistant/chunk:usage"||e.type==="assistant/chunk"&&o==="usage")return{kind:"usage",usage:n.usage??n};if(e.type==="assistant/message"){const r=t.message&&typeof t.message=="object"?t.message:t;return{kind:"text",text:Array.isArray(r.content)?r.content.filter(s=>s&&typeof s=="object"&&String(s.type??"")==="text").map(s=>String(s.text??"")).join(""):String(r.content??r.text??""),usage:r.usage??t.usage,payload:{committed:!0}}}if(e.type==="request/context")return{kind:"context",payload:{provider:String(t.provider??""),model:String(t.model??""),...Number.isFinite(Number(t.contextWindow))?{contextWindow:Number(t.contextWindow)}:{}}};if(e.type==="tool/call")return{kind:"tool_call",callId:String(t.callId??t.id??""),name:String(t.name??t.toolName??"tool"),input:y(t.arguments??t.input),payload:t};if(e.type==="tool/result"){const r=t.message&&typeof t.message=="object"?t.message:void 0,i=r?.source&&typeof r.source=="object"?r.source:void 0,s=Array.isArray(r?.content)?r.content.find(c=>c&&typeof c=="object"&&String(c.type??"")==="tool-result"):void 0,a=String(t.callId??i?.callId??s?.toolCallId??t.id??""),d=g(t.result??t.output??(s?{content:s.content}:t.message));return{kind:"tool_result",callId:a,output:d,...s?.isError===!0?{isError:!0}:{},payload:t}}if(e.type==="todo/write")return{kind:"todo",payload:t};if(e.type.startsWith("compaction/"))return{kind:"compaction",payload:{eventType:e.type,...t}};if(e.type==="turn/end"){const r=t.reason,i=p(r),s=f(r);return{kind:"turn_end",reason:i,...s?{detail:s}:{},payload:t}}return{kind:"unknown",payload:t}}function p(e){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object"){const t=e.kind;if(typeof t=="string"&&t)return t}return"completed"}function f(e){if(typeof e=="string"||!e||typeof e!="object")return;const t=e,n=t.error;if(typeof n=="string"&&n.trim())return n.trim().slice(0,500);if(n&&typeof n=="object"){const o=n.message;if(typeof o=="string"&&o.trim())return o.trim().slice(0,500)}if(typeof t.message=="string"&&t.message.trim())return t.message.trim().slice(0,500)}function y(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function g(e){if(!e||typeof e!="object")return e;const t=e;return Array.isArray(t.content)?t.content.filter(o=>o&&typeof o=="object"&&String(o.type??"")==="text").map(o=>String(o.text??"")).join("")||e:t.content??e}function m(e){if(!e||typeof e!="object")return null;const t=e,n=t.event&&typeof t.event=="object"?t.event:t,o=String(n.type??n.eventType??"").trim();return o?{...n,type:o,sessionId:String(n.sessionId??t.sessionId??"").trim()||void 0,data:n.data&&typeof n.data=="object"?n.data:n}:null}export{f as finishReasonDetail,p as finishReasonKind,l as mapDshSessionEvent,m as unwrapDshSessionEvent};
@@ -1 +1 @@
1
- import{DshJsonRpcAdapter as o}from"./jsonrpc-adapter.js";import{buildDshBindingToolbarMeta as t,DEFAULT_DSH_PRESET_ID as i,DEFAULT_DSH_PRESETS as D}from"./toolbar-state.js";import{buildDshSystemPrompt as d,describeDshSystemPrompt as h}from"./system-prompt.js";import{buildDshUserPrompt as a,extractQuotedMessageMarker as m}from"./prompt-builder.js";import{TurnCorrelator as p}from"./turn-correlator.js";import{DshJsonRpcClient as x}from"./jsonrpc-client.js";import{runDshProtocolProbe as b}from"./probe.js";import{DshBridgeInstaller as _,defaultBridgeTarball as g}from"./bridge-installer.js";import{DEFAULT_DSH_PROFILE_NAME as S,discoverDshBridgeEndpoints as c,listDshProfiles as v,resolveDshConnectorProfileDataDir as T,resolveDshProfileIdentity as I,resolveDshSelectedProfileName as A}from"./profile-resolver.js";import{createDshWebProfile as B}from"./profile-catalog.js";import{DSH_GRIX_PROVIDER_ID as H,buildDshManagedProvider as L,writeDshGrixProvider as U,removeDshGrixProvider as y}from"./dsh-provider-config.js";import{disableDshPlugin as G,enableDshPlugin as J,isDshPluginRestartRequired as N,listDshPlugins as O}from"./plugin-manager.js";export{D as DEFAULT_DSH_PRESETS,i as DEFAULT_DSH_PRESET_ID,S as DEFAULT_DSH_PROFILE_NAME,H as DSH_GRIX_PROVIDER_ID,_ as DshBridgeInstaller,o as DshJsonRpcAdapter,x as DshJsonRpcClient,p as TurnCorrelator,t as buildDshBindingToolbarMeta,L as buildDshManagedProvider,d as buildDshSystemPrompt,a as buildDshUserPrompt,B as createDshWebProfile,g as defaultBridgeTarball,h as describeDshSystemPrompt,G as disableDshPlugin,c as discoverDshBridgeEndpoints,J as enableDshPlugin,m as extractQuotedMessageMarker,N as isDshPluginRestartRequired,O as listDshPlugins,v as listDshProfiles,y as removeDshGrixProvider,T as resolveDshConnectorProfileDataDir,I as resolveDshProfileIdentity,A as resolveDshSelectedProfileName,b as runDshProtocolProbe,U as writeDshGrixProvider};
1
+ import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as o,dshRuntimeEnsureBackoffMs as s,isRetryableDshRuntimeError as t}from"./runtime-ensure.js";import{DshJsonRpcAdapter as i}from"./jsonrpc-adapter.js";import{buildDshBindingToolbarMeta as a,DEFAULT_DSH_PRESET_ID as h,DEFAULT_DSH_PRESETS as d,normalizeDshModeId as m,resolveDshAgentPreset as n,resolveDshModeId as P}from"./toolbar-state.js";import{dshCatalogCachePath as p,readDshCatalogCache as x,resolveDshCatalogForToolbar as E,writeDshCatalogCache as u}from"./catalog-cache.js";import{buildDshSystemPrompt as R,describeDshSystemPrompt as _}from"./system-prompt.js";import{buildDshUserPrompt as c,extractQuotedMessageMarker as S}from"./prompt-builder.js";import{TurnCorrelator as v}from"./turn-correlator.js";import{DshJsonRpcClient as C}from"./jsonrpc-client.js";import{runDshProtocolProbe as A}from"./probe.js";import{DshBridgeInstaller as B,defaultBridgeTarball as F}from"./bridge-installer.js";import{DEFAULT_DSH_PROFILE_NAME as y,discoverDshBridgeEndpoints as L,listDshProfiles as N,resolveDshConnectorProfileDataDir as G,resolveDshProfileIdentity as k,resolveDshSelectedProfileName as w}from"./profile-resolver.js";import{createDshWebProfile as O}from"./profile-catalog.js";import{DSH_GRIX_PROVIDER_ID as q,buildDshManagedProvider as z,writeDshGrixProvider as Q,removeDshGrixProvider as V}from"./dsh-provider-config.js";import{disableDshPlugin as j,enableDshPlugin as K,isDshPluginRestartRequired as Y,listDshPlugins as Z}from"./plugin-manager.js";export{d as DEFAULT_DSH_PRESETS,h as DEFAULT_DSH_PRESET_ID,y as DEFAULT_DSH_PROFILE_NAME,q as DSH_GRIX_PROVIDER_ID,o as DSH_RUNTIME_ENSURE_MAX_ATTEMPTS,B as DshBridgeInstaller,i as DshJsonRpcAdapter,C as DshJsonRpcClient,v as TurnCorrelator,a as buildDshBindingToolbarMeta,z as buildDshManagedProvider,R as buildDshSystemPrompt,c as buildDshUserPrompt,O as createDshWebProfile,F as defaultBridgeTarball,_ as describeDshSystemPrompt,j as disableDshPlugin,L as discoverDshBridgeEndpoints,p as dshCatalogCachePath,s as dshRuntimeEnsureBackoffMs,K as enableDshPlugin,S as extractQuotedMessageMarker,Y as isDshPluginRestartRequired,t as isRetryableDshRuntimeError,Z as listDshPlugins,N as listDshProfiles,m as normalizeDshModeId,x as readDshCatalogCache,V as removeDshGrixProvider,n as resolveDshAgentPreset,E as resolveDshCatalogForToolbar,G as resolveDshConnectorProfileDataDir,P as resolveDshModeId,k as resolveDshProfileIdentity,w as resolveDshSelectedProfileName,A as runDshProtocolProbe,u as writeDshCatalogCache,Q as writeDshGrixProvider};
@@ -1,3 +1,3 @@
1
- import{createHash as H,randomUUID as M}from"node:crypto";import{EventEmitter as B}from"node:events";import{copyFileSync as X,existsSync as $,mkdirSync as Y}from"node:fs";import{dirname as Z,join as P,resolve as q}from"node:path";import{fileURLToPath as N}from"node:url";import{log as f}from"../../core/log/index.js";import{syncDefaultSkillsToDir as ee}from"../../default-skills/index.js";import{resolveCliPath as te}from"../../core/util/cli-probe.js";import{DshWireCapture as ie}from"./audit-boundary.js";import{dsmlToolCallKey as se,projectVisibleDsmlText as oe}from"./dsml-text-filter.js";import{mapDshSessionEvent as re,unwrapDshSessionEvent as ne}from"./event-mapper.js";import{buildDshUserPrompt as j,extractQuotedMessageMarker as U}from"./prompt-builder.js";import{DshProcessRuntime as ae}from"./process-runtime.js";import{DshProfileRuntime as de}from"./profile-runtime.js";import{createDshWebProfile as le}from"./profile-catalog.js";import{disableDshPlugin as ce,enableDshPlugin as he,isDshPluginRestartRequired as ue,listDshPlugins as L,markDshPluginRestartRequired as pe}from"./plugin-manager.js";import{assertSelectableDshProfileName as ge,discoverDshBridgeEndpoints as fe,listDshProfiles as me,resolveDshConnectorProfileDataDir as ve,resolveDshHome as _e,resolveDshProfileIdentity as F,resolveDshSelectedProfileName as be}from"./profile-resolver.js";import{DshBridgeInstaller as D,errorForDshBridgeReadiness as O}from"./bridge-installer.js";import{awaitDshProfileIdle as Se,ensureDshBridgeReady as Ie,prepareDshProfileBridge as ke,restartManagedProfileIfOwned as we}from"./profile-supervisor.js";import{runDshProtocolProbe as Pe}from"./probe.js";import{buildDshSystemPrompt as ye,describeDshSystemPrompt as Ce}from"./system-prompt.js";import{DshActionCoordinator as De}from"./toolbar-actions.js";import{adoptDshProfileModels as xe,adoptLiveDshProviderSelection as Te,buildDshToolbarMeta as Me,DEFAULT_DSH_MAX_TOKENS as Re,DEFAULT_DSH_MODE as Ee,DEFAULT_DSH_MODELS as Ae,DEFAULT_DSH_PRESETS as He,DEFAULT_DSH_PROVIDER_ID as V,normalizeDshPresets as Be,normalizeDshProviders as $e,permissionModeFor as W,resolveDshAgentPreset as Q,resolveDshProviderId as qe,retainRequestedDshProvider as Ne}from"./toolbar-state.js";import{TurnCorrelator as je}from"./turn-correlator.js";import{getDshSessionUsageStore as Ue,normalizeDshUsage as z}from"./usage.js";import{DSH_GRIX_PROVIDER_ID as v,buildDshManagedProvider as G}from"./dsh-provider-config.js";const m="deepseek-harness-adapter",K=20*6e4;class Le extends B{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class St extends B{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;activeTimeoutMs=K;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 De;activeWireStart=0;activeUsage=J();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;providers;presets;catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.models=i.models?.length?i.models:Ae,this.providers=[],this.presets=[...He]}async start(){this.alive=!0,this.stopped=!1,this.syncGrixProvider();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&!this.options.bindingStore.getDshSettings(this.options.aibotSessionId)?.modelId&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{modelId:this.resolveDesiredSettings().modelId}),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 Le(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 te(i),o=!!s;let l={ok:e.conversation!==!0,latency:null};if(o&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const a=await Pe({command:s,args:this.config.args,cordisPath:q(this.options.cordisPath??N(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});l={ok:!0,latency:a.latencyMs,serverName:a.serverName,serverVersion:a.serverVersion}}catch(a){l={ok:!1,latency:null,error:this.redactError(a)}}else{const a=Date.now();try{const d=new D({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),g=await Ie({installer:d,autoStart:!1}),p=O(g);if(p)throw p;const r=fe(g.identity);if(r.length!==1)throw Object.assign(new Error(r.length===0?`No live Grix Bridge endpoint in DSH profile "${g.identity.profileName}"`:`Multiple live Grix Bridge endpoints for DSH profile "${g.identity.profileName}"`),{code:r.length===0?"bridge_missing":"profile_instance_ambiguous"});l={ok:!0,latency:Date.now()-a,serverName:"grix-dsh-profile-bridge",serverVersion:r[0].bridgeVersion}}catch(d){l={ok:!1,latency:null,error:this.redactError(d)}}}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:l.ok,latency_ms:l.latency,...l.ok?{}:{error:{code:"conversation_failed",message:l.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:l.serverName,serverVersion:l.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 je(t),this.activeUsage=J(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{const i=this.ensureRuntimeWithRetry();this.runtimeStartPromise=i;try{await i}finally{this.runtimeStartPromise===i&&(this.runtimeStartPromise=null)}if(this.cancelRequested||this.active!==t)return;this.activeWireStart=this.capture?.offset??0;const s=j(e,this.injectedMessageIds);this.startTimeout(e.timeoutMs);const o=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:s.text}]});if(!o?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(o.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 l=this.callbacks.getAgentProfile(),a=this.profileRevision,d=ye({...l,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),g=Ce(d);this.runtimeGeneration+=1;const p=this.resolveIntegrationMode(),r=this.resolveSelectedProfile();if(p==="profile_bridge")try{const u=await this.attachSelectedProfile(),y=await this.healBridgeUpdate(u),k=O(y);if(k)throw k;this.pushToolbarMeta()}catch(u){throw this.settingsState="failed",this.settingsErrorCode=String(u?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),u}let n=p==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,r):void 0;p==="profile_bridge"&&!n&&(n={profileName:r,sessionId:Ve(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,n),await this.options.bindingStore.flush()),this.runtimeSessionId=n?.sessionId??Oe(this.options.aibotSessionId,this.runtimeGeneration);const h=this.profileDataDir(r),_=P(h,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new ie(_);const b=p==="embedded_jsonrpc"?new ae({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:q(this.options.cordisPath??N(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),home:h,sessionRoot:P(h,"sessions"),env:this.config.env,systemPrompt:d,settings:i,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new de({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:r,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:n?.sessionCreated===!0,lastAckCursor:n?.eventCursor??0,systemPrompt:d,settings:i,managedProvider:i.providerId===v?G(this.options.provider??{}):void 0,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:u=>this.handleBridgeApproval(u),onCursorAck:u=>{!n||u<=n.eventCursor||(n={...n,eventCursor:u},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,n))}});this.runtime=b,this.bridgeAckCursor=n?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const u=await b.start();if(!b.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});b.client?.on("notification",(S,I)=>this.onNotification(S,I)),b.client?.on("protocolError",S=>this.onProtocolError(S)),b.onExit(()=>this.onRuntimeExit()),b.client?.activateNotifications?.();let y=!1;if(p==="profile_bridge"){const S=$e(u.providers),I=Te({requestedProviderId:i.providerId,liveProviders:S,liveSelectedProvider:String(u.selectedProvider??"")});this.providers=Ne(S,I.providerId,this.providers),i={...i,providerId:I.providerId},y=I.persistFallback;const x=I.providerId,R=Object.prototype.hasOwnProperty.call(u,"models")?u.models:void 0,E=!!this.catalogProviderId&&!!x&&x!==this.catalogProviderId;this.models=xe({current:this.models,fetched:R,providerChanged:E}),(R!==void 0||E)&&(this.catalogProviderId=x||this.catalogProviderId);const T=String(u.selectedModel??"");T&&T!==i.modelId&&(i={...i,modelId:T});const A=Be(u.presets);A.length>0&&(this.presets=A);const C=String(u.selectedPreset??"");C&&C!==i.agentPreset&&(i={...i,agentPreset:C},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,C))}const k=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),w={};y&&(k?.providerId??"")!==(i.providerId??"")&&(w.providerId=i.providerId),(k?.modelId??"")!==i.modelId&&(w.modelId=i.modelId),(w.providerId||w.modelId)&&(i.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,w)??i.revision,await this.options.bindingStore.flush(),f.warn(m,`replaced unavailable persisted DSH catalog selection provider=${i.providerId} model=${i.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:i.revision,providerId:i.providerId??V,modelId:i.modelId,modeId:i.modeId},this.runtimeReadiness="ready",this.bridgeCapabilities=u.capabilities??null,p==="profile_bridge"&&n&&!n.sessionCreated&&(n={...n,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,n),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===i.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=a,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,f.info(m,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${g.schemaVersion} prompt_sha256=${g.sha256} prompt_length=${g.length}`),this.pushToolbarMeta()}catch(u){throw this.settingsState="failed",this.settingsErrorCode=String(u?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),u}}async ensureRuntimeWithRetry(){let e;for(let t=1;t<=2;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||s==="binding_missing"||s==="protocol_incompatible"||t===2)throw i;await this.stopRuntime(!0)}throw e}onNotification(e,t){const i=Fe(t);if(e==="session.event"){const s=ne(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&&f.debug(m,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const l=!!this.correlator?.complete;l&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,l)}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=re(e);if(t.kind==="unknown"&&!ze(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")&&f.debug(m,`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=j(this.active.inbound,this.injectedMessageIds);for(const o of s.contextIds)this.injectedMessageIds.add(o);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?t.kind==="text"?(t.payload?.committed===!0?(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.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"?(this.sendRaw("todo_snapshot",t.payload??{},"[todo updated]"),!1):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.text+=e,this.flushVisibleText(!1)}applyCommittedText(e){const t=this.active;if(e.startsWith(t.text))t.text=e;else if(!t.text.startsWith(e)){f.warn(m,`committed assistant text diverged event=${t.inbound.event_id}`);const i=U(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=U(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const o=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),l=oe(o,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(l.suppressedToolCalls);const a=l.visible;this.observeVisibleTextAfterToolCall(a);let d="";a.startsWith(i.sentText)?d=a.slice(i.sentText.length):(e||t.finalizeDsml)&&(d=a),!(!d&&!e)&&(i.seq+=1,this.callbacks.sendStreamChunk(i.inbound.event_id,i.inbound.session_id,d,i.seq,e,`${i.inbound.event_id}-dsh`,this.quotedMessageId),i.sentText=a)}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=se(i);if(t.has(s)||(t.add(s),this.markToolCallAwaitingFinalText(),f.warn(m,`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=z(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=z(e),i=this.resolveDesiredSettings(),s=this.models.find(l=>l.id===i.modelId),o=this.reportedContextCapacity??s?.contextWindow;if(o&&o>0){const l=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:l,totalTokens:o,remainingTokens:Math.max(0,o-l),usedPercentage:l/o*100,remainingPercentage:Math.max(0,100-l/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.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&(s="failed",o="DeepSeek Harness ended after a tool call without returning final assistant text",f.warn(m,`${o} event=${i.inbound.event_id}`)),i.text=i.sentText;const l=s==="failed"&&!!o?.trim();l&&(i.text+=`
1
+ import{createHash as q,randomUUID as R}from"node:crypto";import{EventEmitter as N}from"node:events";import{copyFileSync as Z,existsSync as j,mkdirSync as ee}from"node:fs";import{dirname as te,join as k,resolve as F}from"node:path";import{fileURLToPath as U}from"node:url";import{log as f}from"../../core/log/index.js";import{syncDefaultSkillsToDir as ie}from"../../default-skills/index.js";import{resolveCliPath as se}from"../../core/util/cli-probe.js";import{DshWireCapture as oe}from"./audit-boundary.js";import{dsmlToolCallKey as re,projectVisibleDsmlText as ne}from"./dsml-text-filter.js";import{mapDshSessionEvent as ae,unwrapDshSessionEvent as de}from"./event-mapper.js";import{buildDshUserPrompt as L,extractQuotedMessageMarker as O}from"./prompt-builder.js";import{DshProcessRuntime as le}from"./process-runtime.js";import{DshProfileRuntime as he}from"./profile-runtime.js";import{createDshWebProfile as ce}from"./profile-catalog.js";import{disableDshPlugin as ue,enableDshPlugin as pe,isDshPluginRestartRequired as ge,listDshPlugins as W,markDshPluginRestartRequired as fe}from"./plugin-manager.js";import{assertSelectableDshProfileName as me,discoverDshBridgeEndpoints as ve,listDshProfiles as be,resolveDshConnectorProfileDataDir as _e,resolveDshHome as Se,resolveDshProfileIdentity as V,resolveDshSelectedProfileName as Ie}from"./profile-resolver.js";import{DshBridgeInstaller as y,errorForDshBridgeReadiness as M}from"./bridge-installer.js";import{awaitDshProfileIdle as Pe,ensureDshBridgeReady as ke,prepareDshProfileBridge as we,restartManagedProfileIfOwned as ye}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 Te}from"./probe.js";import{buildDshSystemPrompt as Re,describeDshSystemPrompt as Me}from"./system-prompt.js";import{DshActionCoordinator as xe}from"./toolbar-actions.js";import{adoptDshProfileModels as Ee,adoptLiveDshProviderSelection as Ae,buildDshToolbarMeta as He,DEFAULT_DSH_MAX_TOKENS as Be,DEFAULT_DSH_MODELS as $e,DEFAULT_DSH_PRESETS as qe,DEFAULT_DSH_PROVIDER_ID as x,normalizeDshPresets as Ne,normalizeDshProviders as je,permissionModeFor as Q,resolveDshAgentPreset as z,resolveDshModeId as Fe,resolveDshProviderId as Ue,retainRequestedDshProvider as Le}from"./toolbar-state.js";import{modelsForDshProvider as Oe,resolveDshCatalogForToolbar as We,writeDshCatalogCache as Ve}from"./catalog-cache.js";import{TurnCorrelator as Ge}from"./turn-correlator.js";import{getDshSessionUsageStore as Qe,normalizeDshUsage as K}from"./usage.js";import{DSH_GRIX_PROVIDER_ID as v,buildDshManagedProvider as J}from"./dsh-provider-config.js";const m="deepseek-harness-adapter",X=20*6e4;class ze extends N{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class Mt extends N{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;activeTimeoutMs=X;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 xe;activeWireStart=0;activeUsage=Y();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=$e;providers=[];presets=[...qe];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 ze(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 se(i),o=!!s;let l={ok:e.conversation!==!0,latency:null};if(o&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const d=await Te({command:s,args:this.config.args,cordisPath:F(this.options.cordisPath??U(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});l={ok:!0,latency:d.latencyMs,serverName:d.serverName,serverVersion:d.serverVersion}}catch(d){l={ok:!1,latency:null,error:this.redactError(d)}}else{const d=Date.now();try{const a=new y({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),p=await ke({installer:a,autoStart:!1}),c=M(p);if(c)throw c;const r=ve(p.identity);if(r.length!==1)throw Object.assign(new Error(r.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:r.length===0?"bridge_missing":"profile_instance_ambiguous"});l={ok:!0,latency:Date.now()-d,serverName:"grix-dsh-profile-bridge",serverVersion:r[0].bridgeVersion}}catch(a){l={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:l.ok,latency_ms:l.latency,...l.ok?{}:{error:{code:"conversation_failed",message:l.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:l.serverName,serverVersion:l.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 Ge(t),this.activeUsage=Y(),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=L(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 l=this.callbacks.getAgentProfile(),d=this.profileRevision,a=Re({...l,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),p=Me(a);this.runtimeGeneration+=1;const c=this.resolveIntegrationMode(),r=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 n=c==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,r):void 0;c==="profile_bridge"&&!n&&(n={profileName:r,sessionId:Ye(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,n),await this.options.bindingStore.flush()),this.runtimeSessionId=n?.sessionId??Xe(this.options.aibotSessionId,this.runtimeGeneration);const u=this.profileDataDir(r),b=k(u,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new oe(b);const _=c==="embedded_jsonrpc"?new le({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:F(this.options.cordisPath??U(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),home:u,sessionRoot:k(u,"sessions"),env:this.config.env,systemPrompt:a,settings:i,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new he({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:r,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:n?.sessionCreated===!0,lastAckCursor:n?.eventCursor??0,systemPrompt:a,settings:i,managedProvider:i.providerId===v?J(this.options.provider??{}):void 0,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:g=>this.handleBridgeApproval(g),onCursorAck:g=>{!n||g<=n.eventCursor||(n={...n,eventCursor:g},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,n))}});this.runtime=_,this.bridgeAckCursor=n?.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 E=!1;if(c==="profile_bridge"){const S=je(g.providers),I=Ae({requestedProviderId:i.providerId,liveProviders:S,liveSelectedProvider:String(g.selectedProvider??"")});this.providers=Le(S,I.providerId,this.providers),i={...i,providerId:I.providerId},E=I.persistFallback;const D=I.providerId,H=Object.prototype.hasOwnProperty.call(g,"models")?g.models:void 0,B=!!this.catalogProviderId&&!!D&&D!==this.catalogProviderId;this.models=Ee({current:this.models,fetched:H,providerChanged:B}),(H!==void 0||B)&&(this.catalogProviderId=D||this.catalogProviderId);const T=String(g.selectedModel??"");T&&T!==i.modelId&&(i={...i,modelId:T});const $=Ne(g.presets);$.length>0&&(this.presets=$);const w=String(g.selectedPreset??"");w&&w!==i.agentPreset&&(i={...i,agentPreset:w},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,w))}const C=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),A=(C?.revision??0)!==i.revision,P={};!A&&E&&(C?.providerId??"")!==(i.providerId??"")&&(P.providerId=i.providerId),!A&&(C?.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(),f.warn(m,`replaced unavailable persisted DSH catalog selection provider=${i.providerId} model=${i.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:i.revision,providerId:i.providerId??x,modelId:i.modelId,modeId:i.modeId},this.runtimeReadiness="ready",this.bridgeCapabilities=g.capabilities??null,c==="profile_bridge"&&n&&!n.sessionCreated&&(n={...n,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,n),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===i.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=d,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,f.info(m,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${p.schemaVersion} prompt_sha256=${p.sha256} prompt_length=${p.length}`),await this.persistCatalogCache(i.providerId??x),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;f.warn(m,`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 Je(Ce(t))}throw e}onNotification(e,t){const i=Ke(t);if(e==="session.event"){const s=de(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&&f.debug(m,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const l=!!this.correlator?.complete;l&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,l)}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=ae(e);if(t.kind==="unknown"&&!tt(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")&&f.debug(m,`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=L(this.active.inbound,this.injectedMessageIds);for(const o of s.contextIds)this.injectedMessageIds.add(o);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?t.kind==="text"?(t.payload?.committed===!0?(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.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"?(this.sendRaw("todo_snapshot",t.payload??{},"[todo updated]"),!1):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.text+=e,this.flushVisibleText(!1)}applyCommittedText(e){const t=this.active;if(e.startsWith(t.text))t.text=e;else if(!t.text.startsWith(e)){f.warn(m,`committed assistant text diverged event=${t.inbound.event_id}`);const i=O(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=O(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const o=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),l=ne(o,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(l.suppressedToolCalls);const d=l.visible;this.observeVisibleTextAfterToolCall(d);let a="";d.startsWith(i.sentText)?a=d.slice(i.sentText.length):(e||t.finalizeDsml)&&(a=d),!(!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=d)}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=re(i);if(t.has(s)||(t.add(s),this.markToolCallAwaitingFinalText(),f.warn(m,`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(l=>l.id===i.modelId),o=this.reportedContextCapacity??s?.contextWindow;if(o&&o>0){const l=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:l,totalTokens:o,remainingTokens:Math.max(0,o-l),usedPercentage:l/o*100,remainingPercentage:Math.max(0,100-l/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.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&(s="failed",o="DeepSeek Harness ended after a tool call without returning final assistant text",f.warn(m,`${o} event=${i.inbound.event_id}`)),i.text=i.sentText;const l=s==="failed"&&!!o?.trim();l&&(i.text+=`
2
2
 
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 a=this.personaDirty&&!!this.runtime;a&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const d=`${i.inbound.event_id}-dsh`,g=(p,r,n=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,p,r,n),this.emit("eventDone",i.inbound.event_id),a&&this.rebuildRuntime("persona_changed")};this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,d).then(async()=>{await this.flushPendingFinalBridgeAck(!0),g(s,o,l)},async p=>{await this.flushPendingFinalBridgeAck(!1),g(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(p,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="pending",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 l=setTimeout(()=>{this.pendingApprovals.delete(i),o("unavailable")},3e5);l.unref?.(),this.pendingApprovals.set(i,{resolve:o,timer:l})})):"unavailable"}projectConnectorSkills(){const e=_e(this.options.dshHome??this.config.env?.DSH_HOME,{...process.env,...this.config.env}),t=P(e,"skills"),i=ee(t);i.length>0&&f.info(m,`Synced connector skills to ${t}: [${i.join(", ")}]`)}rebuildRuntime(e){if(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){f.warn(m,`${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 r=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),n=this.pendingApprovals.get(r);if(!n)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(n.timer),this.pendingApprovals.delete(r);const h=e.action_type==="exec_approve"||e.action_type==="permission_approve";return n.resolve(h?"allowed-once":"rejected"),{status:"ok",result:{approval_id:r,decision:h?"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(r){this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:this.redactError(r)}}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 r=new D({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),n=e.action_type==="dsh_install_bridge"?await r.install():await r.status();return this.runtimeReadiness=n.readiness,this.settingsErrorCode=n.readiness==="ready"?null:n.readiness,this.pushToolbarMeta(),{status:"ok",result:We(n)}}catch(r){const n=String(r?.code??"bridge_install_failed");return this.runtimeReadiness=n,this.settingsErrorCode=n,this.pushToolbarMeta(),{status:"failed",errorCode:n,errorMsg:this.redactError(r)}}}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(r){const n=String(r?.code??"resource_query_failed");return{status:n==="capability_unavailable"?"unsupported":"failed",errorCode:n,errorMsg:this.redactError(r)}}}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 r;try{r=ge(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(h){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(h)}}if(this.options.bindingStore.isDshProfileLocked(i)){const h=this.resolveSelectedProfile();return e.action_type==="create_profile"||h!==r?{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:this.finishProfileSelection(r,!1)}if(e.action_type==="create_profile")try{const h=this.options.createDshProfile?await this.options.createDshProfile(r):await le({profileName:r,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),_=h.identity?.profileName??r;return this.persistSelectedProfile(_)?(await this.flushSelectedProfile(),this.finishProfileSelection(_,h.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(h){return{status:"failed",errorCode:String(h?.code??"profile_create_failed"),errorMsg:this.redactError(h)}}return this.listProfiles().some(h=>h.id===r)?this.persistSelectedProfile(r)?(await this.flushSelectedProfile(),this.finishProfileSelection(r,!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 n=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(_=>_.id===n))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const h=Q(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?h===n?{status:"ok",result:this.presetActionResult(n,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:h===n?(this.options.bindingStore.setDshAgentPreset(i,n),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(n,!1)}):this.options.bindingStore.setDshAgentPreset(i,n)?(await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(n,!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 a=this.resolveDesiredSettings();let d;if(e.action_type==="set_provider"){const r=String(t.provider_id??"").trim();if(!this.providers.some(n=>n.id===r))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};d={providerId:r}}else if(e.action_type==="set_model"){const r=String(t.model_id??"").trim();if(!this.models.some(n=>n.id===r))return{status:"failed",errorCode:"model_not_found",errorMsg:"Requested model is not in the Harness catalog"};d={modelId:r}}else{const r=String(t.mode_id??"").trim();if(r!=="approval"&&r!=="full_auto")return{status:"failed",errorCode:"mode_invalid",errorMsg:"mode_id must be approval or full_auto"};d={modeId:r}}if((d.providerId===void 0||d.providerId===a.providerId)&&(d.modelId===void 0||d.modelId===a.modelId)&&(d.modeId===void 0||d.modeId===a.modeId)&&this.applied?.appliedRevision===a.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,d,a.revision,"already_applied",!0)};const p=this.options.bindingStore.updateDshSettings(i,d)??a.revision;if(await this.options.bindingStore.flush(),(d.providerId||d.modelId)&&(this.options.globalConfigStore?.set(this.options.agentName,{...d.providerId?{dshProviderId:d.providerId}:{},...d.modelId?{dshModelId:d.modelId}:{}}),await this.options.globalConfigStore?.flush()),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="pending",this.settingsErrorCode=null,this.pushToolbarMeta(),!this.runtime)return{status:"ok",result:this.settingsActionResult(e.action_type,d,p,"pending",!1)};try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,d,p,"applied",!0)}}catch(r){return{status:"failed",result:this.settingsActionResult(e.action_type,d,p,"failed",!1,this.redactError(r)),errorCode:"settings_apply_failed",errorMsg:this.redactError(r)}}}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 D({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:(f.info(m,`auto-updating stale Bridge profile=${e.identity.profileName} installed=${e.installedBridgeVersion??"none"} bundled=${e.bundledBridgeVersion}`),await this.prepareSelectedProfile(),this.attachSelectedProfile())}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 ke({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 flushSelectedProfile(){await this.options.bindingStore.flush(),await this.options.globalConfigStore?.flush()}listProfiles(){return me({dshHome:this.options.dshHome??this.config.env?.DSH_HOME})}pluginCommandContext(){return{dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),run:this.options.runDshCommand}}currentPlugins(){try{return L(this.pluginCommandContext())}catch{return[]}}pluginRestartRequired(){try{return ue(F({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}).profileKey)}catch{return!1}}async executePluginAction(e,t,i){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"DSH plugins require Profile Bridge mode"};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(),o=!!this.runtime;try{if(e==="dsh_list_plugins"||e==="dsh_refresh_plugins"){const g=L(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(g,!1)}}o&&await this.stopRuntime(!0);const l=F({dshHome:s.dshHome,profileName:s.profileName});await Se(l);const a=e==="dsh_enable_plugin"?await he({...s,name:String(t.name??t.plugin_name??"")}):await ce({...s,name:String(t.name??t.plugin_name??"")});let d="skipped";return a.changed&&(d=this.options.restartManagedProfile?await this.options.restartManagedProfile(a.identity.profileName):await we(new D({command:"dsh",dshHome:s.dshHome,profileName:a.identity.profileName})),pe(a.identity.profileKey,d!=="restarted")),o&&await this.rebuildRuntime("plugin_changed"),this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(a.plugins,a.changed,d)}}catch(l){return o&&!this.runtime&&!this.stopped&&await this.rebuildRuntime("plugin_changed_failed"),{status:"failed",errorCode:String(l?.code??"plugin_action_failed"),errorMsg:this.redactError(l)}}}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=be({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 ve(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=P(this.profileDataDir(e),"session-usage.json"),i=P(this.options.dataRoot,"session-usage.json");return!$(t)&&$(i)&&(Y(Z(t),{recursive:!0,mode:448}),X(i,t)),Ue(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,l){const a=this.resolveDesiredSettings(),d=a.revision||i,g={provider_id:a.providerId,model_id:a.modelId,mode_id:a.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:d};return e==="set_mode"&&(g.sandbox_mode=W(a.modeId),g.approval_policy=a.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:W(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},settingsRevision:d,settings_revision:d,sessionAlive:o,available_providers:[...this.providers],available_models:[...this.models],session_context:g,...l?{error:l}:{}}}syncGrixProvider(){const e=G(this.options.provider??{});if(e){this.providers.some(o=>o.id===v)||(this.providers=[{id:v,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===V||s===v)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:v});return}this.providers=this.providers.filter(t=>t.id!==v)}resolveDesiredSettings(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=e?.providerId??t?.dshProviderId,s=this.providers.some(a=>a.id===v)?v:void 0,o=qe(i||s,this.providers),l=[e?.modelId,t?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(a=>!!a&&this.models.some(d=>d.id===a))??"deepseek-chat";return{providerId:o,modelId:l,modeId:e?.modeId??Ee,agentPreset:Q(e?.agentPreset,this.presets),maxTokens:e?.maxTokens??this.options.maxTokens??Re,revision:e?.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,Me({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??K,this.armTimeout(this.activeTimeoutMs)}touchActivity(e=1){!this.active||!this.timeoutTimer||this.armTimeout(Math.min(this.activeTimeoutMs*e,60*6e4))}armTimeout(e){this.clearTimeout(),this.timeoutTimer=setTimeout(()=>{this.handlePromptTimeout()},e),this.timeoutTimer.unref?.()}async handlePromptTimeout(){if(!this.active)return;const e=this.active;this.clearTimeout();const t=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="pending",this.settingsErrorCode=null,this.pushToolbarMeta(),await t?.cancel(this.runtimeSessionId).catch(()=>{}),t&&!t.isConnected()&&await t.terminate().catch(()=>{}),this.intentionalRuntimeStop=!1,!(this.active!==e||this.stopped)&&(this.finishActive("failed","Harness prompt timed out and the runtime was terminated"),this.emit("exit",1))}clearTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=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 Fe(c){const e=Number(c&&typeof c=="object"?c.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function Oe(c,e){return`grix-${H("sha256").update(c).digest("hex").slice(0,12)}-${e}-${M().slice(0,8)}`}function Ve(c){return`grix-${H("sha256").update(c).digest("hex").slice(0,16)}-${M().slice(0,8)}`}function J(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function We(c){return{readiness:c.readiness,profile:c.identity.profileName,dshVersion:c.dshVersion,runningDshVersion:c.runningDshVersion,installedBridgeVersion:c.installedBridgeVersion,bundledBridgeVersion:c.bundledBridgeVersion,runningBridgeVersion:c.runningBridgeVersion,endpointCount:c.endpointCount,requiresProfileRestart:c.readiness==="profile_restart_required",compatibleDshVersions:c.compatibleDshVersions}}const Qe=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 ze(c){const e=c.data?.chunk&&typeof c.data.chunk=="object"?c.data.chunk:c.data,t=String(e?.type??"");return Qe.has(c.type)||c.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(t)}export{St as DshJsonRpcAdapter};
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 d=this.personaDirty&&!!this.runtime,a=!!this.runtime&&!!this.applied&&this.applied.appliedRevision!==this.resolveDesiredSettings().revision;d&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const p=`${i.inbound.event_id}-dsh`,c=(r,n,u=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,r,n,u),this.emit("eventDone",i.inbound.event_id),d?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,l)},async r=>{await this.flushPendingFinalBridgeAck(!1),c(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(r,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??R());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 l=setTimeout(()=>{this.pendingApprovals.delete(i),o("unavailable")},3e5);l.unref?.(),this.pendingApprovals.set(i,{resolve:o,timer:l})})):"unavailable"}projectConnectorSkills(){const e=Se(this.options.dshHome??this.config.env?.DSH_HOME,{...process.env,...this.config.env}),t=k(e,"skills"),i=ie(t);i.length>0&&f.info(m,`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){f.warn(m,`${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 r=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),n=this.pendingApprovals.get(r);if(!n)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(n.timer),this.pendingApprovals.delete(r);const u=e.action_type==="exec_approve"||e.action_type==="permission_approve";return n.resolve(u?"allowed-once":"rejected"),{status:"ok",result:{approval_id:r,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(r){this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:this.redactError(r)}}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 r=new y({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),n=e.action_type==="dsh_install_bridge"?await r.install():await r.status();return this.runtimeReadiness=n.readiness,this.settingsErrorCode=n.readiness==="ready"?null:n.readiness,this.pushToolbarMeta(),{status:"ok",result:Ze(n)}}catch(r){const n=String(r?.code??"bridge_install_failed");return this.runtimeReadiness=n,this.settingsErrorCode=n,this.pushToolbarMeta(),{status:"failed",errorCode:n,errorMsg:this.redactError(r)}}}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(r){const n=String(r?.code??"resource_query_failed");return{status:n==="capability_unavailable"?"unsupported":"failed",errorCode:n,errorMsg:this.redactError(r)}}}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 r;try{r=me(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!==r?{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:this.finishProfileSelection(r,!1)}if(e.action_type==="create_profile")try{const u=this.options.createDshProfile?await this.options.createDshProfile(r):await ce({profileName:r,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),b=u.identity?.profileName??r;return this.persistSelectedProfile(b)?(await this.flushSelectedProfile(),this.finishProfileSelection(b,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===r)?this.persistSelectedProfile(r)?(await this.flushSelectedProfile(),this.finishProfileSelection(r,!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 n=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(b=>b.id===n))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const u=z(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?u===n?{status:"ok",result:this.presetActionResult(n,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:u===n?(this.options.bindingStore.setDshAgentPreset(i,n),await this.persistGlobalToolbarDefaults({dshAgentPreset:n}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(n,!1)}):this.options.bindingStore.setDshAgentPreset(i,n)?(await this.persistGlobalToolbarDefaults({dshAgentPreset:n}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(n,!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 d=this.resolveDesiredSettings();let a;if(e.action_type==="set_provider"){const r=String(t.provider_id??"").trim();if(!this.providers.some(n=>n.id===r))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};a={providerId:r},r!==d.providerId&&(this.models=Oe(this.options.dataRoot,r),this.catalogProviderId=r,this.models.some(n=>n.id===d.modelId)||(a.modelId=this.models[0]?.id))}else if(e.action_type==="set_model"){const r=String(t.model_id??"").trim();if(!this.models.some(n=>n.id===r))return{status:"failed",errorCode:"model_not_found",errorMsg:"Requested model is not in the Harness catalog"};a={modelId:r}}else{const r=String(t.mode_id??"").trim();if(r!=="approval"&&r!=="full_auto")return{status:"failed",errorCode:"mode_invalid",errorMsg:"mode_id must be approval or full_auto"};a={modeId:r}}if((a.providerId===void 0||a.providerId===d.providerId)&&(a.modelId===void 0||a.modelId===d.modelId)&&(a.modeId===void 0||a.modeId===d.modeId)&&this.applied?.appliedRevision===d.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,a,d.revision,"already_applied",!0)};const c=this.options.bindingStore.updateDshSettings(i,a)??d.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(r){return{status:"failed",result:this.settingsActionResult(e.action_type,a,c,"failed",!1,this.redactError(r)),errorCode:"settings_apply_failed",errorMsg:this.redactError(r)}}}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 y({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:(f.info(m,`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=M(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=M(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 we({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 be({dshHome:this.options.dshHome??this.config.env?.DSH_HOME})}pluginCommandContext(){return{dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),run:this.options.runDshCommand}}currentPlugins(){try{return W(this.pluginCommandContext())}catch{return[]}}pluginRestartRequired(){try{return ge(V({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}).profileKey)}catch{return!1}}async executePluginAction(e,t,i){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"DSH plugins require Profile Bridge mode"};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(),o=!!this.runtime;try{if(e==="dsh_list_plugins"||e==="dsh_refresh_plugins"){const p=W(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(p,!1)}}o&&await this.stopRuntime(!0);const l=V({dshHome:s.dshHome,profileName:s.profileName});await Pe(l);const d=e==="dsh_enable_plugin"?await pe({...s,name:String(t.name??t.plugin_name??"")}):await ue({...s,name:String(t.name??t.plugin_name??"")});let a="skipped";return d.changed&&(a=this.options.restartManagedProfile?await this.options.restartManagedProfile(d.identity.profileName):await ye(new y({command:"dsh",dshHome:s.dshHome,profileName:d.identity.profileName})),fe(d.identity.profileKey,a!=="restarted")),o&&await this.rebuildRuntime("plugin_changed"),this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(d.plugins,d.changed,a)}}catch(l){return o&&!this.runtime&&!this.stopped&&await this.rebuildRuntime("plugin_changed_failed"),{status:"failed",errorCode:String(l?.code??"plugin_action_failed"),errorMsg:this.redactError(l)}}}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=Ie({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 _e(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=k(this.profileDataDir(e),"session-usage.json"),i=k(this.options.dataRoot,"session-usage.json");return!j(t)&&j(i)&&(ee(te(t),{recursive:!0,mode:448}),Z(i,t)),Qe(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,l){const d=this.resolveDesiredSettings(),a=d.revision||i,p={provider_id:d.providerId,model_id:d.modelId,mode_id:d.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=Q(d.modeId),p.approval_policy=d.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:Q(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,...l?{error:l}:{}}}hydrateCatalogFromCache(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=We({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 Ve({dataRoot:this.options.dataRoot,providers:this.providers,providerId:e,models:this.models})}catch(t){f.warn(m,`failed to persist DSH catalog cache: ${t instanceof Error?t.message:String(t)}`)}}syncGrixProvider(){const e=J(this.options.provider??{});if(e){this.providers.some(o=>o.id===v)||(this.providers=[{id:v,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===x||s===v)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:v});return}this.providers=this.providers.filter(t=>t.id!==v)}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===v)?v:void 0,l=Ue(s||o,this.providers),d=[t?.modelId,i?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(p=>!!p&&this.models.some(c=>c.id===p))??"deepseek-chat",a=z(t?.agentPreset??i?.dshAgentPreset,this.presets);return{providerId:l,modelId:d,modeId:Fe(e?.dshModeId,i?.dshModeId),agentPreset:a,maxTokens:t?.maxTokens??this.options.maxTokens??Be,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,He({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??X,this.armTimeout(this.activeTimeoutMs)}touchActivity(e=1){!this.active||!this.timeoutTimer||this.armTimeout(Math.min(this.activeTimeoutMs*e,60*6e4))}armTimeout(e){this.clearTimeout(),this.timeoutTimer=setTimeout(()=>{this.handlePromptTimeout()},e),this.timeoutTimer.unref?.()}async handlePromptTimeout(){if(!this.active)return;const e=this.active;this.clearTimeout();const t=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 t?.cancel(this.runtimeSessionId).catch(()=>{}),t&&!t.isConnected()&&await t.terminate().catch(()=>{}),this.intentionalRuntimeStop=!1,!(this.active!==e||this.stopped)&&(this.finishActive("failed","Harness prompt timed out and the runtime was terminated"),this.emit("exit",1))}clearTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=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 Ke(h){const e=Number(h&&typeof h=="object"?h.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function Je(h){return new Promise(e=>setTimeout(e,h))}function Xe(h,e){return`grix-${q("sha256").update(h).digest("hex").slice(0,12)}-${e}-${R().slice(0,8)}`}function Ye(h){return`grix-${q("sha256").update(h).digest("hex").slice(0,16)}-${R().slice(0,8)}`}function Y(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function Ze(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 et=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 tt(h){const e=h.data?.chunk&&typeof h.data.chunk=="object"?h.data.chunk:h.data,t=String(e?.type??"");return et.has(h.type)||h.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(t)}export{Mt as DshJsonRpcAdapter};
@@ -0,0 +1 @@
1
+ const n=3,t=new Set(["bridge_connect_failed","runtime_initialize_failed"]);function i(e){return t.has(e)}function r(e){return Math.min(2e3,400*Math.max(1,e))}export{n as DSH_RUNTIME_ENSURE_MAX_ATTEMPTS,r as dshRuntimeEnsureBackoffMs,i as isRetryableDshRuntimeError};
@@ -1 +1 @@
1
- import{DEFAULT_DSH_PROFILE_NAME as s,dshProfileDisplayName as _}from"./profile-resolver.js";const h="approval",D=16384,a="deepseek-official",v=Object.freeze([{id:"deepseek-v4-flash",displayName:"DeepSeek-V4-Flash",contextWindow:1e6},{id:"deepseek-v4-pro",displayName:"DeepSeek-V4-Pro",contextWindow:1e6}]),l="standard",p=Object.freeze([{id:"standard",displayName:"\u6807\u51C6\u6A21\u5F0F",description:"\u529F\u80FD\u5B8C\u6574\u7684\u7F16\u7801 Agent\uFF0C\u652F\u6301\u6587\u4EF6\u7F16\u8F91\u3001Shell\u3001\u6587\u4EF6\u4E0E\u7F51\u9875\u68C0\u7D22\u3001Skills\u3001\u8BA1\u5212\u3001\u76EE\u6807\u3001\u5B50\u4EE3\u7406\u548C\u5DE5\u4F5C\u6D41\u3002"},{id:"code",displayName:"PTC \u6A21\u5F0F",description:"\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u901A\u8FC7 Code Mode SDK \u5448\u73B0\u5DE5\u5177\uFF0C\u8BA9\u6A21\u578B\u7528\u4E00\u4E2A TypeScript \u7A0B\u5E8F\u7EC4\u5408\u591A\u6B65\u64CD\u4F5C\u3002"},{id:"minimal",displayName:"\u6781\u7B80\u6A21\u5F0F",description:"\u4EC5\u63D0\u4F9B\u6301\u4E45 bash \u4E0E str_replace_editor \u7684\u53CC\u5DE5\u5177\u7F16\u7801 Agent\u3002"},{id:"cordis",displayName:"\u521B\u9020\u6A21\u5F0F",description:"\u7528\u4E8E\u521B\u5EFA\u81EA\u5B9A\u4E49 Agent preset\uFF1A\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u63D0\u4F9B\u8FD0\u884C\u65F6\u68C0\u67E5\u3001\u63D2\u4EF6\u5B9E\u9A8C\u548C preset \u521B\u4F5C\u6307\u5BFC\u3002"}]);function x(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const i=r,t=String(i.id??"").trim();return t?[{id:t,displayName:String(i.displayName??i.name??t)}]:[]}):[]}function b(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const i=r,t=String(i.id??"").trim();if(!t)return[];const d=Number(i.contextWindow);return[{id:t,displayName:String(i.displayName??i.name??t),contextWindow:Number.isSafeInteger(d)&&d>0?d:1e6}]}):[]}function A(e){return e.fetched!==void 0?b(e.fetched):e.providerChanged?[]:[...e.current]}function P(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const i=r,t=String(i.id??"").trim();if(!t||i.broken)return[];const d=String(i.description??"").trim();return[{id:t,displayName:String(i.displayName??i.name??t),...d?{description:d}:{}}]}):[]}const c=Object.freeze([{id:s,displayName:_(s),webApp:!0}]);function k(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const i=r,t=String(i.id??"").trim();return t?[{id:t,displayName:String(i.displayName??i.name??_(t)),...i.webApp===!0?{webApp:!0}:{}}]:[]}):[]}function f(e,r){const i=String(e??"").trim();return i&&r.some(t=>t.id===i)?i:r.some(t=>t.id===l)?l:r[0]?.id||l}function u(e,r){const i=String(e??"").trim();return i&&r.some(t=>t.id===i)?i:r.some(t=>t.id===a)?a:r[0]?.id||a}function N(e){const r=String(e.requestedProviderId??"").trim();if(!!r&&e.liveProviders.some(o=>o.id===r))return{providerId:r,persistFallback:!1};if(r)return{providerId:r,persistFallback:!1};const t=String(e.liveSelectedProvider??"").trim();return{providerId:u(t||void 0,e.liveProviders),persistFallback:!0}}function y(e,r,i){const t=String(r??"").trim(),d=e.length>0?[...e]:[];if(t&&!d.some(o=>o.id===t)){const o=i.find(n=>n.id===t);o&&d.unshift(o)}return d}function I(e){const r=e.applied,i=e.state??(r?r.appliedRevision===e.desired.revision?"applied":"pending":"applied"),t=e.runtimeReadiness??"unknown",d=e.providers??[],o=e.presets??p,n=u(e.desired.providerId,d),m=f(e.desired.agentPreset,o),g=r!=null||i==="pending"||i==="failed";return{provider_id:n,model_id:e.desired.modelId,mode_id:e.desired.modeId,agent_preset_id:m,agent_preset_locked:e.agentPresetLocked===!0,available_providers:[...d],available_models:[...e.models??v],available_presets:[...o],available_modes:[{id:"approval",label:"\u5BA1\u6279\uFF08\u5DE5\u4F5C\u533A\u5185\u81EA\u52A8\uFF0C\u8D8A\u754C\u5931\u8D25\uFF09"},{id:"full_auto",label:"\u81EA\u52A8\uFF08\u5168\u6743\u9650\uFF09"}],settings_revision:e.desired.revision,...g?{applied_provider_id:r?.providerId??null,applied_model_id:r?.modelId??null,applied_mode_id:r?.modeId??null,applied_settings_revision:r?.appliedRevision??null}:{},settings_state:i,settings_error_code:e.errorCode??null,context_window:e.contextWindow??null,provider_quota:e.providerQuota??null,dsh_integration_mode:e.integrationMode??"profile_bridge",dsh_profile:e.profileName??s,available_profiles:[...e.profiles??c],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0&&e.profileCreate!==!1,dsh_plugins:[...e.plugins??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0,dsh_runtime_readiness:t,dsh_bridge_action_required:["dsh_missing","profile_missing","bridge_missing","bridge_update_required"].includes(t)?"install_bridge":t==="profile_restart_required"?"restart_profile":null,dsh_profile_restart_required:t==="profile_restart_required",dsh_bridge_capabilities:e.bridgeCapabilities??null}}function E(e){return e==="full_auto"?"danger-full-access":"workspace-write"}function L(e){return{agent_preset_id:f(e.agentPreset,p),agent_preset_locked:e.agentPresetLocked===!0,available_presets:[...p],dsh_profile:e.profileName??s,available_profiles:[...e.profiles??c],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0,dsh_plugins:[...e.plugins??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0}}export{D as DEFAULT_DSH_MAX_TOKENS,h as DEFAULT_DSH_MODE,v as DEFAULT_DSH_MODELS,p as DEFAULT_DSH_PRESETS,l as DEFAULT_DSH_PRESET_ID,c as DEFAULT_DSH_PROFILES,a as DEFAULT_DSH_PROVIDER_ID,A as adoptDshProfileModels,N as adoptLiveDshProviderSelection,L as buildDshBindingToolbarMeta,I as buildDshToolbarMeta,b as normalizeDshModels,P as normalizeDshPresets,k as normalizeDshProfiles,x as normalizeDshProviders,E as permissionModeFor,f as resolveDshAgentPreset,u as resolveDshProviderId,y as retainRequestedDshProvider};
1
+ import{DEFAULT_DSH_PROFILE_NAME as s,dshProfileDisplayName as f}from"./profile-resolver.js";const m="approval",x=16384,a="deepseek-official",n=Object.freeze([{id:"deepseek-v4-flash",displayName:"DeepSeek-V4-Flash",contextWindow:1e6},{id:"deepseek-v4-pro",displayName:"DeepSeek-V4-Pro",contextWindow:1e6}]),p="standard",_=Object.freeze([{id:"standard",displayName:"\u6807\u51C6\u6A21\u5F0F",description:"\u529F\u80FD\u5B8C\u6574\u7684\u7F16\u7801 Agent\uFF0C\u652F\u6301\u6587\u4EF6\u7F16\u8F91\u3001Shell\u3001\u6587\u4EF6\u4E0E\u7F51\u9875\u68C0\u7D22\u3001Skills\u3001\u8BA1\u5212\u3001\u76EE\u6807\u3001\u5B50\u4EE3\u7406\u548C\u5DE5\u4F5C\u6D41\u3002"},{id:"code",displayName:"PTC \u6A21\u5F0F",description:"\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u901A\u8FC7 Code Mode SDK \u5448\u73B0\u5DE5\u5177\uFF0C\u8BA9\u6A21\u578B\u7528\u4E00\u4E2A TypeScript \u7A0B\u5E8F\u7EC4\u5408\u591A\u6B65\u64CD\u4F5C\u3002"},{id:"minimal",displayName:"\u6781\u7B80\u6A21\u5F0F",description:"\u4EC5\u63D0\u4F9B\u6301\u4E45 bash \u4E0E str_replace_editor \u7684\u53CC\u5DE5\u5177\u7F16\u7801 Agent\u3002"},{id:"cordis",displayName:"\u521B\u9020\u6A21\u5F0F",description:"\u7528\u4E8E\u521B\u5EFA\u81EA\u5B9A\u4E49 Agent preset\uFF1A\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u63D0\u4F9B\u8FD0\u884C\u65F6\u68C0\u67E5\u3001\u63D2\u4EF6\u5B9E\u9A8C\u548C preset \u521B\u4F5C\u6307\u5BFC\u3002"}]);function u(e){return e==="full_auto"||e==="approval"?e:void 0}function I(e,r){return u(e)??u(r)??m}function A(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const d=r,i=String(d.id??"").trim();return i?[{id:i,displayName:String(d.displayName??d.name??i)}]:[]}):[]}function S(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const d=r,i=String(d.id??"").trim();if(!i)return[];const o=Number(d.contextWindow);return[{id:i,displayName:String(d.displayName??d.name??i),contextWindow:Number.isSafeInteger(o)&&o>0?o:1e6}]}):[]}function P(e){return e.fetched!==void 0?S(e.fetched):e.providerChanged?[]:[...e.current]}function k(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const d=r,i=String(d.id??"").trim();if(!i||d.broken)return[];const o=String(d.description??"").trim();return[{id:i,displayName:String(d.displayName??d.name??i),...o?{description:o}:{}}]}):[]}const g=Object.freeze([{id:s,displayName:f(s),webApp:!0}]);function N(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const d=r,i=String(d.id??"").trim();return i?[{id:i,displayName:String(d.displayName??d.name??f(i)),...d.webApp===!0?{webApp:!0}:{}}]:[]}):[]}function v(e,r){const d=String(e??"").trim();return d&&r.some(i=>i.id===d)?d:r.some(i=>i.id===p)?p:r[0]?.id||p}function c(e,r){const d=String(e??"").trim();return d&&r.some(i=>i.id===d)?d:r.some(i=>i.id===a)?a:r[0]?.id||a}function y(e){const r=String(e.requestedProviderId??"").trim();if(!!r&&e.liveProviders.some(t=>t.id===r))return{providerId:r,persistFallback:!1};if(r)return{providerId:r,persistFallback:!1};const i=String(e.liveSelectedProvider??"").trim();return{providerId:c(i||void 0,e.liveProviders),persistFallback:!0}}function E(e,r,d){const i=String(r??"").trim(),o=e.length>0?[...e]:[];if(i&&!o.some(t=>t.id===i)){const t=d.find(l=>l.id===i);t&&o.unshift(t)}return o}function L(e){const r=e.applied,d=e.state??(r?r.appliedRevision===e.desired.revision?"applied":"pending":"applied"),i=e.runtimeReadiness??"unknown",o=e.providers??[],t=e.presets??_,l=c(e.desired.providerId,o),b=v(e.desired.agentPreset,t),h=r!=null||d==="pending"||d==="failed";return{provider_id:l,model_id:e.desired.modelId,mode_id:e.desired.modeId,agent_preset_id:b,agent_preset_locked:e.agentPresetLocked===!0,available_providers:[...o],available_models:[...e.models??n],available_presets:[...t],available_modes:[{id:"approval",label:"\u5BA1\u6279\uFF08\u5DE5\u4F5C\u533A\u5185\u81EA\u52A8\uFF0C\u8D8A\u754C\u5931\u8D25\uFF09"},{id:"full_auto",label:"\u81EA\u52A8\uFF08\u5168\u6743\u9650\uFF09"}],settings_revision:e.desired.revision,...h?{applied_provider_id:r?.providerId??null,applied_model_id:r?.modelId??null,applied_mode_id:r?.modeId??null,applied_settings_revision:r?.appliedRevision??null}:{},settings_state:d,settings_error_code:e.errorCode??null,context_window:e.contextWindow??null,provider_quota:e.providerQuota??null,dsh_integration_mode:e.integrationMode??"profile_bridge",dsh_profile:e.profileName??s,available_profiles:[...e.profiles??g],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0&&e.profileCreate!==!1,dsh_plugins:[...e.plugins??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0,dsh_runtime_readiness:i,dsh_bridge_action_required:["dsh_missing","profile_missing","bridge_missing","bridge_update_required"].includes(i)?"install_bridge":i==="profile_restart_required"?"restart_profile":null,dsh_profile_restart_required:i==="profile_restart_required",dsh_bridge_capabilities:e.bridgeCapabilities??null}}function M(e){return e==="full_auto"?"danger-full-access":"workspace-write"}function q(e){const r=e.providers??[],d=c(e.providerId,r),i=[...e.models??n],o=String(e.modelId??"").trim()||i[0]?.id||n[0].id,t=e.modeId==="full_auto"?"full_auto":m;return{agent_preset_id:v(e.agentPreset,_),agent_preset_locked:e.agentPresetLocked===!0,available_presets:[..._],dsh_profile:e.profileName??s,available_profiles:[...e.profiles??g],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0,dsh_plugins:[...e.plugins??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0,provider_id:d,model_id:o,mode_id:t,available_providers:[...r],available_models:i,available_modes:[{id:"approval",label:"\u5BA1\u6279\uFF08\u5DE5\u4F5C\u533A\u5185\u81EA\u52A8\uFF0C\u8D8A\u754C\u5931\u8D25\uFF09"},{id:"full_auto",label:"\u81EA\u52A8\uFF08\u5168\u6743\u9650\uFF09"}]}}export{x as DEFAULT_DSH_MAX_TOKENS,m as DEFAULT_DSH_MODE,n as DEFAULT_DSH_MODELS,_ as DEFAULT_DSH_PRESETS,p as DEFAULT_DSH_PRESET_ID,g as DEFAULT_DSH_PROFILES,a as DEFAULT_DSH_PROVIDER_ID,P as adoptDshProfileModels,y as adoptLiveDshProviderSelection,q as buildDshBindingToolbarMeta,L as buildDshToolbarMeta,u as normalizeDshModeId,S as normalizeDshModels,k as normalizeDshPresets,N as normalizeDshProfiles,A as normalizeDshProviders,M as permissionModeFor,v as resolveDshAgentPreset,I as resolveDshModeId,c as resolveDshProviderId,E as retainRequestedDshProvider};
@@ -1 +1 @@
1
- import{chmodSync as d,mkdirSync as T}from"node:fs";import{dirname as f}from"node:path";import{readJSONFile as _,writeJSONFileAtomic as y}from"../../core/util/json-file.js";const m=()=>({inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0}),n=t=>Number.isFinite(Number(t))?Math.max(0,Number(t)):0;function S(t){const e=t&&typeof t=="object"?t:{};return{inputTokens:n(e.inputTokens??e.input_tokens??e.prompt_tokens),outputTokens:n(e.outputTokens??e.output_tokens??e.completion_tokens),cacheReadInputTokens:n(e.cacheReadInputTokens??e.cacheReadTokens??e.cache_read_input_tokens??e.prompt_cache_hit_tokens),cacheCreationInputTokens:n(e.cacheCreationInputTokens??e.cacheWriteTokens??e.cache_creation_input_tokens??e.prompt_cache_miss_tokens),reasoningTokens:n(e.reasoningTokens??e.reasoning_tokens)}}class g{filePath;values=new Map;writePromise=Promise.resolve();constructor(e){this.filePath=e}load(){const e=_(this.filePath);if(!(!e||typeof e!="object"||Array.isArray(e)))for(const[a,s]of Object.entries(e))s?.sessionId&&this.values.set(a,s)}get(e){return this.values.get(e)??{sessionId:e,turns:0,total:m(),models:{},lastCommittedSeqByGeneration:{},updatedAt:0}}commit(e,a,s,u,l){const h=a,o=this.get(e);if((o.lastCommittedSeqByGeneration[h]??-1)>=s)return!1;const i=S(l),p=r=>{r.inputTokens+=i.inputTokens,r.outputTokens+=i.outputTokens,r.cacheReadInputTokens+=i.cacheReadInputTokens,r.cacheCreationInputTokens+=i.cacheCreationInputTokens};p(o.total);const c=o.models[u]??{turns:0,total:m()};return p(c.total),c.turns+=1,o.models[u]=c,o.turns+=1,o.lastCommittedSeqByGeneration[h]=s,o.updatedAt=Date.now(),this.values.set(e,o),this.scheduleWrite(),!0}delete(e){this.values.delete(e),this.scheduleWrite()}async flush(){await this.writePromise}scheduleWrite(){this.writePromise=this.writePromise.then(async()=>{T(f(this.filePath),{recursive:!0,mode:448}),await y(this.filePath,Object.fromEntries(this.values));try{d(this.filePath,384)}catch{}})}}const k=new Map;function I(t){let e=k.get(t);return e||(e=new g(t),e.load(),k.set(t,e)),e}export{g as DshSessionUsageStore,I as getDshSessionUsageStore,S as normalizeDshUsage};
1
+ import{chmodSync as d,mkdirSync as T}from"node:fs";import{dirname as f}from"node:path";import{readJSONFile as _,writeJSONFileAtomic as y}from"../../core/util/json-file.js";const m=()=>({inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0}),i=t=>Number.isFinite(Number(t))?Math.max(0,Number(t)):0;function S(t){const e=t&&typeof t=="object"?t:{},s=i(e.cacheReadInputTokens??e.cacheReadTokens??e.cache_read_input_tokens??e.prompt_cache_hit_tokens),o=e.inputTokens??e.input_tokens??e.prompt_cache_miss_tokens;return{inputTokens:o!==void 0?i(o):Math.max(0,i(e.prompt_tokens)-s),outputTokens:i(e.outputTokens??e.output_tokens??e.completion_tokens),cacheReadInputTokens:s,cacheCreationInputTokens:i(e.cacheCreationInputTokens??e.cacheWriteTokens??e.cache_creation_input_tokens),reasoningTokens:i(e.reasoningTokens??e.reasoning_tokens)}}class g{filePath;values=new Map;writePromise=Promise.resolve();constructor(e){this.filePath=e}load(){const e=_(this.filePath);if(!(!e||typeof e!="object"||Array.isArray(e)))for(const[s,o]of Object.entries(e))o?.sessionId&&this.values.set(s,o)}get(e){return this.values.get(e)??{sessionId:e,turns:0,total:m(),models:{},lastCommittedSeqByGeneration:{},updatedAt:0}}commit(e,s,o,u,l){const h=s,n=this.get(e);if((n.lastCommittedSeqByGeneration[h]??-1)>=o)return!1;const a=S(l),p=r=>{r.inputTokens+=a.inputTokens,r.outputTokens+=a.outputTokens,r.cacheReadInputTokens+=a.cacheReadInputTokens,r.cacheCreationInputTokens+=a.cacheCreationInputTokens};p(n.total);const c=n.models[u]??{turns:0,total:m()};return p(c.total),c.turns+=1,n.models[u]=c,n.turns+=1,n.lastCommittedSeqByGeneration[h]=o,n.updatedAt=Date.now(),this.values.set(e,n),this.scheduleWrite(),!0}delete(e){this.values.delete(e),this.scheduleWrite()}async flush(){await this.writePromise}scheduleWrite(){this.writePromise=this.writePromise.then(async()=>{T(f(this.filePath),{recursive:!0,mode:448}),await y(this.filePath,Object.fromEntries(this.values));try{d(this.filePath,384)}catch{}})}}const k=new Map;function C(t){let e=k.get(t);return e||(e=new g(t),e.load(),k.set(t,e)),e}export{g as DshSessionUsageStore,C as getDshSessionUsageStore,S as normalizeDshUsage};
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "3.26.13",
4
- "tarball": "grix-dsh-bridge-3.26.13.tgz",
5
- "size": 11973,
6
- "unpackedSize": 46345,
7
- "shasum": "0df4ddbc7f0d4a0b930e0b4e86665d327eacd5a7",
8
- "integrity": "sha512-kwC2kGPOrwTP6pi2XH1iTGgN/G5qKMaw23bjlbSovs5liwUlkmqF1qAQ/yeQ9RI9+6YnV5Ct9Zq/zv6N5LAmzQ=="
3
+ "bridgeVersion": "3.27.0",
4
+ "tarball": "grix-dsh-bridge-3.27.0.tgz",
5
+ "size": 11972,
6
+ "unpackedSize": 46341,
7
+ "shasum": "da7510c426124926137ed8e1c9f2fc071ad65c85",
8
+ "integrity": "sha512-7ZuK2bQkcq16St6xsGsci66jZ360fyis7ih0jYRVG7BWGJedmeeh8EIGmhMvsZhCfYyZsXc3kdskggfRAC/HAg=="
9
9
  }