grix-connector 3.21.0 → 3.22.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.
- package/dist/adapter/claude/claude-bridge-server.js +1 -1
- package/dist/adapter/claude/claude-tools.js +1 -1
- package/dist/adapter/claude/claude-worker-client.js +1 -1
- package/dist/adapter/claude/mcp-http-launcher.js +2 -2
- package/dist/adapter/claude/result-timeout.js +1 -1
- package/dist/adapter/claude/session-history.js +2 -2
- package/dist/adapter/codewhale/session-history.js +1 -0
- package/dist/adapter/codex/session-history.js +1 -0
- package/dist/adapter/opencode/opencode-adapter.js +6 -5
- package/dist/adapter/opencode/opencode-transport.js +2 -2
- package/dist/adapter/opencode/session-history.js +8 -0
- package/dist/adapter/pi/session-history.js +2 -0
- package/dist/adapter/shared/session-history.js +1 -1
- package/dist/bridge/bridge.js +9 -9
- package/dist/core/access/allowlist-store.js +1 -1
- package/dist/core/file-ops/list-files.js +1 -1
- package/dist/log.js +2 -2
- package/dist/mcp/stream-http/config.js +1 -1
- package/dist/mcp/stream-http/connection-binding.js +1 -1
- package/dist/mcp/stream-http/security.js +1 -1
- package/dist/mcp/stream-http/tool-executor.js +1 -1
- package/dist/mcp/stream-http/tool-registry.js +1 -1
- package/dist/mcp/stream-http/tool-schemas.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const
|
|
1
|
+
import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const n of t)e.push(n);const r=Buffer.concat(e).toString("utf8").trim();return r?JSON.parse(r):{}}function k(t){const e=(t.headers.authorization??"").trim();return e.toLowerCase().startsWith("bearer ")?e.slice(7).trim():""}class w{host="127.0.0.1";port=0;token;callbacks;server=null;address=null;constructor(e){this.token=d(),this.callbacks=e}getToken(){return this.token}getURL(){return this.address?`http://${this.address.address}:${this.address.port}`:""}async start(){this.server||(this.server=c.createServer(async(e,r)=>{try{await this.handleRequest(e,r)}catch(n){h(r,n instanceof Error?n.message:String(n))}}),await new Promise((e,r)=>{this.server.once("error",r),this.server.listen(this.port,this.host,()=>{this.server.off("error",r),e()})}),this.address=this.server.address(),o.info("claude-bridge",`Bridge server listening on ${this.getURL()}`))}async stop(){if(!this.server)return;const e=this.server;this.server=null,this.address=null,e.closeIdleConnections?.(),e.closeAllConnections?.(),await new Promise((r,n)=>{e.close(s=>s?n(s):r())})}async handleRequest(e,r){if(k(e)!==this.token){l(r);return}if(e.method!=="POST"){r.writeHead(405,{"content-type":"application/json"}),r.end(JSON.stringify({error:"method_not_allowed"}));return}const n=new URL(e.url,"http://localhost").pathname,s=await v(e),i=f.get(n);if(!i){u(r);return}const a=await i(this.callbacks,s);p(r,a??{ok:!0})}}const f=new Map([["/v1/worker/register",async(t,e)=>(o.info("claude-bridge",`Worker registered: ${e.worker_id} (pid=${e.pid})`),t.onRegisterWorker(e))],["/v1/worker/status",async(t,e)=>(o.info("claude-bridge",`Worker status: ${e.status}`),t.onStatusUpdate(e))],["/v1/worker/send-text",async(t,e)=>t.onSendText(e)],["/v1/worker/send-stream-chunk",async(t,e)=>t.onSendStreamChunk(e)],["/v1/worker/send-media",async(t,e)=>t.onSendMedia(e)],["/v1/worker/delete-message",async(t,e)=>t.onDeleteMessage(e)],["/v1/worker/ack-event",async(t,e)=>t.onAckEvent(e)],["/v1/worker/event-result",async(t,e)=>t.onSendEventResult(e)],["/v1/worker/event-stop-ack",async(t,e)=>t.onSendEventStopAck(e)],["/v1/worker/event-stop-result",async(t,e)=>t.onSendEventStopResult(e)],["/v1/worker/session-composing",async(t,e)=>t.onSetSessionComposing(e)],["/v1/worker/agent-invoke",async(t,e)=>t.onAgentInvoke(e)],["/v1/worker/local-action-result",async(t,e)=>t.onLocalActionResult(e)]]);export{w as ClaudeBridgeServer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as x}from"node:crypto";import{CallToolRequestSchema as S,ListToolsRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{log as f}from"../../core/log/index.js";import{toolCallToInvoke as k}from"../../core/mcp/tools.js";const E=new Set(["contact_search","session_search","message_history","message_search","group_create","group_detail_read","group_leave_self","group_member_add","group_member_remove","group_member_role_update","group_all_members_muted_update","group_member_speaking_update","group_dissolve","send_msg","delete_msg","agent_api_create","agent_category_list","agent_category_create","agent_category_update","agent_category_assign","agent_api_key_rotate"]),y=3e4,I=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},files:{type:"array",items:{type:"string"},description:"Optional absolute local file paths. Each file is uploaded through Agent API OSS presign before sending."},final:{type:"boolean",description:"Whether this is the final reply for the event. Defaults to false \u2014 the event stays open while Claude continues working, and auto-completes after inactivity. Set true only when this is definitively the last message for the event."}},required:["chat_id","event_id"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},code:{type:"string"},msg:{type:"string"}},required:["event_id","status"]}},{name:"delete_message",description:"Delete a previously sent message in the same grix-claude chat.",inputSchema:{type:"object",properties:{chat_id:{type:"string"},message_id:{type:"string"}},required:["chat_id","message_id"]}},{name:"status",description:"Show grix-claude runtime status, upstream access state, bridge health, and startup hints.",inputSchema:{type:"object",properties:{}}},{name:"send",description:"Send a message to a chat session proactively, without requiring an inbound event. Use for notifications or scheduled reports.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The target chat/session id."},text:{type:"string",description:"The message text to send."}},required:["chat_id","text"]}},{name:"access_pair",description:"Forward a sender pairing approval code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"access_deny",description:"Forward a sender pairing denial code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"allow_sender",description:"Ask upstream access control to allow a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"remove_sender",description:"Ask upstream access control to remove a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"access_policy",description:"Ask upstream access control to update the sender access policy.",inputSchema:{type:"object",properties:{policy:{type:"string",enum:["allowlist","open","disabled"]}},required:["policy"]}},{name:"grix_query",description:"Search contacts, sessions, message history, or messages by keyword in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},keyword:{type:"string"},id:{type:"string"},sessionId:{type:"string"},limit:{type:"number"},offset:{type:"number"},beforeId:{type:"string"}},required:["action"]}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string"},memberIds:{type:"array",items:{type:"string"}},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer",description:"Member type (for update_member_role / update_member_speaking)."},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted (for update_member_speaking)."}},required:["action"]}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},content:{type:"string"},msgType:{type:"number"},quotedMessageId:{type:"string"},threadId:{type:"string"}},required:["sessionId","content"]}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},msgId:{type:"string"}},required:["sessionId","msgId"]}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentId:{type:"string"},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"number"}},required:["action"]}}];function q(r,e){r.setRequestHandler(w,async()=>({tools:I})),r.setRequestHandler(S,async i=>{const{name:n,arguments:t}=i.params,s=t??{};try{switch(n){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(n,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(n,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${n}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${n} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(r,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const n=String(r.text??""),t=String(r.chat_id??""),s=String(r.event_id??i.eventId),a=r.reply_to,d=r.files,_=r.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!n.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,n),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(r,e){const i=e.getActiveEvent(),n=String(r.event_id??""),t=r.status??"",s=r.code,a=r.msg;if(!n||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(n)?(e.bridge.sendEventResult(n,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(r,e){const i=String(r.chat_id??""),n=String(r.message_id??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:n},y),c(`deleted (${n})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(r){const e=r.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(r,e){const i=String(r.chat_id??""),n=String(r.text??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(n),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(r,e,i){try{const n=C[r];if(!n)throw new Error(`Unknown access control tool: ${r}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:n.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}async function O(r,e,i){try{const n=k(r,e);if(!E.has(n.action))throw new Error(`Action not allowed: ${n.action}`);const t=await i.bridge.agentInvoke(n.action,n.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}function c(r){return{content:[{type:"text",text:r}]}}export{q as registerClaudeTools};
|
|
1
|
+
import{randomUUID as x}from"node:crypto";import{CallToolRequestSchema as S,ListToolsRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{log as f}from"../../core/log/index.js";import{toolCallToInvoke as k}from"../../core/mcp/tools.js";const E=new Set(["contact_search","session_search","message_history","message_search","group_create","group_detail_read","group_leave_self","group_member_add","group_member_remove","group_member_role_update","group_all_members_muted_update","group_member_speaking_update","group_dissolve","send_msg","delete_msg","agent_api_create","agent_category_list","agent_category_create","agent_category_update","agent_category_assign","agent_api_key_rotate"]),y=3e4,I=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},files:{type:"array",items:{type:"string"},description:"Optional absolute local file paths. Each file is uploaded through Agent API OSS presign before sending."},final:{type:"boolean",description:"Whether this is the final reply for the event. Defaults to false \u2014 the event stays open while Claude continues working, and auto-completes after inactivity. Set true only when this is definitively the last message for the event."}},required:["chat_id","event_id"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},code:{type:"string"},msg:{type:"string"}},required:["event_id","status"]}},{name:"delete_message",description:"Delete a previously sent message in the same grix-claude chat.",inputSchema:{type:"object",properties:{chat_id:{type:"string"},message_id:{type:"string"}},required:["chat_id","message_id"]}},{name:"status",description:"Show grix-claude runtime status, upstream access state, bridge health, and startup hints.",inputSchema:{type:"object",properties:{}}},{name:"send",description:"Send a message to a chat session proactively, without requiring an inbound event. Use for notifications or scheduled reports.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The target chat/session id."},text:{type:"string",description:"The message text to send."}},required:["chat_id","text"]}},{name:"access_pair",description:"Forward a sender pairing approval code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"access_deny",description:"Forward a sender pairing denial code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"allow_sender",description:"Ask upstream access control to allow a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"remove_sender",description:"Ask upstream access control to remove a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"access_policy",description:"Ask upstream access control to update the sender access policy.",inputSchema:{type:"object",properties:{policy:{type:"string",enum:["allowlist","open","disabled"]}},required:["policy"]}},{name:"grix_query",description:"Search contacts, sessions, message history, or messages by keyword in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},keyword:{type:"string"},id:{type:"string"},sessionId:{type:"string"},limit:{type:"number"},offset:{type:"number"},beforeId:{type:"string"}},required:["action"]}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string"},memberIds:{type:"array",items:{type:"string"}},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer",description:"Member type (for update_member_role / update_member_speaking)."},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted (for update_member_speaking)."}},required:["action"]}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},content:{type:"string"},msgType:{type:"number"},quotedMessageId:{type:"string"},threadId:{type:"string"}},required:["sessionId","content"]}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},msgId:{type:"string"}},required:["sessionId","msgId"]}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentId:{type:"string"},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"number"}},required:["action"]}}];function q(n,e){n.setRequestHandler(w,async()=>({tools:I})),n.setRequestHandler(S,async i=>{const{name:r,arguments:t}=i.params,s=t??{};try{switch(r){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(r,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(r,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${r}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${r} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(n,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const r=String(n.text??""),t=String(n.chat_id??""),s=String(n.event_id??i.eventId),a=n.reply_to,d=n.files,_=n.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!r.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,r),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(n,e){const i=e.getActiveEvent(),r=String(n.event_id??""),t=n.status??"",s=n.code,a=n.msg;if(!r||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(r)?(e.bridge.sendEventResult(r,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(n,e){const i=String(n.chat_id??""),r=String(n.message_id??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:r},y),c(`deleted (${r})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(n){const e=n.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(n,e){const i=String(n.chat_id??""),r=String(n.text??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(r),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(n,e,i){try{const r=C[n];if(!r)throw new Error(`Unknown access control tool: ${n}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:r.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}async function O(n,e,i){try{const r=k(n,e);if(!E.has(r.action))throw new Error(`Action not allowed: ${r.action}`);const t=await i.bridge.agentInvoke(r.action,r.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}function c(n){return{content:[{type:"text",text:n}]}}export{q as registerClaudeTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(
|
|
1
|
+
import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(t,e){this.controlURL=t.replace(/\/+$/,""),this.token=e.trim(),l.info("claude-worker-client",`Configured with control URL: ${this.controlURL}`)}async post(t,e,s){if(!this.isConfigured())throw new Error("worker control not configured");const i=new AbortController,o=setTimeout(()=>i.abort(),s);try{const r=await fetch(`${this.controlURL}${t}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.token}`},body:JSON.stringify(e),signal:i.signal}),n=await r.text(),a=n.trim()?JSON.parse(n):{};if(!r.ok)throw new Error(a.error||`worker control failed ${r.status}`);return a}finally{clearTimeout(o)}}isRetryableError(t){const e=t instanceof Error?t.message:String(t);return/fetch failed|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|aborted/i.test(e)}async postWithRetry(t,e,s,i=1){let o;for(let r=0;r<=i;r++)try{return r>0&&l.info("claude-worker-client",`Retrying ${t} attempt=${r+1}`),await this.post(t,e,s)}catch(n){if(o=n,r>=i||!this.isRetryableError(n))break;await new Promise(a=>setTimeout(a,150))}throw o instanceof Error?o:new Error(String(o))}async deliverEvent(t){return this.postWithRetry("/v1/worker/deliver-event",{payload:t},1e4,1)}async deliverStop(t){return this.postWithRetry("/v1/worker/deliver-stop",{payload:t},1e4,1)}async deliverLocalAction(t){return this.postWithRetry("/v1/worker/deliver-local-action",{payload:t},1e4,1)}async ping(){try{return await this.postWithRetry("/v1/worker/ping",{},5e3,1),!0}catch{return!1}}}export{c as ClaudeWorkerClient};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as
|
|
2
|
-
`),"utf8"),{expectPath:a,pidPath:i}}function h(
|
|
1
|
+
import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as l}from"./protocol-contract.js";function P(e){let t=null,r=0,n=!1,i=!1;const a=v(),s=e.gatewayUrl??"http://127.0.0.1:19580/mcp";return{async start(){await F(e.command,s,e.env);const c=E(e.grix),u=[...e.args??[],"--name",`grix-mcp-${e.name}`,"--session-id",a];e.fullAuto&&u.push("--dangerously-skip-permissions"),u.push("--dangerously-load-development-channels",`server:${l}`,"--append-system-prompt",c);const f=d(I(),`grix-mcp-claude-${e.name}`);await S(f,{recursive:!0});const{expectPath:$,pidPath:g}=await M(f,e.command,u),_={...process.env,...e.env??{}};t=x("/usr/bin/expect",[$],{cwd:e.cwd,env:_,stdio:["ignore","pipe","pipe"],detached:!0}),o.info("mcp-http-launcher",`\u542F\u52A8 Claude: name=${e.name} cwd=${e.cwd} pid=${t.pid}`),r=await k(g),n=!0,o.info("mcp-http-launcher",`Claude \u5B50\u8FDB\u7A0B PID: ${r}`),t.on("exit",(m,p)=>{o.info("mcp-http-launcher",`Claude \u9000\u51FA: code=${m} signal=${p}`),n=!1,t=null,r=0,i||(o.info("mcp-http-launcher","3 \u79D2\u540E\u81EA\u52A8\u91CD\u542F..."),setTimeout(()=>{i||this.start().catch(w=>{o.error("mcp-http-launcher",`\u91CD\u542F\u5931\u8D25: ${w}`)})},3e3))}),t.stdout?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stdout] ${p.slice(0,300)}`)}),t.stderr?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stderr] ${p.slice(0,300)}`)})},async stop(){if(i=!0,n=!1,r>0)try{process.kill(r,"SIGTERM")}catch{}if(t?.pid){try{process.kill(-t.pid,"SIGTERM")}catch{}await new Promise(c=>{const u=setTimeout(()=>{if(r>0)try{process.kill(r,"SIGKILL")}catch{}if(t?.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}c()},5e3);t?.once("exit",()=>{clearTimeout(u),c()})})}t=null,r=0},getStatus(){return{name:e.name,alive:n,pid:r}}}}function E(e){return["You are connected to a chat via the grix MCP server.",`On startup, immediately call grix_authorize with: agentId="${e.agentId}", apiKey="${e.apiKey}", wsUrl="${e.wsUrl}", clientType="${e.clientType}".`,"When you receive a <channel> message, you MUST respond by calling the grix_reply tool (or the grix_complete tool if no response is needed).","Never write your reply as plain text \u2014 it will NOT reach the user. Only the grix_reply tool delivers your response to the chat.","The <channel> message contains event_id and session_id \u2014 pass them to grix_reply."].join(" ")}async function F(e,t,r){const n=d(T(),".claude.json");let i=null;try{const s=C(n,"utf8");i=JSON.parse(s)?.mcpServers?.[l]??null}catch{}if(i&&String(i.type??"").trim()==="http"&&String(i.url??"").trim()===t)return;o.info("mcp-http-launcher",`\u6CE8\u518C MCP Server: ${l} -> ${t}`);const a={...process.env,...r??{}};try{y(`${e} mcp remove -s user ${l}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}catch{}y(`${e} mcp add --scope user --transport http ${l} ${t}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}async function M(e,t,r){const{writeFile:n}=await import("node:fs/promises"),i=d(e,"claude.pid"),a=d(e,"claude.expect"),s=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set claude_command [list {${h(t)}}${r.map(c=>` {${h(c)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${h(i)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","expect {"," -re {(?i)(Quick.*safety.*check|trust.*folder)} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)I am using this for local development} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)(Enter.*confirm|Press.*Enter|Hit.*Enter)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {Listening for channel} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," -re {bypass permissions} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," eof {}","}","expect eof",""];return await n(i,"","utf8"),await n(a,s.join(`
|
|
2
|
+
`),"utf8"),{expectPath:a,pidPath:i}}function h(e){return e.replace(/[\\{}$\[\]"]/g,"\\$&")}async function k(e,t=1e4){const{readFile:r}=await import("node:fs/promises"),n=Math.ceil(t/100);for(let i=0;i<n;i++){try{const a=await r(e,"utf8"),s=parseInt(String(a).trim(),10);if(Number.isFinite(s)&&s>0)return s}catch{}await new Promise(a=>setTimeout(a,100))}return 0}export{P as createMcpHttpLauncher};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(
|
|
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,2 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
`)}return t==null?"":String(t)}function
|
|
1
|
+
import S from"node:os";import{join as _,resolve as g,sep as x}from"node:path";import{SESSION_HISTORY_ERROR_CODES as m,SessionHistoryError as h,readJsonlHistoryPage as A,registerSessionHistoryReader as j}from"../shared/session-history.js";import{encodeProjectPath as T,resolveSessionJsonlPath as E}from"./usage-parser.js";const k=/^[A-Za-z0-9][A-Za-z0-9_-]*$/,P=new Set(["summary","custom-title","ai-title","file-history-snapshot","queue-operation"]),b=["<local-command-caveat","<command-name","<local-command-stdout"];function y(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function w(t){const o=t.trimStart();return b.some(s=>o.startsWith(s))}function O(t){if(typeof t=="string")return t;if(Array.isArray(t)){const o=[];for(const s of t)y(s)&&s.type==="text"&&typeof s.text=="string"&&o.push(s.text);return o.join(`
|
|
2
|
+
`)}return t==null?"":String(t)}function R(t,o){if(t.isSidechain===!0||t.isMeta===!0)return[];const s=typeof t.type=="string"?t.type:"";if(P.has(s))return[];const a=typeof t.uuid=="string"&&t.uuid?t.uuid:o,f=typeof t.parentUuid=="string"?t.parentUuid:null,u=typeof t.timestamp=="string"?t.timestamp:"",p=y(t.message)?t.message:void 0,c=[];if(s==="user"){const i=p?.content;if(typeof i=="string")c.push({role:"user",content:i,msg_type:"text"});else if(Array.isArray(i))for(const r of i){if(!y(r))continue;const n=r;if(n.type==="text"&&typeof n.text=="string"){if(w(n.text))continue;c.push({role:"user",content:n.text,msg_type:"text"})}else if(n.type==="tool_result"){const e={};typeof n.tool_use_id=="string"&&(e.tool_use_id=n.tool_use_id),n.is_error===!0&&(e.is_error=!0),c.push({role:"tool",content:O(n.content),msg_type:"tool_result",...Object.keys(e).length>0?{extra:e}:{}})}}}else if(s==="assistant"){const i=p?.content,r=typeof p?.model=="string"?p.model:void 0;if(typeof i=="string")c.push({role:"assistant",content:i,msg_type:"text",...r?{extra:{model:r}}:{}});else if(Array.isArray(i))for(const n of i){if(!y(n))continue;const e=n;if(e.type==="text"&&typeof e.text=="string")c.push({role:"assistant",content:e.text,msg_type:"text",...r?{extra:{model:r}}:{}});else if(e.type==="thinking"&&typeof e.thinking=="string")c.push({role:"assistant",content:e.thinking,msg_type:"thinking"});else if(e.type==="tool_use"){const l={};typeof e.name=="string"&&(l.tool_name=e.name),typeof e.id=="string"&&(l.tool_use_id=e.id);let d="{}";try{d=JSON.stringify(e.input??{})}catch{}c.push({role:"assistant",content:d,msg_type:"tool_use",...Object.keys(l).length>0?{extra:l}:{}})}}}else if(s==="system")c.push({role:"system",content:String(t.content??""),msg_type:typeof t.subtype=="string"?t.subtype:"system"});else return[];return c.map((i,r)=>({native_message_id:r===0?a:`${a}#${r}`,native_parent_id:f,created_at:u,...i}))}function v(t,o){if(!k.test(t.agent_session_id))throw new h(m.invalidAgentSession,`invalid agent_session_id: ${t.agent_session_id}`);const s=o?.projectsDir??_(S.homedir(),".claude","projects"),a=o?.projectsDir?_(o.projectsDir,T(t.cwd),`${t.agent_session_id}.jsonl`):E(t.agent_session_id,t.cwd),f=g(s),u=g(a);if(u!==f&&!u.startsWith(f+x))throw new h(m.invalidAgentSession,`transcript path escapes projects dir: ${t.agent_session_id}`);return u}async function D(t,o){const s=v(t,o);return{...await A({filePath:s,cursor:t.cursor,limit:t.limit,mapLine:R,sourceLabel:"claude session transcript",logTag:"claude-session-history"}),...t.sync_run_id?{sync_run_id:t.sync_run_id}:{}}}j("claude",D);export{D as readClaudeSessionHistory};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readFileSync as x,statSync as A}from"node:fs";import{join as p,resolve as S,sep as b}from"node:path";import{SESSION_HISTORY_ERROR_CODES as c,SessionHistoryError as d,decodeOpaqueCursor as C,encodeOpaqueCursor as $,normalizeHistoryLimit as E,registerSessionHistoryReader as I}from"../shared/session-history.js";import{resolveCodeWhaleHome as N}from"./session-scanner.js";const O=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function f(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function R(e,n){if(!O.test(e.agent_session_id))throw new d(c.invalidAgentSession,`invalid agent_session_id: ${e.agent_session_id}`);const o=p(N(n?.homeDir),"sessions"),s=p(o,`${e.agent_session_id}.json`),i=S(o),t=S(s);if(t!==i&&!t.startsWith(i+b))throw new d(c.invalidAgentSession,`session file path escapes sessions dir: ${e.agent_session_id}`);return t}function D(e){const n=C(e);if(n.v!==2||typeof n.idx!="number"||!Number.isInteger(n.idx)||n.idx<0)throw new d(c.invalidCursor,`invalid sync_history cursor: ${e}`);return n.idx}function H(e){let n;try{if(A(e).isDirectory())throw new d(c.sourceUnreadable,`codewhale session file is a directory: ${e}`);n=x(e,"utf8")}catch(s){throw s instanceof d?s:s.code==="ENOENT"?new d(c.sessionNotFound,`codewhale session file not found: ${e}`):new d(c.sourceUnreadable,`failed to read codewhale session file ${e}: ${s}`)}let o;try{o=JSON.parse(n)}catch(s){throw new d(c.sourceUnreadable,`failed to parse codewhale session file ${e}: ${s}`)}if(!f(o)||!Array.isArray(o.messages))throw new d(c.sourceUnreadable,`codewhale session file has no messages array: ${e}`);return o}function w(e,n,o,s){if(!f(e))return null;const i=e.role;if(i!=="user"&&i!=="assistant"&&i!=="tool"&&i!=="system")return null;const t=typeof e.content=="string"?e.content:e.content==null?"":String(e.content);if(!t)return null;const a=typeof e.timestamp=="string"&&e.timestamp||typeof e.created_at=="string"&&e.created_at||s;return{native_message_id:typeof e.id=="string"&&e.id?e.id:`cw-${n}-${o}`,native_parent_id:null,role:i,content:t,created_at:a,msg_type:i==="system"?"system":"text"}}async function T(e,n){const o=R(e,n),s=e.cursor?D(e.cursor):0,i=E(e.limit),t=H(o),a=f(t.metadata)?t.metadata:{},l=typeof a.created_at=="string"&&a.created_at||typeof a.updated_at=="string"&&a.updated_at||"",m=typeof t.system_prompt=="string"&&t.system_prompt.length>0,_=t.messages.length+(m?1:0);if(s>_)throw new d(c.invalidCursor,`cursor index ${s} is beyond codewhale session message count ${_}: ${o}`);if(s===_)return{messages:[],has_more:!1,next_cursor:$({v:2,idx:s}),...e.sync_run_id?{sync_run_id:e.sync_run_id}:{}};const v=r=>m?r===0?{native_message_id:`cw-${e.agent_session_id}-sys`,native_parent_id:null,role:"system",content:t.system_prompt,created_at:l,msg_type:"system"}:w(t.messages[r-1],e.agent_session_id,r-1,l):w(t.messages[r],e.agent_session_id,r,l),u=[];let g=s,h=!1;for(let r=s;r<_;r++){const y=v(r);if(u.length>=i){if(y){h=!0;break}continue}g=r+1,y&&u.push(y)}return{messages:u,has_more:h,next_cursor:$({v:2,idx:g}),...e.sync_run_id?{sync_run_id:e.sync_run_id}:{}}}I("codewhale",T);export{T as readCodeWhaleSessionHistory};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resolve as p,sep as g}from"node:path";import{SESSION_HISTORY_ERROR_CODES as _,SessionHistoryError as f,readJsonlHistoryPage as m,registerSessionHistoryReader as x}from"../shared/session-history.js";import{resolveCodexHome as h}from"./codex-trust.js";import{findRolloutFile as S}from"./rollout-locator.js";const v=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function y(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function A(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t)}catch{return String(t)}}function w(t,l){if((typeof t.type=="string"?t.type:"")!=="response_item")return[];const e=y(t.payload)?t.payload:void 0;if(!e)return[];const s=typeof e.type=="string"?e.type:"",r=typeof t.timestamp=="string"?t.timestamp:"",u=typeof e.id=="string"&&e.id?e.id:l,c=[];if(s==="message"){const n=e.role==="user"?"user":e.role==="assistant"?"assistant":e.role==="developer"?"system":null;if(!n)return[];const o=e.content;if(!Array.isArray(o))return[];for(const i of o)y(i)&&(i.type==="input_text"||i.type==="output_text")&&typeof i.text=="string"&&c.push({role:n,content:i.text,msg_type:"text"})}else if(s==="function_call"||s==="custom_tool_call"){const n=typeof e.call_id=="string"&&e.call_id?e.call_id:void 0,o=typeof e.name=="string"?e.name:void 0,i=s==="function_call"?e.arguments:e.input,d={};return o&&(d.tool_name=o),n&&(d.call_id=n),c.push({role:"assistant",content:typeof i=="string"?i:"{}",msg_type:"tool_use",...Object.keys(d).length>0?{extra:d}:{}}),[{native_message_id:n??u,native_parent_id:null,created_at:r,...c[0]}]}else if(s==="function_call_output"||s==="custom_tool_call_output"){const n=typeof e.call_id=="string"&&e.call_id?e.call_id:void 0;return[{native_message_id:n?`${n}/output`:u,native_parent_id:null,role:"tool",content:A(e.output),created_at:r,msg_type:"tool_result",...n?{extra:{call_id:n}}:{}}]}else if(s==="reasoning"){const n=e.summary;if(!Array.isArray(n))return[];for(const o of n)y(o)&&typeof o.text=="string"&&o.text&&c.push({role:"assistant",content:o.text,msg_type:"thinking"})}else return[];return c.map((n,o)=>({native_message_id:o===0?u:`${u}#${o}`,native_parent_id:null,created_at:r,...n}))}function R(t,l){if(!v.test(t.agent_session_id))throw new f(_.invalidAgentSession,`invalid agent_session_id: ${t.agent_session_id}`);const a=h(l?.codexHome),e=S(t.agent_session_id,a);if(!e)throw new f(_.sessionNotFound,`codex session rollout not found for thread: ${t.agent_session_id}`);const s=p(a),r=p(e);if(r!==s&&!r.startsWith(s+g))throw new f(_.invalidAgentSession,`rollout path escapes codex home: ${t.agent_session_id}`);return r}async function H(t,l){const a=R(t,l);return{...await m({filePath:a,cursor:t.cursor,limit:t.limit,mapLine:w,sourceLabel:"codex session rollout",logTag:"codex-session-history"}),...t.sync_run_id?{sync_run_id:t.sync_run_id}:{}}}x("codex",H);export{H as readCodexSessionHistory};
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import{EventEmitter as
|
|
2
|
-
`,"utf8"),
|
|
3
|
-
`)){const I=u.match(/opencode server listening on (https?:\/\/[^\s]+)/);if(I){clearTimeout(v),l=!0,this.alive=!0,i(I[1]);return}}}),this.process.stderr?.on("data",c=>{const u=c.toString().trim();u&&n.info("opencode-adapter",`[stderr] ${u}`)}),this.process.on("error",c=>{n.error("opencode-adapter",`Spawn error: ${c.message}`),clearTimeout(v),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${c.message}`),this.clearRun()),l?this.stopped||this.emit("exit",1):(l=!0,o(c))}),this.process.on("exit",c=>{n.info("opencode-adapter",`Process exited (code=${c})`),clearTimeout(v),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${c})`),this.clearRun()),l?this.stopped||this.emit("exit",c??1):(l=!0,o(new Error(`opencode serve exited with code ${c}`)))})})}async ensureOcSession(e){const t=this.sessions.get(e),s=this.getSessionCwd(e);if(await this.transport.useDirectory(s),t?.ocSessionId)try{return await this.transport.getSession(t.ocSessionId,s),t.ocSessionId}catch{n.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, creating new`),t.ocSessionId=""}const i=this.options.bindingStore?.getAcpSessionId(e);if(i)try{return await this.transport.getSession(i,s),this.sessions.set(e,{ocSessionId:i,cwd:s}),n.info("opencode-adapter",`Resumed OC session ${i} for aibot=${e}`),i}catch{n.warn("opencode-adapter",`Persisted OC session ${i} gone, creating new`)}const o=await this.transport.createSession({title:`grix-${e.slice(-8)}`},s);return this.sessions.set(e,{ocSessionId:o.id,cwd:s}),this.options.bindingStore?.setAcpSessionId(e,o.id),n.info("opencode-adapter",`Created OC session ${o.id} for aibot=${e}`),o.id}async sendOcPrompt(e,t){const s=this.getSessionCwd(e),i=await this.ensureOcSession(e);this.activeRun&&(this.activeRun.ocSessionId=i,this.activeRun.cwd=s),await this.transport.sendPromptAsync(i,{parts:[{type:"text",text:t}]},s)}handleSseEvent(e){if(!this.stopped){if(this.lastSseAt=Date.now(),this.updateToolInFlight(e),this.resetIdleTimer(),this.activeRun){const t=this.auditCaptures.get(this.activeRun.eventId);t&&t.push({sequence:t.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(e.type){case"message.part.updated":{if(!this.activeRun)break;const t=e.part,s=e.delta;if(t.type==="text"){const i=s||t.text;i&&this.acceptAssistantPartText(t.messageID,"text",i)}else t.type==="reasoning"?s&&this.acceptAssistantPartText(t.messageID,"reasoning",s):t.type==="tool"&&this.handleToolPartUpdate(t,s);break}case"message.updated":{if(!this.activeRun)break;const t=e.info;if(this.rememberMessageRole(t),t.role==="assistant"){const s=t;this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.activeRun.cwd,{model_provider:s.providerID,model_id:s.modelID}),s.error&&n.warn("opencode-adapter",`Message error: ${JSON.stringify(s.error)}`);const i=this.activeRun.ocSessionId;i&&s.sessionID===i&&(s.error?(this.flushTextBuffer(),this.finishRun("failed",s.error.message||s.error.type)):s.time?.completed&&s.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}break}case"session.idle":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.status":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&e.status.type==="idle"&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.error":{if(!this.activeRun)break;const t=e.error,s=t?typeof t=="object"&&"message"in t?t.message:JSON.stringify(t):"unknown session error";n.error("opencode-adapter",`Session error: ${s}`),this.flushTextBuffer(),this.finishRun("failed",s);break}case"permission.updated":{this.handlePermission(e.permission);break}case"session.created":case"session.updated":case"session.deleted":case"session.compacted":case"session.diff":case"file.edited":case"server.connected":break;case"server.instance.disposed":{n.warn("opencode-adapter",`Server instance disposed: ${e.directory}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"failed","server instance disposed"),this.clearRun()),this.stopped||this.emit("exit",-1);break}default:break}}}updateToolInFlight(e){if(e.type!=="message.part.updated")return;const t=e.part;if(t?.type!=="tool"||!t.callID)return;const s=t.state?.status;s==="pending"||s==="running"?this.toolCallsInFlight.add(t.callID):(s==="completed"||s==="error")&&this.toolCallsInFlight.delete(t.callID)}rememberMessageRole(e){const t=typeof e.id=="string"?e.id.trim():"";t&&(e.role!=="user"&&e.role!=="assistant"||(this.messageRoles.set(t,e.role),this.flushOrDropPendingParts(t,e.role)))}acceptAssistantPartText(e,t,s){if(!this.activeRun||!s)return;const i=typeof e=="string"?e.trim():"";if(!i)return;const o=this.messageRoles.get(i);if(o==="user")return;if(o==="assistant"){this.emitAssistantPartChunk(t,s);return}const r=this.pendingPartChunks.get(i)??[];r.push({kind:t,value:s}),this.pendingPartChunks.set(i,r)}flushOrDropPendingParts(e,t){const s=this.pendingPartChunks.get(e);if(this.pendingPartChunks.delete(e),!(!s||s.length===0)&&t==="assistant")for(const i of s)this.emitAssistantPartChunk(i.kind,i.value)}emitAssistantPartChunk(e,t){if(!(!this.activeRun||!t)){if(e==="reasoning"){this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,t);return}this.appendText(t)}}clearMessageRoleState(){this.messageRoles.clear(),this.pendingPartChunks.clear()}handleToolPartUpdate(e,t){if(!this.activeRun)return;const s=e.state;switch(s.status){case"pending":case"running":{this.sendToolUseOnce(e,s.input);break}case"completed":{this.sendToolUseOnce(e,s.input);break}case"error":{this.sendToolUseOnce(e,s.input),this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,"(failed)");break}}}sendToolUseOnce(e,t){!this.activeRun||this.toolCardsSent.has(e.callID)||(this.flushTextBuffer(),this.toolCardsSent.add(e.callID),this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,H(t??{})))}handlePermission(e){if(!this.activeRun)return;const{eventId:t,sessionId:s,ocSessionId:i}=this.activeRun;if(this.options.permissionPolicy==="fullAuto"){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(r=>{n.warn("opencode-adapter",`Auto-approve failed: ${r}`)});return}this.stopIdleTimer(),this.pendingPermissions.set(t,{permissionId:e.id,ocSessionId:i,cwd:this.activeRun.cwd});const o=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(t,s,e.type,o)}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const t=this.pendingPermissions.get(this.activeRun.eventId);if(!t)return{handled:!1,kind:""};const{permissionId:s,ocSessionId:i,cwd:o}=t,a=e.action_type==="exec_approve"||e.action_type==="permission_approve"?"once":"reject";return this.pendingPermissions.delete(this.activeRun.eventId),this.transport.respondPermission(i,s,a,o).then(()=>{n.info("opencode-adapter",`Permission ${a}: ${s}`),this.resetIdleTimer()}).catch(d=>{n.warn("opencode-adapter",`Permission response failed: ${d}`)}),{handled:!0,kind:"permission"}}startRun(e,t,s=!1){this.activeRun={eventId:e,sessionId:t,ocSessionId:"",cwd:this.getSessionCwd(t),chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null},this.toolCardsSent.clear(),s&&this.auditCaptures.set(e,[]),this.lastSseAt=Date.now(),this.livenessExtendStartAt=void 0}finishRun(e,t){const s=this.activeRun;if(!s)return;if(this.completedEvents.add(s.eventId),this.completedEvents.size>Q){const a=[...this.completedEvents].slice(-500);this.completedEvents=new Set(a)}this.snapshotAuditBoundary(s),this.activeRun=null,this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopComposing(),this.stopIdleTimer();const i=++s.chunkSeq,o=s.clientMsgId;e==="failed"&&t&&this.callbacks.sendRunError(s.eventId,s.sessionId,t);const r=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(s.eventId,s.sessionId,o).then(()=>{this.callbacks.sendEventResult(s.eventId,e,t)}).catch(a=>{const d=e==="responded"?"failed":e,h=e==="responded"?`final output delivery failed: ${a instanceof Error?a.message:String(a)}`:t;this.callbacks.sendEventResult(s.eventId,d,h)}):(this.callbacks.sendStreamChunk(s.eventId,s.sessionId,"",i,!0,o),this.callbacks.sendEventResult(s.eventId,e,t))};if(s.textBuffer){this.stopTextFlush();for(const a of T(s.textBuffer))s.chunkSeq++,this.callbacks.sendStreamChunk(s.eventId,s.sessionId,a,s.chunkSeq,!1,s.clientMsgId);s.textBuffer=""}r(),this.emit("eventDone",s.eventId)}clearRun(){this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const e=this.activeRun?.eventId;this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null,this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopIdleTimer(),e&&this.emit("eventDone",e)}snapshotAuditBoundary(e){const t=this.auditCaptures.get(e.eventId);t&&(this.completedAuditBoundaries.set(e.eventId,{adapterType:"opencode",providerSessionId:e.ocSessionId||void 0,openCodeEvidence:{events:t}}),this.auditCaptures.delete(e.eventId))}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=z){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},q))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const e of T(this.activeRun.textBuffer))this.activeRun.chunkSeq++,this.callbacks.sendStreamChunk(this.activeRun.eventId,this.activeRun.sessionId,e,this.activeRun.chunkSeq,!1,this.activeRun.clientMsgId);this.activeRun.textBuffer=""}}stopTextFlush(){this.activeRun?.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null)}startComposing(e){}stopComposing(){}shouldExtendByLiveness(){if(!this.activeRun)return!1;const e=this.process?.pid;if(!this.alive||!e||!k(e))return!1;const t=Date.now(),s=this.lastSseAt>0?t-this.lastSseAt:Number.POSITIVE_INFINITY;if(s<W)return this.livenessExtendStartAt=t,n.info("opencode-adapter",`Liveness check: fresh SSE for ${this.activeRun.eventId} (sseAge=${s}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const o=this.livenessExtendStartAt??t;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=o),t-o>x?(n.warn("opencode-adapter",`Liveness extension budget exhausted for ${this.activeRun.eventId} (no progress for ${Math.round((t-o)/6e4)}min), allowing idle fail`),!1):(n.info("opencode-adapter",`Liveness check: turn in progress for ${this.activeRun.eventId} (toolsInFlight=${this.toolCallsInFlight.size}, sseAge=${Number.isFinite(s)?`${s}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.activeRun)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.activeRun)return;if(this.pendingPermissions.has(this.activeRun.eventId)&&this.shouldExtendByLiveness()){n.info("opencode-adapter",`Idle timeout skipped: pendingPermissions for ${this.activeRun.eventId}, resetting timer`),this.resetIdleTimer();return}if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const e=this.process?.pid,s=!!(this.alive&&e&&k(e))?`liveness budget exhausted after ${x/6e4}min`:"process not alive";n.error("opencode-adapter",`Idle timeout (${s}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`idle timeout: ${s}`),this.clearRun()),this.emit("exit",-1)},V))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveCwd(){const e=this.options.aibotSessionId?this.options.bindingStore?.get(this.options.aibotSessionId)?.cwd:void 0;if(e)return e;const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}getSessionCwd(e){return this.sessions.get(e)?.cwd??this.options.bindingStore?.get(e)?.cwd??this.resolveCwd()}buildPromptText(e){let t=e.text;return e.contextMessages&&e.contextMessages.length>0&&(t=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
|
|
1
|
+
import{EventEmitter as T}from"node:events";import{stat as P}from"node:fs/promises";import{existsSync as _,mkdirSync as b,readFileSync as C,writeFileSync as E}from"node:fs";import{join as I,resolve as $,dirname as O}from"node:path";import{homedir as M}from"node:os";import{fileURLToPath as F}from"node:url";import{resolveCommandPath as B,spawnCommand as j,killProcessGroup as w,hasChildProcesses as D}from"../../core/runtime/spawn.js";import{InternalApiServer as N}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as Q}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as L}from"../../default-skills/index.js";import{buildSimpleProbeReport as U}from"../shared/probe-util.js";import{compactToolInputForWire as H}from"../shared/tool-wire-payload.js";import{buildOpencodeConfigContent as q}from"./opencode-config.js";import{OpenCodeTransport as J}from"./opencode-transport.js";import{log as o}from"../../core/log/index.js";import{splitTextForAibotProtocol as k}from"../../core/protocol/index.js";class G extends T{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){o.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const X=200,z=2e3,W=12e4,V=90*1e3,y=1800*1e3,A=3e4,R=600*1e3,Y="claude_interaction_reply",K="127.0.0.1",Z=0,ee=1e3;function x(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class ge extends T{type="opencode";config;callbacks;options;identity;process=null;transport=new J;alive=!1;stopped=!1;internalApi=null;sessions=new Map;activeRun=null;completedEvents=new Set;clientMsgSeq=0;auditCaptures=new Map;completedAuditBoundaries=new Map;idleTimer=null;lastSseAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;toolCardsSent=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;pendingQuestions=new Map;permissionHandler=null;constructor(e,t,s){super(),this.config=e,this.callbacks=t,this.options=s??{},this.identity=new Q("opencode-adapter",t.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}async start(){await this.startInternalApiAndInjectMcp();const e=this.options.hostname??K,t=this.options.port??Z,s=await this.spawnAndWait(e,t),i=this.resolveCwd();await this.transport.connect(s,i),this.transport.on("event",n=>this.handleSseEvent(n)),o.info("opencode-adapter",`Ready (pid=${this.process?.pid}, url=${s})`)}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.transport.disconnect(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.process){const e=this.process;try{w(e,"SIGTERM")}catch{}const t=setTimeout(()=>{try{w(e,"SIGKILL")}catch{}},5e3);e.on("exit",()=>clearTimeout(t)),this.process=null}}isAlive(){return this.alive}async createSession(e){const t=e.cwd??this.resolveCwd();await this.transport.useDirectory(t);const s=await this.transport.createSession({title:`grix-${Date.now()}`},t);return this.sessions.set(s.id,{ocSessionId:s.id,cwd:t}),o.info("opencode-adapter",`Created OC session ${s.id} for cwd=${t}`),s.id}async resumeSession(e,t){const s=this.sessions.get(e);if(s?.ocSessionId)try{await this.transport.useDirectory(s.cwd),await this.transport.getSession(s.ocSessionId,s.cwd)}catch{o.warn("opencode-adapter",`OC session ${s.ocSessionId} gone, will create new on next prompt`),s.ocSessionId=""}}async destroySession(e){const t=this.sessions.get(e),s=t?t.ocSessionId:e;if(s)try{await this.transport.deleteSession(s,t?.cwd)}catch{}this.sessions.delete(e),this.identity.forgetSession(e)}sendPrompt(e){const t=new G(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(s=>{t.emitError(s instanceof Error?s:new Error(String(s)))}),t}async cancel(e){if(this.activeRun)try{await this.transport.abortSession(this.activeRun.ocSessionId,this.activeRun.cwd)}catch{}}deliverInboundEvent(e){const{event_id:t,session_id:s,content:i}=e;if(this.completedEvents.has(t)){o.info("opencode-adapter",`Dropping duplicate event ${t}`),this.callbacks.sendEventAck(t,s),this.callbacks.sendEventResult(t,"responded");return}if(!this.alive){o.warn("opencode-adapter",`Dropping event ${t}: process not alive`),this.callbacks.sendEventAck(t,s),this.callbacks.sendEventResult(t,"failed","Agent process not running");return}this.activeRun&&this.activeRun.eventId!==t&&(o.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${t}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),o.info("opencode-adapter",`prompt: event=${t} session=${s}`),this.callbacks.sendEventAck(t,s),this.startRun(t,s,e.audit?.enabled===!0),this.startComposing(s),this.resetIdleTimer();const n=this.buildPromptTextFromEvent(e);this.sendOcPrompt(s,n).catch(r=>{o.error("opencode-adapter",`prompt_async failed: ${r}`),this.finishRun("failed",String(r))})}deliverStopEvent(e,t){this.activeRun&&this.activeRun.eventId===e&&(o.info("opencode-adapter",`stop: event=${e}`),this.rejectAllPendingInteractions(),this.transport.abortSession(this.activeRun.ocSessionId,this.activeRun.cwd).catch(()=>{}),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.sessions.size}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.rejectAllPendingInteractions(),this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=$(F(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?D(e,[e]):!1}async probe(e){const t=this.getStatus();return U(this.config.command||"opencode",{alive:t.alive,busy:t.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){try{this.internalApi=new N,this.internalApi.setInvokeHandler(async(d,p,c,u)=>this.callbacks.agentInvoke(d,p,u)),await this.internalApi.start(0),o.info("opencode-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),t=process.env.XDG_CONFIG_HOME||I(M(),".config"),s=I(t,"opencode","opencode.json");b(O(s),{recursive:!0});let i={};try{_(s)&&(i=JSON.parse(C(s,"utf8")))}catch{}const n=i.mcp&&typeof i.mcp=="object"?i.mcp:{};n[e.name]={type:"local",command:[e.command,...e.args??[]],enabled:!0},i.mcp=n,E(s,`${JSON.stringify(i,null,2)}
|
|
2
|
+
`,"utf8"),o.info("opencode-adapter",`MCP config injected into ${s}`);const r=I(t,"opencode","skills"),a=L(r);a.length>0&&o.info("opencode-adapter",`Synced connector skills to ${r}: [${a.join(", ")}]`)}catch(e){o.warn("opencode-adapter",`Failed to inject MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`)}}async handleLocalAction(e){const{action_type:t}=e;if(t==="exec_approve"||t==="exec_reject"||t==="permission_approve"||t==="permission_reject")return this.handlePermissionAction(e);if(t===Y){const s=e.params??{};if(String(s.kind??"")==="permission"){const i=s.resolution??{},n=String(i.value??"");return this.handlePermissionAction({...e,action_type:n==="allow"?"exec_approve":"exec_reject",params:{...s,approval_command_id:s.request_id}})}return this.handleQuestionReplyAction(e)}return{handled:!1,kind:""}}bindSession(e,t){if(o.info("opencode-adapter",`bindSession: ${e} \u2192 ${t}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:t});else{const s=this.sessions.get(e);s.cwd=t}}async spawnAndWait(e,t){const s=this.resolveCwd();try{if(!(await P(s)).isDirectory())throw new Error(`Bound path is not a directory: ${s}`)}catch(i){throw String(i?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${s}. Please rebind with /grix open <valid-directory>.`):i}return new Promise((i,n)=>{const r=this.config.command||"opencode",d=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${t}`],p={...process.env,...this.config.env},c=q({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider});c&&(p.OPENCODE_CONFIG_CONTENT=JSON.stringify(c));const u=B(r,typeof p.PATH=="string"?p.PATH:void 0);o.info("opencode-adapter",`Spawning: ${u} ${d.join(" ")} (cwd=${s})`),this.process=j(u,d,{env:p,cwd:s}).process;let f="",l=!1;const m=setTimeout(()=>{l||(l=!0,n(new Error(`opencode serve did not start after ${A/1e3}s`)))},A);this.process.stdout?.on("data",h=>{if(f+=h.toString(),!l)for(const v of f.split(`
|
|
3
|
+
`)){const S=v.match(/opencode server listening on (https?:\/\/[^\s]+)/);if(S){clearTimeout(m),l=!0,this.alive=!0,i(S[1]);return}}}),this.process.stderr?.on("data",h=>{const v=h.toString().trim();v&&o.info("opencode-adapter",`[stderr] ${v}`)}),this.process.on("error",h=>{o.error("opencode-adapter",`Spawn error: ${h.message}`),clearTimeout(m),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${h.message}`),this.clearRun()),l?this.stopped||this.emit("exit",1):(l=!0,n(h))}),this.process.on("exit",h=>{o.info("opencode-adapter",`Process exited (code=${h})`),clearTimeout(m),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${h})`),this.clearRun()),l?this.stopped||this.emit("exit",h??1):(l=!0,n(new Error(`opencode serve exited with code ${h}`)))})})}async ensureOcSession(e){const t=this.sessions.get(e),s=this.getSessionCwd(e);if(await this.transport.useDirectory(s),t?.ocSessionId)try{return await this.transport.getSession(t.ocSessionId,s),t.ocSessionId}catch{o.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, creating new`),t.ocSessionId=""}const i=this.options.bindingStore?.getAcpSessionId(e);if(i)try{return await this.transport.getSession(i,s),this.sessions.set(e,{ocSessionId:i,cwd:s}),o.info("opencode-adapter",`Resumed OC session ${i} for aibot=${e}`),i}catch{o.warn("opencode-adapter",`Persisted OC session ${i} gone, creating new`)}const n=await this.transport.createSession({title:`grix-${e.slice(-8)}`},s);return this.sessions.set(e,{ocSessionId:n.id,cwd:s}),this.options.bindingStore?.setAcpSessionId(e,n.id),o.info("opencode-adapter",`Created OC session ${n.id} for aibot=${e}`),n.id}async sendOcPrompt(e,t){const s=this.getSessionCwd(e),i=await this.ensureOcSession(e);this.activeRun&&(this.activeRun.ocSessionId=i,this.activeRun.cwd=s),await this.transport.sendPromptAsync(i,{parts:[{type:"text",text:t}]},s)}handleSseEvent(e){if(!this.stopped){if(this.lastSseAt=Date.now(),this.updateToolInFlight(e),this.resetIdleTimer(),this.activeRun){const t=this.auditCaptures.get(this.activeRun.eventId);t&&t.push({sequence:t.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(e.type){case"message.part.updated":{if(!this.activeRun)break;const t=e.part,s=e.delta;if(t.type==="text"){const i=s||t.text;i&&this.acceptAssistantPartText(t.messageID,"text",i)}else t.type==="reasoning"?s&&this.acceptAssistantPartText(t.messageID,"reasoning",s):t.type==="tool"&&this.handleToolPartUpdate(t,s);break}case"message.updated":{if(!this.activeRun)break;const t=e.info;if(this.rememberMessageRole(t),t.role==="assistant"){const s=t;this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.activeRun.cwd,{model_provider:s.providerID,model_id:s.modelID}),s.error&&o.warn("opencode-adapter",`Message error: ${JSON.stringify(s.error)}`);const i=this.activeRun.ocSessionId;i&&s.sessionID===i&&(s.error?(this.flushTextBuffer(),this.finishRun("failed",s.error.message||s.error.type)):s.time?.completed&&s.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}break}case"session.idle":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.status":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&e.status.type==="idle"&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.error":{if(!this.activeRun)break;const t=e.error,s=t?typeof t=="object"&&"message"in t?t.message:JSON.stringify(t):"unknown session error";o.error("opencode-adapter",`Session error: ${s}`),this.flushTextBuffer(),this.finishRun("failed",s);break}case"permission.updated":{this.handlePermission(e.permission);break}case"permission.asked":{this.handlePermissionAsked(e);break}case"question.asked":{this.handleQuestionAsked(e);break}case"permission.replied":case"question.replied":case"question.rejected":o.debug("opencode-adapter",`Interaction settled: ${e.type}`);break;case"session.created":case"session.updated":case"session.deleted":case"session.compacted":case"session.diff":case"file.edited":case"server.connected":break;case"server.instance.disposed":{o.warn("opencode-adapter",`Server instance disposed: ${e.directory}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"failed","server instance disposed"),this.clearRun()),this.stopped||this.emit("exit",-1);break}default:o.debug("opencode-adapter",`Unhandled SSE event type: ${e.type}`);break}}}updateToolInFlight(e){if(e.type!=="message.part.updated")return;const t=e.part;if(t?.type!=="tool"||!t.callID)return;const s=t.state?.status;s==="pending"||s==="running"?this.toolCallsInFlight.add(t.callID):(s==="completed"||s==="error")&&this.toolCallsInFlight.delete(t.callID)}rememberMessageRole(e){const t=typeof e.id=="string"?e.id.trim():"";t&&(e.role!=="user"&&e.role!=="assistant"||(this.messageRoles.set(t,e.role),this.flushOrDropPendingParts(t,e.role)))}acceptAssistantPartText(e,t,s){if(!this.activeRun||!s)return;const i=typeof e=="string"?e.trim():"";if(!i)return;const n=this.messageRoles.get(i);if(n==="user")return;if(n==="assistant"){this.emitAssistantPartChunk(t,s);return}const r=this.pendingPartChunks.get(i)??[];r.push({kind:t,value:s}),this.pendingPartChunks.set(i,r)}flushOrDropPendingParts(e,t){const s=this.pendingPartChunks.get(e);if(this.pendingPartChunks.delete(e),!(!s||s.length===0)&&t==="assistant")for(const i of s)this.emitAssistantPartChunk(i.kind,i.value)}emitAssistantPartChunk(e,t){if(!(!this.activeRun||!t)){if(e==="reasoning"){this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,t);return}this.appendText(t)}}clearMessageRoleState(){this.messageRoles.clear(),this.pendingPartChunks.clear()}handleToolPartUpdate(e,t){if(!this.activeRun)return;const s=e.state;switch(s.status){case"pending":case"running":{this.sendToolUseOnce(e,s.input);break}case"completed":{this.sendToolUseOnce(e,s.input);break}case"error":{this.sendToolUseOnce(e,s.input),this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,"(failed)");break}}}sendToolUseOnce(e,t){!this.activeRun||this.toolCardsSent.has(e.callID)||(this.flushTextBuffer(),this.toolCardsSent.add(e.callID),this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,H(t??{})))}onPermissionTimeout(e){const t=this.pendingPermissions.get(e);t&&(this.pendingPermissions.delete(e),o.error("opencode-adapter",`Permission approval timeout: ${e}`),this.transport.respondPermission(t.ocSessionId,e,"reject",t.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===t.eventId&&(this.flushTextBuffer(),this.finishRun("failed","permission approval timeout")))}trackPendingPermission(e){if(!this.activeRun)return;this.stopIdleTimer();const t=setTimeout(()=>this.onPermissionTimeout(e),R);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:t})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(r=>{o.warn("opencode-adapter",`Orphan permission reject failed: ${r}`)});return}const{eventId:t,sessionId:s,ocSessionId:i}=this.activeRun;if(this.options.permissionPolicy==="fullAuto"){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(r=>{o.warn("opencode-adapter",`Auto-approve failed: ${r}`)});return}this.trackPendingPermission(e.id);const n=e.patterns.length>0?`${e.permission}: ${e.patterns.join(", ")}`:e.permission;this.callbacks.sendPermissionCard?this.callbacks.sendPermissionCard({eventId:t,sessionId:s,approvalId:e.id,toolName:e.permission,toolTitle:n,toolInput:JSON.stringify(e.metadata??{})}):this.callbacks.sendToolUse(t,s,e.permission,JSON.stringify(e.metadata??{}))}handlePermission(e){if(!this.activeRun)return;const{eventId:t,sessionId:s,ocSessionId:i}=this.activeRun;if(this.options.permissionPolicy==="fullAuto"){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(n=>{o.warn("opencode-adapter",`Auto-approve failed: ${n}`)});return}if(this.trackPendingPermission(e.id),this.callbacks.sendPermissionCard)this.callbacks.sendPermissionCard({eventId:t,sessionId:s,approvalId:e.id,toolName:e.type,toolTitle:e.title||e.type,toolInput:JSON.stringify(e.metadata??{})});else{const n=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(t,s,e.type,n)}}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const t=e.params??{},s=String(t.approval_id??t.approval_command_id??t.approvalId??t.tool_call_id??"");let i=s?this.pendingPermissions.get(s):void 0;if(!i){for(const a of this.pendingPermissions.values())if(a.eventId===this.activeRun.eventId){i=a;break}}if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:"permission"};const n=e.action_type==="exec_approve"||e.action_type==="permission_approve",r=n?"once":"reject";return clearTimeout(i.timer),this.pendingPermissions.delete(i.permissionId),this.transport.respondPermission(i.ocSessionId,i.permissionId,r,i.cwd).then(()=>{o.info("opencode-adapter",`Permission ${r}: ${i.permissionId}`),this.resetIdleTimer()}).catch(a=>{o.warn("opencode-adapter",`Permission response failed: ${a}`),this.resetIdleTimer()}),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.permissionId,decision:n?"approve":"reject"}),{handled:!0,kind:"permission"}}onQuestionTimeout(e){const t=this.pendingQuestions.get(e);t&&(this.pendingQuestions.delete(e),o.error("opencode-adapter",`Question answer timeout: ${e}`),this.transport.rejectQuestion(e,t.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===t.eventId&&(this.flushTextBuffer(),this.finishRun("failed","question answer timeout")))}handleQuestionAsked(e){if(!this.activeRun){this.transport.rejectQuestion(e.id).catch(n=>{o.warn("opencode-adapter",`Orphan question reject failed: ${n}`)});return}const{eventId:t,sessionId:s}=this.activeRun;this.stopIdleTimer();const i=setTimeout(()=>this.onQuestionTimeout(e.id),R);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:t,cwd:this.activeRun.cwd,questions:e.questions,timer:i}),this.callbacks.sendAgentQuestionCard)this.callbacks.sendAgentQuestionCard(t,s,{request_id:e.id,mode:"form",questions:e.questions.map(n=>({header:n.header,prompt:n.question,...n.options.length>0?{options:n.options.map(r=>r.label)}:{},...n.multiple!==void 0?{multi_select:n.multiple}:{}})),expires_at:Date.now()+R});else{const n=e.questions.map(r=>r.question).join(`
|
|
4
|
+
`);this.callbacks.sendRunError(t,s,`Agent asks: ${n}`)}}handleQuestionReplyAction(e){const t=e.params??{},s=String(t.request_id??""),i=s?this.pendingQuestions.get(s):void 0;if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"interaction_request_not_pending","The question is no longer pending; the reply was not delivered."),{handled:!0,kind:"question_reply"};const n=t.resolution??{},r=String(n.type??""),a=(c,u)=>{clearTimeout(i.timer),this.pendingQuestions.delete(i.requestId),c().then(()=>this.resetIdleTimer()).catch(f=>{o.warn("opencode-adapter",`Question response failed: ${f}`),this.resetIdleTimer()}),this.callbacks.sendLocalActionResult(e.action_id,"ok",u)};if(r==="action"){const c=String(n.value??"");if(c==="cancel"||c==="decline")return a(()=>this.transport.rejectQuestion(i.requestId,i.cwd),{request_id:s,resolution:"cancel"}),{handled:!0,kind:"question_reply"}}let d=null;if(Array.isArray(t.answers))d=t.answers.map(c=>Array.isArray(c)?c.map(String):[String(c)]);else if(r==="text"){const c=String(n.value??"");c&&(d=i.questions.map((u,f)=>f===0?[c]:[]))}else if(r==="map"){const c=Array.isArray(n.entries)?n.entries:[];d=i.questions.map((u,f)=>{const l=c.find(m=>m.key===u.header||m.key===String(f));return l&&l.value?[l.value]:[]})}if(!d||d.every(c=>c.length===0))return a(()=>this.transport.rejectQuestion(i.requestId,i.cwd),{request_id:s,resolution:"cancel"}),{handled:!0,kind:"question_reply"};const p=d;return a(()=>this.transport.replyQuestion(i.requestId,p,i.cwd),{request_id:s,resolution:"answer"}),{handled:!0,kind:"question_reply"}}rejectAllPendingInteractions(){for(const e of this.pendingPermissions.values())clearTimeout(e.timer),this.transport.respondPermission(e.ocSessionId,e.permissionId,"reject",e.cwd).catch(()=>{});this.pendingPermissions.clear();for(const e of this.pendingQuestions.values())clearTimeout(e.timer),this.transport.rejectQuestion(e.requestId,e.cwd).catch(()=>{});this.pendingQuestions.clear()}hasPendingInteractionForRun(e){for(const t of this.pendingPermissions.values())if(t.eventId===e)return!0;for(const t of this.pendingQuestions.values())if(t.eventId===e)return!0;return!1}startRun(e,t,s=!1){this.activeRun={eventId:e,sessionId:t,ocSessionId:"",cwd:this.getSessionCwd(t),chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null},this.toolCardsSent.clear(),s&&this.auditCaptures.set(e,[]),this.lastSseAt=Date.now(),this.livenessExtendStartAt=void 0}finishRun(e,t){const s=this.activeRun;if(!s)return;if(this.completedEvents.add(s.eventId),this.completedEvents.size>ee){const a=[...this.completedEvents].slice(-500);this.completedEvents=new Set(a)}this.snapshotAuditBoundary(s),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopComposing(),this.stopIdleTimer();const i=++s.chunkSeq,n=s.clientMsgId;e==="failed"&&t&&this.callbacks.sendRunError(s.eventId,s.sessionId,t);const r=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(s.eventId,s.sessionId,n).then(()=>{this.callbacks.sendEventResult(s.eventId,e,t)}).catch(a=>{const d=e==="responded"?"failed":e,p=e==="responded"?`final output delivery failed: ${a instanceof Error?a.message:String(a)}`:t;this.callbacks.sendEventResult(s.eventId,d,p)}):(this.callbacks.sendStreamChunk(s.eventId,s.sessionId,"",i,!0,n),this.callbacks.sendEventResult(s.eventId,e,t))};if(s.textBuffer){this.stopTextFlush();for(const a of k(s.textBuffer))s.chunkSeq++,this.callbacks.sendStreamChunk(s.eventId,s.sessionId,a,s.chunkSeq,!1,s.clientMsgId);s.textBuffer=""}r(),this.emit("eventDone",s.eventId)}clearRun(){this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const e=this.activeRun?.eventId;this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopIdleTimer(),e&&this.emit("eventDone",e)}snapshotAuditBoundary(e){const t=this.auditCaptures.get(e.eventId);t&&(this.completedAuditBoundaries.set(e.eventId,{adapterType:"opencode",providerSessionId:e.ocSessionId||void 0,openCodeEvidence:{events:t}}),this.auditCaptures.delete(e.eventId))}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=z){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},X))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const e of k(this.activeRun.textBuffer))this.activeRun.chunkSeq++,this.callbacks.sendStreamChunk(this.activeRun.eventId,this.activeRun.sessionId,e,this.activeRun.chunkSeq,!1,this.activeRun.clientMsgId);this.activeRun.textBuffer=""}}stopTextFlush(){this.activeRun?.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null)}startComposing(e){}stopComposing(){}shouldExtendByLiveness(){if(!this.activeRun)return!1;const e=this.process?.pid;if(!this.alive||!e||!x(e))return!1;const t=Date.now(),s=this.lastSseAt>0?t-this.lastSseAt:Number.POSITIVE_INFINITY;if(s<V)return this.livenessExtendStartAt=t,o.info("opencode-adapter",`Liveness check: fresh SSE for ${this.activeRun.eventId} (sseAge=${s}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??t;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),t-n>y?(o.warn("opencode-adapter",`Liveness extension budget exhausted for ${this.activeRun.eventId} (no progress for ${Math.round((t-n)/6e4)}min), allowing idle fail`),!1):(o.info("opencode-adapter",`Liveness check: turn in progress for ${this.activeRun.eventId} (toolsInFlight=${this.toolCallsInFlight.size}, sseAge=${Number.isFinite(s)?`${s}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.activeRun)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.activeRun)return;if(this.hasPendingInteractionForRun(this.activeRun.eventId)&&this.shouldExtendByLiveness()){o.info("opencode-adapter",`Idle timeout skipped: pending interaction for ${this.activeRun.eventId}, resetting timer`),this.resetIdleTimer();return}if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const e=this.process?.pid,s=!!(this.alive&&e&&x(e))?`liveness budget exhausted after ${y/6e4}min`:"process not alive";o.error("opencode-adapter",`Idle timeout (${s}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`idle timeout: ${s}`),this.clearRun()),this.emit("exit",-1)},W))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveCwd(){const e=this.options.aibotSessionId?this.options.bindingStore?.get(this.options.aibotSessionId)?.cwd:void 0;if(e)return e;const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}getSessionCwd(e){return this.sessions.get(e)?.cwd??this.options.bindingStore?.get(e)?.cwd??this.resolveCwd()}buildPromptText(e){let t=e.text;return e.contextMessages&&e.contextMessages.length>0&&(t=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
|
|
4
5
|
`)+`
|
|
5
6
|
|
|
6
|
-
`+t),this.identity.injectOnce(e.adapterSessionId,t)}buildPromptTextFromEvent(e){let t=e.content||"";if(e.context_messages_json)try{const s=JSON.parse(e.context_messages_json);Array.isArray(s)&&s.length>0&&(t=s.map(
|
|
7
|
+
`+t),this.identity.injectOnce(e.adapterSessionId,t)}buildPromptTextFromEvent(e){let t=e.content||"";if(e.context_messages_json)try{const s=JSON.parse(e.context_messages_json);Array.isArray(s)&&s.length>0&&(t=s.map(n=>`[context] ${n.sender_id??"unknown"}: ${n.content}`).join(`
|
|
7
8
|
`)+`
|
|
8
9
|
|
|
9
|
-
`+t)}catch{}return this.identity.injectOnce(e.session_id,t)}}export{
|
|
10
|
+
`+t)}catch{}return this.identity.injectOnce(e.session_id,t)}}export{ge as OpenCodeAdapter};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{EventEmitter as
|
|
1
|
+
import{EventEmitter as f}from"node:events";import{log as l}from"../../core/log/index.js";const p=3e4,u=3e3,y=3e4;class b extends f{baseUrl="";directory="";abortController=null;closed=!1;sseConnected=!1;sseGeneration=0;async connect(t,e){this.baseUrl=t,this.directory=e??"",this.closed=!1,await this.subscribeEvents(),l.info("opencode-transport",`connected to ${t}`)}async useDirectory(t){const e=t??"";this.directory===e&&this.sseConnected&&!this.closed||(this.directory=e,!(!this.baseUrl||this.closed)&&(this.abortController&&(this.abortController.abort(),this.abortController=null),this.sseConnected=!1,await this.subscribeEvents(),l.info("opencode-transport",`switched directory to ${e||"<default>"}`)))}async subscribeEvents(){if(this.closed)return;const t=++this.sseGeneration,e=new AbortController;this.abortController=e;const s=new URL("/event",this.baseUrl);this.directory&&s.searchParams.set("directory",this.directory);const r=await fetch(s.toString(),{method:"GET",headers:{Accept:"text/event-stream"},signal:e.signal});if(!r.ok||!r.body)throw new Error(`SSE connect failed: ${r.status}`);this.sseConnected=!0,this.readSseStream(r.body.getReader(),t)}async readSseStream(t,e){const s=new TextDecoder;let r="";try{for(;!this.closed;){const{done:n,value:o}=await t.read();if(n)break;r+=s.decode(o,{stream:!0});const a=r.split(`
|
|
2
2
|
|
|
3
3
|
`);r=a.pop()??"";for(const h of a){const c=this.parseSseFrame(h);if(c)try{this.emit("event",c)}catch(i){const d=i instanceof Error?i.message:String(i);l.warn("opencode-transport",`event handler failed (${c.type}): ${d}`)}}}}catch(n){if(this.closed)return;const o=n instanceof Error?n.message:String(n);if(o.includes("abort"))return;l.warn("opencode-transport",`SSE error: ${o}, reconnecting...`),await this.reconnectSse(e)}finally{e===this.sseGeneration&&(this.sseConnected=!1)}}parseSseFrame(t){let e="",s=[];for(const r of t.split(`
|
|
4
4
|
`))r.startsWith("event:")?e=r.slice(6).trim():r.startsWith("data:")&&s.push(r.slice(5).trimStart());if(s.length===0)return null;try{const r=s.join(`
|
|
5
|
-
`),n=JSON.parse(r);if(e&&n.type!==e&&(n.type=e),n&&typeof n.properties=="object"&&n.properties!==null){const{properties:o,...a}=n;return{...a,...o}}return n}catch{return null}}async reconnectSse(t){if(this.closed||t!==this.sseGeneration)return;const e=
|
|
5
|
+
`),n=JSON.parse(r);if(e&&n.type!==e&&(n.type=e),n&&typeof n.properties=="object"&&n.properties!==null){const{properties:o,...a}=n;return{...a,...o}}return n}catch{return null}}async reconnectSse(t){if(this.closed||t!==this.sseGeneration)return;const e=u+Math.random()*u;if(await new Promise(s=>setTimeout(s,Math.min(e,y))),!this.closed&&t===this.sseGeneration)try{await this.subscribeEvents()}catch(s){if(this.closed)return;l.warn("opencode-transport",`SSE reconnect failed: ${s instanceof Error?s.message:String(s)}`),this.reconnectSse(this.sseGeneration)}}async request(t,e,s,r){if(this.closed)throw new Error("transport closed");const n=new URL(e,this.baseUrl),o=r?.directory??this.directory;o&&n.searchParams.set("directory",o);const a=new AbortController,h=setTimeout(()=>a.abort(),p);try{const c={method:t,headers:{"Content-Type":"application/json"},signal:a.signal};s!==void 0&&(c.body=JSON.stringify(s));const i=await fetch(n.toString(),c);if(i.status===204)return;const d=await i.json();if(!i.ok)throw new Error(`REST ${t} ${e}: ${i.status} ${JSON.stringify(d)}`);return d}finally{clearTimeout(h)}}async createSession(t,e){return this.request("POST","/session",t??{},{directory:e})}async getSession(t,e){return this.request("GET",`/session/${t}`,void 0,{directory:e})}async deleteSession(t,e){await this.request("DELETE",`/session/${t}`,void 0,{directory:e})}async sendPromptAsync(t,e,s){await this.request("POST",`/session/${t}/prompt_async`,e,{directory:s})}async abortSession(t,e){await this.request("POST",`/session/${t}/abort`,void 0,{directory:e})}async respondPermission(t,e,s,r){await this.request("POST",`/session/${t}/permissions/${e}`,{response:s},{directory:r})}async replyQuestion(t,e,s){await this.request("POST",`/question/${t}/reply`,{answers:e},{directory:s})}async rejectQuestion(t,e){await this.request("POST",`/question/${t}/reject`,void 0,{directory:e})}async listProviders(){return(await this.request("GET","/config/providers"))?.providers??[]}async healthCheck(){try{return(await fetch(new URL("/session",this.baseUrl).toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:AbortSignal.timeout(3e3)})).ok}catch{return!1}}disconnect(){this.closed=!0,this.sseGeneration++,this.abortController&&(this.abortController.abort(),this.abortController=null),this.sseConnected=!1,this.removeAllListeners()}get isConnected(){return this.sseConnected&&!this.closed}}export{b as OpenCodeTransport};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{log as O}from"../../core/log/index.js";import{openReadOnlyDatabase as R}from"../../core/util/sqlite-reader.js";import{SESSION_HISTORY_ERROR_CODES as p,SessionHistoryError as f,decodeOpaqueCursor as E,encodeOpaqueCursor as x,normalizeHistoryLimit as I,registerSessionHistoryReader as b}from"../shared/session-history.js";import{resolveOpenCodeDbPath as T}from"./session-scanner.js";const w="opencode-session-history",A=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function y(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function N(t){const s=E(t);if(s.v!==2||typeof s.t!="number"||!Number.isFinite(s.t)||s.t<0||typeof s.id!="string")throw new f(p.invalidCursor,`invalid opencode sync_history cursor: ${t}`);return{t:s.t,id:s.id}}function g(t){return x({v:2,t:t.t,id:t.id})}function $(t){return t==="user"||t==="assistant"||t==="system"||t==="tool"?t:"system"}const m=new Set(["pending","running"]);function S(t){try{const s=JSON.parse(t.data);return y(s)?s:null}catch{return null}}function D(t){const s=S(t);if(!s||s.type!=="tool")return!1;const e=y(s.state)?s.state:void 0,r=typeof e?.status=="string"?e.status:"";return m.has(r)}function P(t,s){const e=S(t);if(!e)return[];const r=typeof e.type=="string"?e.type:"",d=t.id||s,c=t.message_id||null,h=new Date(t.time_created).toISOString(),o=[];if(r==="text"){if(typeof e.text!="string"||!e.text)return[];o.push({role:$(t.role),content:e.text,msg_type:"text"})}else if(r==="reasoning"){if(typeof e.text!="string"||!e.text)return[];o.push({role:"assistant",content:e.text,msg_type:"thinking"})}else if(r==="tool"){const a=typeof e.tool=="string"?e.tool:"",i=typeof e.callID=="string"?e.callID:"",n=y(e.state)?e.state:void 0;if(!a||!i)return O.warn(w,`skipped unidentifiable tool part: ${d}`),[];const _=typeof n?.status=="string"?n.status:"";if(m.has(_))return[];let u="{}";try{u=JSON.stringify(n?.input??{})}catch{}o.push({role:"assistant",content:u,msg_type:"tool_use",extra:{tool_name:a,tool_use_id:i}}),_==="error"?o.push({role:"tool",content:typeof n?.error=="string"?n.error:"",msg_type:"tool_result",extra:{tool_use_id:i,is_error:!0}}):o.push({role:"tool",content:typeof n?.output=="string"?n.output:"",msg_type:"tool_result",extra:{tool_use_id:i}})}else return[];return o.map((a,i)=>({native_message_id:i===0?d:`${d}#${i}`,native_parent_id:c,created_at:h,...a}))}async function C(t,s){if(!A.test(t.agent_session_id))throw new f(p.invalidAgentSession,`invalid agent_session_id: ${t.agent_session_id}`);const e=t.cursor?N(t.cursor):{t:0,id:""},r=I(t.limit),d=s?.dbPath??T(),c=R(d);if(!c)throw new f(p.sourceUnreadable,`failed to open opencode database: ${d}`);try{if(c.all("SELECT id FROM session WHERE id = ?",t.agent_session_id).length===0)throw new f(p.sessionNotFound,`opencode session not found: ${t.agent_session_id}`);let o;try{o=c.all(`SELECT p.id, p.message_id, p.time_created, p.data,
|
|
2
|
+
json_extract(m.data, '$.role') AS role
|
|
3
|
+
FROM part p
|
|
4
|
+
LEFT JOIN message m ON m.id = p.message_id
|
|
5
|
+
WHERE p.session_id = ?
|
|
6
|
+
AND (p.time_created > ? OR (p.time_created = ? AND p.id > ?))
|
|
7
|
+
ORDER BY p.time_created, p.id
|
|
8
|
+
LIMIT ?`,t.agent_session_id,e.t,e.t,e.id,r+1)}catch(l){throw new f(p.sourceUnreadable,`failed to query opencode parts for ${t.agent_session_id}: ${l}`)}if(o.length===0)return{messages:[],has_more:!1,next_cursor:t.cursor??g(e),...t.sync_run_id?{sync_run_id:t.sync_run_id}:{}};let a=o.length>r;const i=o.slice(0,r),n=[],_=[];for(const l of i){if(D(l)){a=!1;break}n.push(l),_.push(...P(l,`part-${l.time_created}-${n.length-1}`))}const u=n[n.length-1];return{messages:_,has_more:a,next_cursor:u?g({t:u.time_created,id:u.id}):t.cursor??g(e),...t.sync_run_id?{sync_run_id:t.sync_run_id}:{}}}finally{c.close()}}b("opencode",C);export{C as readOpenCodeSessionHistory};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{isAbsolute as x,join as S,resolve as u,sep as k}from"node:path";import{readJsonlHistoryPage as A,registerSessionHistoryReader as b,SESSION_HISTORY_ERROR_CODES as d,SessionHistoryError as _}from"../shared/session-history.js";import{resolvePiAgentDir as R}from"./session-scanner.js";function c(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function I(t){if(typeof t=="string")return t;if(Array.isArray(t)){const r=[];for(const n of t)c(n)&&n.type==="text"&&typeof n.text=="string"&&r.push(n.text);return r.join(`
|
|
2
|
+
`)}return t==null?"":String(t)}function v(t,r){if((typeof t.type=="string"?t.type:"")!=="message")return[];const e=c(t.message)?t.message:void 0;if(!e)return[];const p=typeof e.role=="string"?e.role:"",y=typeof t.id=="string"&&t.id?t.id:r,m=typeof t.parentId=="string"?t.parentId:null,h=typeof t.timestamp=="string"?t.timestamp:typeof e.timestamp=="string"?e.timestamp:"",a=[];if(p==="user"){const s=e.content;if(typeof s=="string")a.push({role:"user",content:s,msg_type:"text"});else if(Array.isArray(s))for(const i of s){if(!c(i))continue;const l=i;l.type==="text"&&typeof l.text=="string"&&a.push({role:"user",content:l.text,msg_type:"text"})}}else if(p==="assistant"){const s=e.content,i=typeof e.model=="string"?e.model:void 0;if(typeof s=="string")a.push({role:"assistant",content:s,msg_type:"text",...i?{extra:{model:i}}:{}});else if(Array.isArray(s))for(const l of s){if(!c(l))continue;const o=l;if(o.type==="text"&&typeof o.text=="string")a.push({role:"assistant",content:o.text,msg_type:"text",...i?{extra:{model:i}}:{}});else if(o.type==="thinking"){const f=typeof o.thinking=="string"?o.thinking:typeof o.text=="string"?o.text:"";if(!f)continue;a.push({role:"assistant",content:f,msg_type:"thinking"})}else if(o.type==="toolCall"){const f={};typeof o.name=="string"&&(f.tool_name=o.name),typeof o.id=="string"&&(f.tool_use_id=o.id);let g="{}";try{g=JSON.stringify(o.arguments??{})}catch{}a.push({role:"assistant",content:g,msg_type:"tool_use",...Object.keys(f).length>0?{extra:f}:{}})}}}else if(p==="toolResult"){const s={};typeof e.toolCallId=="string"&&(s.tool_use_id=e.toolCallId),e.isError===!0&&(s.is_error=!0),a.push({role:"tool",content:I(e.content),msg_type:"tool_result",...Object.keys(s).length>0?{extra:s}:{}})}else return[];return a.map((s,i)=>({native_message_id:i===0?y:`${y}#${i}`,native_parent_id:m,created_at:h,...s}))}function w(t,r){const n=t.agent_session_id;if(!n||!x(n))throw new _(d.invalidAgentSession,`invalid pi agent_session_id (expect absolute session file path): ${t.agent_session_id}`);const e=u(r?.sessionsDir??S(R(),"sessions")),p=u(n);if(p!==e&&!p.startsWith(e+k))throw new _(d.invalidAgentSession,`pi session path escapes sessions dir: ${t.agent_session_id}`);return p}async function O(t,r){const n=w(t,r);return{...await A({filePath:n,cursor:t.cursor,limit:t.limit,mapLine:v,sourceLabel:"pi session transcript",logTag:"pi-session-history"}),...t.sync_run_id?{sync_run_id:t.sync_run_id}:{}}}b("pi",O);export{O as readPiSessionHistory};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
import{createReadStream as v,statSync as I}from"node:fs";import{createInterface as N}from"node:readline";import{log as R}from"../../core/log/index.js";const s={agentSessionRequired:"history_agent_session_required",invalidAgentSession:"history_invalid_agent_session",cwdRequired:"history_cwd_required",sessionNotFound:"history_session_not_found",invalidCursor:"history_invalid_cursor",sourceUnreadable:"history_source_unreadable",providerUnsupported:"history_provider_unsupported",runtimeError:"history_runtime_error"};class o extends Error{code;constructor(e,d){super(d),this.name="SessionHistoryError",this.code=e}}const b=new Map;function A(r,e){b.set(r,e)}function B(r){return b.get(r)}const C=50,O=200;function H(r){if(typeof r!="number"||!Number.isFinite(r)||r===0)return C;const e=Math.floor(r);return e<1?1:e>O?O:e}function $(r){const e={v:1,off:r};return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}function L(r){const e=T(r);if(e.v!==1||typeof e.off!="number"||!Number.isInteger(e.off)||e.off<0)throw new o(s.invalidCursor,`invalid sync_history cursor: ${r}`);return e.off}function J(r){return Buffer.from(JSON.stringify(r),"utf8").toString("base64url")}function T(r){try{const e=JSON.parse(Buffer.from(r,"base64url").toString("utf8"));if(!e||typeof e!="object"||Array.isArray(e))throw new Error("bad cursor payload");return e}catch(e){throw e instanceof o?e:new o(s.invalidCursor,`invalid sync_history cursor: ${r}`)}}async function z(r){const{filePath:e,mapLine:d,sourceLabel:n}=r,i=r.cursor?L(r.cursor):0,x=H(r.limit);let a;try{const t=I(e);if(t.isDirectory())throw new o(s.sourceUnreadable,`${n} is a directory: ${e}`);a=t.size}catch(t){throw t instanceof o?t:t.code==="ENOENT"?new o(s.sessionNotFound,`${n} not found: ${e}`):new o(s.sourceUnreadable,`failed to stat ${n} ${e}: ${t}`)}if(i>a)throw new o(s.invalidCursor,`cursor offset ${i} is beyond ${n} size ${a}: ${e}`);if(i===a)return{messages:[],has_more:!1,next_cursor:$(i)};const f=[];let l=!1,y=0,p=!1,c=i;const h=v(e,{start:i}),_=N({input:h,crlfDelay:1/0});try{for await(const t of _){const u=c,m=Buffer.byteLength(t,"utf8");if(u+m===a)break;c=u+m+1;const S=t.trim();if(!S)continue;let g;try{g=JSON.parse(S)}catch{y++;continue}const w=d(g,`line-${u}`);if(p){if(w.length>0){l=!0;break}continue}for(const E of w)f.push({message:E,lineEndOffset:c});f.length>=x&&(p=!0)}}catch(t){throw new o(s.sourceUnreadable,`failed to read ${n} ${e}: ${t}`)}finally{_.close(),h.destroy()}return y>0&&R.warn(r.logTag??n,`skipped ${y} malformed line(s) in ${e}`),{messages:f.map(t=>t.message),has_more:l,next_cursor:$(l?f[f.length-1].lineEndOffset:c)}}export{C as SESSION_HISTORY_DEFAULT_LIMIT,s as SESSION_HISTORY_ERROR_CODES,O as SESSION_HISTORY_MAX_LIMIT,o as SessionHistoryError,L as decodeOffsetCursor,T as decodeOpaqueCursor,$ as encodeOffsetCursor,J as encodeOpaqueCursor,B as getSessionHistoryReader,H as normalizeHistoryLimit,z as readJsonlHistoryPage,A as registerSessionHistoryReader};
|