grix-connector 3.14.0 → 3.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/claude/claude-bridge-server.js +1 -1
- package/dist/adapter/claude/claude-tools.js +1 -1
- package/dist/adapter/claude/claude-worker-client.js +1 -1
- package/dist/adapter/claude/mcp-http-launcher.js +2 -2
- package/dist/adapter/claude/result-timeout.js +1 -1
- package/dist/adapter/cursor/context-window.js +1 -0
- package/dist/adapter/cursor/cursor-adapter.js +11 -5
- package/dist/adapter/cursor/fetch-models.js +2 -0
- package/dist/adapter/cursor/fetch-usage.js +1 -0
- package/dist/adapter/cursor/index.js +1 -1
- package/dist/bridge/bridge.js +9 -9
- package/dist/bridge/raw-event-delivery.js +2 -0
- package/dist/bridge/send-controller.js +3 -3
- package/dist/core/access/allowlist-store.js +1 -1
- package/dist/core/file-ops/list-files.js +1 -1
- package/dist/log.js +2 -2
- package/dist/manager.js +1 -1
- package/dist/mcp/stream-http/config.js +1 -1
- package/dist/mcp/stream-http/connection-binding.js +1 -1
- package/dist/mcp/stream-http/security.js +1 -1
- package/dist/mcp/stream-http/tool-executor.js +1 -1
- package/dist/mcp/stream-http/tool-registry.js +1 -1
- package/dist/mcp/stream-http/tool-schemas.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const
|
|
1
|
+
import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const r of t)e.push(r);const n=Buffer.concat(e).toString("utf8").trim();return n?JSON.parse(n):{}}function k(t){const e=(t.headers.authorization??"").trim();return e.toLowerCase().startsWith("bearer ")?e.slice(7).trim():""}class w{host="127.0.0.1";port=0;token;callbacks;server=null;address=null;constructor(e){this.token=d(),this.callbacks=e}getToken(){return this.token}getURL(){return this.address?`http://${this.address.address}:${this.address.port}`:""}async start(){this.server||(this.server=c.createServer(async(e,n)=>{try{await this.handleRequest(e,n)}catch(r){h(n,r instanceof Error?r.message:String(r))}}),await new Promise((e,n)=>{this.server.once("error",n),this.server.listen(this.port,this.host,()=>{this.server.off("error",n),e()})}),this.address=this.server.address(),o.info("claude-bridge",`Bridge server listening on ${this.getURL()}`))}async stop(){if(!this.server)return;const e=this.server;this.server=null,this.address=null,e.closeIdleConnections?.(),e.closeAllConnections?.(),await new Promise((n,r)=>{e.close(s=>s?r(s):n())})}async handleRequest(e,n){if(k(e)!==this.token){l(n);return}if(e.method!=="POST"){n.writeHead(405,{"content-type":"application/json"}),n.end(JSON.stringify({error:"method_not_allowed"}));return}const r=new URL(e.url,"http://localhost").pathname,s=await v(e),i=f.get(r);if(!i){u(n);return}const a=await i(this.callbacks,s);p(n,a??{ok:!0})}}const f=new Map([["/v1/worker/register",async(t,e)=>(o.info("claude-bridge",`Worker registered: ${e.worker_id} (pid=${e.pid})`),t.onRegisterWorker(e))],["/v1/worker/status",async(t,e)=>(o.info("claude-bridge",`Worker status: ${e.status}`),t.onStatusUpdate(e))],["/v1/worker/send-text",async(t,e)=>t.onSendText(e)],["/v1/worker/send-stream-chunk",async(t,e)=>t.onSendStreamChunk(e)],["/v1/worker/send-media",async(t,e)=>t.onSendMedia(e)],["/v1/worker/delete-message",async(t,e)=>t.onDeleteMessage(e)],["/v1/worker/ack-event",async(t,e)=>t.onAckEvent(e)],["/v1/worker/event-result",async(t,e)=>t.onSendEventResult(e)],["/v1/worker/event-stop-ack",async(t,e)=>t.onSendEventStopAck(e)],["/v1/worker/event-stop-result",async(t,e)=>t.onSendEventStopResult(e)],["/v1/worker/session-composing",async(t,e)=>t.onSetSessionComposing(e)],["/v1/worker/agent-invoke",async(t,e)=>t.onAgentInvoke(e)],["/v1/worker/local-action-result",async(t,e)=>t.onLocalActionResult(e)]]);export{w as ClaudeBridgeServer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUID as x}from"node:crypto";import{CallToolRequestSchema as S,ListToolsRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{log as f}from"../../core/log/index.js";import{toolCallToInvoke as k}from"../../core/mcp/tools.js";const E=new Set(["contact_search","session_search","message_history","message_search","group_create","group_detail_read","group_leave_self","group_member_add","group_member_remove","group_member_role_update","group_all_members_muted_update","group_member_speaking_update","group_dissolve","send_msg","delete_msg","agent_api_create","agent_category_list","agent_category_create","agent_category_update","agent_category_assign","agent_api_key_rotate"]),y=3e4,I=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},files:{type:"array",items:{type:"string"},description:"Optional absolute local file paths. Each file is uploaded through Agent API OSS presign before sending."},final:{type:"boolean",description:"Whether this is the final reply for the event. Defaults to false \u2014 the event stays open while Claude continues working, and auto-completes after inactivity. Set true only when this is definitively the last message for the event."}},required:["chat_id","event_id"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},code:{type:"string"},msg:{type:"string"}},required:["event_id","status"]}},{name:"delete_message",description:"Delete a previously sent message in the same grix-claude chat.",inputSchema:{type:"object",properties:{chat_id:{type:"string"},message_id:{type:"string"}},required:["chat_id","message_id"]}},{name:"status",description:"Show grix-claude runtime status, upstream access state, bridge health, and startup hints.",inputSchema:{type:"object",properties:{}}},{name:"send",description:"Send a message to a chat session proactively, without requiring an inbound event. Use for notifications or scheduled reports.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The target chat/session id."},text:{type:"string",description:"The message text to send."}},required:["chat_id","text"]}},{name:"access_pair",description:"Forward a sender pairing approval code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"access_deny",description:"Forward a sender pairing denial code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"allow_sender",description:"Ask upstream access control to allow a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"remove_sender",description:"Ask upstream access control to remove a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"access_policy",description:"Ask upstream access control to update the sender access policy.",inputSchema:{type:"object",properties:{policy:{type:"string",enum:["allowlist","open","disabled"]}},required:["policy"]}},{name:"grix_query",description:"Search contacts, sessions, message history, or messages by keyword in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},keyword:{type:"string"},id:{type:"string"},sessionId:{type:"string"},limit:{type:"number"},offset:{type:"number"},beforeId:{type:"string"}},required:["action"]}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string"},memberIds:{type:"array",items:{type:"string"}},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer",description:"Member type (for update_member_role / update_member_speaking)."},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted (for update_member_speaking)."}},required:["action"]}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},content:{type:"string"},msgType:{type:"number"},quotedMessageId:{type:"string"},threadId:{type:"string"}},required:["sessionId","content"]}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},msgId:{type:"string"}},required:["sessionId","msgId"]}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentId:{type:"string"},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"number"}},required:["action"]}}];function q(n,e){n.setRequestHandler(w,async()=>({tools:I})),n.setRequestHandler(S,async i=>{const{name:r,arguments:t}=i.params,s=t??{};try{switch(r){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(r,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(r,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${r}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${r} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(n,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const r=String(n.text??""),t=String(n.chat_id??""),s=String(n.event_id??i.eventId),a=n.reply_to,d=n.files,_=n.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!r.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,r),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(n,e){const i=e.getActiveEvent(),r=String(n.event_id??""),t=n.status??"",s=n.code,a=n.msg;if(!r||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(r)?(e.bridge.sendEventResult(r,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(n,e){const i=String(n.chat_id??""),r=String(n.message_id??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:r},y),c(`deleted (${r})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(n){const e=n.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(n,e){const i=String(n.chat_id??""),r=String(n.text??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(r),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(n,e,i){try{const r=C[n];if(!r)throw new Error(`Unknown access control tool: ${n}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:r.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}async function O(n,e,i){try{const r=k(n,e);if(!E.has(r.action))throw new Error(`Action not allowed: ${r.action}`);const t=await i.bridge.agentInvoke(r.action,r.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}function c(n){return{content:[{type:"text",text:n}]}}export{q as registerClaudeTools};
|
|
1
|
+
import{randomUUID as x}from"node:crypto";import{CallToolRequestSchema as S,ListToolsRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{log as f}from"../../core/log/index.js";import{toolCallToInvoke as k}from"../../core/mcp/tools.js";const E=new Set(["contact_search","session_search","message_history","message_search","group_create","group_detail_read","group_leave_self","group_member_add","group_member_remove","group_member_role_update","group_all_members_muted_update","group_member_speaking_update","group_dissolve","send_msg","delete_msg","agent_api_create","agent_category_list","agent_category_create","agent_category_update","agent_category_assign","agent_api_key_rotate"]),y=3e4,I=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},files:{type:"array",items:{type:"string"},description:"Optional absolute local file paths. Each file is uploaded through Agent API OSS presign before sending."},final:{type:"boolean",description:"Whether this is the final reply for the event. Defaults to false \u2014 the event stays open while Claude continues working, and auto-completes after inactivity. Set true only when this is definitively the last message for the event."}},required:["chat_id","event_id"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},code:{type:"string"},msg:{type:"string"}},required:["event_id","status"]}},{name:"delete_message",description:"Delete a previously sent message in the same grix-claude chat.",inputSchema:{type:"object",properties:{chat_id:{type:"string"},message_id:{type:"string"}},required:["chat_id","message_id"]}},{name:"status",description:"Show grix-claude runtime status, upstream access state, bridge health, and startup hints.",inputSchema:{type:"object",properties:{}}},{name:"send",description:"Send a message to a chat session proactively, without requiring an inbound event. Use for notifications or scheduled reports.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The target chat/session id."},text:{type:"string",description:"The message text to send."}},required:["chat_id","text"]}},{name:"access_pair",description:"Forward a sender pairing approval code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"access_deny",description:"Forward a sender pairing denial code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"allow_sender",description:"Ask upstream access control to allow a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"remove_sender",description:"Ask upstream access control to remove a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"access_policy",description:"Ask upstream access control to update the sender access policy.",inputSchema:{type:"object",properties:{policy:{type:"string",enum:["allowlist","open","disabled"]}},required:["policy"]}},{name:"grix_query",description:"Search contacts, sessions, message history, or messages by keyword in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},keyword:{type:"string"},id:{type:"string"},sessionId:{type:"string"},limit:{type:"number"},offset:{type:"number"},beforeId:{type:"string"}},required:["action"]}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string"},memberIds:{type:"array",items:{type:"string"}},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer",description:"Member type (for update_member_role / update_member_speaking)."},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted (for update_member_speaking)."}},required:["action"]}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},content:{type:"string"},msgType:{type:"number"},quotedMessageId:{type:"string"},threadId:{type:"string"}},required:["sessionId","content"]}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},msgId:{type:"string"}},required:["sessionId","msgId"]}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentId:{type:"string"},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"number"}},required:["action"]}}];function q(r,e){r.setRequestHandler(w,async()=>({tools:I})),r.setRequestHandler(S,async i=>{const{name:n,arguments:t}=i.params,s=t??{};try{switch(n){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(n,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(n,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${n}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${n} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(r,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const n=String(r.text??""),t=String(r.chat_id??""),s=String(r.event_id??i.eventId),a=r.reply_to,d=r.files,_=r.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!n.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,n),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(r,e){const i=e.getActiveEvent(),n=String(r.event_id??""),t=r.status??"",s=r.code,a=r.msg;if(!n||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(n)?(e.bridge.sendEventResult(n,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(r,e){const i=String(r.chat_id??""),n=String(r.message_id??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:n},y),c(`deleted (${n})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(r){const e=r.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(r,e){const i=String(r.chat_id??""),n=String(r.text??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(n),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(r,e,i){try{const n=C[r];if(!n)throw new Error(`Unknown access control tool: ${r}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:n.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}async function O(r,e,i){try{const n=k(r,e);if(!E.has(n.action))throw new Error(`Action not allowed: ${n.action}`);const t=await i.bridge.agentInvoke(n.action,n.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}function c(r){return{content:[{type:"text",text:r}]}}export{q as registerClaudeTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(
|
|
1
|
+
import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(r,e){this.controlURL=r.replace(/\/+$/,""),this.token=e.trim(),l.info("claude-worker-client",`Configured with control URL: ${this.controlURL}`)}async post(r,e,s){if(!this.isConfigured())throw new Error("worker control not configured");const i=new AbortController,o=setTimeout(()=>i.abort(),s);try{const t=await fetch(`${this.controlURL}${r}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.token}`},body:JSON.stringify(e),signal:i.signal}),n=await t.text(),a=n.trim()?JSON.parse(n):{};if(!t.ok)throw new Error(a.error||`worker control failed ${t.status}`);return a}finally{clearTimeout(o)}}isRetryableError(r){const e=r instanceof Error?r.message:String(r);return/fetch failed|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|aborted/i.test(e)}async postWithRetry(r,e,s,i=1){let o;for(let t=0;t<=i;t++)try{return t>0&&l.info("claude-worker-client",`Retrying ${r} attempt=${t+1}`),await this.post(r,e,s)}catch(n){if(o=n,t>=i||!this.isRetryableError(n))break;await new Promise(a=>setTimeout(a,150))}throw o instanceof Error?o:new Error(String(o))}async deliverEvent(r){return this.postWithRetry("/v1/worker/deliver-event",{payload:r},1e4,1)}async deliverStop(r){return this.postWithRetry("/v1/worker/deliver-stop",{payload:r},1e4,1)}async deliverLocalAction(r){return this.postWithRetry("/v1/worker/deliver-local-action",{payload:r},1e4,1)}async ping(){try{return await this.postWithRetry("/v1/worker/ping",{},5e3,1),!0}catch{return!1}}}export{c as ClaudeWorkerClient};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as
|
|
2
|
-
`),"utf8"),{expectPath:a,pidPath:i}}function h(
|
|
1
|
+
import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as m}from"./protocol-contract.js";function P(t){let e=null,r=0,n=!1,i=!1;const a=v(),s=t.gatewayUrl??"http://127.0.0.1:19580/mcp";return{async start(){await F(t.command,s,t.env);const c=E(t.grix),u=[...t.args??[],"--name",`grix-mcp-${t.name}`,"--session-id",a];t.fullAuto&&u.push("--dangerously-skip-permissions"),u.push("--dangerously-load-development-channels",`server:${m}`,"--append-system-prompt",c);const f=d(I(),`grix-mcp-claude-${t.name}`);await S(f,{recursive:!0});const{expectPath:$,pidPath:g}=await M(f,t.command,u),_={...process.env,...t.env??{}};e=x("/usr/bin/expect",[$],{cwd:t.cwd,env:_,stdio:["ignore","pipe","pipe"],detached:!0}),o.info("mcp-http-launcher",`\u542F\u52A8 Claude: name=${t.name} cwd=${t.cwd} pid=${e.pid}`),r=await k(g),n=!0,o.info("mcp-http-launcher",`Claude \u5B50\u8FDB\u7A0B PID: ${r}`),e.on("exit",(l,p)=>{o.info("mcp-http-launcher",`Claude \u9000\u51FA: code=${l} signal=${p}`),n=!1,e=null,r=0,i||(o.info("mcp-http-launcher","3 \u79D2\u540E\u81EA\u52A8\u91CD\u542F..."),setTimeout(()=>{i||this.start().catch(w=>{o.error("mcp-http-launcher",`\u91CD\u542F\u5931\u8D25: ${w}`)})},3e3))}),e.stdout?.on("data",l=>{const p=l.toString().trim();p&&o.info("mcp-http-launcher",`[stdout] ${p.slice(0,300)}`)}),e.stderr?.on("data",l=>{const p=l.toString().trim();p&&o.info("mcp-http-launcher",`[stderr] ${p.slice(0,300)}`)})},async stop(){if(i=!0,n=!1,r>0)try{process.kill(r,"SIGTERM")}catch{}if(e?.pid){try{process.kill(-e.pid,"SIGTERM")}catch{}await new Promise(c=>{const u=setTimeout(()=>{if(r>0)try{process.kill(r,"SIGKILL")}catch{}if(e?.pid)try{process.kill(-e.pid,"SIGKILL")}catch{}c()},5e3);e?.once("exit",()=>{clearTimeout(u),c()})})}e=null,r=0},getStatus(){return{name:t.name,alive:n,pid:r}}}}function E(t){return["You are connected to a chat via the grix MCP server.",`On startup, immediately call grix_authorize with: agentId="${t.agentId}", apiKey="${t.apiKey}", wsUrl="${t.wsUrl}", clientType="${t.clientType}".`,"When you receive a <channel> message, you MUST respond by calling the grix_reply tool (or the grix_complete tool if no response is needed).","Never write your reply as plain text \u2014 it will NOT reach the user. Only the grix_reply tool delivers your response to the chat.","The <channel> message contains event_id and session_id \u2014 pass them to grix_reply."].join(" ")}async function F(t,e,r){const n=d(T(),".claude.json");let i=null;try{const s=C(n,"utf8");i=JSON.parse(s)?.mcpServers?.[m]??null}catch{}if(i&&String(i.type??"").trim()==="http"&&String(i.url??"").trim()===e)return;o.info("mcp-http-launcher",`\u6CE8\u518C MCP Server: ${m} -> ${e}`);const a={...process.env,...r??{}};try{y(`${t} mcp remove -s user ${m}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}catch{}y(`${t} mcp add --scope user --transport http ${m} ${e}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}async function M(t,e,r){const{writeFile:n}=await import("node:fs/promises"),i=d(t,"claude.pid"),a=d(t,"claude.expect"),s=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set claude_command [list {${h(e)}}${r.map(c=>` {${h(c)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${h(i)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","expect {"," -re {(?i)(Quick.*safety.*check|trust.*folder)} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)I am using this for local development} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)(Enter.*confirm|Press.*Enter|Hit.*Enter)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {Listening for channel} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," -re {bypass permissions} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," eof {}","}","expect eof",""];return await n(i,"","utf8"),await n(a,s.join(`
|
|
2
|
+
`),"utf8"),{expectPath:a,pidPath:i}}function h(t){return t.replace(/[\\{}$\[\]"]/g,"\\$&")}async function k(t,e=1e4){const{readFile:r}=await import("node:fs/promises"),n=Math.ceil(e/100);for(let i=0;i<n;i++){try{const a=await r(t,"utf8"),s=parseInt(String(a).trim(),10);if(Number.isFinite(s)&&s>0)return s}catch{}await new Promise(a=>setTimeout(a,100))}return 0}export{P as createMcpHttpLauncher};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(
|
|
1
|
+
class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(e){this.defaultTimeoutMs=e.defaultTimeoutMs??9e4,this.onTimeout=e.onTimeout}arm(e,t){this.cancel(e);const s=t?.timeoutMs??this.defaultTimeoutMs,i=Date.now()+s,o=setTimeout(()=>{this.timers.delete(e),this.onTimeout(e).catch(()=>{})},s);return this.timers.set(e,o),i}cancel(e){const t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}has(e){return this.timers.has(e)}close(){for(const e of this.timers.values())clearTimeout(e);this.timers.clear()}}export{m as ResultTimeoutManager};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=2e5,o=1e6;function c(s){const t=String(s??"").trim();if(!t)return 2e5;if(/context\s*=\s*1m\b/i.test(t))return 1e6;if(/context\s*=\s*(\d+)k\b/i.test(t)){const n=t.match(/context\s*=\s*(\d+)k\b/i),e=Number(n?.[1]??0);if(Number.isFinite(e)&&e>0)return e*1e3}if(/context\s*=\s*(\d+)\b/i.test(t)){const n=t.match(/context\s*=\s*(\d+)\b/i),e=Number(n?.[1]??0);if(Number.isFinite(e)&&e>=1e4)return e}return 2e5}function u(s,t){const n=Math.max(0,Number.isFinite(s)?s:0),e=Math.max(1,Number.isFinite(t)&&t>0?t:2e5),i=Math.min(100,n/e*100);return{usedPercentage:i,remainingPercentage:Math.max(0,100-i),usedTokens:n,sizeTokens:e}}export{u as buildCursorContextWindow,c as resolveCursorContextWindowSize};
|
|
@@ -1,8 +1,14 @@
|
|
|
1
|
-
import{createInterface as
|
|
2
|
-
`)){const r=o.trim();if(!r||r.toLowerCase().includes("available model"))continue;const a=r.match(/^(\S+)\s+-\s+(.+)$/);a&&n.push({id:a[1],displayName:a[2].trim()})}n.length>0&&(this._availableModels=n,h.info("cursor-adapter",`Loaded ${n.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())S(e.child,"SIGTERM");this.activeBySession.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 i=this.sessionRuntime.get(e)??{};this.sessionRuntime.set(e,{...i,cwd:typeof t?.cwd=="string"?t.cwd:i.cwd,modelId:typeof t?.modelId=="string"?t.modelId:i.modelId,modeId:typeof t?.modeId=="string"?t.modeId:i.modeId})}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(e){this.sessions.delete(e),this.sessionRuntime.delete(e),this.identity.forgetSession(e)}sendPrompt(e){const t=new D(e.adapterSessionId);if(!this.alive||this.stopped)return queueMicrotask(()=>t.emitError(new Error("adapter not running"))),t;const i=this.inboundQueue.shift()??{event_id:`cursor-evt-${Date.now()}`,session_id:e.adapterSessionId,content:e.text},s=e.adapterSessionId,n=this.pendingBySession.get(s)??[];return n.push({event:i,request:e,handle:t}),this.pendingBySession.set(s,n),this.tryStartNext(s),t}tryStartNext(e){if(this.activeBySession.has(e)||!this.alive||this.stopped)return;const t=this.pendingBySession.get(e);if(!t||t.length===0)return;const i=t.shift();t.length===0?this.pendingBySession.delete(e):this.pendingBySession.set(e,t),i&&this.startJob(i,!1,0)}startJob(e,t,i){const{event:s,request:n,handle:o}=e,r=n.adapterSessionId,a=this.sessionRuntime.get(n.adapterSessionId)??{},d=this.config.options??{},l=[...this.config.args??[]];l.push("-p","--output-format","stream-json","--stream-partial-output"),d.trust!==!1&&l.push("--trust");const g=a.cwd||d.workspace;this.internalApi&&g&&(this.ensureWorkspaceMcpAndSkills(g),l.push("--approve-mcps")),g&&l.push("--workspace",g);const I=a.modelId||d.model;I&&l.push("--model",I);const R=b(a.modeId||d.mode)??"approval";R==="full_auto"?l.push("--yolo"):R==="plan"&&l.push("--plan");const w=a.cursorSessionId??this.bindingStore?.getAcpSessionId(n.adapterSessionId),A=!!(w&&d.use_continue!==!1&&!t);A&&l.push("--resume",w),l.push(this.buildPromptText(n));const _={...process.env,...this.config.env??{}},F=E(this.config.command,typeof _.PATH=="string"?_.PATH:void 0);h.info("cursor-adapter",`job start: event=${s.event_id} session=${s.session_id} retry=${i}`);let p;try{p=$(F,l,{cwd:g||process.cwd(),env:_,stdio:["ignore","pipe","pipe"]}).process}catch(u){this.finishActive(r,"failed",`spawn failed: ${u instanceof Error?u.message:String(u)}`);return}this.callbacks.sendEventAck(s.event_id,s.session_id);const c={event:s,request:n,handle:o,child:p,seq:0,done:!1,stderr:"",timer:null,idleTimer:null,toolCallsInFlight:new Set,retryCount:i,usedContinue:A,workspace:g||process.cwd(),args:l};this.activeBySession.set(r,c),this.notifyBindingReady(r),this.armActiveIdleTimer(r);const y=n.timeoutMs&&n.timeoutMs>0?n.timeoutMs:0;y>0&&(c.timer=setTimeout(()=>{c.done||(S(p,"SIGTERM"),this.finishActive(r,"failed",`cursor agent timeout after ${y}ms`))},y)),O({input:p.stdout}).on("line",u=>this.handleStdoutLineForActive(c,u)),p.stderr?.on("data",u=>{const v=c.stderr+String(u??"");c.stderr=v.length>k.STDERR_MAX_CHARS?v.slice(-k.STDERR_MAX_CHARS):v}),p.once("error",u=>{this.finishActive(r,"failed",`spawn failed: ${String(u?.message??u)}`)}),p.once("close",u=>{if(!c.done)if((u??0)===0)this.finishActive(r,"responded");else{if(this.shouldRetryWithoutContinue(c)){c.timer&&clearTimeout(c.timer),c.idleTimer&&clearTimeout(c.idleTimer),this.activeBySession.delete(r),this.startJob(e,!0,c.retryCount+1);return}const v=c.stderr.trim()||`cursor agent exited with code ${u??-1}`;this.finishActive(r,"failed",v)}})}async cancel(e){const t=this.activeBySession.get(e);t&&(S(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 i={adapterSessionId:t,text:String(e.content??"")},s=new D(t),n=this.pendingBySession.get(t)??[];n.push({event:e,request:i,handle:s}),this.pendingBySession.set(t,n),h.info("cursor-adapter",`inbound queued: event=${e.event_id} session=${t} depth=${n.length}`),this.tryStartNext(t)}killChildWithFallback(e){S(e,"SIGTERM"),setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{S(e,"SIGKILL")}catch{}},5e3).unref()}deliverStopEvent(e,t){if(t){const i=this.activeBySession.get(t);if(i?.event.event_id===e){this.killChildWithFallback(i.child),this.finishActive(t,"canceled","stopped");return}const s=this.pendingBySession.get(t)??[],n=s.findIndex(o=>o.event.event_id===e);if(n>=0){const[o]=s.splice(n,1);s.length===0?this.pendingBySession.delete(t):this.pendingBySession.set(t,s),this.callbacks.sendEventAck(o.event.event_id,o.event.session_id),this.callbacks.sendEventResult(o.event.event_id,"canceled","stopped"),o.handle.emitDone({status:"canceled",error:"stopped"})}return}for(const[i,s]of this.activeBySession.entries())if(s.event.event_id===e){this.killChildWithFallback(s.child),this.finishActive(i,"canceled","stopped");return}for(const[i,s]of this.pendingBySession.entries()){const n=s.findIndex(r=>r.event.event_id===e);if(n<0)continue;const[o]=s.splice(n,1);s.length===0?this.pendingBySession.delete(i):this.pendingBySession.set(i,s),this.callbacks.sendEventAck(o.event.event_id,o.event.session_id),this.callbacks.sendEventResult(o.event.event_id,"canceled","stopped"),o.handle.emitDone({status:"canceled",error:"stopped"});return}}async handleLocalAction(e){const t=String(e.action_type??"").trim().toLowerCase(),i=e.params??{},s=String(i.session_id??"").trim(),n=e.action_id;switch(t){case"set_model":{const o=String(i.model_id??"").trim();if(!o||!s)return this.callbacks.sendLocalActionResult(n,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};const r=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...r,modelId:o}),this.notifyBindingReady(s);const a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(n,"ok",{outcome:"model_set",session_context:{model_id:o,mode_id:a.mode_id,modelId:o,modeId:a.mode_id},model_id:o,mode_id:a.mode_id,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"set_model"}}case"set_mode":{const o=b(i.mode_id);if(!o||!s)return this.callbacks.sendLocalActionResult(n,"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 r=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...r,modeId:o}),this.notifyBindingReady(s);const a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(n,"ok",{outcome:"mode_set",session_context:{model_id:a.model_id,mode_id:o,modelId:a.model_id,modeId:o},model_id:a.model_id,mode_id:o,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"set_mode"}}case"get_context":{const o=s?this.sessionRuntime.get(s):void 0,r=this.config.options??{},a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(n,"ok",{session_context:{model_id:a.model_id,mode_id:a.mode_id,cwd:o?.cwd??r.workspace??null},model_id:a.model_id,mode_id:a.mode_id,modelId:a.model_id,modeId:a.mode_id,cwd:o?.cwd??r.workspace??null,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"get_context"}}case"get_rate_limits":{const o=this.getRateLimitsSnapshot();return this.callbacks.sendLocalActionResult(n,"ok",o),{handled:!0,kind:"get_rate_limits"}}case"get_session_usage":{const o=s?this.getUsageSnapshot(s):null;return o?this.callbacks.sendLocalActionResult(n,"ok",{adapterType:"cursor",available:!0,sampledAt:o.sampledAt,turns:o.turns,tokenUsage:o.total}):this.callbacks.sendLocalActionResult(n,"ok",{adapterType:"cursor",available:!1,sampledAt:null,turns:0,tokenUsage:null}),{handled:!0,kind:"get_session_usage"}}case"session_control":{const o=String(i.verb??"").trim().toLowerCase();if(o==="restart"&&s)this.deliverStopEvent("__all__",s),this.callbacks.sendLocalActionResult(n,"ok",{outcome:"restarted"});else if(o==="status"){const r=this.sessionRuntime.get(s),a=this.config.options??{},d=this.getToolbarMeta(s),l=this.activeBySession.has(s);this.callbacks.sendLocalActionResult(n,"ok",{verb:"status",status:l?"running":"idle",session_context:{model_id:d.model_id,mode_id:d.mode_id,cwd:r?.cwd??a.workspace??null},model_id:d.model_id,mode_id:d.mode_id,modelId:d.model_id,modeId:d.mode_id,cwd:r?.cwd??a.workspace??null,available_models:this.availableModels,available_modes:this.availableModes})}else this.callbacks.sendLocalActionResult(n,"failed",void 0,"invalid_verb",`Unsupported verb: ${o}`);return{handled:!0,kind:"session_control"}}default:return{handled:!1,kind:"unsupported"}}}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 i of this.activeBySession.values()){const s=i.child?.pid;if(s&&!V(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(){this.activeBySession.clear()}getMcpConfig(){return null}async probe(e){const t=this.getStatus();return{...await J(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?Z(e):null;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const i=U(t);return{recordPath:t,lastActivityMs:i.mtimeMs,freshMs:Date.now()-i.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(){return{adapterType:"cursor",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:null,tokenUsage:null}}getToolbarMeta(e){const t=this.config.options??{},i=e||String(t.aibotSessionId??""),s=i?this.sessionRuntime.get(i):void 0,n=String(s?.modelId||t.model||"auto"),o=b(s?.modeId||t.mode)??"approval";return{model_id:n,mode_id:o,currentModelId:n,currentModeId:o,available_models:this.availableModels,available_modes:this.availableModes}}notifyBindingReady(e){if(!this.callbacks.sendUpdateBindingCard)return;const t=this.config.options??{},i=e||String(t.aibotSessionId??"");if(!i)return;const s=this.sessionRuntime.get(i),n=String(s?.cwd||t.workspace||"");n&&this.callbacks.sendUpdateBindingCard(i,this.activeBySession.has(i)?"busy":"ready",n,this.getToolbarMeta(i))}buildPromptText(e){let t;return!e.contextMessages||e.contextMessages.length===0?t=e.text:t=`${e.contextMessages.map(s=>`[${s.senderId}] ${s.content}`).join(`
|
|
1
|
+
import{createInterface as x}from"node:readline";import{EventEmitter as B}from"node:events";import{mkdirSync as $,readFileSync as E,writeFileSync as L,readdirSync as H,statSync as W}from"node:fs";import{join as b,resolve as z}from"node:path";import{fileURLToPath as J}from"node:url";import{homedir as P}from"node:os";import{GRIX_PATHS as G,log as f}from"../../core/log/index.js";import{IdentityInjector as X}from"../shared/identity-injector.js";import{buildSimpleProbeReport as K}from"../shared/probe-util.js";import{InternalApiServer as Q}from"../../core/mcp/internal-api-server.js";import{syncDefaultSkillsToDir as Y}from"../../default-skills/index.js";import{resolveCommandPath as C,spawnCommand as T,killProcessGroup as w}from"../../core/runtime/spawn.js";import{SessionBindingStore as V}from"../../core/persistence/session-binding-store.js";import{fetchCursorParameterizedModels as Z}from"./fetch-models.js";import{fetchCursorAccountUsage as ee}from"./fetch-usage.js";import{buildCursorContextWindow as D,resolveCursorContextWindowSize as O}from"./context-window.js";const te=12e4,se=6e5,ie=8192,ne="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.",N=12e4,j=new Set(["completed","failed","error","errored","canceled","cancelled","rejected"]);function re(l){const e=l.replace(/ToolCall$/i,"").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):l||"tool"}function oe(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 i=Object.keys(t);if(i.length>0){const s=i[0],n=t[s],r=n&&typeof n=="object"&&!Array.isArray(n)?n:null;return{toolName:re(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 ae(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 i=String(e.subtype??"").trim().toLowerCase(),s=oe(e);return i==="started"||i==="start"?{type:"tool_call",payload:{tool_name:s.toolName,...s.callId?{tool_call_id:s.callId}:{}}}:(j.has(i),null)}case"error":return{type:"error",payload:{message:String(e.message??e.error??e.result??"cursor error").trim()||"cursor error"}};case"result":{const i=String(e.subtype??"").trim().toLowerCase();return e.is_error===!0||i==="error"?{type:"error",payload:{message:String(e.result??e.message??"cursor run failed").trim()||"cursor run failed"}}:null}default:return null}}function le(l,e){if(!l||typeof l!="object"||Array.isArray(l))return"";const t=l;if(String(t.type??"")!=="assistant")return"";const i=t.model_call_id??t.modelCallId;if(i!=null&&String(i).trim()!=="")return"";const s=t.message,n=s&&typeof s=="object"&&!Array.isArray(s)?s.content:void 0;if(!Array.isArray(n))return"";const r=n.map(a=>{if(!a||typeof a!="object"||Array.isArray(a))return"";const o=a;return o.type==="text"?String(o.text??""):""}).filter(Boolean).join("");if(!r)return"";if(e){if(r===e||e.startsWith(r)&&r.length<e.length)return"";if(r.startsWith(e))return r.slice(e.length)}return r}const U=[{id:"approval",displayName:"\u4EBA\u5DE5\u786E\u8BA4"},{id:"full_auto",displayName:"\u81EA\u7531\u6A21\u5F0F"},{id:"plan",displayName:"\u8BA1\u5212\u6A21\u5F0F"}];function R(l){const e=String(l??"").trim().toLowerCase();return U.some(t=>t.id===e)?e:null}function de(l){try{return process.kill(l,0),!0}catch(e){return e.code==="EPERM"}}function q(l,e,t){if(t<0)return null;let i;try{i=H(l,{withFileTypes:!0})}catch{return null}for(const s of i){const n=b(l,s.name);if(s.isDirectory()){const r=q(n,e,t-1);if(r)return r}else if(s.isFile()&&s.name.endsWith(e))return n}return null}function ce(l,e){if(!l)return null;const t=e||b(P(),".cursor","projects");return q(t,`${l}.jsonl`,6)}function ue(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(i=>({senderId:String(i.sender_id??"unknown"),content:String(i.content??"")}))}catch{return}}function me(l,e){const t=[String(l??"")],i=String(e.quoted_message_id??"").trim();i&&t.push(`[quoted_message_id] ${i}`);const s=String(e.attachments_json??"").trim();return s&&t.push(`[attachments_json]
|
|
2
|
+
${s}`),t.filter(n=>n.length>0).join(`
|
|
3
|
+
|
|
4
|
+
`)}class F extends B{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){f.warn("cursor-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}class M extends B{type="cursor";static STDERR_MAX_CHARS=8192;config;callbacks;alive=!1;stopped=!1;permissionHandler=null;internalApi=null;bindingStore=null;identity;inboundQueue=[];pendingBySession=new Map;sessions=new Set;sessionRuntime=new Map;sessionSeq=0;lastUsageBySession=new Map;lastContextBySession=new Map;pendingHandoffBySession=new Map;cachedAccountRateLimits=null;rateLimitsInflight=null;_availableModels=[];activeBySession=new Map;constructor(e,t){super(),this.config=e,this.callbacks=t;const i=e.options??{};this.bindingStore=i.bindingStore instanceof V?i.bindingStore:null,this.identity=new X("cursor-adapter",t.getAgentProfile)}async start(){this.alive=!0,this.stopped=!1,(this.config.options??{}).mcp_tools!==!1&&(this.internalApi=new Q,this.internalApi.setInvokeHandler(async(t,i,s,n)=>this.callbacks.agentInvoke(t,i,n)),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 U.map(e=>({...e}))}async refreshModels(){try{const e={...process.env,...this.config.env??{}},t=await Z({command:this.config.command,env:e,cwd:process.cwd()});t.length>0&&(this._availableModels=t,f.info("cursor-adapter",`Loaded ${t.length} available models`))}catch(e){f.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())w(e.child,"SIGTERM");this.activeBySession.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 i=this.sessionRuntime.get(e)??{};this.sessionRuntime.set(e,{...i,cwd:typeof t?.cwd=="string"?t.cwd:i.cwd,modelId:typeof t?.modelId=="string"?t.modelId:i.modelId,modeId:typeof t?.modeId=="string"?t.modeId:i.modeId})}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(e){this.sessions.delete(e),this.sessionRuntime.delete(e),this.identity.forgetSession(e)}sendPrompt(e){const t=new F(e.adapterSessionId);if(!this.alive||this.stopped)return queueMicrotask(()=>t.emitError(new Error("adapter not running"))),t;const i=this.inboundQueue.shift()??{event_id:`cursor-evt-${Date.now()}`,session_id:e.adapterSessionId,content:e.text},s=e.adapterSessionId,n=this.pendingBySession.get(s)??[];return n.push({event:i,request:e,handle:t}),this.pendingBySession.set(s,n),this.tryStartNext(s),t}tryStartNext(e){if(this.activeBySession.has(e)||!this.alive||this.stopped)return;const t=this.pendingBySession.get(e);if(!t||t.length===0)return;const i=t.shift();t.length===0?this.pendingBySession.delete(e):this.pendingBySession.set(e,t),i&&this.startJob(i,!1,0)}startJob(e,t,i){const{event:s,request:n,handle:r}=e,a=n.adapterSessionId,o=this.sessionRuntime.get(n.adapterSessionId)??{},d=this.config.options??{},u=[...this.config.args??[]];u.push("-p","--output-format","stream-json"),d.trust!==!1&&u.push("--trust");const m=o.cwd||d.workspace;this.internalApi&&m&&(this.ensureWorkspaceMcpAndSkills(m),u.push("--approve-mcps")),m&&u.push("--workspace",m);const v=o.modelId||d.model;v&&u.push("--model",v);const _=R(o.modeId||d.mode)??"full_auto";_==="full_auto"?u.push("--yolo"):_==="plan"&&u.push("--plan");const y=o.cursorSessionId??this.bindingStore?.getAcpSessionId(n.adapterSessionId),A=!!(y&&d.use_continue!==!1&&!t);A&&u.push("--resume",y),u.push(this.buildPromptText(n));const c={...process.env,...this.config.env??{}},S=C(this.config.command,typeof c.PATH=="string"?c.PATH:void 0);f.info("cursor-adapter",`job start: event=${s.event_id} session=${s.session_id} retry=${i}`);let p;try{p=T(S,u,{cwd:m||process.cwd(),env:c,stdio:["ignore","pipe","pipe"]}).process}catch(g){this.finishActive(a,"failed",`spawn failed: ${g instanceof Error?g.message:String(g)}`);return}this.callbacks.sendEventAck(s.event_id,s.session_id),this.emit("eventStarted",s.event_id,s.session_id);const h={event:s,request:n,handle:r,child:p,seq:0,done:!1,stderr:"",timer:null,idleTimer:null,toolCallsInFlight:new Set,assistantTextEmitted:"",streamBuffer:"",retryCount:i,usedContinue:A,workspace:m||process.cwd(),args:u};this.activeBySession.set(a,h),this.notifyBindingReady(a),this.armActiveIdleTimer(a);const I=n.timeoutMs&&n.timeoutMs>0?n.timeoutMs:0;I>0&&(h.timer=setTimeout(()=>{h.done||(w(p,"SIGTERM"),this.finishActive(a,"failed",`cursor agent timeout after ${I}ms`))},I)),x({input:p.stdout}).on("line",g=>this.handleStdoutLineForActive(h,g)),p.stderr?.on("data",g=>{const k=h.stderr+String(g??"");h.stderr=k.length>M.STDERR_MAX_CHARS?k.slice(-M.STDERR_MAX_CHARS):k}),p.once("error",g=>{this.finishActive(a,"failed",`spawn failed: ${String(g?.message??g)}`)}),p.once("close",g=>{if(!h.done)if((g??0)===0)this.finishActive(a,"responded");else{if(this.shouldRetryWithoutContinue(h)){h.timer&&clearTimeout(h.timer),h.idleTimer&&clearTimeout(h.idleTimer),this.activeBySession.delete(a),this.startJob(e,!0,h.retryCount+1);return}const k=h.stderr.trim()||`cursor agent exited with code ${g??-1}`;this.finishActive(a,"failed",k)}})}async cancel(e){const t=this.activeBySession.get(e);t&&(w(t.child,"SIGTERM"),this.finishActive(e,"canceled","canceled"))}deliverInboundEvent(e){const t=String(e.session_id??"").trim();if(!t){f.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){f.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 i={adapterSessionId:t,text:me(String(e.content??""),e),contextMessages:ue(e)},s=new F(t),n=this.pendingBySession.get(t)??[];n.push({event:e,request:i,handle:s}),this.pendingBySession.set(t,n),f.info("cursor-adapter",`inbound queued: event=${e.event_id} session=${t} depth=${n.length}`),this.tryStartNext(t)}cancelSessionWork(e,t){const i=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 n of i)this.callbacks.sendEventAck(n.event.event_id,n.event.session_id),this.callbacks.sendEventResult(n.event.event_id,"canceled",t),n.handle.emitDone({status:"canceled",error:t})}killChildWithFallback(e){w(e,"SIGTERM"),setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{w(e,"SIGKILL")}catch{}},5e3).unref()}deliverStopEvent(e,t){if(t){const i=this.activeBySession.get(t);if(i?.event.event_id===e){this.killChildWithFallback(i.child),this.finishActive(t,"canceled","stopped");return}const s=this.pendingBySession.get(t)??[],n=s.findIndex(r=>r.event.event_id===e);if(n>=0){const[r]=s.splice(n,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[i,s]of this.activeBySession.entries())if(s.event.event_id===e){this.killChildWithFallback(s.child),this.finishActive(i,"canceled","stopped");return}for(const[i,s]of this.pendingBySession.entries()){const n=s.findIndex(a=>a.event.event_id===e);if(n<0)continue;const[r]=s.splice(n,1);s.length===0?this.pendingBySession.delete(i):this.pendingBySession.set(i,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(),i=e.params??{},s=String(i.session_id??"").trim(),n=e.action_id;switch(t){case"set_model":{const r=String(i.model_id??"").trim();if(!r||!s)return this.callbacks.sendLocalActionResult(n,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};const a=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...a,modelId:r}),this.notifyBindingReady(s);const o=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(n,"ok",{outcome:"model_set",session_context:{model_id:r,mode_id:o.mode_id,modelId:r,modeId:o.mode_id},model_id:r,mode_id:o.mode_id,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"set_model"}}case"set_mode":{const r=R(i.mode_id);if(!r||!s)return this.callbacks.sendLocalActionResult(n,"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 a=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...a,modeId:r}),this.notifyBindingReady(s);const o=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(n,"ok",{outcome:"mode_set",session_context:{model_id:o.model_id,mode_id:r,modelId:o.model_id,modeId:r},model_id:o.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,a=this.config.options??{},o=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(n,"ok",{session_context:{model_id:o.model_id,mode_id:o.mode_id,cwd:r?.cwd??a.workspace??null},model_id:o.model_id,mode_id:o.mode_id,modelId:o.model_id,modeId:o.mode_id,cwd:r?.cwd??a.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(n,"ok",r),s&&this.notifyBindingReady(s),{handled:!0,kind:"get_rate_limits"}}case"get_session_usage":{const r=s?this.getUsageSnapshot(s):null;return r?this.callbacks.sendLocalActionResult(n,"ok",{adapterType:"cursor",available:!0,sampledAt:r.sampledAt,turns:r.turns,tokenUsage:r.total}):this.callbacks.sendLocalActionResult(n,"ok",{adapterType:"cursor",available:!1,sampledAt:null,turns:0,tokenUsage:null}),{handled:!0,kind:"get_session_usage"}}case"session_control":{const r=String(i.verb??"").trim().toLowerCase();if(r==="restart"&&s)this.cancelSessionWork(s,"restarted"),this.callbacks.sendLocalActionResult(n,"ok",{outcome:"restarted"});else if(r==="status"){const a=this.sessionRuntime.get(s),o=this.config.options??{},d=this.getToolbarMeta(s),u=this.activeBySession.has(s);this.callbacks.sendLocalActionResult(n,"ok",{verb:"status",status:u?"running":"idle",session_context:{model_id:d.model_id,mode_id:d.mode_id,cwd:a?.cwd??o.workspace??null},model_id:d.model_id,mode_id:d.mode_id,modelId:d.model_id,modeId:d.mode_id,cwd:a?.cwd??o.workspace??null,available_models:this.availableModels,available_modes:this.availableModes})}else this.callbacks.sendLocalActionResult(n,"failed",void 0,"invalid_verb",`Unsupported verb: ${r}`);return{handled:!0,kind:"session_control"}}default:return{handled:!1,kind:"unsupported"}}}async execCommand(e,t,i){return e!=="compact"?{status:"unsupported",message:`Unsupported command: ${e}`}:this.runCompactHandoff(i)}async runCompactHandoff(e){if(!e)return{status:"failed",message:"session_id is required"};if(this.activeBySession.has(e))return{status:"failed",message:"Cannot compact while a Cursor turn is active"};const t=this.sessionRuntime.get(e)??{},i=this.config.options??{},s=t.cursorSessionId??this.bindingStore?.getAcpSessionId(e)??null;if(!s)return{status:"failed",message:"No Cursor chat to compact (send a message first)"};const n=String(t.cwd||i.workspace||process.cwd()),r=String(t.modelId||i.model||""),a=R(t.modeId||i.mode)??"full_auto";f.info("cursor-adapter",`[compact] summarize resume=${s} session=${e}`);const o=await this.runPrintOnce({prompt:ne,resumeChatId:s,cwd:n,modelId:r||void 0,modeId:a,timeoutMs:N});if(!o.ok||!o.text.trim())return{status:"failed",message:o.error??"Summarize failed (empty result)"};const d=await this.createEmptyChat();return d?(this.sessionRuntime.set(e,{...t,cwd:n,modelId:r||t.modelId,modeId:a,cursorSessionId:d}),this.bindingStore?.setAcpSessionId(e,d),this.pendingHandoffBySession.set(e,o.text.trim()),this.lastContextBySession.set(e,D(0,O(r))),this.notifyBindingReady(e),f.info("cursor-adapter",`[compact] handoff ready: old=${s} new=${d} summaryChars=${o.text.trim().length}`),{status:"ok",message:"Context compacted via summarize + new chat",data:{previousChatId:s,chatId:d}}):{status:"failed",message:"agent create-chat failed"}}runPrintOnce(e){const t={...process.env,...this.config.env??{}},i=C(this.config.command,typeof t.PATH=="string"?t.PATH:void 0),s=[...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 n=R(e.modeId)??"full_auto";return n==="full_auto"?s.push("--yolo"):n==="plan"&&s.push("--plan"),e.resumeChatId&&s.push("--resume",e.resumeChatId),s.push(e.prompt),new Promise(r=>{let a;try{a=T(i,s,{cwd:e.cwd||process.cwd(),env:t,stdio:["ignore","pipe","pipe"]}).process}catch(c){r({ok:!1,text:"",error:`spawn failed: ${c instanceof Error?c.message:String(c)}`});return}let o="",d="",u="",m=!1;const v=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:N,_=setTimeout(()=>{m||(m=!0,this.killChildWithFallback(a),r({ok:!1,text:o,sessionId:d||void 0,error:`compact timeout after ${v}ms`}))},v);_.unref?.();const y=(c,S)=>{m||(m=!0,clearTimeout(_),r({ok:c,text:o,sessionId:d||void 0,error:S}))};x({input:a.stdout}).on("line",c=>{const S=c.trim();if(!S)return;let p;try{p=JSON.parse(S)}catch{return}if(p?.type!=="result")return;const h=typeof p?.result=="string"?p.result:"";h&&(o=h);const I=String(p?.session_id??"").trim();I&&(d=I)}),a.stderr?.on("data",c=>{u+=typeof c=="string"?c:c.toString("utf8")}),a.on("error",c=>y(!1,c.message)),a.on("close",c=>{if(!m){if(o.trim()){y(!0);return}y(!1,u.trim()||`cursor agent exited with code ${c??"unknown"}`)}})})}createEmptyChat(){const e={...process.env,...this.config.env??{}},t=C(this.config.command,typeof e.PATH=="string"?e.PATH:void 0);return new Promise(i=>{let s;try{s=T(t,["create-chat"],{cwd:process.cwd(),env:e,stdio:["ignore","pipe","pipe"]}).process}catch{i(null);return}let n="",r=!1;const a=setTimeout(()=>{r||(r=!0,this.killChildWithFallback(s),i(null))},3e4);a.unref?.(),s.stdout?.on("data",o=>{n+=typeof o=="string"?o:o.toString("utf8")}),s.on("error",()=>{r||(r=!0,clearTimeout(a),i(null))}),s.on("close",o=>{if(r)return;r=!0,clearTimeout(a);const d=n.trim().split(/\s+/)[0]??"";i(o===0&&/^[0-9a-f-]{16,}$/i.test(d)?d: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 i of this.activeBySession.values()){const s=i.child?.pid;if(s&&!de(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(){this.activeBySession.clear()}getMcpConfig(){return null}async probe(e){const t=this.getStatus();return{...await K(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?ce(e):null;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const i=W(t);return{recordPath:t,lastActivityMs:i.mtimeMs,freshMs:Date.now()-i.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,i=e?this.lastContextBySession.get(e)??null:null;if(!t)return{adapterType:"cursor",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:i,tokenUsage:null};const s=Date.parse(t.sampledAt);return{adapterType:"cursor",available:t.available&&!!t.rateLimits,cached:!0,sampledAt:Number.isFinite(s)?s:Date.now(),rateLimits:t.rateLimits,contextWindow:i,tokenUsage:null,...t.displayMessage?{displayMessage:t.displayMessage}:{},...t.error?{error:t.error}:{}}}async refreshAccountRateLimits(e){const t=e?.force===!0,i=this.cachedAccountRateLimits,s=i?Date.now()-Date.parse(i.sampledAt):Number.POSITIVE_INFINITY;if(!t&&i&&Number.isFinite(s)&&s<6e4||this.rateLimitsInflight&&(await this.rateLimitsInflight,!t))return;const n=(async()=>{const r=await ee();this.cachedAccountRateLimits={available:r.available,sampledAt:r.sampledAt,rateLimits:r.rateLimits,displayMessage:r.displayMessage,error:r.error},r.available&&r.rateLimits?f.info("cursor-adapter",`[rate-limits] monthly=${r.rateLimits.fiveHour.usedPercentage.toFixed(1)}% api=${r.rateLimits.sevenDay.usedPercentage.toFixed(1)}% resetsAt=${r.rateLimits.fiveHour.resetsAt}`+(r.displayMessage?` msg=${r.displayMessage}`:"")):f.warn("cursor-adapter",`[rate-limits] unavailable: ${r.error??"unknown"}`)})();this.rateLimitsInflight=n.finally(()=>{this.rateLimitsInflight=null}),await this.rateLimitsInflight}getToolbarMeta(e){const t=this.config.options??{},i=e||String(t.aibotSessionId??""),s=i?this.sessionRuntime.get(i):void 0,n=String(s?.modelId||t.model||"auto"),r=R(s?.modeId||t.mode)??"full_auto",a={model_id:n,mode_id:r,currentModelId:n,currentModeId:r,available_models:this.availableModels,available_modes:this.availableModes},o=this.cachedAccountRateLimits?.rateLimits;if(o?.fiveHour||o?.sevenDay){const u=Date.parse(this.cachedAccountRateLimits?.sampledAt??"")||Date.now();a.rate_limits={...o.fiveHour?{fiveHour:o.fiveHour}:{},...o.sevenDay?{sevenDay:o.sevenDay}:{},sampledAt:u}}const d=i?this.lastContextBySession.get(i):void 0;return d&&(a.context_window={usedPercentage:d.usedPercentage,remainingPercentage:d.remainingPercentage,usedTokens:d.usedTokens,sizeTokens:d.sizeTokens}),a}notifyBindingReady(e){if(!this.callbacks.sendUpdateBindingCard)return;const t=this.config.options??{},i=e||String(t.aibotSessionId??"");if(!i)return;const s=this.sessionRuntime.get(i),n=String(s?.cwd||t.workspace||"");n&&this.callbacks.sendUpdateBindingCard(i,this.activeBySession.has(i)?"busy":"ready",n,this.getToolbarMeta(i))}buildPromptText(e){let t;!e.contextMessages||e.contextMessages.length===0?t=e.text:t=`${e.contextMessages.map(n=>`[${n.senderId}] ${n.content}`).join(`
|
|
3
5
|
`)}
|
|
4
6
|
|
|
5
7
|
[Current user message]
|
|
6
|
-
${e.text}
|
|
7
|
-
|
|
8
|
-
|
|
8
|
+
${e.text}`;const i=this.pendingHandoffBySession.get(e.adapterSessionId);return i&&(this.pendingHandoffBySession.delete(e.adapterSessionId),t=`[Previous conversation summary \u2014 continue from this handoff]
|
|
9
|
+
${i}
|
|
10
|
+
|
|
11
|
+
[Current user message]
|
|
12
|
+
${t}`),this.identity.injectOnce(e.adapterSessionId,t)}handleStdoutLineForActive(e,t){if(e.done)return;const i=t.trim();if(!i)return;const{event:s}=e;let n;try{n=JSON.parse(i)}catch{this.armActiveIdleTimer(e.request.adapterSessionId);return}if(n?.type==="tool_call"){const o=String(n?.call_id??""),d=String(n?.subtype??"");o&&(d==="started"?(this.flushAssistantStreamBuffer(e),e.toolCallsInFlight.add(o)):j.has(d)&&e.toolCallsInFlight.delete(o))}this.armActiveIdleTimer(e.request.adapterSessionId);const r=ae(n);r&&this.callbacks.sendRawEventEnvelope?.(s.event_id,s.session_id,r);const a=le(n,e.assistantTextEmitted);if(a&&this.enqueueAssistantStreamDelta(e,a),n?.type==="result"){const o=typeof n?.result=="string"?n.result.trim():"";o&&(e.assistantTextEmitted?o.startsWith(e.assistantTextEmitted)&&o.length>e.assistantTextEmitted.length&&this.enqueueAssistantStreamDelta(e,o.slice(e.assistantTextEmitted.length)):this.enqueueAssistantStreamDelta(e,o)),this.flushAssistantStreamBuffer(e);const d=String(n?.session_id??"").trim();if(d){const c=this.sessionRuntime.get(e.request.adapterSessionId)??{};this.sessionRuntime.set(e.request.adapterSessionId,{...c,cursorSessionId:d}),this.bindingStore?.setAcpSessionId(e.request.adapterSessionId,d)}const u=n?.usage??{},m=this.lastUsageBySession.get(e.request.adapterSessionId);this.lastUsageBySession.set(e.request.adapterSessionId,{sampledAt:new Date().toISOString(),turns:(m?.turns??0)+1,total:{input:(m?.total.input??0)+Number(u.inputTokens??0),output:(m?.total.output??0)+Number(u.outputTokens??0),cacheRead:(m?.total.cacheRead??0)+Number(u.cacheReadTokens??0),cacheWrite:(m?.total.cacheWrite??0)+Number(u.cacheWriteTokens??0)}});const v=Number(u.inputTokens??0),_=Number(u.cacheReadTokens??0),y=Number(u.cacheWriteTokens??0),A=[v,_,y].map(c=>Number.isFinite(c)&&c>0?c:0).reduce((c,S)=>c+S,0);if(A>0){const c=String((this.sessionRuntime.get(e.request.adapterSessionId)?.modelId??this.config.options?.model??"")||"");this.lastContextBySession.set(e.request.adapterSessionId,D(A,O(c)))}}}enqueueAssistantStreamDelta(e,t){t&&(e.assistantTextEmitted+=t,e.streamBuffer+=t,e.streamBuffer.length>=ie&&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)}armActiveIdleTimer(e){const t=this.activeBySession.get(e);if(!t||t.done)return;t.idleTimer&&clearTimeout(t.idleTimer);const i=t.toolCallsInFlight.size>0?se:te;t.idleTimer=setTimeout(()=>{t.done||(f.error("cursor-adapter",`Idle timeout (${i/1e3}s, 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 after ${i/1e3}s`))},i),t.idleTimer.unref?.()}finishActive(e,t,i){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 n=String(s.event.quoted_message_id??"").trim()||void 0;this.callbacks.sendStreamChunk(s.event.event_id,s.event.session_id,"",s.seq,!0,void 0,n),f.info("cursor-adapter",`job finish: event=${s.event.event_id} session=${s.event.session_id} status=${t}${i?` msg=${i}`:""}`),this.emit("eventDone",s.event.event_id),this.callbacks.sendEventResult(s.event.event_id,t,i),t==="responded"?s.handle.emitDone({status:"completed"}):t==="canceled"?s.handle.emitDone({status:"canceled",error:i}):s.handle.emitDone({status:"failed",error:i}),this.activeBySession.delete(e),this.notifyBindingReady(e),this.tryStartNext(e)}shouldRetryWithoutContinue(e){if(!e.usedContinue||e.retryCount>0)return!1;const t=e.stderr.toLowerCase(),i=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 i&&s}ensureWorkspaceMcpAndSkills(e){if(!this.internalApi)return;this.ensureCursorMcpConfig(e,this.internalApi.url);const t=b(P(),".cursor","skills"),i=Y(t);i.length>0&&f.info("cursor-adapter",`Synced connector skills to ${t}: [${i.join(", ")}]`)}ensureCursorMcpConfig(e,t){try{const i=b(e,".cursor"),s=b(i,"mcp.json");$(i,{recursive:!0});let n={};try{n=JSON.parse(E(s,"utf8"))}catch{n={}}const r={command:process.execPath,args:[z(J(import.meta.url),"../../../mcp/acp-mcp-server.js"),"--api-url",t]};(!n.mcpServers||typeof n.mcpServers!="object")&&(n.mcpServers={}),n.mcpServers.grix=r,L(s,`${JSON.stringify(n,null,2)}
|
|
13
|
+
`,"utf8"),this.recordCursorMcpRegistry(e,s,r),f.info("cursor-adapter",`MCP config synced: workspace=${e} file=${s}`)}catch(i){f.warn("cursor-adapter",`Failed to ensure .cursor/mcp.json: ${String(i)}`)}}recordCursorMcpRegistry(e,t,i){try{const s=b(G.data,"cursor"),n=b(s,"mcp-registry.json");$(s,{recursive:!0});let r={};try{r=JSON.parse(E(n,"utf8"))}catch{r={}}r[e]={mcp_path:t,server:i,updated_at:new Date().toISOString()},L(n,`${JSON.stringify(r,null,2)}
|
|
14
|
+
`,"utf8")}catch(s){f.warn("cursor-adapter",`Failed to record MCP registry: ${String(s)}`)}}}export{U as CURSOR_MODE_OPTIONS,M as CursorAdapter,le as extractCursorAssistantStreamDelta,ce as findCursorTranscript,ae as mapCursorStreamJsonToRawEnvelope};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{JsonRpcTransport as x}from"../../core/transport/json-rpc.js";import{log as d}from"../../core/log/index.js";import{killProcessGroup as g,resolveCommandPath as h,spawnCommand as w}from"../../core/runtime/spawn.js";const y=3e4,u="none|low|medium|high|xhigh|extra-high|max";function E(o,e){const t=o.trim(),r=e.trim();return t==="default"||t==="default[]"||/^default\[.*\]$/.test(t)?{id:"auto",displayName:!r||r==="default"||r==="Auto"?"Auto (default)":r}:{id:t,displayName:r||t}}function v(o){const e=o.trim();if(!e||e==="auto"||e==="default"||e==="default[]")return"auto";let t=e;return t=t.replace(new RegExp(`-thinking-(?:${u})(?:-fast)?$`),""),t=t.replace(new RegExp(`-(?:${u})-thinking$`),""),t=t.replace(/-thinking(?:-fast)?$/,""),t=t.replace(new RegExp(`-(?:${u})(?:-fast)?$`),""),t=t.replace(/-fast$/,""),t||e}function M(o){let e=o.trim();e=e.replace(/\s*\(default\)\s*$/i,""),e=e.replace(/\s*\(NO ZDR\)\s*$/i,"");const t=/(?:\s+(?:None|Low|Medium|High|Extra High|Max|Fast|Thinking|1M))$/i;for(let r=0;r<8&&t.test(e);r++)e=e.replace(t,"").trim();return e||o.trim()}function T(o){const e=[];for(const t of o.split(`
|
|
2
|
+
`)){const r=t.trim();if(!r||r.toLowerCase().includes("available model")||r.toLowerCase().startsWith("tip:"))continue;const s=r.match(/^(\S+)\s+-\s+(.+)$/);s&&e.push({id:s[1],displayName:s[2].trim()})}return e}function $(o){const e=new Set,t=[];for(const r of o){const s=v(r.id);if(e.has(s))continue;e.add(s);const n=s==="auto"?"Auto (default)":M(r.displayName);t.push({id:s,displayName:n})}return t}async function A(o){return new Promise(e=>{let t="";o.stdout?.on("data",r=>{t+=String(r)}),o.once("close",()=>e(t)),o.once("error",()=>e(t))})}async function I(o){const e={...process.env,...o.env??{}},t=h(o.command,typeof e.PATH=="string"?e.PATH:void 0),{process:r}=w(t,["models"],{cwd:o.cwd??process.cwd(),env:e,stdio:["ignore","pipe","pipe"]}),s=await A(r);return $(T(s))}async function b(o){const e=o.timeoutMs??y,t=o.cwd??process.cwd(),r={...process.env,...o.env??{}},s=h(o.command,typeof r.PATH=="string"?r.PATH:void 0),{process:n}=w(s,["acp"],{cwd:t,env:r,stdio:["pipe","pipe","pipe"]});if(!n.stdout||!n.stdin)throw g(n,"SIGTERM"),new Error("cursor acp spawn missing stdio pipes");const a=new x(n.stdout,n.stdin);a.setHandlers(void 0,(l,m)=>{String(l).startsWith("cursor/")?a.respondSuccess(m,{}):a.respondError(m,-32601,"method not implemented")});const c=new AbortController,C=setTimeout(()=>c.abort(),e),p=l=>{c.abort(l)};n.once("error",p);try{await a.call("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1}},clientInfo:{name:"grix-connector",version:"0"}},c.signal);const f=((await a.call("session/new",{cwd:t,mcpServers:[]},c.signal)).models?.availableModels??[]).filter(i=>typeof i.modelId=="string"&&i.modelId.length>0).map(i=>E(i.modelId,i.name??i.modelId));if(f.length===0)throw new Error("cursor acp session/new returned no models");return f}finally{clearTimeout(C),n.off("error",p);try{a.close()}catch{}g(n,"SIGTERM")}}async function L(o){try{const e=await b(o);return d.info("cursor-adapter",`Loaded ${e.length} parameterized models via acp`),e}catch(e){const t=e instanceof Error?e.message:String(e);d.warn("cursor-adapter",`ACP model probe failed, falling back to collapsed CLI models: ${t}`)}try{const e=await I(o);return e.length>0&&d.info("cursor-adapter",`Loaded ${e.length} collapsed models via CLI fallback`),e}catch(e){const t=e instanceof Error?e.message:String(e);return d.warn("cursor-adapter",`CLI model fallback failed: ${t}`),[]}}export{M as collapseCursorDisplayName,v as collapseCursorModelId,$ as collapseExplodedCursorModels,I as fetchCollapsedModelsFromCli,L as fetchCursorParameterizedModels,b as fetchCursorParameterizedModelsViaAcp,E as normalizeCursorAvailableModel,T as parseExplodedCursorModels};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{execFile as f}from"node:child_process";import{homedir as p,platform as d}from"node:os";import{join as y}from"node:path";import{promisify as b}from"node:util";const u=b(f),g="https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage";function m(e){return Number.isFinite(e)?Math.max(0,Math.min(100,e)):0}function h(e){if(e==null||e==="")return 0;const t=typeof e=="number"?e:Number(String(e).trim());return!Number.isFinite(t)||t<=0?0:t>1e12?Math.floor(t/1e3):Math.floor(t)}function k(e){const t=e.planUsage;if(!t||typeof t!="object")return null;const r=h(e.billingCycleEnd);if(r<=0)return null;const i=m(Number(t.totalPercentUsed??0)),a=t.apiPercentUsed,s=t.autoPercentUsed,c=m(Number(a!=null&&Number.isFinite(Number(a))?a:s??0));return{fiveHour:{usedPercentage:i,resetsAt:r},sevenDay:{usedPercentage:c,resetsAt:r}}}async function S(){if(d()!=="darwin")return null;try{const{stdout:e}=await u("security",["find-generic-password","-s","cursor-access-token","-a","cursor-user","-w"],{timeout:5e3,encoding:"utf8"});return String(e??"").trim()||null}catch{return null}}async function M(){const e=y(p(),"Library","Application Support","Cursor","User","globalStorage","state.vscdb");try{const{stdout:t}=await u("sqlite3",[e,"SELECT value FROM ItemTable WHERE key = 'cursorAuth/accessToken' LIMIT 1;"],{timeout:5e3,encoding:"utf8"});return String(t??"").trim()||null}catch{return null}}async function v(){const e=await S();return e||M()}async function w(e){const t=new Date().toISOString(),r=e&&Object.prototype.hasOwnProperty.call(e,"token")?e.token??null:await v();if(!r)return{available:!1,rateLimits:null,sampledAt:t,error:"no_cursor_access_token"};const i=e?.fetchImpl??fetch,a=e?.timeoutMs??12e3,s=new AbortController,c=setTimeout(()=>s.abort(),a);try{const n=await i(g,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","Connect-Protocol-Version":"1","x-cursor-client-type":"cli"},body:"{}",signal:s.signal});if(!n.ok)return{available:!1,rateLimits:null,sampledAt:t,error:`http_${n.status}`};const o=await n.json(),l=k(o);return l?{available:!0,rateLimits:l,sampledAt:t,displayMessage:o.displayMessage}:{available:!1,rateLimits:null,sampledAt:t,displayMessage:o.displayMessage,error:"plan_usage_unavailable"}}catch(n){const o=n instanceof Error?n.message:String(n);return{available:!1,rateLimits:null,sampledAt:t,error:o.includes("abort")?"timeout":o}}finally{clearTimeout(c)}}export{w as fetchCursorAccountUsage,k as mapCursorPeriodUsageToRateLimits,v as readCursorAccessToken};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CursorAdapter as
|
|
1
|
+
import{CursorAdapter as e,CURSOR_MODE_OPTIONS as s,extractCursorAssistantStreamDelta as a,mapCursorStreamJsonToRawEnvelope as t}from"./cursor-adapter.js";import{collapseCursorDisplayName as d,collapseCursorModelId as C,collapseExplodedCursorModels as u,fetchCursorParameterizedModels as p,normalizeCursorAvailableModel as i,parseExplodedCursorModels as m}from"./fetch-models.js";import{fetchCursorAccountUsage as n,mapCursorPeriodUsageToRateLimits as x,readCursorAccessToken as f}from"./fetch-usage.js";import{buildCursorContextWindow as A,resolveCursorContextWindowSize as S}from"./context-window.js";export{s as CURSOR_MODE_OPTIONS,e as CursorAdapter,A as buildCursorContextWindow,d as collapseCursorDisplayName,C as collapseCursorModelId,u as collapseExplodedCursorModels,a as extractCursorAssistantStreamDelta,n as fetchCursorAccountUsage,p as fetchCursorParameterizedModels,x as mapCursorPeriodUsageToRateLimits,t as mapCursorStreamJsonToRawEnvelope,i as normalizeCursorAvailableModel,m as parseExplodedCursorModels,f as readCursorAccessToken,S as resolveCursorContextWindowSize};
|