grix-connector 4.14.1 → 4.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/adapter/agy/agy-adapter.js +7 -7
  2. package/dist/adapter/agy/model-list.js +2 -2
  3. package/dist/adapter/agy/quota.js +5 -5
  4. package/dist/adapter/claude/claude-bridge-server.js +1 -1
  5. package/dist/adapter/claude/claude-tools.js +1 -1
  6. package/dist/adapter/claude/claude-worker-client.js +1 -1
  7. package/dist/adapter/claude/mcp-http-launcher.js +2 -2
  8. package/dist/adapter/claude/result-timeout.js +1 -1
  9. package/dist/adapter/cursor/context-window.js +1 -1
  10. package/dist/adapter/cursor/cursor-adapter.js +9 -9
  11. package/dist/adapter/opencode/opencode-adapter.js +4 -6
  12. package/dist/adapter/opencode/opencode-transport.js +7 -4
  13. package/dist/adapter/opencode/opencode-v2-events.js +2 -0
  14. package/dist/adapter/opencode/resolve-command.js +1 -0
  15. package/dist/assets/dsh-bridge/grix-dsh-bridge-4.15.2.tgz +0 -0
  16. package/dist/assets/dsh-bridge/manifest.json +6 -6
  17. package/dist/audit/adapters/opencode/opencode-audit-adapter.js +1 -1
  18. package/dist/bridge/bridge.js +2 -2
  19. package/dist/bridge/toolbar-meta.js +1 -1
  20. package/dist/core/access/allowlist-store.js +1 -1
  21. package/dist/core/file-ops/list-files.js +1 -1
  22. package/dist/log.js +2 -2
  23. package/dist/mcp/stream-http/config.js +1 -1
  24. package/dist/mcp/stream-http/connection-binding.js +1 -1
  25. package/dist/mcp/stream-http/security.js +1 -1
  26. package/dist/mcp/stream-http/tool-executor.js +1 -1
  27. package/dist/mcp/stream-http/tool-registry.js +1 -1
  28. package/dist/mcp/stream-http/tool-schemas.js +1 -1
  29. package/openclaw-plugin/audit-recorder-worker.js +2 -2
  30. package/package.json +1 -1
  31. package/dist/assets/dsh-bridge/grix-dsh-bridge-4.14.1.tgz +0 -0
@@ -1,15 +1,15 @@
1
- import{execFileSync as Z}from"node:child_process";import{createInterface as q}from"node:readline";import{EventEmitter as L}from"node:events";import{randomUUID as ee}from"node:crypto";import{mkdirSync as E,readFileSync as P,writeFileSync as D,readdirSync as te,statSync as N}from"node:fs";import{join as A,resolve as se}from"node:path";import{fileURLToPath as ne}from"node:url";import{homedir as F}from"node:os";import{GRIX_PATHS as ie,log as u}from"../../core/log/index.js";import{IdentityInjector as re}from"../shared/identity-injector.js";import{buildSimpleProbeReport as oe}from"../shared/probe-util.js";import{InternalApiServer as ae}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as de,pruneLegacyMcpServerEntries as le}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as ce}from"../shared/inbound-message-id-injector.js";import{insertBeforeTrailingMessageReferences as R}from"../../core/protocol/message-reference.js";import{syncDefaultSkillsToDir as ue}from"../../default-skills/index.js";import{spawnCommand as B,killProcessGroup as I}from"../../core/runtime/spawn.js";import{countLivingDescendantsOutsideBaseline as he,listLivingDescendants as me}from"./living-descendants.js";import{SessionBindingStore as fe}from"../../core/persistence/session-binding-store.js";import{fetchCursorParameterizedModels as pe}from"./fetch-models.js";import{resolveCursorSpawn as M}from"./resolve-command.js";import{fetchCursorAccountUsage as ge}from"./fetch-usage.js";import{buildCursorContextWindow as Se,buildCursorContextWindowFromUsage as ye,resolveCursorContextWindowSize as ve}from"./context-window.js";const _e=12e4,x=300*1e3,j=90*1e3,O=1800*1e3,Ae=8192,Q="Summarize this conversation for handoff to a fresh chat. Include: goals, key decisions, important file paths, current status, and next steps. Be concise but complete. Output ONLY the summary text.",W=12e4,U=new Set(["completed","failed","error","errored","canceled","cancelled","rejected"]);function be(d){const e=d.replace(/ToolCall$/i,"").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):d||"tool"}function z(d){const e=String(d.call_id??d.callId??"").trim(),t=d.tool_call??d.toolCall;if(t&&typeof t=="object"&&!Array.isArray(t)){const n=Object.keys(t);if(n.length>0){const s=n[0],i=t[s],r=i&&typeof i=="object"&&!Array.isArray(i)?i:null;return{toolName:be(s),toolInput:r?.args??r?.arguments??{},callId:e}}}return{toolName:String(d.name??d.tool_name??d.toolName??"tool").trim()||"tool",toolInput:d.args??d.tool_input??d.toolInput??{},callId:e}}function H(d){return String(d??"").trim().toLowerCase().replace(/[^a-z0-9]/g,"")}function J(d){const e=H(d);return e==="askquestion"||e==="askuserquestion"}function G(d){const e=H(d);return e==="createplan"||e==="exitplanmode"}function we(d){if(!Array.isArray(d))return;const e=d.map(t=>{if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";const n=t,s=String(n.label??"").trim();if(s)return s;const 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 ke(d){if(!d||typeof d!="object"||Array.isArray(d))return null;const e=d,t=String(e.title??"").trim(),n=e.questions;if(!Array.isArray(n)||n.length===0)return null;const s=[];for(let i=0;i<n.length;i++){const r=n[i];if(!r||typeof r!="object")continue;const o=r,a=t||`Question ${i+1}`,l=String(o.header??o.id??o.question??a).trim()||a,c=String(o.prompt??o.question??"").trim();if(!c)continue;const h=we(o.options),p=o.multiSelect===!0||o.multi_select===!0;s.push({header:l,prompt:c,...h?{options:h}:{},...p?{multi_select:!0}:{},allow_free_text:!0})}return s.length>0?s:null}function Ie(d){if(!d||typeof d!="object"||Array.isArray(d))return null;const e=d,t=String(e.name??e.title??"").trim(),n=String(e.overview??"").trim(),s=String(e.plan??"").trim();if(!s&&!n&&!t)return null;const i=[];return t&&i.push(`# ${t}`),n&&i.push(n),s&&i.push(s),i.join(`
1
+ import{execFileSync as ee}from"node:child_process";import{createInterface as E}from"node:readline";import{EventEmitter as L}from"node:events";import{randomUUID as te}from"node:crypto";import{mkdirSync as P,readFileSync as q,writeFileSync as D,readdirSync as se,statSync as N}from"node:fs";import{join as A,resolve as ne}from"node:path";import{fileURLToPath as ie}from"node:url";import{homedir as F}from"node:os";import{GRIX_PATHS as re,log as u}from"../../core/log/index.js";import{IdentityInjector as oe}from"../shared/identity-injector.js";import{buildSimpleProbeReport as ae}from"../shared/probe-util.js";import{InternalApiServer as de}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as le,pruneLegacyMcpServerEntries as ce}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as ue}from"../shared/inbound-message-id-injector.js";import{insertBeforeTrailingMessageReferences as R}from"../../core/protocol/message-reference.js";import{syncDefaultSkillsToDir as he}from"../../default-skills/index.js";import{spawnCommand as B,killProcessGroup as C}from"../../core/runtime/spawn.js";import{countLivingDescendantsOutsideBaseline as me,listLivingDescendants as fe}from"./living-descendants.js";import{SessionBindingStore as pe}from"../../core/persistence/session-binding-store.js";import{fetchCursorParameterizedModels as ge}from"./fetch-models.js";import{resolveCursorSpawn as x}from"./resolve-command.js";import{fetchCursorAccountUsage as Se}from"./fetch-usage.js";import{buildCursorContextWindow as ye,buildCursorContextWindowFromUsage as ve,resolveCursorContextWindowSize as _e}from"./context-window.js";const Ae=12e4,M=300*1e3,j=90*1e3,O=1800*1e3,be=8192,Q="Summarize this conversation for handoff to a fresh chat. Include: goals, key decisions, important file paths, current status, and next steps. Be concise but complete. Output ONLY the summary text.",U=12e4,W=90,H=new Set(["completed","failed","error","errored","canceled","cancelled","rejected"]);function we(d){const e=d.replace(/ToolCall$/i,"").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):d||"tool"}function z(d){const e=String(d.call_id??d.callId??"").trim(),t=d.tool_call??d.toolCall;if(t&&typeof t=="object"&&!Array.isArray(t)){const n=Object.keys(t);if(n.length>0){const s=n[0],r=t[s],i=r&&typeof r=="object"&&!Array.isArray(r)?r:null;return{toolName:we(s),toolInput:i?.args??i?.arguments??{},callId:e}}}return{toolName:String(d.name??d.tool_name??d.toolName??"tool").trim()||"tool",toolInput:d.args??d.tool_input??d.toolInput??{},callId:e}}function J(d){return String(d??"").trim().toLowerCase().replace(/[^a-z0-9]/g,"")}function G(d){const e=J(d);return e==="askquestion"||e==="askuserquestion"}function X(d){const e=J(d);return e==="createplan"||e==="exitplanmode"}function ke(d){if(!Array.isArray(d))return;const e=d.map(t=>{if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";const n=t,s=String(n.label??"").trim();if(s)return s;const r=String(n.value??"").trim();if(r)return r;const i=String(n.text??"").trim();return i||""}).filter(t=>t.length>0);return e.length>0?e:void 0}function Ce(d){if(!d||typeof d!="object"||Array.isArray(d))return null;const e=d,t=String(e.title??"").trim(),n=e.questions;if(!Array.isArray(n)||n.length===0)return null;const s=[];for(let r=0;r<n.length;r++){const i=n[r];if(!i||typeof i!="object")continue;const o=i,a=t||`Question ${r+1}`,l=String(o.header??o.id??o.question??a).trim()||a,c=String(o.prompt??o.question??"").trim();if(!c)continue;const h=ke(o.options),p=o.multiSelect===!0||o.multi_select===!0;s.push({header:l,prompt:c,...h?{options:h}:{},...p?{multi_select:!0}:{},allow_free_text:!0})}return s.length>0?s:null}function Ie(d){if(!d||typeof d!="object"||Array.isArray(d))return null;const e=d,t=String(e.name??e.title??"").trim(),n=String(e.overview??"").trim(),s=String(e.plan??"").trim();if(!s&&!n&&!t)return null;const r=[];return t&&r.push(`# ${t}`),n&&r.push(n),s&&r.push(s),r.join(`
2
2
 
3
- `)}function Ce(d){if(!d||typeof d!="object"||Array.isArray(d))return null;const e=d,t=String(e.type??"").trim().toLowerCase();if(!t)return null;switch(t){case"tool_call":{const n=String(e.subtype??"").trim().toLowerCase(),s=z(e);return J(s.toolName)||G(s.toolName)?null:n==="started"||n==="start"?{type:"tool_call",payload:{tool_name:s.toolName,...s.callId?{tool_call_id:s.callId}:{}}}:(U.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 Re(d,e){if(!d||typeof d!="object"||Array.isArray(d))return"";const t=d;if(String(t.type??"")!=="assistant")return"";const n=t.model_call_id??t.modelCallId;if(n!=null&&String(n).trim()!=="")return"";const s=t.message,i=s&&typeof s=="object"&&!Array.isArray(s)?s.content:void 0;if(!Array.isArray(i))return"";const r=i.map(o=>{if(!o||typeof o!="object"||Array.isArray(o))return"";const a=o;return a.type==="text"?String(a.text??""):""}).filter(Boolean).join("");if(!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 X=[{id:"approval",displayName:"\u4EBA\u5DE5\u786E\u8BA4"},{id:"full_auto",displayName:"\u81EA\u7531\u6A21\u5F0F"},{id:"plan",displayName:"\u8BA1\u5212\u6A21\u5F0F"}];function C(d){const e=String(d??"").trim().toLowerCase();return X.some(t=>t.id===e)?e:null}function T(d){try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}function K(d,e,t){if(t<0)return null;let n;try{n=te(d,{withFileTypes:!0})}catch{return null}for(const s of n){const i=A(d,s.name);if(s.isDirectory()){const r=K(i,e,t-1);if(r)return r}else if(s.isFile()&&s.name.endsWith(e))return i}return null}function V(d,e){if(!d)return null;const t=e||A(F(),".cursor","projects");return K(t,`${d}.jsonl`,6)}function Be(d){const e=d.context_messages_json;if(e)try{const t=JSON.parse(e);return!Array.isArray(t)||t.length===0?void 0:t.map(n=>({senderId:String(n.sender_id??"unknown"),content:String(n.content??"")}))}catch{return}}function Me(d,e){const t=[String(d??"")],n=String(e.quoted_message_id??"").trim();n&&t.push(`[quoted_message_id] ${n}`);const s=String(e.attachments_json??"").trim();return s&&t.push(`[attachments_json]
4
- ${s}`),t.filter(i=>i.length>0).join(`
3
+ `)}function Re(d){if(!d||typeof d!="object"||Array.isArray(d))return null;const e=d,t=String(e.type??"").trim().toLowerCase();if(!t)return null;switch(t){case"tool_call":{const n=String(e.subtype??"").trim().toLowerCase(),s=z(e);return G(s.toolName)||X(s.toolName)?null:n==="started"||n==="start"?{type:"tool_call",payload:{tool_name:s.toolName,...s.callId?{tool_call_id:s.callId}:{}}}:(H.has(n),null)}case"error":return{type:"error",payload:{message:String(e.message??e.error??e.result??"cursor error").trim()||"cursor error"}};case"result":{const n=String(e.subtype??"").trim().toLowerCase();return e.is_error===!0||n==="error"?{type:"error",payload:{message:String(e.result??e.message??"cursor run failed").trim()||"cursor run failed"}}:null}default:return null}}function Be(d,e){if(!d||typeof d!="object"||Array.isArray(d))return"";const t=d;if(String(t.type??"")!=="assistant")return"";const n=t.model_call_id??t.modelCallId;if(n!=null&&String(n).trim()!=="")return"";const s=t.message,r=s&&typeof s=="object"&&!Array.isArray(s)?s.content:void 0;if(!Array.isArray(r))return"";const i=r.map(o=>{if(!o||typeof o!="object"||Array.isArray(o))return"";const a=o;return a.type==="text"?String(a.text??""):""}).filter(Boolean).join("");if(!i)return"";if(e){if(i===e||e.startsWith(i)&&i.length<e.length)return"";if(i.startsWith(e))return i.slice(e.length)}return i}const K=[{id:"approval",displayName:"\u4EBA\u5DE5\u786E\u8BA4"},{id:"full_auto",displayName:"\u81EA\u7531\u6A21\u5F0F"},{id:"plan",displayName:"\u8BA1\u5212\u6A21\u5F0F"}];function I(d){const e=String(d??"").trim().toLowerCase();return K.some(t=>t.id===e)?e:null}function T(d){try{return process.kill(d,0),!0}catch(e){return e.code==="EPERM"}}function V(d,e,t){if(t<0)return null;let n;try{n=se(d,{withFileTypes:!0})}catch{return null}for(const s of n){const r=A(d,s.name);if(s.isDirectory()){const i=V(r,e,t-1);if(i)return i}else if(s.isFile()&&s.name.endsWith(e))return r}return null}function Y(d,e){if(!d)return null;const t=e||A(F(),".cursor","projects");return V(t,`${d}.jsonl`,6)}function xe(d){const e=d.context_messages_json;if(e)try{const t=JSON.parse(e);return!Array.isArray(t)||t.length===0?void 0:t.map(n=>({senderId:String(n.sender_id??"unknown"),content:String(n.content??"")}))}catch{return}}function Me(d,e){const t=[String(d??"")],n=String(e.quoted_message_id??"").trim();n&&t.push(`[quoted_message_id] ${n}`);const s=String(e.attachments_json??"").trim();return s&&t.push(`[attachments_json]
4
+ ${s}`),t.filter(r=>r.length>0).join(`
5
5
 
6
- `)}class Y extends L{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){u.warn("cursor-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}class $ extends L{type="cursor";static STDERR_MAX_CHARS=8192;config;callbacks;alive=!1;stopped=!1;permissionHandler=null;internalApi=null;bindingStore=null;identity;inboundMessageIds=new ce;inboundQueue=[];pendingBySession=new Map;sessions=new Set;sessionRuntime=new Map;sessionSeq=0;lastUsageBySession=new Map;auditCaptures=new Map;completedAuditBoundaries=new Map;lastContextBySession=new Map;pendingHandoffBySession=new Map;pendingQuestionByRequestId=new Map;pendingQuestionAnswerBySession=new Map;cachedAccountRateLimits=null;rateLimitsInflight=null;_availableModels=[];transcriptPathBySession=new Map;activeBySession=new Map;constructor(e,t){super(),this.config=e,this.callbacks=t;const n=e.options??{};this.bindingStore=n.bindingStore instanceof fe?n.bindingStore:null,this.identity=new re("cursor-adapter",t.getAgentProfile)}async start(){this.alive=!0,this.stopped=!1,(this.config.options??{}).mcp_tools!==!1&&(this.internalApi=new ae,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 X.map(e=>({...e}))}async refreshModels(){try{const e={...process.env,...this.config.env??{}},t=await pe({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())I(e.child,"SIGTERM");this.activeBySession.clear(),this.transcriptPathBySession.clear(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null)}isAlive(){return this.alive}async createSession(e){const t=`cursor-${Date.now()}-${++this.sessionSeq}`;return this.sessions.add(t),this.sessionRuntime.set(t,{cwd:typeof e.cwd=="string"?e.cwd:void 0,modelId:typeof e.modelId=="string"?e.modelId:void 0,modeId:typeof e.modeId=="string"?e.modeId:void 0}),t}async resumeSession(e,t){this.sessions.add(e);const n=this.sessionRuntime.get(e)??{};this.sessionRuntime.set(e,{...n,cwd:typeof t?.cwd=="string"?t.cwd:n.cwd,modelId:typeof t?.modelId=="string"?t.modelId:n.modelId,modeId:typeof t?.modeId=="string"?t.modeId:n.modeId})}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(e){this.sessions.delete(e),this.sessionRuntime.delete(e),this.transcriptPathBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e),this.pendingQuestionAnswerBySession.delete(e),this.pendingHandoffBySession.delete(e);for(const[t,n]of this.pendingQuestionByRequestId)n.sessionId===e&&this.pendingQuestionByRequestId.delete(t)}sendPrompt(e){const t=new Y(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;s.audit?.enabled&&!this.auditCaptures.has(s.event_id)&&this.auditCaptures.set(s.event_id,[]);const o=i.adapterSessionId,a=this.sessionRuntime.get(i.adapterSessionId)??{},l=this.config.options??{},c=[...this.config.args??[]];c.push("-p","--output-format","stream-json"),l.trust!==!1&&c.push("--trust");const h=a.cwd||l.workspace;this.internalApi&&h&&(this.ensureWorkspaceMcpAndSkills(h),c.push("--approve-mcps")),h&&c.push("--workspace",h);const p=a.modelId||l.model;p&&c.push("--model",p);const _=C(a.modeId||l.mode)??"full_auto";_==="full_auto"?c.push("--yolo"):_==="plan"&&c.push("--plan");const v=a.cursorSessionId??this.bindingStore?.getAcpSessionId(i.adapterSessionId),b=!!(v&&l.use_continue!==!1&&!t);b&&c.push("--resume",v),c.push(this.buildPromptText(i));const f={...process.env,...this.config.env??{}},y=M(this.config.command,f);u.info("cursor-adapter",`job start: event=${s.event_id} session=${s.session_id} retry=${n}`);let g;try{g=B(y.command,[...y.prefixArgs,...c],{cwd:h||process.cwd(),env:y.env,stdio:["ignore","pipe","pipe"]}).process}catch(S){this.finishActive(o,"failed",`spawn failed: ${S instanceof Error?S.message:String(S)}`);return}this.callbacks.sendEventAck(s.event_id,s.session_id),this.emit("eventStarted",s.event_id,s.session_id);const m={event:s,request:i,handle:r,child:g,seq:0,done:!1,stderr:"",timer:null,idleTimer:null,toolCallsInFlight:new Set,toolCallsStarted:0,assistantTextEmitted:"",streamBuffer:"",lastIoAt:Date.now(),sawResult:!1,descendantBaseline:void 0,retryCount:n,usedContinue:b,workspace:h||process.cwd(),args:c};this.activeBySession.set(o,m),this.notifyBindingReady(o),this.armActiveIdleTimer(o);const w=i.timeoutMs&&i.timeoutMs>0?i.timeoutMs:0;w>0&&(m.timer=setTimeout(()=>{m.done||(I(g,"SIGTERM"),this.finishActive(o,"failed",`cursor agent timeout after ${w}ms`))},w)),q({input:g.stdout}).on("line",S=>this.handleStdoutLineForActive(m,S)),g.stderr?.on("data",S=>{if(m.done)return;const k=m.stderr+String(S??"");m.stderr=k.length>$.STDERR_MAX_CHARS?k.slice(-$.STDERR_MAX_CHARS):k,m.lastIoAt=Date.now(),this.armActiveIdleTimer(o)}),g.once("error",S=>{this.finishActive(o,"failed",`spawn failed: ${String(S?.message??S)}`)}),g.once("close",S=>{if(!m.done)if((S??0)===0)this.finishActive(o,"responded");else{if(this.shouldRetryWithoutContinue(m)){m.timer&&clearTimeout(m.timer),m.idleTimer&&clearTimeout(m.idleTimer),this.activeBySession.delete(o),this.startJob(e,!0,m.retryCount+1);return}const k=m.stderr.trim()||`cursor agent exited with code ${S??-1}`;this.finishActive(o,"failed",k)}})}async cancel(e){const t=this.activeBySession.get(e);t&&(I(t.child,"SIGTERM"),this.finishActive(e,"canceled","canceled"))}deliverInboundEvent(e){const t=String(e.session_id??"").trim();if(!t){u.warn("cursor-adapter",`Dropping event ${e.event_id}: missing session_id`),this.callbacks.sendEventResult(e.event_id,"failed","missing session_id");return}if(!this.alive||this.stopped){u.warn("cursor-adapter",`Dropping event ${e.event_id}: adapter not running`),this.callbacks.sendEventAck(e.event_id,t),this.callbacks.sendEventResult(e.event_id,"failed","adapter not running");return}const n={adapterSessionId:t,text:this.inboundMessageIds.inject(t,Me(String(e.content??""),e),e.msg_id),contextMessages:Be(e)},s=new Y(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){I(e,"SIGTERM"),setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{I(e,"SIGKILL")}catch{}},5e3).unref()}deliverStopEvent(e,t){if(t){const n=this.activeBySession.get(t);if(n?.event.event_id===e){this.killChildWithFallback(n.child),this.finishActive(t,"canceled","stopped");return}const s=this.pendingBySession.get(t)??[],i=s.findIndex(r=>r.event.event_id===e);if(i>=0){const[r]=s.splice(i,1);s.length===0?this.pendingBySession.delete(t):this.pendingBySession.set(t,s),this.callbacks.sendEventAck(r.event.event_id,r.event.session_id),this.callbacks.sendEventResult(r.event.event_id,"canceled","stopped"),r.handle.emitDone({status:"canceled",error:"stopped"})}return}for(const[n,s]of this.activeBySession.entries())if(s.event.event_id===e){this.killChildWithFallback(s.child),this.finishActive(n,"canceled","stopped");return}for(const[n,s]of this.pendingBySession.entries()){const i=s.findIndex(o=>o.event.event_id===e);if(i<0)continue;const[r]=s.splice(i,1);s.length===0?this.pendingBySession.delete(n):this.pendingBySession.set(n,s),this.callbacks.sendEventAck(r.event.event_id,r.event.session_id),this.callbacks.sendEventResult(r.event.event_id,"canceled","stopped"),r.handle.emitDone({status:"canceled",error:"stopped"});return}}async handleLocalAction(e){const t=String(e.action_type??"").trim().toLowerCase(),n=e.params??{},s=String(n.session_id??"").trim(),i=e.action_id;if(t==="claude_interaction_reply")return String(n.kind??"").trim()==="permission"?(this.callbacks.sendLocalActionResult(i,"failed",void 0,"unsupported","Cursor adapter does not support interactive permission approvals"),{handled:!0,kind:"permission_unsupported"}):this.handleQuestionReply(e);switch(t){case"set_model":{const r=String(n.model_id??"").trim();if(!r||!s)return this.callbacks.sendLocalActionResult(i,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};const o=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...o,modelId:r}),this.notifyBindingReady(s);const a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(i,"ok",{outcome:"model_set",session_context:{model_id:r,mode_id:a.mode_id,modelId:r,modeId:a.mode_id},model_id:r,mode_id:a.mode_id,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"set_model"}}case"set_mode":{const r=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 o=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...o,modeId:r}),this.notifyBindingReady(s);const a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(i,"ok",{outcome:"mode_set",session_context:{model_id:a.model_id,mode_id:r,modelId:a.model_id,modeId:r},model_id:a.model_id,mode_id:r,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"set_mode"}}case"get_context":{const r=s?this.sessionRuntime.get(s):void 0,o=this.config.options??{},a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(i,"ok",{session_context:{model_id:a.model_id,mode_id:a.mode_id,cwd:r?.cwd??o.workspace??null},model_id:a.model_id,mode_id:a.mode_id,modelId:a.model_id,modeId:a.mode_id,cwd:r?.cwd??o.workspace??null,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"get_context"}}case"get_rate_limits":{await this.refreshAccountRateLimits({force:!0});const r=this.getRateLimitsSnapshot(s||void 0);return this.callbacks.sendLocalActionResult(i,"ok",r),s&&this.notifyBindingReady(s),{handled:!0,kind:"get_rate_limits"}}case"get_session_usage":{const r=s?this.getUsageSnapshot(s):null;if(r){const o={inputTokens:r.total.input,outputTokens:r.total.output,cacheReadInputTokens:r.total.cacheRead,cacheCreationInputTokens:r.total.cacheWrite};this.callbacks.sendLocalActionResult(i,"ok",{sessionId:s,adapterType:"cursor",sampledAt:r.sampledAt,turns:r.turns,total:o,models:[{model:this.getToolbarMeta(s).model_id??"auto",turns:r.turns,total:o}]})}else this.callbacks.sendLocalActionResult(i,"failed",void 0,"usage_not_found","No usage data found for this session");return{handled:!0,kind:"get_session_usage"}}case"session_control":{const r=String(n.verb??"").trim().toLowerCase();if(r==="restart"&&s)this.cancelSessionWork(s,"restarted"),this.callbacks.sendLocalActionResult(i,"ok",{outcome:"restarted"});else if(r==="status"){const o=this.sessionRuntime.get(s),a=this.config.options??{},l=this.getToolbarMeta(s),c=this.activeBySession.has(s);this.callbacks.sendLocalActionResult(i,"ok",{verb:"status",status:c?"running":"idle",session_context:{model_id:l.model_id,mode_id:l.mode_id,cwd:o?.cwd??a.workspace??null},model_id:l.model_id,mode_id:l.mode_id,modelId:l.model_id,modeId:l.mode_id,cwd:o?.cwd??a.workspace??null,available_models:this.availableModels,available_modes:this.availableModes})}else this.callbacks.sendLocalActionResult(i,"failed",void 0,"invalid_verb",`Unsupported verb: ${r}`);return{handled:!0,kind:"session_control"}}default:return{handled:!1,kind:"unsupported"}}}getSupportedCommands(){return[{name:"compact",description:"\u538B\u7F29\u4E0A\u4E0B\u6587",args:"[instructions]"}]}async execCommand(e,t,n){return e!=="compact"?{status:"unsupported",message:`Unsupported command: ${e}`}:this.runCompactHandoff(n,t)}async runCompactHandoff(e,t=""){if(!e)return{status:"failed",message:"session_id is required"};if(this.activeBySession.has(e))return{status:"failed",message:"Cannot compact while a Cursor turn is active"};const n=this.sessionRuntime.get(e)??{},s=this.config.options??{},i=n.cursorSessionId??this.bindingStore?.getAcpSessionId(e)??null;if(!i)return{status:"failed",message:"No Cursor chat to compact (send a message first)"};const r=String(n.cwd||s.workspace||process.cwd()),o=String(n.modelId||s.model||""),a=C(n.modeId||s.mode)??"full_auto",l=t.trim(),c=l?`${Q}
6
+ `)}class Z extends L{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitDone(e){this.emit("done",e)}emitError(e){if(this.listenerCount("error")===0){u.warn("cursor-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}class $ extends L{type="cursor";static STDERR_MAX_CHARS=8192;config;callbacks;alive=!1;stopped=!1;permissionHandler=null;internalApi=null;bindingStore=null;identity;inboundMessageIds=new ue;inboundQueue=[];pendingBySession=new Map;sessions=new Set;sessionRuntime=new Map;sessionSeq=0;lastUsageBySession=new Map;auditCaptures=new Map;completedAuditBoundaries=new Map;lastContextBySession=new Map;compactingSessions=new Set;pendingHandoffBySession=new Map;pendingQuestionByRequestId=new Map;pendingQuestionAnswerBySession=new Map;cachedAccountRateLimits=null;rateLimitsInflight=null;_availableModels=[];transcriptPathBySession=new Map;activeBySession=new Map;constructor(e,t){super(),this.config=e,this.callbacks=t;const n=e.options??{};this.bindingStore=n.bindingStore instanceof pe?n.bindingStore:null,this.identity=new oe("cursor-adapter",t.getAgentProfile)}async start(){this.alive=!0,this.stopped=!1,(this.config.options??{}).mcp_tools!==!1&&(this.internalApi=new de,this.internalApi.setInvokeHandler(async(t,n,s,r)=>this.callbacks.agentInvoke(t,n,r)),await this.internalApi.start()),this.notifyBindingReady(),this.refreshModels().then(()=>this.notifyBindingReady()).catch(()=>{}),this.refreshAccountRateLimits().then(()=>this.notifyBindingReady()).catch(()=>{})}get availableModels(){return this._availableModels}get availableModes(){return K.map(e=>({...e}))}async refreshModels(){try{const e={...process.env,...this.config.env??{}},t=await ge({command:this.config.command,env:e,cwd:process.cwd()});t.length>0&&(this._availableModels=t,u.info("cursor-adapter",`Loaded ${t.length} available models`))}catch(e){u.warn("cursor-adapter",`Failed to refresh models: ${e instanceof Error?e.message:String(e)}`)}}async stop(){this.stopped=!0,this.alive=!1;for(const e of this.activeBySession.values())C(e.child,"SIGTERM");this.activeBySession.clear(),this.transcriptPathBySession.clear(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null)}isAlive(){return this.alive}async createSession(e){const t=`cursor-${Date.now()}-${++this.sessionSeq}`;return this.sessions.add(t),this.sessionRuntime.set(t,{cwd:typeof e.cwd=="string"?e.cwd:void 0,modelId:typeof e.modelId=="string"?e.modelId:void 0,modeId:typeof e.modeId=="string"?e.modeId:void 0}),t}async resumeSession(e,t){this.sessions.add(e);const n=this.sessionRuntime.get(e)??{};this.sessionRuntime.set(e,{...n,cwd:typeof t?.cwd=="string"?t.cwd:n.cwd,modelId:typeof t?.modelId=="string"?t.modelId:n.modelId,modeId:typeof t?.modeId=="string"?t.modeId:n.modeId})}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(e){this.sessions.delete(e),this.sessionRuntime.delete(e),this.transcriptPathBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e),this.pendingQuestionAnswerBySession.delete(e),this.pendingHandoffBySession.delete(e);for(const[t,n]of this.pendingQuestionByRequestId)n.sessionId===e&&this.pendingQuestionByRequestId.delete(t)}sendPrompt(e){const t=new Z(e.adapterSessionId);if(!this.alive||this.stopped)return queueMicrotask(()=>t.emitError(new Error("adapter not running"))),t;const n=this.inboundQueue.shift()??{event_id:`cursor-evt-${Date.now()}`,session_id:e.adapterSessionId,content:e.text},s=e.adapterSessionId,r=this.pendingBySession.get(s)??[];return r.push({event:n,request:e,handle:t}),this.pendingBySession.set(s,r),this.tryStartNext(s),t}tryStartNext(e){if(this.compactingSessions.has(e)||this.activeBySession.has(e)||!this.alive||this.stopped)return;const t=this.pendingBySession.get(e);if(!t||t.length===0)return;const n=t.shift();t.length===0?this.pendingBySession.delete(e):this.pendingBySession.set(e,t),n&&this.startJob(n,!1,0)}startJob(e,t,n){const{event:s,request:r,handle:i}=e;s.audit?.enabled&&!this.auditCaptures.has(s.event_id)&&this.auditCaptures.set(s.event_id,[]);const o=r.adapterSessionId,a=this.sessionRuntime.get(r.adapterSessionId)??{},l=this.config.options??{},c=[...this.config.args??[]];c.push("-p","--output-format","stream-json"),l.trust!==!1&&c.push("--trust");const h=a.cwd||l.workspace;this.internalApi&&h&&(this.ensureWorkspaceMcpAndSkills(h),c.push("--approve-mcps")),h&&c.push("--workspace",h);const p=a.modelId||l.model;p&&c.push("--model",p);const _=I(a.modeId||l.mode)??"full_auto";_==="full_auto"?c.push("--yolo"):_==="plan"&&c.push("--plan");const v=a.cursorSessionId??this.bindingStore?.getAcpSessionId(r.adapterSessionId),b=!!(v&&l.use_continue!==!1&&!t);b&&c.push("--resume",v),c.push(this.buildPromptText(r));const m={...process.env,...this.config.env??{}},g=x(this.config.command,m);u.info("cursor-adapter",`job start: event=${s.event_id} session=${s.session_id} retry=${n}`);let S;try{S=B(g.command,[...g.prefixArgs,...c],{cwd:h||process.cwd(),env:g.env,stdio:["ignore","pipe","pipe"]}).process}catch(y){this.finishActive(o,"failed",`spawn failed: ${y instanceof Error?y.message:String(y)}`);return}this.callbacks.sendEventAck(s.event_id,s.session_id),this.emit("eventStarted",s.event_id,s.session_id);const f={event:s,request:r,handle:i,child:S,seq:0,done:!1,stderr:"",timer:null,idleTimer:null,toolCallsInFlight:new Set,toolCallsStarted:0,assistantTextEmitted:"",streamBuffer:"",lastIoAt:Date.now(),sawResult:!1,descendantBaseline:void 0,retryCount:n,usedContinue:b,workspace:h||process.cwd(),args:c};this.activeBySession.set(o,f),this.notifyBindingReady(o),this.armActiveIdleTimer(o);const w=r.timeoutMs&&r.timeoutMs>0?r.timeoutMs:0;w>0&&(f.timer=setTimeout(()=>{f.done||(C(S,"SIGTERM"),this.finishActive(o,"failed",`cursor agent timeout after ${w}ms`))},w)),E({input:S.stdout}).on("line",y=>this.handleStdoutLineForActive(f,y)),S.stderr?.on("data",y=>{if(f.done)return;const k=f.stderr+String(y??"");f.stderr=k.length>$.STDERR_MAX_CHARS?k.slice(-$.STDERR_MAX_CHARS):k,f.lastIoAt=Date.now(),this.armActiveIdleTimer(o)}),S.once("error",y=>{this.finishActive(o,"failed",`spawn failed: ${String(y?.message??y)}`)}),S.once("close",y=>{if(!f.done)if((y??0)===0)this.finishActive(o,"responded");else{if(this.shouldRetryWithoutContinue(f)){f.timer&&clearTimeout(f.timer),f.idleTimer&&clearTimeout(f.idleTimer),this.activeBySession.delete(o),this.startJob(e,!0,f.retryCount+1);return}const k=f.stderr.trim()||`cursor agent exited with code ${y??-1}`;this.finishActive(o,"failed",k)}})}async cancel(e){const t=this.activeBySession.get(e);t&&(C(t.child,"SIGTERM"),this.finishActive(e,"canceled","canceled"))}deliverInboundEvent(e){const t=String(e.session_id??"").trim();if(!t){u.warn("cursor-adapter",`Dropping event ${e.event_id}: missing session_id`),this.callbacks.sendEventResult(e.event_id,"failed","missing session_id");return}if(!this.alive||this.stopped){u.warn("cursor-adapter",`Dropping event ${e.event_id}: adapter not running`),this.callbacks.sendEventAck(e.event_id,t),this.callbacks.sendEventResult(e.event_id,"failed","adapter not running");return}const n={adapterSessionId:t,text:this.inboundMessageIds.inject(t,Me(String(e.content??""),e),e.msg_id),contextMessages:xe(e)},s=new Z(t),r=this.pendingBySession.get(t)??[];r.push({event:e,request:n,handle:s}),this.pendingBySession.set(t,r),u.info("cursor-adapter",`inbound queued: event=${e.event_id} session=${t} depth=${r.length}`),this.tryStartNext(t)}cancelSessionWork(e,t){const n=this.pendingBySession.get(e)??[];this.pendingBySession.delete(e);const s=this.activeBySession.get(e);s&&(this.killChildWithFallback(s.child),this.finishActive(e,"canceled",t));for(const r of n)this.callbacks.sendEventAck(r.event.event_id,r.event.session_id),this.callbacks.sendEventResult(r.event.event_id,"canceled",t),r.handle.emitDone({status:"canceled",error:t})}killChildWithFallback(e){C(e,"SIGTERM"),setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{C(e,"SIGKILL")}catch{}},5e3).unref()}deliverStopEvent(e,t){if(t){const n=this.activeBySession.get(t);if(n?.event.event_id===e){this.killChildWithFallback(n.child),this.finishActive(t,"canceled","stopped");return}const s=this.pendingBySession.get(t)??[],r=s.findIndex(i=>i.event.event_id===e);if(r>=0){const[i]=s.splice(r,1);s.length===0?this.pendingBySession.delete(t):this.pendingBySession.set(t,s),this.callbacks.sendEventAck(i.event.event_id,i.event.session_id),this.callbacks.sendEventResult(i.event.event_id,"canceled","stopped"),i.handle.emitDone({status:"canceled",error:"stopped"})}return}for(const[n,s]of this.activeBySession.entries())if(s.event.event_id===e){this.killChildWithFallback(s.child),this.finishActive(n,"canceled","stopped");return}for(const[n,s]of this.pendingBySession.entries()){const r=s.findIndex(o=>o.event.event_id===e);if(r<0)continue;const[i]=s.splice(r,1);s.length===0?this.pendingBySession.delete(n):this.pendingBySession.set(n,s),this.callbacks.sendEventAck(i.event.event_id,i.event.session_id),this.callbacks.sendEventResult(i.event.event_id,"canceled","stopped"),i.handle.emitDone({status:"canceled",error:"stopped"});return}}async handleLocalAction(e){const t=String(e.action_type??"").trim().toLowerCase(),n=e.params??{},s=String(n.session_id??"").trim(),r=e.action_id;if(t==="claude_interaction_reply")return String(n.kind??"").trim()==="permission"?(this.callbacks.sendLocalActionResult(r,"failed",void 0,"unsupported","Cursor adapter does not support interactive permission approvals"),{handled:!0,kind:"permission_unsupported"}):this.handleQuestionReply(e);switch(t){case"set_model":{const i=String(n.model_id??"").trim();if(!i||!s)return this.callbacks.sendLocalActionResult(r,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};const o=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...o,modelId:i}),this.notifyBindingReady(s);const a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(r,"ok",{outcome:"model_set",session_context:{model_id:i,mode_id:a.mode_id,modelId:i,modeId:a.mode_id},model_id:i,mode_id:a.mode_id,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"set_model"}}case"set_mode":{const i=I(n.mode_id);if(!i||!s)return this.callbacks.sendLocalActionResult(r,"failed",void 0,"invalid_params","mode_id must be approval, full_auto, or plan and session_id is required"),{handled:!0,kind:"set_mode"};const o=this.sessionRuntime.get(s)??{};this.sessionRuntime.set(s,{...o,modeId:i}),this.notifyBindingReady(s);const a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(r,"ok",{outcome:"mode_set",session_context:{model_id:a.model_id,mode_id:i,modelId:a.model_id,modeId:i},model_id:a.model_id,mode_id:i,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"set_mode"}}case"get_context":{const i=s?this.sessionRuntime.get(s):void 0,o=this.config.options??{},a=this.getToolbarMeta(s);return this.callbacks.sendLocalActionResult(r,"ok",{session_context:{model_id:a.model_id,mode_id:a.mode_id,cwd:i?.cwd??o.workspace??null},model_id:a.model_id,mode_id:a.mode_id,modelId:a.model_id,modeId:a.mode_id,cwd:i?.cwd??o.workspace??null,available_models:this.availableModels,available_modes:this.availableModes}),{handled:!0,kind:"get_context"}}case"get_rate_limits":{await this.refreshAccountRateLimits({force:!0});const i=this.getRateLimitsSnapshot(s||void 0);return this.callbacks.sendLocalActionResult(r,"ok",i),s&&this.notifyBindingReady(s),{handled:!0,kind:"get_rate_limits"}}case"get_session_usage":{const i=s?this.getUsageSnapshot(s):null;if(i){const o={inputTokens:i.total.input,outputTokens:i.total.output,cacheReadInputTokens:i.total.cacheRead,cacheCreationInputTokens:i.total.cacheWrite};this.callbacks.sendLocalActionResult(r,"ok",{sessionId:s,adapterType:"cursor",sampledAt:i.sampledAt,turns:i.turns,total:o,models:[{model:this.getToolbarMeta(s).model_id??"auto",turns:i.turns,total:o}]})}else this.callbacks.sendLocalActionResult(r,"failed",void 0,"usage_not_found","No usage data found for this session");return{handled:!0,kind:"get_session_usage"}}case"session_control":{const i=String(n.verb??"").trim().toLowerCase();if(i==="restart"&&s)this.cancelSessionWork(s,"restarted"),this.callbacks.sendLocalActionResult(r,"ok",{outcome:"restarted"});else if(i==="status"){const o=this.sessionRuntime.get(s),a=this.config.options??{},l=this.getToolbarMeta(s),c=this.activeBySession.has(s);this.callbacks.sendLocalActionResult(r,"ok",{verb:"status",status:c?"running":"idle",session_context:{model_id:l.model_id,mode_id:l.mode_id,cwd:o?.cwd??a.workspace??null},model_id:l.model_id,mode_id:l.mode_id,modelId:l.model_id,modeId:l.mode_id,cwd:o?.cwd??a.workspace??null,available_models:this.availableModels,available_modes:this.availableModes})}else this.callbacks.sendLocalActionResult(r,"failed",void 0,"invalid_verb",`Unsupported verb: ${i}`);return{handled:!0,kind:"session_control"}}default:return{handled:!1,kind:"unsupported"}}}getSupportedCommands(){return[{name:"compact",description:"\u538B\u7F29\u4E0A\u4E0B\u6587",args:"[instructions]"}]}async execCommand(e,t,n){return e!=="compact"?{status:"unsupported",message:`Unsupported command: ${e}`}:this.runCompactHandoff(n,t)}async runCompactHandoff(e,t=""){if(!e)return{status:"failed",message:"session_id is required"};if(this.compactingSessions.has(e))return{status:"failed",message:"compact already in progress"};if(this.activeBySession.has(e))return{status:"failed",message:"Cannot compact while a Cursor turn is active"};const n=this.sessionRuntime.get(e)??{},s=this.config.options??{},r=n.cursorSessionId??this.bindingStore?.getAcpSessionId(e)??null;if(!r)return{status:"failed",message:"No Cursor chat to compact (send a message first)"};this.compactingSessions.add(e);const i=String(n.cwd||s.workspace||process.cwd()),o=String(n.modelId||s.model||""),a=I(n.modeId||s.mode)??"full_auto",l=t.trim(),c=l?`${Q}
7
7
 
8
8
  Additional focus from user:
9
- ${l}`:Q;this.emit("pauseIntake","compaction"),u.info("cursor-adapter",`[compact] summarize resume=${i} session=${e}`);try{const h=await this.runPrintOnce({prompt:c,resumeChatId:i,cwd:r,modelId:o||void 0,modeId:a,timeoutMs:W});if(!h.ok||!h.text.trim())return{status:"failed",message:h.error??"Summarize failed (empty result)"};const p=await this.createEmptyChat();return p?(this.sessionRuntime.set(e,{...n,cwd:r,modelId:o||n.modelId,modeId:a,cursorSessionId:p}),this.transcriptPathBySession.delete(e),this.bindingStore?.setAcpSessionId(e,p),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e),this.pendingHandoffBySession.set(e,h.text.trim()),this.lastContextBySession.set(e,Se(0,ve(o))),this.notifyBindingReady(e),u.info("cursor-adapter",`[compact] handoff ready: old=${i} new=${p} summaryChars=${h.text.trim().length}`),{status:"ok",message:"Context compacted via summarize + new chat",data:{previousChatId:i,chatId:p}}):{status:"failed",message:"agent create-chat failed"}}finally{this.emit("resumeIntake","compaction")}}runPrintOnce(e){const t={...process.env,...this.config.env??{}},n=M(this.config.command,t),s=[...n.prefixArgs,...this.config.args??[]];s.push("-p","--output-format","stream-json"),this.config.options?.trust!==!1&&s.push("--trust"),e.cwd&&s.push("--workspace",e.cwd),e.modelId&&s.push("--model",e.modelId);const i=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 o;try{o=B(n.command,s,{cwd:e.cwd||process.cwd(),env:n.env,stdio:["ignore","pipe","pipe"]}).process}catch(f){r({ok:!1,text:"",error:`spawn failed: ${f instanceof Error?f.message:String(f)}`});return}let a="",l="",c="",h=!1;const p=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:W,_=setTimeout(()=>{h||(h=!0,this.killChildWithFallback(o),r({ok:!1,text:a,sessionId:l||void 0,error:`compact timeout after ${p}ms`}))},p);_.unref?.();const v=(f,y)=>{h||(h=!0,clearTimeout(_),r({ok:f,text:a,sessionId:l||void 0,error:y}))};q({input:o.stdout}).on("line",f=>{const y=f.trim();if(!y)return;let g;try{g=JSON.parse(y)}catch{return}if(g?.type!=="result")return;const m=typeof g?.result=="string"?g.result:"";m&&(a=m);const w=String(g?.session_id??"").trim();w&&(l=w)}),o.stderr?.on("data",f=>{c+=typeof f=="string"?f:f.toString("utf8")}),o.on("error",f=>v(!1,f.message)),o.on("close",f=>{if(!h){if(a.trim()){v(!0);return}v(!1,c.trim()||`cursor agent exited with code ${f??"unknown"}`)}})})}createEmptyChat(){const e={...process.env,...this.config.env??{}},t=M(this.config.command,e);return new Promise(n=>{let s;try{s=B(t.command,[...t.prefixArgs,"create-chat"],{cwd:process.cwd(),env:t.env,stdio:["ignore","pipe","pipe"]}).process}catch{n(null);return}let i="",r=!1;const o=setTimeout(()=>{r||(r=!0,this.killChildWithFallback(s),n(null))},3e4);o.unref?.(),s.stdout?.on("data",a=>{i+=typeof a=="string"?a:a.toString("utf8")}),s.on("error",()=>{r||(r=!0,clearTimeout(o),n(null))}),s.on("close",a=>{if(r)return;r=!0,clearTimeout(o);const l=i.trim().split(/\s+/)[0]??"";n(a===0&&/^[0-9a-f-]{16,}$/i.test(l)?l:null)})})}setPermissionHandler(e){this.permissionHandler=e}async ping(e){if(!this.alive||this.stopped||(this.config.options??{}).mcp_tools!==!1&&this.internalApi===null)return!1;for(const n of this.activeBySession.values()){const s=n.child?.pid;if(s&&!T(s))return!1}return!0}getStatus(){let e=0;for(const t of this.pendingBySession.values())e+=t.length;return{alive:this.alive,busy:this.activeBySession.size>0,sessions:this.sessions.size,details:{queueDepth:e+this.inboundQueue.length,activeSessions:this.activeBySession.size}}}getActiveEventIds(){const e=[];for(const t of this.activeBySession.values())t.event.event_id&&e.push(t.event.event_id);return e}clearActiveEventForShutdown(){for(const[e,t]of this.activeBySession)this.snapshotAuditBoundary(t.event.event_id,e);this.activeBySession.clear()}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}getMcpConfig(){return null}async probe(e){const t=this.getStatus();return{...await oe(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?V(e):null;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const n=N(t);return{recordPath:t,lastActivityMs:n.mtimeMs,freshMs:Date.now()-n.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}firstKnownCursorSessionId(){for(const e of this.activeBySession.keys()){const t=this.sessionRuntime.get(e);if(t?.cursorSessionId)return t.cursorSessionId}for(const e of this.sessionRuntime.values())if(e.cursorSessionId)return e.cursorSessionId;return null}getUsageSnapshot(e){return this.lastUsageBySession.get(e)??null}getRateLimitsSnapshot(e){const t=this.cachedAccountRateLimits,n=e?this.lastContextBySession.get(e)??null:null;if(!t)return{adapterType:"cursor",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:n,tokenUsage:null};const s=Date.parse(t.sampledAt),i=t.rateLimits?.usagePeriod??t.usagePeriod;return{adapterType:"cursor",available:t.available&&!!t.rateLimits,cached:!0,sampledAt:Number.isFinite(s)?s:Date.now(),rateLimits:t.rateLimits,...i?{usagePeriod:i}:{},contextWindow:n,tokenUsage:null,...t.displayMessage?{displayMessage:t.displayMessage}:{},...t.error?{error:t.error}:{}}}async refreshAccountRateLimits(e){const t=e?.force===!0,n=this.cachedAccountRateLimits,s=n?Date.now()-Date.parse(n.sampledAt):Number.POSITIVE_INFINITY;if(!t&&n&&Number.isFinite(s)&&s<6e4||this.rateLimitsInflight&&(await this.rateLimitsInflight,!t))return;const i=(async()=>{const r=await ge();if(this.cachedAccountRateLimits={available:r.available,sampledAt:r.sampledAt,rateLimits:r.rateLimits,usagePeriod:r.usagePeriod??r.rateLimits?.usagePeriod,displayMessage:r.displayMessage,error:r.error},r.available&&r.rateLimits){const o=r.rateLimits.usagePeriod;u.info("cursor-adapter",`[rate-limits] period=${o} total=${r.rateLimits.fiveHour.usedPercentage.toFixed(1)}% api=${r.rateLimits.sevenDay.usedPercentage.toFixed(1)}% resetsAt=${r.rateLimits.fiveHour.resetsAt}`+(r.displayMessage?` msg=${r.displayMessage}`:""))}else 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",o={model_id:i,mode_id:r,currentModelId:i,currentModeId:r,available_models:this.availableModels,available_modes:this.availableModes},a=this.cachedAccountRateLimits?.rateLimits;if(a?.fiveHour||a?.sevenDay){const c=Date.parse(this.cachedAccountRateLimits?.sampledAt??"")||Date.now();o.rate_limits={...a.fiveHour?{fiveHour:a.fiveHour}:{},...a.sevenDay?{sevenDay:a.sevenDay}:{},usagePeriod:a.usagePeriod,sampledAt:c}}const l=n?this.lastContextBySession.get(n):void 0;return l&&(o.context_window={usedPercentage:l.usedPercentage,remainingPercentage:l.remainingPercentage,usedTokens:l.usedTokens,sizeTokens:l.sizeTokens}),o}notifyBindingReady(e){if(!this.callbacks.sendUpdateBindingCard)return;const t=this.config.options??{},n=e||String(t.aibotSessionId??"");if(!n)return;const s=this.sessionRuntime.get(n),i=String(s?.cwd||t.workspace||"");i&&this.callbacks.sendUpdateBindingCard(n,this.activeBySession.has(n)?"busy":"ready",i,this.getToolbarMeta(n))}buildPromptText(e){let t;if(!e.contextMessages||e.contextMessages.length===0)t=e.text;else{const i=e.contextMessages.map(r=>`[${r.senderId}] ${r.content}`).join(`
9
+ ${l}`:Q;this.emit("pauseIntake","compaction"),u.info("cursor-adapter",`[compact] summarize resume=${r} session=${e}`);try{const h=await this.runPrintOnce({prompt:c,resumeChatId:r,cwd:i,modelId:o||void 0,modeId:a,timeoutMs:U});if(!h.ok||!h.text.trim())return{status:"failed",message:h.error??"Summarize failed (empty result)"};const p=await this.createEmptyChat();return p?(this.sessionRuntime.set(e,{...n,cwd:i,modelId:o||n.modelId,modeId:a,cursorSessionId:p}),this.transcriptPathBySession.delete(e),this.bindingStore?.setAcpSessionId(e,p),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e),this.pendingHandoffBySession.set(e,h.text.trim()),this.lastContextBySession.set(e,ye(0,_e(o))),this.notifyBindingReady(e),u.info("cursor-adapter",`[compact] handoff ready: old=${r} new=${p} summaryChars=${h.text.trim().length}`),{status:"ok",message:"Context compacted via summarize + new chat",data:{previousChatId:r,chatId:p}}):{status:"failed",message:"agent create-chat failed"}}finally{this.compactingSessions.delete(e),this.emit("resumeIntake","compaction")}}shouldAutoCompact(e){return(this.lastContextBySession.get(e)?.usedPercentage??0)>=W}runPrintOnce(e){const t={...process.env,...this.config.env??{}},n=x(this.config.command,t),s=[...n.prefixArgs,...this.config.args??[]];s.push("-p","--output-format","stream-json"),this.config.options?.trust!==!1&&s.push("--trust"),e.cwd&&s.push("--workspace",e.cwd),e.modelId&&s.push("--model",e.modelId);const r=I(e.modeId)??"full_auto";return r==="full_auto"?s.push("--yolo"):r==="plan"&&s.push("--plan"),e.resumeChatId&&s.push("--resume",e.resumeChatId),s.push(e.prompt),new Promise(i=>{let o;try{o=B(n.command,s,{cwd:e.cwd||process.cwd(),env:n.env,stdio:["ignore","pipe","pipe"]}).process}catch(m){i({ok:!1,text:"",error:`spawn failed: ${m instanceof Error?m.message:String(m)}`});return}let a="",l="",c="",h=!1;const p=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:U,_=setTimeout(()=>{h||(h=!0,this.killChildWithFallback(o),i({ok:!1,text:a,sessionId:l||void 0,error:`compact timeout after ${p}ms`}))},p);_.unref?.();const v=(m,g)=>{h||(h=!0,clearTimeout(_),i({ok:m,text:a,sessionId:l||void 0,error:g}))};E({input:o.stdout}).on("line",m=>{const g=m.trim();if(!g)return;let S;try{S=JSON.parse(g)}catch{return}if(S?.type!=="result")return;const f=typeof S?.result=="string"?S.result:"";f&&(a=f);const w=String(S?.session_id??"").trim();w&&(l=w)}),o.stderr?.on("data",m=>{c+=typeof m=="string"?m:m.toString("utf8")}),o.on("error",m=>v(!1,m.message)),o.on("close",m=>{if(!h){if(a.trim()){v(!0);return}v(!1,c.trim()||`cursor agent exited with code ${m??"unknown"}`)}})})}createEmptyChat(){const e={...process.env,...this.config.env??{}},t=x(this.config.command,e);return new Promise(n=>{let s;try{s=B(t.command,[...t.prefixArgs,"create-chat"],{cwd:process.cwd(),env:t.env,stdio:["ignore","pipe","pipe"]}).process}catch{n(null);return}let r="",i=!1;const o=setTimeout(()=>{i||(i=!0,this.killChildWithFallback(s),n(null))},3e4);o.unref?.(),s.stdout?.on("data",a=>{r+=typeof a=="string"?a:a.toString("utf8")}),s.on("error",()=>{i||(i=!0,clearTimeout(o),n(null))}),s.on("close",a=>{if(i)return;i=!0,clearTimeout(o);const l=r.trim().split(/\s+/)[0]??"";n(a===0&&/^[0-9a-f-]{16,}$/i.test(l)?l:null)})})}setPermissionHandler(e){this.permissionHandler=e}async ping(e){if(!this.alive||this.stopped||(this.config.options??{}).mcp_tools!==!1&&this.internalApi===null)return!1;for(const n of this.activeBySession.values()){const s=n.child?.pid;if(s&&!T(s))return!1}return!0}getStatus(){let e=0;for(const t of this.pendingBySession.values())e+=t.length;return{alive:this.alive,busy:this.activeBySession.size>0,sessions:this.sessions.size,details:{queueDepth:e+this.inboundQueue.length,activeSessions:this.activeBySession.size}}}getActiveEventIds(){const e=[];for(const t of this.activeBySession.values())t.event.event_id&&e.push(t.event.event_id);return e}clearActiveEventForShutdown(){for(const[e,t]of this.activeBySession)this.snapshotAuditBoundary(t.event.event_id,e);this.activeBySession.clear()}takeAuditBoundary(e){const t=this.completedAuditBoundaries.get(e);return t&&this.completedAuditBoundaries.delete(e),t}getMcpConfig(){return null}async probe(e){const t=this.getStatus();return{...await ae(this.config.command||"cursor-agent",{alive:t.alive,busy:t.busy,started:this.alive},e),session:this.probeSessionRecord()}}probeSessionRecord(){const e=this.firstKnownCursorSessionId(),t=e?Y(e):null;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const n=N(t);return{recordPath:t,lastActivityMs:n.mtimeMs,freshMs:Date.now()-n.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}firstKnownCursorSessionId(){for(const e of this.activeBySession.keys()){const t=this.sessionRuntime.get(e);if(t?.cursorSessionId)return t.cursorSessionId}for(const e of this.sessionRuntime.values())if(e.cursorSessionId)return e.cursorSessionId;return null}getUsageSnapshot(e){return this.lastUsageBySession.get(e)??null}getRateLimitsSnapshot(e){const t=this.cachedAccountRateLimits,n=e?this.lastContextBySession.get(e)??null:null;if(!t)return{adapterType:"cursor",available:!1,cached:!1,sampledAt:null,rateLimits:null,contextWindow:n,tokenUsage:null};const s=Date.parse(t.sampledAt),r=t.rateLimits?.usagePeriod??t.usagePeriod;return{adapterType:"cursor",available:t.available&&!!t.rateLimits,cached:!0,sampledAt:Number.isFinite(s)?s:Date.now(),rateLimits:t.rateLimits,...r?{usagePeriod:r}:{},contextWindow:n,tokenUsage:null,...t.displayMessage?{displayMessage:t.displayMessage}:{},...t.error?{error:t.error}:{}}}async refreshAccountRateLimits(e){const t=e?.force===!0,n=this.cachedAccountRateLimits,s=n?Date.now()-Date.parse(n.sampledAt):Number.POSITIVE_INFINITY;if(!t&&n&&Number.isFinite(s)&&s<6e4||this.rateLimitsInflight&&(await this.rateLimitsInflight,!t))return;const r=(async()=>{const i=await Se();if(this.cachedAccountRateLimits={available:i.available,sampledAt:i.sampledAt,rateLimits:i.rateLimits,usagePeriod:i.usagePeriod??i.rateLimits?.usagePeriod,displayMessage:i.displayMessage,error:i.error},i.available&&i.rateLimits){const o=i.rateLimits.usagePeriod;u.info("cursor-adapter",`[rate-limits] period=${o} total=${i.rateLimits.fiveHour.usedPercentage.toFixed(1)}% api=${i.rateLimits.sevenDay.usedPercentage.toFixed(1)}% resetsAt=${i.rateLimits.fiveHour.resetsAt}`+(i.displayMessage?` msg=${i.displayMessage}`:""))}else u.warn("cursor-adapter",`[rate-limits] unavailable: ${i.error??"unknown"}`)})();this.rateLimitsInflight=r.finally(()=>{this.rateLimitsInflight=null}),await this.rateLimitsInflight}getToolbarMeta(e){const t=this.config.options??{},n=e||String(t.aibotSessionId??""),s=n?this.sessionRuntime.get(n):void 0,r=String(s?.modelId||t.model||"auto"),i=I(s?.modeId||t.mode)??"full_auto",o={model_id:r,mode_id:i,currentModelId:r,currentModeId:i,available_models:this.availableModels,available_modes:this.availableModes},a=this.cachedAccountRateLimits?.rateLimits;if(a?.fiveHour||a?.sevenDay){const c=Date.parse(this.cachedAccountRateLimits?.sampledAt??"")||Date.now();o.rate_limits={...a.fiveHour?{fiveHour:a.fiveHour}:{},...a.sevenDay?{sevenDay:a.sevenDay}:{},usagePeriod:a.usagePeriod,sampledAt:c}}const l=n?this.lastContextBySession.get(n):void 0;return l&&(o.context_window={usedPercentage:l.usedPercentage,remainingPercentage:l.remainingPercentage,usedTokens:l.usedTokens,sizeTokens:l.sizeTokens}),o}notifyBindingReady(e){if(!this.callbacks.sendUpdateBindingCard)return;const t=this.config.options??{},n=e||String(t.aibotSessionId??"");if(!n)return;const s=this.sessionRuntime.get(n),r=String(s?.cwd||t.workspace||"");r&&this.callbacks.sendUpdateBindingCard(n,this.activeBySession.has(n)?"busy":"ready",r,this.getToolbarMeta(n))}buildPromptText(e){let t;if(!e.contextMessages||e.contextMessages.length===0)t=e.text;else{const r=e.contextMessages.map(i=>`[${i.senderId}] ${i.content}`).join(`
10
10
  `);t=R(e.text,`[Conversation context]
11
- ${i}`)}const n=this.pendingQuestionAnswerBySession.get(e.adapterSessionId);n&&(this.pendingQuestionAnswerBySession.delete(e.adapterSessionId),t=R(t,`[User answered a previous agent question]
11
+ ${r}`)}const n=this.pendingQuestionAnswerBySession.get(e.adapterSessionId);n&&(this.pendingQuestionAnswerBySession.delete(e.adapterSessionId),t=R(t,`[User answered a previous agent question]
12
12
  ${n}`));const s=this.pendingHandoffBySession.get(e.adapterSessionId);return s&&(this.pendingHandoffBySession.delete(e.adapterSessionId),t=R(t,`[Previous conversation summary \u2014 continue from this handoff]
13
- ${s}`)),this.identity.injectOnce(e.adapterSessionId,t)}handleStdoutLineForActive(e,t){if(e.done)return;const n=t.trim();if(!n)return;e.lastIoAt=Date.now();const{event:s}=e;let i;try{i=JSON.parse(n)}catch{this.armActiveIdleTimer(e.request.adapterSessionId);return}const r=this.auditCaptures.get(s.event_id);if(r&&i&&typeof i=="object"&&r.push({sequence:r.length,observedAt:new Date().toISOString(),event:structuredClone(i)}),i?.type==="tool_call"){const l=String(i?.call_id??""),c=String(i?.subtype??"");l&&(c==="started"||c==="start"?(this.flushAssistantStreamBuffer(e),e.descendantBaseline===void 0&&this.captureDescendantBaseline(e),e.toolCallsInFlight.add(l),e.toolCallsStarted+=1,this.handleSpecialToolCallStarted(e,i)):U.has(c)&&e.toolCallsInFlight.delete(l))}this.armActiveIdleTimer(e.request.adapterSessionId);const o=Ce(i);o&&this.callbacks.sendRawEventEnvelope?.(s.event_id,s.session_id,o);const a=Re(i,e.assistantTextEmitted);if(a&&this.enqueueAssistantStreamDelta(e,a),i?.type==="result"){e.sawResult=!0;const l=typeof i?.result=="string"?i.result.trim():"";l&&(e.assistantTextEmitted?l.startsWith(e.assistantTextEmitted)&&l.length>e.assistantTextEmitted.length&&this.enqueueAssistantStreamDelta(e,l.slice(e.assistantTextEmitted.length)):this.enqueueAssistantStreamDelta(e,l)),this.flushAssistantStreamBuffer(e);const c=String(i?.session_id??"").trim();if(c){const m=this.sessionRuntime.get(e.request.adapterSessionId)??{};m.cursorSessionId!==c&&this.transcriptPathBySession.delete(e.request.adapterSessionId),this.sessionRuntime.set(e.request.adapterSessionId,{...m,cursorSessionId:c}),this.bindingStore?.setAcpSessionId(e.request.adapterSessionId,c)}const h=i?.usage??{},p=this.lastUsageBySession.get(e.request.adapterSessionId);this.lastUsageBySession.set(e.request.adapterSessionId,{sampledAt:new Date().toISOString(),turns:(p?.turns??0)+1,total:{input:(p?.total.input??0)+Number(h.inputTokens??0),output:(p?.total.output??0)+Number(h.outputTokens??0),cacheRead:(p?.total.cacheRead??0)+Number(h.cacheReadTokens??0),cacheWrite:(p?.total.cacheWrite??0)+Number(h.cacheWriteTokens??0)}});const _=String((this.sessionRuntime.get(e.request.adapterSessionId)?.modelId??this.config.options?.model??"")||""),v=Math.max(1,(e.toolCallsStarted??0)+1),b=Number(h.inputTokens??0),f=Number(h.cacheReadTokens??0),y=Number(h.cacheWriteTokens??0),g=ye({inputTokens:b,cacheReadTokens:f,cacheWriteTokens:y},_,{apiRounds:v});g&&(this.lastContextBySession.set(e.request.adapterSessionId,g),u.info("cursor-adapter",`[context_window] used=${g.usedTokens} size=${g.sizeTokens} pct=${g.usedPercentage.toFixed(1)}% model=${_||"auto"} rawIn=${b} rawCache=${f} rawWrite=${y} apiRounds=${v}`))}}handleSpecialToolCallStarted(e,t){const n=z(t);if(G(n.toolName)){const s=Ie(n.toolInput);s?(e.seq+=1,this.callbacks.sendStreamChunk(e.event.event_id,e.event.session_id,s,e.seq,!1),u.info("cursor-adapter",`CreatePlan forwarded as stream text: event=${e.event.event_id} chars=${s.length}`)):(e.seq+=1,this.callbacks.sendStreamChunk(e.event.event_id,e.event.session_id,"[CreatePlan] \u65B9\u6848\u5185\u5BB9\u89E3\u6790\u5931\u8D25\uFF0C\u672A\u4E0B\u53D1\u6B63\u6587\u3002",e.seq,!1),u.warn("cursor-adapter",`CreatePlan missing plan body: event=${e.event.event_id}`));return}J(n.toolName)&&this.emitAskQuestionCard(e,n.toolInput)}emitAskQuestionCard(e,t){const n=e.event,s=ke(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=ee(),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+x}),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>x+3e4:!0;if(!s||i)return this.pendingQuestionByRequestId.delete(n),this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"interaction_request_not_pending","The question is no longer pending; the reply was not delivered."),{handled:!0,kind:"question_reply_not_pending"};const r=t.resolution??{},o=String(r.type??"");if(o==="action"&&String(r.value??"")==="cancel")return this.pendingQuestionByRequestId.delete(n),this.callbacks.sendLocalActionResult(e.action_id,"ok",{request_id:n,resolution:"cancel"}),{handled:!0,kind:"question_reply_cancel"};let a="";return o==="text"?a=String(r.value??""):o==="map"&&(a=(Array.isArray(r.entries)?r.entries:[]).map(c=>c.value).join(", ")),a?(this.pendingQuestionByRequestId.delete(n),this.pendingQuestionAnswerBySession.set(s.sessionId,a),this.callbacks.sendLocalActionResult(e.action_id,"ok",{request_id:n,resolution:"answer"}),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>=Ae&&this.flushAssistantStreamBuffer(e))}flushAssistantStreamBuffer(e){if(!e.streamBuffer)return;const t=e.streamBuffer;e.streamBuffer="",e.seq+=1,this.callbacks.sendStreamChunk(e.event.event_id,e.event.session_id,t,e.seq,!1,void 0,void 0)}captureDescendantBaseline(e){const t=e.child?.pid;if(!t){e.descendantBaseline=null;return}try{e.descendantBaseline=new Set(me(t)),u.info("cursor-adapter",`Liveness baseline captured for ${e.event.event_id}: ${e.descendantBaseline.size} resident descendant(s)`)}catch{e.descendantBaseline=null,u.warn("cursor-adapter",`Liveness baseline capture failed for ${e.event.event_id}; tool-descendant extend disabled`)}}shouldExtendByLiveness(e){const t=this.activeBySession.get(e);if(!t||t.done)return!1;const n=t.child?.pid;if(!n||!T(n)||t.sawResult)return!1;if(t.toolCallsInFlight.size>0&&t.descendantBaseline instanceof Set){let l=0;try{l=he(n,t.descendantBaseline)}catch{l=0}if(l>0)return t.livenessExtendStartAt=void 0,u.info("cursor-adapter",`Liveness check: tool descendants for ${t.event.event_id} (descendants=${l}, toolsInFlight=${t.toolCallsInFlight.size}), extending without budget`),!0}const s=Date.now(),i=s-t.lastIoAt,r=this.transcriptFreshMsForSession(e);if(i<j||r!==null&&r<j)return t.livenessExtendStartAt=s,u.info("cursor-adapter",`Liveness check: fresh progress for ${t.event.event_id} (ioAge=${i}ms, transcriptAge=${r??"n/a"}, toolsInFlight=${t.toolCallsInFlight.size}), extending`),!0;const a=t.livenessExtendStartAt??s;return t.livenessExtendStartAt===void 0&&(t.livenessExtendStartAt=a),s-a>O?(u.warn("cursor-adapter",`Liveness extension budget exhausted for ${t.event.event_id} (no progress for ${Math.round((s-a)/6e4)}min), allowing idle kill`),!1):(u.info("cursor-adapter",`Liveness check: turn in progress for ${t.event.event_id} (toolsInFlight=${t.toolCallsInFlight.size}, ioAge=${i}ms), extending`),!0)}transcriptFreshMsForSession(e){const t=this.sessionRuntime.get(e)?.cursorSessionId;if(!t)return null;let n=this.transcriptPathBySession.get(e);if(!n){const s=V(t);if(!s)return null;this.transcriptPathBySession.set(e,s),n=s}try{return Date.now()-N(n).mtimeMs}catch{return this.transcriptPathBySession.delete(e),null}}hasPendingQuestionForSession(e){const t=Date.now();for(const[n,s]of this.pendingQuestionByRequestId)if(s.sessionId===e){if(t-s.createdAt>x){this.pendingQuestionByRequestId.delete(n);continue}return!0}return!1}armActiveIdleTimer(e){const t=this.activeBySession.get(e);!t||t.done||(t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{if(t.done)return;if(this.hasPendingQuestionForSession(e)){u.info("cursor-adapter",`Idle timeout skipped: awaiting AskQuestion for ${t.event.event_id}, resetting timer`),this.armActiveIdleTimer(e);return}if(this.shouldExtendByLiveness(e)){this.armActiveIdleTimer(e);return}if(t.sawResult){u.warn("cursor-adapter",`Idle after result with no close \u2014 finishing as responded: event=${t.event.event_id} session=${e}`),this.killChildWithFallback(t.child),this.finishActive(e,"responded");return}const n=t.child?.pid,i=!!(n&&T(n))?`liveness budget exhausted after ${O/6e4}min`:"child process dead";u.error("cursor-adapter",`Idle timeout (${i}, toolsInFlight=${t.toolCallsInFlight.size}) \u2014 killing cursor child: event=${t.event.event_id} session=${e}`),this.killChildWithFallback(t.child),this.finishActive(e,"failed",`idle timeout: ${i}`)},_e),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.snapshotAuditBoundary(s.event.event_id,e),this.emit("eventDone",s.event.event_id),this.callbacks.sendEventResult(s.event.event_id,t,n),t==="responded"?s.handle.emitDone({status:"completed"}):t==="canceled"?s.handle.emitDone({status:"canceled",error:n}):s.handle.emitDone({status:"failed",error:n}),this.activeBySession.delete(e),this.notifyBindingReady(e),this.tryStartNext(e)}snapshotAuditBoundary(e,t){const n=this.auditCaptures.get(e);if(!n)return;const s=this.sessionRuntime.get(t);this.completedAuditBoundaries.set(e,{adapterType:"cursor",providerSessionId:s?.cursorSessionId,cursorEvidence:{events:n}}),this.auditCaptures.delete(e)}shouldRetryWithoutContinue(e){if(!e.usedContinue||e.retryCount>0)return!1;const t=e.stderr.toLowerCase(),n=t.includes("resume")||t.includes("continue")||t.includes("chat")||t.includes("session"),s=t.includes("not found")||t.includes("no previous session")||t.includes("does not exist")||t.includes("invalid");return n&&s}ensureWorkspaceMcpAndSkills(e){if(!this.internalApi)return;this.ensureCursorMcpConfig(e,this.internalApi.url);const t=A(F(),".cursor","skills"),n=ue(t);n.length>0&&u.info("cursor-adapter",`Synced connector skills to ${t}: [${n.join(", ")}]`)}ensureCursorMcpConfig(e,t){const n=de(this.callbacks.getAgentId?.()),s={command:process.execPath,args:[se(ne(import.meta.url),"../../../mcp/acp-mcp-server.js"),"--api-url",t]},i=[e],r=this.resolveGitRoot(e);r&&r!==e&&i.push(r);let o=null;for(const a of i){const l=this.writeCursorMcpConfig(a,n,s,t);!o&&l&&(o=l)}o&&this.recordCursorMcpRegistry(e,o,s)}resolveGitRoot(e){try{return Z("git",["-C",e,"rev-parse","--show-toplevel"],{timeout:5e3,stdio:["ignore","pipe","ignore"],windowsHide:!0}).toString("utf8").trim()||null}catch{return null}}writeCursorMcpConfig(e,t,n,s){try{const i=A(e,".cursor"),r=A(i,"mcp.json");E(i,{recursive:!0});let o={};try{o=JSON.parse(P(r,"utf8"))}catch{o={}}(!o.mcpServers||typeof o.mcpServers!="object")&&(o.mcpServers={});const a=le(o.mcpServers,s);return o.mcpServers[t]=n,D(r,`${JSON.stringify(o,null,2)}
14
- `,"utf8"),u.info("cursor-adapter",`MCP config synced: dir=${e} file=${r} server=${t}${a.length>0?` pruned=${a.join(",")}`:""}`),r}catch(i){return u.warn("cursor-adapter",`Failed to ensure ${A(e,".cursor","mcp.json")}: ${String(i)}`),null}}recordCursorMcpRegistry(e,t,n){try{const s=A(ie.data,"cursor"),i=A(s,"mcp-registry.json");E(s,{recursive:!0});let r={};try{r=JSON.parse(P(i,"utf8"))}catch{r={}}r[e]={mcp_path:t,server:n,updated_at:new Date().toISOString()},D(i,`${JSON.stringify(r,null,2)}
15
- `,"utf8")}catch(s){u.warn("cursor-adapter",`Failed to record MCP registry: ${String(s)}`)}}}export{X as CURSOR_MODE_OPTIONS,$ as CursorAdapter,Re as extractCursorAssistantStreamDelta,V as findCursorTranscript,Ie as formatCursorCreatePlanText,J as isCursorAskQuestionTool,G as isCursorCreatePlanTool,Ce as mapCursorStreamJsonToRawEnvelope,ke as parseCursorAskQuestionPayload};
13
+ ${s}`)),this.identity.injectOnce(e.adapterSessionId,t)}handleStdoutLineForActive(e,t){if(e.done)return;const n=t.trim();if(!n)return;e.lastIoAt=Date.now();const{event:s}=e;let r;try{r=JSON.parse(n)}catch{this.armActiveIdleTimer(e.request.adapterSessionId);return}this.rememberCursorChatId(e.request.adapterSessionId,r?.session_id);const i=this.auditCaptures.get(s.event_id);if(i&&r&&typeof r=="object"&&i.push({sequence:i.length,observedAt:new Date().toISOString(),event:structuredClone(r)}),r?.type==="tool_call"){const l=String(r?.call_id??""),c=String(r?.subtype??"");l&&(c==="started"||c==="start"?(this.flushAssistantStreamBuffer(e),e.descendantBaseline===void 0&&this.captureDescendantBaseline(e),e.toolCallsInFlight.add(l),e.toolCallsStarted+=1,this.handleSpecialToolCallStarted(e,r)):H.has(c)&&e.toolCallsInFlight.delete(l))}this.armActiveIdleTimer(e.request.adapterSessionId);const o=Re(r);o&&this.callbacks.sendRawEventEnvelope?.(s.event_id,s.session_id,o);const a=Be(r,e.assistantTextEmitted);if(a&&this.enqueueAssistantStreamDelta(e,a),r?.type==="result"){e.sawResult=!0;const l=typeof r?.result=="string"?r.result.trim():"";l&&(e.assistantTextEmitted?l.startsWith(e.assistantTextEmitted)&&l.length>e.assistantTextEmitted.length&&this.enqueueAssistantStreamDelta(e,l.slice(e.assistantTextEmitted.length)):this.enqueueAssistantStreamDelta(e,l)),this.flushAssistantStreamBuffer(e);const c=r?.usage??{},h=this.lastUsageBySession.get(e.request.adapterSessionId);this.lastUsageBySession.set(e.request.adapterSessionId,{sampledAt:new Date().toISOString(),turns:(h?.turns??0)+1,total:{input:(h?.total.input??0)+Number(c.inputTokens??0),output:(h?.total.output??0)+Number(c.outputTokens??0),cacheRead:(h?.total.cacheRead??0)+Number(c.cacheReadTokens??0),cacheWrite:(h?.total.cacheWrite??0)+Number(c.cacheWriteTokens??0)}});const p=String((this.sessionRuntime.get(e.request.adapterSessionId)?.modelId??this.config.options?.model??"")||""),_=Math.max(1,(e.toolCallsStarted??0)+1),v=Number(c.inputTokens??0),b=Number(c.cacheReadTokens??0),m=Number(c.cacheWriteTokens??0),g=ve({inputTokens:v,cacheReadTokens:b,cacheWriteTokens:m},p,{apiRounds:_});g&&(this.lastContextBySession.set(e.request.adapterSessionId,g),u.info("cursor-adapter",`[context_window] used=${g.usedTokens} size=${g.sizeTokens} pct=${g.usedPercentage.toFixed(1)}% model=${p||"auto"} rawIn=${v} rawCache=${b} rawWrite=${m} apiRounds=${_}`))}}handleSpecialToolCallStarted(e,t){const n=z(t);if(X(n.toolName)){const s=Ie(n.toolInput);s?(e.seq+=1,this.callbacks.sendStreamChunk(e.event.event_id,e.event.session_id,s,e.seq,!1),u.info("cursor-adapter",`CreatePlan forwarded as stream text: event=${e.event.event_id} chars=${s.length}`)):(e.seq+=1,this.callbacks.sendStreamChunk(e.event.event_id,e.event.session_id,"[CreatePlan] \u65B9\u6848\u5185\u5BB9\u89E3\u6790\u5931\u8D25\uFF0C\u672A\u4E0B\u53D1\u6B63\u6587\u3002",e.seq,!1),u.warn("cursor-adapter",`CreatePlan missing plan body: event=${e.event.event_id}`));return}G(n.toolName)&&this.emitAskQuestionCard(e,n.toolInput)}emitAskQuestionCard(e,t){const n=e.event,s=Ce(t);if(!s){e.seq+=1,this.callbacks.sendStreamChunk(n.event_id,n.session_id,"[AskQuestion] \u95EE\u9898\u5185\u5BB9\u89E3\u6790\u5931\u8D25\uFF0C\u672A\u4E0B\u53D1\u95EE\u9898\u5361\u3002",e.seq,!1),u.warn("cursor-adapter",`AskQuestion parse failed: event=${n.event_id}`);return}if(!this.callbacks.sendAgentQuestionCard){u.warn("cursor-adapter","AskQuestion skipped: sendAgentQuestionCard callback not wired");return}const r=te(),i=Date.now();this.pendingQuestionByRequestId.set(r,{eventId:n.event_id,sessionId:n.session_id,createdAt:i}),this.callbacks.sendAgentQuestionCard(n.event_id,n.session_id,{request_id:r,mode:"form",questions:s,expires_at:i+M}),u.info("cursor-adapter",`Sent agent_question card: request_id=${r} questions=${s.length} event=${n.event_id}`)}async handleQuestionReply(e){const t=e.params??{},n=String(t.request_id??"").trim();if(!n)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"request_id_required","request_id is required"),{handled:!0,kind:"question_reply_no_id"};const s=this.pendingQuestionByRequestId.get(n),r=s?Date.now()-s.createdAt>M+3e4:!0;if(!s||r)return this.pendingQuestionByRequestId.delete(n),this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"interaction_request_not_pending","The question is no longer pending; the reply was not delivered."),{handled:!0,kind:"question_reply_not_pending"};const i=t.resolution??{},o=String(i.type??"");if(o==="action"&&String(i.value??"")==="cancel")return this.pendingQuestionByRequestId.delete(n),this.callbacks.sendLocalActionResult(e.action_id,"ok",{request_id:n,resolution:"cancel"}),{handled:!0,kind:"question_reply_cancel"};let a="";return o==="text"?a=String(i.value??""):o==="map"&&(a=(Array.isArray(i.entries)?i.entries:[]).map(c=>c.value).join(", ")),a?(this.pendingQuestionByRequestId.delete(n),this.pendingQuestionAnswerBySession.set(s.sessionId,a),this.callbacks.sendLocalActionResult(e.action_id,"ok",{request_id:n,resolution:"answer"}),u.info("cursor-adapter",`Question reply cached for next prompt: request_id=${n} session=${s.sessionId}`),{handled:!0,kind:"question_reply"}):(this.pendingQuestionByRequestId.delete(n),this.callbacks.sendLocalActionResult(e.action_id,"ok",{request_id:n,resolution:"cancel"}),{handled:!0,kind:"question_reply_empty"})}enqueueAssistantStreamDelta(e,t){t&&(e.assistantTextEmitted+=t,e.streamBuffer+=t,e.streamBuffer.length>=be&&this.flushAssistantStreamBuffer(e))}flushAssistantStreamBuffer(e){if(!e.streamBuffer)return;const t=e.streamBuffer;e.streamBuffer="",e.seq+=1,this.callbacks.sendStreamChunk(e.event.event_id,e.event.session_id,t,e.seq,!1,void 0,void 0)}captureDescendantBaseline(e){const t=e.child?.pid;if(!t){e.descendantBaseline=null;return}try{e.descendantBaseline=new Set(fe(t)),u.info("cursor-adapter",`Liveness baseline captured for ${e.event.event_id}: ${e.descendantBaseline.size} resident descendant(s)`)}catch{e.descendantBaseline=null,u.warn("cursor-adapter",`Liveness baseline capture failed for ${e.event.event_id}; tool-descendant extend disabled`)}}shouldExtendByLiveness(e){const t=this.activeBySession.get(e);if(!t||t.done)return!1;const n=t.child?.pid;if(!n||!T(n)||t.sawResult)return!1;if(t.toolCallsInFlight.size>0&&t.descendantBaseline instanceof Set){let h=0;try{h=me(n,t.descendantBaseline)}catch{h=0}if(h>0)return t.livenessExtendStartAt=void 0,u.info("cursor-adapter",`Liveness check: tool descendants for ${t.event.event_id} (descendants=${h}, toolsInFlight=${t.toolCallsInFlight.size}), extending without budget`),!0}const s=Date.now(),r=s-t.lastIoAt,i=this.transcriptFreshMsForSession(e);if(r<j||i!==null&&i<j)return t.livenessExtendStartAt=s,u.info("cursor-adapter",`Liveness check: fresh progress for ${t.event.event_id} (ioAge=${r}ms, transcriptAge=${i??"n/a"}, toolsInFlight=${t.toolCallsInFlight.size}), extending`),!0;const a=i===null?0:s-i,l=Math.max(t.lastIoAt,a);t.livenessExtendStartAt===void 0?t.livenessExtendStartAt=s:l>t.livenessExtendStartAt&&(t.livenessExtendStartAt=l);const c=t.livenessExtendStartAt??s;return s-c>O?(u.warn("cursor-adapter",`Liveness extension budget exhausted for ${t.event.event_id} (no progress for ${Math.round((s-c)/6e4)}min), allowing idle kill`),!1):(u.info("cursor-adapter",`Liveness check: turn in progress for ${t.event.event_id} (toolsInFlight=${t.toolCallsInFlight.size}, ioAge=${r}ms), extending`),!0)}rememberCursorChatId(e,t){const n=String(t??"").trim();if(!n)return;const s=this.sessionRuntime.get(e)??{};s.cursorSessionId!==n&&this.transcriptPathBySession.delete(e),this.sessionRuntime.set(e,{...s,cursorSessionId:n}),this.bindingStore?.setAcpSessionId(e,n)}transcriptFreshMsForSession(e){const t=this.sessionRuntime.get(e)?.cursorSessionId;if(!t)return null;let n=this.transcriptPathBySession.get(e);if(!n){const s=Y(t);if(!s)return null;this.transcriptPathBySession.set(e,s),n=s}try{return Date.now()-N(n).mtimeMs}catch{return this.transcriptPathBySession.delete(e),null}}hasPendingQuestionForSession(e){const t=Date.now();for(const[n,s]of this.pendingQuestionByRequestId)if(s.sessionId===e){if(t-s.createdAt>M){this.pendingQuestionByRequestId.delete(n);continue}return!0}return!1}armActiveIdleTimer(e){const t=this.activeBySession.get(e);!t||t.done||(t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{if(t.done)return;if(this.hasPendingQuestionForSession(e)){u.info("cursor-adapter",`Idle timeout skipped: awaiting AskQuestion for ${t.event.event_id}, resetting timer`),this.armActiveIdleTimer(e);return}if(this.shouldExtendByLiveness(e)){this.armActiveIdleTimer(e);return}if(t.sawResult){u.warn("cursor-adapter",`Idle after result with no close \u2014 finishing as responded: event=${t.event.event_id} session=${e}`),this.killChildWithFallback(t.child),this.finishActive(e,"responded");return}const n=t.child?.pid,r=!!(n&&T(n))?`liveness budget exhausted after ${O/6e4}min`:"child process dead";u.error("cursor-adapter",`Idle timeout (${r}, toolsInFlight=${t.toolCallsInFlight.size}) \u2014 killing cursor child: event=${t.event.event_id} session=${e}`),this.killChildWithFallback(t.child),this.finishActive(e,"failed",`idle timeout: ${r}`)},Ae),t.idleTimer.unref?.())}finishActive(e,t,n){const s=this.activeBySession.get(e);if(!s)return;s.done=!0,s.timer&&clearTimeout(s.timer),s.idleTimer&&clearTimeout(s.idleTimer),this.flushAssistantStreamBuffer(s),s.seq+=1;const r=String(s.event.quoted_message_id??"").trim()||void 0;if(this.callbacks.sendStreamChunk(s.event.event_id,s.event.session_id,"",s.seq,!0,void 0,r),u.info("cursor-adapter",`job finish: event=${s.event.event_id} session=${s.event.session_id} status=${t}${n?` msg=${n}`:""}`),this.snapshotAuditBoundary(s.event.event_id,e),this.emit("eventDone",s.event.event_id),this.callbacks.sendEventResult(s.event.event_id,t,n),t==="responded"?s.handle.emitDone({status:"completed"}):t==="canceled"?s.handle.emitDone({status:"canceled",error:n}):s.handle.emitDone({status:"failed",error:n}),this.activeBySession.delete(e),this.notifyBindingReady(e),t==="responded"&&this.shouldAutoCompact(e)){const i=this.lastContextBySession.get(e)?.usedPercentage??0;u.info("cursor-adapter",`[auto-compact] context_window usedPercentage=${i.toFixed(1)}% >= ${W}%, scheduling compact session=${e}`),this.runCompactHandoff(e).finally(()=>{this.tryStartNext(e)});return}this.tryStartNext(e)}snapshotAuditBoundary(e,t){const n=this.auditCaptures.get(e);if(!n)return;const s=this.sessionRuntime.get(t);this.completedAuditBoundaries.set(e,{adapterType:"cursor",providerSessionId:s?.cursorSessionId,cursorEvidence:{events:n}}),this.auditCaptures.delete(e)}shouldRetryWithoutContinue(e){if(!e.usedContinue||e.retryCount>0)return!1;const t=e.stderr.toLowerCase(),n=t.includes("resume")||t.includes("continue")||t.includes("chat")||t.includes("session"),s=t.includes("not found")||t.includes("no previous session")||t.includes("does not exist")||t.includes("invalid");return n&&s}ensureWorkspaceMcpAndSkills(e){if(!this.internalApi)return;this.ensureCursorMcpConfig(e,this.internalApi.url);const t=A(F(),".cursor","skills"),n=he(t);n.length>0&&u.info("cursor-adapter",`Synced connector skills to ${t}: [${n.join(", ")}]`)}ensureCursorMcpConfig(e,t){const n=le(this.callbacks.getAgentId?.()),s={command:process.execPath,args:[ne(ie(import.meta.url),"../../../mcp/acp-mcp-server.js"),"--api-url",t]},r=[e],i=this.resolveGitRoot(e);i&&i!==e&&r.push(i);let o=null;for(const a of r){const l=this.writeCursorMcpConfig(a,n,s,t);!o&&l&&(o=l)}o&&this.recordCursorMcpRegistry(e,o,s)}resolveGitRoot(e){try{return ee("git",["-C",e,"rev-parse","--show-toplevel"],{timeout:5e3,stdio:["ignore","pipe","ignore"],windowsHide:!0}).toString("utf8").trim()||null}catch{return null}}writeCursorMcpConfig(e,t,n,s){try{const r=A(e,".cursor"),i=A(r,"mcp.json");P(r,{recursive:!0});let o={};try{o=JSON.parse(q(i,"utf8"))}catch{o={}}(!o.mcpServers||typeof o.mcpServers!="object")&&(o.mcpServers={});const a=ce(o.mcpServers,s);return o.mcpServers[t]=n,D(i,`${JSON.stringify(o,null,2)}
14
+ `,"utf8"),u.info("cursor-adapter",`MCP config synced: dir=${e} file=${i} server=${t}${a.length>0?` pruned=${a.join(",")}`:""}`),i}catch(r){return u.warn("cursor-adapter",`Failed to ensure ${A(e,".cursor","mcp.json")}: ${String(r)}`),null}}recordCursorMcpRegistry(e,t,n){try{const s=A(re.data,"cursor"),r=A(s,"mcp-registry.json");P(s,{recursive:!0});let i={};try{i=JSON.parse(q(r,"utf8"))}catch{i={}}i[e]={mcp_path:t,server:n,updated_at:new Date().toISOString()},D(r,`${JSON.stringify(i,null,2)}
15
+ `,"utf8")}catch(s){u.warn("cursor-adapter",`Failed to record MCP registry: ${String(s)}`)}}}export{K as CURSOR_MODE_OPTIONS,$ as CursorAdapter,Be as extractCursorAssistantStreamDelta,Y as findCursorTranscript,Ie as formatCursorCreatePlanText,G as isCursorAskQuestionTool,X as isCursorCreatePlanTool,Re as mapCursorStreamJsonToRawEnvelope,Ce as parseCursorAskQuestionPayload};
@@ -1,12 +1,10 @@
1
- import{EventEmitter as y}from"node:events";import{stat as M}from"node:fs/promises";import{existsSync as $,mkdirSync as O,readFileSync as F,writeFileSync as B}from"node:fs";import{join as S,resolve as D,dirname as L}from"node:path";import{homedir as N}from"node:os";import{fileURLToPath as j}from"node:url";import{resolveCommandPath as Q,spawnCommand as U,killProcessGroup as T,hasChildProcesses as q}from"../../core/runtime/spawn.js";import{InternalApiServer as H}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as J,pruneLegacyMcpServerEntries as V}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as W}from"../shared/inbound-message-id-injector.js";import{IdentityInjector as z}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as G}from"../../default-skills/index.js";import{buildSimpleProbeReport as X}from"../shared/probe-util.js";import{compactToolInputForWire as Y}from"../shared/tool-wire-payload.js";import{normalizeOCProviderModels as K}from"./opencode-types.js";import{buildOpencodeConfigContent as Z}from"./opencode-config.js";import{agentIdOf as k}from"../shared/native-provider-config.js";import{formatOpenCodeErrorMessage as A}from"./format-error.js";import{OpenCodeTransport as ee}from"./opencode-transport.js";import{log as r}from"../../core/log/index.js";import{splitTextForAibotProtocol as x}from"../../core/protocol/index.js";class te extends y{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){r.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const se=200,ie=2e3,ne=12e4,oe=90*1e3,b=1800*1e3,P=3e4,R=600*1e3,re="claude_interaction_reply",ae="set_mode",de="set_model",ce="127.0.0.1",le=0,he=1e3,m={fullAuto:"full_auto",approval:"approval"},C=[{id:m.fullAuto,displayName:"Full Auto"},{id:m.approval,displayName:"Approval"}],pe=[{permission:"*",pattern:"*",action:"allow"}],ue=[{permission:"doom_loop",pattern:"*",action:"ask"},{permission:"external_directory",pattern:"*",action:"ask"},{permission:"question",pattern:"*",action:"deny"},{permission:"plan_enter",pattern:"*",action:"deny"},{permission:"plan_exit",pattern:"*",action:"deny"},{permission:"repo_clone",pattern:"*",action:"deny"},{permission:"repo_overview",pattern:"*",action:"deny"},{permission:"read",pattern:"*.env",action:"ask"},{permission:"read",pattern:"*.env.*",action:"ask"},{permission:"read",pattern:"*.env.example",action:"allow"}];function w(g){const e=String(g??"").trim().toLowerCase();if(e==="full_auto"||e==="fullauto")return m.fullAuto;if(e==="approval"||e==="ask"||e==="autoedit"||e==="auto_edit")return m.approval}function E(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class Fe extends y{type="opencode";config;callbacks;options;identity;inboundMessageIds=new W;process=null;transport=new ee;alive=!1;stopped=!1;internalApi=null;sessions=new Map;sessionModes=new Map;sessionModels=new Map;availableModels=[];modelContextLimits=new Map;contextTokensBySession=new Map;activeRun=null;completedEvents=new Set;clientMsgSeq=0;auditCaptures=new Map;completedAuditBoundaries=new Map;idleTimer=null;lastSseAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;toolCardsSent=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;pendingQuestions=new Map;permissionHandler=null;constructor(e,s,t){super(),this.config=e,this.callbacks=s,this.options=t??{},this.identity=new z("opencode-adapter",s.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}async start(){await this.startInternalApiAndInjectMcp();const e=this.options.hostname??ce,s=this.options.port??le,t=await this.spawnAndWait(e,s),i=this.resolveCwd();await this.transport.connect(t,i),this.transport.on("event",n=>this.handleSseEvent(n));try{await this.refreshModels()}catch(n){r.warn("opencode-adapter",`Failed to fetch providers for toolbar models: ${n instanceof Error?n.message:String(n)}`)}r.info("opencode-adapter",`Ready (pid=${this.process?.pid}, url=${t})`)}async refreshModels(e){const s=await this.transport.listProviders(e),t=[],i=new Map;for(const n of s)for(const o of K(n.models)){t.push({id:`${n.id}/${o.id}`,displayName:o.name||o.id});const a=o.limit?.context;typeof a=="number"&&a>0&&i.set(`${n.id}/${o.id}`,a)}t.sort((n,o)=>{const a=n.displayName.toLowerCase().localeCompare(o.displayName.toLowerCase());return a!==0?a:n.id.localeCompare(o.id)}),this.availableModels=t,this.modelContextLimits=i,r.info("opencode-adapter",`Fetched ${t.length} models from ${s.length} providers (directory=${e??"current"})`)}resolveContextLimit(e,s){const t=this.modelContextLimits.get(`${e}/${s}`);if(t)return t;let i;for(const[n,o]of this.modelContextLimits)n.startsWith(`${e}/`)&&(i=i===void 0?o:Math.max(i,o));return i}buildContextWindowMeta(e,s,t,i){if(!i||i<=0)return;const n=this.resolveContextLimit(s,t);if(!n)return;const o=Math.min(100,i/n*100);return{context_window:{used:i,size:n,usedPercentage:o,remainingPercentage:100-o}}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.transport.disconnect(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.process){const e=this.process;try{T(e,"SIGTERM")}catch{}const s=setTimeout(()=>{try{T(e,"SIGKILL")}catch{}},5e3);e.on("exit",()=>clearTimeout(s)),this.process=null}}isAlive(){return this.alive}async createSession(e){const s=e.cwd??this.resolveCwd();await this.transport.useDirectory(s);const t=await this.transport.createSession({title:`grix-${Date.now()}`},s);return this.sessions.set(t.id,{ocSessionId:t.id,cwd:s}),r.info("opencode-adapter",`Created OC session ${t.id} for cwd=${s}`),await this.applySessionPermission(t.id,t.id,s),t.id}async resumeSession(e,s){const t=this.sessions.get(e);if(t?.ocSessionId)try{await this.transport.useDirectory(t.cwd),await this.transport.getSession(t.ocSessionId,t.cwd),await this.applySessionPermission(e,t.ocSessionId,t.cwd)}catch{r.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, will create new on next prompt`),t.ocSessionId=""}}async destroySession(e){const s=this.sessions.get(e),t=s?s.ocSessionId:e;if(t)try{await this.transport.deleteSession(t,s?.cwd)}catch{}this.sessions.delete(e),this.contextTokensBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e)}sendPrompt(e){const s=new te(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(t=>{s.emitError(t instanceof Error?t:new Error(String(t)))}),s}async cancel(e){if(this.activeRun)try{await this.transport.abortSession(this.activeRun.ocSessionId,this.activeRun.cwd)}catch{}}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){r.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){r.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}this.activeRun&&this.activeRun.eventId!==s&&(r.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),r.info("opencode-adapter",`prompt: event=${s} session=${t}`),this.callbacks.sendEventAck(s,t),this.startRun(s,t,e.audit?.enabled===!0),this.startComposing(t),this.resetIdleTimer();const n=this.buildPromptTextFromEvent(e);this.sendOcPrompt(t,n).catch(o=>{r.error("opencode-adapter",`prompt_async failed: ${o}`),this.finishRun("failed",String(o))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(r.info("opencode-adapter",`stop: event=${e}`),this.rejectAllPendingInteractions(),this.transport.abortSession(this.activeRun.ocSessionId,this.activeRun.cwd).catch(()=>{}),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.sessions.size}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}takeAuditBoundary(e){const s=this.completedAuditBoundaries.get(e);return s&&this.completedAuditBoundaries.delete(e),s}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.rejectAllPendingInteractions(),this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=D(j(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:J(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?q(e,[e]):!1}async probe(e){const s=this.getStatus();return X(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){try{this.internalApi=new H,this.internalApi.setInvokeHandler(async(d,l,h,u)=>this.callbacks.agentInvoke(d,l,u)),await this.internalApi.start(0),r.info("opencode-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),s=k(this.config.command||"opencode")||"opencode",t=process.env.XDG_CONFIG_HOME||S(N(),".config"),i=S(t,s,`${s}.json`);O(L(i),{recursive:!0});let n={};try{$(i)&&(n=JSON.parse(F(i,"utf8")))}catch{}const o=n.mcp&&typeof n.mcp=="object"?n.mcp:{};V(o,this.internalApi.url),o[e.name]={type:"local",command:[e.command,...e.args??[]],enabled:!0},n.mcp=o,B(i,`${JSON.stringify(n,null,2)}
2
- `,"utf8"),r.info("opencode-adapter",`MCP config injected into ${i}`);const a=S(t,s,"skills"),c=G(a);c.length>0&&r.info("opencode-adapter",`Synced connector skills to ${a}: [${c.join(", ")}]`)}catch(e){r.warn("opencode-adapter",`Failed to inject MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`)}}async handleLocalAction(e){const{action_type:s}=e;if(s==="exec_approve"||s==="exec_reject"||s==="permission_approve"||s==="permission_reject")return this.handlePermissionAction(e);if(s===ae)return this.handleSetModeAction(e);if(s===de)return this.handleSetModelAction(e);if(s===re){const t=e.params??{};if(String(t.kind??"")==="permission"){const i=t.resolution??{},n=String(i.value??"");return this.handlePermissionAction({...e,action_type:n==="allow"?"exec_approve":"exec_reject",params:{...t,approval_command_id:t.request_id}})}return this.handleQuestionReplyAction(e)}return{handled:!1,kind:""}}handleQuestionReplyEvent(e){let s;if(e.action)s={type:"action",value:e.action};else if(e.response?.type==="single")s={type:"text",value:e.response.value};else if(e.response?.type==="map")s={type:"map",entries:e.response.entries};else return{delivered:!1,errorCode:"resolution_invalid",errorMsg:"Question reply response is invalid."};return this.deliverQuestionReply({request_id:e.request_id,resolution:s})}async bindSession(e,s){if(r.info("opencode-adapter",`bindSession: ${e} \u2192 ${s}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:s});else{const t=this.sessions.get(e);t.cwd=s}try{await this.refreshModels(s)}catch(t){r.warn("opencode-adapter",`Failed to refresh models on bind: ${t instanceof Error?t.message:String(t)}`)}this.callbacks.sendUpdateBindingCard(e,"ready",s,this.buildToolbarMeta(e))}resolveModeId(e){if(e){const t=this.sessionModes.get(e);if(t)return t}const s=w(this.options.permissionPolicy);if(s)return s;if(e){const t=w(this.options.bindingStore?.get(e)?.modeId);if(t)return t}return m.fullAuto}buildModeToolbarMeta(e){const s=this.resolveModeId(e);return{mode_id:s,currentModeId:s,available_modes:C.map(t=>({...t}))}}async applySessionPermission(e,s,t){const i=this.resolveModeId(e),n=i===m.fullAuto?pe:ue;try{await this.transport.updateSessionPermission(s,n,t),r.info("opencode-adapter",`Applied session permission ruleset (${i}) to ${s}`)}catch(o){r.warn("opencode-adapter",`Failed to apply session permission ruleset: ${o instanceof Error?o.message:String(o)}`)}}async handleSetModeAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=w(s.mode_id);if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","mode_id must be full_auto or approval and session_id is required"),{handled:!0,kind:"set_mode"};this.sessionModes.set(t,i);const n=this.sessions.get(t);n?.ocSessionId&&await this.applySessionPermission(t,n.ocSessionId,n.cwd);const o=n?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",o,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"mode_set",session_context:{mode_id:i,modeId:i},mode_id:i,available_modes:C.map(a=>({...a}))}),{handled:!0,kind:"set_mode"}}resolveModelId(e){if(e){const t=this.sessionModels.get(e);if(t)return t}const s=String(this.options.model??"").trim();if(s)return s;if(e){const t=String(this.options.bindingStore?.get(e)?.modelId??"").trim();if(t)return t}return""}buildModelToolbarMeta(e){const s=this.resolveModelId(e);return{model_id:s,currentModelId:s,available_models:this.availableModels.map(t=>({...t}))}}buildToolbarMeta(e){return{...this.buildModelToolbarMeta(e),...this.buildModeToolbarMeta(e)}}handleSetModelAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=String(s.model_id??"").trim();if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};this.sessionModels.set(t,i);const n=this.sessions.get(t)?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",n,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"model_set",session_context:{model_id:i,modelId:i},model_id:i,available_models:this.availableModels.map(o=>({...o}))}),{handled:!0,kind:"set_model"}}async spawnAndWait(e,s){const t=this.resolveCwd();try{if(!(await M(t)).isDirectory())throw new Error(`Bound path is not a directory: ${t}`)}catch(i){throw String(i?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${t}. Please rebind with /grix open <valid-directory>.`):i}return new Promise((i,n)=>{const o=this.config.command||"opencode",c=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${s}`],d={...process.env,...this.config.env},l=Z({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider});if(l){const v=(k(o)||"opencode").toUpperCase().replace(/[^A-Z0-9_]/g,"_")||"OPENCODE";d[`${v}_CONFIG_CONTENT`]=JSON.stringify(l)}const h=Q(o,typeof d.PATH=="string"?d.PATH:void 0);r.info("opencode-adapter",`Spawning: ${h} ${c.join(" ")} (cwd=${t})`),this.process=U(h,c,{env:d,cwd:t}).process;let u="",f=!1;const I=setTimeout(()=>{f||(f=!0,n(new Error(`opencode serve did not start after ${P/1e3}s`)))},P);this.process.stdout?.on("data",p=>{if(u+=p.toString(),!f)for(const v of u.split(`
3
- `)){const _=v.match(/\bserver listening on (https?:\/\/\S+)/);if(_){clearTimeout(I),f=!0,this.alive=!0,i(_[1]);return}}}),this.process.stderr?.on("data",p=>{const v=p.toString().trim();v&&r.info("opencode-adapter",`[stderr] ${v}`)}),this.process.on("error",p=>{r.error("opencode-adapter",`Spawn error: ${p.message}`),clearTimeout(I),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${p.message}`),this.clearRun()),f?this.stopped||this.emit("exit",1):(f=!0,n(p))}),this.process.on("exit",p=>{r.info("opencode-adapter",`Process exited (code=${p})`),clearTimeout(I),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${p})`),this.clearRun()),f?this.stopped||this.emit("exit",p??1):(f=!0,n(new Error(`opencode serve exited with code ${p}`)))})})}async ensureOcSession(e){const s=this.sessions.get(e),t=this.getSessionCwd(e);if(await this.transport.useDirectory(t),s?.ocSessionId)try{return await this.transport.getSession(s.ocSessionId,t),s.ocSessionId}catch{r.warn("opencode-adapter",`OC session ${s.ocSessionId} gone, creating new`),s.ocSessionId=""}const i=this.options.bindingStore?.getAcpSessionId(e);if(i)try{return await this.transport.getSession(i,t),this.sessions.set(e,{ocSessionId:i,cwd:t}),r.info("opencode-adapter",`Resumed OC session ${i} for aibot=${e}`),await this.applySessionPermission(e,i,t),i}catch{r.warn("opencode-adapter",`Persisted OC session ${i} gone, creating new`)}const n=await this.transport.createSession({title:`grix-${e.slice(-8)}`},t);return this.sessions.set(e,{ocSessionId:n.id,cwd:t}),this.options.bindingStore?.setAcpSessionId(e,n.id),r.info("opencode-adapter",`Created OC session ${n.id} for aibot=${e}`),await this.applySessionPermission(e,n.id,t),n.id}async sendOcPrompt(e,s){const t=this.getSessionCwd(e),i=await this.ensureOcSession(e);this.activeRun&&(this.activeRun.ocSessionId=i,this.activeRun.cwd=t);const n=this.resolveModelId(e),o=n.indexOf("/"),a=o>0&&o<n.length-1?{providerID:n.slice(0,o),modelID:n.slice(o+1)}:void 0,c=this.identity.formatBlock();c&&r.info("opencode-adapter",`Injected agent identity via prompt.system session=${e}`),await this.transport.sendPromptAsync(i,{parts:[{type:"text",text:s}],...a?{model:a}:{},...c?{system:c}:{}},t)}handleSseEvent(e){if(!this.stopped){if(this.updateToolInFlight(e),e.type!=="server.heartbeat"&&(this.lastSseAt=Date.now(),this.resetIdleTimer()),this.activeRun){const s=this.auditCaptures.get(this.activeRun.eventId);s&&s.push({sequence:s.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(e.type){case"message.part.updated":{if(!this.activeRun)break;const s=e.part,t=e.delta;if(s.type==="text"){const i=t||s.text;i&&this.acceptAssistantPartText(s.messageID,"text",i)}else s.type==="reasoning"?t&&this.acceptAssistantPartText(s.messageID,"reasoning",t):s.type==="tool"&&this.handleToolPartUpdate(s,t);break}case"message.updated":{if(!this.activeRun)break;const s=e.info;if(this.rememberMessageRole(s),s.role==="assistant"){const t=s;typeof t.tokens?.input=="number"&&this.contextTokensBySession.set(this.activeRun.sessionId,t.tokens.input);const i=this.buildContextWindowMeta(this.activeRun.sessionId,t.providerID,t.modelID,t.tokens?.input);this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.activeRun.cwd,{...this.buildToolbarMeta(this.activeRun.sessionId),model_provider:t.providerID,model_id:t.modelID,...i??{}}),t.error&&r.warn("opencode-adapter",`Message error: ${JSON.stringify(t.error)}`);const n=this.activeRun.ocSessionId;n&&t.sessionID===n&&(t.error?(this.flushTextBuffer(),this.finishRun("failed",A(t.error,t.error.type||"unknown error"))):t.time?.completed&&t.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}break}case"session.idle":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.status":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&e.status.type==="idle"&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.error":{if(!this.activeRun)break;const s=A(e.error);r.error("opencode-adapter",`Session error: ${s}`),this.flushTextBuffer(),this.finishRun("failed",s);break}case"permission.updated":{this.handlePermission(e.permission);break}case"permission.asked":{this.handlePermissionAsked(e);break}case"question.asked":{this.handleQuestionAsked(e);break}case"permission.replied":case"question.replied":case"question.rejected":r.debug("opencode-adapter",`Interaction settled: ${e.type}`);break;case"session.created":case"session.updated":case"session.deleted":case"session.compacted":case"session.diff":case"file.edited":case"server.connected":case"server.heartbeat":break;case"server.instance.disposed":{r.warn("opencode-adapter",`Server instance disposed: ${e.directory}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"failed","server instance disposed"),this.clearRun()),this.stopped||this.emit("exit",-1);break}default:r.debug("opencode-adapter",`Unhandled SSE event type: ${e.type}`);break}}}updateToolInFlight(e){if(e.type!=="message.part.updated")return;const s=e.part;if(s?.type!=="tool"||!s.callID)return;const t=s.state?.status;t==="pending"||t==="running"?this.toolCallsInFlight.add(s.callID):(t==="completed"||t==="error")&&this.toolCallsInFlight.delete(s.callID)}rememberMessageRole(e){const s=typeof e.id=="string"?e.id.trim():"";s&&(e.role!=="user"&&e.role!=="assistant"||(this.messageRoles.set(s,e.role),this.flushOrDropPendingParts(s,e.role)))}acceptAssistantPartText(e,s,t){if(!this.activeRun||!t)return;const i=typeof e=="string"?e.trim():"";if(!i)return;const n=this.messageRoles.get(i);if(n==="user")return;if(n==="assistant"){this.emitAssistantPartChunk(s,t);return}const o=this.pendingPartChunks.get(i)??[];o.push({kind:s,value:t}),this.pendingPartChunks.set(i,o)}flushOrDropPendingParts(e,s){const t=this.pendingPartChunks.get(e);if(this.pendingPartChunks.delete(e),!(!t||t.length===0)&&s==="assistant")for(const i of t)this.emitAssistantPartChunk(i.kind,i.value)}emitAssistantPartChunk(e,s){if(!(!this.activeRun||!s)){if(e==="reasoning"){this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,s);return}this.appendText(s)}}clearMessageRoleState(){this.messageRoles.clear(),this.pendingPartChunks.clear()}handleToolPartUpdate(e,s){if(!this.activeRun)return;const t=e.state;switch(t.status){case"pending":case"running":{this.sendToolUseOnce(e,t.input);break}case"completed":{this.sendToolUseOnce(e,t.input);break}case"error":{this.sendToolUseOnce(e,t.input),this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,"(failed)");break}}}sendToolUseOnce(e,s){!this.activeRun||this.toolCardsSent.has(e.callID)||(this.flushTextBuffer(),this.toolCardsSent.add(e.callID),this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,Y(s??{})))}onPermissionTimeout(e){const s=this.pendingPermissions.get(e);s&&(this.pendingPermissions.delete(e),r.error("opencode-adapter",`Permission approval timeout: ${e}`),this.transport.respondPermission(s.ocSessionId,e,"reject",s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","permission approval timeout")))}trackPendingPermission(e){if(!this.activeRun)return;this.stopIdleTimer();const s=setTimeout(()=>this.onPermissionTimeout(e),R);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:s})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(o=>{r.warn("opencode-adapter",`Orphan permission reject failed: ${o}`)});return}const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===m.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(o=>{r.warn("opencode-adapter",`Auto-approve failed: ${o}`)});return}this.trackPendingPermission(e.id);const n=e.patterns.length>0?`${e.permission}: ${e.patterns.join(", ")}`:e.permission;this.callbacks.sendPermissionCard?this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.permission,toolTitle:n,toolInput:JSON.stringify(e.metadata??{})}):this.callbacks.sendToolUse(s,t,e.permission,JSON.stringify(e.metadata??{}))}handlePermission(e){if(!this.activeRun)return;const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===m.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(n=>{r.warn("opencode-adapter",`Auto-approve failed: ${n}`)});return}if(this.trackPendingPermission(e.id),this.callbacks.sendPermissionCard)this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.type,toolTitle:e.title||e.type,toolInput:JSON.stringify(e.metadata??{})});else{const n=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(s,t,e.type,n)}}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const s=e.params??{},t=String(s.approval_id??s.approval_command_id??s.approvalId??s.tool_call_id??"");let i=t?this.pendingPermissions.get(t):void 0;if(!i){for(const a of this.pendingPermissions.values())if(a.eventId===this.activeRun.eventId){i=a;break}}if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:"permission"};const n=e.action_type==="exec_approve"||e.action_type==="permission_approve",o=n?"once":"reject";return clearTimeout(i.timer),this.pendingPermissions.delete(i.permissionId),this.transport.respondPermission(i.ocSessionId,i.permissionId,o,i.cwd).then(()=>{r.info("opencode-adapter",`Permission ${o}: ${i.permissionId}`),this.resetIdleTimer()}).catch(a=>{r.warn("opencode-adapter",`Permission response failed: ${a}`),this.resetIdleTimer()}),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.permissionId,decision:n?"approve":"reject"}),{handled:!0,kind:"permission"}}async handleExecApprovalEvent(e){if(!this.activeRun)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"no active run"};const s=String(e.approval_id??e.approval_command_id??e.tool_call_id??"");let t=s?this.pendingPermissions.get(s):void 0;if(!t){for(const n of this.pendingPermissions.values())if(n.eventId===this.activeRun.eventId){t=n;break}}if(!t)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"That approval request is no longer pending."};const i=e.decision==="deny"?"reject":e.decision==="allow-always"?"always":"once";return clearTimeout(t.timer),this.pendingPermissions.delete(t.permissionId),this.transport.respondPermission(t.ocSessionId,t.permissionId,i,t.cwd).then(()=>{r.info("opencode-adapter",`Permission ${i} (text event): ${t.permissionId}`),this.resetIdleTimer()}).catch(n=>{r.warn("opencode-adapter",`Permission response failed: ${n}`),this.resetIdleTimer()}),{delivered:!0}}onQuestionTimeout(e){const s=this.pendingQuestions.get(e);s&&(this.pendingQuestions.delete(e),r.error("opencode-adapter",`Question answer timeout: ${e}`),this.transport.rejectQuestion(e,s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","question answer timeout")))}handleQuestionAsked(e){if(!this.activeRun){this.transport.rejectQuestion(e.id).catch(n=>{r.warn("opencode-adapter",`Orphan question reject failed: ${n}`)});return}const{eventId:s,sessionId:t}=this.activeRun;this.stopIdleTimer();const i=setTimeout(()=>this.onQuestionTimeout(e.id),R);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:s,cwd:this.activeRun.cwd,questions:e.questions,timer:i}),this.callbacks.sendAgentQuestionCard)this.callbacks.sendAgentQuestionCard(s,t,{request_id:e.id,mode:"form",questions:e.questions.map(n=>({header:n.header,prompt:n.question,...n.options.length>0?{options:n.options.map(o=>o.label)}:{},...n.multiple!==void 0?{multi_select:n.multiple}:{},...n.custom?{allow_free_text:!0}:{}})),expires_at:Date.now()+R});else{const n=e.questions.map(o=>o.question).join(`
4
- `);this.callbacks.sendRunError(s,t,`Agent asks: ${n}`)}}handleQuestionReplyAction(e){const s=e.params??{},t=this.deliverQuestionReply(s);return t.delivered?this.callbacks.sendLocalActionResult(e.action_id,"ok",t.result):this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,t.errorCode,t.errorMsg),{handled:!0,kind:"question_reply"}}deliverQuestionReply(e){const s=String(e.request_id??""),t=s?this.pendingQuestions.get(s):void 0;if(!t)return{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};const i=e.resolution??{},n=String(i.type??""),o=(d,l)=>(clearTimeout(t.timer),this.pendingQuestions.delete(t.requestId),d().then(()=>this.resetIdleTimer()).catch(h=>{r.warn("opencode-adapter",`Question response failed: ${h}`),this.resetIdleTimer()}),{delivered:!0,result:l});if(n==="action"){const d=String(i.value??"");if(d==="cancel"||d==="decline")return o(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"})}let a=null;if(Array.isArray(e.answers))a=e.answers.map(d=>Array.isArray(d)?d.map(String):[String(d)]);else if(n==="text"){const d=String(i.value??"");d&&(a=t.questions.map((l,h)=>h===0?[d]:[]))}else if(n==="map"){const d=Array.isArray(i.entries)?i.entries:[];a=t.questions.map((l,h)=>{const u=d.find(f=>f.key===l.header||f.key===String(h+1));return u&&u.value?[u.value]:[]}),a.every(l=>l.length===0)&&d.length>0&&(a=t.questions.map((l,h)=>{const u=d[h]?.value;return u?[String(u)]:[]}))}if(!a||a.every(d=>d.length===0))return o(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"});const c=a;return o(()=>this.transport.replyQuestion(t.requestId,c,t.cwd),{request_id:s,resolution:"answer"})}rejectAllPendingInteractions(){for(const e of this.pendingPermissions.values())clearTimeout(e.timer),this.transport.respondPermission(e.ocSessionId,e.permissionId,"reject",e.cwd).catch(()=>{});this.pendingPermissions.clear();for(const e of this.pendingQuestions.values())clearTimeout(e.timer),this.transport.rejectQuestion(e.requestId,e.cwd).catch(()=>{});this.pendingQuestions.clear()}hasPendingInteractionForRun(e){for(const s of this.pendingPermissions.values())if(s.eventId===e)return!0;for(const s of this.pendingQuestions.values())if(s.eventId===e)return!0;return!1}startRun(e,s,t=!1){this.activeRun={eventId:e,sessionId:s,ocSessionId:"",cwd:this.getSessionCwd(s),chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null},this.toolCardsSent.clear(),t&&this.auditCaptures.set(e,[]),this.lastSseAt=Date.now(),this.livenessExtendStartAt=void 0}finishRun(e,s){const t=this.activeRun;if(!t)return;if(this.completedEvents.add(t.eventId),this.completedEvents.size>he){const c=[...this.completedEvents].slice(-500);this.completedEvents=new Set(c)}this.snapshotAuditBoundary(t),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopComposing(),this.stopIdleTimer();const i=++t.chunkSeq,n=t.clientMsgId,o=e==="failed"&&!!s;o&&this.callbacks.sendRunError(t.eventId,t.sessionId,s);const a=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t.eventId,t.sessionId,n).then(()=>{this.callbacks.sendEventResult(t.eventId,e,s,void 0,o)}).catch(c=>{const d=e==="responded"?"failed":e,l=e==="responded"?`final output delivery failed: ${c instanceof Error?c.message:String(c)}`:s,h=e==="responded"?!1:o;this.callbacks.sendEventResult(t.eventId,d,l,void 0,h)}):(this.callbacks.sendStreamChunk(t.eventId,t.sessionId,"",i,!0,n),this.callbacks.sendEventResult(t.eventId,e,s,void 0,o))};if(t.textBuffer){this.stopTextFlush();for(const c of x(t.textBuffer))t.chunkSeq++,this.callbacks.sendStreamChunk(t.eventId,t.sessionId,c,t.chunkSeq,!1,t.clientMsgId);t.textBuffer=""}a(),this.emit("eventDone",t.eventId)}clearRun(){this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const e=this.activeRun?.eventId;this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopIdleTimer(),e&&this.emit("eventDone",e)}snapshotAuditBoundary(e){const s=this.auditCaptures.get(e.eventId);s&&(this.completedAuditBoundaries.set(e.eventId,{adapterType:"opencode",providerSessionId:e.ocSessionId||void 0,openCodeEvidence:{events:s}}),this.auditCaptures.delete(e.eventId))}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=ie){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},se))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const e of x(this.activeRun.textBuffer))this.activeRun.chunkSeq++,this.callbacks.sendStreamChunk(this.activeRun.eventId,this.activeRun.sessionId,e,this.activeRun.chunkSeq,!1,this.activeRun.clientMsgId);this.activeRun.textBuffer=""}}stopTextFlush(){this.activeRun?.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null)}startComposing(e){}stopComposing(){}shouldExtendByLiveness(){if(!this.activeRun)return!1;const e=this.process?.pid;if(!this.alive||!e||!E(e))return!1;const s=Date.now(),t=this.lastSseAt>0?s-this.lastSseAt:Number.POSITIVE_INFINITY;if(t<oe)return this.livenessExtendStartAt=s,r.info("opencode-adapter",`Liveness check: fresh SSE for ${this.activeRun.eventId} (sseAge=${t}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??s;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),s-n>b?(r.warn("opencode-adapter",`Liveness extension budget exhausted for ${this.activeRun.eventId} (no progress for ${Math.round((s-n)/6e4)}min), allowing idle fail`),!1):(r.info("opencode-adapter",`Liveness check: turn in progress for ${this.activeRun.eventId} (toolsInFlight=${this.toolCallsInFlight.size}, sseAge=${Number.isFinite(t)?`${t}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.activeRun)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.activeRun)return;if(this.hasPendingInteractionForRun(this.activeRun.eventId)&&this.shouldExtendByLiveness()){r.info("opencode-adapter",`Idle timeout skipped: pending interaction for ${this.activeRun.eventId}, resetting timer`),this.resetIdleTimer();return}if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const e=this.process?.pid,t=!!(this.alive&&e&&E(e))?`liveness budget exhausted after ${b/6e4}min`:"process not alive";r.error("opencode-adapter",`Idle timeout (${t}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`idle timeout: ${t}`),this.clearRun()),this.emit("exit",-1)},ne))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveCwd(){const e=this.options.aibotSessionId?this.options.bindingStore?.get(this.options.aibotSessionId)?.cwd:void 0;if(e)return e;const s=(this.config.options??{}).cwd;return typeof s=="string"&&s?s:process.cwd()}getSessionCwd(e){return this.sessions.get(e)?.cwd??this.options.bindingStore?.get(e)?.cwd??this.resolveCwd()}buildPromptText(e){let s=e.text;if(e.contextMessages&&e.contextMessages.length>0){const t=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
1
+ import{EventEmitter as E}from"node:events";import{stat as N,mkdtemp as L,rm as j}from"node:fs/promises";import{join as R,resolve as Q}from"node:path";import{tmpdir as U}from"node:os";import{randomBytes as q}from"node:crypto";import{fileURLToPath as H}from"node:url";import{spawnCommand as V,killProcessGroup as S,hasChildProcesses as W}from"../../core/runtime/spawn.js";import{resolveOpencodeCommandPath as G}from"./resolve-command.js";import{InternalApiServer as J}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as z}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as X}from"../shared/inbound-message-id-injector.js";import{IdentityInjector as Y}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as K}from"../../default-skills/index.js";import{buildSimpleProbeReport as Z}from"../shared/probe-util.js";import{compactToolInputForWire as ee}from"../shared/tool-wire-payload.js";import{normalizeOCProviderModels as te}from"./opencode-types.js";import{buildOpencodeConfigContent as se}from"./opencode-config.js";import{agentIdOf as ie}from"../shared/native-provider-config.js";import{formatOpenCodeErrorMessage as P}from"./format-error.js";import{OpenCodeTransport as ne,OpenCodeHttpError as T}from"./opencode-transport.js";import{log as a}from"../../core/log/index.js";import{splitTextForAibotProtocol as x}from"../../core/protocol/index.js";class oe extends E{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){a.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const re=200,ae=2e3,de=12e4,ce=90*1e3,M=1800*1e3,O=3e4,_=600*1e3,le="claude_interaction_reply",he="set_mode",pe="set_model",ue="127.0.0.1",fe=0,me=1e3,v={fullAuto:"full_auto",approval:"approval"},$=[{id:v.fullAuto,displayName:"Full Auto"},{id:v.approval,displayName:"Approval"}],ve=[{permission:"*",pattern:"*",action:"allow"}],ge=[{permission:"doom_loop",pattern:"*",action:"ask"},{permission:"external_directory",pattern:"*",action:"ask"},{permission:"question",pattern:"*",action:"deny"},{permission:"plan_enter",pattern:"*",action:"deny"},{permission:"plan_exit",pattern:"*",action:"deny"},{permission:"repo_clone",pattern:"*",action:"deny"},{permission:"repo_overview",pattern:"*",action:"deny"},{permission:"read",pattern:"*.env",action:"ask"},{permission:"read",pattern:"*.env.*",action:"ask"},{permission:"read",pattern:"*.env.example",action:"allow"}];function k(g){const e=String(g??"").trim().toLowerCase();if(e==="full_auto"||e==="fullauto")return v.fullAuto;if(e==="approval"||e==="ask"||e==="autoedit"||e==="auto_edit")return v.approval}function D(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class je extends E{type="opencode";config;callbacks;options;identity;inboundMessageIds=new X;process=null;transport=new ne;alive=!1;stopped=!1;internalApi=null;sessions=new Map;sessionModes=new Map;sessionModels=new Map;availableModels=[];modelContextLimits=new Map;contextTokensBySession=new Map;activeRun=null;runBarrier=Promise.resolve();cancellationFailure=null;completedEvents=new Set;clientMsgSeq=0;auditCaptures=new Map;completedAuditBoundaries=new Map;idleTimer=null;lastSseAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;toolCardsSent=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;pendingQuestions=new Map;permissionHandler=null;constructor(e,s,t){super(),this.config=e,this.callbacks=s,this.options=t??{},this.identity=new Y("opencode-adapter",s.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}serverPassword="";privateConfigDir=null;childConfig={};startupCancel=null;stopTask=null;async start(){this.stopTask&&await this.stopTask,this.stopped=!1,this.cancellationFailure=null,this.runBarrier=Promise.resolve();try{if(await this.startInternalApiAndInjectMcp(),this.stopped)throw new Error("OpenCode startup canceled");const e=this.options.hostname??ue,s=this.options.port??fe,t=await this.spawnAndWait(e,s);if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.resolveCwd();this.transport.on("event",n=>this.handleSseEvent(n)),this.transport.on("stream-lost",()=>{this.activeRun&&(this.flushTextBuffer(),this.finishRun("failed","OpenCode event stream interrupted; output may be incomplete"))}),this.transport.on("admission-uncertain",()=>{this.alive=!1,this.activeRun&&this.finishRun("failed","OpenCode prompt admission could not be confirmed; server retired"),this.stop(),this.emit("exit",-1)}),this.transport.on("stream-unavailable",()=>{this.alive=!1,this.stopped||this.emit("exit",-1)}),await this.transport.connect(t,i,{username:"opencode",password:this.serverPassword});const o=this.getMcpConfig();await this.transport.configureMcp(o.name,[o.command,...o.args??[]]);try{await this.refreshModels()}catch(n){a.warn("opencode-adapter",`Failed to fetch providers for toolbar models: ${n instanceof Error?n.message:String(n)}`)}if(this.stopped||!this.transport.isConnected)throw new Error("OpenCode startup canceled or disconnected");this.alive=!0,a.info("opencode-adapter",`Ready (pid=${this.process?.pid}, protocol=${this.transport.protocol})`)}catch(e){throw await this.stop(),e}}async refreshModels(e){const s=await this.transport.listProviders(e),t=[],i=new Map;for(const o of s)for(const n of te(o.models)){t.push({id:`${o.id}/${n.id}`,displayName:n.name||n.id});const r=n.limit?.context;typeof r=="number"&&r>0&&i.set(`${o.id}/${n.id}`,r)}t.sort((o,n)=>{const r=o.displayName.toLowerCase().localeCompare(n.displayName.toLowerCase());return r!==0?r:o.id.localeCompare(n.id)}),this.availableModels=t,this.modelContextLimits=i,a.info("opencode-adapter",`Fetched ${t.length} models from ${s.length} providers (directory=${e??"current"})`)}resolveContextLimit(e,s){const t=this.modelContextLimits.get(`${e}/${s}`);if(t)return t;let i;for(const[o,n]of this.modelContextLimits)o.startsWith(`${e}/`)&&(i=i===void 0?n:Math.max(i,n));return i}buildContextWindowMeta(e,s,t,i){if(!i||i<=0)return;const o=this.resolveContextLimit(s,t);if(!o)return;const n=Math.min(100,i/o*100);return{context_window:{used:i,size:o,usedPercentage:n,remainingPercentage:100-n}}}stop(){if(this.stopTask)return this.stopTask;const e=this.stopInternal();return this.stopTask=e,e.then(()=>{this.stopTask=null},()=>{this.stopTask=null}),e}async stopInternal(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.clearRun(),this.startupCancel?.(),this.startupCancel=null,this.transport.disconnect(),await this.runBarrier.catch(()=>{}),this.serverPassword="",this.childConfig={},this.process){const e=this.process;this.process=null,await new Promise(s=>{if(e.exitCode!==null||e.signalCode!==null){try{S(e,"SIGKILL")}catch{}s();return}const t=()=>{clearTimeout(i),e.removeListener("exit",t);try{S(e,"SIGKILL")}catch{}s()},i=setTimeout(t,5e3);e.once("exit",t);try{S(e,"SIGTERM")}catch{t()}})}this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.privateConfigDir&&(await j(this.privateConfigDir,{recursive:!0,force:!0}),this.privateConfigDir=null)}isAlive(){return this.alive}async createSession(e){const s=e.cwd??this.resolveCwd();await this.transport.useDirectory(s);const t=await this.transport.createSession({title:`grix-${Date.now()}`},s);return this.sessions.set(t.id,{ocSessionId:t.id,cwd:s}),a.info("opencode-adapter",`Created OC session ${t.id} for cwd=${s}`),await this.applySessionPermission(t.id,t.id,s),t.id}async resumeSession(e,s){const t=this.sessions.get(e);if(t?.ocSessionId)try{await this.transport.useDirectory(t.cwd),await this.transport.getSession(t.ocSessionId,t.cwd),await this.applySessionPermission(e,t.ocSessionId,t.cwd)}catch(i){if(!(i instanceof T)||i.status!==404||i.method!=="GET")throw i;a.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, will create new on next prompt`),t.ocSessionId=""}}async destroySession(e){const s=this.sessions.get(e),t=s?s.ocSessionId:e;if(t)try{await this.transport.deleteSession(t,s?.cwd)}catch{}this.sessions.delete(e),this.contextTokensBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e)}sendPrompt(e){const s=new oe(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(t=>{s.emitError(t instanceof Error?t:new Error(String(t)))}),s}async cancel(e){const s=this.activeRun;!s||s.sessionId!==e||(this.deliverStopEvent(s.eventId),await s.cancelTask)}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){a.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){a.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}if(this.activeRun)if(this.activeRun.eventId!==s)a.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.finishRun("canceled","steered to new event");else{this.callbacks.sendEventAck(s,t);return}a.info("opencode-adapter",`prompt: event=${s} session=${t}`),this.callbacks.sendEventAck(s,t),this.startRun(s,t,e.audit?.enabled===!0),this.startComposing(t),this.resetIdleTimer();const o=this.buildPromptTextFromEvent(e),n=this.activeRun,r=this.runBarrier.then(async()=>{if(n.controller.signal.throwIfAborted(),this.cancellationFailure)throw this.cancellationFailure;await this.sendOcPrompt(t,o,n)});n.promptTask=r,this.runBarrier=r.catch(()=>{}),r.catch(d=>{this.activeRun===n&&(a.error("opencode-adapter",`prompt_async failed: ${d}`),this.finishRun("failed",String(d)))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(a.info("opencode-adapter",`stop: event=${e}`),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.sessions.size}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}takeAuditBoundary(e){const s=this.completedAuditBoundaries.get(e);return s&&this.completedAuditBoundaries.delete(e),s}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.rejectAllPendingInteractions(),this.activeRun&&(this.cancelRun(this.activeRun),this.snapshotAuditBoundary(this.activeRun)),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=Q(H(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:z(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?W(e,[e]):!1}async probe(e){const s=this.getStatus();return Z(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){if(this.internalApi=new J,this.internalApi.setInvokeHandler(async(t,i,o,n)=>this.callbacks.agentInvoke(t,i,n)),await this.internalApi.start(0),this.stopped)throw new Error("OpenCode startup canceled");if(this.privateConfigDir=await L(R(U(),"grix-opencode-")),this.stopped)throw new Error("OpenCode startup canceled");const e=R(this.privateConfigDir,"skills");K(e);const s=this.getMcpConfig();this.childConfig={mcp:{[s.name]:{type:"local",command:[s.command,...s.args??[]],enabled:!0}},skills:{paths:[e]}}}async handleLocalAction(e){const{action_type:s}=e;if(s==="exec_approve"||s==="exec_reject"||s==="permission_approve"||s==="permission_reject")return this.handlePermissionAction(e);if(s===he)return this.handleSetModeAction(e);if(s===pe)return this.handleSetModelAction(e);if(s===le){const t=e.params??{};if(String(t.kind??"")==="permission"){const i=t.resolution??{},o=String(i.value??"");return this.handlePermissionAction({...e,action_type:o==="allow"?"exec_approve":"exec_reject",params:{...t,approval_command_id:t.request_id}})}return this.handleQuestionReplyAction(e)}return{handled:!1,kind:""}}handleQuestionReplyEvent(e){let s;if(e.action)s={type:"action",value:e.action};else if(e.response?.type==="single")s={type:"text",value:e.response.value};else if(e.response?.type==="map")s={type:"map",entries:e.response.entries};else return{delivered:!1,errorCode:"resolution_invalid",errorMsg:"Question reply response is invalid."};return this.deliverQuestionReply({request_id:e.request_id,resolution:s})}async bindSession(e,s){if(a.info("opencode-adapter",`bindSession: ${e} \u2192 ${s}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:s});else{const t=this.sessions.get(e);t.cwd=s}try{await this.refreshModels(s)}catch(t){a.warn("opencode-adapter",`Failed to refresh models on bind: ${t instanceof Error?t.message:String(t)}`)}this.callbacks.sendUpdateBindingCard(e,"ready",s,this.buildToolbarMeta(e))}resolveModeId(e){if(e){const t=this.sessionModes.get(e);if(t)return t}const s=k(this.options.permissionPolicy);if(s)return s;if(e){const t=k(this.options.bindingStore?.get(e)?.modeId);if(t)return t}return v.fullAuto}buildModeToolbarMeta(e){const s=this.resolveModeId(e);return{mode_id:s,currentModeId:s,available_modes:$.map(t=>({...t}))}}async applySessionPermission(e,s,t,i){i?.throwIfAborted();const o=this.resolveModeId(e),n=o===v.fullAuto?ve:ge;try{await this.transport.updateSessionPermission(s,n,t,...i?[i]:[]),i?.throwIfAborted(),a.info("opencode-adapter",`Applied session permission ruleset (${o}) to ${s}`)}catch(r){if(i?.throwIfAborted(),this.transport.protocol==="v2")throw r;a.warn("opencode-adapter",`Failed to apply session permission ruleset: ${r instanceof Error?r.message:String(r)}`)}}async handleSetModeAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=k(s.mode_id);if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","mode_id must be full_auto or approval and session_id is required"),{handled:!0,kind:"set_mode"};const o=this.sessionModes.get(t);this.sessionModes.set(t,i);const n=this.sessions.get(t);if(n?.ocSessionId)try{await this.applySessionPermission(t,n.ocSessionId,n.cwd)}catch(d){throw o?this.sessionModes.set(t,o):this.sessionModes.delete(t),d}const r=n?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",r,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"mode_set",session_context:{mode_id:i,modeId:i},mode_id:i,available_modes:$.map(d=>({...d}))}),{handled:!0,kind:"set_mode"}}resolveModelId(e){if(e){const t=this.sessionModels.get(e);if(t)return t}const s=String(this.options.model??"").trim();if(s)return s;if(e){const t=String(this.options.bindingStore?.get(e)?.modelId??"").trim();if(t)return t}return""}buildModelToolbarMeta(e){const s=this.resolveModelId(e);return{model_id:s,currentModelId:s,available_models:this.availableModels.map(t=>({...t}))}}buildToolbarMeta(e){return{...this.buildModelToolbarMeta(e),...this.buildModeToolbarMeta(e)}}handleSetModelAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=String(s.model_id??"").trim();if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};this.sessionModels.set(t,i);const o=this.sessions.get(t)?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",o,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"model_set",session_context:{model_id:i,modelId:i},model_id:i,available_models:this.availableModels.map(n=>({...n}))}),{handled:!0,kind:"set_model"}}async spawnAndWait(e,s){const t=this.resolveCwd();try{if(!(await N(t)).isDirectory())throw new Error(`Bound path is not a directory: ${t}`)}catch(n){throw String(n?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${t}. Please rebind with /grix open <valid-directory>.`):n}if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.config.command||"opencode",o=await G(i,typeof this.config.env?.PATH=="string"?this.config.env.PATH:process.env.PATH);return new Promise((n,r)=>{const c=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${s}`],l={...process.env,...this.config.env},p=se({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider}),u=(ie(i)||"opencode").toUpperCase().replace(/[^A-Z0-9_]/g,"_")||"OPENCODE";let h={};if(l[`${u}_CONFIG_CONTENT`])try{if(h=JSON.parse(l[`${u}_CONFIG_CONTENT`]),!h||typeof h!="object"||Array.isArray(h))throw new Error}catch{r(new Error("OpenCode child CONFIG_CONTENT must be a JSON object"));return}const F=Array.isArray(h.skills)?h.skills:Array.isArray(h.skills?.paths)?h.skills.paths:[],C={...h,...p,...this.childConfig,...this.childConfig.mcp?{mcp:{...h.mcp,...this.childConfig.mcp}}:{},...this.privateConfigDir?{skills:{...Array.isArray(h.skills)?{}:h.skills,paths:[...F,R(this.privateConfigDir,"skills")]}}:{}};Object.keys(C).length&&(l[`${u}_CONFIG_CONTENT`]=JSON.stringify(C)),this.serverPassword=q(32).toString("base64url"),l.OPENCODE_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_USERNAME="opencode";const A=u;l[`${A}_SERVER_PASSWORD`]=this.serverPassword,l[`${A}_SERVER_USERNAME`]="opencode",a.info("opencode-adapter",`Spawning OpenCode server (cwd=${t})`),this.process=V(o,c,{env:l,cwd:t}).process;let I="",f=!1;const w=setTimeout(()=>{f||(f=!0,r(new Error(`opencode serve did not start after ${O/1e3}s`)))},O);this.startupCancel=()=>{clearTimeout(w),f||(f=!0,r(new Error("OpenCode startup canceled")))},this.process.stdout?.on("data",m=>{if(f)return;I=(I+m.toString()).slice(-8192);const y=I.split(/\r?\n/);I=y.pop()??"";for(const B of y){const b=B.match(/\bserver listening on (https?:\/\/\S+)/);if(b){clearTimeout(w),f=!0,this.startupCancel=null,n(b[1]);return}}}),this.process.stderr?.on("data",()=>{}),this.process.on("error",m=>{a.error("opencode-adapter",`Spawn error: ${m.message}`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${m.message}`),this.clearRun()),f?this.stopped||this.emit("exit",1):(f=!0,r(m))}),this.process.on("exit",m=>{a.info("opencode-adapter",`Process exited (code=${m})`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${m})`),this.clearRun()),f?this.stopped||this.emit("exit",m??1):(f=!0,r(new Error(`opencode serve exited with code ${m}`)))})})}async ensureOcSession(e,s){s?.throwIfAborted();const t=this.sessions.get(e),i=this.getSessionCwd(e);if(await this.transport.useDirectory(i,...s?[s]:[]),s?.throwIfAborted(),t?.ocSessionId)try{return await this.transport.getSession(t.ocSessionId,i,...s?[s]:[]),s?.throwIfAborted(),t.ocSessionId}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, creating new`),t.ocSessionId=""}const o=this.options.bindingStore?.getAcpSessionId(e);if(o)try{return await this.transport.getSession(o,i,...s?[s]:[]),s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:o,cwd:i}),a.info("opencode-adapter",`Resumed OC session ${o} for aibot=${e}`),await this.applySessionPermission(e,o,i,s),o}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`Persisted OC session ${o} gone, creating new`)}const n=await this.transport.createSession({title:`grix-${e.slice(-8)}`},i,...s?[s]:[]);return s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:n.id,cwd:i}),this.options.bindingStore?.setAcpSessionId(e,n.id),a.info("opencode-adapter",`Created OC session ${n.id} for aibot=${e}`),await this.applySessionPermission(e,n.id,i,s),n.id}async sendOcPrompt(e,s,t=this.activeRun){const i=t?.controller?.signal;i?.throwIfAborted();const o=this.getSessionCwd(e),n=await this.ensureOcSession(e,i);if(i?.throwIfAborted(),this.stopped||t&&this.activeRun!==t)return;this.activeRun&&(this.activeRun.ocSessionId=n,this.activeRun.cwd=o);const r=this.resolveModelId(e),d=r.indexOf("/"),c=d>0&&d<r.length-1?{providerID:r.slice(0,d),modelID:r.slice(d+1)}:void 0,l=this.identity.formatBlock();l&&a.info("opencode-adapter",`Injected agent identity via prompt.system session=${e}`),await this.transport.sendPromptAsync(n,{parts:[{type:"text",text:s}],...c?{model:c}:{},...l?{system:l}:{}},o,...i?[{signal:i,runId:t.eventId}]:[])}handleSseEvent(e){if(this.stopped)return;const s=e,t=e.nativeEvent,i=s.sessionID??s.info?.sessionID??s.part?.sessionID??t?.data?.sessionID??t?.data?.form?.sessionID;if(!(e.runId&&e.runId!==this.activeRun?.eventId)&&!(t&&i&&this.activeRun?.controller&&e.runId!==this.activeRun.eventId)&&!(i&&this.activeRun?.ocSessionId&&i!==this.activeRun.ocSessionId)&&!(t&&i&&!this.activeRun&&![...this.sessions.values()].some(o=>o.ocSessionId===i))){if(this.updateToolInFlight(e),e.type!=="server.heartbeat"&&(this.lastSseAt=Date.now(),this.resetIdleTimer()),this.activeRun){const o=this.auditCaptures.get(this.activeRun.eventId);o&&o.push({sequence:o.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(e.type){case"message.part.updated":{if(!this.activeRun)break;const o=e.part,n=e.delta;if(o.type==="text"){const r=n!==void 0?n:o.text;r&&this.acceptAssistantPartText(o.messageID,"text",r)}else o.type==="reasoning"?n&&this.acceptAssistantPartText(o.messageID,"reasoning",n):o.type==="tool"&&this.handleToolPartUpdate(o,n);break}case"message.updated":{if(!this.activeRun)break;const o=e.info;if(this.rememberMessageRole(o),o.role==="assistant"){const n=o;typeof n.tokens?.input=="number"&&this.contextTokensBySession.set(this.activeRun.sessionId,n.tokens.input);const r=this.buildContextWindowMeta(this.activeRun.sessionId,n.providerID,n.modelID,n.tokens?.input);this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.activeRun.cwd,{...this.buildToolbarMeta(this.activeRun.sessionId),model_provider:n.providerID,model_id:n.modelID,...r??{}}),n.error&&a.warn("opencode-adapter",`Message error: ${JSON.stringify(n.error)}`);const d=this.activeRun.ocSessionId;d&&n.sessionID===d&&(n.error?(this.flushTextBuffer(),this.finishRun("failed",P(n.error,n.error.type||"unknown error"))):!e.nativeEvent&&n.time?.completed&&n.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}break}case"session.canceled":{this.activeRun&&e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("canceled","OpenCode execution interrupted"));break}case"question.unsupported":{this.transport.rejectQuestion(e.id).catch(()=>{}),this.activeRun&&this.onInteractionFailure(new Error("OpenCode form uses unsupported external, hidden or conditional fields"),this.activeRun.eventId);break}case"session.idle":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.status":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&e.status.type==="idle"&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.error":{if(!this.activeRun)break;const o=P(e.error);a.error("opencode-adapter",`Session error: ${o}`),this.flushTextBuffer(),this.finishRun("failed",o);break}case"permission.updated":{this.handlePermission(e.permission);break}case"permission.asked":{this.handlePermissionAsked(e);break}case"question.asked":{this.handleQuestionAsked(e);break}case"permission.replied":{const o=this.pendingPermissions.get(e.requestID);o&&(clearTimeout(o.timer),this.pendingPermissions.delete(e.requestID),this.resetIdleTimer());break}case"question.replied":case"question.rejected":{const o=this.pendingQuestions.get(e.requestID);o&&(clearTimeout(o.timer),this.pendingQuestions.delete(e.requestID),this.resetIdleTimer());break}case"session.created":case"session.updated":case"session.deleted":case"session.compacted":case"session.diff":case"file.edited":case"server.connected":case"server.heartbeat":break;case"server.instance.disposed":{a.warn("opencode-adapter",`Server instance disposed: ${e.directory}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"failed","server instance disposed"),this.clearRun()),this.stopped||this.emit("exit",-1);break}default:a.debug("opencode-adapter",`Unhandled SSE event type: ${e.type}`);break}}}updateToolInFlight(e){if(e.type!=="message.part.updated")return;const s=e.part;if(s?.type!=="tool"||!s.callID)return;const t=s.state?.status;t==="pending"||t==="running"?this.toolCallsInFlight.add(s.callID):(t==="completed"||t==="error")&&this.toolCallsInFlight.delete(s.callID)}rememberMessageRole(e){const s=typeof e.id=="string"?e.id.trim():"";s&&(e.role!=="user"&&e.role!=="assistant"||(this.messageRoles.set(s,e.role),this.flushOrDropPendingParts(s,e.role)))}acceptAssistantPartText(e,s,t){if(!this.activeRun||!t)return;const i=typeof e=="string"?e.trim():"";if(!i)return;const o=this.messageRoles.get(i);if(o==="user")return;if(o==="assistant"){this.emitAssistantPartChunk(s,t);return}const n=this.pendingPartChunks.get(i)??[];n.push({kind:s,value:t}),this.pendingPartChunks.set(i,n)}flushOrDropPendingParts(e,s){const t=this.pendingPartChunks.get(e);if(this.pendingPartChunks.delete(e),!(!t||t.length===0)&&s==="assistant")for(const i of t)this.emitAssistantPartChunk(i.kind,i.value)}emitAssistantPartChunk(e,s){if(!(!this.activeRun||!s)){if(e==="reasoning"){this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,s);return}this.appendText(s)}}clearMessageRoleState(){this.messageRoles.clear(),this.pendingPartChunks.clear()}handleToolPartUpdate(e,s){if(!this.activeRun)return;const t=e.state;switch(t.status){case"pending":case"running":{this.sendToolUseOnce(e,t.input);break}case"completed":{this.sendToolUseOnce(e,t.input);break}case"error":{this.sendToolUseOnce(e,t.input),this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,"(failed)");break}}}sendToolUseOnce(e,s){!this.activeRun||this.toolCardsSent.has(e.callID)||(this.flushTextBuffer(),this.toolCardsSent.add(e.callID),this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,ee(s??{})))}onPermissionTimeout(e){const s=this.pendingPermissions.get(e);s&&(this.pendingPermissions.delete(e),a.error("opencode-adapter",`Permission approval timeout: ${e}`),this.transport.respondPermission(s.ocSessionId,e,"reject",s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","permission approval timeout")))}trackPendingPermission(e){if(!this.activeRun)return;this.stopIdleTimer();const s=this.pendingPermissions.get(e);s&&clearTimeout(s.timer);const t=setTimeout(()=>this.onPermissionTimeout(e),_);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:t})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(n=>{a.warn("opencode-adapter",`Orphan permission reject failed: ${n}`)});return}const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(n=>{a.warn("opencode-adapter",`Auto-approve failed: ${n}`),this.onInteractionFailure(n,s)});return}this.trackPendingPermission(e.id);const o=e.patterns.length>0?`${e.permission}: ${e.patterns.join(", ")}`:e.permission;this.callbacks.sendPermissionCard?this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.permission,toolTitle:o,toolInput:JSON.stringify(e.metadata??{})}):this.callbacks.sendToolUse(s,t,e.permission,JSON.stringify(e.metadata??{}))}handlePermission(e){if(!this.activeRun)return;const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(o=>{a.warn("opencode-adapter",`Auto-approve failed: ${o}`),this.onInteractionFailure(o,s)});return}if(this.trackPendingPermission(e.id),this.callbacks.sendPermissionCard)this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.type,toolTitle:e.title||e.type,toolInput:JSON.stringify(e.metadata??{})});else{const o=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(s,t,e.type,o)}}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const s=e.params??{},t=String(s.approval_id??s.approval_command_id??s.approvalId??s.tool_call_id??"");let i=t?this.pendingPermissions.get(t):void 0;if(!i){for(const r of this.pendingPermissions.values())if(r.eventId===this.activeRun.eventId){i=r;break}}if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:"permission"};const o=e.action_type==="exec_approve"||e.action_type==="permission_approve",n=o?"once":"reject";return clearTimeout(i.timer),this.pendingPermissions.delete(i.permissionId),this.transport.respondPermission(i.ocSessionId,i.permissionId,n,i.cwd).then(()=>{a.info("opencode-adapter",`Permission ${n}: ${i.permissionId}`),this.activeRun?.eventId===i.eventId&&this.resetIdleTimer()}).catch(r=>{a.warn("opencode-adapter",`Permission response failed: ${r}`),this.onInteractionFailure(r,i.eventId)}),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.permissionId,decision:o?"approve":"reject"}),{handled:!0,kind:"permission"}}async handleExecApprovalEvent(e){if(!this.activeRun)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"no active run"};const s=String(e.approval_id??e.approval_command_id??e.tool_call_id??"");let t=s?this.pendingPermissions.get(s):void 0;if(!t){for(const o of this.pendingPermissions.values())if(o.eventId===this.activeRun.eventId){t=o;break}}if(!t)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"That approval request is no longer pending."};const i=e.decision==="deny"?"reject":e.decision==="allow-always"?"always":"once";return clearTimeout(t.timer),this.pendingPermissions.delete(t.permissionId),this.transport.respondPermission(t.ocSessionId,t.permissionId,i,t.cwd).then(()=>{a.info("opencode-adapter",`Permission ${i} (text event): ${t.permissionId}`),this.activeRun?.eventId===t.eventId&&this.resetIdleTimer()}).catch(o=>{a.warn("opencode-adapter",`Permission response failed: ${o}`),this.onInteractionFailure(o,t.eventId)}),{delivered:!0}}onQuestionTimeout(e){const s=this.pendingQuestions.get(e);s&&(this.pendingQuestions.delete(e),a.error("opencode-adapter",`Question answer timeout: ${e}`),this.transport.rejectQuestion(e,s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","question answer timeout")))}handleQuestionAsked(e){if(!this.activeRun){this.transport.rejectQuestion(e.id).catch(n=>{a.warn("opencode-adapter",`Orphan question reject failed: ${n}`)});return}const{eventId:s,sessionId:t}=this.activeRun;this.stopIdleTimer();const i=this.pendingQuestions.get(e.id);i&&clearTimeout(i.timer);const o=setTimeout(()=>this.onQuestionTimeout(e.id),_);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:s,cwd:this.activeRun.cwd,questions:e.questions,timer:o}),this.callbacks.sendAgentQuestionCard)this.callbacks.sendAgentQuestionCard(s,t,{request_id:e.id,mode:"form",questions:e.questions.map(n=>({header:n.header,prompt:n.question,...n.options.length>0?{options:n.options.map(r=>r.label)}:{},...n.multiple!==void 0?{multi_select:n.multiple}:{},...n.custom?{allow_free_text:!0}:{}})),expires_at:Date.now()+_});else{const n=e.questions.map(r=>r.question).join(`
2
+ `);this.callbacks.sendRunError(s,t,`Agent asks: ${n}`)}}handleQuestionReplyAction(e){const s=e.params??{},t=this.deliverQuestionReply(s);return t.delivered?this.callbacks.sendLocalActionResult(e.action_id,"ok",t.result):this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,t.errorCode,t.errorMsg),{handled:!0,kind:"question_reply"}}deliverQuestionReply(e){const s=String(e.request_id??""),t=s?this.pendingQuestions.get(s):void 0;if(!t)return{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};const i=e.resolution??{},o=String(i.type??""),n=(c,l)=>(clearTimeout(t.timer),this.pendingQuestions.delete(t.requestId),c().then(()=>{this.activeRun?.eventId===t.eventId&&this.resetIdleTimer()}).catch(p=>{a.warn("opencode-adapter",`Question response failed: ${p}`),this.onInteractionFailure(p,t.eventId)}),{delivered:!0,result:l});if(o==="action"){const c=String(i.value??"");if(c==="cancel"||c==="decline")return n(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"})}let r=null;if(Array.isArray(e.answers))r=e.answers.map(c=>Array.isArray(c)?c.map(String):[String(c)]);else if(o==="text"){const c=String(i.value??"");c&&(r=t.questions.map((l,p)=>p===0?[c]:[]))}else if(o==="map"){const c=Array.isArray(i.entries)?i.entries:[];r=t.questions.map((l,p)=>{const u=c.find(h=>h.key===l.header||h.key===String(p+1));return u&&u.value?[u.value]:[]}),r.every(l=>l.length===0)&&c.length>0&&(r=t.questions.map((l,p)=>{const u=c[p]?.value;return u?[String(u)]:[]}))}if(!r||r.every(c=>c.length===0))return n(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"});const d=r;return n(()=>this.transport.replyQuestion(t.requestId,d,t.cwd),{request_id:s,resolution:"answer"})}onInteractionFailure(e,s){this.activeRun?.eventId===s&&(this.transport.protocol==="v2"?this.finishRun("failed",e instanceof Error?e.message:"OpenCode interaction failed"):this.resetIdleTimer())}rejectAllPendingInteractions(){for(const e of this.pendingPermissions.values())clearTimeout(e.timer),this.transport.respondPermission(e.ocSessionId,e.permissionId,"reject",e.cwd).catch(()=>{});this.pendingPermissions.clear();for(const e of this.pendingQuestions.values())clearTimeout(e.timer),this.transport.rejectQuestion(e.requestId,e.cwd).catch(()=>{});this.pendingQuestions.clear()}hasPendingInteractionForRun(e){for(const s of this.pendingPermissions.values())if(s.eventId===e)return!0;for(const s of this.pendingQuestions.values())if(s.eventId===e)return!0;return!1}cancelRun(e){if(e.controller?.abort(),e.cancelTask||this.stopped)return;const s=(e.promptTask??Promise.resolve()).catch(()=>{}).then(async()=>{!this.stopped&&e.ocSessionId&&await this.transport.abortSession(e.ocSessionId,e.cwd)});e.cancelTask=s,this.runBarrier=s,s.catch(t=>{if(this.stopped)return;this.cancellationFailure=new Error("OpenCode cancellation not confirmed; replace adapter before sending more prompts"),a.warn("opencode-adapter",`OpenCode cancellation not confirmed: ${t}`),this.alive=!1,(this.activeRun?.promptTask??Promise.resolve()).catch(()=>{}).then(()=>this.stop()).then(()=>this.emit("exit",-1)).catch(()=>{})})}startRun(e,s,t=!1){this.activeRun={eventId:e,sessionId:s,ocSessionId:"",cwd:this.getSessionCwd(s),chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null,controller:new AbortController},this.toolCardsSent.clear(),t&&this.auditCaptures.set(e,[]),this.lastSseAt=Date.now(),this.livenessExtendStartAt=void 0}finishRun(e,s){const t=this.activeRun;if(!t)return;if(e==="responded"?t.controller?.abort():this.cancelRun(t),this.completedEvents.add(t.eventId),this.completedEvents.size>me){const d=[...this.completedEvents].slice(-500);this.completedEvents=new Set(d)}this.snapshotAuditBoundary(t),t.flushTimer&&clearTimeout(t.flushTimer),t.flushTimer=null,this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopComposing(),this.stopIdleTimer();const i=++t.chunkSeq,o=t.clientMsgId,n=e==="failed"&&!!s;n&&this.callbacks.sendRunError(t.eventId,t.sessionId,s);const r=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t.eventId,t.sessionId,o).then(()=>{this.callbacks.sendEventResult(t.eventId,e,s,void 0,n)}).catch(d=>{const c=e==="responded"?"failed":e,l=e==="responded"?`final output delivery failed: ${d instanceof Error?d.message:String(d)}`:s,p=e==="responded"?!1:n;this.callbacks.sendEventResult(t.eventId,c,l,void 0,p)}):(this.callbacks.sendStreamChunk(t.eventId,t.sessionId,"",i,!0,o),this.callbacks.sendEventResult(t.eventId,e,s,void 0,n))};if(t.textBuffer){this.stopTextFlush();for(const d of x(t.textBuffer))t.chunkSeq++,this.callbacks.sendStreamChunk(t.eventId,t.sessionId,d,t.chunkSeq,!1,t.clientMsgId);t.textBuffer=""}r(),this.emit("eventDone",t.eventId)}clearRun(){this.activeRun&&this.cancelRun(this.activeRun),this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const e=this.activeRun?.eventId;this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopIdleTimer(),e&&this.emit("eventDone",e)}snapshotAuditBoundary(e){const s=this.auditCaptures.get(e.eventId);s&&(this.completedAuditBoundaries.set(e.eventId,{adapterType:"opencode",providerSessionId:e.ocSessionId||void 0,openCodeEvidence:{events:s}}),this.auditCaptures.delete(e.eventId))}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=ae){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},re))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const e of x(this.activeRun.textBuffer))this.activeRun.chunkSeq++,this.callbacks.sendStreamChunk(this.activeRun.eventId,this.activeRun.sessionId,e,this.activeRun.chunkSeq,!1,this.activeRun.clientMsgId);this.activeRun.textBuffer=""}}stopTextFlush(){this.activeRun?.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null)}startComposing(e){}stopComposing(){}shouldExtendByLiveness(){if(!this.activeRun)return!1;const e=this.process?.pid;if(!this.alive||!e||!D(e))return!1;const s=Date.now(),t=this.lastSseAt>0?s-this.lastSseAt:Number.POSITIVE_INFINITY;if(t<ce)return this.livenessExtendStartAt=s,a.info("opencode-adapter",`Liveness check: fresh SSE for ${this.activeRun.eventId} (sseAge=${t}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const o=this.livenessExtendStartAt??s;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=o),s-o>M?(a.warn("opencode-adapter",`Liveness extension budget exhausted for ${this.activeRun.eventId} (no progress for ${Math.round((s-o)/6e4)}min), allowing idle fail`),!1):(a.info("opencode-adapter",`Liveness check: turn in progress for ${this.activeRun.eventId} (toolsInFlight=${this.toolCallsInFlight.size}, sseAge=${Number.isFinite(t)?`${t}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){if(this.stopIdleTimer(),this.stopped||!this.activeRun)return;const e=this.activeRun;this.idleTimer=setTimeout(()=>{if(this.stopped||this.activeRun!==e)return;if(this.hasPendingInteractionForRun(this.activeRun.eventId)&&this.shouldExtendByLiveness()){a.info("opencode-adapter",`Idle timeout skipped: pending interaction for ${this.activeRun.eventId}, resetting timer`),this.resetIdleTimer();return}if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const s=this.process?.pid,i=!!(this.alive&&s&&D(s))?`liveness budget exhausted after ${M/6e4}min`:"process not alive";a.error("opencode-adapter",`Idle timeout (${i}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`idle timeout: ${i}`),this.clearRun()),this.emit("exit",-1)},de)}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveCwd(){const e=this.options.aibotSessionId?this.options.bindingStore?.get(this.options.aibotSessionId)?.cwd:void 0;if(e)return e;const s=(this.config.options??{}).cwd;return typeof s=="string"&&s?s:process.cwd()}getSessionCwd(e){return this.sessions.get(e)?.cwd??this.options.bindingStore?.get(e)?.cwd??this.resolveCwd()}buildPromptText(e){let s=e.text;if(e.contextMessages&&e.contextMessages.length>0){const t=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
5
3
  `);s=`${s}
6
4
 
7
5
  [Conversation context]
8
- ${t}`}return s}buildPromptTextFromEvent(e){let s=e.content||"";if(e.context_messages_json)try{const t=JSON.parse(e.context_messages_json);if(Array.isArray(t)&&t.length>0){const i=t.map(n=>`[context] ${n.sender_id??"unknown"}: ${n.content}`).join(`
6
+ ${t}`}return s}buildPromptTextFromEvent(e){let s=e.content||"";if(e.context_messages_json)try{const t=JSON.parse(e.context_messages_json);if(Array.isArray(t)&&t.length>0){const i=t.map(o=>`[context] ${o.sender_id??"unknown"}: ${o.content}`).join(`
9
7
  `);s=`${s}
10
8
 
11
9
  [Conversation context]
12
- ${i}`}}catch{}return this.inboundMessageIds.inject(e.session_id,s,e.msg_id)}}export{Fe as OpenCodeAdapter};
10
+ ${i}`}}catch{}return this.inboundMessageIds.inject(e.session_id,s,e.msg_id)}}export{je as OpenCodeAdapter};
@@ -1,5 +1,8 @@
1
- import{EventEmitter as f}from"node:events";import{log as l}from"../../core/log/index.js";const p=3e4,u=3e3,y=3e4;class b extends f{baseUrl="";directory="";abortController=null;closed=!1;sseConnected=!1;sseGeneration=0;async connect(t,e){this.baseUrl=t,this.directory=e??"",this.closed=!1,await this.subscribeEvents(),l.info("opencode-transport",`connected to ${t}`)}async useDirectory(t){const e=t??"";this.directory===e&&this.sseConnected&&!this.closed||(this.directory=e,!(!this.baseUrl||this.closed)&&(this.abortController&&(this.abortController.abort(),this.abortController=null),this.sseConnected=!1,await this.subscribeEvents(),l.info("opencode-transport",`switched directory to ${e||"<default>"}`)))}async subscribeEvents(){if(this.closed)return;const t=++this.sseGeneration,e=new AbortController;this.abortController=e;const s=new URL("/event",this.baseUrl);this.directory&&s.searchParams.set("directory",this.directory);const r=await fetch(s.toString(),{method:"GET",headers:{Accept:"text/event-stream"},signal:e.signal});if(!r.ok||!r.body)throw new Error(`SSE connect failed: ${r.status}`);this.sseConnected=!0,this.readSseStream(r.body.getReader(),t)}async readSseStream(t,e){const s=new TextDecoder;let r="";try{for(;!this.closed;){const{done:n,value:i}=await t.read();if(n)break;r+=s.decode(i,{stream:!0});const a=r.split(`
1
+ import{EventEmitter as I}from"node:events";import{randomUUID as P}from"node:crypto";import{OpenCodeV2Events as A,isRecord as h}from"./opencode-v2-events.js";const v=3e4,q=300,D=5e3,x=5,y=16*1024*1024,$=2*1024*1024;class l extends Error{method;path;status;kind;constructor(e,t,r,s){super(`OpenCode REST ${e} ${t}: HTTP ${r} (${s})`),this.method=e,this.path=t,this.status=r,this.kind=s,this.name="OpenCodeHttpError"}}function b(p,e){return new Promise((t,r)=>{const s=()=>{clearTimeout(o),r(new Error("OpenCode operation canceled"))},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},p);e.aborted?s():e.addEventListener("abort",s,{once:!0})})}function T(p){return h(p)&&typeof p.version=="string"&&Number.isInteger(p.pid)&&Array.isArray(p.urls)&&p.urls.every(e=>typeof e=="string")&&h(p.paths)&&typeof p.paths.tmp=="string"}class M extends I{baseUrl="";directory="";headers={};closed=!1;connectionGeneration=0;sseConnected=!1;sseGeneration=0;reconnectAttempts=0;sseController=null;requests=new Set;v2Events=new A;mcp=null;mcpDirectories=new Set;selectedProtocol="v1";prompts=new Map;cancellations=new Map;runWindows=new Map;inboxIDs=new Map;admissionUncertain=!1;get protocol(){return this.selectedProtocol}async connect(e,t,r){this.connectionGeneration++,this.cancelConnections();for(const i of this.prompts.values())i.controller.abort();this.prompts.clear(),this.v2Events.clear(),this.mcpDirectories.clear(),this.admissionUncertain=!1,this.runWindows.clear(),this.inboxIDs.clear(),this.cancellations.clear();const s=new URL(e);if(!["http:","https:"].includes(s.protocol)||s.username||s.password||s.search||s.hash)throw new Error("OpenCode connection requires an HTTP URL without embedded credentials or query");this.baseUrl=s.origin,this.directory=t??"",this.headers=r?{Authorization:`Basic ${Buffer.from(`${r.username}:${r.password}`).toString("base64")}`}:{},this.closed=!1,this.reconnectAttempts=0;const o=this.sseGeneration,n=new AbortController;this.sseController=n;try{const i=await this.detectProtocol(n.signal);if(o!==this.sseGeneration||n.signal.aborted)throw new Error("OpenCode connection canceled");this.selectedProtocol=i,await this.subscribeEvents(o,n.signal)}catch(i){throw o===this.sseGeneration&&(this.cancelConnections(),this.closed=!0,this.headers={}),i}}async detectProtocol(e){const t=Date.now()+v;for(;;)try{const r=await this.request("GET","/api/info",void 0,{scoped:!1,timeoutMs:3e3});if(!T(r))throw new l("GET","/api/info",200,"incompatible V2 server info JSON");return"v2"}catch(r){if(e.aborted)throw new Error("OpenCode connection canceled");if(r instanceof l&&r.status===503&&Date.now()<t){await b(200,e);continue}if(!(r instanceof l)||!(r.status===404||r.status===405||r.status===200&&r.kind==="non-JSON response"))throw r;const s=await this.request("GET","/session",void 0,{scoped:!1});if(!Array.isArray(s)||!s.every(o=>h(o)&&typeof o.id=="string"))throw new Error("OpenCode GET /session: incompatible V1 session list JSON");return"v1"}}async useDirectory(e,t){t?.throwIfAborted();const r=e??"";if(this.directory===r&&this.isConnected){await this.ensureMcpDirectory(t);return}if(this.directory=r,!this.baseUrl||this.closed)return;this.sseController?.abort(),this.sseConnected=!1,this.reconnectAttempts=0;const s=++this.sseGeneration,o=new AbortController;this.sseController=o;const n=()=>o.abort();t?.addEventListener("abort",n,{once:!0});try{await this.subscribeEvents(s,o.signal)}finally{t?.removeEventListener("abort",n)}t?.throwIfAborted(),await this.ensureMcpDirectory(t)}async subscribeEvents(e,t){const r=this.protocol==="v2"?"/api/event":"/event",s=this.url(r,this.protocol==="v1"?this.directory:""),o=new AbortController,n=()=>o.abort();t.addEventListener("abort",n,{once:!0});const i=setTimeout(n,v),c=()=>{clearTimeout(i),t.removeEventListener("abort",n)};try{t.aborted&&n();const a=await fetch(s,{headers:{...this.headers,Accept:"text/event-stream"},signal:o.signal,redirect:"error"});if(clearTimeout(i),!a.ok||!a.body||a.headers.get("content-type")?.split(";")[0].trim().toLowerCase()!=="text/event-stream"){try{await a.body?.cancel()}catch{}throw new l("GET",r,a.status,"SSE requires text/event-stream")}if(e!==this.sseGeneration||t.aborted||this.closed)throw await a.body.cancel(),new Error("OpenCode SSE connection canceled");this.sseConnected=!0,this.readSseStream(a.body.getReader(),e,t).catch(()=>{}).finally(c)}catch(a){throw c(),o.abort(),a instanceof l?a:new Error(`OpenCode SSE GET ${r}: connection failed or canceled`)}}async readSseStream(e,t,r){const s=new TextDecoder;let o="";const n=Date.now();try{for(;!this.closed&&!r.aborted&&t===this.sseGeneration;){const{done:i,value:c}=await e.read();if(i)break;if(o+=s.decode(c,{stream:!0}).replace(/\r\n/g,`
2
+ `),o=o.replace(/\r\n/g,`
3
+ `),o.length>$)throw new Error("OpenCode SSE frame too large");let a;for(;(a=o.indexOf(`
2
4
 
3
- `);r=a.pop()??"";for(const h of a){const c=this.parseSseFrame(h);if(c)try{this.emit("event",c)}catch(o){const d=o instanceof Error?o.message:String(o);l.warn("opencode-transport",`event handler failed (${c.type}): ${d}`)}}}}catch(n){if(this.closed)return;const i=n instanceof Error?n.message:String(n);if(i.includes("abort"))return;l.warn("opencode-transport",`SSE error: ${i}, reconnecting...`),await this.reconnectSse(e)}finally{e===this.sseGeneration&&(this.sseConnected=!1)}}parseSseFrame(t){let e="",s=[];for(const r of t.split(`
4
- `))r.startsWith("event:")?e=r.slice(6).trim():r.startsWith("data:")&&s.push(r.slice(5).trimStart());if(s.length===0)return null;try{const r=s.join(`
5
- `),n=JSON.parse(r);if(e&&n.type!==e&&(n.type=e),n&&typeof n.properties=="object"&&n.properties!==null){const{properties:i,...a}=n;return{...a,...i}}return n}catch{return null}}async reconnectSse(t){if(this.closed||t!==this.sseGeneration)return;const e=u+Math.random()*u;if(await new Promise(s=>setTimeout(s,Math.min(e,y))),!this.closed&&t===this.sseGeneration)try{await this.subscribeEvents()}catch(s){if(this.closed)return;l.warn("opencode-transport",`SSE reconnect failed: ${s instanceof Error?s.message:String(s)}`),this.reconnectSse(this.sseGeneration)}}async request(t,e,s,r){if(this.closed)throw new Error("transport closed");const n=new URL(e,this.baseUrl),i=r?.directory??this.directory;i&&n.searchParams.set("directory",i);const a=new AbortController,h=setTimeout(()=>a.abort(),p);try{const c={method:t,headers:{"Content-Type":"application/json"},signal:a.signal};s!==void 0&&(c.body=JSON.stringify(s));const o=await fetch(n.toString(),c);if(o.status===204)return;const d=await o.json();if(!o.ok)throw new Error(`REST ${t} ${e}: ${o.status} ${JSON.stringify(d)}`);return d}finally{clearTimeout(h)}}async createSession(t,e){return this.request("POST","/session",t??{},{directory:e})}async getSession(t,e){return this.request("GET",`/session/${t}`,void 0,{directory:e})}async deleteSession(t,e){await this.request("DELETE",`/session/${t}`,void 0,{directory:e})}async updateSessionPermission(t,e,s){await this.request("PATCH",`/session/${t}`,{permission:e},{directory:s})}async sendPromptAsync(t,e,s){await this.request("POST",`/session/${t}/prompt_async`,e,{directory:s})}async abortSession(t,e){await this.request("POST",`/session/${t}/abort`,void 0,{directory:e})}async respondPermission(t,e,s,r){await this.request("POST",`/session/${t}/permissions/${e}`,{response:s},{directory:r})}async replyQuestion(t,e,s){await this.request("POST",`/question/${t}/reply`,{answers:e},{directory:s})}async rejectQuestion(t,e){await this.request("POST",`/question/${t}/reject`,void 0,{directory:e})}async listProviders(t){return(await this.request("GET","/config/providers",void 0,{directory:t}))?.providers??[]}async healthCheck(){try{return(await fetch(new URL("/session",this.baseUrl).toString(),{method:"GET",headers:{"Content-Type":"application/json"},signal:AbortSignal.timeout(3e3)})).ok}catch{return!1}}disconnect(){this.closed=!0,this.sseGeneration++,this.abortController&&(this.abortController.abort(),this.abortController=null),this.sseConnected=!1,this.removeAllListeners()}get isConnected(){return this.sseConnected&&!this.closed}}export{b as OpenCodeTransport};
5
+ `))>=0;){const d=o.slice(0,a);if(o=o.slice(a+2),t!==this.sseGeneration||r.aborted)return;const f=this.parseSseFrame(d);for(const u of f)try{this.emit("event",u)}catch{}}}}catch{}finally{try{await e.cancel()}catch{}e.releaseLock()}if(!(this.closed||r.aborted||t!==this.sseGeneration)){this.sseConnected=!1,Date.now()-n>=5e3&&(this.reconnectAttempts=0);try{this.emit("stream-lost")}catch{}this.v2Events.clear(),this.reconnectSse(t,r)}}parseSseFrame(e){let t="";const r=[];for(const o of e.split(`
6
+ `))o.startsWith("event:")?t=o.slice(6).trim():o.startsWith("data:")&&r.push(o.slice(5).trimStart());if(!r.length)return[];if(t==="effect/http-api/stream/failure")throw new Error("OpenCode SSE source failure");let s;try{s=JSON.parse(r.join(`
7
+ `))}catch{throw new Error("OpenCode SSE invalid JSON")}if(!h(s)||typeof s.type!="string")throw new Error("OpenCode SSE invalid event");if(this.protocol==="v2"){if(h(s.location)&&s.location.directory&&this.directory&&s.location.directory!==this.directory)return[];const o=s.data?.sessionID??s.data?.form?.sessionID,n=this.runWindows.get(o);return n&&!this.acceptRunEvent(s,n)?[]:this.v2Events.normalize(s).map(i=>n?{...i,runId:n.runId}:i)}if(h(s.properties)){const{properties:o,...n}=s;return[{...n,...o,type:s.type}]}return[s]}acceptRunEvent(e,t){if(t.canceled||t.signal?.aborted)return!1;const r=e.durable?.seq;if(e.type==="session.inbox.enqueued"&&e.data.inboxID===t.promptId){if(!Number.isSafeInteger(r))throw new Error("OpenCode V2 inbox admission requires durable sequence");return t.enqueuedSeq=r,!0}if(e.type==="session.inbox.delivered"&&e.data.inboxID===t.promptId){if(!Number.isSafeInteger(r))throw new Error("OpenCode V2 inbox delivery requires durable sequence");return t.deliveredSeq=r,!0}if(e.type==="session.execution.started"&&t.enqueuedSeq!==void 0&&Number.isSafeInteger(r)&&r>t.enqueuedSeq)return t.executionSeq=r,!0;const s=t.deliveredSeq??t.executionSeq;if(s===void 0||Number.isSafeInteger(r)&&r<=s)return!1;const o=/^session\.execution\.(succeeded|failed|interrupted)$/.test(e.type);if(o&&!Number.isSafeInteger(r))throw new Error("OpenCode V2 execution terminal requires durable sequence");if(t.deliveredSeq===void 0){if(e.type==="session.execution.succeeded")throw new Error("OpenCode V2 execution ended before own inbox delivery");return o}const n=e.data.assistantMessageID;return e.type==="session.step.started"&&t.messages.add(n),!(n&&!t.messages.has(n))}async reconnectSse(e,t){for(;this.reconnectAttempts<x;){const r=this.reconnectAttempts++;try{if(await b(Math.min(q*2**r,D),t),this.closed||t.aborted||e!==this.sseGeneration)return;await this.subscribeEvents(e,t);return}catch(s){if(this.closed||t.aborted||e!==this.sseGeneration)return;if(s instanceof l&&(s.status===401||s.status===403))break}}if(!this.closed&&e===this.sseGeneration)try{this.emit("stream-unavailable")}catch{}}url(e,t=""){const r=new URL(e,this.baseUrl);return t&&r.searchParams.set(this.protocol==="v2"?"location[directory]":"directory",t),r}async request(e,t,r,s){if(this.closed)throw new Error(`OpenCode REST ${e} ${t}: transport closed`);s?.signal?.throwIfAborted();const o=this.url(t,s?.scoped===!1?"":s?.directory??this.directory),n=new AbortController,i=()=>n.abort();s?.signal?.addEventListener("abort",i,{once:!0}),this.requests.add(n);const c=setTimeout(()=>n.abort(),s?.timeoutMs??v);let a;try{const d=await fetch(o,{method:e,headers:{...this.headers,Accept:"application/json",...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},signal:n.signal,redirect:"error"});if(a=d.status,d.status===204&&s?.response==="empty")return;const f=/^application\/(?:[\w.+-]+\+)?json(?:;|$)/i.test(d.headers.get("content-type")??""),u=d.body?.getReader(),E=[];let m=0;try{if(u)for(;;){const{done:g,value:C}=await u.read();if(g||(m+=C.byteLength,m>(d.ok?y:4096)))break;E.push(C)}}finally{u&&(await u.cancel(),u.releaseLock())}const O=Buffer.concat(E).toString("utf8");let S,w=m?f?"invalid JSON response":"non-JSON response":"empty response";if(f&&m<=y)try{S=JSON.parse(O),w="JSON response"}catch{}if(!d.ok||w!=="JSON response"||s?.response==="empty"||m>y)throw new l(e,t,d.status,m>y?"response too large":d.ok&&s?.response==="empty"?"expected HTTP 204":w);return S}catch(d){throw d instanceof l?d:a!==void 0?new l(e,t,a,"response read failed or canceled"):new Error(`OpenCode REST ${e} ${t}: request failed or canceled`)}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",i),this.requests.delete(n)}}sessionPath(e){return`${this.protocol==="v2"?"/api":""}/session/${encodeURIComponent(e)}`}unwrap(e){return this.protocol==="v2"&&h(e)?e.data:e}session(e,t,r){const s=this.unwrap(e);if(!h(s)||typeof s.id!="string")throw new l(t,r,200,"invalid session JSON");return{...s,directory:s.directory??s.location?.directory??this.directory}}async createSession(e,t,r){if(this.protocol==="v2"){const s=t??this.directory;return this.session(await this.request("POST","/api/session",{...e,...s?{location:{directory:s}}:{}},{scoped:!1,signal:r}),"POST","/api/session")}return this.session(await this.request("POST","/session",e??{},{directory:t,signal:r}),"POST","/session")}async getSession(e,t,r){return this.session(await this.request("GET",this.sessionPath(e),void 0,{directory:t,scoped:this.protocol==="v1",signal:r}),"GET",this.sessionPath(e))}async deleteSession(e,t){await this.request("DELETE",this.sessionPath(e),void 0,{directory:t,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1"}),this.v2Events.clearSession(e),this.runWindows.delete(e),this.inboxIDs.delete(e)}async updateSessionPermission(e,t,r,s){await this.request("PATCH",this.sessionPath(e),this.protocol==="v2"?{permissions:t.map(o=>({action:{bash:"shell",task:"subagent",write:"edit",patch:"edit"}[o.permission]??o.permission,resource:o.pattern,effect:o.action}))}:{permission:t},{directory:r,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1",signal:s})}async sendPromptAsync(e,t,r,s){const o=this.cancellations.get(e);if(o&&await o,s?.signal?.throwIfAborted(),this.admissionUncertain)throw new Error("OpenCode prompt admission unconfirmed; server must be replaced");if(this.prompts.has(e))throw new Error("OpenCode session already has a prompt admission in progress");const n=new AbortController,i=()=>n.abort();s?.signal?.addEventListener("abort",i,{once:!0});const c=`msg_${P().replaceAll("-","")}`,a={controller:n,admitted:!1,dispatched:!1,done:Promise.resolve()};this.prompts.set(e,a),this.protocol==="v2"&&this.inboxIDs.set(e,c),this.protocol==="v2"&&s?.runId&&(this.v2Events.clearSession(e),this.runWindows.set(e,{runId:s.runId,promptId:c,signal:s.signal,canceled:!1,messages:new Set}));const d=this.connectionGeneration;a.done=this.preparePrompt(e,t,r,c,a);try{await a.done}catch(f){throw a.dispatched&&!a.admitted&&!this.closed&&d===this.connectionGeneration&&(this.admissionUncertain=!0,this.emit("admission-uncertain")),f}finally{s?.signal?.removeEventListener("abort",i),this.prompts.get(e)===a&&this.prompts.delete(e)}}async preparePrompt(e,t,r,s,o){const n=this.sessionPath(e),i=o.controller.signal;if(this.protocol==="v1"){i.throwIfAborted(),o.dispatched=!0,await this.request("POST",`${n}/prompt_async`,t,{directory:r,response:"empty"}),o.admitted=!0;return}t.model&&await this.request("POST",`${n}/model`,{model:{providerID:t.model.providerID,id:t.model.modelID}},{scoped:!1,response:"empty",signal:i}),t.agent&&await this.request("POST",`${n}/agent`,{agent:t.agent},{scoped:!1,response:"empty",signal:i}),await this.request(t.system?"PUT":"DELETE",`/api/experimental/session/${encodeURIComponent(e)}/instructions/entries/grix_identity`,t.system?{value:t.system}:void 0,{scoped:!1,response:"empty",signal:i}),i.throwIfAborted(),o.dispatched=!0;const c=await this.request("POST",`${n}/prompt`,{id:s,text:t.parts.map(a=>a.text).join(`
8
+ `)},{scoped:!1});if(!h(c)||!h(c.data)||c.data.id!==s)throw new l("POST",`${n}/prompt`,200,"invalid inbox JSON");o.admitted=!0}async abortSession(e,t){const r=this.cancellations.get(e);if(r)return r;const s=this.prompts.get(e);s?.controller.abort();const o=this.runWindows.get(e);o&&(o.canceled=!0);const n=this.interruptAfterAdmission(e,t,s,this.inboxIDs.get(e));return this.cancellations.set(e,n),n.then(()=>{this.cancellations.get(e)===n&&this.cancellations.delete(e)},()=>{}),n}async interruptAfterAdmission(e,t,r,s){const o=this.connectionGeneration,n=()=>{if(this.closed||o!==this.connectionGeneration)throw new Error("OpenCode interrupt connection canceled")};await r?.done.catch(()=>{}),n(),this.protocol==="v2"&&s&&await this.request("DELETE",`${this.sessionPath(e)}/inbox/${encodeURIComponent(s)}`,void 0,{scoped:!1,response:"empty"}),n();const i=await this.request("POST",`${this.sessionPath(e)}/${this.protocol==="v2"?"interrupt":"abort"}`,void 0,{directory:t,scoped:this.protocol==="v1"});if(this.protocol==="v2"&&(!h(i)||typeof i.interrupted!="boolean"))throw new l("POST",`${this.sessionPath(e)}/interrupt`,200,"invalid interrupt JSON");n(),this.protocol==="v2"&&await this.request("POST",`/api/experimental/session/${encodeURIComponent(e)}/wait`,void 0,{scoped:!1,response:"empty"})}async respondPermission(e,t,r,s){await this.request("POST",this.protocol==="v2"?`${this.sessionPath(e)}/permission/${encodeURIComponent(t)}/reply`:`${this.sessionPath(e)}/permissions/${encodeURIComponent(t)}`,this.protocol==="v2"?{decision:r}:{response:r},{directory:s,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1"})}async replyQuestion(e,t,r){if(this.protocol==="v1"){await this.request("POST",`/question/${encodeURIComponent(e)}/reply`,{answers:t},{directory:r});return}const s=this.v2Events.getForm(e);await this.request("POST",`${this.sessionPath(s.sessionID)}/form/${encodeURIComponent(e)}/reply`,{answer:this.v2Events.formAnswer(e,t)},{scoped:!1,response:"empty"}),this.v2Events.forgetForm(e)}async rejectQuestion(e,t){if(this.protocol==="v1"){await this.request("POST",`/question/${encodeURIComponent(e)}/reject`,void 0,{directory:t});return}const r=this.v2Events.getForm(e);await this.request("DELETE",`${this.sessionPath(r.sessionID)}/form/${encodeURIComponent(e)}`,void 0,{scoped:!1,response:"empty"}),this.v2Events.forgetForm(e)}async listProviders(e){if(this.protocol==="v1"){const s=await this.request("GET","/config/providers",void 0,{directory:e});if(!Array.isArray(s?.providers))throw new l("GET","/config/providers",200,"invalid provider JSON");return s.providers}const t=this.unwrap(await this.request("GET","/api/model",void 0,{directory:e}));if(!Array.isArray(t))throw new l("GET","/api/model",200,"invalid model list JSON");const r=new Map;for(const s of t){if(!h(s)||typeof s.id!="string"||typeof s.providerID!="string")throw new l("GET","/api/model",200,"invalid model JSON");if(s.enabled===!1)continue;const o=r.get(s.providerID)??{id:s.providerID,name:s.providerID,models:[]};o.models.push({id:s.id,name:s.name,limit:s.limit}),r.set(s.providerID,o)}return[...r.values()]}async configureMcp(e,t){this.mcp={name:e,command:t},this.mcpDirectories.clear(),await this.ensureMcpDirectory()}async ensureMcpDirectory(e){if(e?.throwIfAborted(),this.protocol!=="v2"||!this.mcp||this.mcpDirectories.has(this.directory))return;const t=this.directory,{name:r,command:s}=this.mcp;await this.request("PUT",`/api/experimental/mcp/${encodeURIComponent(r)}`,{config:{type:"local",command:s,disabled:!1}},{directory:t,response:"empty",signal:e});const o=Date.now()+1e4;for(;;){const n=this.unwrap(await this.request("GET","/api/mcp",void 0,{directory:t,signal:e})),i=Array.isArray(n)?n.find(c=>h(c)&&c.name===r):void 0;if(i?.status?.status==="connected")break;if(i?.status?.status!=="pending"||Date.now()>=o)throw new Error("OpenCode V2 MCP did not become connected");if(!this.sseController)throw new Error("OpenCode MCP setup canceled");await b(100,e??this.sseController.signal)}this.mcpDirectories.add(t)}async healthCheck(){try{if(this.closed)return!1;if(this.protocol==="v2")return T(await this.request("GET","/api/info",void 0,{scoped:!1,timeoutMs:3e3}));const e=await this.request("GET","/session",void 0,{timeoutMs:3e3});return Array.isArray(e)&&e.every(t=>h(t)&&typeof t.id=="string")}catch{return!1}}cancelConnections(){this.sseGeneration++,this.sseController?.abort(),this.sseController=null;for(const e of this.requests)e.abort();this.sseConnected=!1}disconnect(){this.connectionGeneration++,this.closed=!0,this.cancelConnections(),this.headers={},this.mcp=null,this.mcpDirectories.clear(),this.v2Events.clear();for(const e of this.prompts.values())e.controller.abort();this.prompts.clear(),this.cancellations.clear(),this.runWindows.clear(),this.inboxIDs.clear(),this.removeAllListeners()}get isConnected(){return this.sseConnected&&!this.closed}}export{l as OpenCodeHttpError,M as OpenCodeTransport};
@@ -0,0 +1,2 @@
1
+ function u(m){return typeof m=="object"&&m!==null&&!Array.isArray(m)}const g=1024;class f{messages=new Map;textLengths=new Map;tools=new Map;forms=new Map;normalize(o){if(!u(o.data))throw new Error("OpenCode V2 event requires data");if([this.messages,this.textLengths,this.tools,this.forms].some(t=>t.size>g))throw new Error("OpenCode V2 event state limit exceeded");const e=o.data,r=e.sessionID;if(o.type.startsWith("session.")&&typeof r!="string")throw new Error("OpenCode V2 session event requires sessionID");let s=[];const n=e.assistantMessageID;if(/^session\.(step|text|reasoning|tool)\./.test(o.type)&&typeof n!="string")throw new Error("OpenCode V2 event requires assistantMessageID");if(/^session\.(text|reasoning)\.delta$/.test(o.type)&&typeof e.delta!="string")throw new Error("OpenCode V2 event requires text delta");const d=`${r}/${n}/${e.id}`,c=t=>{const a=this.messages.get(n),i={...a,id:n,sessionID:r,role:"assistant",time:{created:a?.time.created??e.started??o.created??Date.now()},modelID:e.model?.id??a?.modelID??"",providerID:e.model?.providerID??a?.providerID??"",...t?{tokens:t,cost:e.cost,time:{created:a?.time.created??o.created,completed:o.created}}:{}};return this.messages.set(n,i),i},p=t=>{const a=this.tools.get(d)??{sessionID:r,name:"unknown",input:{}};return{type:"message.part.updated",part:{id:d,messageID:n,sessionID:r,type:"tool",callID:e.id,tool:a.name,state:{status:t,input:a.input,raw:e.text??"",...t==="completed"?{output:Array.isArray(e.content)?e.content.map(l=>l.type==="text"?l.text:JSON.stringify(l)).join(`
2
+ `):""}:{},...t==="error"?{error:e.error?.message??"Tool failed"}:{},title:a.name,time:{start:a.started??o.created??Date.now(),end:o.created??Date.now()}}}}};switch(o.type){case"server.connected":s=[{type:"server.connected"}];break;case"session.execution.started":s=[{type:"session.status",sessionID:r,status:{type:"busy"}}];break;case"session.execution.succeeded":s=[{type:"session.idle",sessionID:r}],this.clearSession(r,!1);break;case"session.execution.failed":s=[{type:"session.error",sessionID:r,error:this.error(e.error)}],this.clearSession(r,!1);break;case"session.execution.interrupted":s=[{type:"session.canceled",sessionID:r}],this.clearSession(r,!1);break;case"session.step.started":s=[{type:"message.updated",info:c()}];break;case"session.step.ended":s=[{type:"message.updated",info:c(e.tokens)}];break;case"session.text.delta":case"session.reasoning.delta":case"session.text.ended":case"session.reasoning.ended":{const t=o.type.startsWith("session.reasoning."),a=`${r}/${n}/${t}/${e.ordinal}`,i=this.textLengths.get(a)?.text??"",l=o.type.endsWith(".ended"),h=l?String(e.text??"").slice(i.length):String(e.delta??""),y=l?String(e.text??""):i+h;if(y.length>2*1024*1024)throw new Error("OpenCode V2 text limit exceeded");this.textLengths.set(a,{sessionID:r,text:y}),this.messages.has(n)||s.push({type:"message.updated",info:c()}),s.push({type:"message.part.updated",part:{type:t?"reasoning":"text",id:a,messageID:n,text:y},delta:h});break}case"session.tool.input.started":this.tools.set(d,{sessionID:r,name:e.name,input:{},started:o.created});break;case"session.tool.input.ended":{const t=this.tools.get(d);if(t)try{const a=JSON.parse(e.text);u(a)&&(t.input=a)}catch{}break}case"session.tool.called":{const t=this.tools.get(d)??{sessionID:r,name:"unknown",input:{}};t.input=u(e.input)?e.input:{},this.tools.set(d,t),s=[p("running")];break}case"session.tool.success":s=[p("completed")],this.tools.delete(d);break;case"session.tool.failed":s=[p("error")],this.tools.delete(d);break;case"permission.asked":if(typeof e.id!="string"||!Array.isArray(e.resources))throw new Error("OpenCode V2 invalid permission event");s=[{type:"permission.asked",id:e.id,sessionID:r,permission:e.action,patterns:e.resources,always:e.save??[],metadata:e.metadata??{},...e.source?.type==="tool"?{tool:{messageID:e.source.messageID,callID:e.source.id}}:{}}];break;case"permission.replied":s=[{type:"permission.replied",sessionID:r,requestID:e.requestID,reply:e.reply}];break;case"form.created":{const t=e.form;if(!u(t)||typeof t.id!="string"||typeof t.sessionID!="string"||!Array.isArray(t.fields))throw new Error("OpenCode V2 invalid form event");if(this.forms.set(t.id,t),t.fields.some(i=>i.hidden||i.when?.length||!["string","multiselect","boolean","number","integer"].includes(i.type))){s=[{type:"question.unsupported",sessionID:t.sessionID,id:t.id}];break}const a=t.fields.map(i=>({header:i.title||i.key,question:i.description||i.title||i.key,options:i.type==="boolean"?[{label:"true"},{label:"false"}]:(i.options??[]).map(l=>({label:l.label,description:l.description})),multiple:i.type==="multiselect",custom:i.type!=="boolean"&&(i.custom??!i.options?.length)}));s=[{type:"question.asked",id:t.id,sessionID:t.sessionID,questions:a}];break}case"form.replied":s=[{type:"question.replied",sessionID:r,requestID:e.id,answers:[]}],this.forms.delete(e.id);break;case"form.cancelled":s=[{type:"question.rejected",sessionID:r,requestID:e.id}],this.forms.delete(e.id);break;case"location.shutdown":s=[{type:"server.instance.disposed",directory:o.location?.directory??""}];break}return s.length||(s=[{type:"opencode.v2.event"}]),s.map(t=>({...t,nativeEvent:o}))}error(o){return{type:typeof o?.type=="string"?o.type:"unknown",message:typeof o?.message=="string"?o.message:"OpenCode execution failed"}}getForm(o){const e=this.forms.get(o);if(!e)throw new Error("OpenCode V2 form is no longer pending");return e}forgetForm(o){this.forms.delete(o)}formAnswer(o,e){const r=this.getForm(o),s=Object.create(null);return r.fields.forEach((n,d)=>{const c=e[d]??[];if(!c.length){if(n.required)throw new Error("OpenCode V2 form requires an answer");return}const p=c.map(t=>n.options?.find(a=>a.label===t)?.value??t);if(n.type==="multiselect")s[n.key]=p;else if(n.type==="boolean"){if(!["true","false"].includes(p[0]))throw new Error("OpenCode V2 form requires a boolean");s[n.key]=p[0]==="true"}else if(n.type==="number"||n.type==="integer"){const t=Number(p[0]);if(!p[0].trim()||!Number.isFinite(t)||n.type==="integer"&&!Number.isInteger(t))throw new Error("OpenCode V2 form requires a number");s[n.key]=t}else if(n.type==="string")s[n.key]=p[0];else throw new Error("OpenCode V2 form field is unsupported")}),s}clearSession(o,e=!0){for(const[r,s]of this.messages)s.sessionID===o&&this.messages.delete(r);for(const[r,s]of this.textLengths)s.sessionID===o&&this.textLengths.delete(r);for(const[r,s]of this.tools)s.sessionID===o&&this.tools.delete(r);if(e)for(const[r,s]of this.forms)s.sessionID===o&&this.forms.delete(r)}clear(){this.messages.clear(),this.textLengths.clear(),this.tools.clear(),this.forms.clear()}}export{f as OpenCodeV2Events,u as isRecord};