grix-connector 4.18.1 → 4.19.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 -0
- package/dist/adapter/claude/claude-tools.js +1 -0
- package/dist/adapter/claude/claude-worker-client.js +1 -0
- package/dist/adapter/claude/mcp-http-launcher.js +2 -0
- package/dist/adapter/claude/result-timeout.js +1 -0
- package/dist/adapter/deepseek/deepseek-adapter.js +6 -0
- package/dist/adapter/deepseek/index.js +1 -0
- package/dist/adapter/deepseek-harness/dsh-version.js +1 -1
- package/dist/adapter/deepseek-harness/profile-runtime.js +2 -2
- package/dist/adapter/opencode/opencode-transport.js +1 -1
- package/dist/adapter/opencode/opencode-v2-events.js +1 -1
- package/dist/adapter/pi/pi-adapter.js +4 -4
- package/dist/adapter/qwen/index.js +1 -0
- package/dist/adapter/qwen/qwen-adapter.js +4 -0
- package/dist/aibot/client.js +1 -0
- package/dist/aibot/index.js +1 -0
- package/dist/aibot/types.js +0 -0
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.19.0.tgz +0 -0
- package/dist/assets/dsh-bridge/manifest.json +6 -6
- package/dist/bridge/cli-install-flow.js +1 -1
- package/dist/bridge/cli-install-offer.js +1 -1
- package/dist/bridge/local-action-session-control.js +1 -1
- package/dist/bridge/session-control-open.js +1 -1
- package/dist/core/access/allowlist-gate.js +1 -0
- package/dist/core/access/allowlist-store.js +1 -0
- package/dist/core/access/index.js +1 -0
- package/dist/core/file-ops/handler.js +1 -0
- package/dist/core/file-ops/list-files.js +1 -0
- package/dist/core/file-ops/types.js +0 -0
- package/dist/core/mcp/tools.js +1 -1
- package/dist/default-skills/grix-chat-state/SKILL.md +34 -2
- package/dist/grix.js +0 -0
- package/dist/log.js +3 -0
- package/dist/main.js +31 -0
- package/dist/mcp/stream-http/config.js +1 -0
- package/dist/mcp/stream-http/connection-binding.js +1 -0
- package/dist/mcp/stream-http/event-tool-executor.js +1 -0
- package/dist/mcp/stream-http/gateway.js +1 -0
- package/dist/mcp/stream-http/index.js +1 -0
- package/dist/mcp/stream-http/security.js +1 -0
- package/dist/mcp/stream-http/session-manager.js +1 -0
- package/dist/mcp/stream-http/tool-executor.js +1 -0
- package/dist/mcp/stream-http/tool-registry.js +1 -0
- package/dist/mcp/stream-http/tool-schemas.js +1 -0
- package/dist/session/index.js +1 -0
- package/dist/session/manager.js +1 -0
- package/dist/transport/index.js +1 -0
- package/dist/transport/json-rpc.js +3 -0
- package/openclaw-plugin/index.js +99 -0
- package/openclaw-plugin/skills/grix-chat-state/SKILL.md +33 -1
- package/openclaw.plugin.json +1 -0
- package/package.json +1 -1
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.18.1.tgz +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const n of t)e.push(n);const r=Buffer.concat(e).toString("utf8").trim();return r?JSON.parse(r):{}}function k(t){const e=(t.headers.authorization??"").trim();return e.toLowerCase().startsWith("bearer ")?e.slice(7).trim():""}class w{host="127.0.0.1";port=0;token;callbacks;server=null;address=null;constructor(e){this.token=d(),this.callbacks=e}getToken(){return this.token}getURL(){return this.address?`http://${this.address.address}:${this.address.port}`:""}async start(){this.server||(this.server=c.createServer(async(e,r)=>{try{await this.handleRequest(e,r)}catch(n){h(r,n instanceof Error?n.message:String(n))}}),await new Promise((e,r)=>{this.server.once("error",r),this.server.listen(this.port,this.host,()=>{this.server.off("error",r),e()})}),this.address=this.server.address(),o.info("claude-bridge",`Bridge server listening on ${this.getURL()}`))}async stop(){if(!this.server)return;const e=this.server;this.server=null,this.address=null,e.closeIdleConnections?.(),e.closeAllConnections?.(),await new Promise((r,n)=>{e.close(s=>s?n(s):r())})}async handleRequest(e,r){if(k(e)!==this.token){l(r);return}if(e.method!=="POST"){r.writeHead(405,{"content-type":"application/json"}),r.end(JSON.stringify({error:"method_not_allowed"}));return}const n=new URL(e.url,"http://localhost").pathname,s=await v(e),i=f.get(n);if(!i){u(r);return}const a=await i(this.callbacks,s);p(r,a??{ok:!0})}}const f=new Map([["/v1/worker/register",async(t,e)=>(o.info("claude-bridge",`Worker registered: ${e.worker_id} (pid=${e.pid})`),t.onRegisterWorker(e))],["/v1/worker/status",async(t,e)=>(o.info("claude-bridge",`Worker status: ${e.status}`),t.onStatusUpdate(e))],["/v1/worker/send-text",async(t,e)=>t.onSendText(e)],["/v1/worker/send-stream-chunk",async(t,e)=>t.onSendStreamChunk(e)],["/v1/worker/send-media",async(t,e)=>t.onSendMedia(e)],["/v1/worker/delete-message",async(t,e)=>t.onDeleteMessage(e)],["/v1/worker/ack-event",async(t,e)=>t.onAckEvent(e)],["/v1/worker/event-result",async(t,e)=>t.onSendEventResult(e)],["/v1/worker/event-stop-ack",async(t,e)=>t.onSendEventStopAck(e)],["/v1/worker/event-stop-result",async(t,e)=>t.onSendEventStopResult(e)],["/v1/worker/session-composing",async(t,e)=>t.onSetSessionComposing(e)],["/v1/worker/agent-invoke",async(t,e)=>t.onAgentInvoke(e)],["/v1/worker/local-action-result",async(t,e)=>t.onLocalActionResult(e)]]);export{w as ClaudeBridgeServer};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{randomUUID as x}from"node:crypto";import{CallToolRequestSchema as S,ListToolsRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{log as f}from"../../core/log/index.js";import{toolCallToInvoke as k}from"../../core/mcp/tools.js";const E=new Set(["contact_search","session_search","message_history","message_search","group_create","group_detail_read","group_leave_self","group_member_add","group_member_remove","group_member_role_update","group_all_members_muted_update","group_member_speaking_update","group_dissolve","send_msg","delete_msg","agent_api_create","agent_category_list","agent_category_create","agent_category_update","agent_category_assign","agent_api_key_rotate"]),y=3e4,I=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},files:{type:"array",items:{type:"string"},description:"Optional absolute local file paths. Each file is uploaded through Agent API OSS presign before sending."},final:{type:"boolean",description:"Whether this is the final reply for the event. Defaults to false \u2014 the event stays open while Claude continues working, and auto-completes after inactivity. Set true only when this is definitively the last message for the event."}},required:["chat_id","event_id"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},code:{type:"string"},msg:{type:"string"}},required:["event_id","status"]}},{name:"delete_message",description:"Delete a previously sent message in the same grix-claude chat.",inputSchema:{type:"object",properties:{chat_id:{type:"string"},message_id:{type:"string"}},required:["chat_id","message_id"]}},{name:"status",description:"Show grix-claude runtime status, upstream access state, bridge health, and startup hints.",inputSchema:{type:"object",properties:{}}},{name:"send",description:"Send a message to a chat session proactively, without requiring an inbound event. Use for notifications or scheduled reports.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The target chat/session id."},text:{type:"string",description:"The message text to send."}},required:["chat_id","text"]}},{name:"access_pair",description:"Forward a sender pairing approval code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"access_deny",description:"Forward a sender pairing denial code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"allow_sender",description:"Ask upstream access control to allow a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"remove_sender",description:"Ask upstream access control to remove a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"access_policy",description:"Ask upstream access control to update the sender access policy.",inputSchema:{type:"object",properties:{policy:{type:"string",enum:["allowlist","open","disabled"]}},required:["policy"]}},{name:"grix_query",description:"Search contacts, sessions, message history, or messages by keyword in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},keyword:{type:"string"},id:{type:"string"},sessionId:{type:"string"},limit:{type:"number"},offset:{type:"number"},beforeId:{type:"string"}},required:["action"]}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string"},memberIds:{type:"array",items:{type:"string"}},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer",description:"Member type (for update_member_role / update_member_speaking)."},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted (for update_member_speaking)."}},required:["action"]}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},content:{type:"string"},msgType:{type:"number"},quotedMessageId:{type:"string"},threadId:{type:"string"}},required:["sessionId","content"]}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},msgId:{type:"string"}},required:["sessionId","msgId"]}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentId:{type:"string"},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"number"}},required:["action"]}}];function q(n,e){n.setRequestHandler(w,async()=>({tools:I})),n.setRequestHandler(S,async i=>{const{name:r,arguments:t}=i.params,s=t??{};try{switch(r){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(r,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(r,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${r}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${r} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(n,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const r=String(n.text??""),t=String(n.chat_id??""),s=String(n.event_id??i.eventId),a=n.reply_to,d=n.files,_=n.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!r.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,r),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(n,e){const i=e.getActiveEvent(),r=String(n.event_id??""),t=n.status??"",s=n.code,a=n.msg;if(!r||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(r)?(e.bridge.sendEventResult(r,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(n,e){const i=String(n.chat_id??""),r=String(n.message_id??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:r},y),c(`deleted (${r})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(n){const e=n.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(n,e){const i=String(n.chat_id??""),r=String(n.text??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(r),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(n,e,i){try{const r=C[n];if(!r)throw new Error(`Unknown access control tool: ${n}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:r.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}async function O(n,e,i){try{const r=k(n,e);if(!E.has(r.action))throw new Error(`Action not allowed: ${r.action}`);const t=await i.bridge.agentInvoke(r.action,r.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}function c(n){return{content:[{type:"text",text:n}]}}export{q as registerClaudeTools};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(t,e){this.controlURL=t.replace(/\/+$/,""),this.token=e.trim(),l.info("claude-worker-client",`Configured with control URL: ${this.controlURL}`)}async post(t,e,s){if(!this.isConfigured())throw new Error("worker control not configured");const i=new AbortController,o=setTimeout(()=>i.abort(),s);try{const r=await fetch(`${this.controlURL}${t}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.token}`},body:JSON.stringify(e),signal:i.signal}),n=await r.text(),a=n.trim()?JSON.parse(n):{};if(!r.ok)throw new Error(a.error||`worker control failed ${r.status}`);return a}finally{clearTimeout(o)}}isRetryableError(t){const e=t instanceof Error?t.message:String(t);return/fetch failed|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|aborted/i.test(e)}async postWithRetry(t,e,s,i=1){let o;for(let r=0;r<=i;r++)try{return r>0&&l.info("claude-worker-client",`Retrying ${t} attempt=${r+1}`),await this.post(t,e,s)}catch(n){if(o=n,r>=i||!this.isRetryableError(n))break;await new Promise(a=>setTimeout(a,150))}throw o instanceof Error?o:new Error(String(o))}async deliverEvent(t){return this.postWithRetry("/v1/worker/deliver-event",{payload:t},1e4,1)}async deliverStop(t){return this.postWithRetry("/v1/worker/deliver-stop",{payload:t},1e4,1)}async deliverLocalAction(t){return this.postWithRetry("/v1/worker/deliver-local-action",{payload:t},1e4,1)}async ping(){try{return await this.postWithRetry("/v1/worker/ping",{},5e3,1),!0}catch{return!1}}}export{c as ClaudeWorkerClient};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as l}from"./protocol-contract.js";function P(e){let t=null,r=0,n=!1,i=!1;const a=v(),s=e.gatewayUrl??"http://127.0.0.1:19580/mcp";return{async start(){await F(e.command,s,e.env);const c=E(e.grix),u=[...e.args??[],"--name",`grix-mcp-${e.name}`,"--session-id",a];e.fullAuto&&u.push("--dangerously-skip-permissions"),u.push("--dangerously-load-development-channels",`server:${l}`,"--append-system-prompt",c);const f=d(I(),`grix-mcp-claude-${e.name}`);await S(f,{recursive:!0});const{expectPath:$,pidPath:g}=await M(f,e.command,u),_={...process.env,...e.env??{}};t=x("/usr/bin/expect",[$],{cwd:e.cwd,env:_,stdio:["ignore","pipe","pipe"],detached:!0}),o.info("mcp-http-launcher",`\u542F\u52A8 Claude: name=${e.name} cwd=${e.cwd} pid=${t.pid}`),r=await k(g),n=!0,o.info("mcp-http-launcher",`Claude \u5B50\u8FDB\u7A0B PID: ${r}`),t.on("exit",(m,p)=>{o.info("mcp-http-launcher",`Claude \u9000\u51FA: code=${m} signal=${p}`),n=!1,t=null,r=0,i||(o.info("mcp-http-launcher","3 \u79D2\u540E\u81EA\u52A8\u91CD\u542F..."),setTimeout(()=>{i||this.start().catch(w=>{o.error("mcp-http-launcher",`\u91CD\u542F\u5931\u8D25: ${w}`)})},3e3))}),t.stdout?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stdout] ${p.slice(0,300)}`)}),t.stderr?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stderr] ${p.slice(0,300)}`)})},async stop(){if(i=!0,n=!1,r>0)try{process.kill(r,"SIGTERM")}catch{}if(t?.pid){try{process.kill(-t.pid,"SIGTERM")}catch{}await new Promise(c=>{const u=setTimeout(()=>{if(r>0)try{process.kill(r,"SIGKILL")}catch{}if(t?.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}c()},5e3);t?.once("exit",()=>{clearTimeout(u),c()})})}t=null,r=0},getStatus(){return{name:e.name,alive:n,pid:r}}}}function E(e){return["You are connected to a chat via the grix MCP server.",`On startup, immediately call grix_authorize with: agentId="${e.agentId}", apiKey="${e.apiKey}", wsUrl="${e.wsUrl}", clientType="${e.clientType}".`,"When you receive a <channel> message, you MUST respond by calling the grix_reply tool (or the grix_complete tool if no response is needed).","Never write your reply as plain text \u2014 it will NOT reach the user. Only the grix_reply tool delivers your response to the chat.","The <channel> message contains event_id and session_id \u2014 pass them to grix_reply."].join(" ")}async function F(e,t,r){const n=d(T(),".claude.json");let i=null;try{const s=C(n,"utf8");i=JSON.parse(s)?.mcpServers?.[l]??null}catch{}if(i&&String(i.type??"").trim()==="http"&&String(i.url??"").trim()===t)return;o.info("mcp-http-launcher",`\u6CE8\u518C MCP Server: ${l} -> ${t}`);const a={...process.env,...r??{}};try{y(`${e} mcp remove -s user ${l}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}catch{}y(`${e} mcp add --scope user --transport http ${l} ${t}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}async function M(e,t,r){const{writeFile:n}=await import("node:fs/promises"),i=d(e,"claude.pid"),a=d(e,"claude.expect"),s=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set claude_command [list {${h(t)}}${r.map(c=>` {${h(c)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${h(i)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","expect {"," -re {(?i)(Quick.*safety.*check|trust.*folder)} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)I am using this for local development} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)(Enter.*confirm|Press.*Enter|Hit.*Enter)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {Listening for channel} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," -re {bypass permissions} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," eof {}","}","expect eof",""];return await n(i,"","utf8"),await n(a,s.join(`
|
|
2
|
+
`),"utf8"),{expectPath:a,pidPath:i}}function h(e){return e.replace(/[\\{}$\[\]"]/g,"\\$&")}async function k(e,t=1e4){const{readFile:r}=await import("node:fs/promises"),n=Math.ceil(t/100);for(let i=0;i<n;i++){try{const a=await r(e,"utf8"),s=parseInt(String(a).trim(),10);if(Number.isFinite(s)&&s>0)return s}catch{}await new Promise(a=>setTimeout(a,100))}return 0}export{P as createMcpHttpLauncher};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(t){this.defaultTimeoutMs=t.defaultTimeoutMs??9e4,this.onTimeout=t.onTimeout}arm(t,e){this.cancel(t);const s=e?.timeoutMs??this.defaultTimeoutMs,i=Date.now()+s,o=setTimeout(()=>{this.timers.delete(t),this.onTimeout(t).catch(()=>{})},s);return this.timers.set(t,o),i}cancel(t){const e=this.timers.get(t);e&&(clearTimeout(e),this.timers.delete(t))}has(t){return this.timers.has(t)}close(){for(const t of this.timers.values())clearTimeout(t);this.timers.clear()}}export{m as ResultTimeoutManager};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{resolveCommandPath as f,spawnCommand as T}from"../../core/runtime/spawn.js";import{createInterface as w}from"node:readline";import{EventEmitter as I}from"node:events";import{formatInboundMessageReferenceText as _}from"../../core/protocol/message-reference.js";import{log as o}from"../../core/log/index.js";import{SessionBindingStore as E}from"../../core/persistence/session-binding-store.js";const S=120*1e3;class y extends I{type="deepseek";config;callbacks;alive=!1;stopped=!1;deepSeekSessionId=null;activeEventId=null;activeSessionId=null;chunkSeq=0;activeClientMsgId=null;idleTimer=null;activeProcess=null;composingTimer=null;composingTTLClear=null;composingTTL=12e4;composingRefreshInterval=3e4;bindingStore=null;aibotSessionId="";cwd;lastUsage=null;currentModel=null;constructor(e,s){super(),this.config=e,this.callbacks=s;const t=e.options??{};if(this.aibotSessionId=String(t.aibotSessionId??"").trim(),this.bindingStore=t.bindingStore instanceof E?t.bindingStore:null,this.cwd=this.resolveCwd(),this.bindingStore&&this.aibotSessionId){const i=this.bindingStore.getDeepSeekThreadId(this.aibotSessionId);i&&(this.deepSeekSessionId=i)}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}return process.cwd()}async start(){this.alive=!0,this.notifyBindingReady(),o.info("deepseek-adapter","Ready (exec mode)")}async stop(){this.stopped=!0,this.alive=!1,this.stopComposing(),this.clearIdleTimer(),this.killActiveProcess()}isAlive(){return this.alive}async createSession(e){const s=this.deepSeekSessionId??`ds-${Date.now()}`;return this.notifyBindingReady(),s}async resumeSession(e,s){}async destroySession(e){this.deepSeekSessionId=null,this.persistSessionId(void 0)}sendPrompt(e){const s=new k(e.adapterSessionId);return this.runMessage(e,s).catch(t=>{s.emitError(t instanceof Error?t:new Error(String(t)))}),s}async cancel(e){this.killActiveProcess()}setPermissionHandler(e){}async ping(e){return this.alive}getStatus(){return{alive:this.alive,busy:this.activeEventId!==null,sessions:this.deepSeekSessionId?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}clearActiveEventForShutdown(){this.clearIdleTimer(),this.killActiveProcess(),this.activeEventId=null}getMcpConfig(){return null}getUsageSnapshot(){return this.lastUsage}getSupportedCommands(){return[{name:"status",description:"Show session and working directory status"}]}async execCommand(e,s,t){return e==="status"?{status:"ok",message:`Session: ${this.deepSeekSessionId??"none"}, CWD: ${this.cwd}`,data:{sessionId:this.deepSeekSessionId,cwd:this.cwd,alive:this.alive}}:{status:"unsupported",message:`Unknown command: ${e}`}}async handleLocalAction(e){const s=e.action_type??"",t=e.params??{};switch(s){case"get_context":return this.callbacks.sendLocalActionResult(e.action_id,"ok",{sessionId:this.deepSeekSessionId,cwd:this.cwd,model:this.currentModel}),{handled:!0,kind:"get_context"};case"set_model":{const i=String(t.model_id??"").trim();return i?(this.currentModel=i,this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"model_set",modelId:i}),o.info("deepseek-adapter",`Model set to: ${i}`),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","model_id is required"),{handled:!0,kind:"set_model"})}default:return{handled:!1,kind:""}}}deliverInboundEvent(e){const s=_(e.content,{messageId:e.msg_id,quotedMessageId:e.quoted_message_id});if(this.activeEventId){o.info("deepseek-adapter",`Event ${e.event_id}: rejected, busy with ${this.activeEventId}`),this.callbacks.sendEventResult(e.event_id,"failed","agent busy");return}this.startNewMessage(e,s)}deliverStopEvent(e,s){this.activeEventId===e&&(this.callbacks.sendEventResult(e,"canceled","stopped by user"),this.clearActive())}startNewMessage(e,s){this.activeEventId=e.event_id,this.activeSessionId=e.session_id,this.chunkSeq=0,this.activeClientMsgId=`ds-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.startComposing();const t={adapterSessionId:this.deepSeekSessionId??"",text:s,contextMessages:e.context_messages_json?JSON.parse(e.context_messages_json).map(n=>({senderId:n.sender_id??"unknown",content:n.content})):void 0},i=new k(this.deepSeekSessionId??"");this.runMessage(t,i,e.event_id,e.session_id).catch(n=>{o.error("deepseek-adapter",`Message failed: ${n}`),this.callbacks.sendEventResult(e.event_id,"failed",n instanceof Error?n.message:String(n)),this.clearActive()}),this.resetIdleTimer(e.event_id)}buildExecArgs(e){const s=["exec","--output-format","stream-json"];return this.currentModel&&s.push("--model",this.currentModel),this.deepSeekSessionId&&s.push("--resume",this.deepSeekSessionId),s.push("--",e),s}async runMessage(e,s,t,i){let n=e.text;e.contextMessages&&e.contextMessages.length>0&&(n=`Conversation context:
|
|
2
|
+
${e.contextMessages.map(c=>`[${c.senderId??"unknown"}]: ${c.content}`).join(`
|
|
3
|
+
`)}
|
|
4
|
+
|
|
5
|
+
Latest user message:
|
|
6
|
+
${n}`);const h=this.config.command||"codewhale",d=this.buildExecArgs(n),u={...process.env,...this.config.env},g=f(h,typeof u.PATH=="string"?u.PATH:void 0);o.info("deepseek-adapter",`Spawning: ${g} ${d.slice(0,5).join(" ")}...`);const r=T(g,d,{cwd:this.cwd,env:u}).process;return this.activeProcess=r,r.stderr?.on("data",c=>{const l=c.toString().trim();l&&o.info("deepseek-adapter",`[deepseek stderr] ${l}`)}),new Promise((c,l)=>{let p=!1,m="";const v=()=>{this.activeProcess=null};r.on("error",a=>{p||(p=!0,v(),l(a))}),r.on("exit",a=>{if(m.trim()&&this.handleOutputLine(m.trim(),t),m="",p){v();return}if(p=!0,v(),a!==0&&t&&this.activeEventId===t){l(new Error(`deepseek exec exited with code ${a}`));return}s.emitDone({status:"completed"}),c()}),w({input:r.stdout}).on("line",a=>{a.trim()&&this.handleOutputLine(a.trim(),t)}),r.stdin?.end()})}handleOutputLine(e,s){let t;try{t=JSON.parse(e)}catch{o.error("deepseek-adapter",`Invalid JSON: ${e.slice(0,200)}`);return}switch(t.type){case"content":{const i=t.content;i&&s&&this.activeEventId===s&&this.activeSessionId&&(this.chunkSeq++,this.callbacks.sendStreamChunk(s,this.activeSessionId,i,this.chunkSeq,!1,this.activeClientMsgId??void 0),this.startComposing(),this.resetIdleTimer(s));break}case"session_capture":{const i=t.content;i&&(this.deepSeekSessionId=i,this.persistSessionId(i),o.info("deepseek-adapter",`Session captured: ${i}`));break}case"metadata":{const i=t.meta;if(i){o.info("deepseek-adapter",`Metadata: model=${i.model}, tokens_in=${i.input_tokens}, tokens_out=${i.output_tokens}`);const n=Number(i.input_tokens??0),h=Number(i.output_tokens??0);if(n>0||h>0){const d=this.lastUsage;this.lastUsage={sampledAt:new Date().toISOString(),turns:(d?.turns??0)+1,total:{input:(d?.total.input??0)+n,output:(d?.total.output??0)+h}}}}break}case"tool_use":{const i=t.name,n=typeof t.input=="string"?t.input:JSON.stringify(t.input??{});i&&s&&this.activeEventId===s&&this.activeSessionId&&(o.info("deepseek-adapter",`Tool use: ${i}`),this.callbacks.sendToolUse(s,this.activeSessionId,i,n),this.resetIdleTimer(s));break}case"tool_result":{const i=t.name,n=t.output;s&&this.activeEventId===s&&this.activeSessionId&&(this.callbacks.sendToolResult(s,this.activeSessionId,i??"unknown",n??""),this.resetIdleTimer(s));break}case"done":{this.handleMessageCompleted(s);break}default:break}}handleMessageCompleted(e){if(this.stopComposing(),e&&this.activeEventId===e){const s=this.activeSessionId??"",t=this.activeClientMsgId??void 0;s&&(this.chunkSeq++,this.callbacks.sendStreamChunk(e,s,"",this.chunkSeq,!0,t)),this.callbacks.sendEventResult(e,"responded"),this.clearActive()}}killActiveProcess(){const e=this.activeProcess;if(this.activeProcess=null,e?.pid)try{e.kill("SIGTERM")}catch{}}notifyBindingReady(){!this.aibotSessionId||!this.cwd||this.callbacks.sendUpdateBindingCard(this.aibotSessionId,"ready",this.cwd)}persistSessionId(e){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setDeepSeekThreadId(this.aibotSessionId,e)}startComposing(){if(!this.activeSessionId||this.composingTimer)return;this.stopComposing();const e=this.activeSessionId,s={ttl_ms:this.composingTTL};this.callbacks.sendSessionActivitySet(e,"composing",!0,s),this.composingTimer=setInterval(()=>{this.callbacks.sendSessionActivitySet(e,"composing",!0,s)},this.composingRefreshInterval),this.composingTTLClear=setTimeout(()=>{this.stopComposing()},this.composingTTL)}stopComposing(){this.composingTimer&&(clearInterval(this.composingTimer),this.composingTimer=null),this.composingTTLClear&&(clearTimeout(this.composingTTLClear),this.composingTTLClear=null),this.activeSessionId&&this.callbacks.sendSessionActivitySet(this.activeSessionId,"composing",!1)}resetIdleTimer(e){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{this.activeEventId===e&&(o.error("deepseek-adapter",`Agent idle for ${S/1e3}s: ${e}`),this.killActiveProcess(),this.callbacks.sendEventResult(e,"failed",`agent idle for ${S/1e3}s`),this.clearActive(),this.emit("stuck"))},S)}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}clearActive(){const e=this.activeEventId;this.stopComposing(),this.activeEventId=null,this.activeSessionId=null,this.chunkSeq=0,this.activeClientMsgId=null,this.clearIdleTimer(),e&&this.emit("eventDone",e)}}class k extends I{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){o.warn("deepseek-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}export{y as DeepSeekAdapter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{DeepSeekAdapter as e}from"./deepseek-adapter.js";export{e as DeepSeekAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function u(t){const e=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(String(t??"").trim());return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),...e[4]?{prerelease:e[4]}:{}}:null}function d(t,e){const r=u(t),n=u(e);return!r||!n?null:r.major-n.major||r.minor-n.minor||r.patch-n.patch||a(r.prerelease,n.prerelease)}function f(t,e){const r=u(t),n=u(e);return!r||!n?String(t??"").trim()===String(e??"").trim():r.major===n.major&&r.minor===n.minor}function a(t,e){if(t===e)return 0;if(t===void 0)return 1;if(e===void 0)return-1;const r=t.split("."),n=e.split(".");for(let s=0;s<Math.max(r.length,n.length);s+=1){const i=r[s],o=n[s];if(i===o)continue;if(i===void 0)return-1;if(o===void 0)return 1;const c=/^\d+$/.test(i),m=/^\d+$/.test(o);return c&&m?Number(i)-Number(o):c!==m?c?-1:1:i<o?-1:1}return 0}export{d as compareDshVersions,f as isSameDshVersionLine,u as parseDshVersion};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createHmac as H,randomUUID as T}from"node:crypto";import{EventEmitter as O}from"node:events";import{readFileSync as q}from"node:fs";import{createConnection as $}from"node:net";import{
|
|
1
|
+
import{createHmac as H,randomUUID as T}from"node:crypto";import{EventEmitter as O}from"node:events";import{readFileSync as q}from"node:fs";import{createConnection as $}from"node:net";import{isSameDshVersionLine as z}from"./dsh-version.js";import{isDshBridgedGrixTool as G}from"./grix-tool-bridge.js";import{DshBridgeJsonRpcPeer as U,GRIX_DSH_PROTOCOL_MAX as C,GRIX_DSH_PROTOCOL_MIN as M}from"./profile-bridge-protocol.js";import{resolveDshProfileIdentity as L,selectDshBridgeEndpoint as V}from"./profile-resolver.js";import{DEFAULT_DSH_PRESETS as F,normalizeDshPresets as K,normalizeDshProviders as X,resolveDshAgentPreset as J,resolveDshProviderId as W}from"./toolbar-state.js";import{effectiveDshReasoningEffort as Z}from"./types.js";const Q=T(),N=5e3,S=1e4,Y=6e4;class tt extends O{peer;sessionId;ownerId;onCursorAck;notificationsActive=!1;pendingNotifications=[];constructor(t,e,c,s){super(),this.peer=t,this.sessionId=e,this.ownerId=c,this.onCursorAck=s,t.on("notification",(o,a)=>{if(!this.notificationsActive){this.pendingNotifications.push({method:o,params:a});return}this.deliverNotification(o,a)}),t.on("protocolError",o=>this.emit("protocolError",o))}prompt(t,e){return this.peer.call("session/prompt",{sessionId:t.sessionId,ownerId:this.ownerId,contentBlocks:t.contentBlocks},e)}async shutdown(t){try{await this.peer.call("session/close",{sessionId:this.sessionId,ownerId:this.ownerId},f(t,5e3))}finally{this.peer.close()}}close(t){this.peer.close(t)}activateNotifications(){if(!this.notificationsActive){this.notificationsActive=!0;for(const t of this.pendingNotifications.splice(0))this.deliverNotification(t.method,t.params)}}call(t,e,c){const s=e&&typeof e=="object"?e:{};return this.peer.call(t,{sessionId:this.sessionId,ownerId:this.ownerId,...s},f(c,1e4))}async ack(t,e){if(!Number.isSafeInteger(t)||t<=0)throw Object.assign(new Error("Bridge ACK cursor must be a positive integer"),{code:"invalid_params"});const c=await this.peer.call("session/ack",{sessionId:this.sessionId,ownerId:this.ownerId,cursor:t},f(e,5e3));return await this.onCursorAck?.(t),c}cancel(t){return this.peer.call("session/cancel",{sessionId:this.sessionId,ownerId:this.ownerId},f(t,3e4))}setOptions(t,e){return this.peer.call("session/setOptions",{sessionId:this.sessionId,ownerId:this.ownerId,model:t.modelId,modeId:t.modeId},f(e,1e4))}deliverNotification(t,e){this.emit("notification",t,e)}}class mt{options;client=null;peer=null;socket=null;exitEmitter=new O;intentionalClose=!1;constructor(t){this.options=t}async start(){const t=L({dshHome:this.options.dshHome,profileName:this.options.profileName}),e=V(t);if(e.protocolMax<M||e.protocolMin>C)throw Object.assign(new Error(`Incompatible Grix DSH Bridge protocol ${e.protocolMin}-${e.protocolMax}`),{code:"bridge_incompatible"});const c=q(e.tokenPath,"utf8").trim();if(!c)throw Object.assign(new Error("DSH Bridge token file is empty"),{code:"auth_failed"});const s=await et(e.address,this.options.connectTimeoutMs??N);this.socket=s;const o=new U(s,{maxFrameBytes:this.options.maxFrameBytes,capture:this.options.capture});this.peer=o,o.on("close",()=>{this.socket=null,this.peer=null,this.client=null,this.intentionalClose||this.exitEmitter.emit("exit")}),o.setRequestHandler(async(i,l)=>{const n=l&&typeof l=="object"?l:{};if(i==="interaction/requestApproval")return{outcome:await this.options.onApproval?.(n)??"unavailable"};if(i==="grix/tool-call"){if(!this.options.onToolInvoke)throw Object.assign(new Error("grix tools are not wired for this Connector session"),{code:"capability_unavailable"});const d=String(n.tool??"").trim(),b=n.args&&typeof n.args=="object"?n.args:{};if(!d)throw Object.assign(new Error("grix/tool-call requires a tool name"),{code:"invalid_params"});if(!G(d))throw Object.assign(new Error(`grix tool "${d}" is not exposed to DSH`),{code:"capability_unavailable"});const j=Number(n.timeoutMs)||void 0;return{ok:!0,value:await this.options.onToolInvoke(d,b,j)}}throw Object.assign(new Error(`Unsupported Bridge request: ${i}`),{code:"capability_unavailable"})});const a=T(),g=H("sha256",c).update(`${a}
|
|
2
2
|
${t.profileKey}
|
|
3
|
-
${e.instanceId}`).digest("hex"),I=AbortSignal.timeout(this.options.initializeTimeoutMs??this.options.connectTimeoutMs??N),r=await o.call("bridge/initialize",{protocol:{min:M,max:C},client:{name:"grix-connector",version:process.env.npm_package_version??"unknown",instanceId:
|
|
3
|
+
${e.instanceId}`).digest("hex"),I=AbortSignal.timeout(this.options.initializeTimeoutMs??this.options.connectTimeoutMs??N),r=await o.call("bridge/initialize",{protocol:{min:M,max:C},client:{name:"grix-connector",version:process.env.npm_package_version??"unknown",instanceId:Q},profileKey:t.profileKey,requestedRole:"controller",auth:{nonce:a,proof:g}},I),B=r.profile&&typeof r.profile=="object"?r.profile:{},k=String(B.dshVersion??"");if(!z(e.dshVersion,k))throw o.close(new Error("DSH Profile version line changed between discovery and handshake")),Object.assign(new Error(`DSH Profile version mismatch: discovery=${e.dshVersion||"unknown"} handshake=${k||"unknown"}`),{code:"bridge_incompatible"});const R=r.capabilities&&typeof r.capabilities=="object"?r.capabilities:{},y=this.options.settings.skillIds??[],E=(this.options.settings.skillIdsExplicit===!0||y.length>0)&&R.sessionSkillAllowlist===!0,p=String(this.options.settings.providerId??"").trim();let u=[],_=!1;const x=this.options.catalogRefreshAttempts??8;for(let i=0;i<=x;i++){try{const l=AbortSignal.timeout(this.options.catalogTimeoutMs??S),n=await o.call("profile/listProviders",{},l),d=X(n.providers);if(_=!0,d.length>0&&(u=d),!p||u.some(b=>b.id===p))break}catch{break}i<x&&await new Promise(l=>setTimeout(l,150))}const w=_&&p==="grix"&&!u.some(i=>i.id===p)?p:W(p||void 0,u);let m;try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??S),l=await o.call("profile/listModels",{provider:w},i);m=Array.isArray(l.models)?l.models.filter(n=>!!n&&typeof n=="object"):[]}catch{}const P=(m??[]).some(i=>String(i.id??"")===this.options.settings.modelId)?this.options.settings.modelId:String(m?.[0]?.id??this.options.settings.modelId);let v=[...F];try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??S),l=await o.call("profile/listPresets",{},i),n=K(l.presets);n.length>0&&(v=n)}catch{}const D=J(this.options.settings.agentPreset,v);this.client=new tt(o,this.options.sessionId,this.options.ownerId,this.options.onCursorAck);try{const i=AbortSignal.timeout(this.options.sessionCreateTimeoutMs??Y);await o.call("session/create",{sessionId:this.options.sessionId,ownerId:this.options.ownerId,cwd:this.options.cwd,provider:w,model:P,reasoningEffort:Z(this.options.settings),...w==="codex-app-server"?{}:{maxTokens:this.options.settings.maxTokens},modeId:this.options.settings.modeId,agentPreset:D,pluginIds:this.options.settings.pluginIds??[],...E?{skillIds:y,skillIdsExplicit:!0}:{},...E&&this.options.skillsDir?{skillsDir:this.options.skillsDir}:{},...this.options.pluginOverlayPath?{pluginOverlayPath:this.options.pluginOverlayPath}:{},systemPrompt:this.options.systemPrompt,resume:this.options.resumeSession===!0,lastAckCursor:this.options.lastAckCursor??0},i)}catch(i){throw this.client.close(i instanceof Error?i:new Error(String(i))),this.client=null,i}const A=r.serverInfo&&typeof r.serverInfo=="object"?r.serverInfo:{};return{serverInfo:{name:String(A.name??"grix-dsh-profile-bridge"),version:String(A.version??"unknown")},profile:r.profile,capabilities:r.capabilities,...m!==void 0?{models:m}:{},selectedModel:P,providers:u,selectedProvider:w,presets:v,selectedPreset:D}}async shutdown(){this.intentionalClose=!0;try{await this.client?.shutdown()}finally{this.peer?.close(),this.client=null,this.peer=null,this.socket=null}}async terminate(){this.intentionalClose=!0,this.peer?.close(new Error("DSH Profile Bridge connection terminated")),this.client=null,this.peer=null,this.socket=null}async cancel(t){await this.client?.cancel()}async hasBackgroundWork(){return!1}isConnected(){return!!this.client&&!!this.peer?.isOpen}onExit(t){return this.exitEmitter.on("exit",t),()=>this.exitEmitter.off("exit",t)}}function f(h,t){return h??AbortSignal.timeout(t)}function et(h,t){return new Promise((e,c)=>{const s=$(h),o=setTimeout(()=>{a(),s.destroy(),c(Object.assign(new Error("Timed out connecting to DSH Profile Bridge"),{code:"bridge_connect_timeout"}))},t);o.unref?.();const a=()=>{clearTimeout(o),s.off("connect",g),s.off("error",I)},g=()=>{a(),s.setNoDelay(!0),e(s)},I=r=>{a(),c(Object.assign(r,{code:"bridge_connect_failed"}))};s.once("connect",g),s.once("error",I)})}export{S as BRIDGE_CATALOG_TIMEOUT_MS,N as BRIDGE_INITIALIZE_TIMEOUT_MS,Y as BRIDGE_SESSION_CREATE_TIMEOUT_MS,mt as DshProfileRuntime,tt as DshProfileRuntimeClient};
|
|
@@ -4,5 +4,5 @@ import{EventEmitter as I}from"node:events";import{randomUUID as P}from"node:cryp
|
|
|
4
4
|
|
|
5
5
|
`))>=0;){const d=o.slice(0,a);if(o=o.slice(a+2),t!==this.sseGeneration||r.aborted)return;const f=this.parseSseFrame(d);for(const u of f)try{this.emit("event",u)}catch{}}}}catch{}finally{try{await e.cancel()}catch{}e.releaseLock()}if(!(this.closed||r.aborted||t!==this.sseGeneration)){this.sseConnected=!1,Date.now()-n>=5e3&&(this.reconnectAttempts=0);try{this.emit("stream-lost")}catch{}this.v2Events.clear(),this.reconnectSse(t,r)}}parseSseFrame(e){let t="";const r=[];for(const o of e.split(`
|
|
6
6
|
`))o.startsWith("event:")?t=o.slice(6).trim():o.startsWith("data:")&&r.push(o.slice(5).trimStart());if(!r.length)return[];if(t==="effect/http-api/stream/failure")throw new Error("OpenCode SSE source failure");let s;try{s=JSON.parse(r.join(`
|
|
7
|
-
`))}catch{throw new Error("OpenCode SSE invalid JSON")}if(!h(s)||typeof s.type!="string")throw new Error("OpenCode SSE invalid event");if(this.protocol==="v2"){
|
|
7
|
+
`))}catch{throw new Error("OpenCode SSE invalid JSON")}if(!h(s)||typeof s.type!="string")throw new Error("OpenCode SSE invalid event");if(this.protocol==="v2"){s.type==="location.shutdown"&&typeof s.location?.directory=="string"&&this.mcpDirectories.delete(s.location.directory);const o=s.data?.sessionID??s.data?.form?.sessionID,n=this.runWindows.get(o);return!n&&h(s.location)&&s.location.directory&&this.directory&&s.location.directory!==this.directory?[]:n&&!this.acceptRunEvent(s,n)?[]:this.v2Events.normalize(s).map(i=>n?{...i,runId:n.runId}:i)}if(h(s.properties)){const{properties:o,...n}=s;return[{...n,...o,type:s.type}]}return[s]}acceptRunEvent(e,t){if(t.canceled||t.signal?.aborted)return!1;const r=e.durable?.seq;if(e.type==="session.inbox.enqueued"&&e.data.inboxID===t.promptId){if(!Number.isSafeInteger(r))throw new Error("OpenCode V2 inbox admission requires durable sequence");return t.enqueuedSeq=r,!0}if(e.type==="session.inbox.delivered"&&e.data.inboxID===t.promptId){if(!Number.isSafeInteger(r))throw new Error("OpenCode V2 inbox delivery requires durable sequence");return t.deliveredSeq=r,!0}if(e.type==="session.execution.started"&&t.enqueuedSeq!==void 0&&Number.isSafeInteger(r)&&r>t.enqueuedSeq)return t.executionSeq=r,!0;const s=t.deliveredSeq??t.executionSeq;if(s===void 0||Number.isSafeInteger(r)&&r<=s)return!1;const o=/^session\.execution\.(succeeded|failed|interrupted)$/.test(e.type);if(o&&!Number.isSafeInteger(r))throw new Error("OpenCode V2 execution terminal requires durable sequence");if(t.deliveredSeq===void 0){if(e.type==="session.execution.succeeded")throw new Error("OpenCode V2 execution ended before own inbox delivery");return o}const n=e.data.assistantMessageID;return e.type==="session.step.started"&&t.messages.add(n),!(n&&!t.messages.has(n))}async reconnectSse(e,t){for(;this.reconnectAttempts<x;){const r=this.reconnectAttempts++;try{if(await b(Math.min(q*2**r,D),t),this.closed||t.aborted||e!==this.sseGeneration)return;await this.subscribeEvents(e,t);return}catch(s){if(this.closed||t.aborted||e!==this.sseGeneration)return;if(s instanceof l&&(s.status===401||s.status===403))break}}if(!this.closed&&e===this.sseGeneration)try{this.emit("stream-unavailable")}catch{}}url(e,t=""){const r=new URL(e,this.baseUrl);return t&&r.searchParams.set(this.protocol==="v2"?"location[directory]":"directory",t),r}async request(e,t,r,s){if(this.closed)throw new Error(`OpenCode REST ${e} ${t}: transport closed`);s?.signal?.throwIfAborted();const o=this.url(t,s?.scoped===!1?"":s?.directory??this.directory),n=new AbortController,i=()=>n.abort();s?.signal?.addEventListener("abort",i,{once:!0}),this.requests.add(n);const c=setTimeout(()=>n.abort(),s?.timeoutMs??v);let a;try{const d=await fetch(o,{method:e,headers:{...this.headers,Accept:"application/json",...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},signal:n.signal,redirect:"error"});if(a=d.status,d.status===204&&s?.response==="empty")return;const f=/^application\/(?:[\w.+-]+\+)?json(?:;|$)/i.test(d.headers.get("content-type")??""),u=d.body?.getReader(),E=[];let m=0;try{if(u)for(;;){const{done:g,value:C}=await u.read();if(g||(m+=C.byteLength,m>(d.ok?y:4096)))break;E.push(C)}}finally{u&&(await u.cancel(),u.releaseLock())}const O=Buffer.concat(E).toString("utf8");let S,w=m?f?"invalid JSON response":"non-JSON response":"empty response";if(f&&m<=y)try{S=JSON.parse(O),w="JSON response"}catch{}if(!d.ok||w!=="JSON response"||s?.response==="empty"||m>y)throw new l(e,t,d.status,m>y?"response too large":d.ok&&s?.response==="empty"?"expected HTTP 204":w);return S}catch(d){throw d instanceof l?d:a!==void 0?new l(e,t,a,"response read failed or canceled"):new Error(`OpenCode REST ${e} ${t}: request failed or canceled`)}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",i),this.requests.delete(n)}}sessionPath(e){return`${this.protocol==="v2"?"/api":""}/session/${encodeURIComponent(e)}`}unwrap(e){return this.protocol==="v2"&&h(e)?e.data:e}session(e,t,r){const s=this.unwrap(e);if(!h(s)||typeof s.id!="string")throw new l(t,r,200,"invalid session JSON");return{...s,directory:s.directory??s.location?.directory??this.directory}}async createSession(e,t,r){if(this.protocol==="v2"){const s=t??this.directory;return this.session(await this.request("POST","/api/session",{...e,...s?{location:{directory:s}}:{}},{scoped:!1,signal:r}),"POST","/api/session")}return this.session(await this.request("POST","/session",e??{},{directory:t,signal:r}),"POST","/session")}async getSession(e,t,r){return this.session(await this.request("GET",this.sessionPath(e),void 0,{directory:t,scoped:this.protocol==="v1",signal:r}),"GET",this.sessionPath(e))}async deleteSession(e,t){await this.request("DELETE",this.sessionPath(e),void 0,{directory:t,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1"}),this.v2Events.clearSession(e),this.runWindows.delete(e),this.inboxIDs.delete(e)}async updateSessionPermission(e,t,r,s){await this.request("PATCH",this.sessionPath(e),this.protocol==="v2"?{permissions:t.map(o=>({action:{bash:"shell",task:"subagent",write:"edit",patch:"edit"}[o.permission]??o.permission,resource:o.pattern,effect:o.action}))}:{permission:t},{directory:r,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1",signal:s})}async sendPromptAsync(e,t,r,s){const o=this.cancellations.get(e);if(o&&await o,s?.signal?.throwIfAborted(),this.admissionUncertain)throw new Error("OpenCode prompt admission unconfirmed; server must be replaced");if(this.prompts.has(e))throw new Error("OpenCode session already has a prompt admission in progress");const n=new AbortController,i=()=>n.abort();s?.signal?.addEventListener("abort",i,{once:!0});const c=`msg_${P().replaceAll("-","")}`,a={controller:n,admitted:!1,dispatched:!1,done:Promise.resolve()};this.prompts.set(e,a),this.protocol==="v2"&&this.inboxIDs.set(e,c),this.protocol==="v2"&&s?.runId&&(this.v2Events.clearSession(e),this.runWindows.set(e,{runId:s.runId,promptId:c,signal:s.signal,canceled:!1,messages:new Set}));const d=this.connectionGeneration;a.done=this.preparePrompt(e,t,r,c,a);try{await a.done}catch(f){throw a.dispatched&&!a.admitted&&!this.closed&&d===this.connectionGeneration&&(this.admissionUncertain=!0,this.emit("admission-uncertain")),f}finally{s?.signal?.removeEventListener("abort",i),this.prompts.get(e)===a&&this.prompts.delete(e)}}async preparePrompt(e,t,r,s,o){const n=this.sessionPath(e),i=o.controller.signal;if(this.protocol==="v1"){i.throwIfAborted(),o.dispatched=!0,await this.request("POST",`${n}/prompt_async`,t,{directory:r,response:"empty"}),o.admitted=!0;return}t.model&&await this.request("POST",`${n}/model`,{model:{providerID:t.model.providerID,id:t.model.modelID}},{scoped:!1,response:"empty",signal:i}),t.agent&&await this.request("POST",`${n}/agent`,{agent:t.agent},{scoped:!1,response:"empty",signal:i}),await this.request(t.system?"PUT":"DELETE",`/api/experimental/session/${encodeURIComponent(e)}/instructions/entries/grix_identity`,t.system?{value:t.system}:void 0,{scoped:!1,response:"empty",signal:i}),i.throwIfAborted(),o.dispatched=!0;const c=await this.request("POST",`${n}/prompt`,{id:s,text:t.parts.map(a=>a.text).join(`
|
|
8
8
|
`)},{scoped:!1});if(!h(c)||!h(c.data)||c.data.id!==s)throw new l("POST",`${n}/prompt`,200,"invalid inbox JSON");o.admitted=!0}async abortSession(e,t){const r=this.cancellations.get(e);if(r)return r;const s=this.prompts.get(e);s?.controller.abort();const o=this.runWindows.get(e);o&&(o.canceled=!0);const n=this.interruptAfterAdmission(e,t,s,this.inboxIDs.get(e));return this.cancellations.set(e,n),n.then(()=>{this.cancellations.get(e)===n&&this.cancellations.delete(e)},()=>{}),n}async interruptAfterAdmission(e,t,r,s){const o=this.connectionGeneration,n=()=>{if(this.closed||o!==this.connectionGeneration)throw new Error("OpenCode interrupt connection canceled")};await r?.done.catch(()=>{}),n(),this.protocol==="v2"&&s&&await this.request("DELETE",`${this.sessionPath(e)}/inbox/${encodeURIComponent(s)}`,void 0,{scoped:!1,response:"empty"}),n();const i=await this.request("POST",`${this.sessionPath(e)}/${this.protocol==="v2"?"interrupt":"abort"}`,void 0,{directory:t,scoped:this.protocol==="v1"});if(this.protocol==="v2"&&(!h(i)||typeof i.interrupted!="boolean"))throw new l("POST",`${this.sessionPath(e)}/interrupt`,200,"invalid interrupt JSON");n(),this.protocol==="v2"&&await this.request("POST",`/api/experimental/session/${encodeURIComponent(e)}/wait`,void 0,{scoped:!1,response:"empty"})}async respondPermission(e,t,r,s){await this.request("POST",this.protocol==="v2"?`${this.sessionPath(e)}/permission/${encodeURIComponent(t)}/reply`:`${this.sessionPath(e)}/permissions/${encodeURIComponent(t)}`,this.protocol==="v2"?{decision:r}:{response:r},{directory:s,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1"})}async replyQuestion(e,t,r){if(this.protocol==="v1"){await this.request("POST",`/question/${encodeURIComponent(e)}/reply`,{answers:t},{directory:r});return}const s=this.v2Events.getForm(e);await this.request("POST",`${this.sessionPath(s.sessionID)}/form/${encodeURIComponent(e)}/reply`,{answer:this.v2Events.formAnswer(e,t)},{scoped:!1,response:"empty"}),this.v2Events.forgetForm(e)}async rejectQuestion(e,t){if(this.protocol==="v1"){await this.request("POST",`/question/${encodeURIComponent(e)}/reject`,void 0,{directory:t});return}const r=this.v2Events.getForm(e);await this.request("DELETE",`${this.sessionPath(r.sessionID)}/form/${encodeURIComponent(e)}`,void 0,{scoped:!1,response:"empty"}),this.v2Events.forgetForm(e)}async listProviders(e){if(this.protocol==="v1"){const s=await this.request("GET","/config/providers",void 0,{directory:e});if(!Array.isArray(s?.providers))throw new l("GET","/config/providers",200,"invalid provider JSON");return s.providers}const t=this.unwrap(await this.request("GET","/api/model",void 0,{directory:e}));if(!Array.isArray(t))throw new l("GET","/api/model",200,"invalid model list JSON");const r=new Map;for(const s of t){if(!h(s)||typeof s.id!="string"||typeof s.providerID!="string")throw new l("GET","/api/model",200,"invalid model JSON");if(s.enabled===!1)continue;const o=r.get(s.providerID)??{id:s.providerID,name:s.providerID,models:[]};o.models.push({id:s.id,name:s.name,limit:s.limit}),r.set(s.providerID,o)}return[...r.values()]}async configureMcp(e,t){this.mcp={name:e,command:t},this.mcpDirectories.clear(),await this.ensureMcpDirectory()}async ensureMcpDirectory(e){if(e?.throwIfAborted(),this.protocol!=="v2"||!this.mcp||this.mcpDirectories.has(this.directory))return;const t=this.directory,{name:r,command:s}=this.mcp;await this.request("PUT",`/api/experimental/mcp/${encodeURIComponent(r)}`,{config:{type:"local",command:s,disabled:!1}},{directory:t,response:"empty",signal:e});const o=Date.now()+1e4;for(;;){const n=this.unwrap(await this.request("GET","/api/mcp",void 0,{directory:t,signal:e})),i=Array.isArray(n)?n.find(c=>h(c)&&c.name===r):void 0;if(i?.status?.status==="connected")break;if(i?.status?.status!=="pending"||Date.now()>=o)throw new Error("OpenCode V2 MCP did not become connected");if(!this.sseController)throw new Error("OpenCode MCP setup canceled");await b(100,e??this.sseController.signal)}this.mcpDirectories.add(t)}async healthCheck(){try{if(this.closed)return!1;if(this.protocol==="v2")return T(await this.request("GET","/api/info",void 0,{scoped:!1,timeoutMs:3e3}));const e=await this.request("GET","/session",void 0,{timeoutMs:3e3});return Array.isArray(e)&&e.every(t=>h(t)&&typeof t.id=="string")}catch{return!1}}cancelConnections(){this.sseGeneration++,this.sseController?.abort(),this.sseController=null;for(const e of this.requests)e.abort();this.sseConnected=!1}disconnect(){this.connectionGeneration++,this.closed=!0,this.cancelConnections(),this.headers={},this.mcp=null,this.mcpDirectories.clear(),this.v2Events.clear();for(const e of this.prompts.values())e.controller.abort();this.prompts.clear(),this.cancellations.clear(),this.runWindows.clear(),this.inboxIDs.clear(),this.removeAllListeners()}get isConnected(){return this.sseConnected&&!this.closed}}export{l as OpenCodeHttpError,M as OpenCodeTransport};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
function u(m){return typeof m=="object"&&m!==null&&!Array.isArray(m)}const g=1024;class f{messages=new Map;textLengths=new Map;tools=new Map;forms=new Map;normalize(o){if(!u(o.data))throw new Error("OpenCode V2 event requires data");if([this.messages,this.textLengths,this.tools,this.forms].some(t=>t.size>g))throw new Error("OpenCode V2 event state limit exceeded");const e=o.data,r=e.sessionID;if(o.type.startsWith("session.")&&typeof r!="string")throw new Error("OpenCode V2 session event requires sessionID");let s=[];const n=e.assistantMessageID;if(/^session\.(step|text|reasoning|tool)\./.test(o.type)&&typeof n!="string")throw new Error("OpenCode V2 event requires assistantMessageID");if(/^session\.(text|reasoning)\.delta$/.test(o.type)&&typeof e.delta!="string")throw new Error("OpenCode V2 event requires text delta");const d=`${r}/${n}/${e.id}`,c=t=>{const a=this.messages.get(n),i={...a,id:n,sessionID:r,role:"assistant",time:{created:a?.time.created??e.started??o.created??Date.now()},modelID:e.model?.id??a?.modelID??"",providerID:e.model?.providerID??a?.providerID??"",...t?{tokens:t,cost:e.cost,time:{created:a?.time.created??o.created,completed:o.created}}:{}};return this.messages.set(n,i),i},p=t=>{const a=this.tools.get(d)??{sessionID:r,name:"unknown",input:{}};return{type:"message.part.updated",part:{id:d,messageID:n,sessionID:r,type:"tool",callID:e.id,tool:a.name,state:{status:t,input:a.input,raw:e.text??"",...t==="completed"?{output:Array.isArray(e.content)?e.content.map(l=>l.type==="text"?l.text:JSON.stringify(l)).join(`
|
|
2
|
-
`):""}:{},...t==="error"?{error:e.error?.message??"Tool failed"}:{},title:a.name,time:{start:a.started??o.created??Date.now(),end:o.created??Date.now()}}}}};switch(o.type){case"server.connected":s=[{type:"server.connected"}];break;case"session.execution.started":s=[{type:"session.status",sessionID:r,status:{type:"busy"}}];break;case"session.execution.succeeded":s=[{type:"session.idle",sessionID:r}],this.clearSession(r,!1);break;case"session.execution.failed":s=[{type:"session.error",sessionID:r,error:this.error(e.error)}],this.clearSession(r,!1);break;case"session.execution.interrupted":s=[{type:"session.canceled",sessionID:r}],this.clearSession(r,!1);break;case"session.step.started":s=[{type:"message.updated",info:c()}];break;case"session.step.ended":s=[{type:"message.updated",info:c(e.tokens)}];break;case"session.text.delta":case"session.reasoning.delta":case"session.text.ended":case"session.reasoning.ended":{const t=o.type.startsWith("session.reasoning."),a=`${r}/${n}/${t}/${e.ordinal}`,i=this.textLengths.get(a)?.text??"",l=o.type.endsWith(".ended"),
|
|
2
|
+
`):""}:{},...t==="error"?{error:e.error?.message??"Tool failed"}:{},title:a.name,time:{start:a.started??o.created??Date.now(),end:o.created??Date.now()}}}}};switch(o.type){case"server.connected":s=[{type:"server.connected"}];break;case"session.execution.started":s=[{type:"session.status",sessionID:r,status:{type:"busy"}}];break;case"session.execution.succeeded":s=[{type:"session.idle",sessionID:r}],this.clearSession(r,!1);break;case"session.execution.failed":s=[{type:"session.error",sessionID:r,error:this.error(e.error)}],this.clearSession(r,!1);break;case"session.execution.interrupted":s=[{type:"session.canceled",sessionID:r}],this.clearSession(r,!1);break;case"session.step.started":s=[{type:"message.updated",info:c()}];break;case"session.step.ended":s=[{type:"message.updated",info:c(e.tokens)}];break;case"session.text.delta":case"session.reasoning.delta":case"session.text.ended":case"session.reasoning.ended":{const t=o.type.startsWith("session.reasoning."),a=`${r}/${n}/${t}/${e.ordinal}`,i=this.textLengths.get(a)?.text??"",l=o.type.endsWith(".ended"),y=l?String(e.text??"").slice(i.length):String(e.delta??""),h=l?String(e.text??""):i+y;if(h.length>2*1024*1024)throw new Error("OpenCode V2 text limit exceeded");this.textLengths.set(a,{sessionID:r,text:h}),this.messages.has(n)||s.push({type:"message.updated",info:c()}),s.push({type:"message.part.updated",part:{type:t?"reasoning":"text",id:a,messageID:n,text:h},delta:y});break}case"session.tool.input.started":this.tools.set(d,{sessionID:r,name:e.name,input:{},started:o.created});break;case"session.tool.input.ended":{const t=this.tools.get(d);if(t)try{const a=JSON.parse(e.text);u(a)&&(t.input=a)}catch{}break}case"session.tool.called":{const t=this.tools.get(d)??{sessionID:r,name:"unknown",input:{}};t.input=u(e.input)?e.input:{},this.tools.set(d,t),s=[p("running")];break}case"session.tool.success":s=[p("completed")],this.tools.delete(d);break;case"session.tool.failed":s=[p("error")],this.tools.delete(d);break;case"permission.asked":if(typeof e.id!="string"||!Array.isArray(e.resources))throw new Error("OpenCode V2 invalid permission event");s=[{type:"permission.asked",id:e.id,sessionID:r,permission:e.action,patterns:e.resources,always:e.save??[],metadata:e.metadata??{},...e.source?.type==="tool"?{tool:{messageID:e.source.messageID,callID:e.source.id}}:{}}];break;case"permission.replied":s=[{type:"permission.replied",sessionID:r,requestID:e.requestID,reply:e.reply}];break;case"form.created":{const t=e.form;if(!u(t)||typeof t.id!="string"||typeof t.sessionID!="string"||!Array.isArray(t.fields))throw new Error("OpenCode V2 invalid form event");if(this.forms.set(t.id,t),t.fields.some(i=>i.hidden||i.when?.length||!["string","multiselect","boolean","number","integer"].includes(i.type))){s=[{type:"question.unsupported",sessionID:t.sessionID,id:t.id}];break}const a=t.fields.map(i=>({header:i.title||i.key,question:i.description||i.title||i.key,options:i.type==="boolean"?[{label:"true"},{label:"false"}]:(i.options??[]).map(l=>({label:l.label,description:l.description})),multiple:i.type==="multiselect",custom:i.type!=="boolean"&&(i.custom??!i.options?.length)}));s=[{type:"question.asked",id:t.id,sessionID:t.sessionID,questions:a}];break}case"form.replied":s=[{type:"question.replied",sessionID:r,requestID:e.id,answers:[]}],this.forms.delete(e.id);break;case"form.cancelled":s=[{type:"question.rejected",sessionID:r,requestID:e.id}],this.forms.delete(e.id);break;case"location.shutdown":return[]}return s.length||(s=[{type:"opencode.v2.event"}]),s.map(t=>({...t,nativeEvent:o}))}error(o){return{type:typeof o?.type=="string"?o.type:"unknown",message:typeof o?.message=="string"?o.message:"OpenCode execution failed"}}getForm(o){const e=this.forms.get(o);if(!e)throw new Error("OpenCode V2 form is no longer pending");return e}forgetForm(o){this.forms.delete(o)}formAnswer(o,e){const r=this.getForm(o),s=Object.create(null);return r.fields.forEach((n,d)=>{const c=e[d]??[];if(!c.length){if(n.required)throw new Error("OpenCode V2 form requires an answer");return}const p=c.map(t=>n.options?.find(a=>a.label===t)?.value??t);if(n.type==="multiselect")s[n.key]=p;else if(n.type==="boolean"){if(!["true","false"].includes(p[0]))throw new Error("OpenCode V2 form requires a boolean");s[n.key]=p[0]==="true"}else if(n.type==="number"||n.type==="integer"){const t=Number(p[0]);if(!p[0].trim()||!Number.isFinite(t)||n.type==="integer"&&!Number.isInteger(t))throw new Error("OpenCode V2 form requires a number");s[n.key]=t}else if(n.type==="string")s[n.key]=p[0];else throw new Error("OpenCode V2 form field is unsupported")}),s}clearSession(o,e=!0){for(const[r,s]of this.messages)s.sessionID===o&&this.messages.delete(r);for(const[r,s]of this.textLengths)s.sessionID===o&&this.textLengths.delete(r);for(const[r,s]of this.tools)s.sessionID===o&&this.tools.delete(r);if(e)for(const[r,s]of this.forms)s.sessionID===o&&this.forms.delete(r)}clear(){this.messages.clear(),this.textLengths.clear(),this.tools.clear(),this.forms.clear()}}export{f as OpenCodeV2Events,u as isRecord};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{execFile as T}from"node:child_process";import{promisify as M}from"node:util";import{EventEmitter as y}from"node:events";import{stat as k}from"node:fs/promises";import{mkdirSync as C,writeFileSync as R,unlinkSync as B,statSync as f,readFileSync as D,existsSync as g}from"node:fs";import{join as u,resolve as F,delimiter as E}from"node:path";import{fileURLToPath as O}from"node:url";import{tmpdir as N,homedir as w}from"node:os";import{resolveCommandPath as L,resolveWindowsExecInvocation as G,spawnCommand as j,killProcessGroup as _,hasChildProcesses as z}from"../../core/runtime/spawn.js";import{InternalApiServer as q}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as J}from"../shared/identity-injector.js";import{compactToolInputForWire as K}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as H}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as V}from"../claude/skill-scanner.js";import{listLivingDescendants as Y,countLivingDescendantsOutsideBaseline as W}from"../cursor/living-descendants.js";import{SessionBindingStore as X}from"../../core/persistence/session-binding-store.js";import{AgentGlobalConfigStore as Q}from"../../core/persistence/agent-global-config-store.js";import{splitTextForAibotProtocol as Z}from"../../core/protocol/index.js";import{InboundMessageIdInjector as tt}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as et}from"../shared/probe-util.js";import{piGrixProviderId as it,removePiGrixProvider as st,writePiGrixProvider as nt}from"./pi-provider-config.js";import{agentIdOf as rt}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as ot,recordOmpMcpEntryPid as at,removeOmpMcpEntry as dt}from"./omp-mcp-config.js";function ct(d){return rt(d)==="omp"}function lt(d){return process.platform!=="win32"?"PATH":Object.keys(d).find(t=>t.toLowerCase()==="path")??"PATH"}function ht(d){const t=lt(d),e=String(d[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(E).some(r=>r.trim()&&g(u(r.trim(),i))))return d;const n=u(w(),".bun","bin");return g(u(n,i))?(o.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${n}`),{...d,[t]:e?`${n}${E}${e}`:n}):d}const b=new Map;function pt(d){const t=u(d,"mcp.json");try{if(!g(t))return{};const i=JSON.parse(D(t,"utf8"))?.mcpServers;return!i||typeof i!="object"||Array.isArray(i)?{}:i}catch(e){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}async function ut(d){const t=b.get(d);if(t!==void 0)return t;let e=!1;try{const i=M(T),s=G(d,["--help"]),{stdout:n,stderr:r}=await i(s.command,s.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:s.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return b.set(d,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class mt extends y{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const ft=12e4,P=90*1e3,x=1800*1e3;function $(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}const gt=500,vt=2e3,v=3,St=500;function It(d){return new Promise(t=>setTimeout(t,d))}function yt(d){const t=new Set,e=[];for(const i of d){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function m(d){if(d===void 0)return"undefined";if(d===null)return"null";if(typeof d=="string")return d.length>500?`${d.slice(0,500)}...`:d;try{const t=JSON.stringify(d);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(d)}}class A extends y{type="pi";config;callbacks;process=null;transport=new H;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new tt;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;descendantBaseline;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;globalConfigStore=null;modelSelectionRevision=0;initializationPromise=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new J("pi-adapter",e.getAgentProfile);const i=t.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.agentName=String(i.agentName??"").trim(),this.clientType=String(i.clientType??"").trim().toLowerCase(),this.provider=i.provider,this.bindingStore=i.bindingStore instanceof X?i.bindingStore:null,this.globalConfigStore=i.globalConfigStore instanceof Q?i.globalConfigStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t){return this.clientType?this.clientType==="omp":ct(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||u(w(),".pi","agent")}start(){return this.initializationPromise=this.initializeSession(),this.initializationPromise}async initializeSession(){const t=this.resolveInitialModel();if(await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),t)try{await this.setModelSelection(t.provider,t.modelId,!1)}catch(e){o.warn("pi-adapter",`Failed to restore model selection: ${e instanceof Error?e.message:String(e)}`)}o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(!this.aibotSessionId)return;const t=this.modelSelectionRevision;for(let e=1;e<=v;e++)try{const[i,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]);if(t!==this.modelSelectionRevision)return;const n=i.data?.models;if(!n||n.length===0){if(e<v){await It(St);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const r=s.data?.model,l=this.bindingStore?.get(this.aibotSessionId);s.success&&r?.provider&&r.id&&!(l?.piProviderId&&l.piModelId)&&this.bindingStore?.setPiModel(this.aibotSessionId,r.provider,r.id);const c={available_models:n.map(h=>({id:h.id,display_name:h.name??h.id,...h.provider?{provider:h.provider}:{}}))},p=yt(n);p.length>0&&(c.available_providers=p),r?.id&&(c.model_id=r.id),r?.provider&&(c.provider_id=r.provider,c.model_provider=r.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),c),o.info("pi-adapter",`synced model binding: ${n.length} models, current=${r?.id??"unknown"} (attempt ${e})`);return}catch(i){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${i instanceof Error?i.message:String(i)}`);return}}resolveInitialModel(){const t=this.bindingStore?.get(this.aibotSessionId);if(t?.piProviderId&&t.piModelId)return{provider:t.piProviderId,modelId:t.piModelId};if(this.piSessionPath)return;const e=this.globalConfigStore?.get(this.agentName);if(e?.piProviderId&&e.piModelId)return{provider:e.piProviderId,modelId:e.piModelId}}async setModelSelection(t,e,i){const s=await this.transport.send("set_model",{provider:t,modelId:e});if(!s.success)throw new Error(s.error||"set_model failed");this.modelSelectionRevision++,this.aibotSessionId&&this.bindingStore?.setPiModel(this.aibotSessionId,t,e),i&&this.agentName&&this.globalConfigStore?.set(this.agentName,{piProviderId:t,piModelId:e})}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{B(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.cwdMcpJsonDir&&this.cwdMcpJsonKey){const t=this.cwdMcpJsonDir,e=this.cwdMcpJsonKey;this.cwdMcpJsonDir=null,this.cwdMcpJsonKey=null;try{await dt(t,e)}catch(i){o.warn("pi-adapter",`\u6E05\u7406 omp cwd .mcp.json \u6761\u76EE\u5931\u8D25 key=${e}: ${i instanceof Error?i.message:String(i)}`)}}if(this.process){const t=this.process;try{_(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{_(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new mt(t.adapterSessionId),i=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:i})).then(s=>{s.success||e.emitDone({status:"failed",error:s.error})}).catch(s=>{e.emitError(s instanceof Error?s:new Error(String(s)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:i,content:s}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;o.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=i,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{o.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else o.info("pi-adapter",`prompt: event=${e} session=${i}`),this.activeEventId=e,this.activeSessionId=i,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(o.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{o.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const i=this.nextStreamSeq(),s=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",i,!0,s),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const i=t.params??{},s=(i.modelId??i.model_id??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{await this.initializationPromise;let n=(i.provider_id??i.provider??i.model_provider)?.trim();if(!n){const c=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.id===s&&p.provider?.trim());if(c.length>1){const p=(await this.currentModel())?.provider?.trim();n=c.find(h=>h.provider?.trim()===p)?.provider?.trim()}n=n??c[0]?.provider?.trim()}return n?(await this.setModelSelection(n,s,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:s}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${s}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const i=t.params??{},s=(i.provider_id??i.provider??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{await this.initializationPromise;const l=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.provider?.trim()===s);if(l.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${s}`),{handled:!0,kind:"set_provider_error"};const c=(await this.currentModel())?.id,p=l.find(h=>h.id===c)?.id??l[0].id;return await this.setModelSelection(s,p,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:p}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const i=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:i}),{handled:!0,kind:"get_context"}}catch(i){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",i instanceof Error?i.message:String(i)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=F(O(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?z(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await et(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,i){try{if(t==="model"&&e.trim()&&await this.initializationPromise,!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const l=s.indexOf(":");if(l<1)return{status:"failed",message:"Format: provider:model_id"};const c=s.slice(0,l),p=s.slice(l+1);return p?(await this.setModelSelection(c,p,!0),this.syncModelBinding(),{status:"ok",message:`Model set to ${c}:${p}`}):{status:"failed",message:"Format: provider:model_id"}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
|
|
2
|
-
${r.map(
|
|
1
|
+
import{execFile as T}from"node:child_process";import{promisify as M}from"node:util";import{EventEmitter as y}from"node:events";import{stat as k}from"node:fs/promises";import{mkdirSync as C,writeFileSync as R,unlinkSync as B,statSync as f,readFileSync as D,existsSync as g}from"node:fs";import{join as u,resolve as F,delimiter as E}from"node:path";import{fileURLToPath as O}from"node:url";import{tmpdir as N,homedir as w}from"node:os";import{resolveCommandPath as G,resolveWindowsExecInvocation as L,spawnCommand as j,killProcessGroup as b,hasChildProcesses as z}from"../../core/runtime/spawn.js";import{InternalApiServer as q}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as J}from"../shared/identity-injector.js";import{compactToolInputForWire as K}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as H}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as V}from"../claude/skill-scanner.js";import{listLivingDescendants as Y,countLivingDescendantsOutsideBaseline as W}from"../cursor/living-descendants.js";import{SessionBindingStore as X}from"../../core/persistence/session-binding-store.js";import{AgentGlobalConfigStore as Q}from"../../core/persistence/agent-global-config-store.js";import{splitTextForAibotProtocol as Z}from"../../core/protocol/index.js";import{InboundMessageIdInjector as tt}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as et}from"../shared/probe-util.js";import{piGrixProviderId as it,removePiGrixProvider as st,writePiGrixProvider as nt}from"./pi-provider-config.js";import{agentIdOf as rt}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as ot,recordOmpMcpEntryPid as at,removeOmpMcpEntry as dt}from"./omp-mcp-config.js";function ct(l){return rt(l)==="omp"}function lt(l){return process.platform!=="win32"?"PATH":Object.keys(l).find(t=>t.toLowerCase()==="path")??"PATH"}function ht(l){const t=lt(l),e=String(l[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(E).some(r=>r.trim()&&g(u(r.trim(),i))))return l;const n=u(w(),".bun","bin");return g(u(n,i))?(o.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${n}`),{...l,[t]:e?`${n}${E}${e}`:n}):l}const _=new Map;function pt(l){const t=u(l,"mcp.json");try{if(!g(t))return{};const i=JSON.parse(D(t,"utf8"))?.mcpServers;return!i||typeof i!="object"||Array.isArray(i)?{}:i}catch(e){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}async function ut(l){const t=_.get(l);if(t!==void 0)return t;let e=!1;try{const i=M(T),s=L(l,["--help"]),{stdout:n,stderr:r}=await i(s.command,s.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:s.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return _.set(l,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${l})`),e}class mt extends y{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const ft=12e4,P=90*1e3,x=1800*1e3;function $(l){try{return process.kill(l,0),!0}catch(t){return t.code==="EPERM"}}const gt=500,vt=2e3,v=3,St=500;function It(l){return new Promise(t=>setTimeout(t,l))}function yt(l){const t=new Set,e=[];for(const i of l){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function m(l){if(l===void 0)return"undefined";if(l===null)return"null";if(typeof l=="string")return l.length>500?`${l.slice(0,500)}...`:l;try{const t=JSON.stringify(l);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(l)}}class A extends y{type="pi";config;callbacks;process=null;transport=new H;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new tt;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;abortBarrier=null;promptGeneration=0;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;descendantBaseline;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;globalConfigStore=null;modelSelectionRevision=0;initializationPromise=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new J("pi-adapter",e.getAgentProfile);const i=t.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.agentName=String(i.agentName??"").trim(),this.clientType=String(i.clientType??"").trim().toLowerCase(),this.provider=i.provider,this.bindingStore=i.bindingStore instanceof X?i.bindingStore:null,this.globalConfigStore=i.globalConfigStore instanceof Q?i.globalConfigStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t){return this.clientType?this.clientType==="omp":ct(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||u(w(),".pi","agent")}start(){return this.initializationPromise=this.initializeSession(),this.initializationPromise}async initializeSession(){const t=this.resolveInitialModel();if(await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),t)try{await this.setModelSelection(t.provider,t.modelId,!1)}catch(e){o.warn("pi-adapter",`Failed to restore model selection: ${e instanceof Error?e.message:String(e)}`)}o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(!this.aibotSessionId)return;const t=this.modelSelectionRevision;for(let e=1;e<=v;e++)try{const[i,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]);if(t!==this.modelSelectionRevision)return;const n=i.data?.models;if(!n||n.length===0){if(e<v){await It(St);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const r=s.data?.model,a=this.bindingStore?.get(this.aibotSessionId);s.success&&r?.provider&&r.id&&!(a?.piProviderId&&a.piModelId)&&this.bindingStore?.setPiModel(this.aibotSessionId,r.provider,r.id);const d={available_models:n.map(h=>({id:h.id,display_name:h.name??h.id,...h.provider?{provider:h.provider}:{}}))},p=yt(n);p.length>0&&(d.available_providers=p),r?.id&&(d.model_id=r.id),r?.provider&&(d.provider_id=r.provider,d.model_provider=r.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),d),o.info("pi-adapter",`synced model binding: ${n.length} models, current=${r?.id??"unknown"} (attempt ${e})`);return}catch(i){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${i instanceof Error?i.message:String(i)}`);return}}resolveInitialModel(){const t=this.bindingStore?.get(this.aibotSessionId);if(t?.piProviderId&&t.piModelId)return{provider:t.piProviderId,modelId:t.piModelId};if(this.piSessionPath)return;const e=this.globalConfigStore?.get(this.agentName);if(e?.piProviderId&&e.piModelId)return{provider:e.piProviderId,modelId:e.piModelId}}async setModelSelection(t,e,i){const s=await this.transport.send("set_model",{provider:t,modelId:e});if(!s.success)throw new Error(s.error||"set_model failed");this.modelSelectionRevision++,this.aibotSessionId&&this.bindingStore?.setPiModel(this.aibotSessionId,t,e),i&&this.agentName&&this.globalConfigStore?.set(this.agentName,{piProviderId:t,piModelId:e})}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.promptGeneration++,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{B(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.cwdMcpJsonDir&&this.cwdMcpJsonKey){const t=this.cwdMcpJsonDir,e=this.cwdMcpJsonKey;this.cwdMcpJsonDir=null,this.cwdMcpJsonKey=null;try{await dt(t,e)}catch(i){o.warn("pi-adapter",`\u6E05\u7406 omp cwd .mcp.json \u6761\u76EE\u5931\u8D25 key=${e}: ${i instanceof Error?i.message:String(i)}`)}}if(this.process){const t=this.process;try{b(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{b(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new mt(t.adapterSessionId),i=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:i})).then(s=>{s.success||e.emitDone({status:"failed",error:s.error})}).catch(s=>{e.emitError(s instanceof Error?s:new Error(String(s)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:i,content:s}=t,n=++this.promptGeneration,r=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const a=this.activeEventId;o.info("pi-adapter",`steer: cancel ${a} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(a,"canceled","steered to new event"),this.activeAuditCapture?.eventId===a&&(this.snapshotAuditBoundary(a),this.emit("eventDone",a))}this.activeEventId=e,this.activeSessionId=i,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,n,{message:r,streamingBehavior:"steer"})}else o.info("pi-adapter",`prompt: event=${e} session=${i}`),this.activeEventId=e,this.activeSessionId=i,this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,n,{message:r})}sendInboundPrompt(t,e,i){const s=t.event_id,n=()=>!this.stopped&&this.promptGeneration===e&&this.activeEventId===s;(async()=>{if(this.abortBarrier&&await this.abortBarrier,!n())return;this.beginAuditCapture(t);const a=await this.transport.send("prompt",i);if(!a.success)throw new Error(a.error||"prompt rejected")})().catch(a=>{if(!n())return;const d=a instanceof Error?a.message:String(a);o.error("pi-adapter",`prompt error event=${s}: ${d}`),this.isStreaming=!1,this.cancelDoneGuard(),this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(s,"failed",d)})}beginAbortBarrier(){if(this.abortBarrier)return;const t=Promise.resolve().then(()=>this.transport.send("abort")).then(e=>{if(!e.success)throw new Error(e.error||"abort rejected")});this.abortBarrier=t,t.then(()=>{this.abortBarrier===t&&(this.abortBarrier=null)},e=>{o.error("pi-adapter",`abort failed: ${e}`)})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.promptGeneration++,this.beginAbortBarrier(),this.cancelDoneGuard(),this.flushTextBuffer();const i=this.nextStreamSeq(),s=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",i,!0,s),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(t,"canceled","stopped by user")}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const i=t.params??{},s=(i.modelId??i.model_id??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{await this.initializationPromise;let n=(i.provider_id??i.provider??i.model_provider)?.trim();if(!n){const d=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.id===s&&p.provider?.trim());if(d.length>1){const p=(await this.currentModel())?.provider?.trim();n=d.find(h=>h.provider?.trim()===p)?.provider?.trim()}n=n??d[0]?.provider?.trim()}return n?(await this.setModelSelection(n,s,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:s}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${s}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const i=t.params??{},s=(i.provider_id??i.provider??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{await this.initializationPromise;const a=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.provider?.trim()===s);if(a.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${s}`),{handled:!0,kind:"set_provider_error"};const d=(await this.currentModel())?.id,p=a.find(h=>h.id===d)?.id??a[0].id;return await this.setModelSelection(s,p,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:p}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const i=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:i}),{handled:!0,kind:"get_context"}}catch(i){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",i instanceof Error?i.message:String(i)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=F(O(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?z(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await et(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,i){try{if(t==="model"&&e.trim()&&await this.initializationPromise,!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const a=s.indexOf(":");if(a<1)return{status:"failed",message:"Format: provider:model_id"};const d=s.slice(0,a),p=s.slice(a+1);return p?(await this.setModelSelection(d,p,!0),this.syncModelBinding(),{status:"ok",message:`Model set to ${d}:${p}`}):{status:"failed",message:"Format: provider:model_id"}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
|
|
2
|
+
${r.map(d=>` ${d.provider??"unknown"}:${d.id} (${d.name??d.id})`).join(`
|
|
3
3
|
`)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const s=this.getStatus();return{status:"ok",message:`Alive: ${s.alive}, Busy: ${s.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:s.alive,busy:s.busy,sessions:s.sessions,sessionPath:this.piSessionPath}}}case"skills":{const s=V({mode:"pi"}),n=s.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""} [${r.source}]: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
|
|
4
|
-
`):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new q,this.internalApi.setInvokeHandler(async(
|
|
4
|
+
`):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new q,this.internalApi.setInvokeHandler(async(a,d,p,h)=>this.callbacks.agentInvoke(a,d,h)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.resolvePiConfigDir(),e=this.getMcpConfig(),i=pt(t),s=u(N(),"grix-pi-mcp");C(s,{recursive:!0}),this.mcpConfigPath=u(s,`mcp-${process.pid}-${Date.now()}.json`),R(this.mcpConfigPath,JSON.stringify({mcpServers:{...i,[e.name]:{command:e.command,args:e.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const n=u(t,"skills"),r=U(n);r.length>0&&o.info("pi-adapter",`Synced connector skills to ${n}: [${r.join(", ")}]`)}catch(t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async writeOmpCwdMcpConfig(t){if(!this.mcpConfigPath)return;const e=this.getMcpConfig();if(e)try{const i=await ot(t,{name:e.name,command:e.command,args:e.args});this.cwdMcpJsonDir=t,this.cwdMcpJsonKey=i}catch(i){o.warn("pi-adapter",`\u5199\u5165 omp <cwd>/.omp/mcp.json \u5931\u8D25: ${i instanceof Error?i.message:String(i)}`)}}async spawnPi(){const t=this.config.command||"pi",e=G(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),i=this.config.args??[],n=i.some(c=>c.startsWith("--mode"))?[...i]:["--mode","rpc",...i],r=this.resolvePiConfigDir(),a=it(this.agentName);if(this.provider){const c=this.isOmp(e)?"bare":"dollar";await nt(r,a,this.provider,c)?(n.includes("--provider")||n.push("--provider",a),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):o.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied")}else await st(r,a).then(c=>{c&&o.info("pi-adapter",`Removed stale Grix provider "${a}" from models.json`)}).catch(c=>{o.warn("pi-adapter",`Failed to clean up Grix provider config: ${c instanceof Error?c.message:String(c)}`)});this.mcpConfigPath&&!n.some(c=>c==="--mcp-config")&&!this.isOmp(e)&&(await ut(e)?n.push("--mcp-config",this.mcpConfigPath):o.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));let d={...process.env,...this.config.env};this.isOmp(e)&&(d=ht(d));const p=this.provider?.apiKey?.trim();p&&!d.GRIX_PROVIDER_API_KEY?.trim()&&(d.GRIX_PROVIDER_API_KEY=p);const h=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await k(h)).isDirectory())throw new Error(`Bound path is not a directory: ${h}`)}catch(c){throw String(c?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${h}. Please rebind with /grix open <valid-directory>.`):c}const S=this.isOmp(e);S&&await this.writeOmpCwdMcpConfig(h);try{this.process=j(e,n,{env:d,cwd:h}).process}catch(c){throw o.error("pi-adapter",`PI spawn threw: ${c}`),this.alive=!1,c}S&&this.cwdMcpJsonDir&&this.cwdMcpJsonKey&&this.process.pid&&at(this.cwdMcpJsonDir,this.cwdMcpJsonKey,this.process.pid).catch(c=>{o.warn("pi-adapter",`\u8BB0\u5F55 omp \u5B50\u8FDB\u7A0B pid \u5230 mcp \u72B6\u6001\u6587\u4EF6\u5931\u8D25: ${c instanceof Error?c.message:String(c)}`)}),this.process.on("error",c=>{o.error("pi-adapter",`Spawn error: ${c.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${c.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",c=>{o.info("pi-adapter",`PI process exited (code=${c})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${c})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",c??1)}),this.process.stderr?.on("data",c=>{const I=c.toString().trim();I&&o.info("pi-adapter",`[pi stderr] ${I}`)}),this.transport.on("event",c=>this.handlePiEvent(c)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped||this.abortBarrier)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const i=t;this.descendantBaseline===void 0&&this.captureDescendantBaseline(),i.toolCallId&&this.toolCallsInFlight.add(i.toolCallId)}else if(t.type==="tool_execution_end"){const i=t;i.toolCallId&&this.toolCallsInFlight.delete(i.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const i=t.assistantMessageEvent;if(!i)break;const s=i.type;if(s==="text_delta"){const n=i.delta;if(n){const r=typeof i.contentIndex=="number"?i.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(s==="text_end"){const n=i.content,r=typeof i.contentIndex=="number"?i.contentIndex:0;n&&this.appendMissingText(r,n)}else if(s==="thinking_delta"){const n=i.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(s==="done"||s==="error"){if(this.flushTextBuffer(),s==="error"){const n=this.piMessageError(i.error,i.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(i.error)} reason=${m(i.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const i=t.message;i?.role==="assistant"&&i.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${m(i.errorMessage)} message=${m(i)}`),this.recordRunError(this.piMessageError(i,i.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const i=t;if(i.toolName){const s=K(i.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,i.toolName,s)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const i=t;i.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,i.toolName,"(failed)");break}case"agent_end":{if(o.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){o.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.captureOmpAuditMessages(t.messages),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(o.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=vt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},gt))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of Z(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const s=JSON.parse(t.context_messages_json);if(Array.isArray(s)&&s.length>0){const n=s.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
|
|
5
5
|
`);e=`${e}
|
|
6
6
|
|
|
7
7
|
[Conversation context]
|
|
@@ -9,4 +9,4 @@ ${n}`}}catch{}const i=this.identity.injectOnce(t.session_id,e);return this.inbou
|
|
|
9
9
|
`);e=`${e}
|
|
10
10
|
|
|
11
11
|
[Conversation context]
|
|
12
|
-
${i}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.descendantBaseline=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let i;if(e)try{i=f(e).size}catch{i=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...i===void 0?{}:{transcriptStartOffset:i},...this.isOmp(this.config.command??"")?{eventRecords:[]}:{}}}captureOmpAuditMessages(t){const e=this.activeAuditCapture;if(!(!e?.eventRecords||e.eventId!==this.activeEventId)&&Array.isArray(t))for(const i of t){if(!i||typeof i!="object"||Array.isArray(i))continue;const s=i,n=s.timestamp;e.eventRecords.push({type:"message",message:s,timestamp:typeof n=="number"&&Number.isFinite(n)?new Date(n).toISOString():new Date().toISOString()})}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const i={adapterType:"pi"};if(e.transcriptPath){let s=e.transcriptStartOffset??0;try{s=f(e.transcriptPath).size}catch{}i.transcriptPath=e.transcriptPath,i.transcriptStartOffset=e.transcriptStartOffset??0,i.transcriptEndOffset=s,i.providerSessionId=this.piSessionPath??e.transcriptPath}else e.eventRecords&&e.eventRecords.length>0&&(i.eventRecords=e.eventRecords);this.completedAuditBoundaries.set(t,i)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`,this.descendantBaseline=void 0}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",i=this.activeClientMsgId??void 0,s=this.activeRunError??void 0;s&&this.emitPendingRunError();const n=this.runErrorEmitted;this.clearActive(),this.finalizeEvent(t,e,i,s,n)}finalizeEvent(t,e,i,s,n=!1){const r=this.nextStreamSeq(),
|
|
12
|
+
${i}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.descendantBaseline=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let i;if(e)try{i=f(e).size}catch{i=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...i===void 0?{}:{transcriptStartOffset:i},...this.isOmp(this.config.command??"")?{eventRecords:[]}:{}}}captureOmpAuditMessages(t){const e=this.activeAuditCapture;if(!(!e?.eventRecords||e.eventId!==this.activeEventId)&&Array.isArray(t))for(const i of t){if(!i||typeof i!="object"||Array.isArray(i))continue;const s=i,n=s.timestamp;e.eventRecords.push({type:"message",message:s,timestamp:typeof n=="number"&&Number.isFinite(n)?new Date(n).toISOString():new Date().toISOString()})}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const i={adapterType:"pi"};if(e.transcriptPath){let s=e.transcriptStartOffset??0;try{s=f(e.transcriptPath).size}catch{}i.transcriptPath=e.transcriptPath,i.transcriptStartOffset=e.transcriptStartOffset??0,i.transcriptEndOffset=s,i.providerSessionId=this.piSessionPath??e.transcriptPath}else e.eventRecords&&e.eventRecords.length>0&&(i.eventRecords=e.eventRecords);this.completedAuditBoundaries.set(t,i)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`,this.descendantBaseline=void 0}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",i=this.activeClientMsgId??void 0,s=this.activeRunError??void 0;s&&this.emitPendingRunError();const n=this.runErrorEmitted;this.clearActive(),this.finalizeEvent(t,e,i,s,n)}finalizeEvent(t,e,i,s,n=!1){const r=this.nextStreamSeq(),a=s?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${a} clientMsgId=${i??""} terminalError=${s?m(s):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,i).then(()=>{this.callbacks.sendEventResult(t,a,s,void 0,n),o.info("pi-adapter",`event ${a} (reliable) event=${t}`)}).catch(d=>{o.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${d}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${d instanceof Error?d.message:String(d)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",r,!0,i),this.callbacks.sendEventResult(t,a,s,void 0,n),o.info("pi-adapter",`event ${a} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,o.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const i=t.errorMessage;if(typeof i=="string"&&i.trim())return i.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const i=this.emittedTextByIndex.get(t)??"";if(e!==i){if(e.startsWith(i)){const s=e.slice(i.length);s&&(this.rememberEmittedText(t,s),this.appendText(s));return}if(!i){this.rememberEmittedText(t,e),this.appendText(e);return}o.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(o.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},A.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!$(t))return!1;if(this.toolCallsInFlight.size>0&&this.descendantBaseline instanceof Set){let a=0;try{a=W(t,this.descendantBaseline)}catch{a=0}if(a>0)return this.livenessExtendStartAt=void 0,o.info("pi-adapter",`Liveness check: tool descendants for ${this.activeEventId} (descendants=${a}, toolsInFlight=${this.toolCallsInFlight.size}), extending without budget`),!0}const e=Date.now(),i=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY,s=this.transcriptFreshMs();if(i<P||s!==null&&s<P)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh progress for ${this.activeEventId} (rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const r=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=r),e-r>x?(o.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-r)/6e4)}min), allowing idle fail`),!1):(o.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}), extending`),!0)}captureDescendantBaseline(){const t=this.process?.pid;if(!t){this.descendantBaseline=null;return}try{this.descendantBaseline=new Set(Y(t)),o.info("pi-adapter",`Liveness baseline captured for ${this.activeEventId}: ${this.descendantBaseline.size} resident descendant(s)`)}catch{this.descendantBaseline=null}}transcriptFreshMs(){const t=this.piSessionPath;if(!t)return null;try{return Date.now()-f(t).mtimeMs}catch{return null}}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,i=!!(this.alive&&t&&$(t))?`liveness budget exhausted after ${x/6e4}min`:"process not alive";o.error("pi-adapter",`Idle timeout (${i}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${i}`,void 0,this.runErrorEmitted)),this.clearActive(),this.emit("exit",-1)},ft))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&o.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const s=await this.transport.send("get_state");s.success&&(e=s.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{A as PiAdapter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{QwenAdapter as e}from"./qwen-adapter.js";export{e as QwenAdapter};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import l from"node:path";import{fileURLToPath as m}from"node:url";import{EventEmitter as h}from"node:events";import{AgentProcess as f}from"../../agent/process.js";import{AcpClient as v,AcpAuthRequiredError as g}from"../../protocol/acp-client.js";import{AgentEventType as a}from"../../types/events.js";import{QuotedMessageStream as R}from"../../core/util/quoted-message-stream.js";import{InternalApiServer as A}from"../../core/mcp/internal-api-server.js";import{EventResultsStore as b}from"../../core/persistence/event-results-store.js";import{log as r}from"../../core/log/index.js";const d=l.dirname(m(import.meta.url)),w=300*1e3,u=60*1e3,I=200;class T extends h{type="qwen";config;callbacks;agentProcess=null;acpClient=null;internalApi=null;activeRun=null;pendingApprovals=new Map;bindingStore;eventResults=null;currentAibotSessionId;stopped=!1;cwd;model;promptTimeoutMs;clientMsgSeq=0;deferredEvents=new Map;sessionBindings=new Map;constructor(e,t,s,i){super(),this.config=e,this.callbacks=t,this.bindingStore=s,this.cwd=e.cwd??process.cwd(),this.model=e.options?.model,this.promptTimeoutMs=e.options?.promptTimeoutMs??w,i&&(this.eventResults=new b(i))}async start(){const e=[...this.config.args??[],"--acp"];this.model&&e.push("--model",this.model);const t={command:this.config.command||"qwen",args:e,cwd:this.cwd,env:this.config.env},s=await this.startInternalApiAndMcp();this.agentProcess=new f;const i=await this.agentProcess.start(t);r.info("qwen-adapter","Qwen process started"),this.agentProcess.on("exit",n=>{this.stopped||(r.error("qwen-adapter",`Process exited unexpectedly (code=${n})`),this.activeRun&&this.finishRun("failed",`qwen process exited (code=${n})`),this.emit("exit",n))}),this.acpClient=new v,this.acpClient.on("event",n=>this.handleAcpEvent(n));const o=this.currentAibotSessionId?this.bindingStore.getAcpSessionId(this.currentAibotSessionId):void 0;try{await this.acpClient.connect({transport:i,initialMode:"bypass",mcpServers:s,sessionId:o,cwd:this.cwd}),r.info("qwen-adapter",`ACP session ready: ${this.acpClient.sessionId}`),this.currentAibotSessionId&&this.bindingStore.setAcpSessionId(this.currentAibotSessionId,this.acpClient.sessionId);for(const[n,c]of this.sessionBindings)this.callbacks.sendUpdateBindingCard(n,"ready",c)}catch(n){if(n instanceof g){await this.handleAuthRequired(n);return}throw n}}async stop(){this.stopped=!0,this.deferredEvents.clear(),this.activeRun&&(this.activeRun.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null),this.activeRun.timeoutTimer&&(clearTimeout(this.activeRun.timeoutTimer),this.activeRun.timeoutTimer=null),this.activeRun.firstResponseTimer&&(clearTimeout(this.activeRun.firstResponseTimer),this.activeRun.firstResponseTimer=null),this.activeRun=null),this.acpClient&&(this.acpClient.removeAllListeners(),this.acpClient=null),this.agentProcess&&(await this.agentProcess.close(),this.agentProcess=null),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null)}isAlive(){return this.acpClient?.isAlive??!1}async createSession(e){return this.acpClient?.sessionId??""}async resumeSession(e,t){}async destroySession(e){}sendPrompt(e){const t=new S(e.adapterSessionId);return this.acpClient?.isAlive&&this.acpClient.send(e.text).catch(s=>{t.emitError(s instanceof Error?s:new Error(String(s)))}),t}async cancel(e){this.activeRun&&this.acpClient&&(await this.acpClient.cancel(),this.flushStream(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){}async ping(e){return this.acpClient?.ping(e)??!1}getStatus(){return{alive:this.acpClient?.isAlive??!1,busy:this.activeRun!==null,sessions:this.acpClient?1:0}}getMcpConfig(){if(!this.internalApi)return null;const e=l.resolve(d,"../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}get pendingApprovalEntries(){return this.pendingApprovals}get acpSessionOptions(){return this.acpClient?.sessionOptions??null}async handleLocalAction(e){const t=e.action_type??"",s=e.params??{};if(t==="exec_approve"||t==="exec_reject"){const i=String(s.tool_call_id??""),o=t==="exec_approve";if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"tool_call_id_required","tool_call_id is required"),{handled:!0,kind:"approval"};const n=this.pendingApprovals.get(i);return n?(this.pendingApprovals.delete(i),this.acpClient&&this.acpClient.respondPermission(n,{behavior:o?"allow":"deny"}).catch(c=>{r.error("qwen-adapter",`Failed to respond to permission: ${c}`)}),this.callbacks.sendLocalActionResult(e.action_id,"ok"),{handled:!0,kind:"approval"}):(this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"approval_not_found",`no pending approval for tool_call_id: ${i}`),{handled:!0,kind:"approval"})}return{handled:!1,kind:""}}async startInternalApiAndMcp(){try{this.internalApi=new A,this.internalApi.setInvokeHandler(async(t,s)=>this.callbacks.agentInvoke(t,s)),await this.internalApi.start(0),r.info("qwen-adapter",`Internal API started at ${this.internalApi.url}`);const e=l.resolve(d,"../../mcp/acp-mcp-server.js");return[{name:"grix-connector-tools",command:process.execPath,args:[e,"--api-url",this.internalApi.url],env:{GRIX_CONNECTOR_INTERNAL_API:this.internalApi.url}}]}catch(e){r.error("qwen-adapter",`Failed to start MCP tools: ${e}`);return}}bindSession(e,t){return this.sessionBindings.get(e)?!1:(this.sessionBindings.set(e,t),this.bindingStore.set(e,t),this.acpClient?.sessionId&&this.bindingStore.setAcpSessionId(e,this.acpClient.sessionId),this.acpClient?.isAlive&&this.callbacks.sendUpdateBindingCard(e,"connected",t),!0)}getSessionCwd(e){return this.sessionBindings.get(e)}getSessionBindings(){return this.sessionBindings}deliverInboundEvent(e){if(this.callbacks.sendEventAck(e.event_id,e.session_id),this.eventResults?.has(e.session_id,e.event_id)){const t=this.eventResults.get(e.session_id,e.event_id);r.info("qwen-adapter",`Deduplicating event ${e.event_id} (cached: ${t.status})`),this.callbacks.sendEventResult(e.event_id,t.status,t.msg);return}if(this.activeRun){r.info("qwen-adapter",`Event ${e.event_id} rejected: busy`),this.callbacks.sendEventResult(e.event_id,"failed","agent busy");return}if(!this.acpClient?.isAlive){this.callbacks.sendEventResult(e.event_id,"failed","qwen agent not alive");return}if(e.session_id&&e.session_id!==this.currentAibotSessionId&&(this.currentAibotSessionId=e.session_id),!this.sessionBindings.has(e.session_id)){this.deferEvent(e),this.callbacks.sendStreamChunk(e.event_id,e.session_id,"Qwen needs a workspace before it can reply. Use /grix open <directory> to bind.",1,!1),this.callbacks.sendStreamChunk(e.event_id,e.session_id,"",2,!0),this.callbacks.sendEventResult(e.event_id,"responded");return}this.startRun(e,!1)}deliverStopEvent(e){this.activeRun?.eventId===e&&(this.flushStream(),this.finishRun("canceled","stopped by user"))}deferEvent(e){const t=this.deferredEvents.get(e.session_id)??[];t.some(s=>s.event.event_id===e.event_id)||(t.push({event:e,queuedAt:Date.now()}),this.deferredEvents.set(e.session_id,t),r.info("qwen-adapter",`Deferred event ${e.event_id} for session ${e.session_id} (queue: ${t.length})`))}replayDeferredEvents(e){const t=this.deferredEvents.get(e);if(!(!t||t.length===0)){this.deferredEvents.delete(e),r.info("qwen-adapter",`Replaying ${t.length} deferred events for session ${e}`);for(const{event:s}of t){if(this.activeRun){r.info("qwen-adapter",`Cannot replay ${s.event_id}: agent busy, dropping`);continue}this.startRun(s,!0)}}}startRun(e,t){this.activeRun={eventId:e.event_id,sessionId:e.session_id,threadId:e.thread_id,clientMsgId:`qwen_${++this.clientMsgSeq}_${Date.now()}`,chunkSeq:0,buffer:"",quotedStream:new R,responded:!1,silent:t,flushTimer:null,timeoutTimer:null,firstResponseTimer:null};const s=this.activeRun;s.firstResponseTimer=setTimeout(()=>{this.activeRun?.eventId===e.event_id&&!s.responded&&(r.error("qwen-adapter",`No response from agent within ${u}ms for ${e.event_id}`),this.finishRun("failed","agent not responding"))},u),s.timeoutTimer=setTimeout(()=>{this.activeRun?.eventId===e.event_id&&(r.error("qwen-adapter",`Prompt timed out for ${e.event_id}`),this.finishRun("failed","agent response timed out"))},this.promptTimeoutMs),this.callbacks.sendSessionComposing(e.session_id,!0),this.acpClient.send(e.content).catch(i=>{r.error("qwen-adapter",`Prompt failed: ${i}`),this.finishRun("failed",i instanceof Error?i.message:String(i))})}handleAcpEvent(e){if(e.type===a.PermissionRequest){this.handlePermissionRequest(e);return}const t=this.activeRun;if(t)switch(t.responded||(t.responded=!0,t.firstResponseTimer&&(clearTimeout(t.firstResponseTimer),t.firstResponseTimer=null)),e.type){case a.Text:{e.content&&this.appendToStream(t,e.content);break}case a.ToolUse:{e.toolName&&this.callbacks.sendToolUse(t.eventId,t.sessionId,e.toolName,e.toolInput??"");break}case a.ToolResult:{e.content&&this.callbacks.sendToolResult(t.eventId,t.sessionId,e.content);break}case a.Thinking:{e.content&&this.callbacks.sendThinking(t.eventId,t.sessionId,e.content);break}case a.Error:{r.error("qwen-adapter",`ACP error: ${e.error}`);break}case a.Result:{this.flushStream(),this.finishRun("responded");break}}}handlePermissionRequest(e){const t=e.permissionRequest;if(!t||!e.requestId||!this.acpClient)return;const s=t.toolCallId;this.pendingApprovals.set(s,e.requestId);const i=this.activeRun;i?this.callbacks.sendPermissionCard({eventId:i.eventId,sessionId:i.sessionId,toolCallId:s,toolName:t.toolName,toolTitle:t.toolTitle,options:t.options}):(r.info("qwen-adapter",`Permission request without active run, auto-approving: ${t.toolName}`),this.acpClient.respondPermission(e.requestId,{behavior:"allow"}),this.pendingApprovals.delete(s))}async handleAuthRequired(e){r.info("qwen-adapter",`Auth required, methods: ${e.authMethods.map(o=>o.id).join(", ")}`);const t=e.authMethods.find(o=>/oauth|browser/i.test(o.id))??e.authMethods[0];if(!t)throw e;const s=this.currentAibotSessionId??"";this.callbacks.sendAuthNotification(s,`Qwen authentication required (${t.id}). Initiating auth flow...`);for(const[o,n]of this.sessionBindings)this.callbacks.sendUpdateBindingCard(o,"failed",n);const i=await this.captureAuthUrl();i&&this.callbacks.sendAuthNotification(s,`Please open this URL to authenticate:
|
|
2
|
+
${i}
|
|
3
|
+
|
|
4
|
+
Waiting for authentication to complete...`);try{await this.acpClient.authenticate(t.id),r.info("qwen-adapter","Authentication successful"),this.callbacks.sendAuthNotification(s,"Authentication successful. Resuming..."),await this.acpClient.connect({transport:this.agentProcess.transport,initialMode:"bypass",mcpServers:this.internalApi?[{name:"grix-connector-tools",command:process.execPath,args:[l.resolve(d,"../../mcp/acp-mcp-server.js"),"--api-url",this.internalApi.url],env:{GRIX_CONNECTOR_INTERNAL_API:this.internalApi.url}}]:void 0}),r.info("qwen-adapter",`ACP session ready after auth: ${this.acpClient.sessionId}`);for(const[o,n]of this.sessionBindings)this.callbacks.sendUpdateBindingCard(o,"ready",n)}catch(o){throw r.error("qwen-adapter",`Auth retry failed: ${o}`),o}}captureAuthUrl(){return new Promise(e=>{if(!this.agentProcess){e(null);return}const t=/https?:\/\/[^\s"')\]]+/;let s=!1;const i=o=>{if(s)return;const n=o.toString().replace(/\x1b\[[0-9;]*m/g,"").match(t);n&&(s=!0,this.agentProcess.removeListener("stderr",i),e(n[0]))};this.agentProcess.on("stderr",i),setTimeout(()=>{s||(s=!0,this.agentProcess.removeListener("stderr",i),e(null))},3e4)})}appendToStream(e,t){const s=e.quotedStream.consume(t);s.deltaContent&&(e.buffer+=s.deltaContent,e.flushTimer||(e.flushTimer=setTimeout(()=>this.flushStream(),I)))}flushStream(){const e=this.activeRun;if(!e||!e.buffer)return;e.flushTimer&&(clearTimeout(e.flushTimer),e.flushTimer=null);const t=e.buffer;e.buffer="",this.callbacks.sendStreamChunk(e.eventId,e.sessionId,t,++e.chunkSeq,!1)}finishRun(e,t){const s=this.activeRun;if(!s)return;this.activeRun=null,this.callbacks.sendSessionComposing(s.sessionId,!1),s.flushTimer&&(clearTimeout(s.flushTimer),s.flushTimer=null),s.timeoutTimer&&(clearTimeout(s.timeoutTimer),s.timeoutTimer=null),s.firstResponseTimer&&(clearTimeout(s.firstResponseTimer),s.firstResponseTimer=null);const i=s.quotedStream.flush();i.deltaContent&&(s.buffer+=i.deltaContent),s.buffer&&(this.callbacks.sendStreamChunk(s.eventId,s.sessionId,s.buffer,++s.chunkSeq,!1),s.buffer=""),t&&this.callbacks.sendRunError(s.eventId,s.sessionId,t),this.callbacks.sendStreamChunk(s.eventId,s.sessionId,"",++s.chunkSeq,!0),s.silent||this.callbacks.sendEventResult(s.eventId,e,t),this.eventResults&&!s.silent&&this.eventResults.set({sessionId:s.sessionId,eventId:s.eventId,status:e,msg:t,updatedAt:Date.now()})}}class S extends h{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){this.emit("error",e)}async cancel(){}}export{T as QwenAdapter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{EventEmitter as o}from"node:events";import c from"ws";const r="aibot-agent-api-v1",h=1;class l extends o{ws=null;seq=0;heartbeatTimer=null;heartbeatSec=30;connected=!1;config;constructor(e){super(),this.config={url:e.url,agentId:e.agentId,apiKey:e.apiKey,clientType:e.clientType,capabilities:e.capabilities??["stream_chunk","local_action_v1"],localActions:e.localActions??["exec_approve","exec_reject"]}}get isConnected(){return this.connected}async connect(){return new Promise((e,a)=>{const s=new c(this.config.url);this.ws=s;const i=setTimeout(()=>{a(new Error("Auth timeout: no auth_ack received within 15s")),s.close()},15e3);s.on("open",()=>{this.sendPacket("auth",{agent_id:this.config.agentId,api_key:this.config.apiKey,client_type:this.config.clientType,protocol_version:r,contract_version:h,capabilities:this.config.capabilities,local_actions:this.config.localActions})}),s.on("message",t=>{let n;try{n=JSON.parse(t.toString())}catch{return}this.handlePacket(n,i,e,a)}),s.on("close",(t,n)=>{this.connected=!1,this.stopHeartbeat(),clearTimeout(i),this.emit("close",t,n.toString())}),s.on("error",t=>{clearTimeout(i),this.emit("error",t),this.connected||a(t)})})}handlePacket(e,a,s,i){switch(e.cmd){case"auth_ack":{clearTimeout(a);const t=e.payload;t.code===0?(this.connected=!0,t.heartbeat_sec&&(this.heartbeatSec=t.heartbeat_sec),this.startHeartbeat(),this.emit("auth",t),s(t)):i(new Error(`Auth failed: code=${t.code} msg=${t.msg}`));break}case"ping":{this.sendPacket("pong",e.payload??{});break}case"event_msg":{this.emit("event",e.payload);break}case"local_action":{this.emit("localAction",e.payload);break}case"event_stop":{this.emit("stop",e.payload);break}case"kicked":{this.emit("kicked",e.payload),this.disconnect();break}case"error":{const t=e.payload;this.emit("error",new Error(`Server error: code=${t.code} msg=${t.msg}`));break}case"send_ack":case"send_nack":case"local_action_ack":break;default:break}}sendEventAck(e){this.sendPacket("event_ack",e)}sendStreamChunk(e){this.sendPacket("client_stream_chunk",e)}sendMsg(e){this.sendPacket("send_msg",e)}sendEventResult(e){this.sendPacket("event_result",e)}sendLocalActionResult(e){this.sendPacket("local_action_result",e)}sendEventStopAck(e){this.sendPacket("event_stop_ack",e)}sendEventStopResult(e){this.sendPacket("event_stop_result",e)}sendPing(){this.sendPacket("ping",{})}disconnect(){this.connected=!1,this.stopHeartbeat(),this.ws&&(this.ws.close(),this.ws=null)}sendPacket(e,a){if(!this.ws||this.ws.readyState!==c.OPEN)return;const s={cmd:e,seq:++this.seq,payload:a};this.ws.send(JSON.stringify(s))}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.connected&&this.sendPing()},this.heartbeatSec*1e3)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}}export{l as AibotClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export*from"./types.js";import{AibotClient as o}from"./client.js";export{o as AibotClient};
|
|
File without changes
|
|
Binary file
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"bridgeVersion": "4.
|
|
4
|
-
"tarball": "grix-dsh-bridge-4.
|
|
5
|
-
"size":
|
|
6
|
-
"unpackedSize":
|
|
7
|
-
"shasum": "
|
|
8
|
-
"integrity": "sha512-
|
|
3
|
+
"bridgeVersion": "4.19.0",
|
|
4
|
+
"tarball": "grix-dsh-bridge-4.19.0.tgz",
|
|
5
|
+
"size": 24834,
|
|
6
|
+
"unpackedSize": 99268,
|
|
7
|
+
"shasum": "94c398b2eaa3e9ee680fc452cfdc44ea5222c300",
|
|
8
|
+
"integrity": "sha512-kvVaplMnTLuSW/GCiyRtmLzNZpmPkQOC34tsoWNZSVvbI1QZE+Aycw4jkrQbgUo2umoPPJTG/6dyBw/1ie5Bog=="
|
|
9
9
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as u}from"node:crypto";import{parseAgentQuestionReplyMessage as
|
|
1
|
+
import{randomUUID as u}from"node:crypto";import{parseAgentQuestionReplyMessage as m}from"../core/protocol/interaction-parser.js";import{resolveCliPath as g}from"../core/util/cli-probe.js";import{CLI_INSTALL_OPTION_YES as I,CLI_INSTALL_REQUEST_PREFIX as f,buildCliInstallQuestion as C,cliMissingCommandCandidates as v,cliDisplayName as S,isCliMissingError as w,isInstallConfirmReply as b,resolveInstallAgentType as $}from"./cli-install-offer.js";import{log as H}from"../core/log/index.js";const y=["bindSessionForPool","ensureSlotStarted","sendGrixAgentQuestionCard","runConfirmedCliInstall"],M=["name","config","aibotHandle","bindingStore","sessionBindings","pendingCliInstalls","installAgentHandler"];function E(n,e){if(!n.installAgentHandler)return;const s=$(n.config.adapterType,n.config.agent.clientType||n.config.aibot.clientType);if(!s)return;const i=v(s,n.config.agent.command,n.config.adapterType);if(!w(e.err,i))return;const t=S(s,n.config.agent.command),r=`${f}${u()}`,d=String(e.cwd??"").trim()||n.bindingStore.get(e.sessionId)?.cwd;n.pendingCliInstalls.set(r,{sessionId:e.sessionId,agentType:s,cliName:t,cwd:d});const a=e.eventId||`cli-install:${e.sessionId}`,l=`\u6CA1\u627E\u5230\u672C\u673A\u7A0B\u5E8F \`${t}\`\uFF0C\u65E0\u6CD5\u542F\u52A8\u3002\u662F\u5426\u9700\u8981\u5B89\u88C5\uFF1F`;n.aibotHandle.sendMsg({event_id:a,session_id:e.sessionId,msg_type:1,content:l,...e.quotedMessageId?{quoted_message_id:e.quotedMessageId}:{}}),n.sendGrixAgentQuestionCard(a,e.sessionId,C(r,t)),H.warn(n.name,`cli missing: offered install card session=${e.sessionId} agentType=${s} cli=${t}`)}async function R(n,e){const s=m(String(e.content??""));if(!s)return!1;const i=n.pendingCliInstalls.get(s.request_id);if(!i)return!1;if(n.pendingCliInstalls.delete(s.request_id),n.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),!b(s))return n.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:`\u5DF2\u53D6\u6D88\u5B89\u88C5 ${i.cliName}\u3002`,quoted_message_id:e.msg_id}),n.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()}),!0;try{await n.runConfirmedCliInstall(i,{eventId:e.event_id,sessionId:e.session_id,quotedMessageId:e.msg_id})}catch(t){n.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:`${i.cliName} \u5B89\u88C5\u5931\u8D25\uFF1A${t instanceof Error?t.message:String(t)}`,quoted_message_id:e.msg_id})}return n.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()}),!0}async function p(n,e){const s=e.params??{},i=String(s.request_id??"").trim();if(!i)return!1;const t=n.pendingCliInstalls.get(i);if(!t)return!1;n.pendingCliInstalls.delete(i);const r=s.resolution??s.response??{},d=String(s.action??s.kind??"").trim(),a=String(r.value??s.value??"").trim(),l=d==="accept"||a===I||/^yes$/i.test(a)||/^install$/i.test(a),c=String(s.session_id??t.sessionId).trim()||t.sessionId,_=`cli-install:${i}`;if(!l)return n.aibotHandle.sendMsg({event_id:_,session_id:c,msg_type:1,content:`\u5DF2\u53D6\u6D88\u5B89\u88C5 ${t.cliName}\u3002`}),n.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"install_declined"}}),!0;try{await n.runConfirmedCliInstall(t,{eventId:_,sessionId:c}),n.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"install_started"}})}catch(o){n.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"cli_install_failed",error_msg:o instanceof Error?o.message:String(o)})}return!0}async function x(n,e,s){const i=r=>{n.aibotHandle.sendMsg({event_id:s.eventId,session_id:s.sessionId,msg_type:1,content:r,...s.quotedMessageId?{quoted_message_id:s.quotedMessageId}:{}})};if(!n.installAgentHandler){i(`\u65E0\u6CD5\u5B89\u88C5 ${e.cliName}\uFF1A\u5B89\u88C5\u5668\u672A\u5C31\u7EEA\u3002`);return}i(`\u5F00\u59CB\u5B89\u88C5 ${e.cliName}\u2026`);const t=await n.installAgentHandler({agentType:e.agentType});if(!t.ok){i(`${e.cliName} \u5B89\u88C5\u5931\u8D25\uFF1A${t.error?.message??t.phase}`);return}try{await g(e.cliName)}catch{}i(`\u2705 ${e.cliName} \u5B89\u88C5\u6210\u529F\u3002`),e.cwd&&(n.bindingStore.set(e.sessionId,e.cwd),n.sessionBindings.set(e.sessionId,e.cwd));try{await n.ensureSlotStarted(e.sessionId),e.cwd&&(await n.bindSessionForPool(e.sessionId,e.cwd),n.aibotHandle.sendUpdateBindingCard({session_id:e.sessionId,worker_status:"ready",cwd:e.cwd}),i(`\u5DE5\u4F5C\u76EE\u5F55\u5DF2\u5C31\u7EEA\uFF1A\`${e.cwd}\``))}catch(r){i(`\u5B89\u88C5\u6210\u529F\uFF0C\u4F46\u542F\u52A8\u4ECD\u5931\u8D25\uFF1A${r instanceof Error?r.message:String(r)}`)}}export{M as CLI_INSTALL_HOST_FIELDS,y as CLI_INSTALL_HOST_METHODS,p as handleCliInstallInteractionReply,R as handleCliInstallQuestionReply,E as maybeOfferCliInstall,x as runConfirmedCliInstall};
|