grix-connector 3.15.0 → 3.15.1

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.
@@ -1,5 +1,5 @@
1
- import{spawn as $}from"node:child_process";import{randomUUID as k}from"node:crypto";import{EventEmitter as I}from"node:events";import{existsSync as E,readFileSync as _,readdirSync as b,statSync as w,mkdirSync as x,writeFileSync as C,realpathSync as L}from"node:fs";import{homedir as f}from"node:os";import{join as p,dirname as R,resolve as T}from"node:path";import{fileURLToPath as j}from"node:url";import{log as o}from"../../core/log/index.js";import{killProcessGroup as g}from"../../core/runtime/spawn.js";import{InternalApiServer as G}from"../../core/mcp/internal-api-server.js";import{syncDefaultSkillsToDir as M}from"../../default-skills/index.js";import{buildSimpleProbeReport as O}from"../shared/probe-util.js";const a="agy-adapter";function D(y){try{return L(y)}catch{return y}}const m=p(f(),".gemini","antigravity-cli","log"),A=p(f(),".gemini","antigravity-cli","cache","last_conversations.json"),N=["\u4F60\u63A5\u5165\u7684\u662F Grix \u804A\u5929\u3002\u7528\u6237\u6D88\u606F\u88AB\u5305\u5728 <channel ...> \u6807\u7B7E\u91CC\uFF0C\u6807\u7B7E\u5C5E\u6027\u643A\u5E26\u672C\u8F6E\u4E0A\u4E0B\u6587\uFF1A","chat_id\uFF08\u5F53\u524D\u4F1A\u8BDD\uFF09\u3001event_id\uFF08\u672C\u8F6E\u4E8B\u4EF6\uFF09\u3001message_id\uFF08\u7528\u6237\u8FD9\u6761\u6D88\u606F\u7684 ID\uFF09\u3001user_id\uFF08\u53D1\u9001\u8005\uFF09\u3002","\u91CD\u8981\uFF1A\u4F60\u7684\u56DE\u590D\u5FC5\u987B\u8C03\u7528 grix \u7684 `grix_message_send` \u5DE5\u5177\u53D1\u9001\uFF08sessionId \u53D6\u81EA channel \u7684 chat_id\uFF0Ccontent \u4E3A\u4F60\u7684\u56DE\u590D\u5185\u5BB9\uFF09\uFF0C","\u4E0D\u8981\u53EA\u628A\u7B54\u6848\u6253\u5370\u5230\u6807\u51C6\u8F93\u51FA\u2014\u2014\u53EA\u6709\u8C03\u7528\u5DE5\u5177\u624D\u4F1A\u628A\u6D88\u606F\u771F\u6B63\u53D1\u7ED9\u7528\u6237\u3002","grix_message_send \u4F1A\u8FD4\u56DE\u4F60\u521A\u53D1\u51FA\u6D88\u606F\u7684 msg_id\u3002\u9700\u8981\u65F6\u4F60\u53EF\u4EE5\u7528\u8FD9\u4E2A ID \u505A\u540E\u7EED\u64CD\u4F5C\uFF0C\u4F8B\u5982\u8C03\u7528 grix_message_unsend\uFF08\u4F20 msgId\uFF09\u64A4\u56DE\u67D0\u6761\u6D88\u606F\u3002"].join(""),B=new Set(["send_msg","grix_reply"]),Q=new Set(["send_msg","grix_reply","delete_msg","session_send","grix_complete","grix_composing","grix_event_ack"]);class tt extends I{type="agy";config;callbacks;runtimeResolver;alive=!1;stopped=!1;internalApi=null;activeEventId=null;activeEventSessionId=null;activeProcess=null;completedEventIds=new Set;activeEventSentViaTool=!1;sessionConversationMap=new Map;conversationOutputCache=new Map;eventQueue=[];constructor(t,e,s){super(),this.config=t,this.callbacks=e,this.runtimeResolver=s}async start(){this.alive||(this.alive=!0,this.stopped=!1,await this.startInternalApiAndInjectMcp(),o.info(a,"AgyAdapter started"))}async startInternalApiAndInjectMcp(){try{this.internalApi=new G,this.internalApi.setInvokeHandler(async(r,l,h,u)=>this.handleToolInvoke(r,l,u)),await this.internalApi.start(0),o.info(a,`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=p(f(),".gemini","config","mcp_config.json");x(R(e),{recursive:!0});let s={};try{E(e)&&(s=JSON.parse(_(e,"utf8")))}catch{}const i=s.mcpServers&&typeof s.mcpServers=="object"?s.mcpServers:{};i[t.name]={command:t.command,args:t.args},s.mcpServers=i,C(e,`${JSON.stringify(s,null,2)}
2
- `,"utf8"),o.info(a,`MCP config injected into ${e}`);const n=p(f(),".gemini","skills"),c=M(n);c.length>0&&o.info(a,`Synced connector skills to ${n}: [${c.join(", ")}]`)}catch(t){o.warn(a,`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async handleToolInvoke(t,e,s){let i=e;Q.has(t)&&this.activeEventSessionId&&(i.session_id==null||i.session_id==="")&&(i={...i,session_id:this.activeEventSessionId});const n=await this.callbacks.agentInvoke(t,i,s);return B.has(t)&&this.activeEventId&&(this.activeEventSentViaTool=!0),n}async stop(){if(!this.stopped){if(this.stopped=!0,this.alive=!1,this.activeProcess){try{g(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null}if(this.activeEventId&&this.activeEventSessionId)try{this.callbacks.sendEventResult(this.activeEventId,"canceled","adapter stopped")}catch{}if(this.activeEventId=null,this.activeEventSessionId=null,this.internalApi){try{await this.internalApi.stop()}catch{}this.internalApi=null}this.emit("exit",0),o.info(a,"AgyAdapter stopped")}}isAlive(){return this.alive}async createSession(t){return t.cwd??k()}async resumeSession(t,e){}async destroySession(t){}sendPrompt(t){const e=new I;return e.adapterSessionId=t.adapterSessionId,e.cancel=async()=>{e.emit("done",{status:"canceled"})},e}async cancel(t){}cancelCurrentRun(){if(!this.activeEventId||!this.activeProcess)return;const t=this.activeEventId;o.info(a,`cancelCurrentRun: killing process group for event ${t}`);try{g(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null,this.callbacks.sendEventResult(t,"canceled","restarted by user"),this.clearActiveEvent(t),this.drainQueue()}deliverInboundEvent(t){if(!this.stopped){if(this.completedEventIds.has(t.event_id)){o.debug(a,`Skipping duplicate event: ${t.event_id}`);return}if(this.callbacks.sendEventAck(t.event_id,t.session_id),this.activeEventId){o.info(a,`Queuing event ${t.event_id} (active: ${this.activeEventId})`),this.eventQueue.push(t);return}this.processEvent(t)}}deliverStopEvent(t,e){if(this.activeEventId===t&&this.activeProcess){o.info(a,`Stopping event ${t}`);try{g(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null,this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActiveEvent(t),this.drainQueue()}}setPermissionHandler(){}async ping(t){return this.alive}getStatus(){return{alive:this.alive,busy:this.activeEventId!==null,sessions:this.sessionConversationMap.size}}async probe(t){const e=this.getStatus();return O(this.config.command||"agy",{alive:e.alive,busy:e.busy,started:e.alive},t)}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}clearActiveEventForShutdown(){if(this.activeProcess)try{g(this.activeProcess,"SIGKILL")}catch{}this.activeEventId=null,this.activeEventSessionId=null,this.activeProcess=null,this.activeEventSentViaTool=!1}getMcpConfig(){if(!this.internalApi)return null;const t=T(j(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}processEvent(t){const{event_id:e,session_id:s}=t,i=this.runtimeResolver(s);if(!i.cwd){o.warn(a,`No working directory for session ${s}, event should have been intercepted by bridge`),this.callbacks.forceCompleteInternalEvent(e,s);return}this.activeEventId=e,this.activeEventSessionId=s,this.activeEventSentViaTool=!1,this.emit("eventStarted",e,s),o.info(a,`Processing event ${e} for session ${s}`);const n=this.buildAgyPrompt(t);this.spawnAgyPrint(e,s,n,i)}buildAgyPrompt(t){const s=[["chat_id",t.session_id],["event_id",t.event_id],["message_id",t.msg_id],["user_id",t.sender_id],["quoted_message_id",t.quoted_message_id]].filter(([,l])=>l!=null&&l!=="").map(([l,h])=>`${l}="${h}"`).join(" "),i=this.renderContextBlock(t),n=i?`${i}
1
+ import{spawn as $}from"node:child_process";import{randomUUID as k}from"node:crypto";import{EventEmitter as I}from"node:events";import{existsSync as E,readFileSync as _,readdirSync as b,statSync as w,mkdirSync as x,writeFileSync as C,realpathSync as L}from"node:fs";import{homedir as g}from"node:os";import{join as p,dirname as R,resolve as T}from"node:path";import{fileURLToPath as j}from"node:url";import{log as o}from"../../core/log/index.js";import{killProcessGroup as f}from"../../core/runtime/spawn.js";import{InternalApiServer as G}from"../../core/mcp/internal-api-server.js";import{syncDefaultSkillsToDir as M}from"../../default-skills/index.js";import{buildSimpleProbeReport as O}from"../shared/probe-util.js";const a="agy-adapter";function D(y){try{return L(y)}catch{return y}}const m=p(g(),".gemini","antigravity-cli","log"),A=p(g(),".gemini","antigravity-cli","cache","last_conversations.json"),N=["\u4F60\u63A5\u5165\u7684\u662F Grix \u804A\u5929\u3002\u7528\u6237\u6D88\u606F\u88AB\u5305\u5728 <channel ...> \u6807\u7B7E\u91CC\uFF0C\u6807\u7B7E\u5C5E\u6027\u643A\u5E26\u672C\u8F6E\u4E0A\u4E0B\u6587\uFF1A","chat_id\uFF08\u5F53\u524D\u4F1A\u8BDD\uFF09\u3001event_id\uFF08\u672C\u8F6E\u4E8B\u4EF6\uFF09\u3001message_id\uFF08\u7528\u6237\u8FD9\u6761\u6D88\u606F\u7684 ID\uFF09\u3001user_id\uFF08\u53D1\u9001\u8005\uFF09\u3002","\u91CD\u8981\uFF1A\u4F60\u7684\u56DE\u590D\u5FC5\u987B\u8C03\u7528 grix \u7684 `grix_message_send` \u5DE5\u5177\u53D1\u9001\uFF08sessionId \u53D6\u81EA channel \u7684 chat_id\uFF0Ccontent \u4E3A\u4F60\u7684\u56DE\u590D\u5185\u5BB9\uFF09\uFF0C","\u4E0D\u8981\u53EA\u628A\u7B54\u6848\u6253\u5370\u5230\u6807\u51C6\u8F93\u51FA\u2014\u2014\u53EA\u6709\u8C03\u7528\u5DE5\u5177\u624D\u4F1A\u628A\u6D88\u606F\u771F\u6B63\u53D1\u7ED9\u7528\u6237\u3002","grix_message_send \u4F1A\u8FD4\u56DE\u4F60\u521A\u53D1\u51FA\u6D88\u606F\u7684 msg_id\u3002\u9700\u8981\u65F6\u4F60\u53EF\u4EE5\u7528\u8FD9\u4E2A ID \u505A\u540E\u7EED\u64CD\u4F5C\uFF0C\u4F8B\u5982\u8C03\u7528 grix_message_unsend\uFF08\u4F20 msgId\uFF09\u64A4\u56DE\u67D0\u6761\u6D88\u606F\u3002"].join(""),B=new Set(["send_msg","grix_reply"]),Q=new Set(["send_msg","grix_reply","delete_msg","session_send","grix_complete","grix_composing","grix_event_ack"]);class tt extends I{type="agy";config;callbacks;runtimeResolver;alive=!1;stopped=!1;internalApi=null;activeEventId=null;activeEventSessionId=null;activeProcess=null;completedEventIds=new Set;activeEventSentViaTool=!1;sessionConversationMap=new Map;conversationOutputCache=new Map;eventQueue=[];constructor(t,e,s){super(),this.config=t,this.callbacks=e,this.runtimeResolver=s}async start(){this.alive||(this.alive=!0,this.stopped=!1,await this.startInternalApiAndInjectMcp(),o.info(a,"AgyAdapter started"))}async startInternalApiAndInjectMcp(){try{this.internalApi=new G,this.internalApi.setInvokeHandler(async(r,l,h,u)=>this.handleToolInvoke(r,l,u)),await this.internalApi.start(0),o.info(a,`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=p(g(),".gemini","config","mcp_config.json");x(R(e),{recursive:!0});let s={};try{E(e)&&(s=JSON.parse(_(e,"utf8")))}catch{}const i=s.mcpServers&&typeof s.mcpServers=="object"?s.mcpServers:{};i[t.name]={command:t.command,args:t.args},s.mcpServers=i,C(e,`${JSON.stringify(s,null,2)}
2
+ `,"utf8"),o.info(a,`MCP config injected into ${e}`);const n=p(g(),".gemini","skills"),c=M(n);c.length>0&&o.info(a,`Synced connector skills to ${n}: [${c.join(", ")}]`)}catch(t){o.warn(a,`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async handleToolInvoke(t,e,s){let i=e;Q.has(t)&&this.activeEventSessionId&&(i.session_id==null||i.session_id==="")&&(i={...i,session_id:this.activeEventSessionId});const n=await this.callbacks.agentInvoke(t,i,s);return B.has(t)&&this.activeEventId&&(this.activeEventSentViaTool=!0),n}async stop(){if(!this.stopped){if(this.stopped=!0,this.alive=!1,this.activeProcess){try{f(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null}if(this.activeEventId&&this.activeEventSessionId)try{this.callbacks.sendEventResult(this.activeEventId,"canceled","adapter stopped")}catch{}if(this.activeEventId=null,this.activeEventSessionId=null,this.internalApi){try{await this.internalApi.stop()}catch{}this.internalApi=null}this.emit("exit",0),o.info(a,"AgyAdapter stopped")}}isAlive(){return this.alive}async createSession(t){return t.cwd??k()}async resumeSession(t,e){}async destroySession(t){}sendPrompt(t){const e=new I;return e.adapterSessionId=t.adapterSessionId,e.cancel=async()=>{e.emit("done",{status:"canceled"})},e}async cancel(t){}cancelCurrentRun(){if(!this.activeEventId||!this.activeProcess)return;const t=this.activeEventId;o.info(a,`cancelCurrentRun: killing process group for event ${t}`);try{f(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null,this.callbacks.sendEventResult(t,"canceled","restarted by user"),this.clearActiveEvent(t),this.drainQueue()}deliverInboundEvent(t){if(!this.stopped){if(this.completedEventIds.has(t.event_id)){o.debug(a,`Skipping duplicate event: ${t.event_id}`);return}if(this.callbacks.sendEventAck(t.event_id,t.session_id),this.activeEventId){o.info(a,`Queuing event ${t.event_id} (active: ${this.activeEventId})`),this.eventQueue.push(t);return}this.processEvent(t)}}deliverStopEvent(t,e){if(this.activeEventId===t&&this.activeProcess){o.info(a,`Stopping event ${t}`);try{f(this.activeProcess,"SIGKILL")}catch{}this.activeProcess=null,this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActiveEvent(t),this.drainQueue()}}setPermissionHandler(){}async ping(t){return this.alive}getStatus(){return{alive:this.alive,busy:this.activeEventId!==null,sessions:this.sessionConversationMap.size}}async probe(t){const e=this.getStatus();return O(this.config.command||"agy",{alive:e.alive,busy:e.busy,started:e.alive},t)}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}clearActiveEventForShutdown(){if(this.activeProcess)try{f(this.activeProcess,"SIGKILL")}catch{}this.activeEventId=null,this.activeEventSessionId=null,this.activeProcess=null,this.activeEventSentViaTool=!1}getMcpConfig(){if(!this.internalApi)return null;const t=T(j(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}processEvent(t){const{event_id:e,session_id:s}=t,i=this.runtimeResolver(s);if(!i.cwd){o.warn(a,`No working directory for session ${s}, event should have been intercepted by bridge`),this.callbacks.forceCompleteInternalEvent(e,s);return}this.activeEventId=e,this.activeEventSessionId=s,this.activeEventSentViaTool=!1,this.emit("eventStarted",e,s),o.info(a,`Processing event ${e} for session ${s}`);const n=this.buildAgyPrompt(t);this.spawnAgyPrint(e,s,n,i)}buildAgyPrompt(t){const s=[["chat_id",t.session_id],["event_id",t.event_id],["message_id",t.msg_id],["user_id",t.sender_id],["quoted_message_id",t.quoted_message_id]].filter(([,l])=>l!=null&&l!=="").map(([l,h])=>`${l}="${h}"`).join(" "),i=this.renderContextBlock(t),n=i?`${i}
3
3
 
4
4
  ${t.content}`:t.content,c=`<channel source="grix-agy" ${s}>
5
5
  ${n}
@@ -10,4 +10,4 @@ ${c}`}buildIdentityBlock(){const t=this.callbacks.getAgentProfile?.(),e=t?.agent
10
10
 
11
11
  `}renderContextBlock(t){const e=t.context_messages_json;if(!e)return"";let s;try{const r=JSON.parse(e);if(!Array.isArray(r))return"";s=r}catch{return""}const i=String(t.session_type??"")==="2",n=String(t.msg_id??""),c=[];for(const r of s){const l=String(r?.msg_id??"");if(l&&l===n)continue;const h=String(r?.content??"").trim();if(!h)continue;const u=String(r?.sender_id??"");if(h.startsWith("[\u5F15\u7528\u6D88\u606F]")){const d=h.slice(6).replace(/^\s*\n?/,"").trim();c.push(i&&u?`[\u5F15\u7528\u6D88\u606F] (\u6765\u81EA ${u})\uFF1A${d}`:`[\u5F15\u7528\u6D88\u606F]\uFF1A${d}`)}else c.push(i&&u?`[${u}]\uFF1A${h}`:h)}return c.join(`
12
12
  `)}spawnAgyPrint(t,e,s,i){const n=this.buildPrintArgs(s,i),c={...process.env,...this.config.env??{}};o.info(a,`Spawning: agy ${n.map(d=>d.includes(" ")?`"${d}"`:d).join(" ")}`);const r=this.getLatestLogFilePath(),l=$(this.config.command,n,{cwd:i.cwd,env:c,stdio:["pipe","pipe","pipe"],detached:!0});this.activeProcess=l;const h=[],u=[];l.stdout?.on("data",d=>{h.push(d)}),l.stderr?.on("data",d=>{u.push(d)}),l.on("error",d=>{o.error(a,`Process spawn error for event ${t}: ${d.message}`),this.handleProcessResult(t,e,"",`spawn error: ${d.message}`,i)}),l.on("close",d=>{if(o.info(a,`Process exited for event ${t} with code ${d}`),this.activeEventId!==t)return;const v=Buffer.concat(h).toString("utf-8"),P=Buffer.concat(u).toString("utf-8");if(d!==0){const S=P.trim()||`process exited with code ${d}`;this.handleProcessResult(t,e,v,S,i)}else v.trim()?this.handleProcessResult(t,e,v,"",i):this.activeEventSentViaTool?this.handleProcessResult(t,e,v,"",i):setTimeout(()=>{const S=this.extractLogError(r);this.handleProcessResult(t,e,v,S,i)},300)}),l.stdin?.end()}buildPrintArgs(t,e){const s=[];return e.modelId&&s.push("--model",e.modelId),e.cwd&&s.push("--add-dir",e.cwd),s.push("--dangerously-skip-permissions"),e.conversationId&&s.push("--conversation",e.conversationId),s.push("-p",t),s}readAgyConversationId(t){try{if(E(A)){const e=JSON.parse(_(A,"utf-8"));return e[D(t)]||e[t]||void 0}}catch(e){o.debug(a,`readAgyConversationId: ${e}`)}}getLatestLogFilePath(){try{if(!E(m))return null;const t=b(m).filter(e=>e.startsWith("cli-")&&e.endsWith(".log")).map(e=>({name:e,path:p(m,e),mtime:w(p(m,e)).mtimeMs})).sort((e,s)=>s.mtime-e.mtime);return t.length>0?t[0].path:null}catch{return null}}extractLogError(t){try{const e=this.getLatestLogFilePath();if(!e)return o.info(a,"extractLogError: no log files found"),"agy completed without output";const s=_(e,"utf-8");if(!s)return o.info(a,`extractLogError: log file is empty: ${e}`),"agy completed without output";const i=s.split(`
13
- `).filter(n=>n.startsWith("E")).map(n=>{const c=n.indexOf("] ");return c>=0?n.slice(c+2):n}).filter(n=>n.length>0);if(i.length>0){const n=i[i.length-1];return o.info(a,`Extracted error from agy log: ${n.slice(0,120)}`),n.length>500?n.slice(0,500)+"...":n}return"agy completed without output (possible auth or quota issue)"}catch(e){return o.info(a,`extractLogError: ${e}`),"agy completed without output"}}handleProcessResult(t,e,s,i,n){if(this.activeEventId===t){if(i&&!s.trim()){o.error(a,`Event ${t} failed: ${i}`);const r=i.includes("RESOURCE_EXHAUSTED")||i.includes("quota")?"The agy API quota has been exhausted. Please try again later.":`agy execution failed: ${i}`;this.callbacks.sendStreamChunk(t,e,r,1,!0),this.callbacks.sendEventResult(t,"failed",i)}else{const c=s.trim();if(c){const r=n.cwd,l=r?this.extractDelta(c,r):c;r&&this.conversationOutputCache.set(r,c),l&&!this.activeEventSentViaTool&&this.callbacks.sendStreamChunk(t,e,l,1,!0)}if(n.cwd){const r=this.readAgyConversationId(n.cwd);r&&r!==n.conversationId&&(this.sessionConversationMap.set(e,r),this.callbacks.persistConversationId(e,r))}this.callbacks.sendEventResult(t,"responded")}this.clearActiveEvent(t),this.drainQueue()}}extractDelta(t,e){const s=this.conversationOutputCache.get(e);return s&&t.startsWith(s)?t.slice(s.length).trim():t}clearActiveEvent(t){const e=t??this.activeEventId;if(e&&(this.completedEventIds.add(e),this.completedEventIds.size>1e3)){const s=Array.from(this.completedEventIds);this.completedEventIds.clear();for(let i=500;i<s.length;i++)this.completedEventIds.add(s[i])}this.activeEventId=null,this.activeEventSessionId=null,this.activeProcess=null,this.activeEventSentViaTool=!1,e&&this.emit("eventDone",e)}drainQueue(){if(this.stopped||this.activeEventId)return;const t=this.eventQueue.shift();t&&(o.info(a,`Draining queued event ${t.event_id}`),this.processEvent(t))}}export{tt as AgyAdapter};
13
+ `).filter(n=>n.startsWith("E")).map(n=>{const c=n.indexOf("] ");return c>=0?n.slice(c+2):n}).filter(n=>n.length>0);if(i.length>0){const n=i[i.length-1];return o.info(a,`Extracted error from agy log: ${n.slice(0,120)}`),n.length>500?n.slice(0,500)+"...":n}return"agy completed without output (possible auth or quota issue)"}catch(e){return o.info(a,`extractLogError: ${e}`),"agy completed without output"}}handleProcessResult(t,e,s,i,n){if(this.activeEventId===t){if(i&&!s.trim()){o.error(a,`Event ${t} failed: ${i}`);const r=i.includes("RESOURCE_EXHAUSTED")||i.includes("quota")?"The agy API quota has been exhausted. Please try again later.":`agy execution failed: ${i}`;this.callbacks.sendStreamChunk(t,e,r,1,!0,`agy-${t}`),this.callbacks.sendEventResult(t,"failed",i)}else{const c=s.trim();if(c){const r=n.cwd,l=r?this.extractDelta(c,r):c;r&&this.conversationOutputCache.set(r,c),l&&!this.activeEventSentViaTool&&this.callbacks.sendStreamChunk(t,e,l,1,!0,`agy-${t}`)}if(n.cwd){const r=this.readAgyConversationId(n.cwd);r&&r!==n.conversationId&&(this.sessionConversationMap.set(e,r),this.callbacks.persistConversationId(e,r))}this.callbacks.sendEventResult(t,"responded")}this.clearActiveEvent(t),this.drainQueue()}}extractDelta(t,e){const s=this.conversationOutputCache.get(e);return s&&t.startsWith(s)?t.slice(s.length).trim():t}clearActiveEvent(t){const e=t??this.activeEventId;if(e&&(this.completedEventIds.add(e),this.completedEventIds.size>1e3)){const s=Array.from(this.completedEventIds);this.completedEventIds.clear();for(let i=500;i<s.length;i++)this.completedEventIds.add(s[i])}this.activeEventId=null,this.activeEventSessionId=null,this.activeProcess=null,this.activeEventSentViaTool=!1,e&&this.emit("eventDone",e)}drainQueue(){if(this.stopped||this.activeEventId)return;const t=this.eventQueue.shift();t&&(o.info(a,`Draining queued event ${t.event_id}`),this.processEvent(t))}}export{tt as AgyAdapter};
@@ -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 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
+ import c from"node:http";import{randomUUID as d}from"node:crypto";import{log as o}from"../../core/log/index.js";function l(t){t.writeHead(401,{"content-type":"application/json"}),t.end(JSON.stringify({error:"unauthorized"}))}function u(t){t.writeHead(404,{"content-type":"application/json"}),t.end(JSON.stringify({error:"not_found"}))}function h(t,e){t.writeHead(400,{"content-type":"application/json"}),t.end(JSON.stringify({error:e}))}function p(t,e={ok:!0}){t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify(e))}async function v(t){const e=[];for await(const n of t)e.push(n);const r=Buffer.concat(e).toString("utf8").trim();return r?JSON.parse(r):{}}function k(t){const e=(t.headers.authorization??"").trim();return e.toLowerCase().startsWith("bearer ")?e.slice(7).trim():""}class w{host="127.0.0.1";port=0;token;callbacks;server=null;address=null;constructor(e){this.token=d(),this.callbacks=e}getToken(){return this.token}getURL(){return this.address?`http://${this.address.address}:${this.address.port}`:""}async start(){this.server||(this.server=c.createServer(async(e,r)=>{try{await this.handleRequest(e,r)}catch(n){h(r,n instanceof Error?n.message:String(n))}}),await new Promise((e,r)=>{this.server.once("error",r),this.server.listen(this.port,this.host,()=>{this.server.off("error",r),e()})}),this.address=this.server.address(),o.info("claude-bridge",`Bridge server listening on ${this.getURL()}`))}async stop(){if(!this.server)return;const e=this.server;this.server=null,this.address=null,e.closeIdleConnections?.(),e.closeAllConnections?.(),await new Promise((r,n)=>{e.close(s=>s?n(s):r())})}async handleRequest(e,r){if(k(e)!==this.token){l(r);return}if(e.method!=="POST"){r.writeHead(405,{"content-type":"application/json"}),r.end(JSON.stringify({error:"method_not_allowed"}));return}const n=new URL(e.url,"http://localhost").pathname,s=await v(e),i=f.get(n);if(!i){u(r);return}const a=await i(this.callbacks,s);p(r,a??{ok:!0})}}const f=new Map([["/v1/worker/register",async(t,e)=>(o.info("claude-bridge",`Worker registered: ${e.worker_id} (pid=${e.pid})`),t.onRegisterWorker(e))],["/v1/worker/status",async(t,e)=>(o.info("claude-bridge",`Worker status: ${e.status}`),t.onStatusUpdate(e))],["/v1/worker/send-text",async(t,e)=>t.onSendText(e)],["/v1/worker/send-stream-chunk",async(t,e)=>t.onSendStreamChunk(e)],["/v1/worker/send-media",async(t,e)=>t.onSendMedia(e)],["/v1/worker/delete-message",async(t,e)=>t.onDeleteMessage(e)],["/v1/worker/ack-event",async(t,e)=>t.onAckEvent(e)],["/v1/worker/event-result",async(t,e)=>t.onSendEventResult(e)],["/v1/worker/event-stop-ack",async(t,e)=>t.onSendEventStopAck(e)],["/v1/worker/event-stop-result",async(t,e)=>t.onSendEventStopResult(e)],["/v1/worker/session-composing",async(t,e)=>t.onSetSessionComposing(e)],["/v1/worker/agent-invoke",async(t,e)=>t.onAgentInvoke(e)],["/v1/worker/local-action-result",async(t,e)=>t.onLocalActionResult(e)]]);export{w as ClaudeBridgeServer};
@@ -1 +1 @@
1
- import{randomUUID as x}from"node:crypto";import{CallToolRequestSchema as S,ListToolsRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{log as f}from"../../core/log/index.js";import{toolCallToInvoke as k}from"../../core/mcp/tools.js";const E=new Set(["contact_search","session_search","message_history","message_search","group_create","group_detail_read","group_leave_self","group_member_add","group_member_remove","group_member_role_update","group_all_members_muted_update","group_member_speaking_update","group_dissolve","send_msg","delete_msg","agent_api_create","agent_category_list","agent_category_create","agent_category_update","agent_category_assign","agent_api_key_rotate"]),y=3e4,I=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},files:{type:"array",items:{type:"string"},description:"Optional absolute local file paths. Each file is uploaded through Agent API OSS presign before sending."},final:{type:"boolean",description:"Whether this is the final reply for the event. Defaults to false \u2014 the event stays open while Claude continues working, and auto-completes after inactivity. Set true only when this is definitively the last message for the event."}},required:["chat_id","event_id"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},code:{type:"string"},msg:{type:"string"}},required:["event_id","status"]}},{name:"delete_message",description:"Delete a previously sent message in the same grix-claude chat.",inputSchema:{type:"object",properties:{chat_id:{type:"string"},message_id:{type:"string"}},required:["chat_id","message_id"]}},{name:"status",description:"Show grix-claude runtime status, upstream access state, bridge health, and startup hints.",inputSchema:{type:"object",properties:{}}},{name:"send",description:"Send a message to a chat session proactively, without requiring an inbound event. Use for notifications or scheduled reports.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The target chat/session id."},text:{type:"string",description:"The message text to send."}},required:["chat_id","text"]}},{name:"access_pair",description:"Forward a sender pairing approval code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"access_deny",description:"Forward a sender pairing denial code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"allow_sender",description:"Ask upstream access control to allow a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"remove_sender",description:"Ask upstream access control to remove a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"access_policy",description:"Ask upstream access control to update the sender access policy.",inputSchema:{type:"object",properties:{policy:{type:"string",enum:["allowlist","open","disabled"]}},required:["policy"]}},{name:"grix_query",description:"Search contacts, sessions, message history, or messages by keyword in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},keyword:{type:"string"},id:{type:"string"},sessionId:{type:"string"},limit:{type:"number"},offset:{type:"number"},beforeId:{type:"string"}},required:["action"]}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string"},memberIds:{type:"array",items:{type:"string"}},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer",description:"Member type (for update_member_role / update_member_speaking)."},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted (for update_member_speaking)."}},required:["action"]}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},content:{type:"string"},msgType:{type:"number"},quotedMessageId:{type:"string"},threadId:{type:"string"}},required:["sessionId","content"]}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},msgId:{type:"string"}},required:["sessionId","msgId"]}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentId:{type:"string"},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"number"}},required:["action"]}}];function q(r,e){r.setRequestHandler(w,async()=>({tools:I})),r.setRequestHandler(S,async i=>{const{name:n,arguments:t}=i.params,s=t??{};try{switch(n){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(n,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(n,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${n}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${n} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(r,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const n=String(r.text??""),t=String(r.chat_id??""),s=String(r.event_id??i.eventId),a=r.reply_to,d=r.files,_=r.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!n.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,n),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(r,e){const i=e.getActiveEvent(),n=String(r.event_id??""),t=r.status??"",s=r.code,a=r.msg;if(!n||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(n)?(e.bridge.sendEventResult(n,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(r,e){const i=String(r.chat_id??""),n=String(r.message_id??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:n},y),c(`deleted (${n})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(r){const e=r.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(r,e){const i=String(r.chat_id??""),n=String(r.text??"");if(!i||!n)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(n),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(r,e,i){try{const n=C[r];if(!n)throw new Error(`Unknown access control tool: ${r}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:n.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}async function O(r,e,i){try{const n=k(r,e);if(!E.has(n.action))throw new Error(`Action not allowed: ${n.action}`);const t=await i.bridge.agentInvoke(n.action,n.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(n){return{content:[{type:"text",text:`${r} failed: ${n}`}],isError:!0}}}function c(r){return{content:[{type:"text",text:r}]}}export{q as registerClaudeTools};
1
+ import{randomUUID as x}from"node:crypto";import{CallToolRequestSchema as S,ListToolsRequestSchema as w}from"@modelcontextprotocol/sdk/types.js";import{log as f}from"../../core/log/index.js";import{toolCallToInvoke as k}from"../../core/mcp/tools.js";const E=new Set(["contact_search","session_search","message_history","message_search","group_create","group_detail_read","group_leave_self","group_member_add","group_member_remove","group_member_role_update","group_all_members_muted_update","group_member_speaking_update","group_dissolve","send_msg","delete_msg","agent_api_create","agent_category_list","agent_category_create","agent_category_update","agent_category_assign","agent_api_key_rotate"]),y=3e4,I=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},files:{type:"array",items:{type:"string"},description:"Optional absolute local file paths. Each file is uploaded through Agent API OSS presign before sending."},final:{type:"boolean",description:"Whether this is the final reply for the event. Defaults to false \u2014 the event stays open while Claude continues working, and auto-completes after inactivity. Set true only when this is definitively the last message for the event."}},required:["chat_id","event_id"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},code:{type:"string"},msg:{type:"string"}},required:["event_id","status"]}},{name:"delete_message",description:"Delete a previously sent message in the same grix-claude chat.",inputSchema:{type:"object",properties:{chat_id:{type:"string"},message_id:{type:"string"}},required:["chat_id","message_id"]}},{name:"status",description:"Show grix-claude runtime status, upstream access state, bridge health, and startup hints.",inputSchema:{type:"object",properties:{}}},{name:"send",description:"Send a message to a chat session proactively, without requiring an inbound event. Use for notifications or scheduled reports.",inputSchema:{type:"object",properties:{chat_id:{type:"string",description:"The target chat/session id."},text:{type:"string",description:"The message text to send."}},required:["chat_id","text"]}},{name:"access_pair",description:"Forward a sender pairing approval code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"access_deny",description:"Forward a sender pairing denial code to upstream access control.",inputSchema:{type:"object",properties:{code:{type:"string"}},required:["code"]}},{name:"allow_sender",description:"Ask upstream access control to allow a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"remove_sender",description:"Ask upstream access control to remove a sender_id.",inputSchema:{type:"object",properties:{sender_id:{type:"string"}},required:["sender_id"]}},{name:"access_policy",description:"Ask upstream access control to update the sender access policy.",inputSchema:{type:"object",properties:{policy:{type:"string",enum:["allowlist","open","disabled"]}},required:["policy"]}},{name:"grix_query",description:"Search contacts, sessions, message history, or messages by keyword in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},keyword:{type:"string"},id:{type:"string"},sessionId:{type:"string"},limit:{type:"number"},offset:{type:"number"},beforeId:{type:"string"}},required:["action"]}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string"},memberIds:{type:"array",items:{type:"string"}},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer",description:"Member type (for update_member_role / update_member_speaking)."},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted (for update_member_speaking)."}},required:["action"]}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},content:{type:"string"},msgType:{type:"number"},quotedMessageId:{type:"string"},threadId:{type:"string"}},required:["sessionId","content"]}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string"},msgId:{type:"string"}},required:["sessionId","msgId"]}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentId:{type:"string"},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"number"}},required:["action"]}}];function q(n,e){n.setRequestHandler(w,async()=>({tools:I})),n.setRequestHandler(S,async i=>{const{name:r,arguments:t}=i.params,s=t??{};try{switch(r){case"reply":return await A(s,e);case"complete":return await $(s,e);case"delete_message":return await T(s,e);case"status":return j(e);case"send":return await M(s,e);case"access_pair":case"access_deny":case"allow_sender":case"remove_sender":case"access_policy":return await R(r,s,e);case"grix_query":case"grix_group":case"grix_message_send":case"grix_message_unsend":case"grix_admin":return await O(r,s,e);default:return{content:[{type:"text",text:`Unknown tool: ${r}`}],isError:!0}}}catch(a){return f.error("claude-tools",`Tool ${r} error: ${a}`),{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}})}async function A(n,e){const i=e.getActiveEvent();if(!i)return{content:[{type:"text",text:"No active event to reply to"}],isError:!0};const r=String(n.text??""),t=String(n.chat_id??""),s=String(n.event_id??i.eventId),a=n.reply_to,d=n.files,_=n.final===!0;if(!t||!s)return{content:[{type:"text",text:"reply requires chat_id and event_id"}],isError:!0};if(!r.trim()&&(!d||d.length===0))return{content:[{type:"text",text:"reply requires at least one of text or files"}],isError:!0};const{text:g,quotedMessageId:v}=e.resolveQuotedMessageId(a,r),b=[];let m=0;const h=`reply_${s}_${Date.now()}`;try{if(g){const p=e.splitText(g);for(let o=0;o<p.length;o++){if(!e.isEventActive(s))return c("ignored: event no longer active");m++,e.bridge.sendStreamChunk(s,t,p[o],++i.chunkSeq,!1,h)}}if(d&&d.length>0)for(const p of d){if(!e.isEventActive(s))return c("ignored: event no longer active");m++;const o=await e.uploadFile(p,t),l=`${x()}_${m}`;e.bridge.sendMedia(s,t,o.access_url,o.file_name,v,l,o.extra),f.info("claude-tools",`File sent: ${o.file_name}`)}e.bridge.sendStreamChunk(s,t,"",++i.chunkSeq,!0,h)}catch(p){if(g&&b.length===0)try{const o=`fallback_${s}_${Date.now()}`,l=e.splitText(g);for(let u=0;u<l.length;u++)e.bridge.sendStreamChunk("",t,l[u],u+1,!1,o);return e.bridge.sendStreamChunk("",t,"",l.length+1,!0,o),e.markReplySent(s),_&&e.finalizeEvent(s,"responded"),c("sent via fallback")}catch{}if(!e.isEventActive(s))return c("ignored: event no longer active");throw e.bridge.sendEventResult(s,"failed",String(p),"send_msg_failed"),p}return e.markReplySent(s),_?e.finalizeEvent(s,"responded"):(i.responded=!0,e.clearActiveEvent("completed")),c("Reply sent")}async function $(n,e){const i=e.getActiveEvent(),r=String(n.event_id??""),t=n.status??"",s=n.code,a=n.msg;if(!r||!t)return{content:[{type:"text",text:"complete requires event_id and status"}],isError:!0};const d=["responded","canceled","failed"];return d.includes(t)?e.isEventActive(r)?(e.bridge.sendEventResult(r,t,a,s),e.clearActiveEvent(t),c("Event completed")):c("ignored: event no longer active"):{content:[{type:"text",text:`status must be one of: ${d.join(", ")}`}],isError:!0}}async function T(n,e){const i=String(n.chat_id??""),r=String(n.message_id??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and message_id are required"}],isError:!0};try{return await e.bridge.agentInvoke("grix_message_unsend",{sessionId:i,msgId:r},y),c(`deleted (${r})`)}catch(t){return{content:[{type:"text",text:`Delete failed: ${t}`}],isError:!0}}}function j(n){const e=n.getStatusInfo();return{content:[{type:"text",text:JSON.stringify({alive:e.alive,active_event:e.activeEvent,pending_approvals:e.pendingPermissions,pending_questions:e.pendingElicitations})}]}}async function M(n,e){const i=String(n.chat_id??""),r=String(n.text??"");if(!i||!r)return{content:[{type:"text",text:"chat_id and text are required"}],isError:!0};try{const t=e.splitText(r),s=`send_${i}_${Date.now()}`;for(let a=0;a<t.length;a++)e.bridge.sendStreamChunk("",i,t[a],a+1,!1,s);return e.bridge.sendStreamChunk("",i,"",t.length+1,!0,s),c("sent")}catch(t){return{content:[{type:"text",text:`Send failed: ${t}`}],isError:!0}}}const C={access_pair:{verb:"pair_approve",payloadKey:"code"},access_deny:{verb:"pair_deny",payloadKey:"code"},allow_sender:{verb:"sender_allow",payloadKey:"sender_id"},remove_sender:{verb:"sender_remove",payloadKey:"sender_id"},access_policy:{verb:"policy_set",payloadKey:"policy"}};async function R(n,e,i){try{const r=C[n];if(!r)throw new Error(`Unknown access control tool: ${n}`);const t={};e.code!=null&&(t.code=e.code),e.sender_id!=null&&(t.sender_id=e.sender_id),e.policy!=null&&(t.policy=e.policy);const s=await i.bridge.agentInvoke("claude_access_control",{verb:r.verb,payload:t},y);return{content:[{type:"text",text:typeof s=="string"?s:JSON.stringify(s)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}async function O(n,e,i){try{const r=k(n,e);if(!E.has(r.action))throw new Error(`Action not allowed: ${r.action}`);const t=await i.bridge.agentInvoke(r.action,r.params,y);if(t&&Number(t.code??0)!==0)throw new Error(String(t.msg??"invoke failed"));return{content:[{type:"text",text:t?.data!=null?typeof t.data=="string"?t.data:JSON.stringify(t.data):JSON.stringify(t)}]}}catch(r){return{content:[{type:"text",text:`${n} failed: ${r}`}],isError:!0}}}function c(n){return{content:[{type:"text",text:n}]}}export{q as registerClaudeTools};
@@ -1 +1 @@
1
- import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(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
+ import{log as l}from"../../core/log/index.js";class c{controlURL="";token="";isConfigured(){return!!(this.controlURL&&this.token)}configure(t,e){this.controlURL=t.replace(/\/+$/,""),this.token=e.trim(),l.info("claude-worker-client",`Configured with control URL: ${this.controlURL}`)}async post(t,e,s){if(!this.isConfigured())throw new Error("worker control not configured");const i=new AbortController,o=setTimeout(()=>i.abort(),s);try{const r=await fetch(`${this.controlURL}${t}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.token}`},body:JSON.stringify(e),signal:i.signal}),n=await r.text(),a=n.trim()?JSON.parse(n):{};if(!r.ok)throw new Error(a.error||`worker control failed ${r.status}`);return a}finally{clearTimeout(o)}}isRetryableError(t){const e=t instanceof Error?t.message:String(t);return/fetch failed|network|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|aborted/i.test(e)}async postWithRetry(t,e,s,i=1){let o;for(let r=0;r<=i;r++)try{return r>0&&l.info("claude-worker-client",`Retrying ${t} attempt=${r+1}`),await this.post(t,e,s)}catch(n){if(o=n,r>=i||!this.isRetryableError(n))break;await new Promise(a=>setTimeout(a,150))}throw o instanceof Error?o:new Error(String(o))}async deliverEvent(t){return this.postWithRetry("/v1/worker/deliver-event",{payload:t},1e4,1)}async deliverStop(t){return this.postWithRetry("/v1/worker/deliver-stop",{payload:t},1e4,1)}async deliverLocalAction(t){return this.postWithRetry("/v1/worker/deliver-local-action",{payload:t},1e4,1)}async ping(){try{return await this.postWithRetry("/v1/worker/ping",{},5e3,1),!0}catch{return!1}}}export{c as ClaudeWorkerClient};
@@ -1,2 +1,2 @@
1
- import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as 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
+ import{spawn as x,execSync as y}from"node:child_process";import{randomUUID as v}from"node:crypto";import{mkdir as S}from"node:fs/promises";import{readFileSync as C}from"node:fs";import{join as d}from"node:path";import{homedir as T,tmpdir as I}from"node:os";import{log as o}from"../../core/log/index.js";import{MCP_HTTP_CHANNEL_NAME as l}from"./protocol-contract.js";function P(e){let t=null,r=0,n=!1,i=!1;const a=v(),s=e.gatewayUrl??"http://127.0.0.1:19580/mcp";return{async start(){await F(e.command,s,e.env);const c=E(e.grix),u=[...e.args??[],"--name",`grix-mcp-${e.name}`,"--session-id",a];e.fullAuto&&u.push("--dangerously-skip-permissions"),u.push("--dangerously-load-development-channels",`server:${l}`,"--append-system-prompt",c);const f=d(I(),`grix-mcp-claude-${e.name}`);await S(f,{recursive:!0});const{expectPath:$,pidPath:g}=await M(f,e.command,u),_={...process.env,...e.env??{}};t=x("/usr/bin/expect",[$],{cwd:e.cwd,env:_,stdio:["ignore","pipe","pipe"],detached:!0}),o.info("mcp-http-launcher",`\u542F\u52A8 Claude: name=${e.name} cwd=${e.cwd} pid=${t.pid}`),r=await k(g),n=!0,o.info("mcp-http-launcher",`Claude \u5B50\u8FDB\u7A0B PID: ${r}`),t.on("exit",(m,p)=>{o.info("mcp-http-launcher",`Claude \u9000\u51FA: code=${m} signal=${p}`),n=!1,t=null,r=0,i||(o.info("mcp-http-launcher","3 \u79D2\u540E\u81EA\u52A8\u91CD\u542F..."),setTimeout(()=>{i||this.start().catch(w=>{o.error("mcp-http-launcher",`\u91CD\u542F\u5931\u8D25: ${w}`)})},3e3))}),t.stdout?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stdout] ${p.slice(0,300)}`)}),t.stderr?.on("data",m=>{const p=m.toString().trim();p&&o.info("mcp-http-launcher",`[stderr] ${p.slice(0,300)}`)})},async stop(){if(i=!0,n=!1,r>0)try{process.kill(r,"SIGTERM")}catch{}if(t?.pid){try{process.kill(-t.pid,"SIGTERM")}catch{}await new Promise(c=>{const u=setTimeout(()=>{if(r>0)try{process.kill(r,"SIGKILL")}catch{}if(t?.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}c()},5e3);t?.once("exit",()=>{clearTimeout(u),c()})})}t=null,r=0},getStatus(){return{name:e.name,alive:n,pid:r}}}}function E(e){return["You are connected to a chat via the grix MCP server.",`On startup, immediately call grix_authorize with: agentId="${e.agentId}", apiKey="${e.apiKey}", wsUrl="${e.wsUrl}", clientType="${e.clientType}".`,"When you receive a <channel> message, you MUST respond by calling the grix_reply tool (or the grix_complete tool if no response is needed).","Never write your reply as plain text \u2014 it will NOT reach the user. Only the grix_reply tool delivers your response to the chat.","The <channel> message contains event_id and session_id \u2014 pass them to grix_reply."].join(" ")}async function F(e,t,r){const n=d(T(),".claude.json");let i=null;try{const s=C(n,"utf8");i=JSON.parse(s)?.mcpServers?.[l]??null}catch{}if(i&&String(i.type??"").trim()==="http"&&String(i.url??"").trim()===t)return;o.info("mcp-http-launcher",`\u6CE8\u518C MCP Server: ${l} -> ${t}`);const a={...process.env,...r??{}};try{y(`${e} mcp remove -s user ${l}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}catch{}y(`${e} mcp add --scope user --transport http ${l} ${t}`,{encoding:"utf8",timeout:1e4,env:a,stdio:"pipe"})}async function M(e,t,r){const{writeFile:n}=await import("node:fs/promises"),i=d(e,"claude.pid"),a=d(e,"claude.expect"),s=["log_user 1","set timeout -1","set startup_prompt_armed 1",`set claude_command [list {${h(t)}}${r.map(c=>` {${h(c)}}`).join("")}]`,"spawn -noecho {*}$claude_command",`set pid_file [open {${h(i)}} w]`,"puts $pid_file [exp_pid -i $spawn_id]","close $pid_file","expect {"," -re {(?i)(Quick.*safety.*check|trust.*folder)} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)I am using this for local development} {",' if {$startup_prompt_armed} { send -- "1\\r"; after 300 }; exp_continue'," }"," -re {(?i)(Enter.*confirm|Press.*Enter|Hit.*Enter)} {",' if {$startup_prompt_armed} { send -- "\\r"; after 300 }; exp_continue'," }"," -re {Listening for channel} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," -re {bypass permissions} {"," set startup_prompt_armed 0"," after 1000",' send -- "Call grix_authorize now as instructed in your system prompt.\\r"'," }"," eof {}","}","expect eof",""];return await n(i,"","utf8"),await n(a,s.join(`
2
+ `),"utf8"),{expectPath:a,pidPath:i}}function h(e){return e.replace(/[\\{}$\[\]"]/g,"\\$&")}async function k(e,t=1e4){const{readFile:r}=await import("node:fs/promises"),n=Math.ceil(t/100);for(let i=0;i<n;i++){try{const a=await r(e,"utf8"),s=parseInt(String(a).trim(),10);if(Number.isFinite(s)&&s>0)return s}catch{}await new Promise(a=>setTimeout(a,100))}return 0}export{P as createMcpHttpLauncher};
@@ -1 +1 @@
1
- class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(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
+ class m{defaultTimeoutMs;onTimeout;timers=new Map;constructor(t){this.defaultTimeoutMs=t.defaultTimeoutMs??9e4,this.onTimeout=t.onTimeout}arm(t,e){this.cancel(t);const s=e?.timeoutMs??this.defaultTimeoutMs,i=Date.now()+s,o=setTimeout(()=>{this.timers.delete(t),this.onTimeout(t).catch(()=>{})},s);return this.timers.set(t,o),i}cancel(t){const e=this.timers.get(t);e&&(clearTimeout(e),this.timers.delete(t))}has(t){return this.timers.has(t)}close(){for(const t of this.timers.values())clearTimeout(t);this.timers.clear()}}export{m as ResultTimeoutManager};
@@ -1,2 +1,2 @@
1
- import{readdirSync as y,readFileSync as g,existsSync as d,statSync as b}from"node:fs";import{dirname as F,join as r,resolve as O}from"node:path";import{homedir as W}from"node:os";import{log as A}from"../../core/log/index.js";const D=".grix-managed";function x(t){const e=t.trim();if(!e.startsWith("---"))return{name:"",description:""};const i=e.indexOf("---",3);if(i===-1)return{name:"",description:""};const n=e.slice(3,i).trim();let s="",c="",u;for(const f of n.split(`
2
- `)){const a=f.indexOf(":");if(a===-1)continue;const p=f.slice(0,a).trim();let o=f.slice(a+1).trim();(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))&&(o=o.slice(1,-1)),p==="name"?s=o:p==="description"?c=o:p==="trigger"&&(u=o)}return{name:s,description:c,trigger:u}}function L(t,e,i){if(!d(t))return[];const n=[];try{for(const s of y(t,{withFileTypes:!0})){const c=r(t,s.name);if(!S(s,c)||s.name.startsWith("."))continue;const u=r(c,"SKILL.md");if(d(u))try{const f=g(u,"utf-8"),a=x(f);a.name&&n.push({name:a.name,description:a.description,trigger:a.trigger,source:e,pluginName:i,filePath:u,managed:d(r(c,D))})}catch{}}}catch{}return n}function l(t,e,i){if(!d(t))return[];const n=i?.maxDepth??6,s=i?.includeHiddenDirs??!1,c=[],u=(f,a)=>{if(a>n)return;let p;try{p=y(f,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(const o of p){const m=r(f,o.name);if(!S(o,m)||!s&&o.name.startsWith("."))continue;const h=r(m,"SKILL.md");if(d(h))try{const w=g(h,"utf-8"),k=x(w);k.name&&c.push({name:k.name,description:k.description,trigger:k.trigger,source:e,pluginName:i?.pluginName,filePath:h,managed:d(r(m,D))})}catch{}u(m,a+1)}};return u(t,0),c}function j(t){return t.map(e=>({...e,managed:!0}))}function S(t,e){if(t.isDirectory())return!0;if(!t.isSymbolicLink())return!1;try{return b(e).isDirectory()}catch{return!1}}function M(t){const e=[],i=new Set;for(const n of t){const s=n.name.trim().toLowerCase();i.has(s)||(i.add(s),e.push(n))}return e}function N(t){const e=[],i=new Set;let n=O(t);for(;;){i.has(n)||(e.push(n),i.add(n));const s=F(n);if(s===n)break;n=s}return e}function P(t){const e=r(t,".claude","plugins","installed_plugins.json");if(!d(e))return[];const i=[];try{const n=g(e,"utf-8"),c=JSON.parse(n)?.plugins;if(!c||typeof c!="object")return i;for(const[u,f]of Object.entries(c))if(Array.isArray(f))for(const a of f){const p=a?.installPath;if(!p||!d(p))continue;const o=r(p,"skills"),m=u.split("@")[0],h=j(L(o,"plugin",m));i.push(...h)}}catch{}return i}function K(t,e){return t==="claude"?"claude":t==="codex"?"codex":t==="pi"?"pi":e==="kiro"?"kiro":"gemini"}function _(t){const e=[],i=t.homeDir??W();switch(t.mode){case"claude":{const s=r(i,".claude","skills");e.push(...l(s,"global")),t.projectDir&&e.push(...l(r(t.projectDir,".claude","skills"),"project")),e.push(...P(i));break}case"codex":{const s=process.env.CODEX_HOME?.trim()||r(i,".codex");if(t.projectDir)for(const c of N(t.projectDir))e.push(...l(r(c,".agents","skills"),"project")),e.push(...l(r(c,".codex","skills"),"project"));e.push(...l(r(i,".agents","skills"),"codex")),e.push(...l(r(s,"skills"),"codex")),e.push(...j(l(r(s,"skills",".system"),"codex")));break}case"gemini":{e.push(...l(r(i,".gemini","skills"),"gemini")),e.push(...l(r(i,".agents","skills"),"gemini")),t.projectDir&&(e.push(...l(r(t.projectDir,".gemini","skills"),"project")),e.push(...l(r(t.projectDir,".agents","skills"),"project")));break}case"pi":{e.push(...l(r(i,".pi","agent","skills"),"pi")),t.projectDir&&e.push(...l(r(t.projectDir,".pi","skills"),"project"));break}case"kiro":{e.push(...l(r(i,".kiro","skills"),"kiro")),t.projectDir&&e.push(...l(r(t.projectDir,".kiro","skills"),"project"));break}}const n=M(e);return A.info("skill-scanner",`Scanned skills: mode=${t.mode} count=${n.length}`),n}export{D as MANAGED_MARKER,M as dedupeSkills,j as markManaged,x as parseSkillFrontmatter,K as resolveSkillScanMode,l as scanSkillTree,_ as scanSkills};
1
+ import{readdirSync as D,readFileSync as g,existsSync as d,statSync as S}from"node:fs";import{dirname as O,join as t,resolve as F}from"node:path";import{homedir as L}from"node:os";import{log as M}from"../../core/log/index.js";const j=".grix-managed";function x(r){const e=r.trim();if(!e.startsWith("---"))return{name:"",description:""};const i=e.indexOf("---",3);if(i===-1)return{name:"",description:""};const n=e.slice(3,i).trim();let s="",o="",u;for(const p of n.split(`
2
+ `)){const a=p.indexOf(":");if(a===-1)continue;const f=p.slice(0,a).trim();let l=p.slice(a+1).trim();(l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'"))&&(l=l.slice(1,-1)),f==="name"?s=l:f==="description"?o=l:f==="trigger"&&(u=l)}return{name:s,description:o,trigger:u}}function C(r,e,i){if(!d(r))return[];const n=[];try{for(const s of D(r,{withFileTypes:!0})){const o=t(r,s.name);if(!b(s,o)||s.name.startsWith("."))continue;const u=t(o,"SKILL.md");if(d(u))try{const p=g(u,"utf-8"),a=x(p);a.name&&n.push({name:a.name,description:a.description,trigger:a.trigger,source:e,pluginName:i,filePath:u,managed:d(t(o,j))})}catch{}}}catch{}return n}function c(r,e,i){if(!d(r))return[];const n=i?.maxDepth??6,s=i?.includeHiddenDirs??!1,o=[],u=(p,a)=>{if(a>n)return;let f;try{f=D(p,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(const l of f){const m=t(p,l.name);if(!b(l,m)||!s&&l.name.startsWith("."))continue;const h=t(m,"SKILL.md");if(d(h))try{const w=g(h,"utf-8"),k=x(w);k.name&&o.push({name:k.name,description:k.description,trigger:k.trigger,source:e,pluginName:i?.pluginName,filePath:h,managed:d(t(m,j))})}catch{}u(m,a+1)}};return u(r,0),o}function y(r){return r.map(e=>({...e,managed:!0}))}function b(r,e){if(r.isDirectory())return!0;if(!r.isSymbolicLink())return!1;try{return S(e).isDirectory()}catch{return!1}}function E(r){const e=[],i=new Set;for(const n of r){const s=n.name.trim().toLowerCase();i.has(s)||(i.add(s),e.push(n))}return e}function H(r){const e=[],i=new Set;let n=F(r);for(;;){i.has(n)||(e.push(n),i.add(n));const s=O(n);if(s===n)break;n=s}return e}function I(r){const e=t(r,".claude","plugins","installed_plugins.json");if(!d(e))return[];const i=[];try{const n=g(e,"utf-8"),o=JSON.parse(n)?.plugins;if(!o||typeof o!="object")return i;for(const[u,p]of Object.entries(o))if(Array.isArray(p))for(const a of p){const f=a?.installPath;if(!f||!d(f))continue;const l=t(f,"skills"),m=u.split("@")[0],h=y(C(l,"plugin",m));i.push(...h)}}catch{}return i}function N(r,e){const i=(r??"").trim().toLowerCase(),n=(e??"").trim().toLowerCase();return i==="claude"?"claude":i==="codex"?"codex":i==="pi"?"pi":i==="cursor"?"cursor":i==="codewhale"?"codewhale":i==="opencode"?"opencode":i==="agy"?"gemini":i==="openhuman"?"none":n==="kiro"?"kiro":n==="qwen"?"qwen":n==="reasonix"?"reasonix":n==="kimi"?"kimi":n==="hermes"||n==="copilot"?"none":"gemini"}function q(r){const e=[],i=r.homeDir??L();switch(r.mode){case"claude":{const s=t(i,".claude","skills");e.push(...c(s,"global")),r.projectDir&&e.push(...c(t(r.projectDir,".claude","skills"),"project")),e.push(...I(i));break}case"codex":{const s=process.env.CODEX_HOME?.trim()||t(i,".codex");if(r.projectDir)for(const o of H(r.projectDir))e.push(...c(t(o,".agents","skills"),"project")),e.push(...c(t(o,".codex","skills"),"project"));e.push(...c(t(i,".agents","skills"),"codex")),e.push(...c(t(s,"skills"),"codex")),e.push(...y(c(t(s,"skills",".system"),"codex")));break}case"gemini":{e.push(...c(t(i,".gemini","skills"),"gemini")),e.push(...c(t(i,".agents","skills"),"gemini")),r.projectDir&&(e.push(...c(t(r.projectDir,".gemini","skills"),"project")),e.push(...c(t(r.projectDir,".agents","skills"),"project")));break}case"pi":{e.push(...c(t(i,".pi","agent","skills"),"pi")),r.projectDir&&e.push(...c(t(r.projectDir,".pi","skills"),"project"));break}case"kiro":{e.push(...c(t(i,".kiro","skills"),"kiro")),r.projectDir&&e.push(...c(t(r.projectDir,".kiro","skills"),"project"));break}case"qwen":{e.push(...c(t(i,".qwen","skills"),"global")),r.projectDir&&e.push(...c(t(r.projectDir,".qwen","skills"),"project"));break}case"cursor":{e.push(...c(t(i,".cursor","skills"),"global")),r.projectDir&&e.push(...c(t(r.projectDir,".cursor","skills"),"project"));break}case"codewhale":{e.push(...c(t(i,".codewhale","skills"),"global")),r.projectDir&&e.push(...c(t(r.projectDir,".codewhale","skills"),"project"));break}case"opencode":{const s=process.env.XDG_CONFIG_HOME?.trim()||t(i,".config");e.push(...c(t(s,"opencode","skills"),"global"));break}case"reasonix":{e.push(...c(t(i,".reasonix","skills"),"global"));break}case"kimi":{const s=process.env.KIMI_CODE_HOME?.trim()||t(i,".kimi-code");e.push(...c(t(s,"skills"),"global"));break}case"none":break}const n=E(e);return M.info("skill-scanner",`Scanned skills: mode=${r.mode} count=${n.length}`),n}export{j as MANAGED_MARKER,E as dedupeSkills,y as markManaged,x as parseSkillFrontmatter,N as resolveSkillScanMode,c as scanSkillTree,q as scanSkills};
@@ -1 +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
+ const f=2e5,_=1e6;function r(e){const s=Number(e??0);return Number.isFinite(s)&&s>0?s:0}function d(e,s={}){const n=r(e.inputTokens),t=r(e.cacheReadTokens),c=r(e.cacheWriteTokens),i=n+t+c;if(i<=0)return 0;const o=Math.max(n,t)+c;let u=i;n>1e4&&t>1e4&&i>o*1.5&&(u=o);const a=r(s.windowSize)||2e5,T=Math.max(1,Math.floor(r(s.apiRounds)||1));return T>1&&u>a*1.2&&(u=Math.ceil(u/T)),u>a&&(u=a),u}function m(e,s=0){const n=String(e??"").trim();let t=2e5;if(!n||/^auto$/i.test(n))t=1e6;else if(/context\s*=\s*1m\b/i.test(n))t=1e6;else if(/context\s*=\s*(\d+)k\b/i.test(n)){const i=n.match(/context\s*=\s*(\d+)k\b/i),o=Number(i?.[1]??0);Number.isFinite(o)&&o>0&&(t=o*1e3)}else if(/context\s*=\s*(\d+)\b/i.test(n)){const i=n.match(/context\s*=\s*(\d+)\b/i),o=Number(i?.[1]??0);Number.isFinite(o)&&o>=1e4&&(t=o)}return r(s)>t&&t<1e6&&(t=1e6),t}function N(e,s){const n=Math.max(0,Number.isFinite(e)?e:0),t=Math.max(1,Number.isFinite(s)&&s>0?s:2e5),c=Math.min(n,t),i=Math.min(100,c/t*100);return{usedPercentage:i,remainingPercentage:Math.max(0,100-i),usedTokens:c,sizeTokens:t}}function x(e,s,n={}){const t=r(e.inputTokens)+r(e.cacheReadTokens)+r(e.cacheWriteTokens);if(t<=0)return null;const c=m(s,t),i=d(e,{apiRounds:n.apiRounds,windowSize:c});return i<=0?null:N(i,c)}export{N as buildCursorContextWindow,x as buildCursorContextWindowFromUsage,d as estimateCursorContextTokens,m as resolveCursorContextWindowSize};
@@ -1,14 +1,20 @@
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(`
1
+ import{createInterface as x}from"node:readline";import{EventEmitter as B}from"node:events";import{randomUUID as z}from"node:crypto";import{mkdirSync as $,readFileSync as q,writeFileSync as L,readdirSync as J,statSync as G}from"node:fs";import{join as b,resolve as X}from"node:path";import{fileURLToPath as K}from"node:url";import{homedir as E}from"node:os";import{GRIX_PATHS as Y,log as u}from"../../core/log/index.js";import{IdentityInjector as V}from"../shared/identity-injector.js";import{buildSimpleProbeReport as Z}from"../shared/probe-util.js";import{InternalApiServer as ee}from"../../core/mcp/internal-api-server.js";import{syncDefaultSkillsToDir as te}from"../../default-skills/index.js";import{resolveCommandPath as R,spawnCommand as T,killProcessGroup as w}from"../../core/runtime/spawn.js";import{SessionBindingStore as se}from"../../core/persistence/session-binding-store.js";import{fetchCursorParameterizedModels as ne}from"./fetch-models.js";import{fetchCursorAccountUsage as ie}from"./fetch-usage.js";import{buildCursorContextWindow as re,buildCursorContextWindowFromUsage as oe,resolveCursorContextWindowSize as ae}from"./context-window.js";const le=12e4,P=300*1e3,de=6e5,ce=8192,ue="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.",D=12e4,N=new Set(["completed","failed","error","errored","canceled","cancelled","rejected"]);function me(l){const e=l.replace(/ToolCall$/i,"").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):l||"tool"}function O(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:me(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 j(l){return String(l??"").trim().toLowerCase().replace(/[^a-z0-9]/g,"")}function U(l){const e=j(l);return e==="askquestion"||e==="askuserquestion"}function Q(l){const e=j(l);return e==="createplan"||e==="exitplanmode"}function he(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 fe(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 a=r,o=t||`Question ${i+1}`,d=String(a.header??a.id??a.question??o).trim()||o,c=String(a.prompt??a.question??"").trim();if(!c)continue;const h=he(a.options),S=a.multiSelect===!0||a.multi_select===!0;s.push({header:d,prompt:c,...h?{options:h}:{},...S?{multi_select:!0}:{}})}return s.length>0?s:null}function pe(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(`
3
2
 
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
+ `)}function ge(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=O(e);return U(s.toolName)||Q(s.toolName)?null:n==="started"||n==="start"?{type:"tool_call",payload:{tool_name:s.toolName,...s.callId?{tool_call_id:s.callId}:{}}}:(N.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 ye(l,e){if(!l||typeof l!="object"||Array.isArray(l))return"";const t=l;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,i=s&&typeof s=="object"&&!Array.isArray(s)?s.content:void 0;if(!Array.isArray(i))return"";const r=i.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 F=[{id:"approval",displayName:"\u4EBA\u5DE5\u786E\u8BA4"},{id:"full_auto",displayName:"\u81EA\u7531\u6A21\u5F0F"},{id:"plan",displayName:"\u8BA1\u5212\u6A21\u5F0F"}];function C(l){const e=String(l??"").trim().toLowerCase();return F.some(t=>t.id===e)?e:null}function Se(l){try{return process.kill(l,0),!0}catch(e){return e.code==="EPERM"}}function W(l,e,t){if(t<0)return null;let n;try{n=J(l,{withFileTypes:!0})}catch{return null}for(const s of n){const i=b(l,s.name);if(s.isDirectory()){const r=W(i,e,t-1);if(r)return r}else if(s.isFile()&&s.name.endsWith(e))return i}return null}function _e(l,e){if(!l)return null;const t=e||b(E(),".cursor","projects");return W(t,`${l}.jsonl`,6)}function ve(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 be(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]
4
+ ${s}`),t.filter(i=>i.length>0).join(`
5
+
6
+ `)}class H extends B{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 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;pendingQuestionByRequestId=new Map;pendingQuestionAnswerBySession=new Map;cachedAccountRateLimits=null;rateLimitsInflight=null;_availableModels=[];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 V("cursor-adapter",t.getAgentProfile)}async start(){this.alive=!0,this.stopped=!1,(this.config.options??{}).mcp_tools!==!1&&(this.internalApi=new ee,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 F.map(e=>({...e}))}async refreshModels(){try{const e={...process.env,...this.config.env??{}},t=await ne({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())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 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.identity.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 H(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.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,a=i.adapterSessionId,o=this.sessionRuntime.get(i.adapterSessionId)??{},d=this.config.options??{},c=[...this.config.args??[]];c.push("-p","--output-format","stream-json"),d.trust!==!1&&c.push("--trust");const h=o.cwd||d.workspace;this.internalApi&&h&&(this.ensureWorkspaceMcpAndSkills(h),c.push("--approve-mcps")),h&&c.push("--workspace",h);const S=o.modelId||d.model;S&&c.push("--model",S);const v=C(o.modeId||d.mode)??"full_auto";v==="full_auto"?c.push("--yolo"):v==="plan"&&c.push("--plan");const _=o.cursorSessionId??this.bindingStore?.getAcpSessionId(i.adapterSessionId),A=!!(_&&d.use_continue!==!1&&!t);A&&c.push("--resume",_),c.push(this.buildPromptText(i));const m={...process.env,...this.config.env??{}},y=R(this.config.command,typeof m.PATH=="string"?m.PATH:void 0);u.info("cursor-adapter",`job start: event=${s.event_id} session=${s.session_id} retry=${n}`);let p;try{p=T(y,c,{cwd:h||process.cwd(),env:m,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 f={event:s,request:i,handle:r,child:p,seq:0,done:!1,stderr:"",timer:null,idleTimer:null,toolCallsInFlight:new Set,toolCallsStarted:0,assistantTextEmitted:"",streamBuffer:"",retryCount:n,usedContinue:A,workspace:h||process.cwd(),args:c};this.activeBySession.set(a,f),this.notifyBindingReady(a),this.armActiveIdleTimer(a);const k=i.timeoutMs&&i.timeoutMs>0?i.timeoutMs:0;k>0&&(f.timer=setTimeout(()=>{f.done||(w(p,"SIGTERM"),this.finishActive(a,"failed",`cursor agent timeout after ${k}ms`))},k)),x({input:p.stdout}).on("line",g=>this.handleStdoutLineForActive(f,g)),p.stderr?.on("data",g=>{const I=f.stderr+String(g??"");f.stderr=I.length>M.STDERR_MAX_CHARS?I.slice(-M.STDERR_MAX_CHARS):I}),p.once("error",g=>{this.finishActive(a,"failed",`spawn failed: ${String(g?.message??g)}`)}),p.once("close",g=>{if(!f.done)if((g??0)===0)this.finishActive(a,"responded");else{if(this.shouldRetryWithoutContinue(f)){f.timer&&clearTimeout(f.timer),f.idleTimer&&clearTimeout(f.idleTimer),this.activeBySession.delete(a),this.startJob(e,!0,f.retryCount+1);return}const I=f.stderr.trim()||`cursor agent exited with code ${g??-1}`;this.finishActive(a,"failed",I)}})}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){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:be(String(e.content??""),e),contextMessages:ve(e)},s=new H(t),i=this.pendingBySession.get(t)??[];i.push({event:e,request:n,handle:s}),this.pendingBySession.set(t,i),u.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){w(e,"SIGTERM"),setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{w(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(a=>a.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 a=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...a,modelId:r}),this.notifyBindingReady(s);const o=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(i,"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=C(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 a=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...a,modeId:r}),this.notifyBindingReady(s);const o=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(i,"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(i,"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(i,"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(i,"ok",{adapterType:"cursor",available:!0,sampledAt:r.sampledAt,turns:r.turns,tokenUsage:r.total}):this.callbacks.sendLocalActionResult(i,"ok",{adapterType:"cursor",available:!1,sampledAt:null,turns:0,tokenUsage:null}),{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 a=this.sessionRuntime.get(s),o=this.config.options??{},d=this.getToolbarMeta(s),c=this.activeBySession.has(s);this.callbacks.sendLocalActionResult(i,"ok",{verb:"status",status:c?"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(i,"failed",void 0,"invalid_verb",`Unsupported verb: ${r}`);return{handled:!0,kind:"session_control"}}default:return{handled:!1,kind:"unsupported"}}}async execCommand(e,t,n){return e!=="compact"?{status:"unsupported",message:`Unsupported command: ${e}`}:this.runCompactHandoff(n)}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)??{},n=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 i=String(t.cwd||n.workspace||process.cwd()),r=String(t.modelId||n.model||""),a=C(t.modeId||n.mode)??"full_auto";u.info("cursor-adapter",`[compact] summarize resume=${s} session=${e}`);const o=await this.runPrintOnce({prompt:ue,resumeChatId:s,cwd:i,modelId:r||void 0,modeId:a,timeoutMs:D});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:i,modelId:r||t.modelId,modeId:a,cursorSessionId:d}),this.bindingStore?.setAcpSessionId(e,d),this.pendingHandoffBySession.set(e,o.text.trim()),this.lastContextBySession.set(e,re(0,ae(r))),this.notifyBindingReady(e),u.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??{}},n=R(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 i=C(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 a;try{a=T(n,s,{cwd:e.cwd||process.cwd(),env:t,stdio:["ignore","pipe","pipe"]}).process}catch(m){r({ok:!1,text:"",error:`spawn failed: ${m instanceof Error?m.message:String(m)}`});return}let o="",d="",c="",h=!1;const S=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:D,v=setTimeout(()=>{h||(h=!0,this.killChildWithFallback(a),r({ok:!1,text:o,sessionId:d||void 0,error:`compact timeout after ${S}ms`}))},S);v.unref?.();const _=(m,y)=>{h||(h=!0,clearTimeout(v),r({ok:m,text:o,sessionId:d||void 0,error:y}))};x({input:a.stdout}).on("line",m=>{const y=m.trim();if(!y)return;let p;try{p=JSON.parse(y)}catch{return}if(p?.type!=="result")return;const f=typeof p?.result=="string"?p.result:"";f&&(o=f);const k=String(p?.session_id??"").trim();k&&(d=k)}),a.stderr?.on("data",m=>{c+=typeof m=="string"?m:m.toString("utf8")}),a.on("error",m=>_(!1,m.message)),a.on("close",m=>{if(!h){if(o.trim()){_(!0);return}_(!1,c.trim()||`cursor agent exited with code ${m??"unknown"}`)}})})}createEmptyChat(){const e={...process.env,...this.config.env??{}},t=R(this.config.command,typeof e.PATH=="string"?e.PATH:void 0);return new Promise(n=>{let s;try{s=T(t,["create-chat"],{cwd:process.cwd(),env:e,stdio:["ignore","pipe","pipe"]}).process}catch{n(null);return}let i="",r=!1;const a=setTimeout(()=>{r||(r=!0,this.killChildWithFallback(s),n(null))},3e4);a.unref?.(),s.stdout?.on("data",o=>{i+=typeof o=="string"?o:o.toString("utf8")}),s.on("error",()=>{r||(r=!0,clearTimeout(a),n(null))}),s.on("close",o=>{if(r)return;r=!0,clearTimeout(a);const d=i.trim().split(/\s+/)[0]??"";n(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 n of this.activeBySession.values()){const s=n.child?.pid;if(s&&!Se(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 Z(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?_e(e):null;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const n=G(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);return{adapterType:"cursor",available:t.available&&!!t.rateLimits,cached:!0,sampledAt:Number.isFinite(s)?s:Date.now(),rateLimits:t.rateLimits,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 ie();this.cachedAccountRateLimits={available:r.available,sampledAt:r.sampledAt,rateLimits:r.rateLimits,displayMessage:r.displayMessage,error:r.error},r.available&&r.rateLimits?u.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}`:"")):u.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=C(s?.modeId||t.mode)??"full_auto",a={model_id:i,mode_id:r,currentModelId:i,currentModeId:r,available_models:this.availableModels,available_modes:this.availableModes},o=this.cachedAccountRateLimits?.rateLimits;if(o?.fiveHour||o?.sevenDay){const c=Date.parse(this.cachedAccountRateLimits?.sampledAt??"")||Date.now();a.rate_limits={...o.fiveHour?{fiveHour:o.fiveHour}:{},...o.sevenDay?{sevenDay:o.sevenDay}:{},sampledAt:c}}const d=n?this.lastContextBySession.get(n):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??{},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;!e.contextMessages||e.contextMessages.length===0?t=e.text:t=`${e.contextMessages.map(r=>`[${r.senderId}] ${r.content}`).join(`
5
7
  `)}
6
8
 
7
9
  [Current user message]
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
+ ${e.text}`;const n=this.pendingQuestionAnswerBySession.get(e.adapterSessionId);n&&(this.pendingQuestionAnswerBySession.delete(e.adapterSessionId),t=`[User answered a previous agent question]
11
+ ${n}
12
+
13
+ [Current user message]
14
+ ${t}`);const s=this.pendingHandoffBySession.get(e.adapterSessionId);return s&&(this.pendingHandoffBySession.delete(e.adapterSessionId),t=`[Previous conversation summary \u2014 continue from this handoff]
15
+ ${s}
10
16
 
11
17
  [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};
18
+ ${t}`),this.identity.injectOnce(e.adapterSessionId,t)}handleStdoutLineForActive(e,t){if(e.done)return;const n=t.trim();if(!n)return;const{event:s}=e;let i;try{i=JSON.parse(n)}catch{this.armActiveIdleTimer(e.request.adapterSessionId);return}if(i?.type==="tool_call"){const o=String(i?.call_id??""),d=String(i?.subtype??"");o&&(d==="started"||d==="start"?(this.flushAssistantStreamBuffer(e),e.toolCallsInFlight.add(o),e.toolCallsStarted+=1,this.handleSpecialToolCallStarted(e,i)):N.has(d)&&e.toolCallsInFlight.delete(o))}this.armActiveIdleTimer(e.request.adapterSessionId);const r=ge(i);r&&this.callbacks.sendRawEventEnvelope?.(s.event_id,s.session_id,r);const a=ye(i,e.assistantTextEmitted);if(a&&this.enqueueAssistantStreamDelta(e,a),i?.type==="result"){const o=typeof i?.result=="string"?i.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(i?.session_id??"").trim();if(d){const p=this.sessionRuntime.get(e.request.adapterSessionId)??{};this.sessionRuntime.set(e.request.adapterSessionId,{...p,cursorSessionId:d}),this.bindingStore?.setAcpSessionId(e.request.adapterSessionId,d)}const c=i?.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 S=String((this.sessionRuntime.get(e.request.adapterSessionId)?.modelId??this.config.options?.model??"")||""),v=Math.max(1,(e.toolCallsStarted??0)+1),_=Number(c.inputTokens??0),A=Number(c.cacheReadTokens??0),m=Number(c.cacheWriteTokens??0),y=oe({inputTokens:_,cacheReadTokens:A,cacheWriteTokens:m},S,{apiRounds:v});y&&(this.lastContextBySession.set(e.request.adapterSessionId,y),u.info("cursor-adapter",`[context_window] used=${y.usedTokens} size=${y.sizeTokens} pct=${y.usedPercentage.toFixed(1)}% model=${S||"auto"} rawIn=${_} rawCache=${A} rawWrite=${m} apiRounds=${v}`))}}handleSpecialToolCallStarted(e,t){const n=O(t);if(Q(n.toolName)){const s=pe(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}U(n.toolName)&&this.emitAskQuestionCard(e,n.toolInput)}emitAskQuestionCard(e,t){const n=e.event,s=fe(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 i=z(),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+P}),u.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>P+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??{},a=String(r.type??"");if(a==="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 o="";return a==="text"?o=String(r.value??""):a==="map"&&(o=(Array.isArray(r.entries)?r.entries:[]).map(c=>c.value).join(", ")),o?(this.pendingQuestionByRequestId.delete(n),this.pendingQuestionAnswerBySession.set(s.sessionId,o),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>=ce&&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 n=t.toolCallsInFlight.size>0?de:le;t.idleTimer=setTimeout(()=>{t.done||(u.error("cursor-adapter",`Idle timeout (${n/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 ${n/1e3}s`))},n),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;this.callbacks.sendStreamChunk(s.event.event_id,s.event.session_id,"",s.seq,!0,void 0,i),u.info("cursor-adapter",`job finish: event=${s.event.event_id} session=${s.event.session_id} status=${t}${n?` msg=${n}`:""}`),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),this.tryStartNext(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=b(E(),".cursor","skills"),n=te(t);n.length>0&&u.info("cursor-adapter",`Synced connector skills to ${t}: [${n.join(", ")}]`)}ensureCursorMcpConfig(e,t){try{const n=b(e,".cursor"),s=b(n,"mcp.json");$(n,{recursive:!0});let i={};try{i=JSON.parse(q(s,"utf8"))}catch{i={}}const r={command:process.execPath,args:[X(K(import.meta.url),"../../../mcp/acp-mcp-server.js"),"--api-url",t]};(!i.mcpServers||typeof i.mcpServers!="object")&&(i.mcpServers={}),i.mcpServers.grix=r,L(s,`${JSON.stringify(i,null,2)}
19
+ `,"utf8"),this.recordCursorMcpRegistry(e,s,r),u.info("cursor-adapter",`MCP config synced: workspace=${e} file=${s}`)}catch(n){u.warn("cursor-adapter",`Failed to ensure .cursor/mcp.json: ${String(n)}`)}}recordCursorMcpRegistry(e,t,n){try{const s=b(Y.data,"cursor"),i=b(s,"mcp-registry.json");$(s,{recursive:!0});let r={};try{r=JSON.parse(q(i,"utf8"))}catch{r={}}r[e]={mcp_path:t,server:n,updated_at:new Date().toISOString()},L(i,`${JSON.stringify(r,null,2)}
20
+ `,"utf8")}catch(s){u.warn("cursor-adapter",`Failed to record MCP registry: ${String(s)}`)}}}export{F as CURSOR_MODE_OPTIONS,M as CursorAdapter,ye as extractCursorAssistantStreamDelta,_e as findCursorTranscript,pe as formatCursorCreatePlanText,U as isCursorAskQuestionTool,Q as isCursorCreatePlanTool,ge as mapCursorStreamJsonToRawEnvelope,fe as parseCursorAskQuestionPayload};
@@ -1,2 +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};
1
+ import{JsonRpcTransport as y}from"../../core/transport/json-rpc.js";import{log as c}from"../../core/log/index.js";import{killProcessGroup as g,resolveCommandPath as w,spawnCommand as h}from"../../core/runtime/spawn.js";const E=3e4,u="none|low|medium|high|xhigh|extra-high|max";function M(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 T(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 $(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 n=r.match(/^(\S+)\s+-\s+(.+)$/);n&&e.push({id:n[1],displayName:n[2].trim()})}return e}function A(o){const e=new Set,t=[];for(const r of o){const n=v(r.id);if(e.has(n))continue;e.add(n);const s=n==="auto"?"Auto (default)":T(r.displayName);t.push({id:n,displayName:s})}return t}async function I(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 C(o){const e={...process.env,...o.env??{}},t=w(o.command,typeof e.PATH=="string"?e.PATH:void 0),{process:r}=h(t,["models"],{cwd:o.cwd??process.cwd(),env:e,stdio:["ignore","pipe","pipe"]}),n=await I(r);return $(n)}async function k(o){const e=await C(o);return A(e)}async function P(o){const e=o.timeoutMs??E,t=o.cwd??process.cwd(),r={...process.env,...o.env??{}},n=w(o.command,typeof r.PATH=="string"?r.PATH:void 0),{process:s}=h(n,["acp"],{cwd:t,env:r,stdio:["pipe","pipe","pipe"]});if(!s.stdout||!s.stdin)throw g(s,"SIGTERM"),new Error("cursor acp spawn missing stdio pipes");const a=new y(s.stdout,s.stdin);a.setHandlers(void 0,(d,m)=>{String(d).startsWith("cursor/")?a.respondSuccess(m,{}):a.respondError(m,-32601,"method not implemented")});const l=new AbortController,x=setTimeout(()=>l.abort(),e),p=d=>{l.abort(d)};s.once("error",p);try{await a.call("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1}},clientInfo:{name:"grix-connector",version:"0"}},l.signal);const f=((await a.call("session/new",{cwd:t,mcpServers:[]},l.signal)).models?.availableModels??[]).filter(i=>typeof i.modelId=="string"&&i.modelId.length>0).map(i=>M(i.modelId,i.name??i.modelId));if(f.length===0)throw new Error("cursor acp session/new returned no models");return f}finally{clearTimeout(x),s.off("error",p);try{a.close()}catch{}g(s,"SIGTERM")}}async function L(o){try{const e=await C(o);if(e.length>0)return c.info("cursor-adapter",`Loaded ${e.length} models via CLI agent models`),e;c.warn("cursor-adapter","CLI agent models returned empty list, falling back to ACP")}catch(e){const t=e instanceof Error?e.message:String(e);c.warn("cursor-adapter",`CLI agent models failed, falling back to ACP: ${t}`)}try{const e=await P(o);return c.info("cursor-adapter",`Loaded ${e.length} parameterized models via acp fallback`),e}catch(e){const t=e instanceof Error?e.message:String(e);return c.warn("cursor-adapter",`ACP model fallback failed: ${t}`),[]}}export{T as collapseCursorDisplayName,v as collapseCursorModelId,A as collapseExplodedCursorModels,k as fetchCollapsedModelsFromCli,L as fetchCursorParameterizedModels,P as fetchCursorParameterizedModelsViaAcp,C as fetchExplodedModelsFromCli,M as normalizeCursorAvailableModel,$ as parseExplodedCursorModels};
@@ -1 +1 @@
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};
1
+ import{CursorAdapter as e,CURSOR_MODE_OPTIONS as s,extractCursorAssistantStreamDelta as t,mapCursorStreamJsonToRawEnvelope as a,isCursorAskQuestionTool as l,isCursorCreatePlanTool as C,parseCursorAskQuestionPayload as u,formatCursorCreatePlanText as d}from"./cursor-adapter.js";import{collapseCursorDisplayName as n,collapseCursorModelId as p,collapseExplodedCursorModels as m,fetchCursorParameterizedModels as x,fetchExplodedModelsFromCli as c,normalizeCursorAvailableModel as f,parseExplodedCursorModels as T}from"./fetch-models.js";import{fetchCursorAccountUsage as M,mapCursorPeriodUsageToRateLimits as P,readCursorAccessToken as E}from"./fetch-usage.js";import{buildCursorContextWindow as k,buildCursorContextWindowFromUsage as w,estimateCursorContextTokens as O,resolveCursorContextWindowSize as R}from"./context-window.js";export{s as CURSOR_MODE_OPTIONS,e as CursorAdapter,k as buildCursorContextWindow,w as buildCursorContextWindowFromUsage,n as collapseCursorDisplayName,p as collapseCursorModelId,m as collapseExplodedCursorModels,O as estimateCursorContextTokens,t as extractCursorAssistantStreamDelta,M as fetchCursorAccountUsage,x as fetchCursorParameterizedModels,c as fetchExplodedModelsFromCli,d as formatCursorCreatePlanText,l as isCursorAskQuestionTool,C as isCursorCreatePlanTool,P as mapCursorPeriodUsageToRateLimits,a as mapCursorStreamJsonToRawEnvelope,f as normalizeCursorAvailableModel,u as parseCursorAskQuestionPayload,T as parseExplodedCursorModels,E as readCursorAccessToken,R as resolveCursorContextWindowSize};
@@ -1 +1 @@
1
- import{readFileSync as h,readdirSync as l}from"node:fs";import d from"node:path";import{homedir as p}from"node:os";import{log as m}from"../../core/log/index.js";import{makeTitle as y,stripInjectedPreamble as b}from"../../core/util/session-title.js";import{openReadOnlyDatabase as x}from"../../core/util/sqlite-reader.js";function S(r=p()){return d.join(r,".cursor","chats")}function g(r){try{return JSON.parse(h(r,"utf8"))}catch{return null}}function w(r){const e=[];for(let t=0;t+34<=r.length;t+=1)r[t]===10&&r[t+1]===32&&e.push(r.subarray(t+2,t+34).toString("hex"));return e}function A(r){let e;try{e=JSON.parse(r.toString("utf8"))}catch{return}if(e.role!=="user")return;const t=e.content;if(typeof t=="string")return t;if(Array.isArray(t)){for(const n of t)if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}}function C(r){const e=x(r);if(e)try{const t=e.all("SELECT value FROM meta LIMIT 1");if(t.length===0)return;const n=JSON.parse(Buffer.from(t[0].value,"hex").toString("utf8"));if(!n.latestRootBlobId)return;const o=new Map;for(const i of e.all("SELECT id, data FROM blobs"))o.set(i.id,Buffer.from(i.data));const s=o.get(n.latestRootBlobId);if(!s)return;for(const i of w(s)){const a=o.get(i);if(!a)continue;const u=A(a);if(!u)continue;const c=/<user_query>([\s\S]*?)<\/user_query>/.exec(u);if(c)return y(b(c[1]))}return}catch{return}finally{e.close()}}function O(r=p()){const e=S(r),t=[];let n;try{n=l(e,{withFileTypes:!0})}catch{return t}for(const o of n){if(!o.isDirectory())continue;const s=d.join(e,o.name);let i;try{i=l(s,{withFileTypes:!0})}catch{continue}for(const a of i){if(!a.isDirectory())continue;const u=d.join(s,a.name),c=d.join(u,"meta.json"),f=g(c);f?.updatedAtMs&&t.push({sessionId:a.name,cwd:f.cwd??"",title:f.hasConversation?C(d.join(u,"store.db")):void 0,createdAt:f.createdAtMs,updatedAt:f.updatedAtMs,filePath:c})}}return t.sort((o,s)=>s.updatedAt-o.updatedAt),m.info("cursor-session-scanner",`Scanned ${t.length} Cursor sessions from ${e}`),t}export{S as resolveCursorChatsDir,O as scanCursorSessions};
1
+ import{readFileSync as S,readdirSync as m}from"node:fs";import f from"node:path";import{homedir as p}from"node:os";import{log as I}from"../../core/log/index.js";import{makeTitle as h,stripInjectedPreamble as y}from"../../core/util/session-title.js";import{openReadOnlyDatabase as g}from"../../core/util/sqlite-reader.js";function T(e=p()){return f.join(e,".cursor","chats")}function F(e){try{return JSON.parse(S(e,"utf8"))}catch{return null}}function w(e){const r=[];for(let t=0;t+34<=e.length;t+=1)e[t]===10&&e[t+1]===32&&r.push(e.subarray(t+2,t+34).toString("hex"));return r}function A(e){let r;try{r=JSON.parse(e.toString("utf8"))}catch{return}if(r.role!=="user")return;const t=r.content;if(typeof t=="string")return t;if(Array.isArray(t)){for(const n of t)if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}}function x(e){const r=/<user_query>([\s\S]*?)<\/user_query>/.exec(e);if(r)return h(y(r[1]));const t=/\[system-identity\][\s\S]*?\[\/system-identity\]/.exec(e),n=/\[\[message_id:[^\]]+\]\]/.exec(e);if(!t&&!n)return;const s=Math.min(t?.index??Number.POSITIVE_INFINITY,n?.index??Number.POSITIVE_INFINITY),o=y(e.slice(s)),i=o.search(/[\x00-\x08\x0b\x0c\x0e-\x1f]/),c=(i>=0?o.slice(0,i):o).replace(/^\uFFFD+/,"").trim();return h(c)}function b(e){const r=A(e);if(r){const n=x(r);if(n)return n}const t=e.toString("utf8");if(!t.trimStart().startsWith("{"))return x(t)}function D(e){const r=g(e);if(r)try{const t=r.all("SELECT value FROM meta LIMIT 1");if(t.length===0)return;const n=JSON.parse(Buffer.from(t[0].value,"hex").toString("utf8")),s=new Map;for(const o of r.all("SELECT id, data FROM blobs"))s.set(o.id,Buffer.from(o.data));if(n.latestRootBlobId){const o=s.get(n.latestRootBlobId);if(o)for(const i of w(o)){const c=s.get(i);if(!c)continue;const a=b(c);if(a)return a}}for(const o of s.values()){const i=b(o);if(i)return i}return}catch{return}finally{r.close()}}function R(e=p()){const r=T(e),t=[];let n;try{n=m(r,{withFileTypes:!0})}catch{return t}for(const s of n){if(!s.isDirectory())continue;const o=f.join(r,s.name);let i;try{i=m(o,{withFileTypes:!0})}catch{continue}for(const c of i){if(!c.isDirectory())continue;const a=f.join(o,c.name),d=f.join(a,"meta.json"),u=F(d);if(!u?.updatedAtMs)continue;const l=D(f.join(a,"store.db"));!u.hasConversation&&!l||t.push({sessionId:c.name,cwd:u.cwd??"",title:l,createdAt:u.createdAtMs,updatedAt:u.updatedAtMs,filePath:d})}}return t.sort((s,o)=>o.updatedAt-s.updatedAt),I.info("cursor-session-scanner",`Scanned ${t.length} Cursor sessions from ${r}`),t}export{T as resolveCursorChatsDir,R as scanCursorSessions};