grix-connector 4.18.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +1 -1
  2. package/dist/adapter/acp/acp-adapter.js +12 -12
  3. package/dist/adapter/agy/agy-adapter.js +10 -10
  4. package/dist/adapter/agy/model-list.js +2 -2
  5. package/dist/adapter/agy/quota.js +5 -5
  6. package/dist/adapter/claude/claude-adapter.js +20 -20
  7. package/dist/adapter/claude/claude-bridge-server.js +1 -0
  8. package/dist/adapter/claude/claude-tools.js +1 -0
  9. package/dist/adapter/claude/claude-worker-client.js +1 -0
  10. package/dist/adapter/claude/mcp-http-launcher.js +2 -0
  11. package/dist/adapter/claude/result-timeout.js +1 -0
  12. package/dist/adapter/cursor/cursor-adapter.js +12 -11
  13. package/dist/adapter/deepseek/deepseek-adapter.js +6 -0
  14. package/dist/adapter/deepseek/index.js +1 -0
  15. package/dist/adapter/deepseek-harness/dsh-version.js +1 -1
  16. package/dist/adapter/deepseek-harness/event-mapper.js +1 -1
  17. package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +3 -3
  18. package/dist/adapter/deepseek-harness/profile-runtime.js +2 -2
  19. package/dist/adapter/opencode/opencode-transport.js +1 -1
  20. package/dist/adapter/opencode/opencode-v2-events.js +1 -1
  21. package/dist/adapter/pi/pi-adapter.js +6 -5
  22. package/dist/adapter/pi/pi-grix-tools-extension.js +2 -0
  23. package/dist/adapter/qwen/index.js +1 -0
  24. package/dist/adapter/qwen/qwen-adapter.js +4 -0
  25. package/dist/aibot/client.js +1 -0
  26. package/dist/aibot/index.js +1 -0
  27. package/dist/aibot/types.js +0 -0
  28. package/dist/assets/dsh-bridge/grix-dsh-bridge-5.0.0.tgz +0 -0
  29. package/dist/assets/dsh-bridge/manifest.json +6 -6
  30. package/dist/bridge/bridge.js +1 -1
  31. package/dist/bridge/cli-install-flow.js +1 -1
  32. package/dist/bridge/cli-install-offer.js +1 -1
  33. package/dist/bridge/local-action-session-control.js +1 -1
  34. package/dist/bridge/rate-limits.js +1 -1
  35. package/dist/bridge/send-controller.js +3 -3
  36. package/dist/bridge/session-control-open.js +1 -1
  37. package/dist/bridge/toolbar-meta.js +1 -1
  38. package/dist/core/access/allowlist-gate.js +1 -0
  39. package/dist/core/access/allowlist-store.js +1 -0
  40. package/dist/core/access/index.js +1 -0
  41. package/dist/core/file-ops/handler.js +1 -0
  42. package/dist/core/file-ops/list-files.js +1 -0
  43. package/dist/core/file-ops/types.js +0 -0
  44. package/dist/core/installer/registry.js +1 -1
  45. package/dist/core/mcp/tools.js +1 -1
  46. package/dist/core/util/home-env.js +1 -0
  47. package/dist/default-skills/grix-chat-state/SKILL.md +34 -2
  48. package/dist/grix.js +5 -5
  49. package/dist/log.js +3 -0
  50. package/dist/main.js +31 -0
  51. package/dist/manager.js +1 -1
  52. package/dist/mcp/stream-http/config.js +1 -0
  53. package/dist/mcp/stream-http/connection-binding.js +1 -0
  54. package/dist/mcp/stream-http/event-tool-executor.js +1 -0
  55. package/dist/mcp/stream-http/gateway.js +1 -0
  56. package/dist/mcp/stream-http/index.js +1 -0
  57. package/dist/mcp/stream-http/security.js +1 -0
  58. package/dist/mcp/stream-http/session-manager.js +1 -0
  59. package/dist/mcp/stream-http/tool-executor.js +1 -0
  60. package/dist/mcp/stream-http/tool-registry.js +1 -0
  61. package/dist/mcp/stream-http/tool-schemas.js +1 -0
  62. package/dist/protocol/acp-client.js +1 -1
  63. package/dist/session/index.js +1 -0
  64. package/dist/session/manager.js +1 -0
  65. package/dist/transport/index.js +1 -0
  66. package/dist/transport/json-rpc.js +3 -0
  67. package/openclaw-plugin/audit-recorder-worker.js +2 -1
  68. package/openclaw-plugin/index.js +99 -0
  69. package/openclaw-plugin/skills/grix-chat-state/SKILL.md +33 -1
  70. package/openclaw.plugin.json +1 -0
  71. package/package.json +1 -1
  72. 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 r of t)e.push(r);const n=Buffer.concat(e).toString("utf8").trim();return n?JSON.parse(n):{}}function k(t){const e=(t.headers.authorization??"").trim();return e.toLowerCase().startsWith("bearer ")?e.slice(7).trim():""}class w{host="127.0.0.1";port=0;token;callbacks;server=null;address=null;constructor(e){this.token=d(),this.callbacks=e}getToken(){return this.token}getURL(){return this.address?`http://${this.address.address}:${this.address.port}`:""}async start(){this.server||(this.server=c.createServer(async(e,n)=>{try{await this.handleRequest(e,n)}catch(r){h(n,r instanceof Error?r.message:String(r))}}),await new Promise((e,n)=>{this.server.once("error",n),this.server.listen(this.port,this.host,()=>{this.server.off("error",n),e()})}),this.address=this.server.address(),o.info("claude-bridge",`Bridge server listening on ${this.getURL()}`))}async stop(){if(!this.server)return;const e=this.server;this.server=null,this.address=null,e.closeIdleConnections?.(),e.closeAllConnections?.(),await new Promise((n,r)=>{e.close(s=>s?r(s):n())})}async handleRequest(e,n){if(k(e)!==this.token){l(n);return}if(e.method!=="POST"){n.writeHead(405,{"content-type":"application/json"}),n.end(JSON.stringify({error:"method_not_allowed"}));return}const r=new URL(e.url,"http://localhost").pathname,s=await v(e),i=f.get(r);if(!i){u(n);return}const a=await i(this.callbacks,s);p(n,a??{ok:!0})}}const f=new Map([["/v1/worker/register",async(t,e)=>(o.info("claude-bridge",`Worker registered: ${e.worker_id} (pid=${e.pid})`),t.onRegisterWorker(e))],["/v1/worker/status",async(t,e)=>(o.info("claude-bridge",`Worker status: ${e.status}`),t.onStatusUpdate(e))],["/v1/worker/send-text",async(t,e)=>t.onSendText(e)],["/v1/worker/send-stream-chunk",async(t,e)=>t.onSendStreamChunk(e)],["/v1/worker/send-media",async(t,e)=>t.onSendMedia(e)],["/v1/worker/delete-message",async(t,e)=>t.onDeleteMessage(e)],["/v1/worker/ack-event",async(t,e)=>t.onAckEvent(e)],["/v1/worker/event-result",async(t,e)=>t.onSendEventResult(e)],["/v1/worker/event-stop-ack",async(t,e)=>t.onSendEventStopAck(e)],["/v1/worker/event-stop-result",async(t,e)=>t.onSendEventStopResult(e)],["/v1/worker/session-composing",async(t,e)=>t.onSetSessionComposing(e)],["/v1/worker/agent-invoke",async(t,e)=>t.onAgentInvoke(e)],["/v1/worker/local-action-result",async(t,e)=>t.onLocalActionResult(e)]]);export{w as ClaudeBridgeServer};
@@ -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(r,e){r.setRequestHandler(w,async()=>({tools:I})),r.setRequestHandler(S,async i=>{const{name:n,arguments:t}=i.params,s=t??{};try{switch(n){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(n,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(n,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${n}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${n} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(r,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const n=String(r.text??""),t=String(r.chat_id??""),s=String(r.event_id??i.eventId),a=r.reply_to,d=r.files,_=r.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!n.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,n),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(r,e){const i=e.getActiveEvent(),n=String(r.event_id??""),t=r.status??"",s=r.code,a=r.msg;if(!n||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(n)?(e.bridge.sendEventResult(n,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(r,e){const i=String(r.chat_id??""),n=String(r.message_id??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:n},y),c(`deleted (${n})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(r){const e=r.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(r,e){const i=String(r.chat_id??""),n=String(r.text??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(n),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(r,e,i){try{const n=C[r];if(!n)throw new Error(`Unknown access control tool: ${r}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:n.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}async function O(r,e,i){try{const n=k(r,e);if(!E.has(n.action))throw new Error(`Action not allowed: ${n.action}`);const t=await i.bridge.agentInvoke(n.action,n.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}function c(r){return{content:[{type:"text",text:r}]}}export{q as registerClaudeTools};
@@ -0,0 +1 @@
1
+ import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(r,e){this.controlURL=r.replace(/\/+$/,""),this.token=e.trim(),l.info("claude-worker-client",`Configured with control URL: ${this.controlURL}`)}async post(r,e,s){if(!this.isConfigured())throw new Error("worker control not configured");const i=new AbortController,o=setTimeout(()=>i.abort(),s);try{const t=await fetch(`${this.controlURL}${r}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.token}`},body:JSON.stringify(e),signal:i.signal}),n=await t.text(),a=n.trim()?JSON.parse(n):{};if(!t.ok)throw new Error(a.error||`worker control failed ${t.status}`);return a}finally{clearTimeout(o)}}isRetryableError(r){const e=r instanceof Error?r.message:String(r);return/fetch failed|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|aborted/i.test(e)}async postWithRetry(r,e,s,i=1){let o;for(let t=0;t<=i;t++)try{return t>0&&l.info("claude-worker-client",`Retrying ${r} attempt=${t+1}`),await this.post(r,e,s)}catch(n){if(o=n,t>=i||!this.isRetryableError(n))break;await new Promise(a=>setTimeout(a,150))}throw o instanceof Error?o:new Error(String(o))}async deliverEvent(r){return this.postWithRetry("/v1/worker/deliver-event",{payload:r},1e4,1)}async deliverStop(r){return this.postWithRetry("/v1/worker/deliver-stop",{payload:r},1e4,1)}async deliverLocalAction(r){return this.postWithRetry("/v1/worker/deliver-local-action",{payload:r},1e4,1)}async ping(){try{return await this.postWithRetry("/v1/worker/ping",{},5e3,1),!0}catch{return!1}}}export{c as ClaudeWorkerClient};
@@ -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 m}from"./protocol-contract.js";function P(t){let e=null,r=0,n=!1,i=!1;const a=v(),s=t.gatewayUrl??"http://127.0.0.1:19580/mcp";return{async start(){await F(t.command,s,t.env);const c=E(t.grix),u=[...t.args??[],"--name",`grix-mcp-${t.name}`,"--session-id",a];t.fullAuto&&u.push("--dangerously-skip-permissions"),u.push("--dangerously-load-development-channels",`server:${m}`,"--append-system-prompt",c);const f=d(I(),`grix-mcp-claude-${t.name}`);await S(f,{recursive:!0});const{expectPath:$,pidPath:g}=await M(f,t.command,u),_={...process.env,...t.env??{}};e=x("/usr/bin/expect",[$],{cwd:t.cwd,env:_,stdio:["ignore","pipe","pipe"],detached:!0}),o.info("mcp-http-launcher",`\u542F\u52A8 Claude: name=${t.name} cwd=${t.cwd} pid=${e.pid}`),r=await k(g),n=!0,o.info("mcp-http-launcher",`Claude \u5B50\u8FDB\u7A0B PID: ${r}`),e.on("exit",(l,p)=>{o.info("mcp-http-launcher",`Claude \u9000\u51FA: code=${l} signal=${p}`),n=!1,e=null,r=0,i||(o.info("mcp-http-launcher","3 \u79D2\u540E\u81EA\u52A8\u91CD\u542F..."),setTimeout(()=>{i||this.start().catch(w=>{o.error("mcp-http-launcher",`\u91CD\u542F\u5931\u8D25: ${w}`)})},3e3))}),e.stdout?.on("data",l=>{const p=l.toString().trim();p&&o.info("mcp-http-launcher",`[stdout] ${p.slice(0,300)}`)}),e.stderr?.on("data",l=>{const p=l.toString().trim();p&&o.info("mcp-http-launcher",`[stderr] ${p.slice(0,300)}`)})},async stop(){if(i=!0,n=!1,r>0)try{process.kill(r,"SIGTERM")}catch{}if(e?.pid){try{process.kill(-e.pid,"SIGTERM")}catch{}await new Promise(c=>{const u=setTimeout(()=>{if(r>0)try{process.kill(r,"SIGKILL")}catch{}if(e?.pid)try{process.kill(-e.pid,"SIGKILL")}catch{}c()},5e3);e?.once("exit",()=>{clearTimeout(u),c()})})}e=null,r=0},getStatus(){return{name:t.name,alive:n,pid:r}}}}function E(t){return["You are connected to a chat via the grix MCP server.",`On startup, immediately call grix_authorize with: agentId="${t.agentId}", apiKey="${t.apiKey}", wsUrl="${t.wsUrl}", clientType="${t.clientType}".`,"When you receive a <channel> message, you MUST respond by calling the grix_reply tool (or the grix_complete tool if no response is needed).","Never write your reply as plain text \u2014 it will NOT reach the user. Only the grix_reply tool delivers your response to the chat.","The <channel> message contains event_id and session_id \u2014 pass them to grix_reply."].join(" ")}async function F(t,e,r){const n=d(T(),".claude.json");let i=null;try{const s=C(n,"utf8");i=JSON.parse(s)?.mcpServers?.[m]??null}catch{}if(i&&String(i.type??"").trim()==="http"&&String(i.url??"").trim()===e)return;o.info("mcp-http-launcher",`\u6CE8\u518C MCP Server: ${m} -> ${e}`);const a={...process.env,...r??{}};try{y(`${t} mcp remove -s user ${m}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}catch{}y(`${t} mcp add --scope user --transport http ${m} ${e}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}async function M(t,e,r){const{writeFile:n}=await import("node:fs/promises"),i=d(t,"claude.pid"),a=d(t,"claude.expect"),s=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set claude_command [list {${h(e)}}${r.map(c=>` {${h(c)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${h(i)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","expect {"," -re {(?i)(Quick.*safety.*check|trust.*folder)} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)I am using this for local development} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)(Enter.*confirm|Press.*Enter|Hit.*Enter)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {Listening for channel} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," -re {bypass permissions} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," eof {}","}","expect eof",""];return await n(i,"","utf8"),await n(a,s.join(`
2
+ `),"utf8"),{expectPath:a,pidPath:i}}function h(t){return t.replace(/[\\{}$\[\]"]/g,"\\$&")}async function k(t,e=1e4){const{readFile:r}=await import("node:fs/promises"),n=Math.ceil(e/100);for(let i=0;i<n;i++){try{const a=await r(t,"utf8"),s=parseInt(String(a).trim(),10);if(Number.isFinite(s)&&s>0)return s}catch{}await new Promise(a=>setTimeout(a,100))}return 0}export{P as createMcpHttpLauncher};
@@ -0,0 +1 @@
1
+ class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(e){this.defaultTimeoutMs=e.defaultTimeoutMs??9e4,this.onTimeout=e.onTimeout}arm(e,t){this.cancel(e);const s=t?.timeoutMs??this.defaultTimeoutMs,i=Date.now()+s,o=setTimeout(()=>{this.timers.delete(e),this.onTimeout(e).catch(()=>{})},s);return this.timers.set(e,o),i}cancel(e){const t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}has(e){return this.timers.has(e)}close(){for(const e of this.timers.values())clearTimeout(e);this.timers.clear()}}export{m as ResultTimeoutManager};
@@ -1,15 +1,16 @@
1
- import{execFileSync as ee}from"node:child_process";import{createInterface as E}from"node:readline";import{EventEmitter as L}from"node:events";import{randomUUID as te}from"node:crypto";import{mkdirSync as P,readFileSync as q,writeFileSync as D,readdirSync as se,statSync as N}from"node:fs";import{join as A,resolve as ne}from"node:path";import{fileURLToPath as ie}from"node:url";import{homedir as F}from"node:os";import{GRIX_PATHS as re,log as u}from"../../core/log/index.js";import{IdentityInjector as oe}from"../shared/identity-injector.js";import{buildSimpleProbeReport as ae}from"../shared/probe-util.js";import{InternalApiServer as de}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as le,pruneLegacyMcpServerEntries as ce}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as ue}from"../shared/inbound-message-id-injector.js";import{insertBeforeTrailingMessageReferences as R}from"../../core/protocol/message-reference.js";import{syncDefaultSkillsToDir as he}from"../../default-skills/index.js";import{spawnCommand as B,killProcessGroup as C}from"../../core/runtime/spawn.js";import{countLivingDescendantsOutsideBaseline as me,listLivingDescendants as fe}from"./living-descendants.js";import{SessionBindingStore as pe}from"../../core/persistence/session-binding-store.js";import{fetchCursorParameterizedModels as ge}from"./fetch-models.js";import{resolveCursorSpawn as x}from"./resolve-command.js";import{fetchCursorAccountUsage as Se}from"./fetch-usage.js";import{buildCursorContextWindow as ye,buildCursorContextWindowFromUsage as ve,resolveCursorContextWindowSize as _e}from"./context-window.js";const Ae=12e4,M=300*1e3,j=90*1e3,O=1800*1e3,be=8192,Q="Summarize this conversation for handoff to a fresh chat. Include: goals, key decisions, important file paths, current status, and next steps. Be concise but complete. Output ONLY the summary text.",U=600*1e3,W=90,H=new Set(["completed","failed","error","errored","canceled","cancelled","rejected"]);function we(d){const e=d.replace(/ToolCall$/i,"").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):d||"tool"}function z(d){const e=String(d.call_id??d.callId??"").trim(),t=d.tool_call??d.toolCall;if(t&&typeof t=="object"&&!Array.isArray(t)){const n=Object.keys(t);if(n.length>0){const s=n[0],r=t[s],i=r&&typeof r=="object"&&!Array.isArray(r)?r:null;return{toolName:we(s),toolInput:i?.args??i?.arguments??{},callId:e}}}return{toolName:String(d.name??d.tool_name??d.toolName??"tool").trim()||"tool",toolInput:d.args??d.tool_input??d.toolInput??{},callId:e}}function J(d){return String(d??"").trim().toLowerCase().replace(/[^a-z0-9]/g,"")}function G(d){const e=J(d);return e==="askquestion"||e==="askuserquestion"}function X(d){const e=J(d);return e==="createplan"||e==="exitplanmode"}function ke(d){if(!Array.isArray(d))return;const e=d.map(t=>{if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";const n=t,s=String(n.label??"").trim();if(s)return s;const r=String(n.value??"").trim();if(r)return r;const i=String(n.text??"").trim();return i||""}).filter(t=>t.length>0);return e.length>0?e:void 0}function Ce(d){if(!d||typeof d!="object"||Array.isArray(d))return null;const e=d,t=String(e.title??"").trim(),n=e.questions;if(!Array.isArray(n)||n.length===0)return null;const s=[];for(let r=0;r<n.length;r++){const i=n[r];if(!i||typeof i!="object")continue;const o=i,a=t||`Question ${r+1}`,l=String(o.header??o.id??o.question??a).trim()||a,c=String(o.prompt??o.question??"").trim();if(!c)continue;const h=ke(o.options),p=o.multiSelect===!0||o.multi_select===!0;s.push({header:l,prompt:c,...h?{options:h}:{},...p?{multi_select:!0}:{},allow_free_text:!0})}return s.length>0?s:null}function Ie(d){if(!d||typeof d!="object"||Array.isArray(d))return null;const e=d,t=String(e.name??e.title??"").trim(),n=String(e.overview??"").trim(),s=String(e.plan??"").trim();if(!s&&!n&&!t)return null;const r=[];return t&&r.push(`# ${t}`),n&&r.push(n),s&&r.push(s),r.join(`
1
+ import{execFileSync as ne}from"node:child_process";import{createInterface as F}from"node:readline";import{EventEmitter as N}from"node:events";import{randomUUID as ie}from"node:crypto";import{mkdirSync as O,readFileSync as T,writeFileSync as j,readdirSync as re,statSync as B}from"node:fs";import{join as w,resolve as oe}from"node:path";import{fileURLToPath as ae}from"node:url";import{homedir as Q}from"node:os";import{GRIX_PATHS as le,log as h}from"../../core/log/index.js";import{IdentityInjector as de}from"../shared/identity-injector.js";import{buildSimpleProbeReport as ce}from"../shared/probe-util.js";import{InternalApiServer as ue}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as he,pruneLegacyMcpServerEntries as fe}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as me}from"../shared/inbound-message-id-injector.js";import{insertBeforeTrailingMessageReferences as M}from"../../core/protocol/message-reference.js";import{syncDefaultSkillsToDir as pe}from"../../default-skills/index.js";import{spawnCommand as $,killProcessGroup as I}from"../../core/runtime/spawn.js";import{countLivingDescendantsOutsideBaseline as W,listLivingDescendants as ge}from"./living-descendants.js";import{SessionBindingStore as Se}from"../../core/persistence/session-binding-store.js";import{fetchCursorParameterizedModels as ye}from"./fetch-models.js";import{resolveCursorSpawn as P}from"./resolve-command.js";import{fetchCursorAccountUsage as _e}from"./fetch-usage.js";import{buildCursorContextWindow as ve,buildCursorContextWindowFromUsage as Ae,resolveCursorContextWindowSize as be}from"./context-window.js";const we=12e4,q=300*1e3,U=90*1e3,z=1800*1e3,ke=8192,H="Summarize this conversation for handoff to a fresh chat. Include: goals, key decisions, important file paths, current status, and next steps. Be concise but complete. Output ONLY the summary text.",J=600*1e3,G=90,X=new Set(["completed","failed","error","errored","canceled","cancelled","rejected"]);function Ce(l){const e=l.replace(/ToolCall$/i,"").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):l||"tool"}function K(l){const e=String(l.call_id??l.callId??"").trim(),t=l.tool_call??l.toolCall;if(t&&typeof t=="object"&&!Array.isArray(t)){const n=Object.keys(t);if(n.length>0){const s=n[0],i=t[s],r=i&&typeof i=="object"&&!Array.isArray(i)?i:null;return{toolName:Ce(s),toolInput:r?.args??r?.arguments??{},callId:e}}}return{toolName:String(l.name??l.tool_name??l.toolName??"tool").trim()||"tool",toolInput:l.args??l.tool_input??l.toolInput??{},callId:e}}function V(l){return String(l??"").trim().toLowerCase().replace(/[^a-z0-9]/g,"")}function Y(l){const e=V(l);return e==="askquestion"||e==="askuserquestion"}function Z(l){const e=V(l);return e==="createplan"||e==="exitplanmode"}function Ie(l){if(!Array.isArray(l))return;const e=l.map(t=>{if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";const n=t,s=String(n.label??"").trim();if(s)return s;const i=String(n.value??"").trim();if(i)return i;const r=String(n.text??"").trim();return r||""}).filter(t=>t.length>0);return e.length>0?e:void 0}function xe(l){if(!l||typeof l!="object"||Array.isArray(l))return null;const e=l,t=String(e.title??"").trim(),n=e.questions;if(!Array.isArray(n)||n.length===0)return null;const s=[];for(let i=0;i<n.length;i++){const r=n[i];if(!r||typeof r!="object")continue;const o=r,a=t||`Question ${i+1}`,u=String(o.header??o.id??o.question??a).trim()||a,c=String(o.prompt??o.question??"").trim();if(!c)continue;const d=Ie(o.options),f=o.multiSelect===!0||o.multi_select===!0;s.push({header:u,prompt:c,...d?{options:d}:{},...f?{multi_select:!0}:{},allow_free_text:!0})}return s.length>0?s:null}function Be(l){if(!l||typeof l!="object"||Array.isArray(l))return null;const e=l,t=String(e.name??e.title??"").trim(),n=String(e.overview??"").trim(),s=String(e.plan??"").trim();if(!s&&!n&&!t)return null;const i=[];return t&&i.push(`# ${t}`),n&&i.push(n),s&&i.push(s),i.join(`
2
2
 
3
- `)}function Re(d){if(!d||typeof d!="object"||Array.isArray(d))return null;const e=d,t=String(e.type??"").trim().toLowerCase();if(!t)return null;switch(t){case"tool_call":{const n=String(e.subtype??"").trim().toLowerCase(),s=z(e);return G(s.toolName)||X(s.toolName)?null:n==="started"||n==="start"?{type:"tool_call",payload:{tool_name:s.toolName,...s.callId?{tool_call_id:s.callId}:{}}}:(H.has(n),null)}case"error":return{type:"error",payload:{message:String(e.message??e.error??e.result??"cursor error").trim()||"cursor error"}};case"result":{const n=String(e.subtype??"").trim().toLowerCase();return e.is_error===!0||n==="error"?{type:"error",payload:{message:String(e.result??e.message??"cursor run failed").trim()||"cursor run failed"}}:null}default:return null}}function Be(d,e){if(!d||typeof d!="object"||Array.isArray(d))return"";const t=d;if(String(t.type??"")!=="assistant")return"";const n=t.model_call_id??t.modelCallId;if(n!=null&&String(n).trim()!=="")return"";const s=t.message,r=s&&typeof s=="object"&&!Array.isArray(s)?s.content:void 0;if(!Array.isArray(r))return"";const i=r.map(o=>{if(!o||typeof o!="object"||Array.isArray(o))return"";const a=o;return a.type==="text"?String(a.text??""):""}).filter(Boolean).join("");if(!i)return"";if(e){if(i===e||e.startsWith(i)&&i.length<e.length)return"";if(i.startsWith(e))return i.slice(e.length)}return i}const K=[{id:"approval",displayName:"\u4EBA\u5DE5\u786E\u8BA4"},{id:"full_auto",displayName:"\u81EA\u7531\u6A21\u5F0F"},{id:"plan",displayName:"\u8BA1\u5212\u6A21\u5F0F"}];function I(d){const e=String(d??"").trim().toLowerCase();return K.some(t=>t.id===e)?e:null}function T(d){try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}function V(d,e,t){if(t<0)return null;let n;try{n=se(d,{withFileTypes:!0})}catch{return null}for(const s of n){const r=A(d,s.name);if(s.isDirectory()){const i=V(r,e,t-1);if(i)return i}else if(s.isFile()&&s.name.endsWith(e))return r}return null}function Y(d,e){if(!d)return null;const t=e||A(F(),".cursor","projects");return V(t,`${d}.jsonl`,6)}function xe(d){const e=d.context_messages_json;if(e)try{const t=JSON.parse(e);return!Array.isArray(t)||t.length===0?void 0:t.map(n=>({senderId:String(n.sender_id??"unknown"),content:String(n.content??"")}))}catch{return}}function Me(d,e){const t=[String(d??"")],n=String(e.quoted_message_id??"").trim();n&&t.push(`[quoted_message_id] ${n}`);const s=String(e.attachments_json??"").trim();return s&&t.push(`[attachments_json]
4
- ${s}`),t.filter(r=>r.length>0).join(`
3
+ `)}function Re(l){if(!l||typeof l!="object"||Array.isArray(l))return null;const e=l,t=String(e.type??"").trim().toLowerCase();if(!t)return null;switch(t){case"tool_call":{const n=String(e.subtype??"").trim().toLowerCase(),s=K(e);return Y(s.toolName)||Z(s.toolName)?null:n==="started"||n==="start"?{type:"tool_call",payload:{tool_name:s.toolName,...s.callId?{tool_call_id:s.callId}:{}}}:(X.has(n),null)}case"error":return{type:"error",payload:{message:String(e.message??e.error??e.result??"cursor error").trim()||"cursor error"}};case"result":{const n=String(e.subtype??"").trim().toLowerCase();return e.is_error===!0||n==="error"?{type:"error",payload:{message:String(e.result??e.message??"cursor run failed").trim()||"cursor run failed"}}:null}default:return null}}function Te(l,e){if(!l||typeof l!="object"||Array.isArray(l))return"";const t=l;if(String(t.type??"")!=="assistant")return"";const n=t.message,s=n&&typeof n=="object"&&!Array.isArray(n)?n.content:void 0;if(!Array.isArray(s))return"";const i=s.map(r=>{if(!r||typeof r!="object"||Array.isArray(r))return"";const o=r;return o.type==="text"?String(o.text??""):""}).filter(Boolean).join("");if(!i)return"";if(e){if(i===e||e.startsWith(i)&&i.length<e.length)return"";if(i.startsWith(e))return i.slice(e.length)}return i}const ee=[{id:"approval",displayName:"\u4EBA\u5DE5\u786E\u8BA4"},{id:"full_auto",displayName:"\u81EA\u7531\u6A21\u5F0F"},{id:"plan",displayName:"\u8BA1\u5212\u6A21\u5F0F"}];function x(l){const e=String(l??"").trim().toLowerCase();return ee.some(t=>t.id===e)?e:null}function E(l){try{return process.kill(l,0),!0}catch(e){return e.code==="EPERM"}}function te(l,e,t){if(t<0)return null;let n;try{n=re(l,{withFileTypes:!0})}catch{return null}for(const s of n){const i=w(l,s.name);if(s.isDirectory()){const r=te(i,e,t-1);if(r)return r}else if(s.isFile()&&s.name.endsWith(e))return i}return null}function L(l,e){if(!l)return null;const t=e||w(Q(),".cursor","projects");return te(t,`${l}.jsonl`,6)}function Me(l,e){let t;try{const i=T(l);t=e<i.length?i.subarray(e):Buffer.alloc(0)}catch{return null}const n=t.toString("utf8").split(`
4
+ `);let s=!1;for(let i=n.length-1;i>=0;i--){const r=n[i]?.trim();if(!r)continue;let o;try{o=JSON.parse(r)}catch{continue}if(o.role==="user"||o.type==="user"){s=!0;continue}if(o.role!=="assistant"&&o.type!=="assistant")continue;const a=o.message;if(!a||typeof a!="object"||Array.isArray(a))continue;const u=a.content;if(!Array.isArray(u))continue;const c=u.filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d));return{lastAssistant:{text:c.filter(d=>d.type==="text").map(d=>String(d.text??"")).join(""),hasToolUse:c.some(d=>d.type==="tool_use")},hasUserAfterLastAssistant:s}}return{lastAssistant:null,hasUserAfterLastAssistant:s}}function $e(l){const e=l.context_messages_json;if(e)try{const t=JSON.parse(e);return!Array.isArray(t)||t.length===0?void 0:t.map(n=>({senderId:String(n.sender_id??"unknown"),content:String(n.content??"")}))}catch{return}}function Pe(l,e){const t=[String(l??"")],n=String(e.quoted_message_id??"").trim();n&&t.push(`[quoted_message_id] ${n}`);const s=String(e.attachments_json??"").trim();return s&&t.push(`[attachments_json]
5
+ ${s}`),t.filter(i=>i.length>0).join(`
5
6
 
6
- `)}class Z extends L{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){u.warn("cursor-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}class $ extends L{type="cursor";static STDERR_MAX_CHARS=8192;config;callbacks;alive=!1;stopped=!1;permissionHandler=null;internalApi=null;bindingStore=null;identity;inboundMessageIds=new ue;inboundQueue=[];pendingBySession=new Map;sessions=new Set;sessionRuntime=new Map;sessionSeq=0;lastUsageBySession=new Map;auditCaptures=new Map;completedAuditBoundaries=new Map;lastContextBySession=new Map;compactingSessions=new Set;pendingHandoffBySession=new Map;pendingQuestionByRequestId=new Map;pendingQuestionAnswerBySession=new Map;cachedAccountRateLimits=null;rateLimitsInflight=null;_availableModels=[];transcriptPathBySession=new Map;activeBySession=new Map;constructor(e,t){super(),this.config=e,this.callbacks=t;const n=e.options??{};this.bindingStore=n.bindingStore instanceof pe?n.bindingStore:null,this.identity=new oe("cursor-adapter",t.getAgentProfile)}async start(){this.alive=!0,this.stopped=!1,(this.config.options??{}).mcp_tools!==!1&&(this.internalApi=new de,this.internalApi.setInvokeHandler(async(t,n,s,r)=>this.callbacks.agentInvoke(t,n,r)),await this.internalApi.start()),this.notifyBindingReady(),this.refreshModels().then(()=>this.notifyBindingReady()).catch(()=>{}),this.refreshAccountRateLimits().then(()=>this.notifyBindingReady()).catch(()=>{})}get availableModels(){return this._availableModels}get availableModes(){return K.map(e=>({...e}))}async refreshModels(){try{const e={...process.env,...this.config.env??{}},t=await ge({command:this.config.command,env:e,cwd:process.cwd()});t.length>0&&(this._availableModels=t,u.info("cursor-adapter",`Loaded ${t.length} available models`))}catch(e){u.warn("cursor-adapter",`Failed to refresh models: ${e instanceof Error?e.message:String(e)}`)}}async stop(){this.stopped=!0,this.alive=!1;for(const e of this.activeBySession.values())C(e.child,"SIGTERM");this.activeBySession.clear(),this.transcriptPathBySession.clear(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null)}isAlive(){return this.alive}async createSession(e){const t=`cursor-${Date.now()}-${++this.sessionSeq}`;return this.sessions.add(t),this.sessionRuntime.set(t,{cwd:typeof e.cwd=="string"?e.cwd:void 0,modelId:typeof e.modelId=="string"?e.modelId:void 0,modeId:typeof e.modeId=="string"?e.modeId:void 0}),t}async resumeSession(e,t){this.sessions.add(e);const n=this.sessionRuntime.get(e)??{};this.sessionRuntime.set(e,{...n,cwd:typeof t?.cwd=="string"?t.cwd:n.cwd,modelId:typeof t?.modelId=="string"?t.modelId:n.modelId,modeId:typeof t?.modeId=="string"?t.modeId:n.modeId})}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(e){this.sessions.delete(e),this.sessionRuntime.delete(e),this.transcriptPathBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e),this.pendingQuestionAnswerBySession.delete(e),this.pendingHandoffBySession.delete(e);for(const[t,n]of this.pendingQuestionByRequestId)n.sessionId===e&&this.pendingQuestionByRequestId.delete(t)}sendPrompt(e){const t=new Z(e.adapterSessionId);if(!this.alive||this.stopped)return queueMicrotask(()=>t.emitError(new Error("adapter not running"))),t;const n=this.inboundQueue.shift()??{event_id:`cursor-evt-${Date.now()}`,session_id:e.adapterSessionId,content:e.text},s=e.adapterSessionId,r=this.pendingBySession.get(s)??[];return r.push({event:n,request:e,handle:t}),this.pendingBySession.set(s,r),this.tryStartNext(s),t}tryStartNext(e){if(this.compactingSessions.has(e)||this.activeBySession.has(e)||!this.alive||this.stopped)return;const t=this.pendingBySession.get(e);if(!t||t.length===0)return;const n=t.shift();t.length===0?this.pendingBySession.delete(e):this.pendingBySession.set(e,t),n&&this.startJob(n,!1,0)}startJob(e,t,n){const{event:s,request:r,handle:i}=e;s.audit?.enabled&&!this.auditCaptures.has(s.event_id)&&this.auditCaptures.set(s.event_id,[]);const o=r.adapterSessionId,a=this.sessionRuntime.get(r.adapterSessionId)??{},l=this.config.options??{},c=[...this.config.args??[]];c.push("-p","--output-format","stream-json"),l.trust!==!1&&c.push("--trust");const h=a.cwd||l.workspace;this.internalApi&&h&&(this.ensureWorkspaceMcpAndSkills(h),c.push("--approve-mcps")),h&&c.push("--workspace",h);const p=a.modelId||l.model;p&&c.push("--model",p);const _=I(a.modeId||l.mode)??"full_auto";_==="full_auto"?c.push("--yolo"):_==="plan"&&c.push("--plan");const v=a.cursorSessionId??this.bindingStore?.getAcpSessionId(r.adapterSessionId),b=!!(v&&l.use_continue!==!1&&!t);b&&c.push("--resume",v),c.push(this.buildPromptText(r));const m={...process.env,...this.config.env??{}},g=x(this.config.command,m);u.info("cursor-adapter",`job start: event=${s.event_id} session=${s.session_id} retry=${n}`);let S;try{S=B(g.command,[...g.prefixArgs,...c],{cwd:h||process.cwd(),env:g.env,stdio:["ignore","pipe","pipe"]}).process}catch(y){this.finishActive(o,"failed",`spawn failed: ${y instanceof Error?y.message:String(y)}`);return}this.callbacks.sendEventAck(s.event_id,s.session_id),this.emit("eventStarted",s.event_id,s.session_id);const f={event:s,request:r,handle:i,child:S,seq:0,done:!1,stderr:"",timer:null,idleTimer:null,toolCallsInFlight:new Set,toolCallsStarted:0,assistantTextEmitted:"",streamBuffer:"",lastIoAt:Date.now(),sawResult:!1,descendantBaseline:void 0,retryCount:n,usedContinue:b,workspace:h||process.cwd(),args:c};this.activeBySession.set(o,f),this.notifyBindingReady(o),this.armActiveIdleTimer(o);const w=r.timeoutMs&&r.timeoutMs>0?r.timeoutMs:0;w>0&&(f.timer=setTimeout(()=>{f.done||(C(S,"SIGTERM"),this.finishActive(o,"failed",`cursor agent timeout after ${w}ms`))},w)),E({input:S.stdout}).on("line",y=>this.handleStdoutLineForActive(f,y)),S.stderr?.on("data",y=>{if(f.done)return;const k=f.stderr+String(y??"");f.stderr=k.length>$.STDERR_MAX_CHARS?k.slice(-$.STDERR_MAX_CHARS):k,f.lastIoAt=Date.now(),this.armActiveIdleTimer(o)}),S.once("error",y=>{this.finishActive(o,"failed",`spawn failed: ${String(y?.message??y)}`)}),S.once("close",y=>{if(!f.done)if((y??0)===0)this.finishActive(o,"responded");else{if(this.shouldRetryWithoutContinue(f)){f.timer&&clearTimeout(f.timer),f.idleTimer&&clearTimeout(f.idleTimer),this.activeBySession.delete(o),this.startJob(e,!0,f.retryCount+1);return}const k=f.stderr.trim()||`cursor agent exited with code ${y??-1}`;this.finishActive(o,"failed",k)}})}async cancel(e){const t=this.activeBySession.get(e);t&&(C(t.child,"SIGTERM"),this.finishActive(e,"canceled","canceled"))}deliverInboundEvent(e){const t=String(e.session_id??"").trim();if(!t){u.warn("cursor-adapter",`Dropping event ${e.event_id}: missing session_id`),this.callbacks.sendEventResult(e.event_id,"failed","missing session_id");return}if(!this.alive||this.stopped){u.warn("cursor-adapter",`Dropping event ${e.event_id}: adapter not running`),this.callbacks.sendEventAck(e.event_id,t),this.callbacks.sendEventResult(e.event_id,"failed","adapter not running");return}const n={adapterSessionId:t,text:this.inboundMessageIds.inject(t,Me(String(e.content??""),e),e.msg_id),contextMessages:xe(e)},s=new Z(t),r=this.pendingBySession.get(t)??[];r.push({event:e,request:n,handle:s}),this.pendingBySession.set(t,r),u.info("cursor-adapter",`inbound queued: event=${e.event_id} session=${t} depth=${r.length}`),this.tryStartNext(t)}cancelSessionWork(e,t){const n=this.pendingBySession.get(e)??[];this.pendingBySession.delete(e);const s=this.activeBySession.get(e);s&&(this.killChildWithFallback(s.child),this.finishActive(e,"canceled",t));for(const r of n)this.callbacks.sendEventAck(r.event.event_id,r.event.session_id),this.callbacks.sendEventResult(r.event.event_id,"canceled",t),r.handle.emitDone({status:"canceled",error:t})}killChildWithFallback(e){C(e,"SIGTERM"),setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{C(e,"SIGKILL")}catch{}},5e3).unref()}deliverStopEvent(e,t){if(t){const n=this.activeBySession.get(t);if(n?.event.event_id===e){this.killChildWithFallback(n.child),this.finishActive(t,"canceled","stopped");return}const s=this.pendingBySession.get(t)??[],r=s.findIndex(i=>i.event.event_id===e);if(r>=0){const[i]=s.splice(r,1);s.length===0?this.pendingBySession.delete(t):this.pendingBySession.set(t,s),this.callbacks.sendEventAck(i.event.event_id,i.event.session_id),this.callbacks.sendEventResult(i.event.event_id,"canceled","stopped"),i.handle.emitDone({status:"canceled",error:"stopped"})}return}for(const[n,s]of this.activeBySession.entries())if(s.event.event_id===e){this.killChildWithFallback(s.child),this.finishActive(n,"canceled","stopped");return}for(const[n,s]of this.pendingBySession.entries()){const r=s.findIndex(o=>o.event.event_id===e);if(r<0)continue;const[i]=s.splice(r,1);s.length===0?this.pendingBySession.delete(n):this.pendingBySession.set(n,s),this.callbacks.sendEventAck(i.event.event_id,i.event.session_id),this.callbacks.sendEventResult(i.event.event_id,"canceled","stopped"),i.handle.emitDone({status:"canceled",error:"stopped"});return}}async handleLocalAction(e){const t=String(e.action_type??"").trim().toLowerCase(),n=e.params??{},s=String(n.session_id??"").trim(),r=e.action_id;if(t==="claude_interaction_reply")return String(n.kind??"").trim()==="permission"?(this.callbacks.sendLocalActionResult(r,"failed",void 0,"unsupported","Cursor adapter does not support interactive permission approvals"),{handled:!0,kind:"permission_unsupported"}):this.handleQuestionReply(e);switch(t){case"set_model":{const i=String(n.model_id??"").trim();if(!i||!s)return this.callbacks.sendLocalActionResult(r,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};const o=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...o,modelId:i}),this.notifyBindingReady(s);const a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(r,"ok",{outcome:"model_set",session_context:{model_id:i,mode_id:a.mode_id,modelId:i,modeId:a.mode_id},model_id:i,mode_id:a.mode_id,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"set_model"}}case"set_mode":{const i=I(n.mode_id);if(!i||!s)return this.callbacks.sendLocalActionResult(r,"failed",void 0,"invalid_params","mode_id must be approval, full_auto, or plan and session_id is required"),{handled:!0,kind:"set_mode"};const o=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...o,modeId:i}),this.notifyBindingReady(s);const a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(r,"ok",{outcome:"mode_set",session_context:{model_id:a.model_id,mode_id:i,modelId:a.model_id,modeId:i},model_id:a.model_id,mode_id:i,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"set_mode"}}case"get_context":{const i=s?this.sessionRuntime.get(s):void 0,o=this.config.options??{},a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(r,"ok",{session_context:{model_id:a.model_id,mode_id:a.mode_id,cwd:i?.cwd??o.workspace??null},model_id:a.model_id,mode_id:a.mode_id,modelId:a.model_id,modeId:a.mode_id,cwd:i?.cwd??o.workspace??null,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"get_context"}}case"get_rate_limits":{await this.refreshAccountRateLimits({force:!0});const i=this.getRateLimitsSnapshot(s||void 0);return this.callbacks.sendLocalActionResult(r,"ok",i),s&&this.notifyBindingReady(s),{handled:!0,kind:"get_rate_limits"}}case"get_session_usage":{const i=s?this.getUsageSnapshot(s):null;if(i){const o={inputTokens:i.total.input,outputTokens:i.total.output,cacheReadInputTokens:i.total.cacheRead,cacheCreationInputTokens:i.total.cacheWrite};this.callbacks.sendLocalActionResult(r,"ok",{sessionId:s,adapterType:"cursor",sampledAt:i.sampledAt,turns:i.turns,total:o,models:[{model:this.getToolbarMeta(s).model_id??"auto",turns:i.turns,total:o}]})}else this.callbacks.sendLocalActionResult(r,"failed",void 0,"usage_not_found","No usage data found for this session");return{handled:!0,kind:"get_session_usage"}}case"session_control":{const i=String(n.verb??"").trim().toLowerCase();if(i==="restart"&&s)this.cancelSessionWork(s,"restarted"),this.callbacks.sendLocalActionResult(r,"ok",{outcome:"restarted"});else if(i==="status"){const o=this.sessionRuntime.get(s),a=this.config.options??{},l=this.getToolbarMeta(s),c=this.activeBySession.has(s);this.callbacks.sendLocalActionResult(r,"ok",{verb:"status",status:c?"running":"idle",session_context:{model_id:l.model_id,mode_id:l.mode_id,cwd:o?.cwd??a.workspace??null},model_id:l.model_id,mode_id:l.mode_id,modelId:l.model_id,modeId:l.mode_id,cwd:o?.cwd??a.workspace??null,available_models:this.availableModels,available_modes:this.availableModes})}else this.callbacks.sendLocalActionResult(r,"failed",void 0,"invalid_verb",`Unsupported verb: ${i}`);return{handled:!0,kind:"session_control"}}default:return{handled:!1,kind:"unsupported"}}}getSupportedCommands(){return[{name:"compact",description:"\u538B\u7F29\u4E0A\u4E0B\u6587",args:"[instructions]"}]}async execCommand(e,t,n){return e!=="compact"?{status:"unsupported",message:`Unsupported command: ${e}`}:this.runCompactHandoff(n,t)}async runCompactHandoff(e,t=""){if(!e)return{status:"failed",message:"session_id is required"};if(this.compactingSessions.has(e))return{status:"failed",message:"compact already in progress"};if(this.activeBySession.has(e))return{status:"failed",message:"Cannot compact while a Cursor turn is active"};const n=this.sessionRuntime.get(e)??{},s=this.config.options??{},r=n.cursorSessionId??this.bindingStore?.getAcpSessionId(e)??null;if(!r)return{status:"failed",message:"No Cursor chat to compact (send a message first)"};this.compactingSessions.add(e);const i=String(n.cwd||s.workspace||process.cwd()),o=String(n.modelId||s.model||""),a=I(n.modeId||s.mode)??"full_auto",l=t.trim(),c=l?`${Q}
7
+ `)}class se extends N{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){h.warn("cursor-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}class D extends N{type="cursor";static STDERR_MAX_CHARS=8192;config;callbacks;alive=!1;stopped=!1;permissionHandler=null;internalApi=null;bindingStore=null;identity;inboundMessageIds=new me;inboundQueue=[];pendingBySession=new Map;sessions=new Set;sessionRuntime=new Map;sessionSeq=0;clientMsgSeq=0;lastUsageBySession=new Map;auditCaptures=new Map;completedAuditBoundaries=new Map;lastContextBySession=new Map;compactingSessions=new Set;pendingHandoffBySession=new Map;pendingQuestionByRequestId=new Map;pendingQuestionAnswerBySession=new Map;cachedAccountRateLimits=null;rateLimitsInflight=null;_availableModels=[];transcriptPathBySession=new Map;activeBySession=new Map;constructor(e,t){super(),this.config=e,this.callbacks=t;const n=e.options??{};this.bindingStore=n.bindingStore instanceof Se?n.bindingStore:null,this.identity=new de("cursor-adapter",t.getAgentProfile)}async start(){this.alive=!0,this.stopped=!1,(this.config.options??{}).mcp_tools!==!1&&(this.internalApi=new ue,this.internalApi.setInvokeHandler(async(t,n,s,i)=>this.callbacks.agentInvoke(t,n,i)),await this.internalApi.start()),this.notifyBindingReady(),this.refreshModels().then(()=>this.notifyBindingReady()).catch(()=>{}),this.refreshAccountRateLimits().then(()=>this.notifyBindingReady()).catch(()=>{})}get availableModels(){return this._availableModels}get availableModes(){return ee.map(e=>({...e}))}async refreshModels(){try{const e={...process.env,...this.config.env??{}},t=await ye({command:this.config.command,env:e,cwd:process.cwd()});t.length>0&&(this._availableModels=t,h.info("cursor-adapter",`Loaded ${t.length} available models`))}catch(e){h.warn("cursor-adapter",`Failed to refresh models: ${e instanceof Error?e.message:String(e)}`)}}async stop(){this.stopped=!0,this.alive=!1;for(const e of this.activeBySession.values())I(e.child,"SIGTERM");this.activeBySession.clear(),this.transcriptPathBySession.clear(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null)}isAlive(){return this.alive}async createSession(e){const t=`cursor-${Date.now()}-${++this.sessionSeq}`;return this.sessions.add(t),this.sessionRuntime.set(t,{cwd:typeof e.cwd=="string"?e.cwd:void 0,modelId:typeof e.modelId=="string"?e.modelId:void 0,modeId:typeof e.modeId=="string"?e.modeId:void 0}),t}async resumeSession(e,t){this.sessions.add(e);const n=this.sessionRuntime.get(e)??{};this.sessionRuntime.set(e,{...n,cwd:typeof t?.cwd=="string"?t.cwd:n.cwd,modelId:typeof t?.modelId=="string"?t.modelId:n.modelId,modeId:typeof t?.modeId=="string"?t.modeId:n.modeId})}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(e){this.sessions.delete(e),this.sessionRuntime.delete(e),this.transcriptPathBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e),this.pendingQuestionAnswerBySession.delete(e),this.pendingHandoffBySession.delete(e);for(const[t,n]of this.pendingQuestionByRequestId)n.sessionId===e&&this.pendingQuestionByRequestId.delete(t)}sendPrompt(e){const t=new se(e.adapterSessionId);if(!this.alive||this.stopped)return queueMicrotask(()=>t.emitError(new Error("adapter not running"))),t;const n=this.inboundQueue.shift()??{event_id:`cursor-evt-${Date.now()}`,session_id:e.adapterSessionId,content:e.text},s=e.adapterSessionId,i=this.pendingBySession.get(s)??[];return i.push({event:n,request:e,handle:t}),this.pendingBySession.set(s,i),this.tryStartNext(s),t}tryStartNext(e){if(this.compactingSessions.has(e)||this.activeBySession.has(e)||!this.alive||this.stopped)return;const t=this.pendingBySession.get(e);if(!t||t.length===0)return;const n=t.shift();t.length===0?this.pendingBySession.delete(e):this.pendingBySession.set(e,t),n&&this.startJob(n,!1,0)}startJob(e,t,n){const{event:s,request:i,handle:r}=e;s.audit?.enabled&&!this.auditCaptures.has(s.event_id)&&this.auditCaptures.set(s.event_id,[]);const o=i.adapterSessionId,a=this.sessionRuntime.get(i.adapterSessionId)??{},u=this.config.options??{},c=[...this.config.args??[]];c.push("-p","--output-format","stream-json"),u.trust!==!1&&c.push("--trust");const d=a.cwd||u.workspace;this.internalApi&&d&&(this.ensureWorkspaceMcpAndSkills(d),c.push("--approve-mcps")),d&&c.push("--workspace",d);const f=a.modelId||u.model;f&&c.push("--model",f);const A=x(a.modeId||u.mode)??"full_auto";A==="full_auto"?c.push("--yolo"):A==="plan"&&c.push("--plan");const _=a.cursorSessionId??this.bindingStore?.getAcpSessionId(i.adapterSessionId),b=!!(_&&u.use_continue!==!1&&!t);let m=b?void 0:0;if(b&&_){const p=this.transcriptPathBySession.get(o)??L(_);if(p){this.transcriptPathBySession.set(o,p);try{m=B(p).size}catch{this.transcriptPathBySession.delete(o)}}}b&&c.push("--resume",_),c.push(this.buildPromptText(i));const v={...process.env,...this.config.env??{}},S=P(this.config.command,v);h.info("cursor-adapter",`job start: event=${s.event_id} session=${s.session_id} retry=${n}`);let y;try{y=$(S.command,[...S.prefixArgs,...c],{cwd:d||process.cwd(),env:S.env,stdio:["ignore","pipe","pipe"]}).process}catch(p){this.finishActive(o,"failed",`spawn failed: ${p instanceof Error?p.message:String(p)}`);return}this.callbacks.sendEventAck(s.event_id,s.session_id),this.emit("eventStarted",s.event_id,s.session_id);const k=`cursor_${++this.clientMsgSeq}_${Date.now()}`,g={event:s,request:i,handle:r,child:y,seq:0,clientMsgIdBase:k,currentClientMsgId:k,segmentIndex:0,textSegmentInterrupted:!1,done:!1,stderr:"",timer:null,idleTimer:null,toolCallsInFlight:new Set,toolCallsStarted:0,assistantTextEmitted:"",streamBuffer:"",lastIoAt:Date.now(),sawResult:!1,transcriptBaseOffset:m,descendantBaseline:void 0,retryCount:n,usedContinue:b,workspace:d||process.cwd(),args:c};this.activeBySession.set(o,g),this.notifyBindingReady(o),this.armActiveIdleTimer(o);const R=i.timeoutMs&&i.timeoutMs>0?i.timeoutMs:0;R>0&&(g.timer=setTimeout(()=>{g.done||(I(y,"SIGTERM"),this.finishActive(o,"failed",`cursor agent timeout after ${R}ms`))},R)),F({input:y.stdout}).on("line",p=>this.handleStdoutLineForActive(g,p)),y.stderr?.on("data",p=>{if(g.done)return;const C=g.stderr+String(p??"");g.stderr=C.length>D.STDERR_MAX_CHARS?C.slice(-D.STDERR_MAX_CHARS):C,g.lastIoAt=Date.now(),this.armActiveIdleTimer(o)}),y.once("error",p=>{this.finishActive(o,"failed",`spawn failed: ${String(p?.message??p)}`)}),y.once("close",p=>{if(!g.done)if((p??0)===0)this.finishActive(o,"responded");else{if(this.shouldRetryWithoutContinue(g)){g.timer&&clearTimeout(g.timer),g.idleTimer&&clearTimeout(g.idleTimer),this.activeBySession.delete(o),this.startJob(e,!0,g.retryCount+1);return}const C=g.stderr.trim()||`cursor agent exited with code ${p??-1}`;this.finishActive(o,"failed",C)}})}async cancel(e){const t=this.activeBySession.get(e);t&&(I(t.child,"SIGTERM"),this.finishActive(e,"canceled","canceled"))}deliverInboundEvent(e){const t=String(e.session_id??"").trim();if(!t){h.warn("cursor-adapter",`Dropping event ${e.event_id}: missing session_id`),this.callbacks.sendEventResult(e.event_id,"failed","missing session_id");return}if(!this.alive||this.stopped){h.warn("cursor-adapter",`Dropping event ${e.event_id}: adapter not running`),this.callbacks.sendEventAck(e.event_id,t),this.callbacks.sendEventResult(e.event_id,"failed","adapter not running");return}const n={adapterSessionId:t,text:this.inboundMessageIds.inject(t,Pe(String(e.content??""),e),e.msg_id),contextMessages:$e(e)},s=new se(t),i=this.pendingBySession.get(t)??[];i.push({event:e,request:n,handle:s}),this.pendingBySession.set(t,i),h.info("cursor-adapter",`inbound queued: event=${e.event_id} session=${t} depth=${i.length}`),this.tryStartNext(t)}cancelSessionWork(e,t){const n=this.pendingBySession.get(e)??[];this.pendingBySession.delete(e);const s=this.activeBySession.get(e);s&&(this.killChildWithFallback(s.child),this.finishActive(e,"canceled",t));for(const i of n)this.callbacks.sendEventAck(i.event.event_id,i.event.session_id),this.callbacks.sendEventResult(i.event.event_id,"canceled",t),i.handle.emitDone({status:"canceled",error:t})}killChildWithFallback(e){I(e,"SIGTERM"),setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{I(e,"SIGKILL")}catch{}},5e3).unref()}deliverStopEvent(e,t){if(t){const n=this.activeBySession.get(t);if(n?.event.event_id===e){this.killChildWithFallback(n.child),this.finishActive(t,"canceled","stopped");return}const s=this.pendingBySession.get(t)??[],i=s.findIndex(r=>r.event.event_id===e);if(i>=0){const[r]=s.splice(i,1);s.length===0?this.pendingBySession.delete(t):this.pendingBySession.set(t,s),this.callbacks.sendEventAck(r.event.event_id,r.event.session_id),this.callbacks.sendEventResult(r.event.event_id,"canceled","stopped"),r.handle.emitDone({status:"canceled",error:"stopped"})}return}for(const[n,s]of this.activeBySession.entries())if(s.event.event_id===e){this.killChildWithFallback(s.child),this.finishActive(n,"canceled","stopped");return}for(const[n,s]of this.pendingBySession.entries()){const i=s.findIndex(o=>o.event.event_id===e);if(i<0)continue;const[r]=s.splice(i,1);s.length===0?this.pendingBySession.delete(n):this.pendingBySession.set(n,s),this.callbacks.sendEventAck(r.event.event_id,r.event.session_id),this.callbacks.sendEventResult(r.event.event_id,"canceled","stopped"),r.handle.emitDone({status:"canceled",error:"stopped"});return}}async handleLocalAction(e){const t=String(e.action_type??"").trim().toLowerCase(),n=e.params??{},s=String(n.session_id??"").trim(),i=e.action_id;if(t==="claude_interaction_reply")return String(n.kind??"").trim()==="permission"?(this.callbacks.sendLocalActionResult(i,"failed",void 0,"unsupported","Cursor adapter does not support interactive permission approvals"),{handled:!0,kind:"permission_unsupported"}):this.handleQuestionReply(e);switch(t){case"set_model":{const r=String(n.model_id??"").trim();if(!r||!s)return this.callbacks.sendLocalActionResult(i,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};const o=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...o,modelId:r}),this.notifyBindingReady(s);const a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(i,"ok",{outcome:"model_set",session_context:{model_id:r,mode_id:a.mode_id,modelId:r,modeId:a.mode_id},model_id:r,mode_id:a.mode_id,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"set_model"}}case"set_mode":{const r=x(n.mode_id);if(!r||!s)return this.callbacks.sendLocalActionResult(i,"failed",void 0,"invalid_params","mode_id must be approval, full_auto, or plan and session_id is required"),{handled:!0,kind:"set_mode"};const o=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...o,modeId:r}),this.notifyBindingReady(s);const a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(i,"ok",{outcome:"mode_set",session_context:{model_id:a.model_id,mode_id:r,modelId:a.model_id,modeId:r},model_id:a.model_id,mode_id:r,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"set_mode"}}case"get_context":{const r=s?this.sessionRuntime.get(s):void 0,o=this.config.options??{},a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(i,"ok",{session_context:{model_id:a.model_id,mode_id:a.mode_id,cwd:r?.cwd??o.workspace??null},model_id:a.model_id,mode_id:a.mode_id,modelId:a.model_id,modeId:a.mode_id,cwd:r?.cwd??o.workspace??null,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"get_context"}}case"get_rate_limits":{await this.refreshAccountRateLimits({force:!0});const r=this.getRateLimitsSnapshot(s||void 0);return this.callbacks.sendLocalActionResult(i,"ok",r),s&&this.notifyBindingReady(s),{handled:!0,kind:"get_rate_limits"}}case"get_session_usage":{const r=s?this.getUsageSnapshot(s):null;if(r){const o={inputTokens:r.total.input,outputTokens:r.total.output,cacheReadInputTokens:r.total.cacheRead,cacheCreationInputTokens:r.total.cacheWrite};this.callbacks.sendLocalActionResult(i,"ok",{sessionId:s,adapterType:"cursor",sampledAt:r.sampledAt,turns:r.turns,total:o,models:[{model:this.getToolbarMeta(s).model_id??"auto",turns:r.turns,total:o}]})}else this.callbacks.sendLocalActionResult(i,"failed",void 0,"usage_not_found","No usage data found for this session");return{handled:!0,kind:"get_session_usage"}}case"session_control":{const r=String(n.verb??"").trim().toLowerCase();if(r==="restart"&&s)this.cancelSessionWork(s,"restarted"),this.callbacks.sendLocalActionResult(i,"ok",{outcome:"restarted"});else if(r==="status"){const o=this.sessionRuntime.get(s),a=this.config.options??{},u=this.getToolbarMeta(s),c=this.activeBySession.has(s);this.callbacks.sendLocalActionResult(i,"ok",{verb:"status",status:c?"running":"idle",session_context:{model_id:u.model_id,mode_id:u.mode_id,cwd:o?.cwd??a.workspace??null},model_id:u.model_id,mode_id:u.mode_id,modelId:u.model_id,modeId:u.mode_id,cwd:o?.cwd??a.workspace??null,available_models:this.availableModels,available_modes:this.availableModes})}else this.callbacks.sendLocalActionResult(i,"failed",void 0,"invalid_verb",`Unsupported verb: ${r}`);return{handled:!0,kind:"session_control"}}default:return{handled:!1,kind:"unsupported"}}}getSupportedCommands(){return[{name:"compact",description:"\u538B\u7F29\u4E0A\u4E0B\u6587",args:"[instructions]"}]}async execCommand(e,t,n){return e!=="compact"?{status:"unsupported",message:`Unsupported command: ${e}`}:this.runCompactHandoff(n,t)}async runCompactHandoff(e,t=""){if(!e)return{status:"failed",message:"session_id is required"};if(this.compactingSessions.has(e))return{status:"failed",message:"compact already in progress"};if(this.activeBySession.has(e))return{status:"failed",message:"Cannot compact while a Cursor turn is active"};const n=this.sessionRuntime.get(e)??{},s=this.config.options??{},i=n.cursorSessionId??this.bindingStore?.getAcpSessionId(e)??null;if(!i)return{status:"failed",message:"No Cursor chat to compact (send a message first)"};this.compactingSessions.add(e);const r=String(n.cwd||s.workspace||process.cwd()),o=String(n.modelId||s.model||""),a=x(n.modeId||s.mode)??"full_auto",u=t.trim(),c=u?`${H}
7
8
 
8
9
  Additional focus from user:
9
- ${l}`:Q;this.emit("pauseIntake","compaction"),u.info("cursor-adapter",`[compact] summarize resume=${r} session=${e}`);try{const h=await this.runPrintOnce({prompt:c,resumeChatId:r,cwd:i,modelId:o||void 0,modeId:a,timeoutMs:U});if(!h.ok||!h.text.trim())return{status:"failed",message:h.error??"Summarize failed (empty result)"};const p=await this.createEmptyChat();return p?(this.sessionRuntime.set(e,{...n,cwd:i,modelId:o||n.modelId,modeId:a,cursorSessionId:p}),this.transcriptPathBySession.delete(e),this.bindingStore?.setAcpSessionId(e,p),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e),this.pendingHandoffBySession.set(e,h.text.trim()),this.lastContextBySession.set(e,ye(0,_e(o))),this.notifyBindingReady(e),u.info("cursor-adapter",`[compact] handoff ready: old=${r} new=${p} summaryChars=${h.text.trim().length}`),{status:"ok",message:"Context compacted via summarize + new chat",data:{previousChatId:r,chatId:p}}):{status:"failed",message:"agent create-chat failed"}}finally{this.compactingSessions.delete(e),this.emit("resumeIntake","compaction")}}shouldAutoCompact(e){return(this.lastContextBySession.get(e)?.usedPercentage??0)>=W}runPrintOnce(e){const t={...process.env,...this.config.env??{}},n=x(this.config.command,t),s=[...n.prefixArgs,...this.config.args??[]];s.push("-p","--output-format","stream-json"),this.config.options?.trust!==!1&&s.push("--trust"),e.cwd&&s.push("--workspace",e.cwd),e.modelId&&s.push("--model",e.modelId);const r=I(e.modeId)??"full_auto";return r==="full_auto"?s.push("--yolo"):r==="plan"&&s.push("--plan"),e.resumeChatId&&s.push("--resume",e.resumeChatId),s.push(e.prompt),new Promise(i=>{let o;try{o=B(n.command,s,{cwd:e.cwd||process.cwd(),env:n.env,stdio:["ignore","pipe","pipe"]}).process}catch(m){i({ok:!1,text:"",error:`spawn failed: ${m instanceof Error?m.message:String(m)}`});return}let a="",l="",c="",h=!1;const p=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:U,_=setTimeout(()=>{h||(h=!0,this.killChildWithFallback(o),i({ok:!1,text:a,sessionId:l||void 0,error:`compact timeout after ${p}ms`}))},p);_.unref?.();const v=(m,g)=>{h||(h=!0,clearTimeout(_),i({ok:m,text:a,sessionId:l||void 0,error:g}))};E({input:o.stdout}).on("line",m=>{const g=m.trim();if(!g)return;let S;try{S=JSON.parse(g)}catch{return}if(S?.type!=="result")return;const f=typeof S?.result=="string"?S.result:"";f&&(a=f);const w=String(S?.session_id??"").trim();w&&(l=w)}),o.stderr?.on("data",m=>{c+=typeof m=="string"?m:m.toString("utf8")}),o.on("error",m=>v(!1,m.message)),o.on("close",m=>{if(!h){if(a.trim()){v(!0);return}v(!1,c.trim()||`cursor agent exited with code ${m??"unknown"}`)}})})}createEmptyChat(){const e={...process.env,...this.config.env??{}},t=x(this.config.command,e);return new Promise(n=>{let s;try{s=B(t.command,[...t.prefixArgs,"create-chat"],{cwd:process.cwd(),env:t.env,stdio:["ignore","pipe","pipe"]}).process}catch{n(null);return}let r="",i=!1;const o=setTimeout(()=>{i||(i=!0,this.killChildWithFallback(s),n(null))},3e4);o.unref?.(),s.stdout?.on("data",a=>{r+=typeof a=="string"?a:a.toString("utf8")}),s.on("error",()=>{i||(i=!0,clearTimeout(o),n(null))}),s.on("close",a=>{if(i)return;i=!0,clearTimeout(o);const l=r.trim().split(/\s+/)[0]??"";n(a===0&&/^[0-9a-f-]{16,}$/i.test(l)?l:null)})})}setPermissionHandler(e){this.permissionHandler=e}async ping(e){if(!this.alive||this.stopped||(this.config.options??{}).mcp_tools!==!1&&this.internalApi===null)return!1;for(const n of this.activeBySession.values()){const s=n.child?.pid;if(s&&!T(s))return!1}return!0}getStatus(){let e=0;for(const t of this.pendingBySession.values())e+=t.length;return{alive:this.alive,busy:this.activeBySession.size>0,sessions:this.sessions.size,details:{queueDepth:e+this.inboundQueue.length,activeSessions:this.activeBySession.size}}}getActiveEventIds(){const e=[];for(const t of this.activeBySession.values())t.event.event_id&&e.push(t.event.event_id);return e}clearActiveEventForShutdown(){for(const[e,t]of this.activeBySession)this.snapshotAuditBoundary(t.event.event_id,e);this.activeBySession.clear()}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}getMcpConfig(){return null}async probe(e){const t=this.getStatus();return{...await ae(this.config.command||"cursor-agent",{alive:t.alive,busy:t.busy,started:this.alive},e),session:this.probeSessionRecord()}}probeSessionRecord(){const e=this.firstKnownCursorSessionId(),t=e?Y(e):null;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const n=N(t);return{recordPath:t,lastActivityMs:n.mtimeMs,freshMs:Date.now()-n.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}firstKnownCursorSessionId(){for(const e of this.activeBySession.keys()){const t=this.sessionRuntime.get(e);if(t?.cursorSessionId)return t.cursorSessionId}for(const e of this.sessionRuntime.values())if(e.cursorSessionId)return e.cursorSessionId;return null}getUsageSnapshot(e){return this.lastUsageBySession.get(e)??null}getRateLimitsSnapshot(e){const t=this.cachedAccountRateLimits,n=e?this.lastContextBySession.get(e)??null:null;if(!t)return{adapterType:"cursor",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:n,tokenUsage:null};const s=Date.parse(t.sampledAt),r=t.rateLimits?.usagePeriod??t.usagePeriod;return{adapterType:"cursor",available:t.available&&!!t.rateLimits,cached:!0,sampledAt:Number.isFinite(s)?s:Date.now(),rateLimits:t.rateLimits,...r?{usagePeriod:r}:{},contextWindow:n,tokenUsage:null,...t.displayMessage?{displayMessage:t.displayMessage}:{},...t.error?{error:t.error}:{}}}async refreshAccountRateLimits(e){const t=e?.force===!0,n=this.cachedAccountRateLimits,s=n?Date.now()-Date.parse(n.sampledAt):Number.POSITIVE_INFINITY;if(!t&&n&&Number.isFinite(s)&&s<6e4||this.rateLimitsInflight&&(await this.rateLimitsInflight,!t))return;const r=(async()=>{const i=await Se();if(this.cachedAccountRateLimits={available:i.available,sampledAt:i.sampledAt,rateLimits:i.rateLimits,usagePeriod:i.usagePeriod??i.rateLimits?.usagePeriod,displayMessage:i.displayMessage,error:i.error},i.available&&i.rateLimits){const o=i.rateLimits.usagePeriod;u.info("cursor-adapter",`[rate-limits] period=${o} total=${i.rateLimits.fiveHour.usedPercentage.toFixed(1)}% api=${i.rateLimits.sevenDay.usedPercentage.toFixed(1)}% resetsAt=${i.rateLimits.fiveHour.resetsAt}`+(i.displayMessage?` msg=${i.displayMessage}`:""))}else u.warn("cursor-adapter",`[rate-limits] unavailable: ${i.error??"unknown"}`)})();this.rateLimitsInflight=r.finally(()=>{this.rateLimitsInflight=null}),await this.rateLimitsInflight}getToolbarMeta(e){const t=this.config.options??{},n=e||String(t.aibotSessionId??""),s=n?this.sessionRuntime.get(n):void 0,r=String(s?.modelId||t.model||"auto"),i=I(s?.modeId||t.mode)??"full_auto",o={model_id:r,mode_id:i,currentModelId:r,currentModeId:i,available_models:this.availableModels,available_modes:this.availableModes},a=this.cachedAccountRateLimits?.rateLimits;if(a?.fiveHour||a?.sevenDay){const c=Date.parse(this.cachedAccountRateLimits?.sampledAt??"")||Date.now();o.rate_limits={...a.fiveHour?{fiveHour:a.fiveHour}:{},...a.sevenDay?{sevenDay:a.sevenDay}:{},usagePeriod:a.usagePeriod,sampledAt:c}}const l=n?this.lastContextBySession.get(n):void 0;return l&&(o.context_window={usedPercentage:l.usedPercentage,remainingPercentage:l.remainingPercentage,usedTokens:l.usedTokens,sizeTokens:l.sizeTokens}),o}notifyBindingReady(e){if(!this.callbacks.sendUpdateBindingCard)return;const t=this.config.options??{},n=e||String(t.aibotSessionId??"");if(!n)return;const s=this.sessionRuntime.get(n),r=String(s?.cwd||t.workspace||"");r&&this.callbacks.sendUpdateBindingCard(n,this.activeBySession.has(n)?"busy":"ready",r,this.getToolbarMeta(n))}buildPromptText(e){let t;if(!e.contextMessages||e.contextMessages.length===0)t=e.text;else{const r=e.contextMessages.map(i=>`[${i.senderId}] ${i.content}`).join(`
10
- `);t=R(e.text,`[Conversation context]
11
- ${r}`)}const n=this.pendingQuestionAnswerBySession.get(e.adapterSessionId);n&&(this.pendingQuestionAnswerBySession.delete(e.adapterSessionId),t=R(t,`[User answered a previous agent question]
12
- ${n}`));const s=this.pendingHandoffBySession.get(e.adapterSessionId);return s&&(this.pendingHandoffBySession.delete(e.adapterSessionId),t=R(t,`[Previous conversation summary \u2014 continue from this handoff]
13
- ${s}`)),this.identity.injectOnce(e.adapterSessionId,t)}handleStdoutLineForActive(e,t){if(e.done)return;const n=t.trim();if(!n)return;e.lastIoAt=Date.now();const{event:s}=e;let r;try{r=JSON.parse(n)}catch{this.armActiveIdleTimer(e.request.adapterSessionId);return}this.rememberCursorChatId(e.request.adapterSessionId,r?.session_id);const i=this.auditCaptures.get(s.event_id);if(i&&r&&typeof r=="object"&&i.push({sequence:i.length,observedAt:new Date().toISOString(),event:structuredClone(r)}),r?.type==="tool_call"){const l=String(r?.call_id??""),c=String(r?.subtype??"");l&&(c==="started"||c==="start"?(this.flushAssistantStreamBuffer(e),e.descendantBaseline===void 0&&this.captureDescendantBaseline(e),e.toolCallsInFlight.add(l),e.toolCallsStarted+=1,this.handleSpecialToolCallStarted(e,r)):H.has(c)&&e.toolCallsInFlight.delete(l))}this.armActiveIdleTimer(e.request.adapterSessionId);const o=Re(r);o&&this.callbacks.sendRawEventEnvelope?.(s.event_id,s.session_id,o);const a=Be(r,e.assistantTextEmitted);if(a&&this.enqueueAssistantStreamDelta(e,a),r?.type==="result"){e.sawResult=!0;const l=typeof r?.result=="string"?r.result.trim():"";l&&(e.assistantTextEmitted?l.startsWith(e.assistantTextEmitted)&&l.length>e.assistantTextEmitted.length&&this.enqueueAssistantStreamDelta(e,l.slice(e.assistantTextEmitted.length)):this.enqueueAssistantStreamDelta(e,l)),this.flushAssistantStreamBuffer(e);const c=r?.usage??{},h=this.lastUsageBySession.get(e.request.adapterSessionId);this.lastUsageBySession.set(e.request.adapterSessionId,{sampledAt:new Date().toISOString(),turns:(h?.turns??0)+1,total:{input:(h?.total.input??0)+Number(c.inputTokens??0),output:(h?.total.output??0)+Number(c.outputTokens??0),cacheRead:(h?.total.cacheRead??0)+Number(c.cacheReadTokens??0),cacheWrite:(h?.total.cacheWrite??0)+Number(c.cacheWriteTokens??0)}});const p=String((this.sessionRuntime.get(e.request.adapterSessionId)?.modelId??this.config.options?.model??"")||""),_=Math.max(1,(e.toolCallsStarted??0)+1),v=Number(c.inputTokens??0),b=Number(c.cacheReadTokens??0),m=Number(c.cacheWriteTokens??0),g=ve({inputTokens:v,cacheReadTokens:b,cacheWriteTokens:m},p,{apiRounds:_});g&&(this.lastContextBySession.set(e.request.adapterSessionId,g),u.info("cursor-adapter",`[context_window] used=${g.usedTokens} size=${g.sizeTokens} pct=${g.usedPercentage.toFixed(1)}% model=${p||"auto"} rawIn=${v} rawCache=${b} rawWrite=${m} apiRounds=${_}`))}}handleSpecialToolCallStarted(e,t){const n=z(t);if(X(n.toolName)){const s=Ie(n.toolInput);s?(e.seq+=1,this.callbacks.sendStreamChunk(e.event.event_id,e.event.session_id,s,e.seq,!1),u.info("cursor-adapter",`CreatePlan forwarded as stream text: event=${e.event.event_id} chars=${s.length}`)):(e.seq+=1,this.callbacks.sendStreamChunk(e.event.event_id,e.event.session_id,"[CreatePlan] \u65B9\u6848\u5185\u5BB9\u89E3\u6790\u5931\u8D25\uFF0C\u672A\u4E0B\u53D1\u6B63\u6587\u3002",e.seq,!1),u.warn("cursor-adapter",`CreatePlan missing plan body: event=${e.event.event_id}`));return}G(n.toolName)&&this.emitAskQuestionCard(e,n.toolInput)}emitAskQuestionCard(e,t){const n=e.event,s=Ce(t);if(!s){e.seq+=1,this.callbacks.sendStreamChunk(n.event_id,n.session_id,"[AskQuestion] \u95EE\u9898\u5185\u5BB9\u89E3\u6790\u5931\u8D25\uFF0C\u672A\u4E0B\u53D1\u95EE\u9898\u5361\u3002",e.seq,!1),u.warn("cursor-adapter",`AskQuestion parse failed: event=${n.event_id}`);return}if(!this.callbacks.sendAgentQuestionCard){u.warn("cursor-adapter","AskQuestion skipped: sendAgentQuestionCard callback not wired");return}const r=te(),i=Date.now();this.pendingQuestionByRequestId.set(r,{eventId:n.event_id,sessionId:n.session_id,createdAt:i}),this.callbacks.sendAgentQuestionCard(n.event_id,n.session_id,{request_id:r,mode:"form",questions:s,expires_at:i+M}),u.info("cursor-adapter",`Sent agent_question card: request_id=${r} questions=${s.length} event=${n.event_id}`)}async handleQuestionReply(e){const t=e.params??{},n=String(t.request_id??"").trim();if(!n)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"request_id_required","request_id is required"),{handled:!0,kind:"question_reply_no_id"};const s=this.pendingQuestionByRequestId.get(n),r=s?Date.now()-s.createdAt>M+3e4:!0;if(!s||r)return this.pendingQuestionByRequestId.delete(n),this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"interaction_request_not_pending","The question is no longer pending; the reply was not delivered."),{handled:!0,kind:"question_reply_not_pending"};const i=t.resolution??{},o=String(i.type??"");if(o==="action"&&String(i.value??"")==="cancel")return this.pendingQuestionByRequestId.delete(n),this.callbacks.sendLocalActionResult(e.action_id,"ok",{request_id:n,resolution:"cancel"}),{handled:!0,kind:"question_reply_cancel"};let a="";return o==="text"?a=String(i.value??""):o==="map"&&(a=(Array.isArray(i.entries)?i.entries:[]).map(c=>c.value).join(", ")),a?(this.pendingQuestionByRequestId.delete(n),this.pendingQuestionAnswerBySession.set(s.sessionId,a),this.callbacks.sendLocalActionResult(e.action_id,"ok",{request_id:n,resolution:"answer"}),u.info("cursor-adapter",`Question reply cached for next prompt: request_id=${n} session=${s.sessionId}`),{handled:!0,kind:"question_reply"}):(this.pendingQuestionByRequestId.delete(n),this.callbacks.sendLocalActionResult(e.action_id,"ok",{request_id:n,resolution:"cancel"}),{handled:!0,kind:"question_reply_empty"})}enqueueAssistantStreamDelta(e,t){t&&(e.assistantTextEmitted+=t,e.streamBuffer+=t,e.streamBuffer.length>=be&&this.flushAssistantStreamBuffer(e))}flushAssistantStreamBuffer(e){if(!e.streamBuffer)return;const t=e.streamBuffer;e.streamBuffer="",e.seq+=1,this.callbacks.sendStreamChunk(e.event.event_id,e.event.session_id,t,e.seq,!1,void 0,void 0)}captureDescendantBaseline(e){const t=e.child?.pid;if(!t){e.descendantBaseline=null;return}try{e.descendantBaseline=new Set(fe(t)),u.info("cursor-adapter",`Liveness baseline captured for ${e.event.event_id}: ${e.descendantBaseline.size} resident descendant(s)`)}catch{e.descendantBaseline=null,u.warn("cursor-adapter",`Liveness baseline capture failed for ${e.event.event_id}; tool-descendant extend disabled`)}}shouldExtendByLiveness(e){const t=this.activeBySession.get(e);if(!t||t.done)return!1;const n=t.child?.pid;if(!n||!T(n)||t.sawResult)return!1;if(t.toolCallsInFlight.size>0&&t.descendantBaseline instanceof Set){let h=0;try{h=me(n,t.descendantBaseline)}catch{h=0}if(h>0)return t.livenessExtendStartAt=void 0,u.info("cursor-adapter",`Liveness check: tool descendants for ${t.event.event_id} (descendants=${h}, toolsInFlight=${t.toolCallsInFlight.size}), extending without budget`),!0}const s=Date.now(),r=s-t.lastIoAt,i=this.transcriptFreshMsForSession(e);if(r<j||i!==null&&i<j)return t.livenessExtendStartAt=s,u.info("cursor-adapter",`Liveness check: fresh progress for ${t.event.event_id} (ioAge=${r}ms, transcriptAge=${i??"n/a"}, toolsInFlight=${t.toolCallsInFlight.size}), extending`),!0;const a=i===null?0:s-i,l=Math.max(t.lastIoAt,a);t.livenessExtendStartAt===void 0?t.livenessExtendStartAt=s:l>t.livenessExtendStartAt&&(t.livenessExtendStartAt=l);const c=t.livenessExtendStartAt??s;return s-c>O?(u.warn("cursor-adapter",`Liveness extension budget exhausted for ${t.event.event_id} (no progress for ${Math.round((s-c)/6e4)}min), allowing idle kill`),!1):(u.info("cursor-adapter",`Liveness check: turn in progress for ${t.event.event_id} (toolsInFlight=${t.toolCallsInFlight.size}, ioAge=${r}ms), extending`),!0)}rememberCursorChatId(e,t){const n=String(t??"").trim();if(!n)return;const s=this.sessionRuntime.get(e)??{};s.cursorSessionId!==n&&this.transcriptPathBySession.delete(e),this.sessionRuntime.set(e,{...s,cursorSessionId:n}),this.bindingStore?.setAcpSessionId(e,n)}transcriptFreshMsForSession(e){const t=this.sessionRuntime.get(e)?.cursorSessionId;if(!t)return null;let n=this.transcriptPathBySession.get(e);if(!n){const s=Y(t);if(!s)return null;this.transcriptPathBySession.set(e,s),n=s}try{return Date.now()-N(n).mtimeMs}catch{return this.transcriptPathBySession.delete(e),null}}hasPendingQuestionForSession(e){const t=Date.now();for(const[n,s]of this.pendingQuestionByRequestId)if(s.sessionId===e){if(t-s.createdAt>M){this.pendingQuestionByRequestId.delete(n);continue}return!0}return!1}armActiveIdleTimer(e){const t=this.activeBySession.get(e);!t||t.done||(t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{if(t.done)return;if(this.hasPendingQuestionForSession(e)){u.info("cursor-adapter",`Idle timeout skipped: awaiting AskQuestion for ${t.event.event_id}, resetting timer`),this.armActiveIdleTimer(e);return}if(this.shouldExtendByLiveness(e)){this.armActiveIdleTimer(e);return}if(t.sawResult){u.warn("cursor-adapter",`Idle after result with no close \u2014 finishing as responded: event=${t.event.event_id} session=${e}`),this.killChildWithFallback(t.child),this.finishActive(e,"responded");return}const n=t.child?.pid,r=!!(n&&T(n))?`liveness budget exhausted after ${O/6e4}min`:"child process dead";u.error("cursor-adapter",`Idle timeout (${r}, toolsInFlight=${t.toolCallsInFlight.size}) \u2014 killing cursor child: event=${t.event.event_id} session=${e}`),this.killChildWithFallback(t.child),this.finishActive(e,"failed",`idle timeout: ${r}`)},Ae),t.idleTimer.unref?.())}finishActive(e,t,n){const s=this.activeBySession.get(e);if(!s)return;s.done=!0,s.timer&&clearTimeout(s.timer),s.idleTimer&&clearTimeout(s.idleTimer),this.flushAssistantStreamBuffer(s),s.seq+=1;const r=String(s.event.quoted_message_id??"").trim()||void 0;if(this.callbacks.sendStreamChunk(s.event.event_id,s.event.session_id,"",s.seq,!0,void 0,r),u.info("cursor-adapter",`job finish: event=${s.event.event_id} session=${s.event.session_id} status=${t}${n?` msg=${n}`:""}`),this.snapshotAuditBoundary(s.event.event_id,e),this.emit("eventDone",s.event.event_id),this.callbacks.sendEventResult(s.event.event_id,t,n),t==="responded"?s.handle.emitDone({status:"completed"}):t==="canceled"?s.handle.emitDone({status:"canceled",error:n}):s.handle.emitDone({status:"failed",error:n}),this.activeBySession.delete(e),this.notifyBindingReady(e),t==="responded"&&this.shouldAutoCompact(e)){const i=this.lastContextBySession.get(e)?.usedPercentage??0;u.info("cursor-adapter",`[auto-compact] context_window usedPercentage=${i.toFixed(1)}% >= ${W}%, scheduling compact session=${e}`),this.runCompactHandoff(e).finally(()=>{this.tryStartNext(e)});return}this.tryStartNext(e)}snapshotAuditBoundary(e,t){const n=this.auditCaptures.get(e);if(!n)return;const s=this.sessionRuntime.get(t);this.completedAuditBoundaries.set(e,{adapterType:"cursor",providerSessionId:s?.cursorSessionId,cursorEvidence:{events:n}}),this.auditCaptures.delete(e)}shouldRetryWithoutContinue(e){if(!e.usedContinue||e.retryCount>0)return!1;const t=e.stderr.toLowerCase(),n=t.includes("resume")||t.includes("continue")||t.includes("chat")||t.includes("session"),s=t.includes("not found")||t.includes("no previous session")||t.includes("does not exist")||t.includes("invalid");return n&&s}ensureWorkspaceMcpAndSkills(e){if(!this.internalApi)return;this.ensureCursorMcpConfig(e,this.internalApi.url);const t=A(F(),".cursor","skills"),n=he(t);n.length>0&&u.info("cursor-adapter",`Synced connector skills to ${t}: [${n.join(", ")}]`)}ensureCursorMcpConfig(e,t){const n=le(this.callbacks.getAgentId?.()),s={command:process.execPath,args:[ne(ie(import.meta.url),"../../../mcp/acp-mcp-server.js"),"--api-url",t]},r=[e],i=this.resolveGitRoot(e);i&&i!==e&&r.push(i);let o=null;for(const a of r){const l=this.writeCursorMcpConfig(a,n,s,t);!o&&l&&(o=l)}o&&this.recordCursorMcpRegistry(e,o,s)}resolveGitRoot(e){try{return ee("git",["-C",e,"rev-parse","--show-toplevel"],{timeout:5e3,stdio:["ignore","pipe","ignore"],windowsHide:!0}).toString("utf8").trim()||null}catch{return null}}writeCursorMcpConfig(e,t,n,s){try{const r=A(e,".cursor"),i=A(r,"mcp.json");P(r,{recursive:!0});let o={};try{o=JSON.parse(q(i,"utf8"))}catch{o={}}(!o.mcpServers||typeof o.mcpServers!="object")&&(o.mcpServers={});const a=ce(o.mcpServers,s);return o.mcpServers[t]=n,D(i,`${JSON.stringify(o,null,2)}
14
- `,"utf8"),u.info("cursor-adapter",`MCP config synced: dir=${e} file=${i} server=${t}${a.length>0?` pruned=${a.join(",")}`:""}`),i}catch(r){return u.warn("cursor-adapter",`Failed to ensure ${A(e,".cursor","mcp.json")}: ${String(r)}`),null}}recordCursorMcpRegistry(e,t,n){try{const s=A(re.data,"cursor"),r=A(s,"mcp-registry.json");P(s,{recursive:!0});let i={};try{i=JSON.parse(q(r,"utf8"))}catch{i={}}i[e]={mcp_path:t,server:n,updated_at:new Date().toISOString()},D(r,`${JSON.stringify(i,null,2)}
15
- `,"utf8")}catch(s){u.warn("cursor-adapter",`Failed to record MCP registry: ${String(s)}`)}}}export{K as CURSOR_MODE_OPTIONS,$ as CursorAdapter,Be as extractCursorAssistantStreamDelta,Y as findCursorTranscript,Ie as formatCursorCreatePlanText,G as isCursorAskQuestionTool,X as isCursorCreatePlanTool,Re as mapCursorStreamJsonToRawEnvelope,Ce as parseCursorAskQuestionPayload};
10
+ ${u}`:H;this.emit("pauseIntake","compaction"),h.info("cursor-adapter",`[compact] summarize resume=${i} session=${e}`);try{const d=await this.runPrintOnce({prompt:c,resumeChatId:i,cwd:r,modelId:o||void 0,modeId:a,timeoutMs:J});if(!d.ok||!d.text.trim())return{status:"failed",message:d.error??"Summarize failed (empty result)"};const f=await this.createEmptyChat();return f?(this.sessionRuntime.set(e,{...n,cwd:r,modelId:o||n.modelId,modeId:a,cursorSessionId:f}),this.transcriptPathBySession.delete(e),this.bindingStore?.setAcpSessionId(e,f),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e),this.pendingHandoffBySession.set(e,d.text.trim()),this.lastContextBySession.set(e,ve(0,be(o))),this.notifyBindingReady(e),h.info("cursor-adapter",`[compact] handoff ready: old=${i} new=${f} summaryChars=${d.text.trim().length}`),{status:"ok",message:"Context compacted via summarize + new chat",data:{previousChatId:i,chatId:f}}):{status:"failed",message:"agent create-chat failed"}}finally{this.compactingSessions.delete(e),this.emit("resumeIntake","compaction")}}shouldAutoCompact(e){return(this.lastContextBySession.get(e)?.usedPercentage??0)>=G}runPrintOnce(e){const t={...process.env,...this.config.env??{}},n=P(this.config.command,t),s=[...n.prefixArgs,...this.config.args??[]];s.push("-p","--output-format","stream-json"),this.config.options?.trust!==!1&&s.push("--trust"),e.cwd&&s.push("--workspace",e.cwd),e.modelId&&s.push("--model",e.modelId);const i=x(e.modeId)??"full_auto";return i==="full_auto"?s.push("--yolo"):i==="plan"&&s.push("--plan"),e.resumeChatId&&s.push("--resume",e.resumeChatId),s.push(e.prompt),new Promise(r=>{let o;try{o=$(n.command,s,{cwd:e.cwd||process.cwd(),env:n.env,stdio:["ignore","pipe","pipe"]}).process}catch(m){r({ok:!1,text:"",error:`spawn failed: ${m instanceof Error?m.message:String(m)}`});return}let a="",u="",c="",d=!1;const f=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:J,A=setTimeout(()=>{d||(d=!0,this.killChildWithFallback(o),r({ok:!1,text:a,sessionId:u||void 0,error:`compact timeout after ${f}ms`}))},f);A.unref?.();const _=(m,v)=>{d||(d=!0,clearTimeout(A),r({ok:m,text:a,sessionId:u||void 0,error:v}))};F({input:o.stdout}).on("line",m=>{const v=m.trim();if(!v)return;let S;try{S=JSON.parse(v)}catch{return}if(S?.type!=="result")return;const y=typeof S?.result=="string"?S.result:"";y&&(a=y);const k=String(S?.session_id??"").trim();k&&(u=k)}),o.stderr?.on("data",m=>{c+=typeof m=="string"?m:m.toString("utf8")}),o.on("error",m=>_(!1,m.message)),o.on("close",m=>{if(!d){if(a.trim()){_(!0);return}_(!1,c.trim()||`cursor agent exited with code ${m??"unknown"}`)}})})}createEmptyChat(){const e={...process.env,...this.config.env??{}},t=P(this.config.command,e);return new Promise(n=>{let s;try{s=$(t.command,[...t.prefixArgs,"create-chat"],{cwd:process.cwd(),env:t.env,stdio:["ignore","pipe","pipe"]}).process}catch{n(null);return}let i="",r=!1;const o=setTimeout(()=>{r||(r=!0,this.killChildWithFallback(s),n(null))},3e4);o.unref?.(),s.stdout?.on("data",a=>{i+=typeof a=="string"?a:a.toString("utf8")}),s.on("error",()=>{r||(r=!0,clearTimeout(o),n(null))}),s.on("close",a=>{if(r)return;r=!0,clearTimeout(o);const u=i.trim().split(/\s+/)[0]??"";n(a===0&&/^[0-9a-f-]{16,}$/i.test(u)?u:null)})})}setPermissionHandler(e){this.permissionHandler=e}async ping(e){if(!this.alive||this.stopped||(this.config.options??{}).mcp_tools!==!1&&this.internalApi===null)return!1;for(const n of this.activeBySession.values()){const s=n.child?.pid;if(s&&!E(s))return!1}return!0}getStatus(){let e=0;for(const t of this.pendingBySession.values())e+=t.length;return{alive:this.alive,busy:this.activeBySession.size>0,sessions:this.sessions.size,details:{queueDepth:e+this.inboundQueue.length,activeSessions:this.activeBySession.size}}}getActiveEventIds(){const e=[];for(const t of this.activeBySession.values())t.event.event_id&&e.push(t.event.event_id);return e}clearActiveEventForShutdown(){for(const[e,t]of this.activeBySession)this.snapshotAuditBoundary(t.event.event_id,e);this.activeBySession.clear()}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}getMcpConfig(){return null}async probe(e){const t=this.getStatus();return{...await ce(this.config.command||"cursor-agent",{alive:t.alive,busy:t.busy,started:this.alive},e),session:this.probeSessionRecord()}}probeSessionRecord(){const e=this.firstKnownCursorSessionId(),t=e?L(e):null;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const n=B(t);return{recordPath:t,lastActivityMs:n.mtimeMs,freshMs:Date.now()-n.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}firstKnownCursorSessionId(){for(const e of this.activeBySession.keys()){const t=this.sessionRuntime.get(e);if(t?.cursorSessionId)return t.cursorSessionId}for(const e of this.sessionRuntime.values())if(e.cursorSessionId)return e.cursorSessionId;return null}getUsageSnapshot(e){return this.lastUsageBySession.get(e)??null}getRateLimitsSnapshot(e){const t=this.cachedAccountRateLimits,n=e?this.lastContextBySession.get(e)??null:null;if(!t)return{adapterType:"cursor",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:n,tokenUsage:null};const s=Date.parse(t.sampledAt),i=t.rateLimits?.usagePeriod??t.usagePeriod;return{adapterType:"cursor",available:t.available&&!!t.rateLimits,cached:!0,sampledAt:Number.isFinite(s)?s:Date.now(),rateLimits:t.rateLimits,...i?{usagePeriod:i}:{},contextWindow:n,tokenUsage:null,...t.displayMessage?{displayMessage:t.displayMessage}:{},...t.error?{error:t.error}:{}}}async refreshAccountRateLimits(e){const t=e?.force===!0,n=this.cachedAccountRateLimits,s=n?Date.now()-Date.parse(n.sampledAt):Number.POSITIVE_INFINITY;if(!t&&n&&Number.isFinite(s)&&s<6e4||this.rateLimitsInflight&&(await this.rateLimitsInflight,!t))return;const i=(async()=>{const r=await _e();if(this.cachedAccountRateLimits={available:r.available,sampledAt:r.sampledAt,rateLimits:r.rateLimits,usagePeriod:r.usagePeriod??r.rateLimits?.usagePeriod,displayMessage:r.displayMessage,error:r.error},r.available&&r.rateLimits){const o=r.rateLimits.usagePeriod;h.info("cursor-adapter",`[rate-limits] period=${o} total=${r.rateLimits.fiveHour.usedPercentage.toFixed(1)}% api=${r.rateLimits.sevenDay.usedPercentage.toFixed(1)}% resetsAt=${r.rateLimits.fiveHour.resetsAt}`+(r.displayMessage?` msg=${r.displayMessage}`:""))}else h.warn("cursor-adapter",`[rate-limits] unavailable: ${r.error??"unknown"}`)})();this.rateLimitsInflight=i.finally(()=>{this.rateLimitsInflight=null}),await this.rateLimitsInflight}getToolbarMeta(e){const t=this.config.options??{},n=e||String(t.aibotSessionId??""),s=n?this.sessionRuntime.get(n):void 0,i=String(s?.modelId||t.model||"auto"),r=x(s?.modeId||t.mode)??"full_auto",o={model_id:i,mode_id:r,currentModelId:i,currentModeId:r,available_models:this.availableModels,available_modes:this.availableModes},a=this.cachedAccountRateLimits?.rateLimits;if(a?.fiveHour||a?.sevenDay){const c=Date.parse(this.cachedAccountRateLimits?.sampledAt??"")||Date.now();o.rate_limits={...a.fiveHour?{fiveHour:a.fiveHour}:{},...a.sevenDay?{sevenDay:a.sevenDay}:{},usagePeriod:a.usagePeriod,sampledAt:c}}const u=n?this.lastContextBySession.get(n):void 0;return u&&(o.context_window={usedPercentage:u.usedPercentage,remainingPercentage:u.remainingPercentage,usedTokens:u.usedTokens,sizeTokens:u.sizeTokens}),o}notifyBindingReady(e){if(!this.callbacks.sendUpdateBindingCard)return;const t=this.config.options??{},n=e||String(t.aibotSessionId??"");if(!n)return;const s=this.sessionRuntime.get(n),i=String(s?.cwd||t.workspace||"");i&&this.callbacks.sendUpdateBindingCard(n,this.activeBySession.has(n)?"busy":"ready",i,this.getToolbarMeta(n))}buildPromptText(e){let t;if(!e.contextMessages||e.contextMessages.length===0)t=e.text;else{const i=e.contextMessages.map(r=>`[${r.senderId}] ${r.content}`).join(`
11
+ `);t=M(e.text,`[Conversation context]
12
+ ${i}`)}const n=this.pendingQuestionAnswerBySession.get(e.adapterSessionId);n&&(this.pendingQuestionAnswerBySession.delete(e.adapterSessionId),t=M(t,`[User answered a previous agent question]
13
+ ${n}`));const s=this.pendingHandoffBySession.get(e.adapterSessionId);return s&&(this.pendingHandoffBySession.delete(e.adapterSessionId),t=M(t,`[Previous conversation summary \u2014 continue from this handoff]
14
+ ${s}`)),this.identity.injectOnce(e.adapterSessionId,t)}handleStdoutLineForActive(e,t){if(e.done)return;const n=t.trim();if(!n)return;e.lastIoAt=Date.now();const{event:s}=e;let i;try{i=JSON.parse(n)}catch{this.armActiveIdleTimer(e.request.adapterSessionId);return}const r=i?.type==="system"&&i?.subtype==="init";this.rememberCursorChatId(e.request.adapterSessionId,i?.session_id,r);const o=this.auditCaptures.get(s.event_id);if(o&&i&&typeof i=="object"&&o.push({sequence:o.length,observedAt:new Date().toISOString(),event:structuredClone(i)}),i?.type==="tool_call"){const c=String(i?.call_id??""),d=String(i?.subtype??"");c&&(d==="started"||d==="start"?(this.flushAssistantStreamBuffer(e),e.textSegmentInterrupted=!0,e.descendantBaseline===void 0&&this.captureDescendantBaseline(e),e.toolCallsInFlight.add(c),e.toolCallsStarted+=1,this.handleSpecialToolCallStarted(e,i)):X.has(d)&&e.toolCallsInFlight.delete(c))}this.armActiveIdleTimer(e.request.adapterSessionId);const a=Re(i);a&&this.callbacks.sendRawEventEnvelope?.(s.event_id,s.session_id,a);const u=Te(i,e.assistantTextEmitted);if(u&&this.enqueueAssistantStreamDelta(e,u),i?.type==="result"){e.sawResult=!0;const c=typeof i?.result=="string"?i.result.trim():"";if(c)if(!e.assistantTextEmitted)this.enqueueAssistantStreamDelta(e,c);else if(c.startsWith(e.assistantTextEmitted)){const y=c.slice(e.assistantTextEmitted.length);y&&this.enqueueAssistantStreamDelta(e,y)}else!e.assistantTextEmitted.endsWith(c)&&!e.assistantTextEmitted.startsWith(c)&&this.enqueueAssistantStreamDelta(e,c);this.flushAssistantStreamBuffer(e);const d=i?.usage??{},f=this.lastUsageBySession.get(e.request.adapterSessionId);this.lastUsageBySession.set(e.request.adapterSessionId,{sampledAt:new Date().toISOString(),turns:(f?.turns??0)+1,total:{input:(f?.total.input??0)+Number(d.inputTokens??0),output:(f?.total.output??0)+Number(d.outputTokens??0),cacheRead:(f?.total.cacheRead??0)+Number(d.cacheReadTokens??0),cacheWrite:(f?.total.cacheWrite??0)+Number(d.cacheWriteTokens??0)}});const A=String((this.sessionRuntime.get(e.request.adapterSessionId)?.modelId??this.config.options?.model??"")||""),_=Math.max(1,(e.toolCallsStarted??0)+1),b=Number(d.inputTokens??0),m=Number(d.cacheReadTokens??0),v=Number(d.cacheWriteTokens??0),S=Ae({inputTokens:b,cacheReadTokens:m,cacheWriteTokens:v},A,{apiRounds:_});S&&(this.lastContextBySession.set(e.request.adapterSessionId,S),h.info("cursor-adapter",`[context_window] used=${S.usedTokens} size=${S.sizeTokens} pct=${S.usedPercentage.toFixed(1)}% model=${A||"auto"} rawIn=${b} rawCache=${m} rawWrite=${v} apiRounds=${_}`))}}handleSpecialToolCallStarted(e,t){const n=K(t);if(Z(n.toolName)){const s=Be(n.toolInput);s?(e.seq+=1,this.callbacks.sendStreamChunk(e.event.event_id,e.event.session_id,s,e.seq,!1,e.currentClientMsgId),h.info("cursor-adapter",`CreatePlan forwarded as stream text: event=${e.event.event_id} chars=${s.length}`)):(e.seq+=1,this.callbacks.sendStreamChunk(e.event.event_id,e.event.session_id,"[CreatePlan] \u65B9\u6848\u5185\u5BB9\u89E3\u6790\u5931\u8D25\uFF0C\u672A\u4E0B\u53D1\u6B63\u6587\u3002",e.seq,!1,e.currentClientMsgId),h.warn("cursor-adapter",`CreatePlan missing plan body: event=${e.event.event_id}`));return}Y(n.toolName)&&this.emitAskQuestionCard(e,n.toolInput)}emitAskQuestionCard(e,t){const n=e.event,s=xe(t);if(!s){e.seq+=1,this.callbacks.sendStreamChunk(n.event_id,n.session_id,"[AskQuestion] \u95EE\u9898\u5185\u5BB9\u89E3\u6790\u5931\u8D25\uFF0C\u672A\u4E0B\u53D1\u95EE\u9898\u5361\u3002",e.seq,!1,e.currentClientMsgId),h.warn("cursor-adapter",`AskQuestion parse failed: event=${n.event_id}`);return}if(!this.callbacks.sendAgentQuestionCard){h.warn("cursor-adapter","AskQuestion skipped: sendAgentQuestionCard callback not wired");return}const i=ie(),r=Date.now();this.pendingQuestionByRequestId.set(i,{eventId:n.event_id,sessionId:n.session_id,createdAt:r}),this.callbacks.sendAgentQuestionCard(n.event_id,n.session_id,{request_id:i,mode:"form",questions:s,expires_at:r+q}),h.info("cursor-adapter",`Sent agent_question card: request_id=${i} questions=${s.length} event=${n.event_id}`)}async handleQuestionReply(e){const t=e.params??{},n=String(t.request_id??"").trim();if(!n)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"request_id_required","request_id is required"),{handled:!0,kind:"question_reply_no_id"};const s=this.pendingQuestionByRequestId.get(n),i=s?Date.now()-s.createdAt>q+3e4:!0;if(!s||i)return this.pendingQuestionByRequestId.delete(n),this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"interaction_request_not_pending","The question is no longer pending; the reply was not delivered."),{handled:!0,kind:"question_reply_not_pending"};const r=t.resolution??{},o=String(r.type??"");if(o==="action"&&String(r.value??"")==="cancel")return this.pendingQuestionByRequestId.delete(n),this.callbacks.sendLocalActionResult(e.action_id,"ok",{request_id:n,resolution:"cancel"}),{handled:!0,kind:"question_reply_cancel"};let a="";return o==="text"?a=String(r.value??""):o==="map"&&(a=(Array.isArray(r.entries)?r.entries:[]).map(c=>c.value).join(", ")),a?(this.pendingQuestionByRequestId.delete(n),this.pendingQuestionAnswerBySession.set(s.sessionId,a),this.callbacks.sendLocalActionResult(e.action_id,"ok",{request_id:n,resolution:"answer"}),h.info("cursor-adapter",`Question reply cached for next prompt: request_id=${n} session=${s.sessionId}`),{handled:!0,kind:"question_reply"}):(this.pendingQuestionByRequestId.delete(n),this.callbacks.sendLocalActionResult(e.action_id,"ok",{request_id:n,resolution:"cancel"}),{handled:!0,kind:"question_reply_empty"})}enqueueAssistantStreamDelta(e,t){t&&(this.rolloverInterruptedTextSegment(e),e.assistantTextEmitted+=t,e.streamBuffer+=t,e.streamBuffer.length>=ke&&this.flushAssistantStreamBuffer(e))}rolloverInterruptedTextSegment(e){e.textSegmentInterrupted&&(e.textSegmentInterrupted=!1,this.flushAssistantStreamBuffer(e),e.seq!==0&&(e.seq+=1,this.callbacks.sendStreamChunk(e.event.event_id,e.event.session_id,"",e.seq,!0,e.currentClientMsgId),e.segmentIndex+=1,e.currentClientMsgId=`${e.clientMsgIdBase}_seg_${e.segmentIndex}`,e.seq=0,h.info("cursor-adapter",`stream segment rollover event=${e.event.event_id} segment=${e.segmentIndex} reason=tool_call`)))}flushAssistantStreamBuffer(e){if(!e.streamBuffer)return;const t=e.streamBuffer;e.streamBuffer="",e.seq+=1,this.callbacks.sendStreamChunk(e.event.event_id,e.event.session_id,t,e.seq,!1,e.currentClientMsgId,void 0)}captureDescendantBaseline(e){const t=e.child?.pid;if(!t){e.descendantBaseline=null;return}try{e.descendantBaseline=new Set(ge(t)),h.info("cursor-adapter",`Liveness baseline captured for ${e.event.event_id}: ${e.descendantBaseline.size} resident descendant(s)`)}catch{e.descendantBaseline=null,h.warn("cursor-adapter",`Liveness baseline capture failed for ${e.event.event_id}; tool-descendant extend disabled`)}}shouldExtendByLiveness(e){const t=this.activeBySession.get(e);if(!t||t.done)return!1;const n=t.child?.pid;if(!n||!E(n)||t.sawResult)return!1;const s=this.transcriptTurnStateForSession(e)?.lastAssistant!=null;if((t.toolCallsInFlight.size>0||s)&&t.descendantBaseline instanceof Set){let f=0;try{f=W(n,t.descendantBaseline)}catch{f=0}if(f>0)return t.livenessExtendStartAt=void 0,h.info("cursor-adapter",`Liveness check: tool descendants for ${t.event.event_id} (descendants=${f}, toolsInFlight=${t.toolCallsInFlight.size}), extending without budget`),!0}const i=Date.now(),r=i-t.lastIoAt,o=this.transcriptFreshMsForSession(e);if(r<U||o!==null&&o<U)return t.livenessExtendStartAt=i,h.info("cursor-adapter",`Liveness check: fresh progress for ${t.event.event_id} (ioAge=${r}ms, transcriptAge=${o??"n/a"}, toolsInFlight=${t.toolCallsInFlight.size}), extending`),!0;const u=o===null?0:i-o,c=Math.max(t.lastIoAt,u);t.livenessExtendStartAt===void 0?t.livenessExtendStartAt=i:c>t.livenessExtendStartAt&&(t.livenessExtendStartAt=c);const d=t.livenessExtendStartAt??i;return i-d>z?(h.warn("cursor-adapter",`Liveness extension budget exhausted for ${t.event.event_id} (no progress for ${Math.round((i-d)/6e4)}min), allowing idle kill`),!1):(h.info("cursor-adapter",`Liveness check: turn in progress for ${t.event.event_id} (toolsInFlight=${t.toolCallsInFlight.size}, ioAge=${r}ms), extending`),!0)}rememberCursorChatId(e,t,n=!1){const s=String(t??"").trim();if(!s)return;const i=this.sessionRuntime.get(e)??{};if(i.cursorSessionId!==s&&this.transcriptPathBySession.delete(e),this.sessionRuntime.set(e,{...i,cursorSessionId:s}),n){const r=this.activeBySession.get(e);if(r&&r.transcriptBaseOffset===void 0){const o=this.transcriptPathForSession(e);if(o)try{r.transcriptBaseOffset=B(o).size}catch{this.transcriptPathBySession.delete(e)}else r.usedContinue||(r.transcriptBaseOffset=0)}}this.bindingStore?.setAcpSessionId(e,s)}transcriptPathForSession(e){const t=this.sessionRuntime.get(e)?.cursorSessionId;if(!t)return null;const n=this.transcriptPathBySession.get(e);if(n)return n;const s=L(t);return s?(this.transcriptPathBySession.set(e,s),s):null}transcriptFreshMsForSession(e){const t=this.transcriptPathForSession(e);if(!t)return null;try{return Date.now()-B(t).mtimeMs}catch{return this.transcriptPathBySession.delete(e),null}}transcriptTurnStateForSession(e){const t=this.activeBySession.get(e);if(!t||t.transcriptBaseOffset===void 0)return null;const n=this.transcriptPathForSession(e);return n?Me(n,t.transcriptBaseOffset):null}tryFinishActiveFromTranscript(e){const t=this.activeBySession.get(e);if(!t||t.done||t.sawResult||t.toolCallsInFlight.size>0)return!1;const n=this.transcriptTurnStateForSession(e);if(!n||n.hasUserAfterLastAssistant)return!1;const s=n.lastAssistant;if(!s||s.hasToolUse)return!1;const i=s.text.trim();if(!i)return!1;if(t.descendantBaseline instanceof Set)try{const r=t.child?.pid;if(r&&W(r,t.descendantBaseline)>0)return!1}catch{return!1}if(!t.assistantTextEmitted)this.enqueueAssistantStreamDelta(t,i);else if(i.startsWith(t.assistantTextEmitted)){const r=i.slice(t.assistantTextEmitted.length);r&&this.enqueueAssistantStreamDelta(t,r)}else!t.assistantTextEmitted.endsWith(i)&&!t.assistantTextEmitted.startsWith(i)&&this.enqueueAssistantStreamDelta(t,i);return h.info("cursor-adapter",`Transcript final text recovered for ${t.event.event_id}; stream-json result was missing, finishing as responded`),this.killChildWithFallback(t.child),this.finishActive(e,"responded"),!0}hasPendingQuestionForSession(e){const t=Date.now();for(const[n,s]of this.pendingQuestionByRequestId)if(s.sessionId===e){if(t-s.createdAt>q){this.pendingQuestionByRequestId.delete(n);continue}return!0}return!1}armActiveIdleTimer(e){const t=this.activeBySession.get(e);!t||t.done||(t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{if(t.done)return;if(this.hasPendingQuestionForSession(e)){h.info("cursor-adapter",`Idle timeout skipped: awaiting AskQuestion for ${t.event.event_id}, resetting timer`),this.armActiveIdleTimer(e);return}if(this.tryFinishActiveFromTranscript(e))return;if(this.shouldExtendByLiveness(e)){this.armActiveIdleTimer(e);return}if(t.sawResult){h.warn("cursor-adapter",`Idle after result with no close \u2014 finishing as responded: event=${t.event.event_id} session=${e}`),this.killChildWithFallback(t.child),this.finishActive(e,"responded");return}const n=t.child?.pid,i=!!(n&&E(n))?`liveness budget exhausted after ${z/6e4}min`:"child process dead";h.error("cursor-adapter",`Idle timeout (${i}, toolsInFlight=${t.toolCallsInFlight.size}) \u2014 killing cursor child: event=${t.event.event_id} session=${e}`),this.killChildWithFallback(t.child),this.finishActive(e,"failed",`idle timeout: ${i}`)},we),t.idleTimer.unref?.())}finishActive(e,t,n){const s=this.activeBySession.get(e);if(!s)return;s.done=!0,s.timer&&clearTimeout(s.timer),s.idleTimer&&clearTimeout(s.idleTimer),this.flushAssistantStreamBuffer(s),s.seq+=1;const i=String(s.event.quoted_message_id??"").trim()||void 0;if(this.callbacks.sendStreamChunk(s.event.event_id,s.event.session_id,"",s.seq,!0,s.currentClientMsgId,i),h.info("cursor-adapter",`job finish: event=${s.event.event_id} session=${s.event.session_id} status=${t}${n?` msg=${n}`:""}`),this.snapshotAuditBoundary(s.event.event_id,e),this.emit("eventDone",s.event.event_id),this.callbacks.sendEventResult(s.event.event_id,t,n),t==="responded"?s.handle.emitDone({status:"completed"}):t==="canceled"?s.handle.emitDone({status:"canceled",error:n}):s.handle.emitDone({status:"failed",error:n}),this.activeBySession.delete(e),this.notifyBindingReady(e),t==="responded"&&this.shouldAutoCompact(e)){const r=this.lastContextBySession.get(e)?.usedPercentage??0;h.info("cursor-adapter",`[auto-compact] context_window usedPercentage=${r.toFixed(1)}% >= ${G}%, scheduling compact session=${e}`),this.runCompactHandoff(e).finally(()=>{this.tryStartNext(e)});return}this.tryStartNext(e)}snapshotAuditBoundary(e,t){const n=this.auditCaptures.get(e);if(!n)return;const s=this.sessionRuntime.get(t);this.completedAuditBoundaries.set(e,{adapterType:"cursor",providerSessionId:s?.cursorSessionId,cursorEvidence:{events:n}}),this.auditCaptures.delete(e)}shouldRetryWithoutContinue(e){if(!e.usedContinue||e.retryCount>0)return!1;const t=e.stderr.toLowerCase(),n=t.includes("resume")||t.includes("continue")||t.includes("chat")||t.includes("session"),s=t.includes("not found")||t.includes("no previous session")||t.includes("does not exist")||t.includes("invalid");return n&&s}ensureWorkspaceMcpAndSkills(e){if(!this.internalApi)return;this.ensureCursorMcpConfig(e,this.internalApi.url);const t=w(Q(),".cursor","skills"),n=pe(t);n.length>0&&h.info("cursor-adapter",`Synced connector skills to ${t}: [${n.join(", ")}]`)}ensureCursorMcpConfig(e,t){const n=he(this.callbacks.getAgentId?.()),s={command:process.execPath,args:[oe(ae(import.meta.url),"../../../mcp/acp-mcp-server.js"),"--api-url",t]},i=[e],r=this.resolveGitRoot(e);r&&r!==e&&i.push(r);let o=null;for(const a of i){const u=this.writeCursorMcpConfig(a,n,s,t);!o&&u&&(o=u)}o&&this.recordCursorMcpRegistry(e,o,s)}resolveGitRoot(e){try{return ne("git",["-C",e,"rev-parse","--show-toplevel"],{timeout:5e3,stdio:["ignore","pipe","ignore"],windowsHide:!0}).toString("utf8").trim()||null}catch{return null}}writeCursorMcpConfig(e,t,n,s){try{const i=w(e,".cursor"),r=w(i,"mcp.json");O(i,{recursive:!0});let o={};try{o=JSON.parse(T(r,"utf8"))}catch{o={}}(!o.mcpServers||typeof o.mcpServers!="object")&&(o.mcpServers={});const a=fe(o.mcpServers,s);return o.mcpServers[t]=n,j(r,`${JSON.stringify(o,null,2)}
15
+ `,"utf8"),h.info("cursor-adapter",`MCP config synced: dir=${e} file=${r} server=${t}${a.length>0?` pruned=${a.join(",")}`:""}`),r}catch(i){return h.warn("cursor-adapter",`Failed to ensure ${w(e,".cursor","mcp.json")}: ${String(i)}`),null}}recordCursorMcpRegistry(e,t,n){try{const s=w(le.data,"cursor"),i=w(s,"mcp-registry.json");O(s,{recursive:!0});let r={};try{r=JSON.parse(T(i,"utf8"))}catch{r={}}r[e]={mcp_path:t,server:n,updated_at:new Date().toISOString()},j(i,`${JSON.stringify(r,null,2)}
16
+ `,"utf8")}catch(s){h.warn("cursor-adapter",`Failed to record MCP registry: ${String(s)}`)}}}export{ee as CURSOR_MODE_OPTIONS,D as CursorAdapter,Te as extractCursorAssistantStreamDelta,L as findCursorTranscript,Be as formatCursorCreatePlanText,Y as isCursorAskQuestionTool,Z as isCursorCreatePlanTool,Re as mapCursorStreamJsonToRawEnvelope,xe as parseCursorAskQuestionPayload};
@@ -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 d(t){const e=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(String(t??"").trim());return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),...e[4]?{prerelease:e[4]}:{}}:null}function a(t,e){const r=d(t),n=d(e);return!r||!n?null:r.major-n.major||r.minor-n.minor||r.patch-n.patch||f(r.prerelease,n.prerelease)}function f(t,e){if(t===e)return 0;if(t===void 0)return 1;if(e===void 0)return-1;const r=t.split("."),n=e.split(".");for(let s=0;s<Math.max(r.length,n.length);s+=1){const i=r[s],u=n[s];if(i===u)continue;if(i===void 0)return-1;if(u===void 0)return 1;const o=/^\d+$/.test(i),c=/^\d+$/.test(u);return o&&c?Number(i)-Number(u):o!==c?o?-1:1:i<u?-1:1}return 0}export{a as compareDshVersions,d as parseDshVersion};
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 +1 @@
1
- function u(e){return e.data&&typeof e.data=="object"?e.data:{}}function g(e){const t=u(e),n=t.chunk&&typeof t.chunk=="object"?t.chunk:t,o=String(n.type??t.chunkType??"").toLowerCase();if(e.type==="assistant/chunk:text-delta"||e.type==="assistant/chunk"&&o==="text-delta")return{kind:"text",text:String(n.delta??n.text??"")};if(e.type==="assistant/chunk:reasoning-delta"||e.type==="assistant/chunk"&&o==="reasoning-delta")return{kind:"thinking",text:String(n.delta??n.text??"")};if(e.type==="assistant/chunk:usage"||e.type==="assistant/chunk"&&o==="usage")return{kind:"usage",usage:n.usage??n};if(e.type==="assistant/message"){const r=t.message&&typeof t.message=="object"?t.message:t,c=Array.isArray(r.content)?r.content:[],i=c.some(s=>s&&typeof s=="object"&&String(s.type??"")==="tool-call");return{kind:"text",text:Array.isArray(r.content)?c.filter(s=>s&&typeof s=="object"&&String(s.type??"")==="text").map(s=>String(s.text??"")).join(""):String(r.content??r.text??""),usage:r.usage??t.usage,payload:{committed:!0,hasToolCall:i}}}if(e.type==="request/context")return{kind:"context",payload:{provider:String(t.provider??""),model:String(t.model??""),...Number.isFinite(Number(t.contextWindow))?{contextWindow:Number(t.contextWindow)}:{}}};if(e.type==="tool/call")return{kind:"tool_call",callId:String(t.callId??t.id??""),name:String(t.name??t.toolName??"tool"),input:y(t.arguments??t.input),payload:t};if(e.type==="tool/result"){const r=t.message&&typeof t.message=="object"?t.message:void 0,c=r?.source&&typeof r.source=="object"?r.source:void 0,i=Array.isArray(r?.content)?r.content.find(a=>a&&typeof a=="object"&&String(a.type??"")==="tool-result"):void 0,d=String(t.callId??c?.callId??i?.toolCallId??t.id??""),s=l(t.result??t.output??(i?{content:i.content}:t.message));return{kind:"tool_result",callId:d,output:s,...i?.isError===!0?{isError:!0}:{},payload:t}}if(e.type==="todo/write")return{kind:"todo",payload:t};if(e.type.startsWith("compaction/"))return{kind:"compaction",payload:{eventType:e.type,...t}};if(e.type==="turn/end"){const r=t.reason,c=p(r),i=f(r);return{kind:"turn_end",reason:c,...i?{detail:i}:{},payload:t}}return{kind:"unknown",payload:t}}function p(e){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object"){const t=e.kind;if(typeof t=="string"&&t)return t}return"completed"}function f(e){if(typeof e=="string"||!e||typeof e!="object")return;const t=e,n=t.error;if(typeof n=="string"&&n.trim())return n.trim().slice(0,500);if(n&&typeof n=="object"){const o=n.message;if(typeof o=="string"&&o.trim())return o.trim().slice(0,500)}if(typeof t.message=="string"&&t.message.trim())return t.message.trim().slice(0,500)}function y(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function l(e){if(!e||typeof e!="object")return e;const t=e;return Array.isArray(t.content)?t.content.filter(o=>o&&typeof o=="object"&&String(o.type??"")==="text").map(o=>String(o.text??"")).join("")||e:t.content??e}function m(e){if(!e||typeof e!="object")return null;const t=e,n=t.event&&typeof t.event=="object"?t.event:t,o=String(n.type??n.eventType??"").trim();return o?{...n,type:o,sessionId:String(n.sessionId??t.sessionId??"").trim()||void 0,data:n.data&&typeof n.data=="object"?n.data:n}:null}export{f as finishReasonDetail,p as finishReasonKind,g as mapDshSessionEvent,m as unwrapDshSessionEvent};
1
+ function u(e){return e.data&&typeof e.data=="object"?e.data:{}}function l(e){const t=u(e),n=t.chunk&&typeof t.chunk=="object"?t.chunk:t,r=String(n.type??t.chunkType??"").toLowerCase();if(e.type==="assistant/chunk:text-delta"||e.type==="assistant/chunk"&&r==="text-delta")return{kind:"text",text:String(n.delta??n.text??"")};if(e.type==="assistant/chunk:reasoning-delta"||e.type==="assistant/chunk"&&r==="reasoning-delta")return{kind:"thinking",text:String(n.delta??n.text??"")};if(e.type==="assistant/chunk:usage"||e.type==="assistant/chunk"&&r==="usage")return{kind:"usage",usage:n.usage??n};if(e.type==="assistant/message"){const s=t.message&&typeof t.message=="object"?t.message:t,c=Array.isArray(s.content)?s.content:[],i=c.some(o=>o&&typeof o=="object"&&String(o.type??"")==="tool-call"),a=Array.isArray(s.content)?c.filter(o=>o&&typeof o=="object"&&String(o.type??"")==="text").map(o=>String(o.text??"")).join(""):String(s.content??s.text??""),d=c.filter(o=>o&&typeof o=="object"&&String(o.type??"")==="reasoning").map(o=>String(o.text??"")).join("");return{kind:"text",text:a,reasoning:d,usage:s.usage??t.usage,payload:{committed:!0,hasToolCall:i}}}if(e.type==="request/context")return{kind:"context",payload:{provider:String(t.provider??""),model:String(t.model??""),...Number.isFinite(Number(t.contextWindow))?{contextWindow:Number(t.contextWindow)}:{}}};if(e.type==="tool/call")return{kind:"tool_call",callId:String(t.callId??t.id??""),name:String(t.name??t.toolName??"tool"),input:y(t.arguments??t.input),payload:t};if(e.type==="tool/result"){const s=t.message&&typeof t.message=="object"?t.message:void 0,c=s?.source&&typeof s.source=="object"?s.source:void 0,i=Array.isArray(s?.content)?s.content.find(o=>o&&typeof o=="object"&&String(o.type??"")==="tool-result"):void 0,a=String(t.callId??c?.callId??i?.toolCallId??t.id??""),d=g(t.result??t.output??(i?{content:i.content}:t.message));return{kind:"tool_result",callId:a,output:d,...i?.isError===!0?{isError:!0}:{},payload:t}}if(e.type==="todo/write")return{kind:"todo",payload:t};if(e.type.startsWith("compaction/"))return{kind:"compaction",payload:{eventType:e.type,...t}};if(e.type==="turn/end"){const s=t.reason,c=p(s),i=f(s);return{kind:"turn_end",reason:c,...i?{detail:i}:{},payload:t}}return{kind:"unknown",payload:t}}function p(e){if(typeof e=="string"&&e)return e;if(e&&typeof e=="object"){const t=e.kind;if(typeof t=="string"&&t)return t}return"completed"}function f(e){if(typeof e=="string"||!e||typeof e!="object")return;const t=e,n=t.error;if(typeof n=="string"&&n.trim())return n.trim().slice(0,500);if(n&&typeof n=="object"){const r=n.message;if(typeof r=="string"&&r.trim())return r.trim().slice(0,500)}if(typeof t.message=="string"&&t.message.trim())return t.message.trim().slice(0,500)}function y(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function g(e){if(!e||typeof e!="object")return e;const t=e;return Array.isArray(t.content)?t.content.filter(r=>r&&typeof r=="object"&&String(r.type??"")==="text").map(r=>String(r.text??"")).join("")||e:t.content??e}function m(e){if(!e||typeof e!="object")return null;const t=e,n=t.event&&typeof t.event=="object"?t.event:t,r=String(n.type??n.eventType??"").trim();return r?{...n,type:r,sessionId:String(n.sessionId??t.sessionId??"").trim()||void 0,data:n.data&&typeof n.data=="object"?n.data:n}:null}export{f as finishReasonDetail,p as finishReasonKind,l as mapDshSessionEvent,m as unwrapDshSessionEvent};